SoftwareGLContext.cpp 45 KB

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