GLContext.cpp 141 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747
  1. /*
  2. * Copyright (c) 2021, Jesse Buhagiar <jooster669@gmail.com>
  3. * Copyright (c) 2021, Stephan Unverwerth <s.unverwerth@serenityos.org>
  4. * Copyright (c) 2022, Jelle Raaijmakers <jelle@gmta.nl>
  5. *
  6. * SPDX-License-Identifier: BSD-2-Clause
  7. */
  8. #include <AK/Assertions.h>
  9. #include <AK/Debug.h>
  10. #include <AK/Format.h>
  11. #include <AK/QuickSort.h>
  12. #include <AK/StringBuilder.h>
  13. #include <AK/TemporaryChange.h>
  14. #include <AK/Variant.h>
  15. #include <AK/Vector.h>
  16. #include <LibGL/GLContext.h>
  17. #include <LibGfx/Bitmap.h>
  18. #include <LibGfx/Painter.h>
  19. #include <LibGfx/Vector4.h>
  20. #include <LibSoftGPU/Device.h>
  21. #include <LibSoftGPU/Enums.h>
  22. #include <LibSoftGPU/ImageFormat.h>
  23. __attribute__((visibility("hidden"))) GL::GLContext* g_gl_context;
  24. namespace GL {
  25. static constexpr size_t MODELVIEW_MATRIX_STACK_LIMIT = 64;
  26. static constexpr size_t PROJECTION_MATRIX_STACK_LIMIT = 8;
  27. static constexpr size_t TEXTURE_MATRIX_STACK_LIMIT = 8;
  28. #define APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(name, ...) \
  29. if (should_append_to_listing()) { \
  30. append_to_listing<&GLContext::name>(__VA_ARGS__); \
  31. if (!should_execute_after_appending_to_listing()) \
  32. return; \
  33. }
  34. #define APPEND_TO_CALL_LIST_WITH_ARG_AND_RETURN_IF_NEEDED(name, arg) \
  35. if (should_append_to_listing()) { \
  36. auto ptr = store_in_listing(arg); \
  37. append_to_listing<&GLContext::name>(*ptr); \
  38. if (!should_execute_after_appending_to_listing()) \
  39. return; \
  40. }
  41. #define RETURN_WITH_ERROR_IF(condition, error) \
  42. if (condition) { \
  43. dbgln_if(GL_DEBUG, "{}(): error {:#x}", __func__, error); \
  44. if (m_error == GL_NO_ERROR) \
  45. m_error = error; \
  46. return; \
  47. }
  48. #define RETURN_VALUE_WITH_ERROR_IF(condition, error, return_value) \
  49. if (condition) { \
  50. dbgln_if(GL_DEBUG, "{}(): error {:#x}", __func__, error); \
  51. if (m_error == GL_NO_ERROR) \
  52. m_error = error; \
  53. return return_value; \
  54. }
  55. GLContext::GLContext(Gfx::Bitmap& frontbuffer)
  56. : m_viewport(frontbuffer.rect())
  57. , m_frontbuffer(frontbuffer)
  58. , m_rasterizer(frontbuffer.size())
  59. , m_device_info(m_rasterizer.info())
  60. {
  61. m_texture_units.resize(m_device_info.num_texture_units);
  62. m_active_texture_unit = &m_texture_units[0];
  63. // All texture units are initialized with default textures for all targets; these
  64. // can be referenced later on with texture name 0 in operations like glBindTexture().
  65. auto default_texture_2d = adopt_ref(*new Texture2D());
  66. m_default_textures.set(GL_TEXTURE_2D, default_texture_2d);
  67. for (auto& texture_unit : m_texture_units)
  68. texture_unit.set_texture_2d_target_texture(default_texture_2d);
  69. // Query the number lights from the device and set set up their state
  70. // locally in the GL
  71. m_light_states.resize(m_device_info.num_lights);
  72. // Set-up light0's state, as it has a different default state
  73. // to the other lights, as per the OpenGL 1.5 spec
  74. auto& light0 = m_light_states.at(0);
  75. light0.diffuse_intensity = { 1.0f, 1.0f, 1.0f, 1.0f };
  76. light0.specular_intensity = { 1.0f, 1.0f, 1.0f, 1.0f };
  77. m_light_state_is_dirty = true;
  78. m_client_side_texture_coord_array_enabled.resize(m_device_info.num_texture_units);
  79. m_client_tex_coord_pointer.resize(m_device_info.num_texture_units);
  80. m_current_vertex_tex_coord.resize(m_device_info.num_texture_units);
  81. for (auto& tex_coord : m_current_vertex_tex_coord)
  82. tex_coord = { 0.0f, 0.0f, 0.0f, 1.0f };
  83. // Initialize the texture coordinate generation coefficients
  84. // Indices 0,1,2,3 refer to the S,T,R and Q coordinate of the respective texture
  85. // coordinate generation config.
  86. m_texture_coordinate_generation.resize(m_device_info.num_texture_units);
  87. for (auto& texture_coordinate_generation : m_texture_coordinate_generation) {
  88. texture_coordinate_generation[0].object_plane_coefficients = { 1.0f, 0.0f, 0.0f, 0.0f };
  89. texture_coordinate_generation[0].eye_plane_coefficients = { 1.0f, 0.0f, 0.0f, 0.0f };
  90. texture_coordinate_generation[1].object_plane_coefficients = { 0.0f, 1.0f, 0.0f, 0.0f };
  91. texture_coordinate_generation[1].eye_plane_coefficients = { 0.0f, 1.0f, 0.0f, 0.0f };
  92. texture_coordinate_generation[2].object_plane_coefficients = { 0.0f, 0.0f, 0.0f, 0.0f };
  93. texture_coordinate_generation[2].eye_plane_coefficients = { 0.0f, 0.0f, 0.0f, 0.0f };
  94. texture_coordinate_generation[3].object_plane_coefficients = { 0.0f, 0.0f, 0.0f, 0.0f };
  95. texture_coordinate_generation[3].eye_plane_coefficients = { 0.0f, 0.0f, 0.0f, 0.0f };
  96. }
  97. build_extension_string();
  98. }
  99. GLContext::~GLContext()
  100. {
  101. dbgln_if(GL_DEBUG, "GLContext::~GLContext() {:p}", this);
  102. if (g_gl_context == this)
  103. make_context_current(nullptr);
  104. }
  105. Optional<ContextParameter> GLContext::get_context_parameter(GLenum name)
  106. {
  107. switch (name) {
  108. case GL_ALPHA_BITS:
  109. return ContextParameter { .type = GL_INT, .value = { .integer_value = sizeof(float) * 8 } };
  110. case GL_ALPHA_TEST:
  111. return ContextParameter { .type = GL_BOOL, .is_capability = true, .value = { .boolean_value = m_alpha_test_enabled } };
  112. case GL_BLEND:
  113. return ContextParameter { .type = GL_BOOL, .is_capability = true, .value = { .boolean_value = m_blend_enabled } };
  114. case GL_BLEND_DST_ALPHA:
  115. return ContextParameter { .type = GL_INT, .value = { .integer_value = static_cast<GLint>(m_blend_destination_factor) } };
  116. case GL_BLEND_SRC_ALPHA:
  117. return ContextParameter { .type = GL_INT, .value = { .integer_value = static_cast<GLint>(m_blend_source_factor) } };
  118. case GL_BLUE_BITS:
  119. return ContextParameter { .type = GL_INT, .value = { .integer_value = sizeof(float) * 8 } };
  120. case GL_COLOR_MATERIAL:
  121. return ContextParameter { .type = GL_BOOL, .is_capability = true, .value = { .boolean_value = m_color_material_enabled } };
  122. case GL_COLOR_MATERIAL_FACE:
  123. return ContextParameter { .type = GL_INT, .value = { .integer_value = static_cast<GLint>(m_color_material_face) } };
  124. case GL_COLOR_MATERIAL_MODE:
  125. return ContextParameter { .type = GL_INT, .value = { .integer_value = static_cast<GLint>(m_color_material_mode) } };
  126. case GL_CULL_FACE:
  127. return ContextParameter { .type = GL_BOOL, .is_capability = true, .value = { .boolean_value = m_cull_faces } };
  128. case GL_DEPTH_BITS:
  129. return ContextParameter { .type = GL_INT, .value = { .integer_value = sizeof(float) * 8 } };
  130. case GL_DEPTH_TEST:
  131. return ContextParameter { .type = GL_BOOL, .is_capability = true, .value = { .boolean_value = m_depth_test_enabled } };
  132. case GL_DITHER:
  133. return ContextParameter { .type = GL_BOOL, .is_capability = true, .value = { .boolean_value = m_dither_enabled } };
  134. case GL_DOUBLEBUFFER:
  135. return ContextParameter { .type = GL_BOOL, .value = { .boolean_value = true } };
  136. case GL_FOG: {
  137. auto fog_enabled = m_rasterizer.options().fog_enabled;
  138. return ContextParameter { .type = GL_BOOL, .is_capability = true, .value = { .boolean_value = fog_enabled } };
  139. }
  140. case GL_GREEN_BITS:
  141. return ContextParameter { .type = GL_INT, .value = { .integer_value = sizeof(float) * 8 } };
  142. case GL_LIGHTING:
  143. return ContextParameter { .type = GL_BOOL, .is_capability = true, .value = { .boolean_value = m_lighting_enabled } };
  144. case GL_MAX_LIGHTS:
  145. return ContextParameter { .type = GL_INT, .value = { .integer_value = static_cast<GLint>(m_device_info.num_lights) } };
  146. case GL_MAX_MODELVIEW_STACK_DEPTH:
  147. return ContextParameter { .type = GL_INT, .value = { .integer_value = MODELVIEW_MATRIX_STACK_LIMIT } };
  148. case GL_MAX_PROJECTION_STACK_DEPTH:
  149. return ContextParameter { .type = GL_INT, .value = { .integer_value = PROJECTION_MATRIX_STACK_LIMIT } };
  150. case GL_MAX_TEXTURE_SIZE:
  151. return ContextParameter { .type = GL_INT, .value = { .integer_value = 4096 } };
  152. case GL_MAX_TEXTURE_STACK_DEPTH:
  153. return ContextParameter { .type = GL_INT, .value = { .integer_value = TEXTURE_MATRIX_STACK_LIMIT } };
  154. case GL_MAX_TEXTURE_UNITS:
  155. return ContextParameter { .type = GL_INT, .value = { .integer_value = static_cast<GLint>(m_texture_units.size()) } };
  156. case GL_NORMALIZE:
  157. return ContextParameter { .type = GL_BOOL, .is_capability = true, .value = { .boolean_value = m_normalize } };
  158. case GL_PACK_ALIGNMENT:
  159. return ContextParameter { .type = GL_INT, .value = { .integer_value = m_pack_alignment } };
  160. case GL_PACK_IMAGE_HEIGHT:
  161. return ContextParameter { .type = GL_BOOL, .value = { .integer_value = 0 } };
  162. case GL_PACK_LSB_FIRST:
  163. return ContextParameter { .type = GL_BOOL, .value = { .boolean_value = false } };
  164. case GL_PACK_ROW_LENGTH:
  165. return ContextParameter { .type = GL_INT, .value = { .integer_value = 0 } };
  166. case GL_PACK_SKIP_PIXELS:
  167. return ContextParameter { .type = GL_INT, .value = { .integer_value = 0 } };
  168. case GL_PACK_SKIP_ROWS:
  169. return ContextParameter { .type = GL_INT, .value = { .integer_value = 0 } };
  170. case GL_PACK_SWAP_BYTES:
  171. return ContextParameter { .type = GL_BOOL, .value = { .boolean_value = false } };
  172. case GL_POLYGON_OFFSET_FILL:
  173. return ContextParameter { .type = GL_BOOL, .is_capability = true, .value = { .boolean_value = m_depth_offset_enabled } };
  174. case GL_RED_BITS:
  175. return ContextParameter { .type = GL_INT, .value = { .integer_value = sizeof(float) * 8 } };
  176. case GL_SCISSOR_BOX: {
  177. auto scissor_box = m_rasterizer.options().scissor_box;
  178. return ContextParameter {
  179. .type = GL_INT,
  180. .count = 4,
  181. .value = {
  182. .integer_list = {
  183. scissor_box.x(),
  184. scissor_box.y(),
  185. scissor_box.width(),
  186. scissor_box.height(),
  187. } }
  188. };
  189. } break;
  190. case GL_SCISSOR_TEST: {
  191. auto scissor_enabled = m_rasterizer.options().scissor_enabled;
  192. return ContextParameter { .type = GL_BOOL, .is_capability = true, .value = { .boolean_value = scissor_enabled } };
  193. }
  194. case GL_STENCIL_BITS:
  195. return ContextParameter { .type = GL_INT, .value = { .integer_value = m_device_info.stencil_bits } };
  196. case GL_STENCIL_CLEAR_VALUE:
  197. return ContextParameter { .type = GL_INT, .value = { .integer_value = m_clear_stencil } };
  198. case GL_STENCIL_TEST:
  199. return ContextParameter { .type = GL_BOOL, .is_capability = true, .value = { .boolean_value = m_stencil_test_enabled } };
  200. case GL_TEXTURE_1D:
  201. return ContextParameter { .type = GL_BOOL, .value = { .boolean_value = m_active_texture_unit->texture_1d_enabled() } };
  202. case GL_TEXTURE_2D:
  203. return ContextParameter { .type = GL_BOOL, .value = { .boolean_value = m_active_texture_unit->texture_2d_enabled() } };
  204. case GL_TEXTURE_3D:
  205. return ContextParameter { .type = GL_BOOL, .value = { .boolean_value = m_active_texture_unit->texture_3d_enabled() } };
  206. case GL_TEXTURE_CUBE_MAP:
  207. return ContextParameter { .type = GL_BOOL, .value = { .boolean_value = m_active_texture_unit->texture_cube_map_enabled() } };
  208. case GL_TEXTURE_GEN_Q:
  209. case GL_TEXTURE_GEN_R:
  210. case GL_TEXTURE_GEN_S:
  211. case GL_TEXTURE_GEN_T: {
  212. auto generation_enabled = texture_coordinate_generation(m_active_texture_unit_index, name).enabled;
  213. return ContextParameter { .type = GL_BOOL, .is_capability = true, .value = { .boolean_value = generation_enabled } };
  214. }
  215. case GL_UNPACK_ALIGNMENT:
  216. return ContextParameter { .type = GL_INT, .value = { .integer_value = m_unpack_alignment } };
  217. case GL_UNPACK_IMAGE_HEIGHT:
  218. return ContextParameter { .type = GL_BOOL, .value = { .integer_value = 0 } };
  219. case GL_UNPACK_LSB_FIRST:
  220. return ContextParameter { .type = GL_BOOL, .value = { .boolean_value = false } };
  221. case GL_UNPACK_ROW_LENGTH:
  222. return ContextParameter { .type = GL_INT, .value = { .integer_value = m_unpack_row_length } };
  223. case GL_UNPACK_SKIP_PIXELS:
  224. return ContextParameter { .type = GL_INT, .value = { .integer_value = 0 } };
  225. case GL_UNPACK_SKIP_ROWS:
  226. return ContextParameter { .type = GL_INT, .value = { .integer_value = 0 } };
  227. case GL_UNPACK_SWAP_BYTES:
  228. return ContextParameter { .type = GL_BOOL, .value = { .boolean_value = false } };
  229. case GL_VIEWPORT:
  230. return ContextParameter {
  231. .type = GL_INT,
  232. .count = 4,
  233. .value = {
  234. .integer_list = {
  235. m_viewport.x(),
  236. m_viewport.y(),
  237. m_viewport.width(),
  238. m_viewport.height(),
  239. } }
  240. };
  241. default:
  242. dbgln_if(GL_DEBUG, "get_context_parameter({:#x}): unknown context parameter", name);
  243. return {};
  244. }
  245. }
  246. void GLContext::gl_begin(GLenum mode)
  247. {
  248. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_begin, mode);
  249. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  250. RETURN_WITH_ERROR_IF(mode > GL_POLYGON, GL_INVALID_ENUM);
  251. m_current_draw_mode = mode;
  252. m_in_draw_state = true; // Certain commands will now generate an error
  253. }
  254. void GLContext::gl_clear(GLbitfield mask)
  255. {
  256. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_clear, mask);
  257. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  258. RETURN_WITH_ERROR_IF(mask & ~(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT), GL_INVALID_ENUM);
  259. if (mask & GL_COLOR_BUFFER_BIT)
  260. m_rasterizer.clear_color(m_clear_color);
  261. if (mask & GL_DEPTH_BUFFER_BIT)
  262. m_rasterizer.clear_depth(m_clear_depth);
  263. if (mask & GL_STENCIL_BUFFER_BIT)
  264. m_rasterizer.clear_stencil(m_clear_stencil);
  265. }
  266. void GLContext::gl_clear_color(GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha)
  267. {
  268. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_clear_color, red, green, blue, alpha);
  269. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  270. m_clear_color = { red, green, blue, alpha };
  271. m_clear_color.clamp(0.f, 1.f);
  272. }
  273. void GLContext::gl_clear_depth(GLdouble depth)
  274. {
  275. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_clear_depth, depth);
  276. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  277. m_clear_depth = clamp(static_cast<float>(depth), 0.f, 1.f);
  278. }
  279. void GLContext::gl_clear_stencil(GLint s)
  280. {
  281. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_clear_stencil, s);
  282. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  283. m_clear_stencil = static_cast<u8>(s & ((1 << m_device_info.stencil_bits) - 1));
  284. }
  285. void GLContext::gl_color(GLdouble r, GLdouble g, GLdouble b, GLdouble a)
  286. {
  287. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_color, r, g, b, a);
  288. m_current_vertex_color = {
  289. static_cast<float>(r),
  290. static_cast<float>(g),
  291. static_cast<float>(b),
  292. static_cast<float>(a),
  293. };
  294. }
  295. void GLContext::gl_end()
  296. {
  297. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_end);
  298. // Make sure we had a `glBegin` before this call...
  299. RETURN_WITH_ERROR_IF(!m_in_draw_state, GL_INVALID_OPERATION);
  300. m_in_draw_state = false;
  301. // FIXME: Add support for the remaining primitive types.
  302. if (m_current_draw_mode != GL_TRIANGLES
  303. && m_current_draw_mode != GL_TRIANGLE_FAN
  304. && m_current_draw_mode != GL_TRIANGLE_STRIP
  305. && m_current_draw_mode != GL_QUADS
  306. && m_current_draw_mode != GL_QUAD_STRIP
  307. && m_current_draw_mode != GL_POLYGON) {
  308. m_vertex_list.clear_with_capacity();
  309. dbgln_if(GL_DEBUG, "gl_end(): draw mode {:#x} unsupported", m_current_draw_mode);
  310. RETURN_WITH_ERROR_IF(true, GL_INVALID_ENUM);
  311. }
  312. Vector<size_t, 32> enabled_texture_units;
  313. for (size_t i = 0; i < m_texture_units.size(); ++i) {
  314. if (m_texture_units[i].texture_2d_enabled())
  315. enabled_texture_units.append(i);
  316. }
  317. sync_device_config();
  318. SoftGPU::PrimitiveType primitive_type;
  319. switch (m_current_draw_mode) {
  320. case GL_TRIANGLES:
  321. primitive_type = SoftGPU::PrimitiveType::Triangles;
  322. break;
  323. case GL_TRIANGLE_STRIP:
  324. case GL_QUAD_STRIP:
  325. primitive_type = SoftGPU::PrimitiveType::TriangleStrip;
  326. break;
  327. case GL_TRIANGLE_FAN:
  328. case GL_POLYGON:
  329. primitive_type = SoftGPU::PrimitiveType::TriangleFan;
  330. break;
  331. case GL_QUADS:
  332. primitive_type = SoftGPU::PrimitiveType::Quads;
  333. break;
  334. default:
  335. VERIFY_NOT_REACHED();
  336. }
  337. // Set up normals transform by taking the upper left 3x3 elements from the model view matrix
  338. // See section 2.11.3 of the OpenGL 1.5 spec
  339. auto const& mv_elements = m_model_view_matrix.elements();
  340. auto const model_view_transposed = FloatMatrix3x3(
  341. mv_elements[0][0], mv_elements[1][0], mv_elements[2][0],
  342. mv_elements[0][1], mv_elements[1][1], mv_elements[2][1],
  343. mv_elements[0][2], mv_elements[1][2], mv_elements[2][2]);
  344. auto const& normal_transform = model_view_transposed.inverse();
  345. m_rasterizer.draw_primitives(primitive_type, m_model_view_matrix, normal_transform, m_projection_matrix, m_texture_matrix, m_vertex_list, enabled_texture_units);
  346. m_vertex_list.clear_with_capacity();
  347. }
  348. void GLContext::gl_frustum(GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble near_val, GLdouble far_val)
  349. {
  350. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_frustum, left, right, bottom, top, near_val, far_val);
  351. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  352. RETURN_WITH_ERROR_IF(near_val < 0 || far_val < 0, GL_INVALID_VALUE);
  353. RETURN_WITH_ERROR_IF(left == right || bottom == top || near_val == far_val, GL_INVALID_VALUE);
  354. // Let's do some math!
  355. auto a = static_cast<float>((right + left) / (right - left));
  356. auto b = static_cast<float>((top + bottom) / (top - bottom));
  357. auto c = static_cast<float>(-((far_val + near_val) / (far_val - near_val)));
  358. auto d = static_cast<float>(-((2 * far_val * near_val) / (far_val - near_val)));
  359. FloatMatrix4x4 frustum {
  360. static_cast<float>(2 * near_val / (right - left)), 0, a, 0,
  361. 0, static_cast<float>(2 * near_val / (top - bottom)), b, 0,
  362. 0, 0, c, d,
  363. 0, 0, -1, 0
  364. };
  365. if (m_current_matrix_mode == GL_PROJECTION)
  366. m_projection_matrix = m_projection_matrix * frustum;
  367. else if (m_current_matrix_mode == GL_MODELVIEW)
  368. m_model_view_matrix = m_model_view_matrix * frustum;
  369. else if (m_current_matrix_mode == GL_TEXTURE)
  370. m_texture_matrix = m_texture_matrix * frustum;
  371. else
  372. VERIFY_NOT_REACHED();
  373. }
  374. void GLContext::gl_ortho(GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble near_val, GLdouble far_val)
  375. {
  376. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_ortho, left, right, bottom, top, near_val, far_val);
  377. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  378. RETURN_WITH_ERROR_IF(left == right || bottom == top || near_val == far_val, GL_INVALID_VALUE);
  379. auto rl = right - left;
  380. auto tb = top - bottom;
  381. auto fn = far_val - near_val;
  382. auto tx = -(right + left) / rl;
  383. auto ty = -(top + bottom) / tb;
  384. auto tz = -(far_val + near_val) / fn;
  385. FloatMatrix4x4 projection {
  386. static_cast<float>(2 / rl), 0, 0, static_cast<float>(tx),
  387. 0, static_cast<float>(2 / tb), 0, static_cast<float>(ty),
  388. 0, 0, static_cast<float>(-2 / fn), static_cast<float>(tz),
  389. 0, 0, 0, 1
  390. };
  391. if (m_current_matrix_mode == GL_PROJECTION)
  392. m_projection_matrix = m_projection_matrix * projection;
  393. else if (m_current_matrix_mode == GL_MODELVIEW)
  394. m_model_view_matrix = m_model_view_matrix * projection;
  395. else if (m_current_matrix_mode == GL_TEXTURE)
  396. m_texture_matrix = m_texture_matrix * projection;
  397. else
  398. VERIFY_NOT_REACHED();
  399. }
  400. GLenum GLContext::gl_get_error()
  401. {
  402. if (m_in_draw_state)
  403. return GL_INVALID_OPERATION;
  404. auto last_error = m_error;
  405. m_error = GL_NO_ERROR;
  406. return last_error;
  407. }
  408. GLubyte* GLContext::gl_get_string(GLenum name)
  409. {
  410. RETURN_VALUE_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION, nullptr);
  411. switch (name) {
  412. case GL_VENDOR:
  413. return reinterpret_cast<GLubyte*>(const_cast<char*>(m_device_info.vendor_name.characters()));
  414. case GL_RENDERER:
  415. return reinterpret_cast<GLubyte*>(const_cast<char*>(m_device_info.device_name.characters()));
  416. case GL_VERSION:
  417. return reinterpret_cast<GLubyte*>(const_cast<char*>("1.5"));
  418. case GL_EXTENSIONS:
  419. return reinterpret_cast<GLubyte*>(const_cast<char*>(m_extensions.characters()));
  420. case GL_SHADING_LANGUAGE_VERSION:
  421. return reinterpret_cast<GLubyte*>(const_cast<char*>("0.0"));
  422. default:
  423. dbgln_if(GL_DEBUG, "gl_get_string({:#x}): unknown name", name);
  424. break;
  425. }
  426. RETURN_VALUE_WITH_ERROR_IF(true, GL_INVALID_ENUM, nullptr);
  427. }
  428. void GLContext::gl_load_identity()
  429. {
  430. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_load_identity);
  431. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  432. if (m_current_matrix_mode == GL_PROJECTION)
  433. m_projection_matrix = FloatMatrix4x4::identity();
  434. else if (m_current_matrix_mode == GL_MODELVIEW)
  435. m_model_view_matrix = FloatMatrix4x4::identity();
  436. else if (m_current_matrix_mode == GL_TEXTURE)
  437. m_texture_matrix = FloatMatrix4x4::identity();
  438. else
  439. VERIFY_NOT_REACHED();
  440. }
  441. void GLContext::gl_load_matrix(const FloatMatrix4x4& matrix)
  442. {
  443. APPEND_TO_CALL_LIST_WITH_ARG_AND_RETURN_IF_NEEDED(gl_load_matrix, matrix);
  444. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  445. if (m_current_matrix_mode == GL_PROJECTION)
  446. m_projection_matrix = matrix;
  447. else if (m_current_matrix_mode == GL_MODELVIEW)
  448. m_model_view_matrix = matrix;
  449. else if (m_current_matrix_mode == GL_TEXTURE)
  450. m_texture_matrix = matrix;
  451. else
  452. VERIFY_NOT_REACHED();
  453. }
  454. void GLContext::gl_matrix_mode(GLenum mode)
  455. {
  456. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_matrix_mode, mode);
  457. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  458. RETURN_WITH_ERROR_IF(mode < GL_MODELVIEW || mode > GL_TEXTURE, GL_INVALID_ENUM);
  459. m_current_matrix_mode = mode;
  460. }
  461. void GLContext::gl_push_matrix()
  462. {
  463. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_push_matrix);
  464. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  465. switch (m_current_matrix_mode) {
  466. case GL_PROJECTION:
  467. RETURN_WITH_ERROR_IF(m_projection_matrix_stack.size() >= PROJECTION_MATRIX_STACK_LIMIT, GL_STACK_OVERFLOW);
  468. m_projection_matrix_stack.append(m_projection_matrix);
  469. break;
  470. case GL_MODELVIEW:
  471. RETURN_WITH_ERROR_IF(m_model_view_matrix_stack.size() >= MODELVIEW_MATRIX_STACK_LIMIT, GL_STACK_OVERFLOW);
  472. m_model_view_matrix_stack.append(m_model_view_matrix);
  473. break;
  474. case GL_TEXTURE:
  475. RETURN_WITH_ERROR_IF(m_texture_matrix_stack.size() >= TEXTURE_MATRIX_STACK_LIMIT, GL_STACK_OVERFLOW);
  476. m_texture_matrix_stack.append(m_texture_matrix);
  477. break;
  478. default:
  479. VERIFY_NOT_REACHED();
  480. }
  481. }
  482. void GLContext::gl_pop_matrix()
  483. {
  484. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_pop_matrix);
  485. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  486. switch (m_current_matrix_mode) {
  487. case GL_PROJECTION:
  488. RETURN_WITH_ERROR_IF(m_projection_matrix_stack.size() == 0, GL_STACK_UNDERFLOW);
  489. m_projection_matrix = m_projection_matrix_stack.take_last();
  490. break;
  491. case GL_MODELVIEW:
  492. RETURN_WITH_ERROR_IF(m_model_view_matrix_stack.size() == 0, GL_STACK_UNDERFLOW);
  493. m_model_view_matrix = m_model_view_matrix_stack.take_last();
  494. break;
  495. case GL_TEXTURE:
  496. RETURN_WITH_ERROR_IF(m_texture_matrix_stack.size() == 0, GL_STACK_UNDERFLOW);
  497. m_texture_matrix = m_texture_matrix_stack.take_last();
  498. break;
  499. default:
  500. VERIFY_NOT_REACHED();
  501. }
  502. }
  503. void GLContext::gl_mult_matrix(FloatMatrix4x4 const& matrix)
  504. {
  505. APPEND_TO_CALL_LIST_WITH_ARG_AND_RETURN_IF_NEEDED(gl_mult_matrix, matrix);
  506. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  507. if (m_current_matrix_mode == GL_MODELVIEW)
  508. m_model_view_matrix = m_model_view_matrix * matrix;
  509. else if (m_current_matrix_mode == GL_PROJECTION)
  510. m_projection_matrix = m_projection_matrix * matrix;
  511. else if (m_current_matrix_mode == GL_TEXTURE)
  512. m_texture_matrix = m_texture_matrix * matrix;
  513. else
  514. VERIFY_NOT_REACHED();
  515. }
  516. void GLContext::gl_rotate(GLfloat angle, GLfloat x, GLfloat y, GLfloat z)
  517. {
  518. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_rotate, angle, x, y, z);
  519. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  520. FloatVector3 axis = { x, y, z };
  521. if (axis.length() > 0.f)
  522. axis.normalize();
  523. auto rotation_mat = Gfx::rotation_matrix(axis, angle * static_cast<float>(M_PI * 2 / 360));
  524. if (m_current_matrix_mode == GL_MODELVIEW)
  525. m_model_view_matrix = m_model_view_matrix * rotation_mat;
  526. else if (m_current_matrix_mode == GL_PROJECTION)
  527. m_projection_matrix = m_projection_matrix * rotation_mat;
  528. else if (m_current_matrix_mode == GL_TEXTURE)
  529. m_texture_matrix = m_texture_matrix * rotation_mat;
  530. else
  531. VERIFY_NOT_REACHED();
  532. }
  533. void GLContext::gl_scale(GLdouble x, GLdouble y, GLdouble z)
  534. {
  535. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_scale, x, y, z);
  536. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  537. auto scale_matrix = Gfx::scale_matrix(FloatVector3 { static_cast<float>(x), static_cast<float>(y), static_cast<float>(z) });
  538. if (m_current_matrix_mode == GL_MODELVIEW)
  539. m_model_view_matrix = m_model_view_matrix * scale_matrix;
  540. else if (m_current_matrix_mode == GL_PROJECTION)
  541. m_projection_matrix = m_projection_matrix * scale_matrix;
  542. else if (m_current_matrix_mode == GL_TEXTURE)
  543. m_texture_matrix = m_texture_matrix * scale_matrix;
  544. else
  545. VERIFY_NOT_REACHED();
  546. }
  547. void GLContext::gl_translate(GLdouble x, GLdouble y, GLdouble z)
  548. {
  549. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_translate, x, y, z);
  550. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  551. auto translation_matrix = Gfx::translation_matrix(FloatVector3 { static_cast<float>(x), static_cast<float>(y), static_cast<float>(z) });
  552. if (m_current_matrix_mode == GL_MODELVIEW)
  553. m_model_view_matrix = m_model_view_matrix * translation_matrix;
  554. else if (m_current_matrix_mode == GL_PROJECTION)
  555. m_projection_matrix = m_projection_matrix * translation_matrix;
  556. else if (m_current_matrix_mode == GL_TEXTURE)
  557. m_texture_matrix = m_texture_matrix * translation_matrix;
  558. else
  559. VERIFY_NOT_REACHED();
  560. }
  561. void GLContext::gl_vertex(GLdouble x, GLdouble y, GLdouble z, GLdouble w)
  562. {
  563. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_vertex, x, y, z, w);
  564. SoftGPU::Vertex vertex;
  565. vertex.position = { static_cast<float>(x), static_cast<float>(y), static_cast<float>(z), static_cast<float>(w) };
  566. vertex.color = m_current_vertex_color;
  567. for (size_t i = 0; i < m_device_info.num_texture_units; ++i)
  568. vertex.tex_coords[i] = m_current_vertex_tex_coord[i];
  569. vertex.normal = m_current_vertex_normal;
  570. m_vertex_list.append(vertex);
  571. }
  572. void GLContext::gl_tex_coord(GLfloat s, GLfloat t, GLfloat r, GLfloat q)
  573. {
  574. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_tex_coord, s, t, r, q);
  575. m_current_vertex_tex_coord[0] = { s, t, r, q };
  576. }
  577. void GLContext::gl_multi_tex_coord(GLenum target, GLfloat s, GLfloat t, GLfloat r, GLfloat q)
  578. {
  579. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_multi_tex_coord, target, s, t, r, q);
  580. RETURN_WITH_ERROR_IF(target < GL_TEXTURE0 || target >= GL_TEXTURE0 + m_device_info.num_texture_units, GL_INVALID_ENUM);
  581. m_current_vertex_tex_coord[target - GL_TEXTURE0] = { s, t, r, q };
  582. }
  583. void GLContext::gl_viewport(GLint x, GLint y, GLsizei width, GLsizei height)
  584. {
  585. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_viewport, x, y, width, height);
  586. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  587. RETURN_WITH_ERROR_IF(width < 0 || height < 0, GL_INVALID_VALUE);
  588. m_viewport = { x, y, width, height };
  589. auto rasterizer_options = m_rasterizer.options();
  590. rasterizer_options.viewport = m_viewport;
  591. m_rasterizer.set_options(rasterizer_options);
  592. }
  593. void GLContext::gl_enable(GLenum capability)
  594. {
  595. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_enable, capability);
  596. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  597. auto rasterizer_options = m_rasterizer.options();
  598. bool update_rasterizer_options = false;
  599. switch (capability) {
  600. case GL_COLOR_MATERIAL:
  601. m_color_material_enabled = true;
  602. break;
  603. case GL_CULL_FACE:
  604. m_cull_faces = true;
  605. rasterizer_options.enable_culling = true;
  606. update_rasterizer_options = true;
  607. break;
  608. case GL_DEPTH_TEST:
  609. m_depth_test_enabled = true;
  610. rasterizer_options.enable_depth_test = true;
  611. update_rasterizer_options = true;
  612. break;
  613. case GL_BLEND:
  614. m_blend_enabled = true;
  615. rasterizer_options.enable_blending = true;
  616. update_rasterizer_options = true;
  617. break;
  618. case GL_ALPHA_TEST:
  619. m_alpha_test_enabled = true;
  620. rasterizer_options.enable_alpha_test = true;
  621. update_rasterizer_options = true;
  622. break;
  623. case GL_DITHER:
  624. m_dither_enabled = true;
  625. break;
  626. case GL_FOG:
  627. rasterizer_options.fog_enabled = true;
  628. update_rasterizer_options = true;
  629. break;
  630. case GL_LIGHTING:
  631. m_lighting_enabled = true;
  632. rasterizer_options.lighting_enabled = true;
  633. update_rasterizer_options = true;
  634. break;
  635. case GL_NORMALIZE:
  636. m_normalize = true;
  637. rasterizer_options.normalization_enabled = true;
  638. update_rasterizer_options = true;
  639. break;
  640. case GL_POLYGON_OFFSET_FILL:
  641. m_depth_offset_enabled = true;
  642. rasterizer_options.depth_offset_enabled = true;
  643. update_rasterizer_options = true;
  644. break;
  645. case GL_SCISSOR_TEST:
  646. rasterizer_options.scissor_enabled = true;
  647. update_rasterizer_options = true;
  648. break;
  649. case GL_STENCIL_TEST:
  650. m_stencil_test_enabled = true;
  651. rasterizer_options.enable_stencil_test = true;
  652. update_rasterizer_options = true;
  653. break;
  654. case GL_TEXTURE_1D:
  655. m_active_texture_unit->set_texture_1d_enabled(true);
  656. m_sampler_config_is_dirty = true;
  657. break;
  658. case GL_TEXTURE_2D:
  659. m_active_texture_unit->set_texture_2d_enabled(true);
  660. m_sampler_config_is_dirty = true;
  661. break;
  662. case GL_TEXTURE_3D:
  663. m_active_texture_unit->set_texture_3d_enabled(true);
  664. m_sampler_config_is_dirty = true;
  665. break;
  666. case GL_TEXTURE_CUBE_MAP:
  667. m_active_texture_unit->set_texture_cube_map_enabled(true);
  668. m_sampler_config_is_dirty = true;
  669. break;
  670. case GL_LIGHT0:
  671. case GL_LIGHT1:
  672. case GL_LIGHT2:
  673. case GL_LIGHT3:
  674. case GL_LIGHT4:
  675. case GL_LIGHT5:
  676. case GL_LIGHT6:
  677. case GL_LIGHT7:
  678. m_light_states.at(capability - GL_LIGHT0).is_enabled = true;
  679. m_light_state_is_dirty = true;
  680. break;
  681. case GL_TEXTURE_GEN_Q:
  682. case GL_TEXTURE_GEN_R:
  683. case GL_TEXTURE_GEN_S:
  684. case GL_TEXTURE_GEN_T:
  685. texture_coordinate_generation(m_active_texture_unit_index, capability).enabled = true;
  686. m_texcoord_generation_dirty = true;
  687. break;
  688. default:
  689. dbgln_if(GL_DEBUG, "gl_enable({:#x}): unknown parameter", capability);
  690. RETURN_WITH_ERROR_IF(true, GL_INVALID_ENUM);
  691. }
  692. if (update_rasterizer_options)
  693. m_rasterizer.set_options(rasterizer_options);
  694. }
  695. void GLContext::gl_disable(GLenum capability)
  696. {
  697. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_disable, capability);
  698. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  699. auto rasterizer_options = m_rasterizer.options();
  700. bool update_rasterizer_options = false;
  701. switch (capability) {
  702. case GL_COLOR_MATERIAL:
  703. m_color_material_enabled = false;
  704. break;
  705. case GL_CULL_FACE:
  706. m_cull_faces = false;
  707. rasterizer_options.enable_culling = false;
  708. update_rasterizer_options = true;
  709. break;
  710. case GL_DEPTH_TEST:
  711. m_depth_test_enabled = false;
  712. rasterizer_options.enable_depth_test = false;
  713. update_rasterizer_options = true;
  714. break;
  715. case GL_BLEND:
  716. m_blend_enabled = false;
  717. rasterizer_options.enable_blending = false;
  718. update_rasterizer_options = true;
  719. break;
  720. case GL_ALPHA_TEST:
  721. m_alpha_test_enabled = false;
  722. rasterizer_options.enable_alpha_test = false;
  723. update_rasterizer_options = true;
  724. break;
  725. case GL_DITHER:
  726. m_dither_enabled = false;
  727. break;
  728. case GL_FOG:
  729. rasterizer_options.fog_enabled = false;
  730. update_rasterizer_options = true;
  731. break;
  732. case GL_LIGHTING:
  733. m_lighting_enabled = false;
  734. rasterizer_options.lighting_enabled = false;
  735. update_rasterizer_options = true;
  736. break;
  737. case GL_LIGHT0:
  738. case GL_LIGHT1:
  739. case GL_LIGHT2:
  740. case GL_LIGHT3:
  741. case GL_LIGHT4:
  742. case GL_LIGHT5:
  743. case GL_LIGHT6:
  744. case GL_LIGHT7:
  745. m_light_states.at(capability - GL_LIGHT0).is_enabled = false;
  746. m_light_state_is_dirty = true;
  747. break;
  748. case GL_NORMALIZE:
  749. m_normalize = false;
  750. rasterizer_options.normalization_enabled = false;
  751. update_rasterizer_options = true;
  752. break;
  753. case GL_POLYGON_OFFSET_FILL:
  754. m_depth_offset_enabled = false;
  755. rasterizer_options.depth_offset_enabled = false;
  756. update_rasterizer_options = true;
  757. break;
  758. case GL_SCISSOR_TEST:
  759. rasterizer_options.scissor_enabled = false;
  760. update_rasterizer_options = true;
  761. break;
  762. case GL_STENCIL_TEST:
  763. m_stencil_test_enabled = false;
  764. rasterizer_options.enable_stencil_test = false;
  765. update_rasterizer_options = true;
  766. break;
  767. case GL_TEXTURE_1D:
  768. m_active_texture_unit->set_texture_1d_enabled(false);
  769. m_sampler_config_is_dirty = true;
  770. break;
  771. case GL_TEXTURE_2D:
  772. m_active_texture_unit->set_texture_2d_enabled(false);
  773. m_sampler_config_is_dirty = true;
  774. break;
  775. case GL_TEXTURE_3D:
  776. m_active_texture_unit->set_texture_3d_enabled(false);
  777. m_sampler_config_is_dirty = true;
  778. break;
  779. case GL_TEXTURE_CUBE_MAP:
  780. m_active_texture_unit->set_texture_cube_map_enabled(false);
  781. m_sampler_config_is_dirty = true;
  782. break;
  783. case GL_TEXTURE_GEN_Q:
  784. case GL_TEXTURE_GEN_R:
  785. case GL_TEXTURE_GEN_S:
  786. case GL_TEXTURE_GEN_T:
  787. texture_coordinate_generation(m_active_texture_unit_index, capability).enabled = false;
  788. m_texcoord_generation_dirty = true;
  789. break;
  790. default:
  791. dbgln_if(GL_DEBUG, "gl_disable({:#x}): unknown parameter", capability);
  792. RETURN_WITH_ERROR_IF(true, GL_INVALID_ENUM);
  793. }
  794. if (update_rasterizer_options)
  795. m_rasterizer.set_options(rasterizer_options);
  796. }
  797. GLboolean GLContext::gl_is_enabled(GLenum capability)
  798. {
  799. RETURN_VALUE_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION, 0);
  800. auto optional_parameter = get_context_parameter(capability);
  801. RETURN_VALUE_WITH_ERROR_IF(!optional_parameter.has_value(), GL_INVALID_ENUM, 0);
  802. auto parameter = optional_parameter.release_value();
  803. RETURN_VALUE_WITH_ERROR_IF(!parameter.is_capability, GL_INVALID_ENUM, 0);
  804. return parameter.value.boolean_value;
  805. }
  806. void GLContext::gl_gen_textures(GLsizei n, GLuint* textures)
  807. {
  808. RETURN_WITH_ERROR_IF(n < 0, GL_INVALID_VALUE);
  809. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  810. m_name_allocator.allocate(n, textures);
  811. // Initialize all texture names with a nullptr
  812. for (auto i = 0; i < n; ++i) {
  813. GLuint name = textures[i];
  814. m_allocated_textures.set(name, nullptr);
  815. }
  816. }
  817. void GLContext::gl_delete_textures(GLsizei n, const GLuint* textures)
  818. {
  819. RETURN_WITH_ERROR_IF(n < 0, GL_INVALID_VALUE);
  820. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  821. for (auto i = 0; i < n; i++) {
  822. GLuint name = textures[i];
  823. if (name == 0)
  824. continue;
  825. m_name_allocator.free(name);
  826. auto texture_object = m_allocated_textures.find(name);
  827. if (texture_object == m_allocated_textures.end() || texture_object->value.is_null())
  828. continue;
  829. auto texture = texture_object->value;
  830. // Check all texture units
  831. for (auto& texture_unit : m_texture_units) {
  832. if (texture->is_texture_2d() && texture_unit.texture_2d_target_texture() == texture) {
  833. // If a texture that is currently bound is deleted, the binding reverts to 0 (the default texture)
  834. texture_unit.set_texture_2d_target_texture(get_default_texture<Texture2D>(GL_TEXTURE_2D));
  835. }
  836. }
  837. m_allocated_textures.remove(name);
  838. }
  839. }
  840. void GLContext::gl_tex_image_2d(GLenum target, GLint level, GLint internal_format, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, GLvoid const* data)
  841. {
  842. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  843. // We only support GL_TEXTURE_2D for now
  844. RETURN_WITH_ERROR_IF(target != GL_TEXTURE_2D, GL_INVALID_ENUM);
  845. // Internal format can also be a number between 1 and 4. Symbolic formats were only added with EXT_texture, promoted to core in OpenGL 1.1
  846. if (internal_format == 1)
  847. internal_format = GL_ALPHA;
  848. else if (internal_format == 2)
  849. internal_format = GL_LUMINANCE_ALPHA;
  850. else if (internal_format == 3)
  851. internal_format = GL_RGB;
  852. else if (internal_format == 4)
  853. internal_format = GL_RGBA;
  854. // We only support symbolic constants for now
  855. RETURN_WITH_ERROR_IF(!(internal_format == GL_RGB || internal_format == GL_RGBA || internal_format == GL_LUMINANCE8 || internal_format == GL_LUMINANCE8_ALPHA8), GL_INVALID_ENUM);
  856. RETURN_WITH_ERROR_IF(!(type == GL_UNSIGNED_BYTE || type == GL_UNSIGNED_SHORT_5_6_5), GL_INVALID_VALUE);
  857. RETURN_WITH_ERROR_IF(level < 0 || level > Texture2D::LOG2_MAX_TEXTURE_SIZE, GL_INVALID_VALUE);
  858. RETURN_WITH_ERROR_IF(width < 0 || height < 0 || width > (2 + Texture2D::MAX_TEXTURE_SIZE) || height > (2 + Texture2D::MAX_TEXTURE_SIZE), GL_INVALID_VALUE);
  859. // Check if width and height are a power of 2
  860. if (!m_device_info.supports_npot_textures) {
  861. RETURN_WITH_ERROR_IF(!is_power_of_two(width), GL_INVALID_VALUE);
  862. RETURN_WITH_ERROR_IF(!is_power_of_two(height), GL_INVALID_VALUE);
  863. }
  864. RETURN_WITH_ERROR_IF(border != 0, GL_INVALID_VALUE);
  865. auto texture_2d = m_active_texture_unit->texture_2d_target_texture();
  866. VERIFY(!texture_2d.is_null());
  867. if (level == 0) {
  868. // FIXME: OpenGL has the concept of texture and mipmap completeness. A texture has to fulfill certain criteria to be considered complete.
  869. // Trying to render while an incomplete texture is bound will result in an error.
  870. // Here we simply create a complete device image when mipmap level 0 is attached to the texture object. This has the unfortunate side effect
  871. // that constructing GL textures in any but the default mipmap order, going from level 0 upwards will cause mip levels to stay uninitialized.
  872. // To be spec compliant we should create the device image once the texture has become complete and is used for rendering the first time.
  873. // All images that were attached before the device image was created need to be stored somewhere to be used to initialize the device image once complete.
  874. texture_2d->set_device_image(m_rasterizer.create_image(SoftGPU::ImageFormat::BGRA8888, width, height, 1, 999, 1));
  875. m_sampler_config_is_dirty = true;
  876. }
  877. texture_2d->upload_texture_data(level, internal_format, width, height, format, type, data, m_unpack_row_length, m_unpack_alignment);
  878. }
  879. void GLContext::gl_tex_sub_image_2d(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, GLvoid const* data)
  880. {
  881. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  882. // We only support GL_TEXTURE_2D for now
  883. RETURN_WITH_ERROR_IF(target != GL_TEXTURE_2D, GL_INVALID_ENUM);
  884. // We only support symbolic constants for now
  885. RETURN_WITH_ERROR_IF(!(format == GL_RGBA || format == GL_RGB), GL_INVALID_VALUE);
  886. RETURN_WITH_ERROR_IF(!(type == GL_UNSIGNED_BYTE || type == GL_UNSIGNED_SHORT_5_6_5), GL_INVALID_VALUE);
  887. RETURN_WITH_ERROR_IF(level < 0 || level > Texture2D::LOG2_MAX_TEXTURE_SIZE, GL_INVALID_VALUE);
  888. RETURN_WITH_ERROR_IF(width < 0 || height < 0 || width > (2 + Texture2D::MAX_TEXTURE_SIZE) || height > (2 + Texture2D::MAX_TEXTURE_SIZE), GL_INVALID_VALUE);
  889. // A 2D texture array must have been defined by a previous glTexImage2D operation
  890. auto texture_2d = m_active_texture_unit->texture_2d_target_texture();
  891. RETURN_WITH_ERROR_IF(texture_2d.is_null(), GL_INVALID_OPERATION);
  892. RETURN_WITH_ERROR_IF(xoffset < 0 || yoffset < 0 || xoffset + width > texture_2d->width_at_lod(level) || yoffset + height > texture_2d->height_at_lod(level), GL_INVALID_VALUE);
  893. texture_2d->replace_sub_texture_data(level, xoffset, yoffset, width, height, format, type, data, m_unpack_row_length, m_unpack_alignment);
  894. }
  895. void GLContext::gl_tex_parameter(GLenum target, GLenum pname, GLfloat param)
  896. {
  897. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_tex_parameter, target, pname, param);
  898. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  899. // FIXME: We currently only support GL_TETXURE_2D targets. 1D, 3D and CUBE should also be supported (https://docs.gl/gl2/glTexParameter)
  900. RETURN_WITH_ERROR_IF(target != GL_TEXTURE_2D, GL_INVALID_ENUM);
  901. // FIXME: implement the remaining parameters. (https://docs.gl/gl2/glTexParameter)
  902. RETURN_WITH_ERROR_IF(!(pname == GL_TEXTURE_MIN_FILTER
  903. || pname == GL_TEXTURE_MAG_FILTER
  904. || pname == GL_TEXTURE_WRAP_S
  905. || pname == GL_TEXTURE_WRAP_T),
  906. GL_INVALID_ENUM);
  907. // We assume GL_TEXTURE_2D (see above)
  908. auto texture_2d = m_active_texture_unit->texture_2d_target_texture();
  909. if (texture_2d.is_null())
  910. return;
  911. switch (pname) {
  912. case GL_TEXTURE_MIN_FILTER:
  913. RETURN_WITH_ERROR_IF(!(param == GL_NEAREST
  914. || param == GL_LINEAR
  915. || param == GL_NEAREST_MIPMAP_NEAREST
  916. || param == GL_LINEAR_MIPMAP_NEAREST
  917. || param == GL_NEAREST_MIPMAP_LINEAR
  918. || param == GL_LINEAR_MIPMAP_LINEAR),
  919. GL_INVALID_ENUM);
  920. texture_2d->sampler().set_min_filter(param);
  921. break;
  922. case GL_TEXTURE_MAG_FILTER:
  923. RETURN_WITH_ERROR_IF(!(param == GL_NEAREST
  924. || param == GL_LINEAR),
  925. GL_INVALID_ENUM);
  926. texture_2d->sampler().set_mag_filter(param);
  927. break;
  928. case GL_TEXTURE_WRAP_S:
  929. RETURN_WITH_ERROR_IF(!(param == GL_CLAMP
  930. || param == GL_CLAMP_TO_BORDER
  931. || param == GL_CLAMP_TO_EDGE
  932. || param == GL_MIRRORED_REPEAT
  933. || param == GL_REPEAT),
  934. GL_INVALID_ENUM);
  935. texture_2d->sampler().set_wrap_s_mode(param);
  936. break;
  937. case GL_TEXTURE_WRAP_T:
  938. RETURN_WITH_ERROR_IF(!(param == GL_CLAMP
  939. || param == GL_CLAMP_TO_BORDER
  940. || param == GL_CLAMP_TO_EDGE
  941. || param == GL_MIRRORED_REPEAT
  942. || param == GL_REPEAT),
  943. GL_INVALID_ENUM);
  944. texture_2d->sampler().set_wrap_t_mode(param);
  945. break;
  946. default:
  947. VERIFY_NOT_REACHED();
  948. }
  949. m_sampler_config_is_dirty = true;
  950. }
  951. void GLContext::gl_front_face(GLenum face)
  952. {
  953. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_front_face, face);
  954. RETURN_WITH_ERROR_IF(face < GL_CW || face > GL_CCW, GL_INVALID_ENUM);
  955. m_front_face = face;
  956. auto rasterizer_options = m_rasterizer.options();
  957. rasterizer_options.front_face = (face == GL_CW) ? SoftGPU::WindingOrder::Clockwise : SoftGPU::WindingOrder::CounterClockwise;
  958. m_rasterizer.set_options(rasterizer_options);
  959. }
  960. void GLContext::gl_cull_face(GLenum cull_mode)
  961. {
  962. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_cull_face, cull_mode);
  963. RETURN_WITH_ERROR_IF(cull_mode < GL_FRONT || cull_mode > GL_FRONT_AND_BACK, GL_INVALID_ENUM);
  964. m_culled_sides = cull_mode;
  965. auto rasterizer_options = m_rasterizer.options();
  966. rasterizer_options.cull_back = cull_mode == GL_BACK || cull_mode == GL_FRONT_AND_BACK;
  967. rasterizer_options.cull_front = cull_mode == GL_FRONT || cull_mode == GL_FRONT_AND_BACK;
  968. m_rasterizer.set_options(rasterizer_options);
  969. }
  970. GLuint GLContext::gl_gen_lists(GLsizei range)
  971. {
  972. RETURN_VALUE_WITH_ERROR_IF(range <= 0, GL_INVALID_VALUE, 0);
  973. RETURN_VALUE_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION, 0);
  974. auto initial_entry = m_listings.size();
  975. m_listings.resize(range + initial_entry);
  976. return initial_entry + 1;
  977. }
  978. void GLContext::invoke_list(size_t list_index)
  979. {
  980. auto& listing = m_listings[list_index - 1];
  981. for (auto& entry : listing.entries) {
  982. entry.function.visit([&](auto& function) {
  983. entry.arguments.visit([&](auto& arguments) {
  984. auto apply = [&]<typename... Args>(Args && ... args)
  985. {
  986. if constexpr (requires { (this->*function)(forward<Args>(args)...); })
  987. (this->*function)(forward<Args>(args)...);
  988. };
  989. arguments.apply_as_args(apply);
  990. });
  991. });
  992. }
  993. }
  994. void GLContext::gl_call_list(GLuint list)
  995. {
  996. if (m_gl_call_depth > max_allowed_gl_call_depth)
  997. return;
  998. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_call_list, list);
  999. if (m_listings.size() < list)
  1000. return;
  1001. TemporaryChange change { m_gl_call_depth, m_gl_call_depth + 1 };
  1002. invoke_list(list);
  1003. }
  1004. void GLContext::gl_call_lists(GLsizei n, GLenum type, void const* lists)
  1005. {
  1006. if (m_gl_call_depth > max_allowed_gl_call_depth)
  1007. return;
  1008. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_call_lists, n, type, lists);
  1009. RETURN_WITH_ERROR_IF(n < 0, GL_INVALID_VALUE);
  1010. RETURN_WITH_ERROR_IF(!(type == GL_BYTE
  1011. || type == GL_UNSIGNED_BYTE
  1012. || type == GL_SHORT
  1013. || type == GL_UNSIGNED_SHORT
  1014. || type == GL_INT
  1015. || type == GL_UNSIGNED_INT
  1016. || type == GL_FLOAT
  1017. || type == GL_2_BYTES
  1018. || type == GL_3_BYTES
  1019. || type == GL_4_BYTES),
  1020. GL_INVALID_ENUM);
  1021. TemporaryChange change { m_gl_call_depth, m_gl_call_depth + 1 };
  1022. auto invoke_all_lists = [&]<typename T>(T const* lists) {
  1023. for (int i = 0; i < n; ++i) {
  1024. auto list = static_cast<size_t>(lists[i]);
  1025. invoke_list(m_list_base + list);
  1026. }
  1027. };
  1028. switch (type) {
  1029. case GL_BYTE:
  1030. invoke_all_lists(static_cast<GLbyte const*>(lists));
  1031. break;
  1032. case GL_UNSIGNED_BYTE:
  1033. invoke_all_lists(static_cast<GLubyte const*>(lists));
  1034. break;
  1035. case GL_SHORT:
  1036. invoke_all_lists(static_cast<GLshort const*>(lists));
  1037. break;
  1038. case GL_UNSIGNED_SHORT:
  1039. invoke_all_lists(static_cast<GLushort const*>(lists));
  1040. break;
  1041. case GL_INT:
  1042. invoke_all_lists(static_cast<GLint const*>(lists));
  1043. break;
  1044. case GL_UNSIGNED_INT:
  1045. invoke_all_lists(static_cast<GLuint const*>(lists));
  1046. break;
  1047. case GL_FLOAT:
  1048. invoke_all_lists(static_cast<GLfloat const*>(lists));
  1049. break;
  1050. case GL_2_BYTES:
  1051. case GL_3_BYTES:
  1052. case GL_4_BYTES:
  1053. dbgln("GLContext FIXME: unimplemented glCallLists() with type {}", type);
  1054. break;
  1055. default:
  1056. VERIFY_NOT_REACHED();
  1057. }
  1058. }
  1059. void GLContext::gl_delete_lists(GLuint list, GLsizei range)
  1060. {
  1061. if (m_listings.size() < list || m_listings.size() <= list + range)
  1062. return;
  1063. for (auto& entry : m_listings.span().slice(list - 1, range))
  1064. entry.entries.clear_with_capacity();
  1065. }
  1066. void GLContext::gl_list_base(GLuint base)
  1067. {
  1068. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_list_base, base);
  1069. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  1070. m_list_base = base;
  1071. }
  1072. void GLContext::gl_end_list()
  1073. {
  1074. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  1075. RETURN_WITH_ERROR_IF(!m_current_listing_index.has_value(), GL_INVALID_OPERATION);
  1076. m_listings[m_current_listing_index->index] = move(m_current_listing_index->listing);
  1077. m_current_listing_index.clear();
  1078. }
  1079. void GLContext::gl_new_list(GLuint list, GLenum mode)
  1080. {
  1081. RETURN_WITH_ERROR_IF(list == 0, GL_INVALID_VALUE);
  1082. RETURN_WITH_ERROR_IF(mode != GL_COMPILE && mode != GL_COMPILE_AND_EXECUTE, GL_INVALID_ENUM);
  1083. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  1084. RETURN_WITH_ERROR_IF(m_current_listing_index.has_value(), GL_INVALID_OPERATION);
  1085. if (m_listings.size() < list)
  1086. return;
  1087. m_current_listing_index = CurrentListing { {}, static_cast<size_t>(list - 1), mode };
  1088. }
  1089. GLboolean GLContext::gl_is_list(GLuint list)
  1090. {
  1091. RETURN_VALUE_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION, GL_FALSE);
  1092. return list < m_listings.size() ? GL_TRUE : GL_FALSE;
  1093. }
  1094. void GLContext::gl_flush()
  1095. {
  1096. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  1097. // No-op since GLContext is completely synchronous at the moment
  1098. }
  1099. void GLContext::gl_finish()
  1100. {
  1101. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  1102. // No-op since GLContext is completely synchronous at the moment
  1103. }
  1104. void GLContext::gl_blend_func(GLenum src_factor, GLenum dst_factor)
  1105. {
  1106. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_blend_func, src_factor, dst_factor);
  1107. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  1108. // FIXME: The list of allowed enums differs between API versions
  1109. // This was taken from the 2.0 spec on https://docs.gl/gl2/glBlendFunc
  1110. RETURN_WITH_ERROR_IF(!(src_factor == GL_ZERO
  1111. || src_factor == GL_ONE
  1112. || src_factor == GL_SRC_COLOR
  1113. || src_factor == GL_ONE_MINUS_SRC_COLOR
  1114. || src_factor == GL_DST_COLOR
  1115. || src_factor == GL_ONE_MINUS_DST_COLOR
  1116. || src_factor == GL_SRC_ALPHA
  1117. || src_factor == GL_ONE_MINUS_SRC_ALPHA
  1118. || src_factor == GL_DST_ALPHA
  1119. || src_factor == GL_ONE_MINUS_DST_ALPHA
  1120. || src_factor == GL_CONSTANT_COLOR
  1121. || src_factor == GL_ONE_MINUS_CONSTANT_COLOR
  1122. || src_factor == GL_CONSTANT_ALPHA
  1123. || src_factor == GL_ONE_MINUS_CONSTANT_ALPHA
  1124. || src_factor == GL_SRC_ALPHA_SATURATE),
  1125. GL_INVALID_ENUM);
  1126. RETURN_WITH_ERROR_IF(!(dst_factor == GL_ZERO
  1127. || dst_factor == GL_ONE
  1128. || dst_factor == GL_SRC_COLOR
  1129. || dst_factor == GL_ONE_MINUS_SRC_COLOR
  1130. || dst_factor == GL_DST_COLOR
  1131. || dst_factor == GL_ONE_MINUS_DST_COLOR
  1132. || dst_factor == GL_SRC_ALPHA
  1133. || dst_factor == GL_ONE_MINUS_SRC_ALPHA
  1134. || dst_factor == GL_DST_ALPHA
  1135. || dst_factor == GL_ONE_MINUS_DST_ALPHA
  1136. || dst_factor == GL_CONSTANT_COLOR
  1137. || dst_factor == GL_ONE_MINUS_CONSTANT_COLOR
  1138. || dst_factor == GL_CONSTANT_ALPHA
  1139. || dst_factor == GL_ONE_MINUS_CONSTANT_ALPHA),
  1140. GL_INVALID_ENUM);
  1141. m_blend_source_factor = src_factor;
  1142. m_blend_destination_factor = dst_factor;
  1143. auto map_gl_blend_factor_to_device = [](GLenum factor) constexpr
  1144. {
  1145. switch (factor) {
  1146. case GL_ZERO:
  1147. return SoftGPU::BlendFactor::Zero;
  1148. case GL_ONE:
  1149. return SoftGPU::BlendFactor::One;
  1150. case GL_SRC_ALPHA:
  1151. return SoftGPU::BlendFactor::SrcAlpha;
  1152. case GL_ONE_MINUS_SRC_ALPHA:
  1153. return SoftGPU::BlendFactor::OneMinusSrcAlpha;
  1154. case GL_SRC_COLOR:
  1155. return SoftGPU::BlendFactor::SrcColor;
  1156. case GL_ONE_MINUS_SRC_COLOR:
  1157. return SoftGPU::BlendFactor::OneMinusSrcColor;
  1158. case GL_DST_ALPHA:
  1159. return SoftGPU::BlendFactor::DstAlpha;
  1160. case GL_ONE_MINUS_DST_ALPHA:
  1161. return SoftGPU::BlendFactor::OneMinusDstAlpha;
  1162. case GL_DST_COLOR:
  1163. return SoftGPU::BlendFactor::DstColor;
  1164. case GL_ONE_MINUS_DST_COLOR:
  1165. return SoftGPU::BlendFactor::OneMinusDstColor;
  1166. case GL_SRC_ALPHA_SATURATE:
  1167. return SoftGPU::BlendFactor::SrcAlphaSaturate;
  1168. default:
  1169. VERIFY_NOT_REACHED();
  1170. }
  1171. };
  1172. auto options = m_rasterizer.options();
  1173. options.blend_source_factor = map_gl_blend_factor_to_device(m_blend_source_factor);
  1174. options.blend_destination_factor = map_gl_blend_factor_to_device(m_blend_destination_factor);
  1175. m_rasterizer.set_options(options);
  1176. }
  1177. void GLContext::gl_shade_model(GLenum mode)
  1178. {
  1179. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_shade_model, mode);
  1180. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  1181. RETURN_WITH_ERROR_IF(mode != GL_FLAT && mode != GL_SMOOTH, GL_INVALID_ENUM);
  1182. auto options = m_rasterizer.options();
  1183. options.shade_smooth = (mode == GL_SMOOTH);
  1184. m_rasterizer.set_options(options);
  1185. }
  1186. void GLContext::gl_alpha_func(GLenum func, GLclampf ref)
  1187. {
  1188. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_alpha_func, func, ref);
  1189. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  1190. RETURN_WITH_ERROR_IF(func < GL_NEVER || func > GL_ALWAYS, GL_INVALID_ENUM);
  1191. m_alpha_test_func = func;
  1192. m_alpha_test_ref_value = ref;
  1193. auto options = m_rasterizer.options();
  1194. switch (func) {
  1195. case GL_NEVER:
  1196. options.alpha_test_func = SoftGPU::AlphaTestFunction::Never;
  1197. break;
  1198. case GL_ALWAYS:
  1199. options.alpha_test_func = SoftGPU::AlphaTestFunction::Always;
  1200. break;
  1201. case GL_LESS:
  1202. options.alpha_test_func = SoftGPU::AlphaTestFunction::Less;
  1203. break;
  1204. case GL_LEQUAL:
  1205. options.alpha_test_func = SoftGPU::AlphaTestFunction::LessOrEqual;
  1206. break;
  1207. case GL_EQUAL:
  1208. options.alpha_test_func = SoftGPU::AlphaTestFunction::Equal;
  1209. break;
  1210. case GL_NOTEQUAL:
  1211. options.alpha_test_func = SoftGPU::AlphaTestFunction::NotEqual;
  1212. break;
  1213. case GL_GEQUAL:
  1214. options.alpha_test_func = SoftGPU::AlphaTestFunction::GreaterOrEqual;
  1215. break;
  1216. case GL_GREATER:
  1217. options.alpha_test_func = SoftGPU::AlphaTestFunction::Greater;
  1218. break;
  1219. default:
  1220. VERIFY_NOT_REACHED();
  1221. }
  1222. options.alpha_test_ref_value = m_alpha_test_ref_value;
  1223. m_rasterizer.set_options(options);
  1224. }
  1225. void GLContext::gl_hint(GLenum target, GLenum mode)
  1226. {
  1227. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_hint, target, mode);
  1228. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  1229. RETURN_WITH_ERROR_IF(target != GL_PERSPECTIVE_CORRECTION_HINT
  1230. && target != GL_POINT_SMOOTH_HINT
  1231. && target != GL_LINE_SMOOTH_HINT
  1232. && target != GL_POLYGON_SMOOTH_HINT
  1233. && target != GL_FOG_HINT
  1234. && target != GL_GENERATE_MIPMAP_HINT
  1235. && target != GL_TEXTURE_COMPRESSION_HINT,
  1236. GL_INVALID_ENUM);
  1237. RETURN_WITH_ERROR_IF(mode != GL_DONT_CARE
  1238. && mode != GL_FASTEST
  1239. && mode != GL_NICEST,
  1240. GL_INVALID_ENUM);
  1241. // According to the spec implementors are free to ignore glHint. So we do.
  1242. }
  1243. void GLContext::gl_read_buffer(GLenum mode)
  1244. {
  1245. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_read_buffer, mode);
  1246. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  1247. // FIXME: Also allow aux buffers GL_AUX0 through GL_AUX3 here
  1248. // plus any aux buffer between 0 and GL_AUX_BUFFERS
  1249. RETURN_WITH_ERROR_IF(mode != GL_FRONT_LEFT
  1250. && mode != GL_FRONT_RIGHT
  1251. && mode != GL_BACK_LEFT
  1252. && mode != GL_BACK_RIGHT
  1253. && mode != GL_FRONT
  1254. && mode != GL_BACK
  1255. && mode != GL_LEFT
  1256. && mode != GL_RIGHT,
  1257. GL_INVALID_ENUM);
  1258. // FIXME: We do not currently have aux buffers, so make it an invalid
  1259. // operation to select anything but front or back buffers. Also we do
  1260. // not allow selecting the stereoscopic RIGHT buffers since we do not
  1261. // have them configured.
  1262. RETURN_WITH_ERROR_IF(mode != GL_FRONT_LEFT
  1263. && mode != GL_FRONT
  1264. && mode != GL_BACK_LEFT
  1265. && mode != GL_BACK
  1266. && mode != GL_FRONT
  1267. && mode != GL_BACK
  1268. && mode != GL_LEFT,
  1269. GL_INVALID_OPERATION);
  1270. m_current_read_buffer = mode;
  1271. }
  1272. void GLContext::gl_draw_buffer(GLenum buffer)
  1273. {
  1274. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_draw_buffer, buffer);
  1275. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  1276. // FIXME: Also allow aux buffers GL_AUX0 through GL_AUX3 here
  1277. // plus any aux buffer between 0 and GL_AUX_BUFFERS
  1278. RETURN_WITH_ERROR_IF(buffer != GL_NONE
  1279. && buffer != GL_FRONT_LEFT
  1280. && buffer != GL_FRONT_RIGHT
  1281. && buffer != GL_BACK_LEFT
  1282. && buffer != GL_BACK_RIGHT
  1283. && buffer != GL_FRONT
  1284. && buffer != GL_BACK
  1285. && buffer != GL_LEFT
  1286. && buffer != GL_RIGHT,
  1287. GL_INVALID_ENUM);
  1288. // FIXME: We do not currently have aux buffers, so make it an invalid
  1289. // operation to select anything but front or back buffers. Also we do
  1290. // not allow selecting the stereoscopic RIGHT buffers since we do not
  1291. // have them configured.
  1292. RETURN_WITH_ERROR_IF(buffer != GL_NONE
  1293. && buffer != GL_FRONT_LEFT
  1294. && buffer != GL_FRONT
  1295. && buffer != GL_BACK_LEFT
  1296. && buffer != GL_BACK
  1297. && buffer != GL_FRONT
  1298. && buffer != GL_BACK
  1299. && buffer != GL_LEFT,
  1300. GL_INVALID_OPERATION);
  1301. m_current_draw_buffer = buffer;
  1302. auto rasterizer_options = m_rasterizer.options();
  1303. // FIXME: We only have a single draw buffer in SoftGPU at the moment,
  1304. // so we simply disable color writes if GL_NONE is selected
  1305. rasterizer_options.enable_color_write = m_current_draw_buffer != GL_NONE;
  1306. m_rasterizer.set_options(rasterizer_options);
  1307. }
  1308. void GLContext::gl_read_pixels(GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, GLvoid* pixels)
  1309. {
  1310. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  1311. RETURN_WITH_ERROR_IF(width < 0 || height < 0, GL_INVALID_VALUE);
  1312. RETURN_WITH_ERROR_IF(format != GL_COLOR_INDEX
  1313. && format != GL_STENCIL_INDEX
  1314. && format != GL_DEPTH_COMPONENT
  1315. && format != GL_RED
  1316. && format != GL_GREEN
  1317. && format != GL_BLUE
  1318. && format != GL_ALPHA
  1319. && format != GL_RGB
  1320. && format != GL_RGBA
  1321. && format != GL_LUMINANCE
  1322. && format != GL_LUMINANCE_ALPHA,
  1323. GL_INVALID_ENUM);
  1324. RETURN_WITH_ERROR_IF(type != GL_UNSIGNED_BYTE
  1325. && type != GL_BYTE
  1326. && type != GL_BITMAP
  1327. && type != GL_UNSIGNED_SHORT
  1328. && type != GL_SHORT
  1329. && type != GL_BLUE
  1330. && type != GL_UNSIGNED_INT
  1331. && type != GL_INT
  1332. && type != GL_FLOAT,
  1333. GL_INVALID_ENUM);
  1334. // FIXME: We only support RGBA buffers for now.
  1335. // Once we add support for indexed color modes do the correct check here
  1336. RETURN_WITH_ERROR_IF(format == GL_COLOR_INDEX, GL_INVALID_OPERATION);
  1337. // FIXME: We do not have stencil buffers yet
  1338. // Once we add support for stencil buffers do the correct check here
  1339. RETURN_WITH_ERROR_IF(format == GL_STENCIL_INDEX, GL_INVALID_OPERATION);
  1340. if (format == GL_DEPTH_COMPONENT) {
  1341. // FIXME: This check needs to be a bit more sophisticated. Currently the buffers
  1342. // are hardcoded. Once we add proper structures for them we need to correct this check
  1343. // Error because only back buffer has a depth buffer
  1344. RETURN_WITH_ERROR_IF(m_current_read_buffer == GL_FRONT
  1345. || m_current_read_buffer == GL_FRONT_LEFT
  1346. || m_current_read_buffer == GL_FRONT_RIGHT,
  1347. GL_INVALID_OPERATION);
  1348. }
  1349. // Some helper functions for converting float values to integer types
  1350. auto float_to_i8 = [](float f) -> GLchar {
  1351. return static_cast<GLchar>((0x7f * min(max(f, 0.0f), 1.0f) - 1) / 2);
  1352. };
  1353. auto float_to_i16 = [](float f) -> GLshort {
  1354. return static_cast<GLshort>((0x7fff * min(max(f, 0.0f), 1.0f) - 1) / 2);
  1355. };
  1356. auto float_to_i32 = [](float f) -> GLint {
  1357. return static_cast<GLint>((0x7fffffff * min(max(f, 0.0f), 1.0f) - 1) / 2);
  1358. };
  1359. auto float_to_u8 = [](float f) -> GLubyte {
  1360. return static_cast<GLubyte>(0xff * min(max(f, 0.0f), 1.0f));
  1361. };
  1362. auto float_to_u16 = [](float f) -> GLushort {
  1363. return static_cast<GLushort>(0xffff * min(max(f, 0.0f), 1.0f));
  1364. };
  1365. auto float_to_u32 = [](float f) -> GLuint {
  1366. return static_cast<GLuint>(0xffffffff * min(max(f, 0.0f), 1.0f));
  1367. };
  1368. u8 component_size = 0;
  1369. switch (type) {
  1370. case GL_BYTE:
  1371. case GL_UNSIGNED_BYTE:
  1372. component_size = 1;
  1373. break;
  1374. case GL_SHORT:
  1375. case GL_UNSIGNED_SHORT:
  1376. component_size = 2;
  1377. break;
  1378. case GL_INT:
  1379. case GL_UNSIGNED_INT:
  1380. case GL_FLOAT:
  1381. component_size = 4;
  1382. break;
  1383. }
  1384. if (format == GL_DEPTH_COMPONENT) {
  1385. auto const row_stride = (width * component_size + m_pack_alignment - 1) / m_pack_alignment * m_pack_alignment;
  1386. // Read from depth buffer
  1387. for (GLsizei i = 0; i < height; ++i) {
  1388. for (GLsizei j = 0; j < width; ++j) {
  1389. float depth = m_rasterizer.get_depthbuffer_value(x + j, y + i);
  1390. auto char_ptr = reinterpret_cast<char*>(pixels) + i * row_stride + j * component_size;
  1391. switch (type) {
  1392. case GL_BYTE:
  1393. *reinterpret_cast<GLchar*>(char_ptr) = float_to_i8(depth);
  1394. break;
  1395. case GL_SHORT:
  1396. *reinterpret_cast<GLshort*>(char_ptr) = float_to_i16(depth);
  1397. break;
  1398. case GL_INT:
  1399. *reinterpret_cast<GLint*>(char_ptr) = float_to_i32(depth);
  1400. break;
  1401. case GL_UNSIGNED_BYTE:
  1402. *reinterpret_cast<GLubyte*>(char_ptr) = float_to_u8(depth);
  1403. break;
  1404. case GL_UNSIGNED_SHORT:
  1405. *reinterpret_cast<GLushort*>(char_ptr) = float_to_u16(depth);
  1406. break;
  1407. case GL_UNSIGNED_INT:
  1408. *reinterpret_cast<GLuint*>(char_ptr) = float_to_u32(depth);
  1409. break;
  1410. case GL_FLOAT:
  1411. *reinterpret_cast<GLfloat*>(char_ptr) = min(max(depth, 0.0f), 1.0f);
  1412. break;
  1413. }
  1414. }
  1415. }
  1416. return;
  1417. }
  1418. bool write_red = false;
  1419. bool write_green = false;
  1420. bool write_blue = false;
  1421. bool write_alpha = false;
  1422. size_t component_count = 0;
  1423. size_t red_offset = 0;
  1424. size_t green_offset = 0;
  1425. size_t blue_offset = 0;
  1426. size_t alpha_offset = 0;
  1427. char* red_ptr = nullptr;
  1428. char* green_ptr = nullptr;
  1429. char* blue_ptr = nullptr;
  1430. char* alpha_ptr = nullptr;
  1431. switch (format) {
  1432. case GL_RGB:
  1433. write_red = true;
  1434. write_green = true;
  1435. write_blue = true;
  1436. component_count = 3;
  1437. red_offset = 2;
  1438. green_offset = 1;
  1439. blue_offset = 0;
  1440. break;
  1441. case GL_RGBA:
  1442. write_red = true;
  1443. write_green = true;
  1444. write_blue = true;
  1445. write_alpha = true;
  1446. component_count = 4;
  1447. red_offset = 3;
  1448. green_offset = 2;
  1449. blue_offset = 1;
  1450. alpha_offset = 0;
  1451. break;
  1452. case GL_RED:
  1453. write_red = true;
  1454. component_count = 1;
  1455. red_offset = 0;
  1456. break;
  1457. case GL_GREEN:
  1458. write_green = true;
  1459. component_count = 1;
  1460. green_offset = 0;
  1461. break;
  1462. case GL_BLUE:
  1463. write_blue = true;
  1464. component_count = 1;
  1465. blue_offset = 0;
  1466. break;
  1467. case GL_ALPHA:
  1468. write_alpha = true;
  1469. component_count = 1;
  1470. alpha_offset = 0;
  1471. break;
  1472. }
  1473. auto const pixel_bytes = component_size * component_count;
  1474. auto const row_alignment_bytes = (m_pack_alignment - ((width * pixel_bytes) % m_pack_alignment)) % m_pack_alignment;
  1475. char* out_ptr = reinterpret_cast<char*>(pixels);
  1476. for (int i = 0; i < (int)height; ++i) {
  1477. for (int j = 0; j < (int)width; ++j) {
  1478. Gfx::ARGB32 color {};
  1479. if (m_current_read_buffer == GL_FRONT || m_current_read_buffer == GL_LEFT || m_current_read_buffer == GL_FRONT_LEFT) {
  1480. if (y + i >= m_frontbuffer->width() || x + j >= m_frontbuffer->height())
  1481. color = 0;
  1482. else
  1483. color = m_frontbuffer->scanline(y + i)[x + j];
  1484. } else {
  1485. color = m_rasterizer.get_color_buffer_pixel(x + j, y + i);
  1486. }
  1487. float red = ((color >> 24) & 0xff) / 255.0f;
  1488. float green = ((color >> 16) & 0xff) / 255.0f;
  1489. float blue = ((color >> 8) & 0xff) / 255.0f;
  1490. float alpha = (color & 0xff) / 255.0f;
  1491. // FIXME: Set up write pointers based on selected endianness (glPixelStore)
  1492. red_ptr = out_ptr + (component_size * red_offset);
  1493. green_ptr = out_ptr + (component_size * green_offset);
  1494. blue_ptr = out_ptr + (component_size * blue_offset);
  1495. alpha_ptr = out_ptr + (component_size * alpha_offset);
  1496. switch (type) {
  1497. case GL_BYTE:
  1498. if (write_red)
  1499. *reinterpret_cast<GLchar*>(red_ptr) = float_to_i8(red);
  1500. if (write_green)
  1501. *reinterpret_cast<GLchar*>(green_ptr) = float_to_i8(green);
  1502. if (write_blue)
  1503. *reinterpret_cast<GLchar*>(blue_ptr) = float_to_i8(blue);
  1504. if (write_alpha)
  1505. *reinterpret_cast<GLchar*>(alpha_ptr) = float_to_i8(alpha);
  1506. break;
  1507. case GL_UNSIGNED_BYTE:
  1508. if (write_red)
  1509. *reinterpret_cast<GLubyte*>(red_ptr) = float_to_u8(red);
  1510. if (write_green)
  1511. *reinterpret_cast<GLubyte*>(green_ptr) = float_to_u8(green);
  1512. if (write_blue)
  1513. *reinterpret_cast<GLubyte*>(blue_ptr) = float_to_u8(blue);
  1514. if (write_alpha)
  1515. *reinterpret_cast<GLubyte*>(alpha_ptr) = float_to_u8(alpha);
  1516. break;
  1517. case GL_SHORT:
  1518. if (write_red)
  1519. *reinterpret_cast<GLshort*>(red_ptr) = float_to_i16(red);
  1520. if (write_green)
  1521. *reinterpret_cast<GLshort*>(green_ptr) = float_to_i16(green);
  1522. if (write_blue)
  1523. *reinterpret_cast<GLshort*>(blue_ptr) = float_to_i16(blue);
  1524. if (write_alpha)
  1525. *reinterpret_cast<GLshort*>(alpha_ptr) = float_to_i16(alpha);
  1526. break;
  1527. case GL_UNSIGNED_SHORT:
  1528. if (write_red)
  1529. *reinterpret_cast<GLushort*>(red_ptr) = float_to_u16(red);
  1530. if (write_green)
  1531. *reinterpret_cast<GLushort*>(green_ptr) = float_to_u16(green);
  1532. if (write_blue)
  1533. *reinterpret_cast<GLushort*>(blue_ptr) = float_to_u16(blue);
  1534. if (write_alpha)
  1535. *reinterpret_cast<GLushort*>(alpha_ptr) = float_to_u16(alpha);
  1536. break;
  1537. case GL_INT:
  1538. if (write_red)
  1539. *reinterpret_cast<GLint*>(red_ptr) = float_to_i32(red);
  1540. if (write_green)
  1541. *reinterpret_cast<GLint*>(green_ptr) = float_to_i32(green);
  1542. if (write_blue)
  1543. *reinterpret_cast<GLint*>(blue_ptr) = float_to_i32(blue);
  1544. if (write_alpha)
  1545. *reinterpret_cast<GLint*>(alpha_ptr) = float_to_i32(alpha);
  1546. break;
  1547. case GL_UNSIGNED_INT:
  1548. if (write_red)
  1549. *reinterpret_cast<GLuint*>(red_ptr) = float_to_u32(red);
  1550. if (write_green)
  1551. *reinterpret_cast<GLuint*>(green_ptr) = float_to_u32(green);
  1552. if (write_blue)
  1553. *reinterpret_cast<GLuint*>(blue_ptr) = float_to_u32(blue);
  1554. if (write_alpha)
  1555. *reinterpret_cast<GLuint*>(alpha_ptr) = float_to_u32(alpha);
  1556. break;
  1557. case GL_FLOAT:
  1558. if (write_red)
  1559. *reinterpret_cast<GLfloat*>(red_ptr) = min(max(red, 0.0f), 1.0f);
  1560. if (write_green)
  1561. *reinterpret_cast<GLfloat*>(green_ptr) = min(max(green, 0.0f), 1.0f);
  1562. if (write_blue)
  1563. *reinterpret_cast<GLfloat*>(blue_ptr) = min(max(blue, 0.0f), 1.0f);
  1564. if (write_alpha)
  1565. *reinterpret_cast<GLfloat*>(alpha_ptr) = min(max(alpha, 0.0f), 1.0f);
  1566. break;
  1567. }
  1568. out_ptr += pixel_bytes;
  1569. }
  1570. out_ptr += row_alignment_bytes;
  1571. }
  1572. }
  1573. void GLContext::gl_bind_texture(GLenum target, GLuint texture)
  1574. {
  1575. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  1576. RETURN_WITH_ERROR_IF(target != GL_TEXTURE_1D
  1577. && target != GL_TEXTURE_2D
  1578. && target != GL_TEXTURE_3D
  1579. && target != GL_TEXTURE_1D_ARRAY
  1580. && target != GL_TEXTURE_2D_ARRAY
  1581. && target != GL_TEXTURE_CUBE_MAP,
  1582. GL_INVALID_ENUM);
  1583. // FIXME: We only support GL_TEXTURE_2D for now
  1584. if (target != GL_TEXTURE_2D) {
  1585. dbgln("gl_bind_texture(target = {:#x}): currently only GL_TEXTURE_2D is supported", target);
  1586. return;
  1587. }
  1588. RefPtr<Texture2D> texture_2d;
  1589. if (texture == 0) {
  1590. // Texture name 0 refers to the default texture
  1591. texture_2d = get_default_texture<Texture2D>(target);
  1592. } else {
  1593. // Find this texture name in our previously allocated textures
  1594. auto it = m_allocated_textures.find(texture);
  1595. if (it != m_allocated_textures.end()) {
  1596. auto texture_object = it->value;
  1597. if (!texture_object.is_null()) {
  1598. // Texture must have been created with the same target
  1599. RETURN_WITH_ERROR_IF(!texture_object->is_texture_2d(), GL_INVALID_OPERATION);
  1600. texture_2d = static_cast<Texture2D*>(texture_object.ptr());
  1601. }
  1602. }
  1603. // OpenGL 1.x supports binding texture names that were not previously generated by glGenTextures.
  1604. // If there is not an allocated texture, meaning it was not previously generated by glGenTextures,
  1605. // we can keep texture_object null to both allocate and bind the texture with the passed in texture name.
  1606. // FIXME: Later OpenGL versions such as 4.x enforce that texture names being bound were previously generated
  1607. // by glGenTextures.
  1608. if (!texture_2d) {
  1609. texture_2d = adopt_ref(*new Texture2D());
  1610. m_allocated_textures.set(texture, texture_2d);
  1611. }
  1612. }
  1613. m_active_texture_unit->set_texture_2d_target_texture(texture_2d);
  1614. m_sampler_config_is_dirty = true;
  1615. }
  1616. GLboolean GLContext::gl_is_texture(GLuint texture)
  1617. {
  1618. RETURN_VALUE_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION, GL_FALSE);
  1619. if (texture == 0)
  1620. return GL_FALSE;
  1621. auto it = m_allocated_textures.find(texture);
  1622. if (it == m_allocated_textures.end())
  1623. return GL_FALSE;
  1624. return it->value.is_null() ? GL_FALSE : GL_TRUE;
  1625. }
  1626. void GLContext::gl_active_texture(GLenum texture)
  1627. {
  1628. RETURN_WITH_ERROR_IF(texture < GL_TEXTURE0 || texture >= GL_TEXTURE0 + m_device_info.num_texture_units, GL_INVALID_ENUM);
  1629. m_active_texture_unit_index = texture - GL_TEXTURE0;
  1630. m_active_texture_unit = &m_texture_units.at(m_active_texture_unit_index);
  1631. }
  1632. void GLContext::gl_get_booleanv(GLenum pname, GLboolean* data)
  1633. {
  1634. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  1635. auto optional_parameter = get_context_parameter(pname);
  1636. RETURN_WITH_ERROR_IF(!optional_parameter.has_value(), GL_INVALID_ENUM);
  1637. auto parameter = optional_parameter.release_value();
  1638. switch (parameter.type) {
  1639. case GL_BOOL:
  1640. *data = parameter.value.boolean_value ? GL_TRUE : GL_FALSE;
  1641. break;
  1642. case GL_DOUBLE:
  1643. *data = (parameter.value.double_value == 0.0) ? GL_FALSE : GL_TRUE;
  1644. break;
  1645. case GL_INT:
  1646. *data = (parameter.value.integer_value == 0) ? GL_FALSE : GL_TRUE;
  1647. break;
  1648. default:
  1649. VERIFY_NOT_REACHED();
  1650. }
  1651. }
  1652. void GLContext::gl_get_doublev(GLenum pname, GLdouble* params)
  1653. {
  1654. get_floating_point(pname, params);
  1655. }
  1656. void GLContext::gl_get_floatv(GLenum pname, GLfloat* params)
  1657. {
  1658. get_floating_point(pname, params);
  1659. }
  1660. template<typename T>
  1661. void GLContext::get_floating_point(GLenum pname, T* params)
  1662. {
  1663. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  1664. // Handle matrix retrieval first
  1665. auto flatten_and_assign_matrix = [&params](FloatMatrix4x4 const& matrix) {
  1666. auto elements = matrix.elements();
  1667. for (size_t i = 0; i < 4; ++i) {
  1668. for (size_t j = 0; j < 4; ++j) {
  1669. // Return transposed matrix since OpenGL defines them as column-major
  1670. params[i * 4 + j] = static_cast<T>(elements[j][i]);
  1671. }
  1672. }
  1673. };
  1674. switch (pname) {
  1675. case GL_MODELVIEW_MATRIX:
  1676. flatten_and_assign_matrix(m_model_view_matrix);
  1677. return;
  1678. case GL_PROJECTION_MATRIX:
  1679. flatten_and_assign_matrix(m_projection_matrix);
  1680. return;
  1681. }
  1682. // Regular parameters
  1683. auto optional_parameter = get_context_parameter(pname);
  1684. RETURN_WITH_ERROR_IF(!optional_parameter.has_value(), GL_INVALID_ENUM);
  1685. auto parameter = optional_parameter.release_value();
  1686. switch (parameter.type) {
  1687. case GL_BOOL:
  1688. *params = parameter.value.boolean_value ? GL_TRUE : GL_FALSE;
  1689. break;
  1690. case GL_DOUBLE:
  1691. for (size_t i = 0; i < parameter.count; ++i)
  1692. params[i] = parameter.value.double_list[i];
  1693. break;
  1694. case GL_INT:
  1695. for (size_t i = 0; i < parameter.count; ++i)
  1696. params[i] = parameter.value.integer_list[i];
  1697. break;
  1698. default:
  1699. VERIFY_NOT_REACHED();
  1700. }
  1701. }
  1702. void GLContext::gl_get_integerv(GLenum pname, GLint* data)
  1703. {
  1704. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  1705. auto optional_parameter = get_context_parameter(pname);
  1706. RETURN_WITH_ERROR_IF(!optional_parameter.has_value(), GL_INVALID_ENUM);
  1707. auto parameter = optional_parameter.release_value();
  1708. switch (parameter.type) {
  1709. case GL_BOOL:
  1710. *data = parameter.value.boolean_value ? GL_TRUE : GL_FALSE;
  1711. break;
  1712. case GL_DOUBLE: {
  1713. double const int_range = static_cast<double>(NumericLimits<GLint>::max()) - NumericLimits<GLint>::min();
  1714. for (size_t i = 0; i < parameter.count; ++i) {
  1715. double const result_factor = (clamp(parameter.value.double_list[i], -1.0, 1.0) + 1.0) / 2.0;
  1716. data[i] = static_cast<GLint>(NumericLimits<GLint>::min() + result_factor * int_range);
  1717. }
  1718. break;
  1719. }
  1720. case GL_INT:
  1721. for (size_t i = 0; i < parameter.count; ++i)
  1722. data[i] = parameter.value.integer_list[i];
  1723. break;
  1724. default:
  1725. VERIFY_NOT_REACHED();
  1726. }
  1727. }
  1728. void GLContext::gl_depth_mask(GLboolean flag)
  1729. {
  1730. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_depth_mask, flag);
  1731. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  1732. auto options = m_rasterizer.options();
  1733. options.enable_depth_write = (flag != GL_FALSE);
  1734. m_rasterizer.set_options(options);
  1735. }
  1736. void GLContext::gl_enable_client_state(GLenum cap)
  1737. {
  1738. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  1739. switch (cap) {
  1740. case GL_COLOR_ARRAY:
  1741. m_client_side_color_array_enabled = true;
  1742. break;
  1743. case GL_NORMAL_ARRAY:
  1744. m_client_side_normal_array_enabled = true;
  1745. break;
  1746. case GL_TEXTURE_COORD_ARRAY:
  1747. m_client_side_texture_coord_array_enabled[m_client_active_texture] = true;
  1748. break;
  1749. case GL_VERTEX_ARRAY:
  1750. m_client_side_vertex_array_enabled = true;
  1751. break;
  1752. default:
  1753. RETURN_WITH_ERROR_IF(true, GL_INVALID_ENUM);
  1754. }
  1755. }
  1756. void GLContext::gl_disable_client_state(GLenum cap)
  1757. {
  1758. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  1759. switch (cap) {
  1760. case GL_COLOR_ARRAY:
  1761. m_client_side_color_array_enabled = false;
  1762. break;
  1763. case GL_NORMAL_ARRAY:
  1764. m_client_side_normal_array_enabled = false;
  1765. break;
  1766. case GL_TEXTURE_COORD_ARRAY:
  1767. m_client_side_texture_coord_array_enabled[m_client_active_texture] = false;
  1768. break;
  1769. case GL_VERTEX_ARRAY:
  1770. m_client_side_vertex_array_enabled = false;
  1771. break;
  1772. default:
  1773. RETURN_WITH_ERROR_IF(true, GL_INVALID_ENUM);
  1774. }
  1775. }
  1776. void GLContext::gl_client_active_texture(GLenum target)
  1777. {
  1778. RETURN_WITH_ERROR_IF(target < GL_TEXTURE0 || target >= GL_TEXTURE0 + m_device_info.num_texture_units, GL_INVALID_ENUM);
  1779. m_client_active_texture = target - GL_TEXTURE0;
  1780. }
  1781. void GLContext::gl_vertex_pointer(GLint size, GLenum type, GLsizei stride, const void* pointer)
  1782. {
  1783. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  1784. RETURN_WITH_ERROR_IF(!(size == 2 || size == 3 || size == 4), GL_INVALID_VALUE);
  1785. RETURN_WITH_ERROR_IF(!(type == GL_SHORT || type == GL_INT || type == GL_FLOAT || type == GL_DOUBLE), GL_INVALID_ENUM);
  1786. RETURN_WITH_ERROR_IF(stride < 0, GL_INVALID_VALUE);
  1787. m_client_vertex_pointer = { .size = size, .type = type, .stride = stride, .pointer = pointer };
  1788. }
  1789. void GLContext::gl_color_pointer(GLint size, GLenum type, GLsizei stride, const void* pointer)
  1790. {
  1791. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  1792. RETURN_WITH_ERROR_IF(!(size == 3 || size == 4), GL_INVALID_VALUE);
  1793. RETURN_WITH_ERROR_IF(type != GL_BYTE
  1794. && type != GL_UNSIGNED_BYTE
  1795. && type != GL_SHORT
  1796. && type != GL_UNSIGNED_SHORT
  1797. && type != GL_INT
  1798. && type != GL_UNSIGNED_INT
  1799. && type != GL_FLOAT
  1800. && type != GL_DOUBLE,
  1801. GL_INVALID_ENUM);
  1802. RETURN_WITH_ERROR_IF(stride < 0, GL_INVALID_VALUE);
  1803. m_client_color_pointer = { .size = size, .type = type, .stride = stride, .pointer = pointer };
  1804. }
  1805. void GLContext::gl_tex_coord_pointer(GLint size, GLenum type, GLsizei stride, const void* pointer)
  1806. {
  1807. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  1808. RETURN_WITH_ERROR_IF(!(size == 1 || size == 2 || size == 3 || size == 4), GL_INVALID_VALUE);
  1809. RETURN_WITH_ERROR_IF(!(type == GL_SHORT || type == GL_INT || type == GL_FLOAT || type == GL_DOUBLE), GL_INVALID_ENUM);
  1810. RETURN_WITH_ERROR_IF(stride < 0, GL_INVALID_VALUE);
  1811. auto& tex_coord_pointer = m_client_tex_coord_pointer[m_client_active_texture];
  1812. tex_coord_pointer = { .size = size, .type = type, .stride = stride, .pointer = pointer };
  1813. }
  1814. void GLContext::gl_normal_pointer(GLenum type, GLsizei stride, void const* pointer)
  1815. {
  1816. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  1817. RETURN_WITH_ERROR_IF(type != GL_BYTE
  1818. && type != GL_SHORT
  1819. && type != GL_INT
  1820. && type != GL_FLOAT
  1821. && type != GL_DOUBLE,
  1822. GL_INVALID_ENUM);
  1823. RETURN_WITH_ERROR_IF(stride < 0, GL_INVALID_VALUE);
  1824. m_client_normal_pointer = { .size = 3, .type = type, .stride = stride, .pointer = pointer };
  1825. }
  1826. void GLContext::gl_tex_env(GLenum target, GLenum pname, GLfloat param)
  1827. {
  1828. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_tex_env, target, pname, param);
  1829. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  1830. // FIXME: We currently only support a subset of possible target values. Implement the rest!
  1831. RETURN_WITH_ERROR_IF(target != GL_TEXTURE_ENV, GL_INVALID_ENUM);
  1832. // FIXME: We currently only support a subset of possible pname values. Implement the rest!
  1833. RETURN_WITH_ERROR_IF(pname != GL_TEXTURE_ENV_MODE, GL_INVALID_ENUM);
  1834. auto param_enum = static_cast<GLenum>(param);
  1835. switch (param_enum) {
  1836. case GL_MODULATE:
  1837. case GL_REPLACE:
  1838. case GL_DECAL:
  1839. m_active_texture_unit->set_env_mode(param_enum);
  1840. m_sampler_config_is_dirty = true;
  1841. break;
  1842. default:
  1843. // FIXME: We currently only support a subset of possible param values. Implement the rest!
  1844. dbgln_if(GL_DEBUG, "gl_tex_env({:#x}, {:#x}, {}): param unimplemented", target, pname, param);
  1845. RETURN_WITH_ERROR_IF(true, GL_INVALID_ENUM);
  1846. }
  1847. }
  1848. void GLContext::gl_draw_arrays(GLenum mode, GLint first, GLsizei count)
  1849. {
  1850. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_draw_arrays, mode, first, count);
  1851. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  1852. // FIXME: Some modes are still missing (GL_POINTS, GL_LINE_STRIP, GL_LINE_LOOP, GL_LINES)
  1853. RETURN_WITH_ERROR_IF(!(mode == GL_TRIANGLE_STRIP
  1854. || mode == GL_TRIANGLE_FAN
  1855. || mode == GL_TRIANGLES
  1856. || mode == GL_QUADS
  1857. || mode == GL_QUAD_STRIP
  1858. || mode == GL_POLYGON),
  1859. GL_INVALID_ENUM);
  1860. RETURN_WITH_ERROR_IF(count < 0, GL_INVALID_VALUE);
  1861. // At least the vertex array needs to be enabled
  1862. if (!m_client_side_vertex_array_enabled)
  1863. return;
  1864. auto last = first + count;
  1865. gl_begin(mode);
  1866. for (int i = first; i < last; i++) {
  1867. if (m_client_side_color_array_enabled) {
  1868. float color[4] { 0, 0, 0, 1 };
  1869. read_from_vertex_attribute_pointer(m_client_color_pointer, i, color, true);
  1870. gl_color(color[0], color[1], color[2], color[3]);
  1871. }
  1872. for (size_t t = 0; t < m_client_tex_coord_pointer.size(); ++t) {
  1873. if (m_client_side_texture_coord_array_enabled[t]) {
  1874. float tex_coords[4] { 0, 0, 0, 0 };
  1875. read_from_vertex_attribute_pointer(m_client_tex_coord_pointer[t], i, tex_coords, false);
  1876. gl_multi_tex_coord(GL_TEXTURE0 + t, tex_coords[0], tex_coords[1], tex_coords[2], tex_coords[3]);
  1877. }
  1878. }
  1879. if (m_client_side_normal_array_enabled) {
  1880. float normal[3];
  1881. read_from_vertex_attribute_pointer(m_client_normal_pointer, i, normal, false);
  1882. gl_normal(normal[0], normal[1], normal[2]);
  1883. }
  1884. float vertex[4] { 0, 0, 0, 1 };
  1885. read_from_vertex_attribute_pointer(m_client_vertex_pointer, i, vertex, false);
  1886. gl_vertex(vertex[0], vertex[1], vertex[2], vertex[3]);
  1887. }
  1888. gl_end();
  1889. }
  1890. void GLContext::gl_draw_elements(GLenum mode, GLsizei count, GLenum type, const void* indices)
  1891. {
  1892. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_draw_elements, mode, count, type, indices);
  1893. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  1894. // FIXME: Some modes are still missing (GL_POINTS, GL_LINE_STRIP, GL_LINE_LOOP, GL_LINES)
  1895. RETURN_WITH_ERROR_IF(!(mode == GL_TRIANGLE_STRIP
  1896. || mode == GL_TRIANGLE_FAN
  1897. || mode == GL_TRIANGLES
  1898. || mode == GL_QUADS
  1899. || mode == GL_QUAD_STRIP
  1900. || mode == GL_POLYGON),
  1901. GL_INVALID_ENUM);
  1902. RETURN_WITH_ERROR_IF(!(type == GL_UNSIGNED_BYTE
  1903. || type == GL_UNSIGNED_SHORT
  1904. || type == GL_UNSIGNED_INT),
  1905. GL_INVALID_ENUM);
  1906. RETURN_WITH_ERROR_IF(count < 0, GL_INVALID_VALUE);
  1907. // At least the vertex array needs to be enabled
  1908. if (!m_client_side_vertex_array_enabled)
  1909. return;
  1910. gl_begin(mode);
  1911. for (int index = 0; index < count; index++) {
  1912. int i = 0;
  1913. switch (type) {
  1914. case GL_UNSIGNED_BYTE:
  1915. i = reinterpret_cast<const GLubyte*>(indices)[index];
  1916. break;
  1917. case GL_UNSIGNED_SHORT:
  1918. i = reinterpret_cast<const GLushort*>(indices)[index];
  1919. break;
  1920. case GL_UNSIGNED_INT:
  1921. i = reinterpret_cast<const GLuint*>(indices)[index];
  1922. break;
  1923. }
  1924. if (m_client_side_color_array_enabled) {
  1925. float color[4] { 0, 0, 0, 1 };
  1926. read_from_vertex_attribute_pointer(m_client_color_pointer, i, color, true);
  1927. gl_color(color[0], color[1], color[2], color[3]);
  1928. }
  1929. for (size_t t = 0; t < m_client_tex_coord_pointer.size(); ++t) {
  1930. if (m_client_side_texture_coord_array_enabled[t]) {
  1931. float tex_coords[4] { 0, 0, 0, 0 };
  1932. read_from_vertex_attribute_pointer(m_client_tex_coord_pointer[t], i, tex_coords, false);
  1933. gl_multi_tex_coord(GL_TEXTURE0 + t, tex_coords[0], tex_coords[1], tex_coords[2], tex_coords[3]);
  1934. }
  1935. }
  1936. if (m_client_side_normal_array_enabled) {
  1937. float normal[3];
  1938. read_from_vertex_attribute_pointer(m_client_normal_pointer, i, normal, false);
  1939. gl_normal(normal[0], normal[1], normal[2]);
  1940. }
  1941. float vertex[4] { 0, 0, 0, 1 };
  1942. read_from_vertex_attribute_pointer(m_client_vertex_pointer, i, vertex, false);
  1943. gl_vertex(vertex[0], vertex[1], vertex[2], vertex[3]);
  1944. }
  1945. gl_end();
  1946. }
  1947. void GLContext::gl_draw_pixels(GLsizei width, GLsizei height, GLenum format, GLenum type, const void* data)
  1948. {
  1949. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_draw_pixels, width, height, format, type, data);
  1950. RETURN_WITH_ERROR_IF(format < GL_COLOR_INDEX || format > GL_BGRA, GL_INVALID_ENUM);
  1951. RETURN_WITH_ERROR_IF((type < GL_BYTE || type > GL_FLOAT)
  1952. && (type < GL_UNSIGNED_BYTE_3_3_2 || type > GL_UNSIGNED_INT_10_10_10_2)
  1953. && (type < GL_UNSIGNED_BYTE_2_3_3_REV || type > GL_UNSIGNED_INT_2_10_10_10_REV),
  1954. GL_INVALID_ENUM);
  1955. RETURN_WITH_ERROR_IF(type == GL_BITMAP && !(format == GL_COLOR_INDEX || format == GL_STENCIL_INDEX), GL_INVALID_ENUM);
  1956. RETURN_WITH_ERROR_IF(width < 0 || height < 0, GL_INVALID_VALUE);
  1957. // FIXME: GL_INVALID_OPERATION is generated if format is GL_STENCIL_INDEX and there is no stencil buffer
  1958. // FIXME: GL_INVALID_OPERATION is generated if format is GL_RED, GL_GREEN, GL_BLUE, GL_ALPHA, GL_RGB, GL_RGBA,
  1959. // GL_BGR, GL_BGRA, GL_LUMINANCE, or GL_LUMINANCE_ALPHA, and the GL is in color index mode
  1960. RETURN_WITH_ERROR_IF(format != GL_RGB
  1961. && (type == GL_UNSIGNED_BYTE_3_3_2
  1962. || type == GL_UNSIGNED_BYTE_2_3_3_REV
  1963. || type == GL_UNSIGNED_SHORT_5_6_5
  1964. || type == GL_UNSIGNED_SHORT_5_6_5_REV),
  1965. GL_INVALID_OPERATION);
  1966. RETURN_WITH_ERROR_IF(!(format == GL_RGBA || format == GL_BGRA)
  1967. && (type == GL_UNSIGNED_SHORT_4_4_4_4
  1968. || type == GL_UNSIGNED_SHORT_4_4_4_4_REV
  1969. || type == GL_UNSIGNED_SHORT_5_5_5_1
  1970. || type == GL_UNSIGNED_SHORT_1_5_5_5_REV
  1971. || type == GL_UNSIGNED_INT_8_8_8_8
  1972. || type == GL_UNSIGNED_INT_8_8_8_8_REV
  1973. || type == GL_UNSIGNED_INT_10_10_10_2
  1974. || type == GL_UNSIGNED_INT_2_10_10_10_REV),
  1975. GL_INVALID_OPERATION);
  1976. // FIXME: GL_INVALID_OPERATION is generated if a non-zero buffer object name is bound to the GL_PIXEL_UNPACK_BUFFER
  1977. // target and the buffer object's data store is currently mapped.
  1978. // FIXME: GL_INVALID_OPERATION is generated if a non-zero buffer object name is bound to the GL_PIXEL_UNPACK_BUFFER
  1979. // target and the data would be unpacked from the buffer object such that the memory reads required would
  1980. // exceed the data store size.
  1981. // FIXME: GL_INVALID_OPERATION is generated if a non-zero buffer object name is bound to the GL_PIXEL_UNPACK_BUFFER
  1982. // target and data is not evenly divisible into the number of bytes needed to store in memory a datum
  1983. // indicated by type.
  1984. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  1985. // FIXME: we only support RGBA + UNSIGNED_BYTE and DEPTH_COMPONENT + UNSIGNED_SHORT, implement all combinations!
  1986. if (!((format == GL_RGBA && type == GL_UNSIGNED_BYTE) || (format == GL_DEPTH_COMPONENT && type == GL_UNSIGNED_SHORT))) {
  1987. dbgln_if(GL_DEBUG, "gl_draw_pixels(): support for format {:#x} and/or type {:#x} not implemented", format, type);
  1988. return;
  1989. }
  1990. // FIXME: implement support for pixel parameters such as GL_UNPACK_ALIGNMENT
  1991. if (format == GL_RGBA) {
  1992. auto bitmap_or_error = Gfx::Bitmap::try_create(Gfx::BitmapFormat::BGRA8888, { width, height });
  1993. RETURN_WITH_ERROR_IF(bitmap_or_error.is_error(), GL_OUT_OF_MEMORY);
  1994. auto bitmap = bitmap_or_error.release_value();
  1995. auto pixel_data = static_cast<u32 const*>(data);
  1996. for (int y = 0; y < height; ++y)
  1997. for (int x = 0; x < width; ++x)
  1998. bitmap->set_pixel(x, y, Color::from_argb(*(pixel_data++)));
  1999. m_rasterizer.blit_to_color_buffer_at_raster_position(bitmap);
  2000. } else if (format == GL_DEPTH_COMPONENT) {
  2001. Vector<float> depth_values;
  2002. depth_values.ensure_capacity(width * height);
  2003. auto depth_data = static_cast<u16 const*>(data);
  2004. for (int y = 0; y < height; ++y) {
  2005. for (int x = 0; x < width; ++x) {
  2006. auto u16_value = *(depth_data++);
  2007. auto float_value = static_cast<float>(u16_value) / NumericLimits<u16>::max();
  2008. depth_values.append(float_value);
  2009. }
  2010. }
  2011. m_rasterizer.blit_to_depth_buffer_at_raster_position(depth_values, width, height);
  2012. } else {
  2013. VERIFY_NOT_REACHED();
  2014. }
  2015. }
  2016. void GLContext::gl_depth_range(GLdouble min, GLdouble max)
  2017. {
  2018. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_depth_range, min, max);
  2019. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  2020. auto options = m_rasterizer.options();
  2021. options.depth_min = clamp<float>(min, 0.f, 1.f);
  2022. options.depth_max = clamp<float>(max, 0.f, 1.f);
  2023. m_rasterizer.set_options(options);
  2024. }
  2025. void GLContext::gl_depth_func(GLenum func)
  2026. {
  2027. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_depth_func, func);
  2028. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  2029. RETURN_WITH_ERROR_IF(!(func == GL_NEVER
  2030. || func == GL_LESS
  2031. || func == GL_EQUAL
  2032. || func == GL_LEQUAL
  2033. || func == GL_GREATER
  2034. || func == GL_NOTEQUAL
  2035. || func == GL_GEQUAL
  2036. || func == GL_ALWAYS),
  2037. GL_INVALID_ENUM);
  2038. auto options = m_rasterizer.options();
  2039. switch (func) {
  2040. case GL_NEVER:
  2041. options.depth_func = SoftGPU::DepthTestFunction::Never;
  2042. break;
  2043. case GL_ALWAYS:
  2044. options.depth_func = SoftGPU::DepthTestFunction::Always;
  2045. break;
  2046. case GL_LESS:
  2047. options.depth_func = SoftGPU::DepthTestFunction::Less;
  2048. break;
  2049. case GL_LEQUAL:
  2050. options.depth_func = SoftGPU::DepthTestFunction::LessOrEqual;
  2051. break;
  2052. case GL_EQUAL:
  2053. options.depth_func = SoftGPU::DepthTestFunction::Equal;
  2054. break;
  2055. case GL_NOTEQUAL:
  2056. options.depth_func = SoftGPU::DepthTestFunction::NotEqual;
  2057. break;
  2058. case GL_GEQUAL:
  2059. options.depth_func = SoftGPU::DepthTestFunction::GreaterOrEqual;
  2060. break;
  2061. case GL_GREATER:
  2062. options.depth_func = SoftGPU::DepthTestFunction::Greater;
  2063. break;
  2064. default:
  2065. VERIFY_NOT_REACHED();
  2066. }
  2067. m_rasterizer.set_options(options);
  2068. }
  2069. // General helper function to read arbitrary vertex attribute data into a float array
  2070. void GLContext::read_from_vertex_attribute_pointer(VertexAttribPointer const& attrib, int index, float* elements, bool normalize)
  2071. {
  2072. auto byte_ptr = reinterpret_cast<const char*>(attrib.pointer);
  2073. size_t stride = attrib.stride;
  2074. switch (attrib.type) {
  2075. case GL_BYTE: {
  2076. if (stride == 0)
  2077. stride = sizeof(GLbyte) * attrib.size;
  2078. for (int i = 0; i < attrib.size; i++) {
  2079. elements[i] = *(reinterpret_cast<const GLbyte*>(byte_ptr + stride * index) + i);
  2080. if (normalize)
  2081. elements[i] /= 0x80;
  2082. }
  2083. break;
  2084. }
  2085. case GL_UNSIGNED_BYTE: {
  2086. if (stride == 0)
  2087. stride = sizeof(GLubyte) * attrib.size;
  2088. for (int i = 0; i < attrib.size; i++) {
  2089. elements[i] = *(reinterpret_cast<const GLubyte*>(byte_ptr + stride * index) + i);
  2090. if (normalize)
  2091. elements[i] /= 0xff;
  2092. }
  2093. break;
  2094. }
  2095. case GL_SHORT: {
  2096. if (stride == 0)
  2097. stride = sizeof(GLshort) * attrib.size;
  2098. for (int i = 0; i < attrib.size; i++) {
  2099. elements[i] = *(reinterpret_cast<const GLshort*>(byte_ptr + stride * index) + i);
  2100. if (normalize)
  2101. elements[i] /= 0x8000;
  2102. }
  2103. break;
  2104. }
  2105. case GL_UNSIGNED_SHORT: {
  2106. if (stride == 0)
  2107. stride = sizeof(GLushort) * attrib.size;
  2108. for (int i = 0; i < attrib.size; i++) {
  2109. elements[i] = *(reinterpret_cast<const GLushort*>(byte_ptr + stride * index) + i);
  2110. if (normalize)
  2111. elements[i] /= 0xffff;
  2112. }
  2113. break;
  2114. }
  2115. case GL_INT: {
  2116. if (stride == 0)
  2117. stride = sizeof(GLint) * attrib.size;
  2118. for (int i = 0; i < attrib.size; i++) {
  2119. elements[i] = *(reinterpret_cast<const GLint*>(byte_ptr + stride * index) + i);
  2120. if (normalize)
  2121. elements[i] /= 0x80000000;
  2122. }
  2123. break;
  2124. }
  2125. case GL_UNSIGNED_INT: {
  2126. if (stride == 0)
  2127. stride = sizeof(GLuint) * attrib.size;
  2128. for (int i = 0; i < attrib.size; i++) {
  2129. elements[i] = *(reinterpret_cast<const GLuint*>(byte_ptr + stride * index) + i);
  2130. if (normalize)
  2131. elements[i] /= 0xffffffff;
  2132. }
  2133. break;
  2134. }
  2135. case GL_FLOAT: {
  2136. if (stride == 0)
  2137. stride = sizeof(GLfloat) * attrib.size;
  2138. for (int i = 0; i < attrib.size; i++)
  2139. elements[i] = *(reinterpret_cast<const GLfloat*>(byte_ptr + stride * index) + i);
  2140. break;
  2141. }
  2142. case GL_DOUBLE: {
  2143. if (stride == 0)
  2144. stride = sizeof(GLdouble) * attrib.size;
  2145. for (int i = 0; i < attrib.size; i++)
  2146. elements[i] = static_cast<float>(*(reinterpret_cast<const GLdouble*>(byte_ptr + stride * index) + i));
  2147. break;
  2148. }
  2149. }
  2150. }
  2151. void GLContext::gl_color_mask(GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha)
  2152. {
  2153. auto options = m_rasterizer.options();
  2154. auto mask = options.color_mask;
  2155. if (!red)
  2156. mask &= ~0x000000ff;
  2157. else
  2158. mask |= 0x000000ff;
  2159. if (!green)
  2160. mask &= ~0x0000ff00;
  2161. else
  2162. mask |= 0x0000ff00;
  2163. if (!blue)
  2164. mask &= ~0x00ff0000;
  2165. else
  2166. mask |= 0x00ff0000;
  2167. if (!alpha)
  2168. mask &= ~0xff000000;
  2169. else
  2170. mask |= 0xff000000;
  2171. options.color_mask = mask;
  2172. m_rasterizer.set_options(options);
  2173. }
  2174. void GLContext::gl_polygon_mode(GLenum face, GLenum mode)
  2175. {
  2176. RETURN_WITH_ERROR_IF(!(face == GL_BACK || face == GL_FRONT || face == GL_FRONT_AND_BACK), GL_INVALID_ENUM);
  2177. RETURN_WITH_ERROR_IF(!(mode == GL_POINT || mode == GL_LINE || mode == GL_FILL), GL_INVALID_ENUM);
  2178. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  2179. auto options = m_rasterizer.options();
  2180. // FIXME: This must support different polygon modes for front- and backside
  2181. if (face == GL_BACK) {
  2182. dbgln_if(GL_DEBUG, "gl_polygon_mode(GL_BACK, {:#x}): unimplemented", mode);
  2183. return;
  2184. }
  2185. auto map_mode = [](GLenum mode) -> SoftGPU::PolygonMode {
  2186. switch (mode) {
  2187. case GL_FILL:
  2188. return SoftGPU::PolygonMode::Fill;
  2189. case GL_LINE:
  2190. return SoftGPU::PolygonMode::Line;
  2191. case GL_POINT:
  2192. return SoftGPU::PolygonMode::Point;
  2193. default:
  2194. VERIFY_NOT_REACHED();
  2195. }
  2196. };
  2197. options.polygon_mode = map_mode(mode);
  2198. m_rasterizer.set_options(options);
  2199. }
  2200. void GLContext::gl_polygon_offset(GLfloat factor, GLfloat units)
  2201. {
  2202. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_polygon_offset, factor, units);
  2203. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  2204. auto rasterizer_options = m_rasterizer.options();
  2205. rasterizer_options.depth_offset_factor = factor;
  2206. rasterizer_options.depth_offset_constant = units;
  2207. m_rasterizer.set_options(rasterizer_options);
  2208. }
  2209. void GLContext::gl_fogfv(GLenum pname, GLfloat* params)
  2210. {
  2211. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_fogfv, pname, params);
  2212. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  2213. auto options = m_rasterizer.options();
  2214. switch (pname) {
  2215. case GL_FOG_COLOR:
  2216. options.fog_color = { params[0], params[1], params[2], params[3] };
  2217. break;
  2218. default:
  2219. RETURN_WITH_ERROR_IF(true, GL_INVALID_ENUM);
  2220. }
  2221. m_rasterizer.set_options(options);
  2222. }
  2223. void GLContext::gl_fogf(GLenum pname, GLfloat param)
  2224. {
  2225. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_fogf, pname, param);
  2226. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  2227. RETURN_WITH_ERROR_IF(param < 0.0f, GL_INVALID_VALUE);
  2228. auto options = m_rasterizer.options();
  2229. switch (pname) {
  2230. case GL_FOG_DENSITY:
  2231. options.fog_density = param;
  2232. break;
  2233. case GL_FOG_END:
  2234. options.fog_end = param;
  2235. break;
  2236. case GL_FOG_START:
  2237. options.fog_start = param;
  2238. break;
  2239. default:
  2240. RETURN_WITH_ERROR_IF(true, GL_INVALID_ENUM);
  2241. }
  2242. m_rasterizer.set_options(options);
  2243. }
  2244. void GLContext::gl_fogi(GLenum pname, GLint param)
  2245. {
  2246. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_fogi, pname, param);
  2247. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  2248. RETURN_WITH_ERROR_IF(param != GL_LINEAR && param != GL_EXP && param != GL_EXP2, GL_INVALID_ENUM);
  2249. auto options = m_rasterizer.options();
  2250. switch (pname) {
  2251. case GL_FOG_MODE:
  2252. switch (param) {
  2253. case GL_LINEAR:
  2254. options.fog_mode = SoftGPU::FogMode::Linear;
  2255. break;
  2256. case GL_EXP:
  2257. options.fog_mode = SoftGPU::FogMode::Exp;
  2258. break;
  2259. case GL_EXP2:
  2260. options.fog_mode = SoftGPU::FogMode::Exp2;
  2261. break;
  2262. }
  2263. break;
  2264. default:
  2265. RETURN_WITH_ERROR_IF(true, GL_INVALID_ENUM);
  2266. }
  2267. m_rasterizer.set_options(options);
  2268. }
  2269. void GLContext::gl_pixel_storei(GLenum pname, GLint param)
  2270. {
  2271. // FIXME: Implement missing parameters
  2272. switch (pname) {
  2273. case GL_PACK_ALIGNMENT:
  2274. RETURN_WITH_ERROR_IF(param != 1 && param != 2 && param != 4 && param != 8, GL_INVALID_VALUE);
  2275. m_pack_alignment = param;
  2276. break;
  2277. case GL_UNPACK_ROW_LENGTH:
  2278. RETURN_WITH_ERROR_IF(param < 0, GL_INVALID_VALUE);
  2279. m_unpack_row_length = static_cast<size_t>(param);
  2280. break;
  2281. case GL_UNPACK_ALIGNMENT:
  2282. RETURN_WITH_ERROR_IF(param != 1 && param != 2 && param != 4 && param != 8, GL_INVALID_VALUE);
  2283. m_unpack_alignment = param;
  2284. break;
  2285. default:
  2286. RETURN_WITH_ERROR_IF(true, GL_INVALID_ENUM);
  2287. break;
  2288. }
  2289. }
  2290. void GLContext::gl_scissor(GLint x, GLint y, GLsizei width, GLsizei height)
  2291. {
  2292. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_scissor, x, y, width, height);
  2293. RETURN_WITH_ERROR_IF(width < 0 || height < 0, GL_INVALID_VALUE);
  2294. auto options = m_rasterizer.options();
  2295. options.scissor_box = { x, y, width, height };
  2296. m_rasterizer.set_options(options);
  2297. }
  2298. void GLContext::gl_stencil_func_separate(GLenum face, GLenum func, GLint ref, GLuint mask)
  2299. {
  2300. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_stencil_func_separate, face, func, ref, mask);
  2301. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  2302. RETURN_WITH_ERROR_IF(!(face == GL_FRONT || face == GL_BACK || face == GL_FRONT_AND_BACK), GL_INVALID_ENUM);
  2303. RETURN_WITH_ERROR_IF(!(func == GL_NEVER
  2304. || func == GL_LESS
  2305. || func == GL_LEQUAL
  2306. || func == GL_GREATER
  2307. || func == GL_GEQUAL
  2308. || func == GL_EQUAL
  2309. || func == GL_NOTEQUAL
  2310. || func == GL_ALWAYS),
  2311. GL_INVALID_ENUM);
  2312. ref = clamp(ref, 0, (1 << m_device_info.stencil_bits) - 1);
  2313. StencilFunctionOptions new_options = { func, ref, mask };
  2314. if (face == GL_FRONT || face == GL_FRONT_AND_BACK)
  2315. m_stencil_function[Face::Front] = new_options;
  2316. if (face == GL_BACK || face == GL_FRONT_AND_BACK)
  2317. m_stencil_function[Face::Back] = new_options;
  2318. m_stencil_configuration_dirty = true;
  2319. }
  2320. void GLContext::gl_stencil_mask_separate(GLenum face, GLuint mask)
  2321. {
  2322. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_stencil_mask_separate, face, mask);
  2323. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  2324. if (face == GL_FRONT || face == GL_FRONT_AND_BACK)
  2325. m_stencil_operation[Face::Front].write_mask = mask;
  2326. if (face == GL_BACK || face == GL_FRONT_AND_BACK)
  2327. m_stencil_operation[Face::Back].write_mask = mask;
  2328. m_stencil_configuration_dirty = true;
  2329. }
  2330. void GLContext::gl_stencil_op_separate(GLenum face, GLenum sfail, GLenum dpfail, GLenum dppass)
  2331. {
  2332. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_stencil_op_separate, face, sfail, dpfail, dppass);
  2333. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  2334. RETURN_WITH_ERROR_IF(!(face == GL_FRONT || face == GL_BACK || face == GL_FRONT_AND_BACK), GL_INVALID_ENUM);
  2335. auto is_valid_op = [](GLenum op) -> bool {
  2336. return op == GL_KEEP || op == GL_ZERO || op == GL_REPLACE || op == GL_INCR || op == GL_INCR_WRAP
  2337. || op == GL_DECR || op == GL_DECR_WRAP || op == GL_INVERT;
  2338. };
  2339. RETURN_WITH_ERROR_IF(!is_valid_op(sfail), GL_INVALID_ENUM);
  2340. RETURN_WITH_ERROR_IF(!is_valid_op(dpfail), GL_INVALID_ENUM);
  2341. RETURN_WITH_ERROR_IF(!is_valid_op(dppass), GL_INVALID_ENUM);
  2342. auto update_stencil_operation = [&](Face face, GLenum sfail, GLenum dpfail, GLenum dppass) {
  2343. auto& stencil_operation = m_stencil_operation[face];
  2344. stencil_operation.op_fail = sfail;
  2345. stencil_operation.op_depth_fail = dpfail;
  2346. stencil_operation.op_pass = dppass;
  2347. };
  2348. if (face == GL_FRONT || face == GL_FRONT_AND_BACK)
  2349. update_stencil_operation(Face::Front, sfail, dpfail, dppass);
  2350. if (face == GL_BACK || face == GL_FRONT_AND_BACK)
  2351. update_stencil_operation(Face::Back, sfail, dpfail, dppass);
  2352. m_stencil_configuration_dirty = true;
  2353. }
  2354. void GLContext::gl_normal(GLfloat nx, GLfloat ny, GLfloat nz)
  2355. {
  2356. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_normal, nx, ny, nz);
  2357. m_current_vertex_normal = { nx, ny, nz };
  2358. }
  2359. void GLContext::gl_raster_pos(GLfloat x, GLfloat y, GLfloat z, GLfloat w)
  2360. {
  2361. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_raster_pos, x, y, z, w);
  2362. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  2363. m_rasterizer.set_raster_position({ x, y, z, w }, m_model_view_matrix, m_projection_matrix);
  2364. }
  2365. void GLContext::gl_line_width(GLfloat width)
  2366. {
  2367. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_line_width, width);
  2368. RETURN_WITH_ERROR_IF(width <= 0, GL_INVALID_VALUE);
  2369. m_line_width = width;
  2370. }
  2371. void GLContext::gl_push_attrib(GLbitfield mask)
  2372. {
  2373. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_push_attrib, mask);
  2374. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  2375. // FIXME: implement
  2376. dbgln_if(GL_DEBUG, "GLContext FIXME: implement gl_push_attrib({})", mask);
  2377. }
  2378. void GLContext::gl_pop_attrib()
  2379. {
  2380. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_pop_attrib);
  2381. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  2382. // FIXME: implement
  2383. dbgln_if(GL_DEBUG, "GLContext FIXME: implement gl_pop_attrib()");
  2384. }
  2385. void GLContext::gl_light_model(GLenum pname, GLfloat x, GLfloat y, GLfloat z, GLfloat w)
  2386. {
  2387. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_light_model, pname, x, y, z, w);
  2388. RETURN_WITH_ERROR_IF(pname != GL_LIGHT_MODEL_LOCAL_VIEWER
  2389. && pname != GL_LIGHT_MODEL_TWO_SIDE
  2390. && pname != GL_LIGHT_MODEL_AMBIENT,
  2391. GL_INVALID_ENUM);
  2392. auto lighting_params = m_rasterizer.light_model();
  2393. bool update_lighting_model = false;
  2394. switch (pname) {
  2395. case GL_LIGHT_MODEL_AMBIENT:
  2396. lighting_params.scene_ambient_color = { x, y, z, w };
  2397. update_lighting_model = true;
  2398. break;
  2399. case GL_LIGHT_MODEL_TWO_SIDE:
  2400. VERIFY(y == 0.0f && z == 0.0f && w == 0.0f);
  2401. lighting_params.two_sided_lighting = x;
  2402. update_lighting_model = true;
  2403. break;
  2404. case GL_LIGHT_MODEL_LOCAL_VIEWER:
  2405. // 0 means the viewer is at infinity
  2406. // 1 means they're in local (eye) space
  2407. lighting_params.viewer_at_infinity = (x != 1.0f);
  2408. update_lighting_model = true;
  2409. break;
  2410. default:
  2411. VERIFY_NOT_REACHED();
  2412. }
  2413. if (update_lighting_model)
  2414. m_rasterizer.set_light_model_params(lighting_params);
  2415. }
  2416. void GLContext::gl_bitmap(GLsizei width, GLsizei height, GLfloat xorig, GLfloat yorig, GLfloat xmove, GLfloat ymove, GLubyte const* bitmap)
  2417. {
  2418. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_bitmap, width, height, xorig, yorig, xmove, ymove, bitmap);
  2419. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  2420. if (bitmap != nullptr) {
  2421. // FIXME: implement
  2422. dbgln_if(GL_DEBUG, "gl_bitmap({}, {}, {}, {}, {}, {}, {}): unimplemented", width, height, xorig, yorig, xmove, ymove, bitmap);
  2423. }
  2424. auto raster_position = m_rasterizer.raster_position();
  2425. raster_position.window_coordinates += { xmove, ymove, 0.f, 0.f };
  2426. m_rasterizer.set_raster_position(raster_position);
  2427. }
  2428. void GLContext::gl_copy_tex_image_2d(GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border)
  2429. {
  2430. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_copy_tex_image_2d, target, level, internalformat, x, y, width, height, border);
  2431. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  2432. // FIXME: implement
  2433. dbgln_if(GL_DEBUG, "GLContext FIXME: implement gl_copy_tex_image_2d({:#x}, {}, {:#x}, {}, {}, {}, {}, {})",
  2434. target, level, internalformat, x, y, width, height, border);
  2435. }
  2436. void GLContext::gl_get_tex_parameter_integerv(GLenum target, GLint level, GLenum pname, GLint* params)
  2437. {
  2438. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  2439. // FIXME: support targets other than GL_TEXTURE_2D
  2440. RETURN_WITH_ERROR_IF(target != GL_TEXTURE_2D, GL_INVALID_ENUM);
  2441. // FIXME: support other parameter names
  2442. RETURN_WITH_ERROR_IF(pname < GL_TEXTURE_WIDTH || pname > GL_TEXTURE_HEIGHT, GL_INVALID_ENUM);
  2443. RETURN_WITH_ERROR_IF(level < 0 || level > Texture2D::LOG2_MAX_TEXTURE_SIZE, GL_INVALID_VALUE);
  2444. // FIXME: GL_INVALID_VALUE is generated if target is GL_TEXTURE_BUFFER and level is not zero
  2445. // FIXME: GL_INVALID_OPERATION is generated if GL_TEXTURE_COMPRESSED_IMAGE_SIZE is queried on texture images with an uncompressed internal format or on proxy targets
  2446. VERIFY(!m_active_texture_unit->texture_2d_target_texture().is_null());
  2447. auto const texture_2d = m_active_texture_unit->texture_2d_target_texture();
  2448. switch (pname) {
  2449. case GL_TEXTURE_HEIGHT:
  2450. *params = texture_2d->height_at_lod(level);
  2451. break;
  2452. case GL_TEXTURE_WIDTH:
  2453. *params = texture_2d->width_at_lod(level);
  2454. break;
  2455. }
  2456. }
  2457. void GLContext::gl_rect(GLdouble x1, GLdouble y1, GLdouble x2, GLdouble y2)
  2458. {
  2459. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_rect, x1, y1, x2, y2);
  2460. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  2461. gl_begin(GL_POLYGON);
  2462. gl_vertex(x1, y1, 0.0, 0.0);
  2463. gl_vertex(x2, y1, 0.0, 0.0);
  2464. gl_vertex(x2, y2, 0.0, 0.0);
  2465. gl_vertex(x1, y2, 0.0, 0.0);
  2466. gl_end();
  2467. }
  2468. void GLContext::gl_tex_gen(GLenum coord, GLenum pname, GLint param)
  2469. {
  2470. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_tex_gen, coord, pname, param);
  2471. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  2472. RETURN_WITH_ERROR_IF(coord < GL_S || coord > GL_Q, GL_INVALID_ENUM);
  2473. RETURN_WITH_ERROR_IF(pname != GL_TEXTURE_GEN_MODE, GL_INVALID_ENUM);
  2474. RETURN_WITH_ERROR_IF(param != GL_EYE_LINEAR
  2475. && param != GL_OBJECT_LINEAR
  2476. && param != GL_SPHERE_MAP
  2477. && param != GL_NORMAL_MAP
  2478. && param != GL_REFLECTION_MAP,
  2479. GL_INVALID_ENUM);
  2480. RETURN_WITH_ERROR_IF((coord == GL_R || coord == GL_Q) && param == GL_SPHERE_MAP, GL_INVALID_ENUM);
  2481. RETURN_WITH_ERROR_IF(coord == GL_Q && (param == GL_REFLECTION_MAP || param == GL_NORMAL_MAP), GL_INVALID_ENUM);
  2482. GLenum const capability = GL_TEXTURE_GEN_S + (coord - GL_S);
  2483. texture_coordinate_generation(m_active_texture_unit_index, capability).generation_mode = param;
  2484. m_texcoord_generation_dirty = true;
  2485. }
  2486. void GLContext::gl_tex_gen_floatv(GLenum coord, GLenum pname, GLfloat const* params)
  2487. {
  2488. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_tex_gen_floatv, coord, pname, params);
  2489. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  2490. RETURN_WITH_ERROR_IF(coord < GL_S || coord > GL_Q, GL_INVALID_ENUM);
  2491. RETURN_WITH_ERROR_IF(pname != GL_TEXTURE_GEN_MODE
  2492. && pname != GL_OBJECT_PLANE
  2493. && pname != GL_EYE_PLANE,
  2494. GL_INVALID_ENUM);
  2495. GLenum const capability = GL_TEXTURE_GEN_S + (coord - GL_S);
  2496. switch (pname) {
  2497. case GL_TEXTURE_GEN_MODE: {
  2498. auto param = static_cast<GLenum>(params[0]);
  2499. RETURN_WITH_ERROR_IF(param != GL_EYE_LINEAR
  2500. && param != GL_OBJECT_LINEAR
  2501. && param != GL_SPHERE_MAP
  2502. && param != GL_NORMAL_MAP
  2503. && param != GL_REFLECTION_MAP,
  2504. GL_INVALID_ENUM);
  2505. RETURN_WITH_ERROR_IF((coord == GL_R || coord == GL_Q) && param == GL_SPHERE_MAP, GL_INVALID_ENUM);
  2506. RETURN_WITH_ERROR_IF(coord == GL_Q && (param == GL_REFLECTION_MAP || param == GL_NORMAL_MAP), GL_INVALID_ENUM);
  2507. texture_coordinate_generation(m_active_texture_unit_index, capability).generation_mode = param;
  2508. break;
  2509. }
  2510. case GL_OBJECT_PLANE:
  2511. texture_coordinate_generation(m_active_texture_unit_index, capability).object_plane_coefficients = { params[0], params[1], params[2], params[3] };
  2512. break;
  2513. case GL_EYE_PLANE: {
  2514. auto const& inverse_model_view = m_model_view_matrix.inverse();
  2515. auto input_coefficients = FloatVector4 { params[0], params[1], params[2], params[3] };
  2516. // Note: we are allowed to store transformed coefficients here, according to the documentation on
  2517. // `glGetTexGen`:
  2518. //
  2519. // "The returned values are those maintained in eye coordinates. They are not equal to the values
  2520. // specified using glTexGen, unless the modelview matrix was identity when glTexGen was called."
  2521. texture_coordinate_generation(m_active_texture_unit_index, capability).eye_plane_coefficients = inverse_model_view * input_coefficients;
  2522. break;
  2523. }
  2524. default:
  2525. VERIFY_NOT_REACHED();
  2526. }
  2527. m_texcoord_generation_dirty = true;
  2528. }
  2529. void GLContext::present()
  2530. {
  2531. m_rasterizer.blit_color_buffer_to(*m_frontbuffer);
  2532. }
  2533. void GLContext::sync_device_config()
  2534. {
  2535. sync_device_sampler_config();
  2536. sync_device_texcoord_config();
  2537. sync_light_state();
  2538. sync_stencil_configuration();
  2539. }
  2540. void GLContext::sync_device_sampler_config()
  2541. {
  2542. if (!m_sampler_config_is_dirty)
  2543. return;
  2544. m_sampler_config_is_dirty = false;
  2545. for (unsigned i = 0; i < m_texture_units.size(); ++i) {
  2546. auto const& texture_unit = m_texture_units[i];
  2547. if (!texture_unit.texture_2d_enabled())
  2548. continue;
  2549. SoftGPU::SamplerConfig config;
  2550. auto texture_2d = texture_unit.texture_2d_target_texture();
  2551. if (texture_2d.is_null()) {
  2552. config.bound_image = nullptr;
  2553. m_rasterizer.set_sampler_config(i, config);
  2554. continue;
  2555. }
  2556. config.bound_image = texture_2d->device_image();
  2557. auto const& sampler = texture_2d->sampler();
  2558. switch (sampler.min_filter()) {
  2559. case GL_NEAREST:
  2560. config.texture_min_filter = SoftGPU::TextureFilter::Nearest;
  2561. config.mipmap_filter = SoftGPU::MipMapFilter::None;
  2562. break;
  2563. case GL_LINEAR:
  2564. config.texture_min_filter = SoftGPU::TextureFilter::Linear;
  2565. config.mipmap_filter = SoftGPU::MipMapFilter::None;
  2566. break;
  2567. case GL_NEAREST_MIPMAP_NEAREST:
  2568. config.texture_min_filter = SoftGPU::TextureFilter::Nearest;
  2569. config.mipmap_filter = SoftGPU::MipMapFilter::Nearest;
  2570. break;
  2571. case GL_LINEAR_MIPMAP_NEAREST:
  2572. config.texture_min_filter = SoftGPU::TextureFilter::Linear;
  2573. config.mipmap_filter = SoftGPU::MipMapFilter::Nearest;
  2574. break;
  2575. case GL_NEAREST_MIPMAP_LINEAR:
  2576. config.texture_min_filter = SoftGPU::TextureFilter::Nearest;
  2577. config.mipmap_filter = SoftGPU::MipMapFilter::Linear;
  2578. break;
  2579. case GL_LINEAR_MIPMAP_LINEAR:
  2580. config.texture_min_filter = SoftGPU::TextureFilter::Linear;
  2581. config.mipmap_filter = SoftGPU::MipMapFilter::Linear;
  2582. break;
  2583. default:
  2584. VERIFY_NOT_REACHED();
  2585. }
  2586. switch (sampler.mag_filter()) {
  2587. case GL_NEAREST:
  2588. config.texture_mag_filter = SoftGPU::TextureFilter::Nearest;
  2589. break;
  2590. case GL_LINEAR:
  2591. config.texture_mag_filter = SoftGPU::TextureFilter::Linear;
  2592. break;
  2593. default:
  2594. VERIFY_NOT_REACHED();
  2595. }
  2596. switch (sampler.wrap_s_mode()) {
  2597. case GL_CLAMP:
  2598. config.texture_wrap_u = SoftGPU::TextureWrapMode::Clamp;
  2599. break;
  2600. case GL_CLAMP_TO_BORDER:
  2601. config.texture_wrap_u = SoftGPU::TextureWrapMode::ClampToBorder;
  2602. break;
  2603. case GL_CLAMP_TO_EDGE:
  2604. config.texture_wrap_u = SoftGPU::TextureWrapMode::ClampToEdge;
  2605. break;
  2606. case GL_REPEAT:
  2607. config.texture_wrap_u = SoftGPU::TextureWrapMode::Repeat;
  2608. break;
  2609. case GL_MIRRORED_REPEAT:
  2610. config.texture_wrap_u = SoftGPU::TextureWrapMode::MirroredRepeat;
  2611. break;
  2612. default:
  2613. VERIFY_NOT_REACHED();
  2614. }
  2615. switch (sampler.wrap_t_mode()) {
  2616. case GL_CLAMP:
  2617. config.texture_wrap_v = SoftGPU::TextureWrapMode::Clamp;
  2618. break;
  2619. case GL_CLAMP_TO_BORDER:
  2620. config.texture_wrap_v = SoftGPU::TextureWrapMode::ClampToBorder;
  2621. break;
  2622. case GL_CLAMP_TO_EDGE:
  2623. config.texture_wrap_v = SoftGPU::TextureWrapMode::ClampToEdge;
  2624. break;
  2625. case GL_REPEAT:
  2626. config.texture_wrap_v = SoftGPU::TextureWrapMode::Repeat;
  2627. break;
  2628. case GL_MIRRORED_REPEAT:
  2629. config.texture_wrap_v = SoftGPU::TextureWrapMode::MirroredRepeat;
  2630. break;
  2631. default:
  2632. VERIFY_NOT_REACHED();
  2633. }
  2634. switch (texture_unit.env_mode()) {
  2635. case GL_MODULATE:
  2636. config.fixed_function_texture_env_mode = SoftGPU::TextureEnvMode::Modulate;
  2637. break;
  2638. case GL_REPLACE:
  2639. config.fixed_function_texture_env_mode = SoftGPU::TextureEnvMode::Replace;
  2640. break;
  2641. case GL_DECAL:
  2642. config.fixed_function_texture_env_mode = SoftGPU::TextureEnvMode::Decal;
  2643. break;
  2644. default:
  2645. VERIFY_NOT_REACHED();
  2646. }
  2647. m_rasterizer.set_sampler_config(i, config);
  2648. }
  2649. }
  2650. void GLContext::sync_light_state()
  2651. {
  2652. if (!m_light_state_is_dirty)
  2653. return;
  2654. m_light_state_is_dirty = false;
  2655. auto options = m_rasterizer.options();
  2656. options.color_material_enabled = m_color_material_enabled;
  2657. switch (m_color_material_face) {
  2658. case GL_BACK:
  2659. options.color_material_face = SoftGPU::ColorMaterialFace::Back;
  2660. break;
  2661. case GL_FRONT:
  2662. options.color_material_face = SoftGPU::ColorMaterialFace::Front;
  2663. break;
  2664. case GL_FRONT_AND_BACK:
  2665. options.color_material_face = SoftGPU::ColorMaterialFace::FrontAndBack;
  2666. break;
  2667. default:
  2668. VERIFY_NOT_REACHED();
  2669. }
  2670. switch (m_color_material_mode) {
  2671. case GL_AMBIENT:
  2672. options.color_material_mode = SoftGPU::ColorMaterialMode::Ambient;
  2673. break;
  2674. case GL_AMBIENT_AND_DIFFUSE:
  2675. options.color_material_mode = SoftGPU::ColorMaterialMode::Ambient;
  2676. options.color_material_mode = SoftGPU::ColorMaterialMode::Diffuse;
  2677. break;
  2678. case GL_DIFFUSE:
  2679. options.color_material_mode = SoftGPU::ColorMaterialMode::Diffuse;
  2680. break;
  2681. case GL_EMISSION:
  2682. options.color_material_mode = SoftGPU::ColorMaterialMode::Emissive;
  2683. break;
  2684. case GL_SPECULAR:
  2685. options.color_material_mode = SoftGPU::ColorMaterialMode::Specular;
  2686. break;
  2687. default:
  2688. VERIFY_NOT_REACHED();
  2689. }
  2690. m_rasterizer.set_options(options);
  2691. for (auto light_id = 0u; light_id < SoftGPU::NUM_LIGHTS; light_id++) {
  2692. auto const& current_light_state = m_light_states.at(light_id);
  2693. m_rasterizer.set_light_state(light_id, current_light_state);
  2694. }
  2695. m_rasterizer.set_material_state(SoftGPU::Face::Front, m_material_states[Face::Front]);
  2696. m_rasterizer.set_material_state(SoftGPU::Face::Back, m_material_states[Face::Back]);
  2697. }
  2698. void GLContext::sync_device_texcoord_config()
  2699. {
  2700. if (!m_texcoord_generation_dirty)
  2701. return;
  2702. m_texcoord_generation_dirty = false;
  2703. auto options = m_rasterizer.options();
  2704. for (size_t i = 0; i < m_device_info.num_texture_units; ++i) {
  2705. u8 enabled_coordinates = SoftGPU::TexCoordGenerationCoordinate::None;
  2706. for (GLenum capability = GL_TEXTURE_GEN_S; capability <= GL_TEXTURE_GEN_Q; ++capability) {
  2707. auto const context_coordinate_config = texture_coordinate_generation(i, capability);
  2708. if (!context_coordinate_config.enabled)
  2709. continue;
  2710. SoftGPU::TexCoordGenerationConfig* texcoord_generation_config;
  2711. switch (capability) {
  2712. case GL_TEXTURE_GEN_S:
  2713. enabled_coordinates |= SoftGPU::TexCoordGenerationCoordinate::S;
  2714. texcoord_generation_config = &options.texcoord_generation_config[i][0];
  2715. break;
  2716. case GL_TEXTURE_GEN_T:
  2717. enabled_coordinates |= SoftGPU::TexCoordGenerationCoordinate::T;
  2718. texcoord_generation_config = &options.texcoord_generation_config[i][1];
  2719. break;
  2720. case GL_TEXTURE_GEN_R:
  2721. enabled_coordinates |= SoftGPU::TexCoordGenerationCoordinate::R;
  2722. texcoord_generation_config = &options.texcoord_generation_config[i][2];
  2723. break;
  2724. case GL_TEXTURE_GEN_Q:
  2725. enabled_coordinates |= SoftGPU::TexCoordGenerationCoordinate::Q;
  2726. texcoord_generation_config = &options.texcoord_generation_config[i][3];
  2727. break;
  2728. default:
  2729. VERIFY_NOT_REACHED();
  2730. }
  2731. switch (context_coordinate_config.generation_mode) {
  2732. case GL_OBJECT_LINEAR:
  2733. texcoord_generation_config->mode = SoftGPU::TexCoordGenerationMode::ObjectLinear;
  2734. texcoord_generation_config->coefficients = context_coordinate_config.object_plane_coefficients;
  2735. break;
  2736. case GL_EYE_LINEAR:
  2737. texcoord_generation_config->mode = SoftGPU::TexCoordGenerationMode::EyeLinear;
  2738. texcoord_generation_config->coefficients = context_coordinate_config.eye_plane_coefficients;
  2739. break;
  2740. case GL_SPHERE_MAP:
  2741. texcoord_generation_config->mode = SoftGPU::TexCoordGenerationMode::SphereMap;
  2742. break;
  2743. case GL_REFLECTION_MAP:
  2744. texcoord_generation_config->mode = SoftGPU::TexCoordGenerationMode::ReflectionMap;
  2745. break;
  2746. case GL_NORMAL_MAP:
  2747. texcoord_generation_config->mode = SoftGPU::TexCoordGenerationMode::NormalMap;
  2748. break;
  2749. }
  2750. }
  2751. options.texcoord_generation_enabled_coordinates[i] = enabled_coordinates;
  2752. }
  2753. m_rasterizer.set_options(options);
  2754. }
  2755. void GLContext::sync_stencil_configuration()
  2756. {
  2757. if (!m_stencil_configuration_dirty)
  2758. return;
  2759. m_stencil_configuration_dirty = false;
  2760. auto set_device_stencil = [&](SoftGPU::Face face, StencilFunctionOptions func, StencilOperationOptions op) {
  2761. SoftGPU::StencilConfiguration device_configuration;
  2762. // Stencil test function
  2763. auto map_func = [](GLenum func) -> SoftGPU::StencilTestFunction {
  2764. switch (func) {
  2765. case GL_ALWAYS:
  2766. return SoftGPU::StencilTestFunction::Always;
  2767. case GL_EQUAL:
  2768. return SoftGPU::StencilTestFunction::Equal;
  2769. case GL_GEQUAL:
  2770. return SoftGPU::StencilTestFunction::GreaterOrEqual;
  2771. case GL_GREATER:
  2772. return SoftGPU::StencilTestFunction::Greater;
  2773. case GL_LESS:
  2774. return SoftGPU::StencilTestFunction::Less;
  2775. case GL_LEQUAL:
  2776. return SoftGPU::StencilTestFunction::LessOrEqual;
  2777. case GL_NEVER:
  2778. return SoftGPU::StencilTestFunction::Never;
  2779. case GL_NOTEQUAL:
  2780. return SoftGPU::StencilTestFunction::NotEqual;
  2781. }
  2782. VERIFY_NOT_REACHED();
  2783. };
  2784. device_configuration.test_function = map_func(func.func);
  2785. device_configuration.reference_value = func.reference_value;
  2786. device_configuration.test_mask = func.mask;
  2787. // Stencil operation
  2788. auto map_operation = [](GLenum operation) -> SoftGPU::StencilOperation {
  2789. switch (operation) {
  2790. case GL_DECR:
  2791. return SoftGPU::StencilOperation::Decrement;
  2792. case GL_DECR_WRAP:
  2793. return SoftGPU::StencilOperation::DecrementWrap;
  2794. case GL_INCR:
  2795. return SoftGPU::StencilOperation::Increment;
  2796. case GL_INCR_WRAP:
  2797. return SoftGPU::StencilOperation::IncrementWrap;
  2798. case GL_INVERT:
  2799. return SoftGPU::StencilOperation::Invert;
  2800. case GL_KEEP:
  2801. return SoftGPU::StencilOperation::Keep;
  2802. case GL_REPLACE:
  2803. return SoftGPU::StencilOperation::Replace;
  2804. case GL_ZERO:
  2805. return SoftGPU::StencilOperation::Zero;
  2806. }
  2807. VERIFY_NOT_REACHED();
  2808. };
  2809. device_configuration.on_stencil_test_fail = map_operation(op.op_fail);
  2810. device_configuration.on_depth_test_fail = map_operation(op.op_depth_fail);
  2811. device_configuration.on_pass = map_operation(op.op_pass);
  2812. device_configuration.write_mask = op.write_mask;
  2813. m_rasterizer.set_stencil_configuration(face, device_configuration);
  2814. };
  2815. set_device_stencil(SoftGPU::Face::Front, m_stencil_function[Face::Front], m_stencil_operation[Face::Front]);
  2816. set_device_stencil(SoftGPU::Face::Back, m_stencil_function[Face::Back], m_stencil_operation[Face::Back]);
  2817. }
  2818. void GLContext::build_extension_string()
  2819. {
  2820. Vector<StringView> extensions;
  2821. // FIXME: npot texture support became a required core feature starting with OpenGL 2.0 (https://www.khronos.org/opengl/wiki/NPOT_Texture)
  2822. // Ideally we would verify if the selected device adheres to the requested OpenGL context version before context creation
  2823. // and refuse to create a context if it doesn't.
  2824. if (m_device_info.supports_npot_textures)
  2825. extensions.append("GL_ARB_texture_non_power_of_two");
  2826. if (m_device_info.num_texture_units > 1)
  2827. extensions.append("GL_ARB_multitexture");
  2828. m_extensions = String::join(" ", extensions);
  2829. }
  2830. void GLContext::gl_lightf(GLenum light, GLenum pname, GLfloat param)
  2831. {
  2832. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_lightf, light, pname, param);
  2833. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  2834. RETURN_WITH_ERROR_IF(light < GL_LIGHT0 || light >= (GL_LIGHT0 + m_device_info.num_lights), GL_INVALID_ENUM);
  2835. RETURN_WITH_ERROR_IF(!(pname == GL_CONSTANT_ATTENUATION || pname == GL_LINEAR_ATTENUATION || pname == GL_QUADRATIC_ATTENUATION || pname != GL_SPOT_EXPONENT || pname != GL_SPOT_CUTOFF), GL_INVALID_ENUM);
  2836. RETURN_WITH_ERROR_IF(param < 0.f, GL_INVALID_VALUE);
  2837. auto& light_state = m_light_states.at(light - GL_LIGHT0);
  2838. switch (pname) {
  2839. case GL_CONSTANT_ATTENUATION:
  2840. light_state.constant_attenuation = param;
  2841. break;
  2842. case GL_LINEAR_ATTENUATION:
  2843. light_state.linear_attenuation = param;
  2844. break;
  2845. case GL_QUADRATIC_ATTENUATION:
  2846. light_state.quadratic_attenuation = param;
  2847. break;
  2848. case GL_SPOT_EXPONENT:
  2849. RETURN_WITH_ERROR_IF(param > 128.f, GL_INVALID_VALUE);
  2850. light_state.spotlight_exponent = param;
  2851. break;
  2852. case GL_SPOT_CUTOFF:
  2853. RETURN_WITH_ERROR_IF(param > 90.f && param != 180.f, GL_INVALID_VALUE);
  2854. light_state.spotlight_cutoff_angle = param;
  2855. break;
  2856. default:
  2857. VERIFY_NOT_REACHED();
  2858. }
  2859. m_light_state_is_dirty = true;
  2860. }
  2861. void GLContext::gl_lightfv(GLenum light, GLenum pname, GLfloat const* params)
  2862. {
  2863. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_lightfv, light, pname, params);
  2864. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  2865. RETURN_WITH_ERROR_IF(light < GL_LIGHT0 || light >= (GL_LIGHT0 + m_device_info.num_lights), GL_INVALID_ENUM);
  2866. RETURN_WITH_ERROR_IF(!(pname == GL_AMBIENT || pname == GL_DIFFUSE || pname == GL_SPECULAR || pname == GL_POSITION || pname == GL_CONSTANT_ATTENUATION || pname == GL_LINEAR_ATTENUATION || pname == GL_QUADRATIC_ATTENUATION || pname == GL_SPOT_CUTOFF || pname == GL_SPOT_EXPONENT || pname == GL_SPOT_DIRECTION), GL_INVALID_ENUM);
  2867. auto& light_state = m_light_states.at(light - GL_LIGHT0);
  2868. switch (pname) {
  2869. case GL_AMBIENT:
  2870. light_state.ambient_intensity = { params[0], params[1], params[2], params[3] };
  2871. break;
  2872. case GL_DIFFUSE:
  2873. light_state.diffuse_intensity = { params[0], params[1], params[2], params[3] };
  2874. break;
  2875. case GL_SPECULAR:
  2876. light_state.specular_intensity = { params[0], params[1], params[2], params[3] };
  2877. break;
  2878. case GL_POSITION:
  2879. light_state.position = { params[0], params[1], params[2], params[3] };
  2880. light_state.position = m_model_view_matrix * light_state.position;
  2881. break;
  2882. case GL_CONSTANT_ATTENUATION:
  2883. RETURN_WITH_ERROR_IF(params[0] < 0.f, GL_INVALID_VALUE);
  2884. light_state.constant_attenuation = params[0];
  2885. break;
  2886. case GL_LINEAR_ATTENUATION:
  2887. RETURN_WITH_ERROR_IF(params[0] < 0.f, GL_INVALID_VALUE);
  2888. light_state.linear_attenuation = params[0];
  2889. break;
  2890. case GL_QUADRATIC_ATTENUATION:
  2891. RETURN_WITH_ERROR_IF(params[0] < 0.f, GL_INVALID_VALUE);
  2892. light_state.quadratic_attenuation = params[0];
  2893. break;
  2894. case GL_SPOT_EXPONENT: {
  2895. auto exponent = params[0];
  2896. RETURN_WITH_ERROR_IF(exponent < 0.f || exponent > 128.f, GL_INVALID_VALUE);
  2897. light_state.spotlight_exponent = exponent;
  2898. break;
  2899. }
  2900. case GL_SPOT_CUTOFF: {
  2901. auto cutoff = params[0];
  2902. RETURN_WITH_ERROR_IF((cutoff < 0.f || cutoff > 90.f) && cutoff != 180.f, GL_INVALID_VALUE);
  2903. light_state.spotlight_cutoff_angle = cutoff;
  2904. break;
  2905. }
  2906. case GL_SPOT_DIRECTION: {
  2907. FloatVector4 direction_vector = { params[0], params[1], params[2], 0.f };
  2908. direction_vector = m_model_view_matrix * direction_vector;
  2909. light_state.spotlight_direction = direction_vector.xyz();
  2910. break;
  2911. }
  2912. default:
  2913. VERIFY_NOT_REACHED();
  2914. }
  2915. m_light_state_is_dirty = true;
  2916. }
  2917. void GLContext::gl_lightiv(GLenum light, GLenum pname, GLint const* params)
  2918. {
  2919. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_lightiv, light, pname, params);
  2920. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  2921. RETURN_WITH_ERROR_IF(light < GL_LIGHT0 || light >= (GL_LIGHT0 + m_device_info.num_lights), GL_INVALID_ENUM);
  2922. RETURN_WITH_ERROR_IF(!(pname == GL_AMBIENT || pname == GL_DIFFUSE || pname == GL_SPECULAR || pname == GL_POSITION || pname == GL_CONSTANT_ATTENUATION || pname == GL_LINEAR_ATTENUATION || pname == GL_QUADRATIC_ATTENUATION || pname == GL_SPOT_CUTOFF || pname == GL_SPOT_EXPONENT || pname == GL_SPOT_DIRECTION), GL_INVALID_ENUM);
  2923. auto& light_state = m_light_states[light - GL_LIGHT0];
  2924. auto const to_float_vector = [](GLfloat x, GLfloat y, GLfloat z, GLfloat w) {
  2925. return FloatVector4(x, y, z, w);
  2926. };
  2927. switch (pname) {
  2928. case GL_AMBIENT:
  2929. light_state.ambient_intensity = to_float_vector(params[0], params[1], params[2], params[3]);
  2930. break;
  2931. case GL_DIFFUSE:
  2932. light_state.diffuse_intensity = to_float_vector(params[0], params[1], params[2], params[3]);
  2933. break;
  2934. case GL_SPECULAR:
  2935. light_state.specular_intensity = to_float_vector(params[0], params[1], params[2], params[3]);
  2936. break;
  2937. case GL_POSITION:
  2938. light_state.position = to_float_vector(params[0], params[1], params[2], params[3]);
  2939. light_state.position = m_model_view_matrix * light_state.position;
  2940. break;
  2941. case GL_CONSTANT_ATTENUATION:
  2942. RETURN_WITH_ERROR_IF(params[0] < 0, GL_INVALID_VALUE);
  2943. light_state.constant_attenuation = static_cast<float>(params[0]);
  2944. break;
  2945. case GL_LINEAR_ATTENUATION:
  2946. RETURN_WITH_ERROR_IF(params[0] < 0, GL_INVALID_VALUE);
  2947. light_state.linear_attenuation = static_cast<float>(params[0]);
  2948. break;
  2949. case GL_QUADRATIC_ATTENUATION:
  2950. RETURN_WITH_ERROR_IF(params[0] < 0, GL_INVALID_VALUE);
  2951. light_state.quadratic_attenuation = static_cast<float>(params[0]);
  2952. break;
  2953. case GL_SPOT_EXPONENT: {
  2954. auto exponent = static_cast<float>(params[0]);
  2955. RETURN_WITH_ERROR_IF(exponent < 0.f || exponent > 128.f, GL_INVALID_VALUE);
  2956. light_state.spotlight_exponent = exponent;
  2957. break;
  2958. }
  2959. case GL_SPOT_CUTOFF: {
  2960. auto cutoff = static_cast<float>(params[0]);
  2961. RETURN_WITH_ERROR_IF((cutoff < 0.f || cutoff > 90.f) && cutoff != 180.f, GL_INVALID_VALUE);
  2962. light_state.spotlight_cutoff_angle = cutoff;
  2963. break;
  2964. }
  2965. case GL_SPOT_DIRECTION: {
  2966. auto direction_vector = to_float_vector(params[0], params[1], params[2], 0.0f);
  2967. direction_vector = m_model_view_matrix * direction_vector;
  2968. light_state.spotlight_direction = direction_vector.xyz();
  2969. break;
  2970. }
  2971. default:
  2972. VERIFY_NOT_REACHED();
  2973. }
  2974. m_light_state_is_dirty = true;
  2975. }
  2976. void GLContext::gl_materialf(GLenum face, GLenum pname, GLfloat param)
  2977. {
  2978. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_materialf, face, pname, param);
  2979. RETURN_WITH_ERROR_IF(!(face == GL_FRONT || face == GL_BACK || face == GL_FRONT_AND_BACK), GL_INVALID_ENUM);
  2980. RETURN_WITH_ERROR_IF(pname != GL_SHININESS, GL_INVALID_ENUM);
  2981. RETURN_WITH_ERROR_IF(param > 128.0f, GL_INVALID_VALUE);
  2982. switch (face) {
  2983. case GL_FRONT:
  2984. m_material_states[Face::Front].shininess = param;
  2985. break;
  2986. case GL_BACK:
  2987. m_material_states[Face::Back].shininess = param;
  2988. break;
  2989. case GL_FRONT_AND_BACK:
  2990. m_material_states[Face::Front].shininess = param;
  2991. m_material_states[Face::Back].shininess = param;
  2992. break;
  2993. default:
  2994. VERIFY_NOT_REACHED();
  2995. }
  2996. m_light_state_is_dirty = true;
  2997. }
  2998. void GLContext::gl_materialfv(GLenum face, GLenum pname, GLfloat const* params)
  2999. {
  3000. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_materialfv, face, pname, params);
  3001. RETURN_WITH_ERROR_IF(!(face == GL_FRONT || face == GL_BACK || face == GL_FRONT_AND_BACK), GL_INVALID_ENUM);
  3002. RETURN_WITH_ERROR_IF(!(pname == GL_AMBIENT || pname == GL_DIFFUSE || pname == GL_SPECULAR || pname == GL_EMISSION || pname == GL_SHININESS || pname == GL_AMBIENT_AND_DIFFUSE), GL_INVALID_ENUM);
  3003. RETURN_WITH_ERROR_IF((pname == GL_SHININESS && *params > 128.0f), GL_INVALID_VALUE);
  3004. auto update_material = [](SoftGPU::Material& material, GLenum pname, GLfloat const* params) {
  3005. switch (pname) {
  3006. case GL_AMBIENT:
  3007. material.ambient = { params[0], params[1], params[2], params[3] };
  3008. break;
  3009. case GL_DIFFUSE:
  3010. material.diffuse = { params[0], params[1], params[2], params[3] };
  3011. break;
  3012. case GL_SPECULAR:
  3013. material.specular = { params[0], params[1], params[2], params[3] };
  3014. break;
  3015. case GL_EMISSION:
  3016. material.emissive = { params[0], params[1], params[2], params[3] };
  3017. break;
  3018. case GL_SHININESS:
  3019. material.shininess = *params;
  3020. break;
  3021. case GL_AMBIENT_AND_DIFFUSE:
  3022. material.ambient = { params[0], params[1], params[2], params[3] };
  3023. material.diffuse = { params[0], params[1], params[2], params[3] };
  3024. break;
  3025. }
  3026. };
  3027. switch (face) {
  3028. case GL_FRONT:
  3029. update_material(m_material_states[Face::Front], pname, params);
  3030. break;
  3031. case GL_BACK:
  3032. update_material(m_material_states[Face::Back], pname, params);
  3033. break;
  3034. case GL_FRONT_AND_BACK:
  3035. update_material(m_material_states[Face::Front], pname, params);
  3036. update_material(m_material_states[Face::Back], pname, params);
  3037. break;
  3038. }
  3039. m_light_state_is_dirty = true;
  3040. }
  3041. void GLContext::gl_materialiv(GLenum face, GLenum pname, GLint const* params)
  3042. {
  3043. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_materialiv, face, pname, params);
  3044. RETURN_WITH_ERROR_IF(!(face == GL_FRONT || face == GL_BACK || face == GL_FRONT_AND_BACK), GL_INVALID_ENUM);
  3045. RETURN_WITH_ERROR_IF(!(pname == GL_AMBIENT || pname == GL_DIFFUSE || pname == GL_SPECULAR || pname == GL_EMISSION || pname == GL_SHININESS || pname == GL_AMBIENT_AND_DIFFUSE), GL_INVALID_ENUM);
  3046. RETURN_WITH_ERROR_IF((pname == GL_SHININESS && *params > 128), GL_INVALID_VALUE);
  3047. auto update_material = [](SoftGPU::Material& material, GLenum pname, GLint const* params) {
  3048. switch (pname) {
  3049. case GL_AMBIENT:
  3050. material.ambient = { static_cast<float>(params[0]), static_cast<float>(params[1]), static_cast<float>(params[2]), static_cast<float>(params[3]) };
  3051. break;
  3052. case GL_DIFFUSE:
  3053. material.diffuse = { static_cast<float>(params[0]), static_cast<float>(params[1]), static_cast<float>(params[2]), static_cast<float>(params[3]) };
  3054. break;
  3055. case GL_SPECULAR:
  3056. material.specular = { static_cast<float>(params[0]), static_cast<float>(params[1]), static_cast<float>(params[2]), static_cast<float>(params[3]) };
  3057. break;
  3058. case GL_EMISSION:
  3059. material.emissive = { static_cast<float>(params[0]), static_cast<float>(params[1]), static_cast<float>(params[2]), static_cast<float>(params[3]) };
  3060. break;
  3061. case GL_SHININESS:
  3062. material.shininess = static_cast<float>(params[0]);
  3063. break;
  3064. case GL_AMBIENT_AND_DIFFUSE:
  3065. material.ambient = { static_cast<float>(params[0]), static_cast<float>(params[1]), static_cast<float>(params[2]), static_cast<float>(params[3]) };
  3066. material.diffuse = { static_cast<float>(params[0]), static_cast<float>(params[1]), static_cast<float>(params[2]), static_cast<float>(params[3]) };
  3067. break;
  3068. }
  3069. };
  3070. switch (face) {
  3071. case GL_FRONT:
  3072. update_material(m_material_states[Face::Front], pname, params);
  3073. break;
  3074. case GL_BACK:
  3075. update_material(m_material_states[Face::Back], pname, params);
  3076. break;
  3077. case GL_FRONT_AND_BACK:
  3078. update_material(m_material_states[Face::Front], pname, params);
  3079. update_material(m_material_states[Face::Back], pname, params);
  3080. break;
  3081. }
  3082. m_light_state_is_dirty = true;
  3083. }
  3084. void GLContext::gl_color_material(GLenum face, GLenum mode)
  3085. {
  3086. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_color_material, face, mode);
  3087. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  3088. RETURN_WITH_ERROR_IF(face != GL_FRONT
  3089. && face != GL_BACK
  3090. && face != GL_FRONT_AND_BACK,
  3091. GL_INVALID_ENUM);
  3092. RETURN_WITH_ERROR_IF(mode != GL_EMISSION
  3093. && mode != GL_AMBIENT
  3094. && mode != GL_DIFFUSE
  3095. && mode != GL_SPECULAR
  3096. && mode != GL_AMBIENT_AND_DIFFUSE,
  3097. GL_INVALID_ENUM);
  3098. m_color_material_face = face;
  3099. m_color_material_mode = mode;
  3100. m_light_state_is_dirty = true;
  3101. }
  3102. void GLContext::gl_get_light(GLenum light, GLenum pname, void* params, GLenum type)
  3103. {
  3104. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_get_light, light, pname, params, type);
  3105. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  3106. RETURN_WITH_ERROR_IF(light < GL_LIGHT0 || light > GL_LIGHT0 + m_device_info.num_lights, GL_INVALID_ENUM);
  3107. RETURN_WITH_ERROR_IF(!(pname == GL_AMBIENT || pname == GL_DIFFUSE || pname == GL_SPECULAR || pname == GL_SPOT_DIRECTION || pname == GL_SPOT_EXPONENT || pname == GL_SPOT_CUTOFF || pname == GL_CONSTANT_ATTENUATION || pname == GL_LINEAR_ATTENUATION || pname == GL_QUADRATIC_ATTENUATION), GL_INVALID_ENUM);
  3108. if (type == GL_FLOAT)
  3109. get_light_param<GLfloat>(light, pname, static_cast<GLfloat*>(params));
  3110. else if (type == GL_INT)
  3111. get_light_param<GLint>(light, pname, static_cast<GLint*>(params));
  3112. else
  3113. VERIFY_NOT_REACHED();
  3114. }
  3115. template<typename T>
  3116. void GLContext::get_light_param(GLenum light, GLenum pname, T* params)
  3117. {
  3118. auto const& light_state = m_light_states[light - GL_LIGHT0];
  3119. switch (pname) {
  3120. case GL_AMBIENT:
  3121. params[0] = light_state.ambient_intensity.x();
  3122. params[1] = light_state.ambient_intensity.y();
  3123. params[2] = light_state.ambient_intensity.z();
  3124. params[3] = light_state.ambient_intensity.w();
  3125. break;
  3126. case GL_DIFFUSE:
  3127. params[0] = light_state.diffuse_intensity.x();
  3128. params[1] = light_state.diffuse_intensity.y();
  3129. params[2] = light_state.diffuse_intensity.z();
  3130. params[3] = light_state.diffuse_intensity.w();
  3131. break;
  3132. case GL_SPECULAR:
  3133. params[0] = light_state.specular_intensity.x();
  3134. params[1] = light_state.specular_intensity.y();
  3135. params[2] = light_state.specular_intensity.z();
  3136. params[3] = light_state.specular_intensity.w();
  3137. break;
  3138. case GL_SPOT_DIRECTION:
  3139. params[0] = light_state.spotlight_direction.x();
  3140. params[1] = light_state.spotlight_direction.y();
  3141. params[2] = light_state.spotlight_direction.z();
  3142. break;
  3143. case GL_SPOT_EXPONENT:
  3144. *params = light_state.spotlight_exponent;
  3145. break;
  3146. case GL_SPOT_CUTOFF:
  3147. *params = light_state.spotlight_cutoff_angle;
  3148. break;
  3149. case GL_CONSTANT_ATTENUATION:
  3150. *params = light_state.constant_attenuation;
  3151. break;
  3152. case GL_LINEAR_ATTENUATION:
  3153. *params = light_state.linear_attenuation;
  3154. break;
  3155. case GL_QUADRATIC_ATTENUATION:
  3156. *params = light_state.quadratic_attenuation;
  3157. break;
  3158. }
  3159. }
  3160. void GLContext::gl_get_material(GLenum face, GLenum pname, void* params, GLenum type)
  3161. {
  3162. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_get_material, face, pname, params, type);
  3163. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  3164. RETURN_WITH_ERROR_IF(!(pname == GL_AMBIENT || pname == GL_DIFFUSE || pname == GL_SPECULAR || pname == GL_EMISSION), GL_INVALID_ENUM);
  3165. RETURN_WITH_ERROR_IF(!(face == GL_FRONT || face == GL_BACK), GL_INVALID_ENUM);
  3166. Face material_face = Front;
  3167. switch (face) {
  3168. case GL_FRONT:
  3169. material_face = Front;
  3170. break;
  3171. case GL_BACK:
  3172. material_face = Back;
  3173. break;
  3174. }
  3175. if (type == GL_FLOAT)
  3176. get_material_param<GLfloat>(material_face, pname, static_cast<GLfloat*>(params));
  3177. else if (type == GL_INT)
  3178. get_material_param<GLint>(material_face, pname, static_cast<GLint*>(params));
  3179. else
  3180. VERIFY_NOT_REACHED();
  3181. }
  3182. template<typename T>
  3183. void GLContext::get_material_param(Face face, GLenum pname, T* params)
  3184. {
  3185. auto const& material = m_material_states[face];
  3186. switch (pname) {
  3187. case GL_AMBIENT:
  3188. params[0] = static_cast<T>(material.ambient.x());
  3189. params[1] = static_cast<T>(material.ambient.y());
  3190. params[2] = static_cast<T>(material.ambient.z());
  3191. params[3] = static_cast<T>(material.ambient.w());
  3192. break;
  3193. case GL_DIFFUSE:
  3194. params[0] = static_cast<T>(material.diffuse.x());
  3195. params[1] = static_cast<T>(material.diffuse.y());
  3196. params[2] = static_cast<T>(material.diffuse.z());
  3197. params[3] = static_cast<T>(material.diffuse.w());
  3198. break;
  3199. case GL_SPECULAR:
  3200. params[0] = static_cast<T>(material.specular.x());
  3201. params[1] = static_cast<T>(material.specular.y());
  3202. params[2] = static_cast<T>(material.specular.z());
  3203. params[3] = static_cast<T>(material.specular.w());
  3204. break;
  3205. case GL_EMISSION:
  3206. params[0] = static_cast<T>(material.emissive.x());
  3207. params[1] = static_cast<T>(material.emissive.y());
  3208. params[2] = static_cast<T>(material.emissive.z());
  3209. params[3] = static_cast<T>(material.emissive.w());
  3210. break;
  3211. case GL_SHININESS:
  3212. *params = material.shininess;
  3213. break;
  3214. }
  3215. }
  3216. NonnullOwnPtr<GLContext> create_context(Gfx::Bitmap& bitmap)
  3217. {
  3218. auto context = make<GLContext>(bitmap);
  3219. dbgln_if(GL_DEBUG, "GL::create_context({}) -> {:p}", bitmap.size(), context.ptr());
  3220. if (!g_gl_context)
  3221. make_context_current(context);
  3222. return context;
  3223. }
  3224. void make_context_current(GLContext* context)
  3225. {
  3226. if (g_gl_context == context)
  3227. return;
  3228. dbgln_if(GL_DEBUG, "GL::make_context_current({:p})", context);
  3229. g_gl_context = context;
  3230. }
  3231. void present_context(GLContext* context)
  3232. {
  3233. context->present();
  3234. }
  3235. }