SoftwareGLContext.cpp 53 KB

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