SoftwareGLContext.cpp 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300
  1. /*
  2. * Copyright (c) 2021, Jesse Buhagiar <jooster669@gmail.com>
  3. * Copyright (c) 2021, Stephan Unverwerth <s.unverwerth@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include "SoftwareGLContext.h"
  8. #include "GLStruct.h"
  9. #include "SoftwareRasterizer.h"
  10. #include <AK/Assertions.h>
  11. #include <AK/Debug.h>
  12. #include <AK/Format.h>
  13. #include <AK/QuickSort.h>
  14. #include <AK/TemporaryChange.h>
  15. #include <AK/Variant.h>
  16. #include <AK/Vector.h>
  17. #include <LibGfx/Bitmap.h>
  18. #include <LibGfx/Painter.h>
  19. #include <LibGfx/Vector4.h>
  20. #include <math.h>
  21. using AK::dbgln;
  22. namespace GL {
  23. // FIXME: We should set this up when we create the context!
  24. static constexpr size_t MATRIX_STACK_LIMIT = 1024;
  25. #define APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(name, ...) \
  26. if (should_append_to_listing()) { \
  27. append_to_listing<&SoftwareGLContext::name>(__VA_ARGS__); \
  28. if (!should_execute_after_appending_to_listing()) \
  29. return; \
  30. }
  31. #define RETURN_WITH_ERROR_IF(condition, error) \
  32. if (condition) { \
  33. if (m_error == GL_NO_ERROR) \
  34. m_error = error; \
  35. return; \
  36. }
  37. #define RETURN_VALUE_WITH_ERROR_IF(condition, error, return_value) \
  38. if (condition) { \
  39. if (m_error == GL_NO_ERROR) \
  40. m_error = error; \
  41. return return_value; \
  42. }
  43. SoftwareGLContext::SoftwareGLContext(Gfx::Bitmap& frontbuffer)
  44. : m_frontbuffer(frontbuffer)
  45. , m_rasterizer(frontbuffer.size())
  46. {
  47. }
  48. void SoftwareGLContext::gl_begin(GLenum mode)
  49. {
  50. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_begin, mode);
  51. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  52. RETURN_WITH_ERROR_IF(mode < GL_TRIANGLES || mode > GL_POLYGON, GL_INVALID_ENUM);
  53. m_current_draw_mode = mode;
  54. m_in_draw_state = true; // Certain commands will now generate an error
  55. }
  56. void SoftwareGLContext::gl_clear(GLbitfield mask)
  57. {
  58. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_clear, mask);
  59. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  60. RETURN_WITH_ERROR_IF(mask & ~(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT), GL_INVALID_ENUM);
  61. if (mask & GL_COLOR_BUFFER_BIT)
  62. m_rasterizer.clear_color(m_clear_color);
  63. if (mask & GL_DEPTH_BUFFER_BIT)
  64. m_rasterizer.clear_depth(static_cast<float>(m_clear_depth));
  65. }
  66. void SoftwareGLContext::gl_clear_color(GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha)
  67. {
  68. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_clear_color, red, green, blue, alpha);
  69. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  70. m_clear_color = { red, green, blue, alpha };
  71. }
  72. void SoftwareGLContext::gl_clear_depth(GLdouble depth)
  73. {
  74. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_clear_depth, depth);
  75. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  76. m_clear_depth = depth;
  77. }
  78. void SoftwareGLContext::gl_color(GLdouble r, GLdouble g, GLdouble b, GLdouble a)
  79. {
  80. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_color, r, g, b, a);
  81. m_current_vertex_color = { (float)r, (float)g, (float)b, (float)a };
  82. }
  83. void SoftwareGLContext::gl_end()
  84. {
  85. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_end);
  86. // At this point, the user has effectively specified that they are done with defining the geometry
  87. // of what they want to draw. We now need to do a few things (https://www.khronos.org/opengl/wiki/Rendering_Pipeline_Overview):
  88. //
  89. // 1. Transform all of the vertices in the current vertex list into eye space by mulitplying the model-view matrix
  90. // 2. Transform all of the vertices from eye space into clip space by multiplying by the projection matrix
  91. // 3. If culling is enabled, we cull the desired faces (https://learnopengl.com/Advanced-OpenGL/Face-culling)
  92. // 4. Each element of the vertex is then divided by w to bring the positions into NDC (Normalized Device Coordinates)
  93. // 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)
  94. // 6. The vertices are then sent off to the rasteriser and drawn to the screen
  95. float scr_width = m_frontbuffer->width();
  96. float scr_height = m_frontbuffer->height();
  97. // Make sure we had a `glBegin` before this call...
  98. RETURN_WITH_ERROR_IF(!m_in_draw_state, GL_INVALID_OPERATION);
  99. // Let's construct some triangles
  100. if (m_current_draw_mode == GL_TRIANGLES) {
  101. GLTriangle triangle;
  102. for (size_t i = 0; i < vertex_list.size(); i += 3) {
  103. triangle.vertices[0] = vertex_list.at(i);
  104. triangle.vertices[1] = vertex_list.at(i + 1);
  105. triangle.vertices[2] = vertex_list.at(i + 2);
  106. triangle_list.append(triangle);
  107. }
  108. } else if (m_current_draw_mode == GL_QUADS) {
  109. // We need to construct two triangles to form the quad
  110. GLTriangle triangle;
  111. VERIFY(vertex_list.size() % 4 == 0);
  112. for (size_t i = 0; i < vertex_list.size(); i += 4) {
  113. // Triangle 1
  114. triangle.vertices[0] = vertex_list.at(i);
  115. triangle.vertices[1] = vertex_list.at(i + 1);
  116. triangle.vertices[2] = vertex_list.at(i + 2);
  117. triangle_list.append(triangle);
  118. // Triangle 2
  119. triangle.vertices[0] = vertex_list.at(i + 2);
  120. triangle.vertices[1] = vertex_list.at(i + 3);
  121. triangle.vertices[2] = vertex_list.at(i);
  122. triangle_list.append(triangle);
  123. }
  124. } else if (m_current_draw_mode == GL_TRIANGLE_FAN) {
  125. GLTriangle triangle;
  126. triangle.vertices[0] = vertex_list.at(0); // Root vertex is always the vertex defined first
  127. for (size_t i = 1; i < vertex_list.size() - 1; i++) // This is technically `n-2` triangles. We start at index 1
  128. {
  129. triangle.vertices[1] = vertex_list.at(i);
  130. triangle.vertices[2] = vertex_list.at(i + 1);
  131. triangle_list.append(triangle);
  132. }
  133. } else if (m_current_draw_mode == GL_TRIANGLE_STRIP) {
  134. GLTriangle triangle;
  135. for (size_t i = 0; i < vertex_list.size() - 2; i++) {
  136. triangle.vertices[0] = vertex_list.at(i);
  137. triangle.vertices[1] = vertex_list.at(i + 1);
  138. triangle.vertices[2] = vertex_list.at(i + 2);
  139. triangle_list.append(triangle);
  140. }
  141. } else {
  142. RETURN_WITH_ERROR_IF(true, GL_INVALID_ENUM);
  143. }
  144. // Now let's transform each triangle and send that to the GPU
  145. for (size_t i = 0; i < triangle_list.size(); i++) {
  146. GLTriangle& triangle = triangle_list.at(i);
  147. GLVertex& vertexa = triangle.vertices[0];
  148. GLVertex& vertexb = triangle.vertices[1];
  149. GLVertex& vertexc = triangle.vertices[2];
  150. FloatVector4 veca({ vertexa.x, vertexa.y, vertexa.z, 1.0f });
  151. FloatVector4 vecb({ vertexb.x, vertexb.y, vertexb.z, 1.0f });
  152. FloatVector4 vecc({ vertexc.x, vertexc.y, vertexc.z, 1.0f });
  153. // First multiply the vertex by the MODELVIEW matrix and then the PROJECTION matrix
  154. veca = m_model_view_matrix * veca;
  155. veca = m_projection_matrix * veca;
  156. vecb = m_model_view_matrix * vecb;
  157. vecb = m_projection_matrix * vecb;
  158. vecc = m_model_view_matrix * vecc;
  159. vecc = m_projection_matrix * vecc;
  160. // At this point, we're in clip space
  161. // Here's where we do the clipping. This is a really crude implementation of the
  162. // https://learnopengl.com/Getting-started/Coordinate-Systems
  163. // "Note that if only a part of a primitive e.g. a triangle is outside the clipping volume OpenGL
  164. // will reconstruct the triangle as one or more triangles to fit inside the clipping range. "
  165. //
  166. // ALL VERTICES ARE DEFINED IN A CLOCKWISE ORDER
  167. // Okay, let's do some face culling first
  168. Vector<FloatVector4> vecs;
  169. Vector<GLVertex> verts;
  170. vecs.append(veca);
  171. vecs.append(vecb);
  172. vecs.append(vecc);
  173. m_clipper.clip_triangle_against_frustum(vecs);
  174. // TODO: Copy color and UV information too!
  175. for (size_t vec_idx = 0; vec_idx < vecs.size(); vec_idx++) {
  176. FloatVector4& vec = vecs.at(vec_idx);
  177. GLVertex vertex;
  178. // Perform the perspective divide
  179. if (vec.w() != 0.0f) {
  180. vec.set_x(vec.x() / vec.w());
  181. vec.set_y(vec.y() / vec.w());
  182. vec.set_z(vec.z() / vec.w());
  183. vec.set_w(1 / vec.w());
  184. }
  185. vertex.x = vec.x();
  186. vertex.y = vec.y();
  187. vertex.z = vec.z();
  188. vertex.w = vec.w();
  189. // FIXME: This is to suppress any -Wunused errors
  190. vertex.u = 0.0f;
  191. vertex.v = 0.0f;
  192. if (vec_idx == 0) {
  193. vertex.r = vertexa.r;
  194. vertex.g = vertexa.g;
  195. vertex.b = vertexa.b;
  196. vertex.a = vertexa.a;
  197. vertex.u = vertexa.u;
  198. vertex.v = vertexa.v;
  199. } else if (vec_idx == 1) {
  200. vertex.r = vertexb.r;
  201. vertex.g = vertexb.g;
  202. vertex.b = vertexb.b;
  203. vertex.a = vertexb.a;
  204. vertex.u = vertexb.u;
  205. vertex.v = vertexb.v;
  206. } else {
  207. vertex.r = vertexc.r;
  208. vertex.g = vertexc.g;
  209. vertex.b = vertexc.b;
  210. vertex.a = vertexc.a;
  211. vertex.u = vertexc.u;
  212. vertex.v = vertexc.v;
  213. }
  214. vertex.x = (vec.x() + 1.0f) * (scr_width / 2.0f) + 0.0f; // TODO: 0.0f should be something!?
  215. vertex.y = scr_height - ((vec.y() + 1.0f) * (scr_height / 2.0f) + 0.0f);
  216. vertex.z = vec.z();
  217. verts.append(vertex);
  218. }
  219. if (verts.size() == 0) {
  220. continue;
  221. } else if (verts.size() == 3) {
  222. GLTriangle tri;
  223. tri.vertices[0] = verts.at(0);
  224. tri.vertices[1] = verts.at(1);
  225. tri.vertices[2] = verts.at(2);
  226. processed_triangles.append(tri);
  227. } else if (verts.size() == 4) {
  228. GLTriangle tri1;
  229. GLTriangle tri2;
  230. tri1.vertices[0] = verts.at(0);
  231. tri1.vertices[1] = verts.at(1);
  232. tri1.vertices[2] = verts.at(2);
  233. processed_triangles.append(tri1);
  234. tri2.vertices[0] = verts.at(0);
  235. tri2.vertices[1] = verts.at(2);
  236. tri2.vertices[2] = verts.at(3);
  237. processed_triangles.append(tri2);
  238. }
  239. }
  240. for (size_t i = 0; i < processed_triangles.size(); i++) {
  241. GLTriangle& triangle = processed_triangles.at(i);
  242. // Let's calculate the (signed) area of the triangle
  243. // https://cp-algorithms.com/geometry/oriented-triangle-area.html
  244. float dxAB = triangle.vertices[0].x - triangle.vertices[1].x; // A.x - B.x
  245. float dxBC = triangle.vertices[1].x - triangle.vertices[2].x; // B.X - C.x
  246. float dyAB = triangle.vertices[0].y - triangle.vertices[1].y;
  247. float dyBC = triangle.vertices[1].y - triangle.vertices[2].y;
  248. float area = (dxAB * dyBC) - (dxBC * dyAB);
  249. if (area == 0.0f)
  250. continue;
  251. if (m_cull_faces) {
  252. bool is_front = (m_front_face == GL_CCW ? area > 0 : area < 0);
  253. if (is_front && (m_culled_sides == GL_FRONT || m_culled_sides == GL_FRONT_AND_BACK))
  254. continue;
  255. if (!is_front && (m_culled_sides == GL_BACK || m_culled_sides == GL_FRONT_AND_BACK))
  256. continue;
  257. }
  258. // FIXME: Change this when we have texture units/multi-texturing
  259. if (m_bound_texture_2d == 0) {
  260. m_rasterizer.submit_triangle(triangle);
  261. } else {
  262. auto it = m_allocated_textures.find(m_bound_texture_2d);
  263. m_rasterizer.submit_triangle(triangle, *static_ptr_cast<Texture2D>(it->value));
  264. }
  265. }
  266. triangle_list.clear();
  267. processed_triangles.clear();
  268. vertex_list.clear();
  269. m_in_draw_state = false;
  270. }
  271. void SoftwareGLContext::gl_frustum(GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble near_val, GLdouble far_val)
  272. {
  273. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_frustum, left, right, bottom, top, near_val, far_val);
  274. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  275. // Let's do some math!
  276. // FIXME: Are we losing too much precision by doing this?
  277. float a = static_cast<float>((right + left) / (right - left));
  278. float b = static_cast<float>((top + bottom) / (top - bottom));
  279. float c = static_cast<float>(-((far_val + near_val) / (far_val - near_val)));
  280. float d = static_cast<float>(-((2 * (far_val * near_val)) / (far_val - near_val)));
  281. FloatMatrix4x4 frustum {
  282. ((2 * (float)near_val) / ((float)right - (float)left)), 0, a, 0,
  283. 0, ((2 * (float)near_val) / ((float)top - (float)bottom)), b, 0,
  284. 0, 0, c, d,
  285. 0, 0, -1, 0
  286. };
  287. if (m_current_matrix_mode == GL_PROJECTION) {
  288. m_projection_matrix = m_projection_matrix * frustum;
  289. } else if (m_current_matrix_mode == GL_MODELVIEW) {
  290. dbgln_if(GL_DEBUG, "glFrustum(): frustum created with curr_matrix_mode == GL_MODELVIEW!!!");
  291. m_projection_matrix = m_model_view_matrix * frustum;
  292. }
  293. }
  294. void SoftwareGLContext::gl_ortho(GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble near_val, GLdouble far_val)
  295. {
  296. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_ortho, left, right, bottom, top, near_val, far_val);
  297. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  298. RETURN_WITH_ERROR_IF(left == right || bottom == top || near_val == far_val, GL_INVALID_VALUE);
  299. auto rl = right - left;
  300. auto tb = top - bottom;
  301. auto fn = far_val - near_val;
  302. auto tx = -(right + left) / rl;
  303. auto ty = -(top + bottom) / tb;
  304. auto tz = -(far_val + near_val) / fn;
  305. FloatMatrix4x4 projection {
  306. static_cast<float>(2 / rl), 0, 0, static_cast<float>(tx),
  307. 0, static_cast<float>(2 / tb), 0, static_cast<float>(ty),
  308. 0, 0, static_cast<float>(-2 / fn), static_cast<float>(tz),
  309. 0, 0, 0, 1
  310. };
  311. if (m_current_matrix_mode == GL_PROJECTION) {
  312. m_projection_matrix = m_projection_matrix * projection;
  313. } else if (m_current_matrix_mode == GL_MODELVIEW) {
  314. m_projection_matrix = m_model_view_matrix * projection;
  315. }
  316. }
  317. GLenum SoftwareGLContext::gl_get_error()
  318. {
  319. if (m_in_draw_state)
  320. return GL_INVALID_OPERATION;
  321. auto last_error = m_error;
  322. m_error = GL_NO_ERROR;
  323. return last_error;
  324. }
  325. GLubyte* SoftwareGLContext::gl_get_string(GLenum name)
  326. {
  327. RETURN_VALUE_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION, nullptr);
  328. switch (name) {
  329. case GL_VENDOR:
  330. return reinterpret_cast<GLubyte*>(const_cast<char*>("The SerenityOS Developers"));
  331. case GL_RENDERER:
  332. return reinterpret_cast<GLubyte*>(const_cast<char*>("SerenityOS OpenGL"));
  333. case GL_VERSION:
  334. return reinterpret_cast<GLubyte*>(const_cast<char*>("OpenGL 1.2 SerenityOS"));
  335. default:
  336. dbgln_if(GL_DEBUG, "glGetString(): Unknown enum name!");
  337. break;
  338. }
  339. RETURN_VALUE_WITH_ERROR_IF(true, GL_INVALID_ENUM, nullptr);
  340. }
  341. void SoftwareGLContext::gl_load_identity()
  342. {
  343. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_load_identity);
  344. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  345. if (m_current_matrix_mode == GL_PROJECTION)
  346. m_projection_matrix = FloatMatrix4x4::identity();
  347. else if (m_current_matrix_mode == GL_MODELVIEW)
  348. m_model_view_matrix = FloatMatrix4x4::identity();
  349. else
  350. VERIFY_NOT_REACHED();
  351. }
  352. void SoftwareGLContext::gl_load_matrix(const FloatMatrix4x4& matrix)
  353. {
  354. if (should_append_to_listing()) {
  355. auto ptr = store_in_listing(matrix);
  356. append_to_listing<&SoftwareGLContext::gl_load_matrix>(*ptr);
  357. if (!should_execute_after_appending_to_listing())
  358. return;
  359. }
  360. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  361. if (m_current_matrix_mode == GL_PROJECTION)
  362. m_projection_matrix = matrix;
  363. else if (m_current_matrix_mode == GL_MODELVIEW)
  364. m_model_view_matrix = matrix;
  365. else
  366. VERIFY_NOT_REACHED();
  367. }
  368. void SoftwareGLContext::gl_matrix_mode(GLenum mode)
  369. {
  370. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_matrix_mode, mode);
  371. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  372. RETURN_WITH_ERROR_IF(mode < GL_MODELVIEW || mode > GL_PROJECTION, GL_INVALID_ENUM);
  373. m_current_matrix_mode = mode;
  374. }
  375. void SoftwareGLContext::gl_push_matrix()
  376. {
  377. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_push_matrix);
  378. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  379. dbgln_if(GL_DEBUG, "glPushMatrix(): Pushing matrix to the matrix stack (matrix_mode {})", m_current_matrix_mode);
  380. switch (m_current_matrix_mode) {
  381. case GL_PROJECTION:
  382. RETURN_WITH_ERROR_IF(m_projection_matrix_stack.size() >= MATRIX_STACK_LIMIT, GL_STACK_OVERFLOW);
  383. m_projection_matrix_stack.append(m_projection_matrix);
  384. break;
  385. case GL_MODELVIEW:
  386. RETURN_WITH_ERROR_IF(m_model_view_matrix_stack.size() >= MATRIX_STACK_LIMIT, GL_STACK_OVERFLOW);
  387. m_model_view_matrix_stack.append(m_model_view_matrix);
  388. break;
  389. default:
  390. dbgln_if(GL_DEBUG, "glPushMatrix(): Attempt to push matrix with invalid matrix mode {})", m_current_matrix_mode);
  391. return;
  392. }
  393. }
  394. void SoftwareGLContext::gl_pop_matrix()
  395. {
  396. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_pop_matrix);
  397. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  398. dbgln_if(GL_DEBUG, "glPopMatrix(): Popping matrix from matrix stack (matrix_mode = {})", m_current_matrix_mode);
  399. // FIXME: Make sure stack::top() doesn't cause any nasty issues if it's empty (that could result in a lockup/hang)
  400. switch (m_current_matrix_mode) {
  401. case GL_PROJECTION:
  402. RETURN_WITH_ERROR_IF(m_projection_matrix_stack.size() == 0, GL_STACK_UNDERFLOW);
  403. m_projection_matrix = m_projection_matrix_stack.take_last();
  404. break;
  405. case GL_MODELVIEW:
  406. RETURN_WITH_ERROR_IF(m_model_view_matrix_stack.size() == 0, GL_STACK_UNDERFLOW);
  407. m_model_view_matrix = m_model_view_matrix_stack.take_last();
  408. break;
  409. default:
  410. dbgln_if(GL_DEBUG, "glPopMatrix(): Attempt to pop matrix with invalid matrix mode, {}", m_current_matrix_mode);
  411. return;
  412. }
  413. }
  414. void SoftwareGLContext::gl_rotate(GLdouble angle, GLdouble x, GLdouble y, GLdouble z)
  415. {
  416. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_rotate, angle, x, y, z);
  417. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  418. FloatVector3 axis = { (float)x, (float)y, (float)z };
  419. axis.normalize();
  420. auto rotation_mat = Gfx::rotation_matrix(axis, static_cast<float>(angle));
  421. if (m_current_matrix_mode == GL_MODELVIEW)
  422. m_model_view_matrix = m_model_view_matrix * rotation_mat;
  423. else if (m_current_matrix_mode == GL_PROJECTION)
  424. m_projection_matrix = m_projection_matrix * rotation_mat;
  425. }
  426. void SoftwareGLContext::gl_scale(GLdouble x, GLdouble y, GLdouble z)
  427. {
  428. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_scale, x, y, z);
  429. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  430. if (m_current_matrix_mode == GL_MODELVIEW) {
  431. m_model_view_matrix = m_model_view_matrix * Gfx::scale_matrix(FloatVector3 { static_cast<float>(x), static_cast<float>(y), static_cast<float>(z) });
  432. } else if (m_current_matrix_mode == GL_PROJECTION) {
  433. m_projection_matrix = m_projection_matrix * Gfx::scale_matrix(FloatVector3 { static_cast<float>(x), static_cast<float>(y), static_cast<float>(z) });
  434. }
  435. }
  436. void SoftwareGLContext::gl_translate(GLdouble x, GLdouble y, GLdouble z)
  437. {
  438. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_translate, x, y, z);
  439. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  440. if (m_current_matrix_mode == GL_MODELVIEW) {
  441. m_model_view_matrix = m_model_view_matrix * Gfx::translation_matrix(FloatVector3 { (float)x, (float)y, (float)z });
  442. } else if (m_current_matrix_mode == GL_PROJECTION) {
  443. m_projection_matrix = m_projection_matrix * Gfx::translation_matrix(FloatVector3 { (float)x, (float)y, (float)z });
  444. }
  445. }
  446. void SoftwareGLContext::gl_vertex(GLdouble x, GLdouble y, GLdouble z, GLdouble w)
  447. {
  448. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_vertex, x, y, z, w);
  449. GLVertex vertex;
  450. vertex.x = x;
  451. vertex.y = y;
  452. vertex.z = z;
  453. vertex.w = w;
  454. vertex.r = m_current_vertex_color.x();
  455. vertex.g = m_current_vertex_color.y();
  456. vertex.b = m_current_vertex_color.z();
  457. vertex.a = m_current_vertex_color.w();
  458. // FIXME: This is to suppress any -Wunused errors
  459. vertex.w = 0.0f;
  460. vertex.u = 0.0f;
  461. vertex.v = 0.0f;
  462. vertex_list.append(vertex);
  463. }
  464. // FIXME: We need to add `r` and `q` to our GLVertex?!
  465. void SoftwareGLContext::gl_tex_coord(GLfloat s, GLfloat t, GLfloat, GLfloat)
  466. {
  467. auto& vertex = vertex_list.last(); // Get the last created vertex
  468. vertex.u = s;
  469. vertex.v = t;
  470. }
  471. void SoftwareGLContext::gl_viewport(GLint x, GLint y, GLsizei width, GLsizei height)
  472. {
  473. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_viewport, x, y, width, height);
  474. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  475. (void)(x);
  476. (void)(y);
  477. (void)(width);
  478. (void)(height);
  479. }
  480. void SoftwareGLContext::gl_enable(GLenum capability)
  481. {
  482. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_enable, capability);
  483. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  484. auto rasterizer_options = m_rasterizer.options();
  485. bool update_rasterizer_options = false;
  486. switch (capability) {
  487. case GL_CULL_FACE:
  488. m_cull_faces = true;
  489. break;
  490. case GL_DEPTH_TEST:
  491. m_depth_test_enabled = true;
  492. rasterizer_options.enable_depth_test = true;
  493. update_rasterizer_options = true;
  494. break;
  495. case GL_BLEND:
  496. m_blend_enabled = true;
  497. rasterizer_options.enable_blending = true;
  498. update_rasterizer_options = true;
  499. break;
  500. case GL_ALPHA_TEST:
  501. m_alpha_test_enabled = true;
  502. rasterizer_options.enable_alpha_test = true;
  503. update_rasterizer_options = true;
  504. break;
  505. default:
  506. RETURN_WITH_ERROR_IF(true, GL_INVALID_ENUM);
  507. }
  508. if (update_rasterizer_options)
  509. m_rasterizer.set_options(rasterizer_options);
  510. }
  511. void SoftwareGLContext::gl_disable(GLenum capability)
  512. {
  513. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_disable, capability);
  514. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  515. auto rasterizer_options = m_rasterizer.options();
  516. bool update_rasterizer_options = false;
  517. switch (capability) {
  518. case GL_CULL_FACE:
  519. m_cull_faces = false;
  520. break;
  521. case GL_DEPTH_TEST:
  522. m_depth_test_enabled = false;
  523. rasterizer_options.enable_depth_test = false;
  524. update_rasterizer_options = true;
  525. break;
  526. case GL_BLEND:
  527. m_blend_enabled = false;
  528. rasterizer_options.enable_blending = false;
  529. update_rasterizer_options = true;
  530. break;
  531. case GL_ALPHA_TEST:
  532. m_alpha_test_enabled = false;
  533. rasterizer_options.enable_alpha_test = false;
  534. update_rasterizer_options = true;
  535. break;
  536. default:
  537. RETURN_WITH_ERROR_IF(true, GL_INVALID_ENUM);
  538. }
  539. if (update_rasterizer_options)
  540. m_rasterizer.set_options(rasterizer_options);
  541. }
  542. void SoftwareGLContext::gl_gen_textures(GLsizei n, GLuint* textures)
  543. {
  544. RETURN_WITH_ERROR_IF(n < 0, GL_INVALID_VALUE);
  545. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  546. m_name_allocator.allocate(n, textures);
  547. // Initialize all texture names with a nullptr
  548. for (auto i = 0; i < n; i++) {
  549. GLuint name = textures[i];
  550. m_allocated_textures.set(name, nullptr);
  551. }
  552. }
  553. void SoftwareGLContext::gl_delete_textures(GLsizei n, const GLuint* textures)
  554. {
  555. RETURN_WITH_ERROR_IF(n < 0, GL_INVALID_VALUE);
  556. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  557. m_name_allocator.free(n, textures);
  558. for (auto i = 0; i < n; i++) {
  559. GLuint name = textures[i];
  560. // unbind texture if it is currently bound
  561. if (m_bound_texture_2d == name)
  562. m_bound_texture_2d = 0;
  563. m_allocated_textures.remove(name);
  564. }
  565. }
  566. void SoftwareGLContext::gl_tex_image_2d(GLenum target, GLint level, GLint internal_format, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const GLvoid* data)
  567. {
  568. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  569. // We only support GL_TEXTURE_2D for now
  570. RETURN_WITH_ERROR_IF(target != GL_TEXTURE_2D, GL_INVALID_ENUM);
  571. // Check if there is actually a texture bound
  572. RETURN_WITH_ERROR_IF(target == GL_TEXTURE_2D && m_bound_texture_2d == 0, GL_INVALID_OPERATION);
  573. // We only support symbolic constants for now
  574. RETURN_WITH_ERROR_IF(!(internal_format == GL_RGB || internal_format == GL_RGBA), GL_INVALID_ENUM);
  575. RETURN_WITH_ERROR_IF(type != GL_UNSIGNED_BYTE, GL_INVALID_VALUE);
  576. RETURN_WITH_ERROR_IF(level < 0 || level > Texture2D::LOG2_MAX_TEXTURE_SIZE, GL_INVALID_VALUE);
  577. RETURN_WITH_ERROR_IF(width < 0 || height < 0 || width > (2 + Texture2D::MAX_TEXTURE_SIZE) || height > (2 + Texture2D::MAX_TEXTURE_SIZE), GL_INVALID_VALUE);
  578. RETURN_WITH_ERROR_IF((width & 2) != 0 || (height & 2) != 0, GL_INVALID_VALUE);
  579. RETURN_WITH_ERROR_IF(border < 0 || border > 1, GL_INVALID_VALUE);
  580. // TODO: Load texture from the currently active texture unit
  581. // This is to test the functionality of texture data upload
  582. static_ptr_cast<Texture2D>(m_allocated_textures.find(1)->value)->upload_texture_data(target, level, internal_format, width, height, border, format, type, data);
  583. }
  584. void SoftwareGLContext::gl_front_face(GLenum face)
  585. {
  586. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_front_face, face);
  587. RETURN_WITH_ERROR_IF(face < GL_CW || face > GL_CCW, GL_INVALID_ENUM);
  588. m_front_face = face;
  589. }
  590. void SoftwareGLContext::gl_cull_face(GLenum cull_mode)
  591. {
  592. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_cull_face, cull_mode);
  593. RETURN_WITH_ERROR_IF(cull_mode < GL_FRONT || cull_mode > GL_FRONT_AND_BACK, GL_INVALID_ENUM);
  594. m_culled_sides = cull_mode;
  595. }
  596. GLuint SoftwareGLContext::gl_gen_lists(GLsizei range)
  597. {
  598. RETURN_VALUE_WITH_ERROR_IF(range <= 0, GL_INVALID_VALUE, 0);
  599. RETURN_VALUE_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION, 0);
  600. auto initial_entry = m_listings.size();
  601. m_listings.resize(range + initial_entry);
  602. return initial_entry + 1;
  603. }
  604. void SoftwareGLContext::gl_call_list(GLuint list)
  605. {
  606. if (m_gl_call_depth > max_allowed_gl_call_depth)
  607. return;
  608. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_call_list, list);
  609. if (m_listings.size() < list)
  610. return;
  611. TemporaryChange change { m_gl_call_depth, m_gl_call_depth + 1 };
  612. auto& listing = m_listings[list - 1];
  613. for (auto& entry : listing.entries) {
  614. entry.function.visit([&](auto& function) {
  615. entry.arguments.visit([&](auto& arguments) {
  616. auto apply = [&]<typename... Args>(Args && ... args)
  617. {
  618. if constexpr (requires { (this->*function)(forward<Args>(args)...); })
  619. (this->*function)(forward<Args>(args)...);
  620. };
  621. arguments.apply_as_args(apply);
  622. });
  623. });
  624. }
  625. }
  626. void SoftwareGLContext::gl_delete_lists(GLuint list, GLsizei range)
  627. {
  628. if (m_listings.size() < list || m_listings.size() <= list + range)
  629. return;
  630. for (auto& entry : m_listings.span().slice(list - 1, range))
  631. entry.entries.clear();
  632. }
  633. void SoftwareGLContext::gl_end_list()
  634. {
  635. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  636. RETURN_WITH_ERROR_IF(!m_current_listing_index.has_value(), GL_INVALID_OPERATION);
  637. m_listings[m_current_listing_index->index] = move(m_current_listing_index->listing);
  638. m_current_listing_index.clear();
  639. }
  640. void SoftwareGLContext::gl_new_list(GLuint list, GLenum mode)
  641. {
  642. RETURN_WITH_ERROR_IF(list == 0, GL_INVALID_VALUE);
  643. RETURN_WITH_ERROR_IF(mode != GL_COMPILE && mode != GL_COMPILE_AND_EXECUTE, GL_INVALID_ENUM);
  644. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  645. RETURN_WITH_ERROR_IF(m_current_listing_index.has_value(), GL_INVALID_OPERATION);
  646. if (m_listings.size() < list)
  647. return;
  648. m_current_listing_index = CurrentListing { {}, static_cast<size_t>(list - 1), mode };
  649. }
  650. void SoftwareGLContext::gl_flush()
  651. {
  652. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  653. // No-op since SoftwareGLContext is completely synchronous at the moment
  654. }
  655. void SoftwareGLContext::gl_finish()
  656. {
  657. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  658. // No-op since SoftwareGLContext is completely synchronous at the moment
  659. }
  660. void SoftwareGLContext::gl_blend_func(GLenum src_factor, GLenum dst_factor)
  661. {
  662. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_blend_func, src_factor, dst_factor);
  663. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  664. // FIXME: The list of allowed enums differs between API versions
  665. // This was taken from the 2.0 spec on https://docs.gl/gl2/glBlendFunc
  666. RETURN_WITH_ERROR_IF(!(src_factor == GL_ZERO
  667. || src_factor == GL_ONE
  668. || src_factor == GL_SRC_COLOR
  669. || src_factor == GL_ONE_MINUS_SRC_COLOR
  670. || src_factor == GL_DST_COLOR
  671. || src_factor == GL_ONE_MINUS_DST_COLOR
  672. || src_factor == GL_SRC_ALPHA
  673. || src_factor == GL_ONE_MINUS_SRC_ALPHA
  674. || src_factor == GL_DST_ALPHA
  675. || src_factor == GL_ONE_MINUS_DST_ALPHA
  676. || src_factor == GL_CONSTANT_COLOR
  677. || src_factor == GL_ONE_MINUS_CONSTANT_COLOR
  678. || src_factor == GL_CONSTANT_ALPHA
  679. || src_factor == GL_ONE_MINUS_CONSTANT_ALPHA
  680. || src_factor == GL_SRC_ALPHA_SATURATE),
  681. GL_INVALID_ENUM);
  682. RETURN_WITH_ERROR_IF(!(dst_factor == GL_ZERO
  683. || dst_factor == GL_ONE
  684. || dst_factor == GL_SRC_COLOR
  685. || dst_factor == GL_ONE_MINUS_SRC_COLOR
  686. || dst_factor == GL_DST_COLOR
  687. || dst_factor == GL_ONE_MINUS_DST_COLOR
  688. || dst_factor == GL_SRC_ALPHA
  689. || dst_factor == GL_ONE_MINUS_SRC_ALPHA
  690. || dst_factor == GL_DST_ALPHA
  691. || dst_factor == GL_ONE_MINUS_DST_ALPHA
  692. || dst_factor == GL_CONSTANT_COLOR
  693. || dst_factor == GL_ONE_MINUS_CONSTANT_COLOR
  694. || dst_factor == GL_CONSTANT_ALPHA
  695. || dst_factor == GL_ONE_MINUS_CONSTANT_ALPHA),
  696. GL_INVALID_ENUM);
  697. m_blend_source_factor = src_factor;
  698. m_blend_destination_factor = dst_factor;
  699. auto options = m_rasterizer.options();
  700. options.blend_source_factor = m_blend_source_factor;
  701. options.blend_destination_factor = m_blend_destination_factor;
  702. m_rasterizer.set_options(options);
  703. }
  704. void SoftwareGLContext::gl_shade_model(GLenum mode)
  705. {
  706. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_shade_model, mode);
  707. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  708. RETURN_WITH_ERROR_IF(mode != GL_FLAT && mode != GL_SMOOTH, GL_INVALID_ENUM);
  709. auto options = m_rasterizer.options();
  710. options.shade_smooth = (mode == GL_SMOOTH);
  711. m_rasterizer.set_options(options);
  712. }
  713. void SoftwareGLContext::gl_alpha_func(GLenum func, GLclampf ref)
  714. {
  715. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_alpha_func, func, ref);
  716. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  717. RETURN_WITH_ERROR_IF(func < GL_NEVER || func > GL_ALWAYS, GL_INVALID_ENUM);
  718. m_alpha_test_func = func;
  719. m_alpha_test_ref_value = ref;
  720. auto options = m_rasterizer.options();
  721. options.alpha_test_func = m_alpha_test_func;
  722. options.alpha_test_ref_value = m_alpha_test_ref_value;
  723. m_rasterizer.set_options(options);
  724. }
  725. void SoftwareGLContext::gl_hint(GLenum target, GLenum mode)
  726. {
  727. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_hint, target, mode);
  728. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  729. RETURN_WITH_ERROR_IF(target != GL_PERSPECTIVE_CORRECTION_HINT
  730. && target != GL_POINT_SMOOTH_HINT
  731. && target != GL_LINE_SMOOTH_HINT
  732. && target != GL_POLYGON_SMOOTH_HINT
  733. && target != GL_FOG_HINT
  734. && target != GL_GENERATE_MIPMAP_HINT
  735. && target != GL_TEXTURE_COMPRESSION_HINT,
  736. GL_INVALID_ENUM);
  737. RETURN_WITH_ERROR_IF(mode != GL_DONT_CARE
  738. && mode != GL_FASTEST
  739. && mode != GL_NICEST,
  740. GL_INVALID_ENUM);
  741. // According to the spec implementors are free to ignore glHint. So we do.
  742. }
  743. void SoftwareGLContext::gl_read_buffer(GLenum mode)
  744. {
  745. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_read_buffer, mode);
  746. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  747. // FIXME: Also allow aux buffers GL_AUX0 through GL_AUX3 here
  748. // plus any aux buffer between 0 and GL_AUX_BUFFERS
  749. RETURN_WITH_ERROR_IF(mode != GL_FRONT_LEFT
  750. && mode != GL_FRONT_RIGHT
  751. && mode != GL_BACK_LEFT
  752. && mode != GL_BACK_RIGHT
  753. && mode != GL_FRONT
  754. && mode != GL_BACK
  755. && mode != GL_LEFT
  756. && mode != GL_RIGHT,
  757. GL_INVALID_ENUM);
  758. // FIXME: We do not currently have aux buffers, so make it an invalid
  759. // operation to select anything but front or back buffers. Also we do
  760. // not allow selecting the stereoscopic RIGHT buffers since we do not
  761. // have them configured.
  762. RETURN_WITH_ERROR_IF(mode != GL_FRONT_LEFT
  763. && mode != GL_FRONT
  764. && mode != GL_BACK_LEFT
  765. && mode != GL_BACK
  766. && mode != GL_FRONT
  767. && mode != GL_BACK
  768. && mode != GL_LEFT,
  769. GL_INVALID_OPERATION);
  770. m_current_read_buffer = mode;
  771. }
  772. void SoftwareGLContext::gl_read_pixels(GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, GLvoid* pixels)
  773. {
  774. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  775. RETURN_WITH_ERROR_IF(width < 0 || height < 0, GL_INVALID_VALUE);
  776. RETURN_WITH_ERROR_IF(format != GL_COLOR_INDEX
  777. && format != GL_STENCIL_INDEX
  778. && format != GL_DEPTH_COMPONENT
  779. && format != GL_RED
  780. && format != GL_GREEN
  781. && format != GL_BLUE
  782. && format != GL_ALPHA
  783. && format != GL_RGB
  784. && format != GL_RGBA
  785. && format != GL_LUMINANCE
  786. && format != GL_LUMINANCE_ALPHA,
  787. GL_INVALID_ENUM);
  788. RETURN_WITH_ERROR_IF(type != GL_UNSIGNED_BYTE
  789. && type != GL_BYTE
  790. && type != GL_BITMAP
  791. && type != GL_UNSIGNED_SHORT
  792. && type != GL_SHORT
  793. && type != GL_BLUE
  794. && type != GL_UNSIGNED_INT
  795. && type != GL_INT
  796. && type != GL_FLOAT,
  797. GL_INVALID_ENUM);
  798. // FIXME: We only support RGBA buffers for now.
  799. // Once we add support for indexed color modes do the correct check here
  800. RETURN_WITH_ERROR_IF(format == GL_COLOR_INDEX, GL_INVALID_OPERATION);
  801. // FIXME: We do not have stencil buffers yet
  802. // Once we add support for stencil buffers do the correct check here
  803. RETURN_WITH_ERROR_IF(format == GL_STENCIL_INDEX, GL_INVALID_OPERATION);
  804. if (format == GL_DEPTH_COMPONENT) {
  805. // FIXME: This check needs to be a bit more sophisticated. Currently the buffers
  806. // are hardcoded. Once we add proper structures for them we need to correct this check
  807. // Error because only back buffer has a depth buffer
  808. RETURN_WITH_ERROR_IF(m_current_read_buffer == GL_FRONT
  809. || m_current_read_buffer == GL_FRONT_LEFT
  810. || m_current_read_buffer == GL_FRONT_RIGHT,
  811. GL_INVALID_OPERATION);
  812. }
  813. // Some helper functions for converting float values to integer types
  814. auto float_to_i8 = [](float f) -> GLchar {
  815. return static_cast<GLchar>((0x7f * min(max(f, 0.0f), 1.0f) - 1) / 2);
  816. };
  817. auto float_to_i16 = [](float f) -> GLshort {
  818. return static_cast<GLshort>((0x7fff * min(max(f, 0.0f), 1.0f) - 1) / 2);
  819. };
  820. auto float_to_i32 = [](float f) -> GLint {
  821. return static_cast<GLint>((0x7fffffff * min(max(f, 0.0f), 1.0f) - 1) / 2);
  822. };
  823. auto float_to_u8 = [](float f) -> GLubyte {
  824. return static_cast<GLubyte>(0xff * min(max(f, 0.0f), 1.0f));
  825. };
  826. auto float_to_u16 = [](float f) -> GLushort {
  827. return static_cast<GLushort>(0xffff * min(max(f, 0.0f), 1.0f));
  828. };
  829. auto float_to_u32 = [](float f) -> GLuint {
  830. return static_cast<GLuint>(0xffffffff * min(max(f, 0.0f), 1.0f));
  831. };
  832. if (format == GL_DEPTH_COMPONENT) {
  833. // Read from depth buffer
  834. for (GLsizei i = 0; i < height; ++i) {
  835. for (GLsizei j = 0; j < width; ++j) {
  836. float depth = m_rasterizer.get_depthbuffer_value(x + j, y + i);
  837. switch (type) {
  838. case GL_BYTE:
  839. reinterpret_cast<GLchar*>(pixels)[i * width + j] = float_to_i8(depth);
  840. break;
  841. case GL_SHORT:
  842. reinterpret_cast<GLshort*>(pixels)[i * width + j] = float_to_i16(depth);
  843. break;
  844. case GL_INT:
  845. reinterpret_cast<GLint*>(pixels)[i * width + j] = float_to_i32(depth);
  846. break;
  847. case GL_UNSIGNED_BYTE:
  848. reinterpret_cast<GLubyte*>(pixels)[i * width + j] = float_to_u8(depth);
  849. break;
  850. case GL_UNSIGNED_SHORT:
  851. reinterpret_cast<GLushort*>(pixels)[i * width + j] = float_to_u16(depth);
  852. break;
  853. case GL_UNSIGNED_INT:
  854. reinterpret_cast<GLuint*>(pixels)[i * width + j] = float_to_u32(depth);
  855. break;
  856. case GL_FLOAT:
  857. reinterpret_cast<GLfloat*>(pixels)[i * width + j] = min(max(depth, 0.0f), 1.0f);
  858. break;
  859. }
  860. }
  861. }
  862. return;
  863. }
  864. bool write_red = false;
  865. bool write_green = false;
  866. bool write_blue = false;
  867. bool write_alpha = false;
  868. size_t component_count = 0;
  869. size_t component_size = 0;
  870. size_t red_offset = 0;
  871. size_t green_offset = 0;
  872. size_t blue_offset = 0;
  873. size_t alpha_offset = 0;
  874. char* red_ptr = nullptr;
  875. char* green_ptr = nullptr;
  876. char* blue_ptr = nullptr;
  877. char* alpha_ptr = nullptr;
  878. switch (format) {
  879. case GL_RGB:
  880. write_red = true;
  881. write_green = true;
  882. write_blue = true;
  883. component_count = 3;
  884. red_offset = 2;
  885. green_offset = 1;
  886. blue_offset = 0;
  887. break;
  888. case GL_RGBA:
  889. write_red = true;
  890. write_green = true;
  891. write_blue = true;
  892. write_alpha = true;
  893. component_count = 4;
  894. red_offset = 3;
  895. green_offset = 2;
  896. blue_offset = 1;
  897. alpha_offset = 0;
  898. break;
  899. case GL_RED:
  900. write_red = true;
  901. component_count = 1;
  902. red_offset = 0;
  903. break;
  904. case GL_GREEN:
  905. write_green = true;
  906. component_count = 1;
  907. green_offset = 0;
  908. break;
  909. case GL_BLUE:
  910. write_blue = true;
  911. component_count = 1;
  912. blue_offset = 0;
  913. break;
  914. case GL_ALPHA:
  915. write_alpha = true;
  916. component_count = 1;
  917. alpha_offset = 0;
  918. break;
  919. }
  920. switch (type) {
  921. case GL_BYTE:
  922. case GL_UNSIGNED_BYTE:
  923. component_size = 1;
  924. break;
  925. case GL_SHORT:
  926. case GL_UNSIGNED_SHORT:
  927. component_size = 2;
  928. break;
  929. case GL_INT:
  930. case GL_UNSIGNED_INT:
  931. case GL_FLOAT:
  932. component_size = 4;
  933. break;
  934. }
  935. char* out_ptr = reinterpret_cast<char*>(pixels);
  936. for (int i = 0; i < (int)height; ++i) {
  937. for (int j = 0; j < (int)width; ++j) {
  938. Gfx::RGBA32 color {};
  939. if (m_current_read_buffer == GL_FRONT || m_current_read_buffer == GL_LEFT || m_current_read_buffer == GL_FRONT_LEFT) {
  940. if (y + i >= m_frontbuffer->width() || x + j >= m_frontbuffer->height())
  941. color = 0;
  942. else
  943. color = m_frontbuffer->scanline(y + i)[x + j];
  944. } else {
  945. color = m_rasterizer.get_backbuffer_pixel(x + j, y + i);
  946. }
  947. float red = ((color >> 24) & 0xff) / 255.0f;
  948. float green = ((color >> 16) & 0xff) / 255.0f;
  949. float blue = ((color >> 8) & 0xff) / 255.0f;
  950. float alpha = (color & 0xff) / 255.0f;
  951. // FIXME: Set up write pointers based on selected endianness (glPixelStore)
  952. red_ptr = out_ptr + (component_size * red_offset);
  953. green_ptr = out_ptr + (component_size * green_offset);
  954. blue_ptr = out_ptr + (component_size * blue_offset);
  955. alpha_ptr = out_ptr + (component_size * alpha_offset);
  956. switch (type) {
  957. case GL_BYTE:
  958. if (write_red)
  959. *reinterpret_cast<GLchar*>(red_ptr) = float_to_i8(red);
  960. if (write_green)
  961. *reinterpret_cast<GLchar*>(green_ptr) = float_to_i8(green);
  962. if (write_blue)
  963. *reinterpret_cast<GLchar*>(blue_ptr) = float_to_i8(blue);
  964. if (write_alpha)
  965. *reinterpret_cast<GLchar*>(alpha_ptr) = float_to_i8(alpha);
  966. break;
  967. case GL_UNSIGNED_BYTE:
  968. if (write_red)
  969. *reinterpret_cast<GLubyte*>(red_ptr) = float_to_u8(red);
  970. if (write_green)
  971. *reinterpret_cast<GLubyte*>(green_ptr) = float_to_u8(green);
  972. if (write_blue)
  973. *reinterpret_cast<GLubyte*>(blue_ptr) = float_to_u8(blue);
  974. if (write_alpha)
  975. *reinterpret_cast<GLubyte*>(alpha_ptr) = float_to_u8(alpha);
  976. break;
  977. case GL_SHORT:
  978. if (write_red)
  979. *reinterpret_cast<GLshort*>(red_ptr) = float_to_i16(red);
  980. if (write_green)
  981. *reinterpret_cast<GLshort*>(green_ptr) = float_to_i16(green);
  982. if (write_blue)
  983. *reinterpret_cast<GLshort*>(blue_ptr) = float_to_i16(blue);
  984. if (write_alpha)
  985. *reinterpret_cast<GLshort*>(alpha_ptr) = float_to_i16(alpha);
  986. break;
  987. case GL_UNSIGNED_SHORT:
  988. if (write_red)
  989. *reinterpret_cast<GLushort*>(red_ptr) = float_to_u16(red);
  990. if (write_green)
  991. *reinterpret_cast<GLushort*>(green_ptr) = float_to_u16(green);
  992. if (write_blue)
  993. *reinterpret_cast<GLushort*>(blue_ptr) = float_to_u16(blue);
  994. if (write_alpha)
  995. *reinterpret_cast<GLushort*>(alpha_ptr) = float_to_u16(alpha);
  996. break;
  997. case GL_INT:
  998. if (write_red)
  999. *reinterpret_cast<GLint*>(red_ptr) = float_to_i32(red);
  1000. if (write_green)
  1001. *reinterpret_cast<GLint*>(green_ptr) = float_to_i32(green);
  1002. if (write_blue)
  1003. *reinterpret_cast<GLint*>(blue_ptr) = float_to_i32(blue);
  1004. if (write_alpha)
  1005. *reinterpret_cast<GLint*>(alpha_ptr) = float_to_i32(alpha);
  1006. break;
  1007. case GL_UNSIGNED_INT:
  1008. if (write_red)
  1009. *reinterpret_cast<GLuint*>(red_ptr) = float_to_u32(red);
  1010. if (write_green)
  1011. *reinterpret_cast<GLuint*>(green_ptr) = float_to_u32(green);
  1012. if (write_blue)
  1013. *reinterpret_cast<GLuint*>(blue_ptr) = float_to_u32(blue);
  1014. if (write_alpha)
  1015. *reinterpret_cast<GLuint*>(alpha_ptr) = float_to_u32(alpha);
  1016. break;
  1017. case GL_FLOAT:
  1018. if (write_red)
  1019. *reinterpret_cast<GLfloat*>(red_ptr) = min(max(red, 0.0f), 1.0f);
  1020. if (write_green)
  1021. *reinterpret_cast<GLfloat*>(green_ptr) = min(max(green, 0.0f), 1.0f);
  1022. if (write_blue)
  1023. *reinterpret_cast<GLfloat*>(blue_ptr) = min(max(blue, 0.0f), 1.0f);
  1024. if (write_alpha)
  1025. *reinterpret_cast<GLfloat*>(alpha_ptr) = min(max(alpha, 0.0f), 1.0f);
  1026. break;
  1027. }
  1028. out_ptr += component_size * component_count;
  1029. }
  1030. }
  1031. }
  1032. void SoftwareGLContext::gl_bind_texture(GLenum target, GLuint texture)
  1033. {
  1034. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  1035. // FIXME: We only support GL_TEXTURE_2D for now
  1036. RETURN_WITH_ERROR_IF(target != GL_TEXTURE_2D, GL_INVALID_ENUM);
  1037. if (texture == 0) {
  1038. switch (target) {
  1039. case GL_TEXTURE_2D:
  1040. m_bound_texture_2d = 0;
  1041. return;
  1042. default:
  1043. VERIFY_NOT_REACHED();
  1044. return;
  1045. }
  1046. }
  1047. auto it = m_allocated_textures.find(texture);
  1048. // The texture name does not exist
  1049. RETURN_WITH_ERROR_IF(it == m_allocated_textures.end(), GL_INVALID_VALUE);
  1050. auto texture_object = it->value;
  1051. // Binding a texture to a different target than it was first bound is an invalid operation
  1052. // FIXME: We only support GL_TEXTURE_2D for now
  1053. RETURN_WITH_ERROR_IF(target == GL_TEXTURE_2D && !texture_object.is_null() && !texture_object->is_texture_2d(), GL_INVALID_OPERATION);
  1054. if (!texture_object) {
  1055. // This is the first time the texture is bound. Allocate an actual texture object
  1056. switch (target) {
  1057. case GL_TEXTURE_2D:
  1058. texture_object = adopt_ref(*new Texture2D());
  1059. break;
  1060. default:
  1061. VERIFY_NOT_REACHED();
  1062. break;
  1063. }
  1064. m_allocated_textures.set(texture, texture_object);
  1065. }
  1066. switch (target) {
  1067. case GL_TEXTURE_2D:
  1068. m_bound_texture_2d = texture;
  1069. break;
  1070. }
  1071. }
  1072. void SoftwareGLContext::gl_active_texture(GLenum texture)
  1073. {
  1074. RETURN_WITH_ERROR_IF(texture < GL_TEXTURE0 || texture > GL_TEXTURE31, GL_INVALID_ENUM);
  1075. m_active_texture_unit = &m_texture_units.at(texture - GL_TEXTURE0);
  1076. }
  1077. void SoftwareGLContext::present()
  1078. {
  1079. m_rasterizer.blit_to(*m_frontbuffer);
  1080. }
  1081. }