main.cpp 162 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447
  1. /**************************************************************************/
  2. /* main.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #include "main.h"
  31. #include "core/config/project_settings.h"
  32. #include "core/core_globals.h"
  33. #include "core/crypto/crypto.h"
  34. #include "core/debugger/engine_debugger.h"
  35. #include "core/extension/extension_api_dump.h"
  36. #include "core/extension/gdextension_interface_dump.gen.h"
  37. #include "core/extension/gdextension_manager.h"
  38. #include "core/input/input.h"
  39. #include "core/input/input_map.h"
  40. #include "core/io/dir_access.h"
  41. #include "core/io/file_access_pack.h"
  42. #include "core/io/file_access_zip.h"
  43. #include "core/io/image_loader.h"
  44. #include "core/io/ip.h"
  45. #include "core/io/resource_loader.h"
  46. #include "core/object/message_queue.h"
  47. #include "core/os/os.h"
  48. #include "core/os/time.h"
  49. #include "core/register_core_types.h"
  50. #include "core/string/translation.h"
  51. #include "core/version.h"
  52. #include "drivers/register_driver_types.h"
  53. #include "main/app_icon.gen.h"
  54. #include "main/main_timer_sync.h"
  55. #include "main/performance.h"
  56. #include "main/splash.gen.h"
  57. #include "modules/register_module_types.h"
  58. #include "platform/register_platform_apis.h"
  59. #include "scene/main/scene_tree.h"
  60. #include "scene/main/window.h"
  61. #include "scene/property_list_helper.h"
  62. #include "scene/register_scene_types.h"
  63. #include "scene/resources/packed_scene.h"
  64. #include "scene/theme/theme_db.h"
  65. #include "servers/audio_server.h"
  66. #include "servers/camera_server.h"
  67. #include "servers/display_server.h"
  68. #include "servers/movie_writer/movie_writer.h"
  69. #include "servers/movie_writer/movie_writer_mjpeg.h"
  70. #include "servers/navigation_server_3d.h"
  71. #include "servers/navigation_server_3d_dummy.h"
  72. #include "servers/register_server_types.h"
  73. #include "servers/rendering/rendering_server_default.h"
  74. #include "servers/text/text_server_dummy.h"
  75. #include "servers/text_server.h"
  76. // 2D
  77. #include "servers/navigation_server_2d.h"
  78. #include "servers/navigation_server_2d_dummy.h"
  79. #include "servers/physics_server_2d.h"
  80. #ifndef _3D_DISABLED
  81. #include "servers/physics_server_3d.h"
  82. #include "servers/xr_server.h"
  83. #endif // _3D_DISABLED
  84. #ifdef TESTS_ENABLED
  85. #include "tests/test_main.h"
  86. #endif
  87. #ifdef TOOLS_ENABLED
  88. #include "editor/debugger/debug_adapter/debug_adapter_server.h"
  89. #include "editor/debugger/editor_debugger_node.h"
  90. #include "editor/doc_data_class_path.gen.h"
  91. #include "editor/doc_tools.h"
  92. #include "editor/editor_file_system.h"
  93. #include "editor/editor_help.h"
  94. #include "editor/editor_node.h"
  95. #include "editor/editor_paths.h"
  96. #include "editor/editor_settings.h"
  97. #include "editor/editor_translation.h"
  98. #include "editor/progress_dialog.h"
  99. #include "editor/project_manager.h"
  100. #include "editor/register_editor_types.h"
  101. #if defined(TOOLS_ENABLED) && !defined(NO_EDITOR_SPLASH)
  102. #include "main/splash_editor.gen.h"
  103. #endif
  104. #ifndef DISABLE_DEPRECATED
  105. #include "editor/project_converter_3_to_4.h"
  106. #endif // DISABLE_DEPRECATED
  107. #endif // TOOLS_ENABLED
  108. #if defined(STEAMAPI_ENABLED)
  109. #include "main/steam_tracker.h"
  110. #endif
  111. #include "modules/modules_enabled.gen.h" // For mono.
  112. #if defined(MODULE_MONO_ENABLED) && defined(TOOLS_ENABLED)
  113. #include "modules/mono/editor/bindings_generator.h"
  114. #endif
  115. #ifdef MODULE_GDSCRIPT_ENABLED
  116. #include "modules/gdscript/gdscript.h"
  117. #if defined(TOOLS_ENABLED) && !defined(GDSCRIPT_NO_LSP)
  118. #include "modules/gdscript/language_server/gdscript_language_server.h"
  119. #endif // TOOLS_ENABLED && !GDSCRIPT_NO_LSP
  120. #endif // MODULE_GDSCRIPT_ENABLED
  121. /* Static members */
  122. // Singletons
  123. // Initialized in setup()
  124. static Engine *engine = nullptr;
  125. static ProjectSettings *globals = nullptr;
  126. static Input *input = nullptr;
  127. static InputMap *input_map = nullptr;
  128. static TranslationServer *translation_server = nullptr;
  129. static Performance *performance = nullptr;
  130. static PackedData *packed_data = nullptr;
  131. #ifdef MINIZIP_ENABLED
  132. static ZipArchive *zip_packed_data = nullptr;
  133. #endif
  134. static MessageQueue *message_queue = nullptr;
  135. #if defined(STEAMAPI_ENABLED)
  136. static SteamTracker *steam_tracker = nullptr;
  137. #endif
  138. // Initialized in setup2()
  139. static AudioServer *audio_server = nullptr;
  140. static CameraServer *camera_server = nullptr;
  141. static DisplayServer *display_server = nullptr;
  142. static RenderingServer *rendering_server = nullptr;
  143. static TextServerManager *tsman = nullptr;
  144. static ThemeDB *theme_db = nullptr;
  145. static NavigationServer2D *navigation_server_2d = nullptr;
  146. static PhysicsServer2DManager *physics_server_2d_manager = nullptr;
  147. static PhysicsServer2D *physics_server_2d = nullptr;
  148. static NavigationServer3D *navigation_server_3d = nullptr;
  149. #ifndef _3D_DISABLED
  150. static PhysicsServer3DManager *physics_server_3d_manager = nullptr;
  151. static PhysicsServer3D *physics_server_3d = nullptr;
  152. static XRServer *xr_server = nullptr;
  153. #endif // _3D_DISABLED
  154. // We error out if setup2() doesn't turn this true
  155. static bool _start_success = false;
  156. // Drivers
  157. String display_driver = "";
  158. String tablet_driver = "";
  159. String text_driver = "";
  160. String rendering_driver = "";
  161. String rendering_method = "";
  162. static int text_driver_idx = -1;
  163. static int audio_driver_idx = -1;
  164. // Engine config/tools
  165. static bool single_window = false;
  166. static bool editor = false;
  167. static bool project_manager = false;
  168. static bool cmdline_tool = false;
  169. static String locale;
  170. static String log_file;
  171. static bool show_help = false;
  172. static uint64_t quit_after = 0;
  173. static OS::ProcessID editor_pid = 0;
  174. #ifdef TOOLS_ENABLED
  175. static bool found_project = false;
  176. static bool auto_build_solutions = false;
  177. static String debug_server_uri;
  178. static bool wait_for_import = false;
  179. #ifndef DISABLE_DEPRECATED
  180. static int converter_max_kb_file = 4 * 1024; // 4MB
  181. static int converter_max_line_length = 100000;
  182. #endif // DISABLE_DEPRECATED
  183. HashMap<Main::CLIScope, Vector<String>> forwardable_cli_arguments;
  184. #endif
  185. static bool single_threaded_scene = false;
  186. // Display
  187. static DisplayServer::WindowMode window_mode = DisplayServer::WINDOW_MODE_WINDOWED;
  188. static DisplayServer::ScreenOrientation window_orientation = DisplayServer::SCREEN_LANDSCAPE;
  189. static DisplayServer::VSyncMode window_vsync_mode = DisplayServer::VSYNC_ENABLED;
  190. static uint32_t window_flags = 0;
  191. static Size2i window_size = Size2i(1152, 648);
  192. static int init_screen = DisplayServer::SCREEN_PRIMARY;
  193. static bool init_fullscreen = false;
  194. static bool init_maximized = false;
  195. static bool init_windowed = false;
  196. static bool init_always_on_top = false;
  197. static bool init_use_custom_pos = false;
  198. static bool init_use_custom_screen = false;
  199. static Vector2 init_custom_pos;
  200. // Debug
  201. static bool use_debug_profiler = false;
  202. #ifdef DEBUG_ENABLED
  203. static bool debug_collisions = false;
  204. static bool debug_paths = false;
  205. static bool debug_navigation = false;
  206. static bool debug_avoidance = false;
  207. static bool debug_canvas_item_redraw = false;
  208. #endif
  209. static int max_fps = -1;
  210. static int frame_delay = 0;
  211. static int audio_output_latency = 0;
  212. static bool disable_render_loop = false;
  213. static int fixed_fps = -1;
  214. static MovieWriter *movie_writer = nullptr;
  215. static bool disable_vsync = false;
  216. static bool print_fps = false;
  217. #ifdef TOOLS_ENABLED
  218. static bool dump_gdextension_interface = false;
  219. static bool dump_extension_api = false;
  220. static bool include_docs_in_extension_api_dump = false;
  221. static bool validate_extension_api = false;
  222. static String validate_extension_api_file;
  223. #endif
  224. bool profile_gpu = false;
  225. // Constants.
  226. static const String NULL_DISPLAY_DRIVER("headless");
  227. static const String NULL_AUDIO_DRIVER("Dummy");
  228. // The length of the longest column in the command-line help we should align to
  229. // (excluding the 2-space left and right margins).
  230. // Currently, this is `--export-release <preset> <path>`.
  231. static const int OPTION_COLUMN_LENGTH = 32;
  232. /* Helper methods */
  233. bool Main::is_cmdline_tool() {
  234. return cmdline_tool;
  235. }
  236. #ifdef TOOLS_ENABLED
  237. const Vector<String> &Main::get_forwardable_cli_arguments(Main::CLIScope p_scope) {
  238. return forwardable_cli_arguments[p_scope];
  239. }
  240. #endif
  241. static String unescape_cmdline(const String &p_str) {
  242. return p_str.replace("%20", " ");
  243. }
  244. static String get_full_version_string() {
  245. String hash = String(VERSION_HASH);
  246. if (!hash.is_empty()) {
  247. hash = "." + hash.left(9);
  248. }
  249. return String(VERSION_FULL_BUILD) + hash;
  250. }
  251. #if defined(TOOLS_ENABLED) && defined(MODULE_GDSCRIPT_ENABLED)
  252. static Vector<String> get_files_with_extension(const String &p_root, const String &p_extension) {
  253. Vector<String> paths;
  254. Ref<DirAccess> dir = DirAccess::open(p_root);
  255. if (dir.is_valid()) {
  256. dir->list_dir_begin();
  257. String fn = dir->get_next();
  258. while (!fn.is_empty()) {
  259. if (!dir->current_is_hidden() && fn != "." && fn != "..") {
  260. if (dir->current_is_dir()) {
  261. paths.append_array(get_files_with_extension(p_root.path_join(fn), p_extension));
  262. } else if (fn.get_extension() == p_extension) {
  263. paths.append(p_root.path_join(fn));
  264. }
  265. }
  266. fn = dir->get_next();
  267. }
  268. dir->list_dir_end();
  269. }
  270. return paths;
  271. }
  272. #endif
  273. // FIXME: Could maybe be moved to have less code in main.cpp.
  274. void initialize_physics() {
  275. #ifndef _3D_DISABLED
  276. /// 3D Physics Server
  277. physics_server_3d = PhysicsServer3DManager::get_singleton()->new_server(
  278. GLOBAL_GET(PhysicsServer3DManager::setting_property_name));
  279. if (!physics_server_3d) {
  280. // Physics server not found, Use the default physics
  281. physics_server_3d = PhysicsServer3DManager::get_singleton()->new_default_server();
  282. }
  283. ERR_FAIL_NULL(physics_server_3d);
  284. physics_server_3d->init();
  285. #endif // _3D_DISABLED
  286. // 2D Physics server
  287. physics_server_2d = PhysicsServer2DManager::get_singleton()->new_server(
  288. GLOBAL_GET(PhysicsServer2DManager::get_singleton()->setting_property_name));
  289. if (!physics_server_2d) {
  290. // Physics server not found, Use the default physics
  291. physics_server_2d = PhysicsServer2DManager::get_singleton()->new_default_server();
  292. }
  293. ERR_FAIL_NULL(physics_server_2d);
  294. physics_server_2d->init();
  295. }
  296. void finalize_physics() {
  297. #ifndef _3D_DISABLED
  298. physics_server_3d->finish();
  299. memdelete(physics_server_3d);
  300. #endif // _3D_DISABLED
  301. physics_server_2d->finish();
  302. memdelete(physics_server_2d);
  303. }
  304. void finalize_display() {
  305. rendering_server->finish();
  306. memdelete(rendering_server);
  307. memdelete(display_server);
  308. }
  309. void initialize_navigation_server() {
  310. ERR_FAIL_COND(navigation_server_3d != nullptr);
  311. ERR_FAIL_COND(navigation_server_2d != nullptr);
  312. // Init 3D Navigation Server
  313. navigation_server_3d = NavigationServer3DManager::new_default_server();
  314. // Fall back to dummy if no default server has been registered.
  315. if (!navigation_server_3d) {
  316. navigation_server_3d = memnew(NavigationServer3DDummy);
  317. }
  318. // Should be impossible, but make sure it's not null.
  319. ERR_FAIL_NULL_MSG(navigation_server_3d, "Failed to initialize NavigationServer3D.");
  320. navigation_server_3d->init();
  321. // Init 2D Navigation Server
  322. navigation_server_2d = NavigationServer2DManager::new_default_server();
  323. if (!navigation_server_2d) {
  324. navigation_server_2d = memnew(NavigationServer2DDummy);
  325. }
  326. ERR_FAIL_NULL_MSG(navigation_server_2d, "Failed to initialize NavigationServer2D.");
  327. navigation_server_2d->init();
  328. }
  329. void finalize_navigation_server() {
  330. ERR_FAIL_NULL(navigation_server_3d);
  331. navigation_server_3d->finish();
  332. memdelete(navigation_server_3d);
  333. navigation_server_3d = nullptr;
  334. ERR_FAIL_NULL(navigation_server_2d);
  335. navigation_server_2d->finish();
  336. memdelete(navigation_server_2d);
  337. navigation_server_2d = nullptr;
  338. }
  339. void initialize_theme_db() {
  340. theme_db = memnew(ThemeDB);
  341. }
  342. void finalize_theme_db() {
  343. memdelete(theme_db);
  344. theme_db = nullptr;
  345. }
  346. //#define DEBUG_INIT
  347. #ifdef DEBUG_INIT
  348. #define MAIN_PRINT(m_txt) print_line(m_txt)
  349. #else
  350. #define MAIN_PRINT(m_txt)
  351. #endif
  352. void Main::print_header(bool p_rich) {
  353. if (VERSION_TIMESTAMP > 0) {
  354. // Version timestamp available.
  355. if (p_rich) {
  356. Engine::get_singleton()->print_header_rich("\u001b[38;5;39m" + String(VERSION_NAME) + "\u001b[0m v" + get_full_version_string() + " (" + Time::get_singleton()->get_datetime_string_from_unix_time(VERSION_TIMESTAMP, true) + " UTC) - \u001b[4m" + String(VERSION_WEBSITE));
  357. } else {
  358. Engine::get_singleton()->print_header(String(VERSION_NAME) + " v" + get_full_version_string() + " (" + Time::get_singleton()->get_datetime_string_from_unix_time(VERSION_TIMESTAMP, true) + " UTC) - " + String(VERSION_WEBSITE));
  359. }
  360. } else {
  361. if (p_rich) {
  362. Engine::get_singleton()->print_header_rich("\u001b[38;5;39m" + String(VERSION_NAME) + "\u001b[0m v" + get_full_version_string() + " - \u001b[4m" + String(VERSION_WEBSITE));
  363. } else {
  364. Engine::get_singleton()->print_header(String(VERSION_NAME) + " v" + get_full_version_string() + " - " + String(VERSION_WEBSITE));
  365. }
  366. }
  367. }
  368. /**
  369. * Prints a copyright notice in the command-line help with colored text. A newline is
  370. * automatically added at the end.
  371. */
  372. void Main::print_help_copyright(const char *p_notice) {
  373. OS::get_singleton()->print("\u001b[90m%s\u001b[0m\n", p_notice);
  374. }
  375. /**
  376. * Prints a title in the command-line help with colored text. A newline is
  377. * automatically added at beginning and at the end.
  378. */
  379. void Main::print_help_title(const char *p_title) {
  380. OS::get_singleton()->print("\n\u001b[1;93m%s:\u001b[0m\n", p_title);
  381. }
  382. /**
  383. * Returns the option string with required and optional arguments colored separately from the rest of the option.
  384. * This color replacement must be done *after* calling `rpad()` for the length padding to be done correctly.
  385. */
  386. String Main::format_help_option(const char *p_option) {
  387. return (String(p_option)
  388. .rpad(OPTION_COLUMN_LENGTH)
  389. .replace("[", "\u001b[96m[")
  390. .replace("]", "]\u001b[0m")
  391. .replace("<", "\u001b[95m<")
  392. .replace(">", ">\u001b[0m"));
  393. }
  394. /**
  395. * Prints an option in the command-line help with colored text. No newline is
  396. * added at the end. `p_availability` denotes which build types the argument is
  397. * available in. Support in release export templates implies support in debug
  398. * export templates and editor. Support in debug export templates implies
  399. * support in editor.
  400. */
  401. void Main::print_help_option(const char *p_option, const char *p_description, CLIOptionAvailability p_availability) {
  402. const bool option_empty = (p_option && !p_option[0]);
  403. if (!option_empty) {
  404. const char *availability_badge = "";
  405. switch (p_availability) {
  406. case CLI_OPTION_AVAILABILITY_EDITOR:
  407. availability_badge = "\u001b[1;91mE";
  408. break;
  409. case CLI_OPTION_AVAILABILITY_TEMPLATE_DEBUG:
  410. availability_badge = "\u001b[1;94mD";
  411. break;
  412. case CLI_OPTION_AVAILABILITY_TEMPLATE_RELEASE:
  413. availability_badge = "\u001b[1;92mR";
  414. break;
  415. case CLI_OPTION_AVAILABILITY_HIDDEN:
  416. // Use for multiline option names (but not when the option name is empty).
  417. availability_badge = " ";
  418. break;
  419. }
  420. OS::get_singleton()->print(
  421. " \u001b[92m%s %s\u001b[0m %s",
  422. format_help_option(p_option).utf8().ptr(),
  423. availability_badge,
  424. p_description);
  425. } else {
  426. // Make continuation lines for descriptions faint if the option name is empty.
  427. OS::get_singleton()->print(
  428. " \u001b[92m%s \u001b[0m \u001b[90m%s",
  429. format_help_option(p_option).utf8().ptr(),
  430. p_description);
  431. }
  432. }
  433. void Main::print_help(const char *p_binary) {
  434. print_header(true);
  435. print_help_copyright("Free and open source software under the terms of the MIT license.");
  436. print_help_copyright("(c) 2014-present Godot Engine contributors. (c) 2007-present Juan Linietsky, Ariel Manzur.");
  437. print_help_title("Usage");
  438. OS::get_singleton()->print(" %s \u001b[96m[options] [path to scene or \"project.godot\" file]\u001b[0m\n", p_binary);
  439. #if defined(TOOLS_ENABLED)
  440. print_help_title("Option legend (this build = editor)");
  441. #elif defined(DEBUG_ENABLED)
  442. print_help_title("Option legend (this build = debug export template)");
  443. #else
  444. print_help_title("Option legend (this build = release export template)");
  445. #endif
  446. OS::get_singleton()->print(" \u001b[1;92mR\u001b[0m Available in editor builds, debug export templates and release export templates.\n");
  447. #ifdef DEBUG_ENABLED
  448. OS::get_singleton()->print(" \u001b[1;94mD\u001b[0m Available in editor builds and debug export templates only.\n");
  449. #endif
  450. #ifdef TOOLS_ENABLED
  451. OS::get_singleton()->print(" \u001b[1;91mE\u001b[0m Only available in editor builds.\n");
  452. #endif
  453. print_help_title("General options");
  454. print_help_option("-h, --help", "Display this help message.\n");
  455. print_help_option("--version", "Display the version string.\n");
  456. print_help_option("-v, --verbose", "Use verbose stdout mode.\n");
  457. print_help_option("--quiet", "Quiet mode, silences stdout messages. Errors are still displayed.\n");
  458. print_help_option("--no-header", "Do not print engine version and rendering method header on startup.\n");
  459. print_help_title("Run options");
  460. print_help_option("--, ++", "Separator for user-provided arguments. Following arguments are not used by the engine, but can be read from `OS.get_cmdline_user_args()`.\n");
  461. #ifdef TOOLS_ENABLED
  462. print_help_option("-e, --editor", "Start the editor instead of running the scene.\n", CLI_OPTION_AVAILABILITY_EDITOR);
  463. print_help_option("-p, --project-manager", "Start the project manager, even if a project is auto-detected.\n", CLI_OPTION_AVAILABILITY_EDITOR);
  464. print_help_option("--debug-server <uri>", "Start the editor debug server (<protocol>://<host/IP>[:port], e.g. tcp://127.0.0.1:6007)\n", CLI_OPTION_AVAILABILITY_EDITOR);
  465. print_help_option("--dap-port <port>", "Use the specified port for the GDScript Debugger Adaptor protocol. Recommended port range [1024, 49151].\n", CLI_OPTION_AVAILABILITY_EDITOR);
  466. #if defined(MODULE_GDSCRIPT_ENABLED) && !defined(GDSCRIPT_NO_LSP)
  467. print_help_option("--lsp-port <port>", "Use the specified port for the GDScript language server protocol. Recommended port range [1024, 49151].\n", CLI_OPTION_AVAILABILITY_EDITOR);
  468. #endif // MODULE_GDSCRIPT_ENABLED && !GDSCRIPT_NO_LSP
  469. #endif
  470. print_help_option("--quit", "Quit after the first iteration.\n");
  471. print_help_option("--quit-after <int>", "Quit after the given number of iterations. Set to 0 to disable.\n");
  472. print_help_option("-l, --language <locale>", "Use a specific locale (<locale> being a two-letter code).\n");
  473. print_help_option("--path <directory>", "Path to a project (<directory> must contain a \"project.godot\" file).\n");
  474. print_help_option("-u, --upwards", "Scan folders upwards for project.godot file.\n");
  475. print_help_option("--main-pack <file>", "Path to a pack (.pck) file to load.\n");
  476. print_help_option("--render-thread <mode>", "Render thread mode (\"unsafe\", \"safe\", \"separate\").\n");
  477. print_help_option("--remote-fs <address>", "Remote filesystem (<host/IP>[:<port>] address).\n");
  478. print_help_option("--remote-fs-password <password>", "Password for remote filesystem.\n");
  479. print_help_option("--audio-driver <driver>", "Audio driver [");
  480. for (int i = 0; i < AudioDriverManager::get_driver_count(); i++) {
  481. if (i > 0) {
  482. OS::get_singleton()->print(", ");
  483. }
  484. OS::get_singleton()->print("\"%s\"", AudioDriverManager::get_driver(i)->get_name());
  485. }
  486. OS::get_singleton()->print("].\n");
  487. print_help_option("--display-driver <driver>", "Display driver (and rendering driver) [");
  488. for (int i = 0; i < DisplayServer::get_create_function_count(); i++) {
  489. if (i > 0) {
  490. OS::get_singleton()->print(", ");
  491. }
  492. OS::get_singleton()->print("\"%s\" (", DisplayServer::get_create_function_name(i));
  493. Vector<String> rd = DisplayServer::get_create_function_rendering_drivers(i);
  494. for (int j = 0; j < rd.size(); j++) {
  495. if (j > 0) {
  496. OS::get_singleton()->print(", ");
  497. }
  498. OS::get_singleton()->print("\"%s\"", rd[j].utf8().get_data());
  499. }
  500. OS::get_singleton()->print(")");
  501. }
  502. OS::get_singleton()->print("].\n");
  503. print_help_option("--audio-output-latency <ms>", "Override audio output latency in milliseconds (default is 15 ms).\n");
  504. print_help_option("", "Lower values make sound playback more reactive but increase CPU usage, and may result in audio cracking if the CPU can't keep up.\n");
  505. print_help_option("--rendering-method <renderer>", "Renderer name. Requires driver support.\n");
  506. print_help_option("--rendering-driver <driver>", "Rendering driver (depends on display driver).\n");
  507. print_help_option("--gpu-index <device_index>", "Use a specific GPU (run with --verbose to get a list of available devices).\n");
  508. print_help_option("--text-driver <driver>", "Text driver (used for font rendering, bidirectional support and shaping).\n");
  509. print_help_option("--tablet-driver <driver>", "Pen tablet input driver.\n");
  510. print_help_option("--headless", "Enable headless mode (--display-driver headless --audio-driver Dummy). Useful for servers and with --script.\n");
  511. print_help_option("--log-file <file>", "Write output/error log to the specified path instead of the default location defined by the project.\n");
  512. print_help_option("", "<file> path should be absolute or relative to the project directory.\n");
  513. print_help_option("--write-movie <file>", "Write a video to the specified path (usually with .avi or .png extension).\n");
  514. print_help_option("", "--fixed-fps is forced when enabled, but it can be used to change movie FPS.\n");
  515. print_help_option("", "--disable-vsync can speed up movie writing but makes interaction more difficult.\n");
  516. print_help_option("", "--quit-after can be used to specify the number of frames to write.\n");
  517. print_help_title("Display options");
  518. print_help_option("-f, --fullscreen", "Request fullscreen mode.\n");
  519. print_help_option("-m, --maximized", "Request a maximized window.\n");
  520. print_help_option("-w, --windowed", "Request windowed mode.\n");
  521. print_help_option("-t, --always-on-top", "Request an always-on-top window.\n");
  522. print_help_option("--resolution <W>x<H>", "Request window resolution.\n");
  523. print_help_option("--position <X>,<Y>", "Request window position.\n");
  524. print_help_option("--screen <N>", "Request window screen.\n");
  525. print_help_option("--single-window", "Use a single window (no separate subwindows).\n");
  526. print_help_option("--xr-mode <mode>", "Select XR (Extended Reality) mode [\"default\", \"off\", \"on\"].\n");
  527. print_help_title("Debug options");
  528. print_help_option("-d, --debug", "Debug (local stdout debugger).\n");
  529. print_help_option("-b, --breakpoints", "Breakpoint list as source::line comma-separated pairs, no spaces (use %%20 instead).\n");
  530. print_help_option("--profiling", "Enable profiling in the script debugger.\n");
  531. print_help_option("--gpu-profile", "Show a GPU profile of the tasks that took the most time during frame rendering.\n");
  532. print_help_option("--gpu-validation", "Enable graphics API validation layers for debugging.\n");
  533. #ifdef DEBUG_ENABLED
  534. print_help_option("--gpu-abort", "Abort on graphics API usage errors (usually validation layer errors). May help see the problem if your system freezes.\n", CLI_OPTION_AVAILABILITY_TEMPLATE_DEBUG);
  535. #endif
  536. print_help_option("--generate-spirv-debug-info", "Generate SPIR-V debug information. This allows source-level shader debugging with RenderDoc.\n");
  537. print_help_option("--remote-debug <uri>", "Remote debug (<protocol>://<host/IP>[:<port>], e.g. tcp://127.0.0.1:6007).\n");
  538. print_help_option("--single-threaded-scene", "Force scene tree to run in single-threaded mode. Sub-thread groups are disabled and run on the main thread.\n");
  539. #if defined(DEBUG_ENABLED)
  540. print_help_option("--debug-collisions", "Show collision shapes when running the scene.\n", CLI_OPTION_AVAILABILITY_TEMPLATE_DEBUG);
  541. print_help_option("--debug-paths", "Show path lines when running the scene.\n", CLI_OPTION_AVAILABILITY_TEMPLATE_DEBUG);
  542. print_help_option("--debug-navigation", "Show navigation polygons when running the scene.\n", CLI_OPTION_AVAILABILITY_TEMPLATE_DEBUG);
  543. print_help_option("--debug-avoidance", "Show navigation avoidance debug visuals when running the scene.\n", CLI_OPTION_AVAILABILITY_TEMPLATE_DEBUG);
  544. print_help_option("--debug-stringnames", "Print all StringName allocations to stdout when the engine quits.\n", CLI_OPTION_AVAILABILITY_TEMPLATE_DEBUG);
  545. print_help_option("--debug-canvas-item-redraw", "Display a rectangle each time a canvas item requests a redraw (useful to troubleshoot low processor mode).\n", CLI_OPTION_AVAILABILITY_TEMPLATE_DEBUG);
  546. #endif
  547. print_help_option("--max-fps <fps>", "Set a maximum number of frames per second rendered (can be used to limit power usage). A value of 0 results in unlimited framerate.\n");
  548. print_help_option("--frame-delay <ms>", "Simulate high CPU load (delay each frame by <ms> milliseconds). Do not use as a FPS limiter; use --max-fps instead.\n");
  549. print_help_option("--time-scale <scale>", "Force time scale (higher values are faster, 1.0 is normal speed).\n");
  550. print_help_option("--disable-vsync", "Forces disabling of vertical synchronization, even if enabled in the project settings. Does not override driver-level V-Sync enforcement.\n");
  551. print_help_option("--disable-render-loop", "Disable render loop so rendering only occurs when called explicitly from script.\n");
  552. print_help_option("--disable-crash-handler", "Disable crash handler when supported by the platform code.\n");
  553. print_help_option("--fixed-fps <fps>", "Force a fixed number of frames per second. This setting disables real-time synchronization.\n");
  554. print_help_option("--delta-smoothing <enable>", "Enable or disable frame delta smoothing [\"enable\", \"disable\"].\n");
  555. print_help_option("--print-fps", "Print the frames per second to the stdout.\n");
  556. print_help_title("Standalone tools");
  557. print_help_option("-s, --script <script>", "Run a script.\n");
  558. print_help_option("--main-loop <main_loop_name>", "Run a MainLoop specified by its global class name.\n");
  559. print_help_option("--check-only", "Only parse for errors and quit (use with --script).\n");
  560. #ifdef TOOLS_ENABLED
  561. print_help_option("--import", "Starts the editor, waits for any resources to be imported, and then quits.\n", CLI_OPTION_AVAILABILITY_EDITOR);
  562. print_help_option("--export-release <preset> <path>", "Export the project in release mode using the given preset and output path. The preset name should match one defined in \"export_presets.cfg\".\n", CLI_OPTION_AVAILABILITY_EDITOR);
  563. print_help_option("", "<path> should be absolute or relative to the project directory, and include the filename for the binary (e.g. \"builds/game.exe\").\n");
  564. print_help_option("", "The target directory must exist.\n");
  565. print_help_option("--export-debug <preset> <path>", "Export the project in debug mode using the given preset and output path. See --export-release description for other considerations.\n", CLI_OPTION_AVAILABILITY_EDITOR);
  566. print_help_option("--export-pack <preset> <path>", "Export the project data only using the given preset and output path. The <path> extension determines whether it will be in PCK or ZIP format.\n", CLI_OPTION_AVAILABILITY_EDITOR);
  567. print_help_option("--install-android-build-template", "Install the Android build template. Used in conjunction with --export-release or --export-debug.\n", CLI_OPTION_AVAILABILITY_EDITOR);
  568. #ifndef DISABLE_DEPRECATED
  569. // Commands are long; split the description to a second line.
  570. print_help_option("--convert-3to4 ", "\n", CLI_OPTION_AVAILABILITY_HIDDEN);
  571. print_help_option(" [max_file_kb] [max_line_size]", "Converts project from Godot 3.x to Godot 4.x.\n", CLI_OPTION_AVAILABILITY_EDITOR);
  572. print_help_option("--validate-conversion-3to4 ", "\n", CLI_OPTION_AVAILABILITY_HIDDEN);
  573. print_help_option(" [max_file_kb] [max_line_size]", "Shows what elements will be renamed when converting project from Godot 3.x to Godot 4.x.\n", CLI_OPTION_AVAILABILITY_EDITOR);
  574. #endif // DISABLE_DEPRECATED
  575. print_help_option("--doctool [path]", "Dump the engine API reference to the given <path> (defaults to current directory) in XML format, merging if existing files are found.\n", CLI_OPTION_AVAILABILITY_EDITOR);
  576. print_help_option("--no-docbase", "Disallow dumping the base types (used with --doctool).\n", CLI_OPTION_AVAILABILITY_EDITOR);
  577. print_help_option("--gdextension-docs", "Rather than dumping the engine API, generate API reference from all the GDExtensions loaded in the current project (used with --doctool).\n", CLI_OPTION_AVAILABILITY_EDITOR);
  578. #ifdef MODULE_GDSCRIPT_ENABLED
  579. print_help_option("--gdscript-docs <path>", "Rather than dumping the engine API, generate API reference from the inline documentation in the GDScript files found in <path> (used with --doctool).\n", CLI_OPTION_AVAILABILITY_EDITOR);
  580. #endif
  581. print_help_option("--build-solutions", "Build the scripting solutions (e.g. for C# projects). Implies --editor and requires a valid project to edit.\n", CLI_OPTION_AVAILABILITY_EDITOR);
  582. print_help_option("--dump-gdextension-interface", "Generate a GDExtension header file \"gdextension_interface.h\" in the current folder. This file is the base file required to implement a GDExtension.\n", CLI_OPTION_AVAILABILITY_EDITOR);
  583. print_help_option("--dump-extension-api", "Generate a JSON dump of the Godot API for GDExtension bindings named \"extension_api.json\" in the current folder.\n", CLI_OPTION_AVAILABILITY_EDITOR);
  584. print_help_option("--dump-extension-api-with-docs", "Generate JSON dump of the Godot API like the previous option, but including documentation.\n", CLI_OPTION_AVAILABILITY_EDITOR);
  585. print_help_option("--validate-extension-api <path>", "Validate an extension API file dumped (with one of the two previous options) from a previous version of the engine to ensure API compatibility.\n", CLI_OPTION_AVAILABILITY_EDITOR);
  586. print_help_option("", "If incompatibilities or errors are detected, the exit code will be non-zero.\n");
  587. print_help_option("--benchmark", "Benchmark the run time and print it to console.\n", CLI_OPTION_AVAILABILITY_EDITOR);
  588. print_help_option("--benchmark-file <path>", "Benchmark the run time and save it to a given file in JSON format. The path should be absolute.\n", CLI_OPTION_AVAILABILITY_EDITOR);
  589. #ifdef TESTS_ENABLED
  590. print_help_option("--test [--help]", "Run unit tests. Use --test --help for more information.\n", CLI_OPTION_AVAILABILITY_EDITOR);
  591. #endif
  592. #endif
  593. OS::get_singleton()->print("\n");
  594. }
  595. #ifdef TESTS_ENABLED
  596. // The order is the same as in `Main::setup()`, only core and some editor types
  597. // are initialized here. This also combines `Main::setup2()` initialization.
  598. Error Main::test_setup() {
  599. Thread::make_main_thread();
  600. set_current_thread_safe_for_nodes(true);
  601. OS::get_singleton()->initialize();
  602. engine = memnew(Engine);
  603. register_core_types();
  604. register_core_driver_types();
  605. packed_data = memnew(PackedData);
  606. globals = memnew(ProjectSettings);
  607. register_core_settings(); // Here globals are present.
  608. translation_server = memnew(TranslationServer);
  609. tsman = memnew(TextServerManager);
  610. if (tsman) {
  611. Ref<TextServerDummy> ts;
  612. ts.instantiate();
  613. tsman->add_interface(ts);
  614. }
  615. #ifndef _3D_DISABLED
  616. physics_server_3d_manager = memnew(PhysicsServer3DManager);
  617. #endif // _3D_DISABLED
  618. physics_server_2d_manager = memnew(PhysicsServer2DManager);
  619. // From `Main::setup2()`.
  620. initialize_modules(MODULE_INITIALIZATION_LEVEL_CORE);
  621. register_core_extensions();
  622. register_core_singletons();
  623. /** INITIALIZE SERVERS **/
  624. register_server_types();
  625. #ifndef _3D_DISABLED
  626. XRServer::set_xr_mode(XRServer::XRMODE_OFF); // Skip in tests.
  627. #endif // _3D_DISABLED
  628. initialize_modules(MODULE_INITIALIZATION_LEVEL_SERVERS);
  629. GDExtensionManager::get_singleton()->initialize_extensions(GDExtension::INITIALIZATION_LEVEL_SERVERS);
  630. translation_server->setup(); //register translations, load them, etc.
  631. if (!locale.is_empty()) {
  632. translation_server->set_locale(locale);
  633. }
  634. translation_server->load_translations();
  635. ResourceLoader::load_translation_remaps(); //load remaps for resources
  636. ResourceLoader::load_path_remaps();
  637. // Initialize ThemeDB early so that scene types can register their theme items.
  638. // Default theme will be initialized later, after modules and ScriptServer are ready.
  639. initialize_theme_db();
  640. register_scene_types();
  641. register_driver_types();
  642. register_scene_singletons();
  643. initialize_modules(MODULE_INITIALIZATION_LEVEL_SCENE);
  644. GDExtensionManager::get_singleton()->initialize_extensions(GDExtension::INITIALIZATION_LEVEL_SCENE);
  645. #ifdef TOOLS_ENABLED
  646. ClassDB::set_current_api(ClassDB::API_EDITOR);
  647. register_editor_types();
  648. initialize_modules(MODULE_INITIALIZATION_LEVEL_EDITOR);
  649. GDExtensionManager::get_singleton()->initialize_extensions(GDExtension::INITIALIZATION_LEVEL_EDITOR);
  650. ClassDB::set_current_api(ClassDB::API_CORE);
  651. #endif
  652. register_platform_apis();
  653. // Theme needs modules to be initialized so that sub-resources can be loaded.
  654. theme_db->initialize_theme_noproject();
  655. initialize_navigation_server();
  656. ERR_FAIL_COND_V(TextServerManager::get_singleton()->get_interface_count() == 0, ERR_CANT_CREATE);
  657. /* Use one with the most features available. */
  658. int max_features = 0;
  659. for (int i = 0; i < TextServerManager::get_singleton()->get_interface_count(); i++) {
  660. uint32_t features = TextServerManager::get_singleton()->get_interface(i)->get_features();
  661. int feature_number = 0;
  662. while (features) {
  663. feature_number += features & 1;
  664. features >>= 1;
  665. }
  666. if (feature_number >= max_features) {
  667. max_features = feature_number;
  668. text_driver_idx = i;
  669. }
  670. }
  671. if (text_driver_idx >= 0) {
  672. Ref<TextServer> ts = TextServerManager::get_singleton()->get_interface(text_driver_idx);
  673. TextServerManager::get_singleton()->set_primary_interface(ts);
  674. if (ts->has_feature(TextServer::FEATURE_USE_SUPPORT_DATA)) {
  675. ts->load_support_data("res://" + ts->get_support_data_filename());
  676. }
  677. } else {
  678. ERR_FAIL_V_MSG(ERR_CANT_CREATE, "TextServer: Unable to create TextServer interface.");
  679. }
  680. ClassDB::set_current_api(ClassDB::API_NONE);
  681. _start_success = true;
  682. return OK;
  683. }
  684. // The order is the same as in `Main::cleanup()`.
  685. void Main::test_cleanup() {
  686. ERR_FAIL_COND(!_start_success);
  687. for (int i = 0; i < TextServerManager::get_singleton()->get_interface_count(); i++) {
  688. TextServerManager::get_singleton()->get_interface(i)->cleanup();
  689. }
  690. ResourceLoader::remove_custom_loaders();
  691. ResourceSaver::remove_custom_savers();
  692. PropertyListHelper::clear_base_helpers();
  693. #ifdef TOOLS_ENABLED
  694. GDExtensionManager::get_singleton()->deinitialize_extensions(GDExtension::INITIALIZATION_LEVEL_EDITOR);
  695. uninitialize_modules(MODULE_INITIALIZATION_LEVEL_EDITOR);
  696. unregister_editor_types();
  697. #endif
  698. GDExtensionManager::get_singleton()->deinitialize_extensions(GDExtension::INITIALIZATION_LEVEL_SCENE);
  699. uninitialize_modules(MODULE_INITIALIZATION_LEVEL_SCENE);
  700. unregister_platform_apis();
  701. unregister_driver_types();
  702. unregister_scene_types();
  703. finalize_theme_db();
  704. finalize_navigation_server();
  705. GDExtensionManager::get_singleton()->deinitialize_extensions(GDExtension::INITIALIZATION_LEVEL_SERVERS);
  706. uninitialize_modules(MODULE_INITIALIZATION_LEVEL_SERVERS);
  707. unregister_server_types();
  708. EngineDebugger::deinitialize();
  709. OS::get_singleton()->finalize();
  710. if (packed_data) {
  711. memdelete(packed_data);
  712. }
  713. if (translation_server) {
  714. memdelete(translation_server);
  715. }
  716. if (tsman) {
  717. memdelete(tsman);
  718. }
  719. #ifndef _3D_DISABLED
  720. if (physics_server_3d_manager) {
  721. memdelete(physics_server_3d_manager);
  722. }
  723. #endif // _3D_DISABLED
  724. if (physics_server_2d_manager) {
  725. memdelete(physics_server_2d_manager);
  726. }
  727. if (globals) {
  728. memdelete(globals);
  729. }
  730. unregister_core_driver_types();
  731. unregister_core_extensions();
  732. uninitialize_modules(MODULE_INITIALIZATION_LEVEL_CORE);
  733. if (engine) {
  734. memdelete(engine);
  735. }
  736. unregister_core_types();
  737. OS::get_singleton()->finalize_core();
  738. }
  739. #endif
  740. int Main::test_entrypoint(int argc, char *argv[], bool &tests_need_run) {
  741. for (int x = 0; x < argc; x++) {
  742. if ((strncmp(argv[x], "--test", 6) == 0) && (strlen(argv[x]) == 6)) {
  743. tests_need_run = true;
  744. #ifdef TESTS_ENABLED
  745. // TODO: need to come up with different test contexts.
  746. // Not every test requires high-level functionality like `ClassDB`.
  747. test_setup();
  748. int status = test_main(argc, argv);
  749. test_cleanup();
  750. return status;
  751. #else
  752. ERR_PRINT(
  753. "`--test` was specified on the command line, but this Godot binary was compiled without support for unit tests. Aborting.\n"
  754. "To be able to run unit tests, use the `tests=yes` SCons option when compiling Godot.\n");
  755. return EXIT_FAILURE;
  756. #endif
  757. }
  758. }
  759. tests_need_run = false;
  760. return EXIT_SUCCESS;
  761. }
  762. /* Engine initialization
  763. *
  764. * Consists of several methods that are called by each platform's specific main(argc, argv).
  765. * To fully understand engine init, one should therefore start from the platform's main and
  766. * see how it calls into the Main class' methods.
  767. *
  768. * The initialization is typically done in 3 steps (with the setup2 step triggered either
  769. * automatically by setup, or manually in the platform's main).
  770. *
  771. * - setup(execpath, argc, argv, p_second_phase) is the main entry point for all platforms,
  772. * responsible for the initialization of all low level singletons and core types, and parsing
  773. * command line arguments to configure things accordingly.
  774. * If p_second_phase is true, it will chain into setup2() (default behavior). This is
  775. * disabled on some platforms (Android, iOS) which trigger the second step in their own time.
  776. *
  777. * - setup2(p_main_tid_override) registers high level servers and singletons, displays the
  778. * boot splash, then registers higher level types (scene, editor, etc.).
  779. *
  780. * - start() is the last step and that's where command line tools can run, or the main loop
  781. * can be created eventually and the project settings put into action. That's also where
  782. * the editor node is created, if relevant.
  783. * start() does it own argument parsing for a subset of the command line arguments described
  784. * in help, it's a bit messy and should be globalized with the setup() parsing somehow.
  785. */
  786. Error Main::setup(const char *execpath, int argc, char *argv[], bool p_second_phase) {
  787. Thread::make_main_thread();
  788. set_current_thread_safe_for_nodes(true);
  789. OS::get_singleton()->initialize();
  790. // Benchmark tracking must be done after `OS::get_singleton()->initialize()` as on some
  791. // platforms, it's used to set up the time utilities.
  792. OS::get_singleton()->benchmark_begin_measure("Startup", "Main::Setup");
  793. engine = memnew(Engine);
  794. MAIN_PRINT("Main: Initialize CORE");
  795. register_core_types();
  796. register_core_driver_types();
  797. MAIN_PRINT("Main: Initialize Globals");
  798. input_map = memnew(InputMap);
  799. globals = memnew(ProjectSettings);
  800. register_core_settings(); //here globals are present
  801. translation_server = memnew(TranslationServer);
  802. performance = memnew(Performance);
  803. GDREGISTER_CLASS(Performance);
  804. engine->add_singleton(Engine::Singleton("Performance", performance));
  805. // Only flush stdout in debug builds by default, as spamming `print()` will
  806. // decrease performance if this is enabled.
  807. GLOBAL_DEF_RST("application/run/flush_stdout_on_print", false);
  808. GLOBAL_DEF_RST("application/run/flush_stdout_on_print.debug", true);
  809. MAIN_PRINT("Main: Parse CMDLine");
  810. /* argument parsing and main creation */
  811. List<String> args;
  812. List<String> main_args;
  813. List<String> user_args;
  814. bool adding_user_args = false;
  815. List<String> platform_args = OS::get_singleton()->get_cmdline_platform_args();
  816. // Add command line arguments.
  817. for (int i = 0; i < argc; i++) {
  818. args.push_back(String::utf8(argv[i]));
  819. }
  820. // Add arguments received from macOS LaunchService (URL schemas, file associations).
  821. for (const String &arg : platform_args) {
  822. args.push_back(arg);
  823. }
  824. List<String>::Element *I = args.front();
  825. while (I) {
  826. I->get() = unescape_cmdline(I->get().strip_edges());
  827. I = I->next();
  828. }
  829. String audio_driver = "";
  830. String project_path = ".";
  831. bool upwards = false;
  832. String debug_uri = "";
  833. bool skip_breakpoints = false;
  834. String main_pack;
  835. bool quiet_stdout = false;
  836. int rtm = -1;
  837. String remotefs;
  838. String remotefs_pass;
  839. Vector<String> breakpoints;
  840. bool use_custom_res = true;
  841. bool force_res = false;
  842. bool delta_smoothing_override = false;
  843. String default_renderer = "";
  844. String default_renderer_mobile = "";
  845. String renderer_hints = "";
  846. packed_data = PackedData::get_singleton();
  847. if (!packed_data) {
  848. packed_data = memnew(PackedData);
  849. }
  850. #ifdef MINIZIP_ENABLED
  851. //XXX: always get_singleton() == 0x0
  852. zip_packed_data = ZipArchive::get_singleton();
  853. //TODO: remove this temporary fix
  854. if (!zip_packed_data) {
  855. zip_packed_data = memnew(ZipArchive);
  856. }
  857. packed_data->add_pack_source(zip_packed_data);
  858. #endif
  859. // Exit error code used in the `goto error` conditions.
  860. // It's returned as the program exit code. ERR_HELP is special cased and handled as success (0).
  861. Error exit_err = ERR_INVALID_PARAMETER;
  862. I = args.front();
  863. while (I) {
  864. List<String>::Element *N = I->next();
  865. const String &arg = I->get();
  866. #ifdef MACOS_ENABLED
  867. // Ignore the process serial number argument passed by macOS Gatekeeper.
  868. // Otherwise, Godot would try to open a non-existent project on the first start and abort.
  869. if (arg.begins_with("-psn_")) {
  870. I = N;
  871. continue;
  872. }
  873. #endif
  874. #ifdef TOOLS_ENABLED
  875. if (arg == "--debug" ||
  876. arg == "--verbose" ||
  877. arg == "--disable-crash-handler") {
  878. forwardable_cli_arguments[CLI_SCOPE_TOOL].push_back(arg);
  879. forwardable_cli_arguments[CLI_SCOPE_PROJECT].push_back(arg);
  880. }
  881. if (arg == "--single-window") {
  882. forwardable_cli_arguments[CLI_SCOPE_TOOL].push_back(arg);
  883. }
  884. if (arg == "--audio-driver" ||
  885. arg == "--display-driver" ||
  886. arg == "--rendering-method" ||
  887. arg == "--rendering-driver") {
  888. if (N) {
  889. forwardable_cli_arguments[CLI_SCOPE_TOOL].push_back(arg);
  890. forwardable_cli_arguments[CLI_SCOPE_TOOL].push_back(N->get());
  891. }
  892. }
  893. // If gpu is specified, both editor and debug instances started from editor will inherit.
  894. if (arg == "--gpu-index") {
  895. if (N) {
  896. const String &next_arg = N->get();
  897. forwardable_cli_arguments[CLI_SCOPE_TOOL].push_back(arg);
  898. forwardable_cli_arguments[CLI_SCOPE_TOOL].push_back(next_arg);
  899. forwardable_cli_arguments[CLI_SCOPE_PROJECT].push_back(arg);
  900. forwardable_cli_arguments[CLI_SCOPE_PROJECT].push_back(next_arg);
  901. }
  902. }
  903. #endif
  904. if (adding_user_args) {
  905. user_args.push_back(arg);
  906. } else if (arg == "-h" || arg == "--help" || arg == "/?") { // display help
  907. show_help = true;
  908. exit_err = ERR_HELP; // Hack to force an early exit in `main()` with a success code.
  909. goto error;
  910. } else if (arg == "--version") {
  911. print_line(get_full_version_string());
  912. exit_err = ERR_HELP; // Hack to force an early exit in `main()` with a success code.
  913. goto error;
  914. } else if (arg == "-v" || arg == "--verbose") { // verbose output
  915. OS::get_singleton()->_verbose_stdout = true;
  916. } else if (arg == "-q" || arg == "--quiet") { // quieter output
  917. quiet_stdout = true;
  918. } else if (arg == "--no-header") {
  919. Engine::get_singleton()->_print_header = false;
  920. } else if (arg == "--audio-driver") { // audio driver
  921. if (N) {
  922. audio_driver = N->get();
  923. bool found = false;
  924. for (int i = 0; i < AudioDriverManager::get_driver_count(); i++) {
  925. if (audio_driver == AudioDriverManager::get_driver(i)->get_name()) {
  926. found = true;
  927. }
  928. }
  929. if (!found) {
  930. OS::get_singleton()->print("Unknown audio driver '%s', aborting.\nValid options are ",
  931. audio_driver.utf8().get_data());
  932. for (int i = 0; i < AudioDriverManager::get_driver_count(); i++) {
  933. if (i == AudioDriverManager::get_driver_count() - 1) {
  934. OS::get_singleton()->print(" and ");
  935. } else if (i != 0) {
  936. OS::get_singleton()->print(", ");
  937. }
  938. OS::get_singleton()->print("'%s'", AudioDriverManager::get_driver(i)->get_name());
  939. }
  940. OS::get_singleton()->print(".\n");
  941. goto error;
  942. }
  943. N = N->next();
  944. } else {
  945. OS::get_singleton()->print("Missing audio driver argument, aborting.\n");
  946. goto error;
  947. }
  948. } else if (arg == "--audio-output-latency") {
  949. if (N) {
  950. audio_output_latency = N->get().to_int();
  951. N = N->next();
  952. } else {
  953. OS::get_singleton()->print("Missing audio output latency argument, aborting.\n");
  954. goto error;
  955. }
  956. } else if (arg == "--text-driver") {
  957. if (N) {
  958. text_driver = N->get();
  959. N = N->next();
  960. } else {
  961. OS::get_singleton()->print("Missing text driver argument, aborting.\n");
  962. goto error;
  963. }
  964. } else if (arg == "--display-driver") { // force video driver
  965. if (N) {
  966. display_driver = N->get();
  967. bool found = false;
  968. for (int i = 0; i < DisplayServer::get_create_function_count(); i++) {
  969. if (display_driver == DisplayServer::get_create_function_name(i)) {
  970. found = true;
  971. }
  972. }
  973. if (!found) {
  974. OS::get_singleton()->print("Unknown display driver '%s', aborting.\nValid options are ",
  975. display_driver.utf8().get_data());
  976. for (int i = 0; i < DisplayServer::get_create_function_count(); i++) {
  977. if (i == DisplayServer::get_create_function_count() - 1) {
  978. OS::get_singleton()->print(" and ");
  979. } else if (i != 0) {
  980. OS::get_singleton()->print(", ");
  981. }
  982. OS::get_singleton()->print("'%s'", DisplayServer::get_create_function_name(i));
  983. }
  984. OS::get_singleton()->print(".\n");
  985. goto error;
  986. }
  987. N = N->next();
  988. } else {
  989. OS::get_singleton()->print("Missing display driver argument, aborting.\n");
  990. goto error;
  991. }
  992. } else if (arg == "--rendering-method") {
  993. if (N) {
  994. rendering_method = N->get();
  995. N = N->next();
  996. } else {
  997. OS::get_singleton()->print("Missing renderer name argument, aborting.\n");
  998. goto error;
  999. }
  1000. } else if (arg == "--rendering-driver") {
  1001. if (N) {
  1002. rendering_driver = N->get();
  1003. N = N->next();
  1004. } else {
  1005. OS::get_singleton()->print("Missing rendering driver argument, aborting.\n");
  1006. goto error;
  1007. }
  1008. } else if (arg == "-f" || arg == "--fullscreen") { // force fullscreen
  1009. init_fullscreen = true;
  1010. window_mode = DisplayServer::WINDOW_MODE_FULLSCREEN;
  1011. } else if (arg == "-m" || arg == "--maximized") { // force maximized window
  1012. init_maximized = true;
  1013. window_mode = DisplayServer::WINDOW_MODE_MAXIMIZED;
  1014. } else if (arg == "-w" || arg == "--windowed") { // force windowed window
  1015. init_windowed = true;
  1016. } else if (arg == "--gpu-index") {
  1017. if (N) {
  1018. Engine::singleton->gpu_idx = N->get().to_int();
  1019. N = N->next();
  1020. } else {
  1021. OS::get_singleton()->print("Missing GPU index argument, aborting.\n");
  1022. goto error;
  1023. }
  1024. } else if (arg == "--gpu-validation") {
  1025. Engine::singleton->use_validation_layers = true;
  1026. #ifdef DEBUG_ENABLED
  1027. } else if (arg == "--gpu-abort") {
  1028. Engine::singleton->abort_on_gpu_errors = true;
  1029. #endif
  1030. } else if (arg == "--generate-spirv-debug-info") {
  1031. Engine::singleton->generate_spirv_debug_info = true;
  1032. } else if (arg == "--tablet-driver") {
  1033. if (N) {
  1034. tablet_driver = N->get();
  1035. N = N->next();
  1036. } else {
  1037. OS::get_singleton()->print("Missing tablet driver argument, aborting.\n");
  1038. goto error;
  1039. }
  1040. } else if (arg == "--delta-smoothing") {
  1041. if (N) {
  1042. String string = N->get();
  1043. bool recognized = false;
  1044. if (string == "enable") {
  1045. OS::get_singleton()->set_delta_smoothing(true);
  1046. delta_smoothing_override = true;
  1047. recognized = true;
  1048. }
  1049. if (string == "disable") {
  1050. OS::get_singleton()->set_delta_smoothing(false);
  1051. delta_smoothing_override = false;
  1052. recognized = true;
  1053. }
  1054. if (!recognized) {
  1055. OS::get_singleton()->print("Delta-smoothing argument not recognized, aborting.\n");
  1056. goto error;
  1057. }
  1058. N = N->next();
  1059. } else {
  1060. OS::get_singleton()->print("Missing delta-smoothing argument, aborting.\n");
  1061. goto error;
  1062. }
  1063. } else if (arg == "--single-window") { // force single window
  1064. single_window = true;
  1065. } else if (arg == "-t" || arg == "--always-on-top") { // force always-on-top window
  1066. init_always_on_top = true;
  1067. } else if (arg == "--resolution") { // force resolution
  1068. if (N) {
  1069. String vm = N->get();
  1070. if (!vm.contains("x")) { // invalid parameter format
  1071. OS::get_singleton()->print("Invalid resolution '%s', it should be e.g. '1280x720'.\n",
  1072. vm.utf8().get_data());
  1073. goto error;
  1074. }
  1075. int w = vm.get_slice("x", 0).to_int();
  1076. int h = vm.get_slice("x", 1).to_int();
  1077. if (w <= 0 || h <= 0) {
  1078. OS::get_singleton()->print("Invalid resolution '%s', width and height must be above 0.\n",
  1079. vm.utf8().get_data());
  1080. goto error;
  1081. }
  1082. window_size.width = w;
  1083. window_size.height = h;
  1084. force_res = true;
  1085. N = N->next();
  1086. } else {
  1087. OS::get_singleton()->print("Missing resolution argument, aborting.\n");
  1088. goto error;
  1089. }
  1090. } else if (arg == "--screen") { // set window screen
  1091. if (N) {
  1092. init_screen = N->get().to_int();
  1093. init_use_custom_screen = true;
  1094. N = N->next();
  1095. } else {
  1096. OS::get_singleton()->print("Missing screen argument, aborting.\n");
  1097. goto error;
  1098. }
  1099. } else if (arg == "--position") { // set window position
  1100. if (N) {
  1101. String vm = N->get();
  1102. if (!vm.contains(",")) { // invalid parameter format
  1103. OS::get_singleton()->print("Invalid position '%s', it should be e.g. '80,128'.\n",
  1104. vm.utf8().get_data());
  1105. goto error;
  1106. }
  1107. int x = vm.get_slice(",", 0).to_int();
  1108. int y = vm.get_slice(",", 1).to_int();
  1109. init_custom_pos = Point2(x, y);
  1110. init_use_custom_pos = true;
  1111. N = N->next();
  1112. } else {
  1113. OS::get_singleton()->print("Missing position argument, aborting.\n");
  1114. goto error;
  1115. }
  1116. } else if (arg == "--headless") { // enable headless mode (no audio, no rendering).
  1117. audio_driver = NULL_AUDIO_DRIVER;
  1118. display_driver = NULL_DISPLAY_DRIVER;
  1119. } else if (arg == "--log-file") { // write to log file
  1120. if (N) {
  1121. log_file = N->get();
  1122. N = N->next();
  1123. } else {
  1124. OS::get_singleton()->print("Missing log file path argument, aborting.\n");
  1125. goto error;
  1126. }
  1127. } else if (arg == "--profiling") { // enable profiling
  1128. use_debug_profiler = true;
  1129. } else if (arg == "-l" || arg == "--language") { // language
  1130. if (N) {
  1131. locale = N->get();
  1132. N = N->next();
  1133. } else {
  1134. OS::get_singleton()->print("Missing language argument, aborting.\n");
  1135. goto error;
  1136. }
  1137. } else if (arg == "--remote-fs") { // remote filesystem
  1138. if (N) {
  1139. remotefs = N->get();
  1140. N = N->next();
  1141. } else {
  1142. OS::get_singleton()->print("Missing remote filesystem address, aborting.\n");
  1143. goto error;
  1144. }
  1145. } else if (arg == "--remote-fs-password") { // remote filesystem password
  1146. if (N) {
  1147. remotefs_pass = N->get();
  1148. N = N->next();
  1149. } else {
  1150. OS::get_singleton()->print("Missing remote filesystem password, aborting.\n");
  1151. goto error;
  1152. }
  1153. } else if (arg == "--render-thread") { // render thread mode
  1154. if (N) {
  1155. if (N->get() == "safe") {
  1156. rtm = OS::RENDER_THREAD_SAFE;
  1157. } else if (N->get() == "unsafe") {
  1158. rtm = OS::RENDER_THREAD_UNSAFE;
  1159. } else if (N->get() == "separate") {
  1160. rtm = OS::RENDER_SEPARATE_THREAD;
  1161. } else {
  1162. OS::get_singleton()->print("Unknown render thread mode, aborting.\nValid options are 'unsafe', 'safe' and 'separate'.\n");
  1163. goto error;
  1164. }
  1165. N = N->next();
  1166. } else {
  1167. OS::get_singleton()->print("Missing render thread mode argument, aborting.\n");
  1168. goto error;
  1169. }
  1170. #ifdef TOOLS_ENABLED
  1171. } else if (arg == "-e" || arg == "--editor") { // starts editor
  1172. editor = true;
  1173. } else if (arg == "-p" || arg == "--project-manager") { // starts project manager
  1174. project_manager = true;
  1175. } else if (arg == "--debug-server") {
  1176. if (N) {
  1177. debug_server_uri = N->get();
  1178. if (!debug_server_uri.contains("://")) { // wrong address
  1179. OS::get_singleton()->print("Invalid debug server uri. It should be of the form <protocol>://<bind_address>:<port>.\n");
  1180. goto error;
  1181. }
  1182. N = N->next();
  1183. } else {
  1184. OS::get_singleton()->print("Missing remote debug server uri, aborting.\n");
  1185. goto error;
  1186. }
  1187. } else if (arg == "--single-threaded-scene") {
  1188. single_threaded_scene = true;
  1189. } else if (arg == "--build-solutions") { // Build the scripting solution such C#
  1190. auto_build_solutions = true;
  1191. editor = true;
  1192. cmdline_tool = true;
  1193. } else if (arg == "--dump-gdextension-interface") {
  1194. // Register as an editor instance to use low-end fallback if relevant.
  1195. editor = true;
  1196. cmdline_tool = true;
  1197. dump_gdextension_interface = true;
  1198. print_line("Dumping GDExtension interface header file");
  1199. // Hack. Not needed but otherwise we end up detecting that this should
  1200. // run the project instead of a cmdline tool.
  1201. // Needs full refactoring to fix properly.
  1202. main_args.push_back(arg);
  1203. } else if (arg == "--dump-extension-api") {
  1204. // Register as an editor instance to use low-end fallback if relevant.
  1205. editor = true;
  1206. cmdline_tool = true;
  1207. dump_extension_api = true;
  1208. print_line("Dumping Extension API");
  1209. // Hack. Not needed but otherwise we end up detecting that this should
  1210. // run the project instead of a cmdline tool.
  1211. // Needs full refactoring to fix properly.
  1212. main_args.push_back(arg);
  1213. } else if (arg == "--dump-extension-api-with-docs") {
  1214. // Register as an editor instance to use low-end fallback if relevant.
  1215. editor = true;
  1216. cmdline_tool = true;
  1217. dump_extension_api = true;
  1218. include_docs_in_extension_api_dump = true;
  1219. print_line("Dumping Extension API including documentation");
  1220. // Hack. Not needed but otherwise we end up detecting that this should
  1221. // run the project instead of a cmdline tool.
  1222. // Needs full refactoring to fix properly.
  1223. main_args.push_back(arg);
  1224. } else if (arg == "--validate-extension-api") {
  1225. // Register as an editor instance to use low-end fallback if relevant.
  1226. editor = true;
  1227. cmdline_tool = true;
  1228. validate_extension_api = true;
  1229. // Hack. Not needed but otherwise we end up detecting that this should
  1230. // run the project instead of a cmdline tool.
  1231. // Needs full refactoring to fix properly.
  1232. main_args.push_back(arg);
  1233. if (N) {
  1234. validate_extension_api_file = N->get();
  1235. N = N->next();
  1236. } else {
  1237. OS::get_singleton()->print("Missing file to load argument after --validate-extension-api, aborting.");
  1238. goto error;
  1239. }
  1240. } else if (arg == "--import") {
  1241. editor = true;
  1242. cmdline_tool = true;
  1243. wait_for_import = true;
  1244. quit_after = 1;
  1245. } else if (arg == "--export-release" || arg == "--export-debug" ||
  1246. arg == "--export-pack") { // Export project
  1247. // Actually handling is done in start().
  1248. editor = true;
  1249. cmdline_tool = true;
  1250. wait_for_import = true;
  1251. main_args.push_back(arg);
  1252. #ifndef DISABLE_DEPRECATED
  1253. } else if (arg == "--export") { // For users used to 3.x syntax.
  1254. OS::get_singleton()->print("The Godot 3 --export option was changed to more explicit --export-release / --export-debug / --export-pack options.\nSee the --help output for details.\n");
  1255. goto error;
  1256. } else if (arg == "--convert-3to4") {
  1257. // Actually handling is done in start().
  1258. cmdline_tool = true;
  1259. main_args.push_back(arg);
  1260. if (N && !N->get().begins_with("-")) {
  1261. if (itos(N->get().to_int()) == N->get()) {
  1262. converter_max_kb_file = N->get().to_int();
  1263. }
  1264. if (N->next() && !N->next()->get().begins_with("-")) {
  1265. if (itos(N->next()->get().to_int()) == N->next()->get()) {
  1266. converter_max_line_length = N->next()->get().to_int();
  1267. }
  1268. }
  1269. }
  1270. } else if (arg == "--validate-conversion-3to4") {
  1271. // Actually handling is done in start().
  1272. cmdline_tool = true;
  1273. main_args.push_back(arg);
  1274. if (N && !N->get().begins_with("-")) {
  1275. if (itos(N->get().to_int()) == N->get()) {
  1276. converter_max_kb_file = N->get().to_int();
  1277. }
  1278. if (N->next() && !N->next()->get().begins_with("-")) {
  1279. if (itos(N->next()->get().to_int()) == N->next()->get()) {
  1280. converter_max_line_length = N->next()->get().to_int();
  1281. }
  1282. }
  1283. }
  1284. #endif // DISABLE_DEPRECATED
  1285. } else if (arg == "--doctool") {
  1286. // Actually handling is done in start().
  1287. cmdline_tool = true;
  1288. // `--doctool` implies `--headless` to avoid spawning an unnecessary window
  1289. // and speed up class reference generation.
  1290. audio_driver = NULL_AUDIO_DRIVER;
  1291. display_driver = NULL_DISPLAY_DRIVER;
  1292. main_args.push_back(arg);
  1293. #ifdef MODULE_GDSCRIPT_ENABLED
  1294. } else if (arg == "--gdscript-docs") {
  1295. if (N) {
  1296. project_path = N->get();
  1297. // Will be handled in start()
  1298. main_args.push_back(arg);
  1299. main_args.push_back(N->get());
  1300. N = N->next();
  1301. // GDScript docgen requires Autoloads, but loading those also creates a main loop.
  1302. // This forces main loop to quit without adding more GDScript-specific exceptions to setup.
  1303. quit_after = 1;
  1304. } else {
  1305. OS::get_singleton()->print("Missing relative or absolute path to project for --gdscript-docs, aborting.\n");
  1306. goto error;
  1307. }
  1308. #endif // MODULE_GDSCRIPT_ENABLED
  1309. #endif // TOOLS_ENABLED
  1310. } else if (arg == "--path") { // set path of project to start or edit
  1311. if (N) {
  1312. String p = N->get();
  1313. if (OS::get_singleton()->set_cwd(p) != OK) {
  1314. OS::get_singleton()->print("Invalid project path specified: \"%s\", aborting.\n", p.utf8().get_data());
  1315. goto error;
  1316. }
  1317. N = N->next();
  1318. } else {
  1319. OS::get_singleton()->print("Missing relative or absolute path, aborting.\n");
  1320. goto error;
  1321. }
  1322. } else if (arg == "-u" || arg == "--upwards") { // scan folders upwards
  1323. upwards = true;
  1324. } else if (arg == "--quit") { // Auto quit at the end of the first main loop iteration
  1325. quit_after = 1;
  1326. } else if (arg == "--quit-after") { // Quit after the given number of iterations
  1327. if (N) {
  1328. quit_after = N->get().to_int();
  1329. N = N->next();
  1330. } else {
  1331. OS::get_singleton()->print("Missing number of iterations, aborting.\n");
  1332. goto error;
  1333. }
  1334. } else if (arg.ends_with("project.godot")) {
  1335. String path;
  1336. String file = arg;
  1337. int sep = MAX(file.rfind("/"), file.rfind("\\"));
  1338. if (sep == -1) {
  1339. path = ".";
  1340. } else {
  1341. path = file.substr(0, sep);
  1342. }
  1343. if (OS::get_singleton()->set_cwd(path) == OK) {
  1344. // path already specified, don't override
  1345. } else {
  1346. project_path = path;
  1347. }
  1348. #ifdef TOOLS_ENABLED
  1349. editor = true;
  1350. #endif
  1351. } else if (arg == "-b" || arg == "--breakpoints") { // add breakpoints
  1352. if (N) {
  1353. String bplist = N->get();
  1354. breakpoints = bplist.split(",");
  1355. N = N->next();
  1356. } else {
  1357. OS::get_singleton()->print("Missing list of breakpoints, aborting.\n");
  1358. goto error;
  1359. }
  1360. } else if (arg == "--max-fps") { // set maximum rendered FPS
  1361. if (N) {
  1362. max_fps = N->get().to_int();
  1363. N = N->next();
  1364. } else {
  1365. OS::get_singleton()->print("Missing maximum FPS argument, aborting.\n");
  1366. goto error;
  1367. }
  1368. } else if (arg == "--frame-delay") { // force frame delay
  1369. if (N) {
  1370. frame_delay = N->get().to_int();
  1371. N = N->next();
  1372. } else {
  1373. OS::get_singleton()->print("Missing frame delay argument, aborting.\n");
  1374. goto error;
  1375. }
  1376. } else if (arg == "--time-scale") { // force time scale
  1377. if (N) {
  1378. Engine::get_singleton()->set_time_scale(N->get().to_float());
  1379. N = N->next();
  1380. } else {
  1381. OS::get_singleton()->print("Missing time scale argument, aborting.\n");
  1382. goto error;
  1383. }
  1384. } else if (arg == "--main-pack") {
  1385. if (N) {
  1386. main_pack = N->get();
  1387. N = N->next();
  1388. } else {
  1389. OS::get_singleton()->print("Missing path to main pack file, aborting.\n");
  1390. goto error;
  1391. }
  1392. } else if (arg == "-d" || arg == "--debug") {
  1393. debug_uri = "local://";
  1394. OS::get_singleton()->_debug_stdout = true;
  1395. #if defined(DEBUG_ENABLED)
  1396. } else if (arg == "--debug-collisions") {
  1397. debug_collisions = true;
  1398. } else if (arg == "--debug-paths") {
  1399. debug_paths = true;
  1400. } else if (arg == "--debug-navigation") {
  1401. debug_navigation = true;
  1402. } else if (arg == "--debug-avoidance") {
  1403. debug_avoidance = true;
  1404. } else if (arg == "--debug-canvas-item-redraw") {
  1405. debug_canvas_item_redraw = true;
  1406. } else if (arg == "--debug-stringnames") {
  1407. StringName::set_debug_stringnames(true);
  1408. #endif
  1409. } else if (arg == "--remote-debug") {
  1410. if (N) {
  1411. debug_uri = N->get();
  1412. if (!debug_uri.contains("://")) { // wrong address
  1413. OS::get_singleton()->print(
  1414. "Invalid debug host address, it should be of the form <protocol>://<host/IP>:<port>.\n");
  1415. goto error;
  1416. }
  1417. N = N->next();
  1418. } else {
  1419. OS::get_singleton()->print("Missing remote debug host address, aborting.\n");
  1420. goto error;
  1421. }
  1422. } else if (arg == "--editor-pid") { // not exposed to user
  1423. if (N) {
  1424. editor_pid = N->get().to_int();
  1425. N = N->next();
  1426. } else {
  1427. OS::get_singleton()->print("Missing editor PID argument, aborting.\n");
  1428. goto error;
  1429. }
  1430. } else if (arg == "--disable-render-loop") {
  1431. disable_render_loop = true;
  1432. } else if (arg == "--fixed-fps") {
  1433. if (N) {
  1434. fixed_fps = N->get().to_int();
  1435. N = N->next();
  1436. } else {
  1437. OS::get_singleton()->print("Missing fixed-fps argument, aborting.\n");
  1438. goto error;
  1439. }
  1440. } else if (arg == "--write-movie") {
  1441. if (N) {
  1442. Engine::get_singleton()->set_write_movie_path(N->get());
  1443. N = N->next();
  1444. if (fixed_fps == -1) {
  1445. fixed_fps = 60;
  1446. }
  1447. OS::get_singleton()->_writing_movie = true;
  1448. } else {
  1449. OS::get_singleton()->print("Missing write-movie argument, aborting.\n");
  1450. goto error;
  1451. }
  1452. } else if (arg == "--disable-vsync") {
  1453. disable_vsync = true;
  1454. } else if (arg == "--print-fps") {
  1455. print_fps = true;
  1456. } else if (arg == "--profile-gpu") {
  1457. profile_gpu = true;
  1458. } else if (arg == "--disable-crash-handler") {
  1459. OS::get_singleton()->disable_crash_handler();
  1460. } else if (arg == "--skip-breakpoints") {
  1461. skip_breakpoints = true;
  1462. #ifndef _3D_DISABLED
  1463. } else if (arg == "--xr-mode") {
  1464. if (N) {
  1465. String xr_mode = N->get().to_lower();
  1466. N = N->next();
  1467. if (xr_mode == "default") {
  1468. XRServer::set_xr_mode(XRServer::XRMODE_DEFAULT);
  1469. } else if (xr_mode == "off") {
  1470. XRServer::set_xr_mode(XRServer::XRMODE_OFF);
  1471. } else if (xr_mode == "on") {
  1472. XRServer::set_xr_mode(XRServer::XRMODE_ON);
  1473. } else {
  1474. OS::get_singleton()->print("Unknown --xr-mode argument \"%s\", aborting.\n", xr_mode.ascii().get_data());
  1475. goto error;
  1476. }
  1477. } else {
  1478. OS::get_singleton()->print("Missing --xr-mode argument, aborting.\n");
  1479. goto error;
  1480. }
  1481. #endif // _3D_DISABLED
  1482. } else if (arg == "--benchmark") {
  1483. OS::get_singleton()->set_use_benchmark(true);
  1484. } else if (arg == "--benchmark-file") {
  1485. if (N) {
  1486. OS::get_singleton()->set_use_benchmark(true);
  1487. String benchmark_file = N->get();
  1488. OS::get_singleton()->set_benchmark_file(benchmark_file);
  1489. N = N->next();
  1490. } else {
  1491. OS::get_singleton()->print("Missing <path> argument for --benchmark-file <path>.\n");
  1492. goto error;
  1493. }
  1494. #if defined(TOOLS_ENABLED) && defined(MODULE_GDSCRIPT_ENABLED) && !defined(GDSCRIPT_NO_LSP)
  1495. } else if (arg == "--lsp-port") {
  1496. if (N) {
  1497. int port_override = N->get().to_int();
  1498. if (port_override < 0 || port_override > 65535) {
  1499. OS::get_singleton()->print("<port> argument for --lsp-port <port> must be between 0 and 65535.\n");
  1500. goto error;
  1501. }
  1502. GDScriptLanguageServer::port_override = port_override;
  1503. N = N->next();
  1504. } else {
  1505. OS::get_singleton()->print("Missing <port> argument for --lsp-port <port>.\n");
  1506. goto error;
  1507. }
  1508. #endif // TOOLS_ENABLED && MODULE_GDSCRIPT_ENABLED && !GDSCRIPT_NO_LSP
  1509. #if defined(TOOLS_ENABLED)
  1510. } else if (arg == "--dap-port") {
  1511. if (N) {
  1512. int port_override = N->get().to_int();
  1513. if (port_override < 0 || port_override > 65535) {
  1514. OS::get_singleton()->print("<port> argument for --dap-port <port> must be between 0 and 65535.\n");
  1515. goto error;
  1516. }
  1517. DebugAdapterServer::port_override = port_override;
  1518. N = N->next();
  1519. } else {
  1520. OS::get_singleton()->print("Missing <port> argument for --dap-port <port>.\n");
  1521. goto error;
  1522. }
  1523. #endif // TOOLS_ENABLED
  1524. } else if (arg == "--" || arg == "++") {
  1525. adding_user_args = true;
  1526. } else {
  1527. main_args.push_back(arg);
  1528. }
  1529. I = N;
  1530. }
  1531. #ifdef TOOLS_ENABLED
  1532. if (editor && project_manager) {
  1533. OS::get_singleton()->print(
  1534. "Error: Command line arguments implied opening both editor and project manager, which is not possible. Aborting.\n");
  1535. goto error;
  1536. }
  1537. #endif
  1538. // Network file system needs to be configured before globals, since globals are based on the
  1539. // 'project.godot' file which will only be available through the network if this is enabled
  1540. if (!remotefs.is_empty()) {
  1541. int port;
  1542. if (remotefs.contains(":")) {
  1543. port = remotefs.get_slicec(':', 1).to_int();
  1544. remotefs = remotefs.get_slicec(':', 0);
  1545. } else {
  1546. port = 6010;
  1547. }
  1548. Error err = OS::get_singleton()->setup_remote_filesystem(remotefs, port, remotefs_pass, project_path);
  1549. if (err) {
  1550. OS::get_singleton()->printerr("Could not connect to remotefs: %s:%i.\n", remotefs.utf8().get_data(), port);
  1551. goto error;
  1552. }
  1553. }
  1554. OS::get_singleton()->_in_editor = editor;
  1555. if (globals->setup(project_path, main_pack, upwards, editor) == OK) {
  1556. #ifdef TOOLS_ENABLED
  1557. found_project = true;
  1558. #endif
  1559. } else {
  1560. #ifdef TOOLS_ENABLED
  1561. editor = false;
  1562. #else
  1563. const String error_msg = "Error: Couldn't load project data at path \"" + project_path + "\". Is the .pck file missing?\nIf you've renamed the executable, the associated .pck file should also be renamed to match the executable's name (without the extension).\n";
  1564. OS::get_singleton()->print("%s", error_msg.utf8().get_data());
  1565. OS::get_singleton()->alert(error_msg);
  1566. goto error;
  1567. #endif
  1568. }
  1569. // Initialize WorkerThreadPool.
  1570. {
  1571. #ifdef THREADS_ENABLED
  1572. if (editor || project_manager) {
  1573. WorkerThreadPool::get_singleton()->init(-1, 0.75);
  1574. } else {
  1575. int worker_threads = GLOBAL_GET("threading/worker_pool/max_threads");
  1576. float low_priority_ratio = GLOBAL_GET("threading/worker_pool/low_priority_thread_ratio");
  1577. WorkerThreadPool::get_singleton()->init(worker_threads, low_priority_ratio);
  1578. }
  1579. #else
  1580. WorkerThreadPool::get_singleton()->init(0, 0);
  1581. #endif
  1582. }
  1583. #ifdef TOOLS_ENABLED
  1584. if (editor) {
  1585. Engine::get_singleton()->set_editor_hint(true);
  1586. Engine::get_singleton()->set_extension_reloading_enabled(true);
  1587. }
  1588. #endif
  1589. // Initialize user data dir.
  1590. OS::get_singleton()->ensure_user_data_dir();
  1591. initialize_modules(MODULE_INITIALIZATION_LEVEL_CORE);
  1592. register_core_extensions(); // core extensions must be registered after globals setup and before display
  1593. ResourceUID::get_singleton()->load_from_cache(true); // load UUIDs from cache.
  1594. if (ProjectSettings::get_singleton()->has_custom_feature("dedicated_server")) {
  1595. audio_driver = NULL_AUDIO_DRIVER;
  1596. display_driver = NULL_DISPLAY_DRIVER;
  1597. }
  1598. GLOBAL_DEF(PropertyInfo(Variant::INT, "network/limits/debugger/max_chars_per_second", PROPERTY_HINT_RANGE, "0, 4096, 1, or_greater"), 32768);
  1599. GLOBAL_DEF(PropertyInfo(Variant::INT, "network/limits/debugger/max_queued_messages", PROPERTY_HINT_RANGE, "0, 8192, 1, or_greater"), 2048);
  1600. GLOBAL_DEF(PropertyInfo(Variant::INT, "network/limits/debugger/max_errors_per_second", PROPERTY_HINT_RANGE, "0, 200, 1, or_greater"), 400);
  1601. GLOBAL_DEF(PropertyInfo(Variant::INT, "network/limits/debugger/max_warnings_per_second", PROPERTY_HINT_RANGE, "0, 200, 1, or_greater"), 400);
  1602. EngineDebugger::initialize(debug_uri, skip_breakpoints, breakpoints, []() {
  1603. if (editor_pid) {
  1604. DisplayServer::get_singleton()->enable_for_stealing_focus(editor_pid);
  1605. }
  1606. });
  1607. #ifdef TOOLS_ENABLED
  1608. if (editor) {
  1609. packed_data->set_disabled(true);
  1610. main_args.push_back("--editor");
  1611. if (!init_windowed && !init_fullscreen) {
  1612. init_maximized = true;
  1613. window_mode = DisplayServer::WINDOW_MODE_MAXIMIZED;
  1614. }
  1615. }
  1616. if (!project_manager && !editor) {
  1617. // If we didn't find a project, we fall back to the project manager.
  1618. project_manager = !found_project && !cmdline_tool;
  1619. }
  1620. if (project_manager) {
  1621. Engine::get_singleton()->set_project_manager_hint(true);
  1622. }
  1623. #endif
  1624. GLOBAL_DEF("debug/file_logging/enable_file_logging", false);
  1625. // Only file logging by default on desktop platforms as logs can't be
  1626. // accessed easily on mobile/Web platforms (if at all).
  1627. // This also prevents logs from being created for the editor instance, as feature tags
  1628. // are disabled while in the editor (even if they should logically apply).
  1629. GLOBAL_DEF("debug/file_logging/enable_file_logging.pc", true);
  1630. GLOBAL_DEF("debug/file_logging/log_path", "user://logs/godot.log");
  1631. GLOBAL_DEF(PropertyInfo(Variant::INT, "debug/file_logging/max_log_files", PROPERTY_HINT_RANGE, "0,20,1,or_greater"), 5);
  1632. // If `--log-file` is used to override the log path, allow creating logs for the project manager or editor
  1633. // and even if file logging is disabled in the Project Settings.
  1634. // `--log-file` can be used with any path (including absolute paths outside the project folder),
  1635. // so check for filesystem access if it's used.
  1636. if (FileAccess::get_create_func(!log_file.is_empty() ? FileAccess::ACCESS_FILESYSTEM : FileAccess::ACCESS_USERDATA) &&
  1637. (!log_file.is_empty() || (!project_manager && !editor && GLOBAL_GET("debug/file_logging/enable_file_logging")))) {
  1638. // Don't create logs for the project manager as they would be written to
  1639. // the current working directory, which is inconvenient.
  1640. String base_path;
  1641. int max_files;
  1642. if (!log_file.is_empty()) {
  1643. base_path = log_file;
  1644. // Ensure log file name respects the specified override by disabling log rotation.
  1645. max_files = 1;
  1646. } else {
  1647. base_path = GLOBAL_GET("debug/file_logging/log_path");
  1648. max_files = GLOBAL_GET("debug/file_logging/max_log_files");
  1649. }
  1650. OS::get_singleton()->add_logger(memnew(RotatedFileLogger(base_path, max_files)));
  1651. }
  1652. if (main_args.size() == 0 && String(GLOBAL_GET("application/run/main_scene")) == "") {
  1653. #ifdef TOOLS_ENABLED
  1654. if (!editor && !project_manager) {
  1655. #endif
  1656. const String error_msg = "Error: Can't run project: no main scene defined in the project.\n";
  1657. OS::get_singleton()->print("%s", error_msg.utf8().get_data());
  1658. OS::get_singleton()->alert(error_msg);
  1659. goto error;
  1660. #ifdef TOOLS_ENABLED
  1661. }
  1662. #endif
  1663. }
  1664. if (editor || project_manager) {
  1665. Engine::get_singleton()->set_editor_hint(true);
  1666. use_custom_res = false;
  1667. input_map->load_default(); //keys for editor
  1668. } else {
  1669. input_map->load_from_project_settings(); //keys for game
  1670. }
  1671. if (bool(GLOBAL_GET("application/run/disable_stdout"))) {
  1672. quiet_stdout = true;
  1673. }
  1674. if (bool(GLOBAL_GET("application/run/disable_stderr"))) {
  1675. CoreGlobals::print_error_enabled = false;
  1676. }
  1677. if (!bool(GLOBAL_GET("application/run/print_header"))) {
  1678. // --no-header option for project settings.
  1679. Engine::get_singleton()->_print_header = false;
  1680. }
  1681. if (quiet_stdout) {
  1682. CoreGlobals::print_line_enabled = false;
  1683. }
  1684. Logger::set_flush_stdout_on_print(GLOBAL_GET("application/run/flush_stdout_on_print"));
  1685. OS::get_singleton()->set_cmdline(execpath, main_args, user_args);
  1686. {
  1687. String driver_hints = "";
  1688. String driver_hints_with_d3d12 = "";
  1689. {
  1690. Vector<String> driver_hints_arr;
  1691. #ifdef VULKAN_ENABLED
  1692. driver_hints_arr.push_back("vulkan");
  1693. #endif
  1694. driver_hints = String(",").join(driver_hints_arr);
  1695. #ifdef D3D12_ENABLED
  1696. driver_hints_arr.push_back("d3d12");
  1697. #endif
  1698. driver_hints_with_d3d12 = String(",").join(driver_hints_arr);
  1699. }
  1700. String default_driver = driver_hints.get_slice(",", 0);
  1701. String default_driver_with_d3d12 = driver_hints_with_d3d12.get_slice(",", 0);
  1702. // For now everything defaults to vulkan when available. This can change in future updates.
  1703. GLOBAL_DEF_RST_NOVAL("rendering/rendering_device/driver", default_driver);
  1704. GLOBAL_DEF_RST_NOVAL(PropertyInfo(Variant::STRING, "rendering/rendering_device/driver.windows", PROPERTY_HINT_ENUM, driver_hints_with_d3d12), default_driver_with_d3d12);
  1705. GLOBAL_DEF_RST_NOVAL(PropertyInfo(Variant::STRING, "rendering/rendering_device/driver.linuxbsd", PROPERTY_HINT_ENUM, driver_hints), default_driver);
  1706. GLOBAL_DEF_RST_NOVAL(PropertyInfo(Variant::STRING, "rendering/rendering_device/driver.android", PROPERTY_HINT_ENUM, driver_hints), default_driver);
  1707. GLOBAL_DEF_RST_NOVAL(PropertyInfo(Variant::STRING, "rendering/rendering_device/driver.ios", PROPERTY_HINT_ENUM, driver_hints), default_driver);
  1708. GLOBAL_DEF_RST_NOVAL(PropertyInfo(Variant::STRING, "rendering/rendering_device/driver.macos", PROPERTY_HINT_ENUM, driver_hints), default_driver);
  1709. GLOBAL_DEF_RST("rendering/rendering_device/fallback_to_vulkan", true);
  1710. GLOBAL_DEF_RST("rendering/rendering_device/fallback_to_d3d12", true);
  1711. }
  1712. {
  1713. String driver_hints = "";
  1714. String driver_hints_angle = "";
  1715. String driver_hints_egl = "";
  1716. #ifdef GLES3_ENABLED
  1717. driver_hints = "opengl3";
  1718. driver_hints_angle = "opengl3,opengl3_angle"; // macOS, Windows.
  1719. driver_hints_egl = "opengl3,opengl3_es"; // Linux.
  1720. #endif
  1721. String default_driver = driver_hints.get_slice(",", 0);
  1722. GLOBAL_DEF_RST_NOVAL("rendering/gl_compatibility/driver", default_driver);
  1723. GLOBAL_DEF_RST_NOVAL(PropertyInfo(Variant::STRING, "rendering/gl_compatibility/driver.windows", PROPERTY_HINT_ENUM, driver_hints_angle), default_driver);
  1724. GLOBAL_DEF_RST_NOVAL(PropertyInfo(Variant::STRING, "rendering/gl_compatibility/driver.linuxbsd", PROPERTY_HINT_ENUM, driver_hints_egl), default_driver);
  1725. GLOBAL_DEF_RST_NOVAL(PropertyInfo(Variant::STRING, "rendering/gl_compatibility/driver.web", PROPERTY_HINT_ENUM, driver_hints), default_driver);
  1726. GLOBAL_DEF_RST_NOVAL(PropertyInfo(Variant::STRING, "rendering/gl_compatibility/driver.android", PROPERTY_HINT_ENUM, driver_hints), default_driver);
  1727. GLOBAL_DEF_RST_NOVAL(PropertyInfo(Variant::STRING, "rendering/gl_compatibility/driver.ios", PROPERTY_HINT_ENUM, driver_hints), default_driver);
  1728. GLOBAL_DEF_RST_NOVAL(PropertyInfo(Variant::STRING, "rendering/gl_compatibility/driver.macos", PROPERTY_HINT_ENUM, driver_hints_angle), default_driver);
  1729. GLOBAL_DEF_RST("rendering/gl_compatibility/nvidia_disable_threaded_optimization", true);
  1730. GLOBAL_DEF_RST("rendering/gl_compatibility/fallback_to_angle", true);
  1731. GLOBAL_DEF_RST("rendering/gl_compatibility/fallback_to_native", true);
  1732. GLOBAL_DEF_RST("rendering/gl_compatibility/fallback_to_gles", true);
  1733. Array device_blocklist;
  1734. #define BLOCK_DEVICE(m_vendor, m_name) \
  1735. { \
  1736. Dictionary device; \
  1737. device["vendor"] = m_vendor; \
  1738. device["name"] = m_name; \
  1739. device_blocklist.push_back(device); \
  1740. }
  1741. // AMD GPUs.
  1742. BLOCK_DEVICE("ATI", "Radeon 9"); // ATI Radeon 9000 Series
  1743. BLOCK_DEVICE("ATI", "Radeon X"); // ATI Radeon X500-X2000 Series
  1744. BLOCK_DEVICE("ATI", "Radeon HD 2"); // AMD/ATI (Mobility) Radeon HD 2xxx Series
  1745. BLOCK_DEVICE("ATI", "Radeon HD 3"); // AMD/ATI (Mobility) Radeon HD 3xxx Series
  1746. BLOCK_DEVICE("ATI", "Radeon HD 4"); // AMD/ATI (Mobility) Radeon HD 4xxx Series
  1747. BLOCK_DEVICE("ATI", "Radeon HD 5"); // AMD/ATI (Mobility) Radeon HD 5xxx Series
  1748. BLOCK_DEVICE("ATI", "Radeon HD 6"); // AMD/ATI (Mobility) Radeon HD 6xxx Series
  1749. BLOCK_DEVICE("ATI", "Radeon HD 7"); // AMD/ATI (Mobility) Radeon HD 7xxx Series
  1750. BLOCK_DEVICE("ATI", "Radeon HD 8"); // AMD/ATI (Mobility) Radeon HD 8xxx Series
  1751. BLOCK_DEVICE("ATI", "Radeon(TM) R2 Graphics"); // APUs
  1752. BLOCK_DEVICE("ATI", "Radeon(TM) R3 Graphics");
  1753. BLOCK_DEVICE("ATI", "Radeon(TM) R4 Graphics");
  1754. BLOCK_DEVICE("ATI", "Radeon(TM) R5 Graphics");
  1755. BLOCK_DEVICE("ATI", "Radeon(TM) R6 Graphics");
  1756. BLOCK_DEVICE("ATI", "Radeon(TM) R7 Graphics");
  1757. BLOCK_DEVICE("AMD", "Radeon(TM) R7 Graphics");
  1758. BLOCK_DEVICE("AMD", "Radeon(TM) R8 Graphics");
  1759. BLOCK_DEVICE("ATI", "Radeon R5 Graphics");
  1760. BLOCK_DEVICE("ATI", "Radeon R6 Graphics");
  1761. BLOCK_DEVICE("ATI", "Radeon R7 Graphics");
  1762. BLOCK_DEVICE("AMD", "Radeon R7 Graphics");
  1763. BLOCK_DEVICE("AMD", "Radeon R8 Graphics");
  1764. BLOCK_DEVICE("ATI", "Radeon R5 2"); // Rx 2xx Series
  1765. BLOCK_DEVICE("ATI", "Radeon R7 2");
  1766. BLOCK_DEVICE("ATI", "Radeon R9 2");
  1767. BLOCK_DEVICE("ATI", "Radeon R5 M2"); // Rx M2xx Series
  1768. BLOCK_DEVICE("ATI", "Radeon R7 M2");
  1769. BLOCK_DEVICE("ATI", "Radeon R9 M2");
  1770. BLOCK_DEVICE("ATI", "Radeon (TM) R9 Fury");
  1771. BLOCK_DEVICE("ATI", "Radeon (TM) R5 3"); // Rx 3xx Series
  1772. BLOCK_DEVICE("AMD", "Radeon (TM) R5 3");
  1773. BLOCK_DEVICE("ATI", "Radeon (TM) R7 3");
  1774. BLOCK_DEVICE("AMD", "Radeon (TM) R7 3");
  1775. BLOCK_DEVICE("ATI", "Radeon (TM) R9 3");
  1776. BLOCK_DEVICE("AMD", "Radeon (TM) R9 3");
  1777. BLOCK_DEVICE("ATI", "Radeon (TM) R5 M3"); // Rx M3xx Series
  1778. BLOCK_DEVICE("AMD", "Radeon (TM) R5 M3");
  1779. BLOCK_DEVICE("ATI", "Radeon (TM) R7 M3");
  1780. BLOCK_DEVICE("AMD", "Radeon (TM) R7 M3");
  1781. BLOCK_DEVICE("ATI", "Radeon (TM) R9 M3");
  1782. BLOCK_DEVICE("AMD", "Radeon (TM) R9 M3");
  1783. // Intel GPUs.
  1784. BLOCK_DEVICE("0x8086", "0x0042"); // HD Graphics, Gen5, Clarkdale
  1785. BLOCK_DEVICE("0x8086", "0x0046"); // HD Graphics, Gen5, Arrandale
  1786. BLOCK_DEVICE("0x8086", "0x010A"); // HD Graphics, Gen6, Sandy Bridge
  1787. BLOCK_DEVICE("Intel", "Intel HD Graphics 2000");
  1788. BLOCK_DEVICE("Intel", "Intel(R) HD Graphics 2000");
  1789. BLOCK_DEVICE("0x8086", "0x0102"); // HD Graphics 2000, Gen6, Sandy Bridge
  1790. BLOCK_DEVICE("0x8086", "0x0116"); // HD Graphics 3000, Gen6, Sandy Bridge
  1791. BLOCK_DEVICE("Intel", "Intel HD Graphics 3000");
  1792. BLOCK_DEVICE("Intel", "Intel(R) HD Graphics 3000");
  1793. BLOCK_DEVICE("0x8086", "0x0126"); // HD Graphics 3000, Gen6, Sandy Bridge
  1794. BLOCK_DEVICE("Intel", "Intel HD Graphics P3000");
  1795. BLOCK_DEVICE("Intel", "Intel(R) HD Graphics P3000");
  1796. BLOCK_DEVICE("0x8086", "0x0112"); // HD Graphics P3000, Gen6, Sandy Bridge
  1797. BLOCK_DEVICE("0x8086", "0x0122"); // HD Graphics P3000, Gen6, Sandy Bridge
  1798. BLOCK_DEVICE("0x8086", "0x015A"); // HD Graphics, Gen7, Ivy Bridge
  1799. BLOCK_DEVICE("Intel", "Intel HD Graphics 2500");
  1800. BLOCK_DEVICE("Intel", "Intel(R) HD Graphics 2500");
  1801. BLOCK_DEVICE("0x8086", "0x0152"); // HD Graphics 2500, Gen7, Ivy Bridge
  1802. BLOCK_DEVICE("Intel", "Intel HD Graphics 4000");
  1803. BLOCK_DEVICE("Intel", "Intel(R) HD Graphics 4000");
  1804. BLOCK_DEVICE("0x8086", "0x0162"); // HD Graphics 4000, Gen7, Ivy Bridge
  1805. BLOCK_DEVICE("0x8086", "0x0166"); // HD Graphics 4000, Gen7, Ivy Bridge
  1806. BLOCK_DEVICE("Intel", "Intel HD Graphics P4000");
  1807. BLOCK_DEVICE("Intel", "Intel(R) HD Graphics P4000");
  1808. BLOCK_DEVICE("0x8086", "0x016A"); // HD Graphics P4000, Gen7, Ivy Bridge
  1809. #undef BLOCK_DEVICE
  1810. GLOBAL_DEF_RST_NOVAL(PropertyInfo(Variant::ARRAY, "rendering/gl_compatibility/force_angle_on_devices", PROPERTY_HINT_ARRAY_TYPE, vformat("%s/%s:%s", Variant::DICTIONARY, PROPERTY_HINT_NONE, String())), device_blocklist);
  1811. }
  1812. // Start with RenderingDevice-based backends.
  1813. #ifdef RD_ENABLED
  1814. renderer_hints = "forward_plus,mobile";
  1815. default_renderer_mobile = "mobile";
  1816. #endif
  1817. // And Compatibility next, or first if Vulkan is disabled.
  1818. #ifdef GLES3_ENABLED
  1819. if (!renderer_hints.is_empty()) {
  1820. renderer_hints += ",";
  1821. }
  1822. renderer_hints += "gl_compatibility";
  1823. if (default_renderer_mobile.is_empty()) {
  1824. default_renderer_mobile = "gl_compatibility";
  1825. }
  1826. // Default to Compatibility when using the project manager.
  1827. if (rendering_driver.is_empty() && rendering_method.is_empty() && project_manager) {
  1828. rendering_driver = "opengl3";
  1829. rendering_method = "gl_compatibility";
  1830. default_renderer_mobile = "gl_compatibility";
  1831. }
  1832. #endif
  1833. if (renderer_hints.is_empty()) {
  1834. ERR_PRINT("No renderers available.");
  1835. }
  1836. if (!rendering_method.is_empty()) {
  1837. if (rendering_method != "forward_plus" &&
  1838. rendering_method != "mobile" &&
  1839. rendering_method != "gl_compatibility") {
  1840. OS::get_singleton()->print("Unknown renderer name '%s', aborting. Valid options are: %s\n", rendering_method.utf8().get_data(), renderer_hints.utf8().get_data());
  1841. goto error;
  1842. }
  1843. }
  1844. if (!rendering_driver.is_empty()) {
  1845. // As the rendering drivers available may depend on the display driver and renderer
  1846. // selected, we can't do an exhaustive check here, but we can look through all
  1847. // the options in all the display drivers for a match.
  1848. bool found = false;
  1849. for (int i = 0; i < DisplayServer::get_create_function_count(); i++) {
  1850. Vector<String> r_drivers = DisplayServer::get_create_function_rendering_drivers(i);
  1851. for (int d = 0; d < r_drivers.size(); d++) {
  1852. if (rendering_driver == r_drivers[d]) {
  1853. found = true;
  1854. break;
  1855. }
  1856. }
  1857. }
  1858. if (!found) {
  1859. OS::get_singleton()->print("Unknown rendering driver '%s', aborting.\nValid options are ",
  1860. rendering_driver.utf8().get_data());
  1861. for (int i = 0; i < DisplayServer::get_create_function_count(); i++) {
  1862. Vector<String> r_drivers = DisplayServer::get_create_function_rendering_drivers(i);
  1863. for (int d = 0; d < r_drivers.size(); d++) {
  1864. OS::get_singleton()->print("'%s', ", r_drivers[d].utf8().get_data());
  1865. }
  1866. }
  1867. OS::get_singleton()->print(".\n");
  1868. goto error;
  1869. }
  1870. // Set a default renderer if none selected. Try to choose one that matches the driver.
  1871. if (rendering_method.is_empty()) {
  1872. if (rendering_driver == "opengl3" || rendering_driver == "opengl3_angle" || rendering_driver == "opengl3_es") {
  1873. rendering_method = "gl_compatibility";
  1874. } else {
  1875. rendering_method = "forward_plus";
  1876. }
  1877. }
  1878. // Now validate whether the selected driver matches with the renderer.
  1879. bool valid_combination = false;
  1880. Vector<String> available_drivers;
  1881. if (rendering_method == "forward_plus" || rendering_method == "mobile") {
  1882. #ifdef VULKAN_ENABLED
  1883. available_drivers.push_back("vulkan");
  1884. #endif
  1885. #ifdef D3D12_ENABLED
  1886. available_drivers.push_back("d3d12");
  1887. #endif
  1888. }
  1889. #ifdef GLES3_ENABLED
  1890. if (rendering_method == "gl_compatibility") {
  1891. available_drivers.push_back("opengl3");
  1892. available_drivers.push_back("opengl3_angle");
  1893. available_drivers.push_back("opengl3_es");
  1894. }
  1895. #endif
  1896. if (available_drivers.is_empty()) {
  1897. OS::get_singleton()->print("Unknown renderer name '%s', aborting.\n", rendering_method.utf8().get_data());
  1898. goto error;
  1899. }
  1900. for (int i = 0; i < available_drivers.size(); i++) {
  1901. if (rendering_driver == available_drivers[i]) {
  1902. valid_combination = true;
  1903. break;
  1904. }
  1905. }
  1906. if (!valid_combination) {
  1907. OS::get_singleton()->print("Invalid renderer/driver combination '%s' and '%s', aborting. %s only supports the following drivers ", rendering_method.utf8().get_data(), rendering_driver.utf8().get_data(), rendering_method.utf8().get_data());
  1908. for (int d = 0; d < available_drivers.size(); d++) {
  1909. OS::get_singleton()->print("'%s', ", available_drivers[d].utf8().get_data());
  1910. }
  1911. OS::get_singleton()->print(".\n");
  1912. goto error;
  1913. }
  1914. }
  1915. default_renderer = renderer_hints.get_slice(",", 0);
  1916. GLOBAL_DEF_RST_BASIC(PropertyInfo(Variant::STRING, "rendering/renderer/rendering_method", PROPERTY_HINT_ENUM, renderer_hints), default_renderer);
  1917. GLOBAL_DEF_RST_BASIC("rendering/renderer/rendering_method.mobile", default_renderer_mobile);
  1918. GLOBAL_DEF_RST_BASIC("rendering/renderer/rendering_method.web", "gl_compatibility"); // This is a bit of a hack until we have WebGPU support.
  1919. // Default to ProjectSettings default if nothing set on the command line.
  1920. if (rendering_method.is_empty()) {
  1921. rendering_method = GLOBAL_GET("rendering/renderer/rendering_method");
  1922. }
  1923. if (rendering_driver.is_empty()) {
  1924. if (rendering_method == "gl_compatibility") {
  1925. rendering_driver = GLOBAL_GET("rendering/gl_compatibility/driver");
  1926. } else {
  1927. rendering_driver = GLOBAL_GET("rendering/rendering_device/driver");
  1928. }
  1929. }
  1930. // note this is the desired rendering driver, it doesn't mean we will get it.
  1931. // TODO - make sure this is updated in the case of fallbacks, so that the user interface
  1932. // shows the correct driver string.
  1933. OS::get_singleton()->set_current_rendering_driver_name(rendering_driver);
  1934. OS::get_singleton()->set_current_rendering_method(rendering_method);
  1935. // always convert to lower case for consistency in the code
  1936. rendering_driver = rendering_driver.to_lower();
  1937. if (use_custom_res) {
  1938. if (!force_res) {
  1939. window_size.width = GLOBAL_GET("display/window/size/viewport_width");
  1940. window_size.height = GLOBAL_GET("display/window/size/viewport_height");
  1941. if (globals->has_setting("display/window/size/window_width_override") &&
  1942. globals->has_setting("display/window/size/window_height_override")) {
  1943. int desired_width = GLOBAL_GET("display/window/size/window_width_override");
  1944. if (desired_width > 0) {
  1945. window_size.width = desired_width;
  1946. }
  1947. int desired_height = GLOBAL_GET("display/window/size/window_height_override");
  1948. if (desired_height > 0) {
  1949. window_size.height = desired_height;
  1950. }
  1951. }
  1952. }
  1953. if (!bool(GLOBAL_GET("display/window/size/resizable"))) {
  1954. window_flags |= DisplayServer::WINDOW_FLAG_RESIZE_DISABLED_BIT;
  1955. }
  1956. if (bool(GLOBAL_GET("display/window/size/borderless"))) {
  1957. window_flags |= DisplayServer::WINDOW_FLAG_BORDERLESS_BIT;
  1958. }
  1959. if (bool(GLOBAL_GET("display/window/size/always_on_top"))) {
  1960. window_flags |= DisplayServer::WINDOW_FLAG_ALWAYS_ON_TOP_BIT;
  1961. }
  1962. if (bool(GLOBAL_GET("display/window/size/transparent"))) {
  1963. window_flags |= DisplayServer::WINDOW_FLAG_TRANSPARENT_BIT;
  1964. }
  1965. if (bool(GLOBAL_GET("display/window/size/extend_to_title"))) {
  1966. window_flags |= DisplayServer::WINDOW_FLAG_EXTEND_TO_TITLE_BIT;
  1967. }
  1968. if (bool(GLOBAL_GET("display/window/size/no_focus"))) {
  1969. window_flags |= DisplayServer::WINDOW_FLAG_NO_FOCUS_BIT;
  1970. }
  1971. window_mode = (DisplayServer::WindowMode)(GLOBAL_GET("display/window/size/mode").operator int());
  1972. int initial_position_type = GLOBAL_GET("display/window/size/initial_position_type").operator int();
  1973. if (initial_position_type == 0) { // Absolute.
  1974. if (!init_use_custom_pos) {
  1975. init_custom_pos = GLOBAL_GET("display/window/size/initial_position").operator Vector2i();
  1976. init_use_custom_pos = true;
  1977. }
  1978. } else if (initial_position_type == 1) { // Center of Primary Screen.
  1979. if (!init_use_custom_screen) {
  1980. init_screen = DisplayServer::SCREEN_PRIMARY;
  1981. init_use_custom_screen = true;
  1982. }
  1983. } else if (initial_position_type == 2) { // Center of Other Screen.
  1984. if (!init_use_custom_screen) {
  1985. init_screen = GLOBAL_GET("display/window/size/initial_screen").operator int();
  1986. init_use_custom_screen = true;
  1987. }
  1988. } else if (initial_position_type == 3) { // Center of Screen With Mouse Pointer.
  1989. if (!init_use_custom_screen) {
  1990. init_screen = DisplayServer::SCREEN_WITH_MOUSE_FOCUS;
  1991. init_use_custom_screen = true;
  1992. }
  1993. } else if (initial_position_type == 4) { // Center of Screen With Keyboard Focus.
  1994. if (!init_use_custom_screen) {
  1995. init_screen = DisplayServer::SCREEN_WITH_KEYBOARD_FOCUS;
  1996. init_use_custom_screen = true;
  1997. }
  1998. }
  1999. }
  2000. GLOBAL_DEF("internationalization/locale/include_text_server_data", false);
  2001. OS::get_singleton()->_allow_hidpi = GLOBAL_DEF("display/window/dpi/allow_hidpi", true);
  2002. OS::get_singleton()->_allow_layered = GLOBAL_DEF("display/window/per_pixel_transparency/allowed", false);
  2003. #ifdef TOOLS_ENABLED
  2004. if (editor || project_manager) {
  2005. // The editor and project manager always detect and use hiDPI if needed.
  2006. OS::get_singleton()->_allow_hidpi = true;
  2007. // Disable Vulkan overlays in editor, they cause various issues.
  2008. OS::get_singleton()->set_environment("DISABLE_MANGOHUD", "1"); // GH-57403.
  2009. OS::get_singleton()->set_environment("DISABLE_RTSS_LAYER", "1"); // GH-57937.
  2010. OS::get_singleton()->set_environment("DISABLE_VKBASALT", "1");
  2011. OS::get_singleton()->set_environment("DISABLE_VK_LAYER_reshade_1", "1"); // GH-70849.
  2012. } else {
  2013. // Re-allow using Vulkan overlays, disabled while using the editor.
  2014. OS::get_singleton()->unset_environment("DISABLE_MANGOHUD");
  2015. OS::get_singleton()->unset_environment("DISABLE_RTSS_LAYER");
  2016. OS::get_singleton()->unset_environment("DISABLE_VKBASALT");
  2017. OS::get_singleton()->unset_environment("DISABLE_VK_LAYER_reshade_1");
  2018. }
  2019. #endif
  2020. if (rtm == -1) {
  2021. rtm = GLOBAL_DEF("rendering/driver/threads/thread_model", OS::RENDER_THREAD_SAFE);
  2022. }
  2023. if (rtm >= 0 && rtm < 3) {
  2024. if (editor || project_manager) {
  2025. // Editor and project manager cannot run with rendering in a separate thread (they will crash on startup).
  2026. rtm = OS::RENDER_THREAD_SAFE;
  2027. }
  2028. #if !defined(THREADS_ENABLED)
  2029. rtm = OS::RENDER_THREAD_SAFE;
  2030. #endif
  2031. OS::get_singleton()->_render_thread_mode = OS::RenderThreadMode(rtm);
  2032. }
  2033. /* Determine audio and video drivers */
  2034. // Display driver, e.g. X11, Wayland.
  2035. // Make sure that headless is the last one, which it is assumed to be by design.
  2036. DEV_ASSERT(NULL_DISPLAY_DRIVER == DisplayServer::get_create_function_name(DisplayServer::get_create_function_count() - 1));
  2037. GLOBAL_DEF_NOVAL("display/display_server/driver", "default");
  2038. GLOBAL_DEF_NOVAL(PropertyInfo(Variant::STRING, "display/display_server/driver.windows", PROPERTY_HINT_ENUM_SUGGESTION, "default,windows,headless"), "default");
  2039. GLOBAL_DEF_NOVAL(PropertyInfo(Variant::STRING, "display/display_server/driver.linuxbsd", PROPERTY_HINT_ENUM_SUGGESTION, "default,x11,wayland,headless"), "default");
  2040. GLOBAL_DEF_NOVAL(PropertyInfo(Variant::STRING, "display/display_server/driver.android", PROPERTY_HINT_ENUM_SUGGESTION, "default,android,headless"), "default");
  2041. GLOBAL_DEF_NOVAL(PropertyInfo(Variant::STRING, "display/display_server/driver.ios", PROPERTY_HINT_ENUM_SUGGESTION, "default,iOS,headless"), "default");
  2042. GLOBAL_DEF_NOVAL(PropertyInfo(Variant::STRING, "display/display_server/driver.macos", PROPERTY_HINT_ENUM_SUGGESTION, "default,macos,headless"), "default");
  2043. GLOBAL_DEF_RST_NOVAL("audio/driver/driver", AudioDriverManager::get_driver(0)->get_name());
  2044. if (audio_driver.is_empty()) { // Specified in project.godot.
  2045. audio_driver = GLOBAL_GET("audio/driver/driver");
  2046. }
  2047. // Make sure that dummy is the last one, which it is assumed to be by design.
  2048. DEV_ASSERT(NULL_AUDIO_DRIVER == AudioDriverManager::get_driver(AudioDriverManager::get_driver_count() - 1)->get_name());
  2049. for (int i = 0; i < AudioDriverManager::get_driver_count(); i++) {
  2050. if (audio_driver == AudioDriverManager::get_driver(i)->get_name()) {
  2051. audio_driver_idx = i;
  2052. break;
  2053. }
  2054. }
  2055. if (audio_driver_idx < 0) {
  2056. // If the requested driver wasn't found, pick the first entry.
  2057. // If all else failed it would be the dummy driver (no sound).
  2058. audio_driver_idx = 0;
  2059. }
  2060. if (Engine::get_singleton()->get_write_movie_path() != String()) {
  2061. // Always use dummy driver for audio driver (which is last), also in no threaded mode.
  2062. audio_driver_idx = AudioDriverManager::get_driver_count() - 1;
  2063. AudioDriverDummy::get_dummy_singleton()->set_use_threads(false);
  2064. }
  2065. {
  2066. window_orientation = DisplayServer::ScreenOrientation(int(GLOBAL_DEF_BASIC("display/window/handheld/orientation", DisplayServer::ScreenOrientation::SCREEN_LANDSCAPE)));
  2067. }
  2068. {
  2069. window_vsync_mode = DisplayServer::VSyncMode(int(GLOBAL_DEF_BASIC("display/window/vsync/vsync_mode", DisplayServer::VSyncMode::VSYNC_ENABLED)));
  2070. if (disable_vsync) {
  2071. window_vsync_mode = DisplayServer::VSyncMode::VSYNC_DISABLED;
  2072. }
  2073. }
  2074. Engine::get_singleton()->set_physics_ticks_per_second(GLOBAL_DEF_BASIC(PropertyInfo(Variant::INT, "physics/common/physics_ticks_per_second", PROPERTY_HINT_RANGE, "1,1000,1"), 60));
  2075. Engine::get_singleton()->set_max_physics_steps_per_frame(GLOBAL_DEF_BASIC(PropertyInfo(Variant::INT, "physics/common/max_physics_steps_per_frame", PROPERTY_HINT_RANGE, "1,100,1"), 8));
  2076. Engine::get_singleton()->set_physics_jitter_fix(GLOBAL_DEF("physics/common/physics_jitter_fix", 0.5));
  2077. Engine::get_singleton()->set_max_fps(GLOBAL_DEF(PropertyInfo(Variant::INT, "application/run/max_fps", PROPERTY_HINT_RANGE, "0,1000,1"), 0));
  2078. GLOBAL_DEF_RST(PropertyInfo(Variant::INT, "audio/driver/output_latency", PROPERTY_HINT_RANGE, "1,100,1"), 15);
  2079. // Use a safer default output_latency for web to avoid audio cracking on low-end devices, especially mobile.
  2080. GLOBAL_DEF_RST("audio/driver/output_latency.web", 50);
  2081. Engine::get_singleton()->set_audio_output_latency(GLOBAL_GET("audio/driver/output_latency"));
  2082. GLOBAL_DEF("debug/settings/stdout/print_fps", false);
  2083. GLOBAL_DEF("debug/settings/stdout/print_gpu_profile", false);
  2084. GLOBAL_DEF("debug/settings/stdout/verbose_stdout", false);
  2085. if (!OS::get_singleton()->_verbose_stdout) { // Not manually overridden.
  2086. OS::get_singleton()->_verbose_stdout = GLOBAL_GET("debug/settings/stdout/verbose_stdout");
  2087. }
  2088. #if defined(MACOS_ENABLED) || defined(IOS_ENABLED)
  2089. OS::get_singleton()->set_environment("MVK_CONFIG_LOG_LEVEL", OS::get_singleton()->_verbose_stdout ? "3" : "1"); // 1 = Errors only, 3 = Info
  2090. #endif
  2091. if (max_fps >= 0) {
  2092. Engine::get_singleton()->set_max_fps(max_fps);
  2093. }
  2094. if (frame_delay == 0) {
  2095. frame_delay = GLOBAL_DEF(PropertyInfo(Variant::INT, "application/run/frame_delay_msec", PROPERTY_HINT_RANGE, "0,100,1,or_greater"), 0);
  2096. if (Engine::get_singleton()->is_editor_hint()) {
  2097. frame_delay = 0;
  2098. }
  2099. }
  2100. if (audio_output_latency >= 1) {
  2101. Engine::get_singleton()->set_audio_output_latency(audio_output_latency);
  2102. }
  2103. OS::get_singleton()->set_low_processor_usage_mode(GLOBAL_DEF("application/run/low_processor_mode", false));
  2104. OS::get_singleton()->set_low_processor_usage_mode_sleep_usec(
  2105. GLOBAL_DEF(PropertyInfo(Variant::INT, "application/run/low_processor_mode_sleep_usec", PROPERTY_HINT_RANGE, "0,33200,1,or_greater"), 6900)); // Roughly 144 FPS
  2106. GLOBAL_DEF("application/run/delta_smoothing", true);
  2107. if (!delta_smoothing_override) {
  2108. OS::get_singleton()->set_delta_smoothing(GLOBAL_GET("application/run/delta_smoothing"));
  2109. }
  2110. GLOBAL_DEF("display/window/ios/allow_high_refresh_rate", true);
  2111. GLOBAL_DEF("display/window/ios/hide_home_indicator", true);
  2112. GLOBAL_DEF("display/window/ios/hide_status_bar", true);
  2113. GLOBAL_DEF("display/window/ios/suppress_ui_gesture", true);
  2114. // XR project settings.
  2115. GLOBAL_DEF_RST_BASIC("xr/openxr/enabled", false);
  2116. GLOBAL_DEF_BASIC(PropertyInfo(Variant::STRING, "xr/openxr/default_action_map", PROPERTY_HINT_FILE, "*.tres"), "res://openxr_action_map.tres");
  2117. GLOBAL_DEF_BASIC(PropertyInfo(Variant::INT, "xr/openxr/form_factor", PROPERTY_HINT_ENUM, "Head Mounted,Handheld"), "0");
  2118. GLOBAL_DEF_BASIC(PropertyInfo(Variant::INT, "xr/openxr/view_configuration", PROPERTY_HINT_ENUM, "Mono,Stereo"), "1"); // "Mono,Stereo,Quad,Observer"
  2119. GLOBAL_DEF_BASIC(PropertyInfo(Variant::INT, "xr/openxr/reference_space", PROPERTY_HINT_ENUM, "Local,Stage,Local Floor"), "1");
  2120. GLOBAL_DEF_BASIC(PropertyInfo(Variant::INT, "xr/openxr/environment_blend_mode", PROPERTY_HINT_ENUM, "Opaque,Additive,Alpha"), "0");
  2121. GLOBAL_DEF_BASIC(PropertyInfo(Variant::INT, "xr/openxr/foveation_level", PROPERTY_HINT_ENUM, "Off,Low,Medium,High"), "0");
  2122. GLOBAL_DEF_BASIC("xr/openxr/foveation_dynamic", false);
  2123. GLOBAL_DEF_BASIC("xr/openxr/submit_depth_buffer", false);
  2124. GLOBAL_DEF_BASIC("xr/openxr/startup_alert", true);
  2125. // OpenXR project extensions settings.
  2126. GLOBAL_DEF_BASIC("xr/openxr/extensions/hand_tracking", true);
  2127. GLOBAL_DEF_RST_BASIC("xr/openxr/extensions/hand_interaction_profile", false);
  2128. GLOBAL_DEF_BASIC("xr/openxr/extensions/eye_gaze_interaction", false);
  2129. #ifdef TOOLS_ENABLED
  2130. // Disabled for now, using XR inside of the editor we'll be working on during the coming months.
  2131. // editor settings (it seems we're too early in the process when setting up rendering, to access editor settings...)
  2132. // EDITOR_DEF_RST("xr/openxr/in_editor", false);
  2133. // GLOBAL_DEF("xr/openxr/in_editor", false);
  2134. #endif
  2135. Engine::get_singleton()->set_frame_delay(frame_delay);
  2136. message_queue = memnew(MessageQueue);
  2137. Thread::release_main_thread(); // If setup2() is called from another thread, that one will become main thread, so preventively release this one.
  2138. set_current_thread_safe_for_nodes(false);
  2139. #if defined(STEAMAPI_ENABLED)
  2140. if (editor || project_manager) {
  2141. steam_tracker = memnew(SteamTracker);
  2142. }
  2143. #endif
  2144. OS::get_singleton()->benchmark_end_measure("Startup", "Main::Setup");
  2145. if (p_second_phase) {
  2146. exit_err = setup2();
  2147. if (exit_err != OK) {
  2148. goto error;
  2149. }
  2150. }
  2151. return OK;
  2152. error:
  2153. text_driver = "";
  2154. display_driver = "";
  2155. audio_driver = "";
  2156. tablet_driver = "";
  2157. Engine::get_singleton()->set_write_movie_path(String());
  2158. project_path = "";
  2159. args.clear();
  2160. main_args.clear();
  2161. if (show_help) {
  2162. print_help(execpath);
  2163. }
  2164. EngineDebugger::deinitialize();
  2165. if (performance) {
  2166. memdelete(performance);
  2167. }
  2168. if (input_map) {
  2169. memdelete(input_map);
  2170. }
  2171. if (translation_server) {
  2172. memdelete(translation_server);
  2173. }
  2174. if (globals) {
  2175. memdelete(globals);
  2176. }
  2177. if (packed_data) {
  2178. memdelete(packed_data);
  2179. }
  2180. unregister_core_driver_types();
  2181. unregister_core_extensions();
  2182. if (engine) {
  2183. memdelete(engine);
  2184. }
  2185. unregister_core_types();
  2186. OS::get_singleton()->_cmdline.clear();
  2187. OS::get_singleton()->_user_args.clear();
  2188. if (message_queue) {
  2189. memdelete(message_queue);
  2190. }
  2191. OS::get_singleton()->benchmark_end_measure("Startup", "Main::Setup");
  2192. #if defined(STEAMAPI_ENABLED)
  2193. if (steam_tracker) {
  2194. memdelete(steam_tracker);
  2195. }
  2196. #endif
  2197. OS::get_singleton()->finalize_core();
  2198. locale = String();
  2199. return exit_err;
  2200. }
  2201. Error _parse_resource_dummy(void *p_data, VariantParser::Stream *p_stream, Ref<Resource> &r_res, int &line, String &r_err_str) {
  2202. VariantParser::Token token;
  2203. VariantParser::get_token(p_stream, token, line, r_err_str);
  2204. if (token.type != VariantParser::TK_NUMBER && token.type != VariantParser::TK_STRING) {
  2205. r_err_str = "Expected number (old style sub-resource index) or String (ext-resource ID)";
  2206. return ERR_PARSE_ERROR;
  2207. }
  2208. r_res.unref();
  2209. VariantParser::get_token(p_stream, token, line, r_err_str);
  2210. if (token.type != VariantParser::TK_PARENTHESIS_CLOSE) {
  2211. r_err_str = "Expected ')'";
  2212. return ERR_PARSE_ERROR;
  2213. }
  2214. return OK;
  2215. }
  2216. Error Main::setup2(bool p_show_boot_logo) {
  2217. OS::get_singleton()->benchmark_begin_measure("Startup", "Main::Setup2");
  2218. Thread::make_main_thread(); // Make whatever thread call this the main thread.
  2219. set_current_thread_safe_for_nodes(true);
  2220. // Don't use rich formatting to prevent ANSI escape codes from being written to log files.
  2221. print_header(false);
  2222. #ifdef TOOLS_ENABLED
  2223. if (editor || project_manager || cmdline_tool) {
  2224. OS::get_singleton()->benchmark_begin_measure("Startup", "Initialize Early Settings");
  2225. EditorPaths::create();
  2226. // Editor setting class is not available, load config directly.
  2227. if (!init_use_custom_screen && (editor || project_manager) && EditorPaths::get_singleton()->are_paths_valid()) {
  2228. ERR_FAIL_COND_V(!DirAccess::dir_exists_absolute(EditorPaths::get_singleton()->get_config_dir()), FAILED);
  2229. String config_file_path = EditorSettings::get_existing_settings_path();
  2230. if (FileAccess::exists(config_file_path)) {
  2231. Error err;
  2232. Ref<FileAccess> f = FileAccess::open(config_file_path, FileAccess::READ, &err);
  2233. if (f.is_valid()) {
  2234. VariantParser::StreamFile stream;
  2235. stream.f = f;
  2236. String assign;
  2237. Variant value;
  2238. VariantParser::Tag next_tag;
  2239. int lines = 0;
  2240. String error_text;
  2241. VariantParser::ResourceParser rp_new;
  2242. rp_new.ext_func = _parse_resource_dummy;
  2243. rp_new.sub_func = _parse_resource_dummy;
  2244. bool screen_found = false;
  2245. String screen_property;
  2246. bool prefer_wayland_found = false;
  2247. bool prefer_wayland = false;
  2248. if (editor) {
  2249. screen_property = "interface/editor/editor_screen";
  2250. } else if (project_manager) {
  2251. screen_property = "interface/editor/project_manager_screen";
  2252. } else {
  2253. // Skip.
  2254. screen_found = true;
  2255. }
  2256. if (!display_driver.is_empty()) {
  2257. // Skip.
  2258. prefer_wayland_found = true;
  2259. }
  2260. while (!screen_found || !prefer_wayland_found) {
  2261. assign = Variant();
  2262. next_tag.fields.clear();
  2263. next_tag.name = String();
  2264. err = VariantParser::parse_tag_assign_eof(&stream, lines, error_text, next_tag, assign, value, &rp_new, true);
  2265. if (err == ERR_FILE_EOF) {
  2266. break;
  2267. }
  2268. if (err == OK && !assign.is_empty()) {
  2269. if (!screen_found && assign == screen_property) {
  2270. init_screen = value;
  2271. screen_found = true;
  2272. }
  2273. if (!prefer_wayland_found && assign == "run/platforms/linuxbsd/prefer_wayland") {
  2274. prefer_wayland = value;
  2275. prefer_wayland_found = true;
  2276. }
  2277. }
  2278. }
  2279. if (display_driver.is_empty()) {
  2280. if (prefer_wayland) {
  2281. display_driver = "wayland";
  2282. } else {
  2283. display_driver = "default";
  2284. }
  2285. }
  2286. }
  2287. }
  2288. }
  2289. if (found_project && EditorPaths::get_singleton()->is_self_contained()) {
  2290. if (ProjectSettings::get_singleton()->get_resource_path() == OS::get_singleton()->get_executable_path().get_base_dir()) {
  2291. ERR_PRINT("You are trying to run a self-contained editor at the same location as a project. This is not allowed, since editor files will mix with project files.");
  2292. OS::get_singleton()->set_exit_code(EXIT_FAILURE);
  2293. return FAILED;
  2294. }
  2295. }
  2296. OS::get_singleton()->benchmark_end_measure("Startup", "Initialize Early Settings");
  2297. }
  2298. #endif
  2299. OS::get_singleton()->benchmark_begin_measure("Startup", "Servers");
  2300. tsman = memnew(TextServerManager);
  2301. if (tsman) {
  2302. Ref<TextServerDummy> ts;
  2303. ts.instantiate();
  2304. tsman->add_interface(ts);
  2305. }
  2306. #ifndef _3D_DISABLED
  2307. physics_server_3d_manager = memnew(PhysicsServer3DManager);
  2308. #endif // _3D_DISABLED
  2309. physics_server_2d_manager = memnew(PhysicsServer2DManager);
  2310. register_server_types();
  2311. {
  2312. OS::get_singleton()->benchmark_begin_measure("Servers", "Modules and Extensions");
  2313. initialize_modules(MODULE_INITIALIZATION_LEVEL_SERVERS);
  2314. GDExtensionManager::get_singleton()->initialize_extensions(GDExtension::INITIALIZATION_LEVEL_SERVERS);
  2315. OS::get_singleton()->benchmark_end_measure("Servers", "Modules and Extensions");
  2316. }
  2317. /* Initialize Input */
  2318. {
  2319. OS::get_singleton()->benchmark_begin_measure("Servers", "Input");
  2320. input = memnew(Input);
  2321. OS::get_singleton()->initialize_joypads();
  2322. OS::get_singleton()->benchmark_end_measure("Servers", "Input");
  2323. }
  2324. /* Initialize Display Server */
  2325. {
  2326. OS::get_singleton()->benchmark_begin_measure("Servers", "Display");
  2327. if (display_driver.is_empty()) {
  2328. display_driver = GLOBAL_GET("display/display_server/driver");
  2329. }
  2330. int display_driver_idx = -1;
  2331. if (display_driver.is_empty() || display_driver == "default") {
  2332. display_driver_idx = 0;
  2333. } else {
  2334. for (int i = 0; i < DisplayServer::get_create_function_count(); i++) {
  2335. String name = DisplayServer::get_create_function_name(i);
  2336. if (display_driver == name) {
  2337. display_driver_idx = i;
  2338. break;
  2339. }
  2340. }
  2341. if (display_driver_idx < 0) {
  2342. // If the requested driver wasn't found, pick the first entry.
  2343. // If all else failed it would be the headless server.
  2344. display_driver_idx = 0;
  2345. }
  2346. }
  2347. // Store this in a globally accessible place, so we can retrieve the rendering drivers
  2348. // list from the display driver for the editor UI.
  2349. OS::get_singleton()->set_display_driver_id(display_driver_idx);
  2350. Vector2i *window_position = nullptr;
  2351. Vector2i position = init_custom_pos;
  2352. if (init_use_custom_pos) {
  2353. window_position = &position;
  2354. }
  2355. Color boot_bg_color = GLOBAL_DEF_BASIC("application/boot_splash/bg_color", boot_splash_bg_color);
  2356. DisplayServer::set_early_window_clear_color_override(true, boot_bg_color);
  2357. DisplayServer::Context context;
  2358. if (editor) {
  2359. context = DisplayServer::CONTEXT_EDITOR;
  2360. } else if (project_manager) {
  2361. context = DisplayServer::CONTEXT_PROJECTMAN;
  2362. } else {
  2363. context = DisplayServer::CONTEXT_ENGINE;
  2364. }
  2365. // rendering_driver now held in static global String in main and initialized in setup()
  2366. Error err;
  2367. display_server = DisplayServer::create(display_driver_idx, rendering_driver, window_mode, window_vsync_mode, window_flags, window_position, window_size, init_screen, context, err);
  2368. if (err != OK || display_server == nullptr) {
  2369. // We can't use this display server, try other ones as fallback.
  2370. // Skip headless (always last registered) because that's not what users
  2371. // would expect if they didn't request it explicitly.
  2372. for (int i = 0; i < DisplayServer::get_create_function_count() - 1; i++) {
  2373. if (i == display_driver_idx) {
  2374. continue; // Don't try the same twice.
  2375. }
  2376. display_server = DisplayServer::create(i, rendering_driver, window_mode, window_vsync_mode, window_flags, window_position, window_size, init_screen, context, err);
  2377. if (err == OK && display_server != nullptr) {
  2378. break;
  2379. }
  2380. }
  2381. }
  2382. if (err != OK || display_server == nullptr) {
  2383. ERR_PRINT("Unable to create DisplayServer, all display drivers failed.\nUse \"--headless\" command line argument to run the engine in headless mode if this is desired (e.g. for continuous integration).");
  2384. if (display_server) {
  2385. memdelete(display_server);
  2386. }
  2387. GDExtensionManager::get_singleton()->deinitialize_extensions(GDExtension::INITIALIZATION_LEVEL_SERVERS);
  2388. uninitialize_modules(MODULE_INITIALIZATION_LEVEL_SERVERS);
  2389. unregister_server_types();
  2390. if (input) {
  2391. memdelete(input);
  2392. }
  2393. if (tsman) {
  2394. memdelete(tsman);
  2395. }
  2396. #ifndef _3D_DISABLED
  2397. if (physics_server_3d_manager) {
  2398. memdelete(physics_server_3d_manager);
  2399. }
  2400. #endif // _3D_DISABLED
  2401. if (physics_server_2d_manager) {
  2402. memdelete(physics_server_2d_manager);
  2403. }
  2404. return err;
  2405. }
  2406. if (display_server->has_feature(DisplayServer::FEATURE_ORIENTATION)) {
  2407. display_server->screen_set_orientation(window_orientation);
  2408. }
  2409. OS::get_singleton()->benchmark_end_measure("Servers", "Display");
  2410. }
  2411. if (GLOBAL_GET("debug/settings/stdout/print_fps") || print_fps) {
  2412. // Print requested V-Sync mode at startup to diagnose the printed FPS not going above the monitor refresh rate.
  2413. switch (window_vsync_mode) {
  2414. case DisplayServer::VSyncMode::VSYNC_DISABLED:
  2415. print_line("Requested V-Sync mode: Disabled");
  2416. break;
  2417. case DisplayServer::VSyncMode::VSYNC_ENABLED:
  2418. print_line("Requested V-Sync mode: Enabled - FPS will likely be capped to the monitor refresh rate.");
  2419. break;
  2420. case DisplayServer::VSyncMode::VSYNC_ADAPTIVE:
  2421. print_line("Requested V-Sync mode: Adaptive");
  2422. break;
  2423. case DisplayServer::VSyncMode::VSYNC_MAILBOX:
  2424. print_line("Requested V-Sync mode: Mailbox");
  2425. break;
  2426. }
  2427. }
  2428. if (OS::get_singleton()->_render_thread_mode == OS::RENDER_SEPARATE_THREAD) {
  2429. WARN_PRINT("The Multi-Threaded rendering thread model is experimental. Feel free to try it since it will eventually become a stable feature.\n"
  2430. "However, bear in mind that at the moment it can lead to project crashes or instability.\n"
  2431. "So, unless you want to test the engine, use the Single-Safe option in the project settings instead.");
  2432. }
  2433. /* Initialize Pen Tablet Driver */
  2434. {
  2435. OS::get_singleton()->benchmark_begin_measure("Servers", "Tablet Driver");
  2436. GLOBAL_DEF_RST_NOVAL("input_devices/pen_tablet/driver", "");
  2437. GLOBAL_DEF_RST_NOVAL(PropertyInfo(Variant::STRING, "input_devices/pen_tablet/driver.windows", PROPERTY_HINT_ENUM, "winink,wintab,dummy"), "");
  2438. if (tablet_driver.is_empty()) { // specified in project.godot
  2439. tablet_driver = GLOBAL_GET("input_devices/pen_tablet/driver");
  2440. if (tablet_driver.is_empty()) {
  2441. tablet_driver = DisplayServer::get_singleton()->tablet_get_driver_name(0);
  2442. }
  2443. }
  2444. for (int i = 0; i < DisplayServer::get_singleton()->tablet_get_driver_count(); i++) {
  2445. if (tablet_driver == DisplayServer::get_singleton()->tablet_get_driver_name(i)) {
  2446. DisplayServer::get_singleton()->tablet_set_current_driver(DisplayServer::get_singleton()->tablet_get_driver_name(i));
  2447. break;
  2448. }
  2449. }
  2450. if (DisplayServer::get_singleton()->tablet_get_current_driver().is_empty()) {
  2451. DisplayServer::get_singleton()->tablet_set_current_driver(DisplayServer::get_singleton()->tablet_get_driver_name(0));
  2452. }
  2453. print_verbose("Using \"" + tablet_driver + "\" pen tablet driver...");
  2454. OS::get_singleton()->benchmark_end_measure("Servers", "Tablet Driver");
  2455. }
  2456. /* Initialize Rendering Server */
  2457. {
  2458. OS::get_singleton()->benchmark_begin_measure("Servers", "Rendering");
  2459. rendering_server = memnew(RenderingServerDefault(OS::get_singleton()->get_render_thread_mode() == OS::RENDER_SEPARATE_THREAD));
  2460. rendering_server->init();
  2461. //rendering_server->call_set_use_vsync(OS::get_singleton()->_use_vsync);
  2462. rendering_server->set_render_loop_enabled(!disable_render_loop);
  2463. if (profile_gpu || (!editor && bool(GLOBAL_GET("debug/settings/stdout/print_gpu_profile")))) {
  2464. rendering_server->set_print_gpu_profile(true);
  2465. }
  2466. if (Engine::get_singleton()->get_write_movie_path() != String()) {
  2467. movie_writer = MovieWriter::find_writer_for_file(Engine::get_singleton()->get_write_movie_path());
  2468. if (movie_writer == nullptr) {
  2469. ERR_PRINT("Can't find movie writer for file type, aborting: " + Engine::get_singleton()->get_write_movie_path());
  2470. Engine::get_singleton()->set_write_movie_path(String());
  2471. }
  2472. }
  2473. OS::get_singleton()->benchmark_end_measure("Servers", "Rendering");
  2474. }
  2475. #ifdef UNIX_ENABLED
  2476. // Print warning after initializing the renderer but before initializing audio.
  2477. if (OS::get_singleton()->get_environment("USER") == "root" && !OS::get_singleton()->has_environment("GODOT_SILENCE_ROOT_WARNING")) {
  2478. WARN_PRINT("Started the engine as `root`/superuser. This is a security risk, and subsystems like audio may not work correctly.\nSet the environment variable `GODOT_SILENCE_ROOT_WARNING` to 1 to silence this warning.");
  2479. }
  2480. #endif
  2481. /* Initialize Audio Driver */
  2482. {
  2483. OS::get_singleton()->benchmark_begin_measure("Servers", "Audio");
  2484. AudioDriverManager::initialize(audio_driver_idx);
  2485. // Right moment to create and initialize the audio server.
  2486. audio_server = memnew(AudioServer);
  2487. audio_server->init();
  2488. OS::get_singleton()->benchmark_end_measure("Servers", "Audio");
  2489. }
  2490. #ifndef _3D_DISABLED
  2491. /* Initialize XR Server */
  2492. {
  2493. OS::get_singleton()->benchmark_begin_measure("Servers", "XR");
  2494. xr_server = memnew(XRServer);
  2495. OS::get_singleton()->benchmark_end_measure("Servers", "XR");
  2496. }
  2497. #endif // _3D_DISABLED
  2498. OS::get_singleton()->benchmark_end_measure("Startup", "Servers");
  2499. #ifndef WEB_ENABLED
  2500. // Add a blank line for readability.
  2501. Engine::get_singleton()->print_header("");
  2502. #endif // WEB_ENABLED
  2503. register_core_singletons();
  2504. /* Initialize the main window and boot screen */
  2505. {
  2506. OS::get_singleton()->benchmark_begin_measure("Startup", "Setup Window and Boot");
  2507. MAIN_PRINT("Main: Setup Logo");
  2508. if (init_windowed) {
  2509. //do none..
  2510. } else if (init_maximized) {
  2511. DisplayServer::get_singleton()->window_set_mode(DisplayServer::WINDOW_MODE_MAXIMIZED);
  2512. } else if (init_fullscreen) {
  2513. DisplayServer::get_singleton()->window_set_mode(DisplayServer::WINDOW_MODE_FULLSCREEN);
  2514. }
  2515. if (init_always_on_top) {
  2516. DisplayServer::get_singleton()->window_set_flag(DisplayServer::WINDOW_FLAG_ALWAYS_ON_TOP, true);
  2517. }
  2518. Color clear = GLOBAL_DEF_BASIC("rendering/environment/defaults/default_clear_color", Color(0.3, 0.3, 0.3));
  2519. RenderingServer::get_singleton()->set_default_clear_color(clear);
  2520. if (p_show_boot_logo) {
  2521. setup_boot_logo();
  2522. }
  2523. MAIN_PRINT("Main: Clear Color");
  2524. DisplayServer::set_early_window_clear_color_override(false);
  2525. GLOBAL_DEF_BASIC(PropertyInfo(Variant::STRING, "application/config/icon", PROPERTY_HINT_FILE, "*.png,*.webp,*.svg"), String());
  2526. GLOBAL_DEF(PropertyInfo(Variant::STRING, "application/config/macos_native_icon", PROPERTY_HINT_FILE, "*.icns"), String());
  2527. GLOBAL_DEF(PropertyInfo(Variant::STRING, "application/config/windows_native_icon", PROPERTY_HINT_FILE, "*.ico"), String());
  2528. MAIN_PRINT("Main: Touch Input");
  2529. Input *id = Input::get_singleton();
  2530. if (id) {
  2531. bool agile_input_event_flushing = GLOBAL_DEF("input_devices/buffering/agile_event_flushing", false);
  2532. id->set_agile_input_event_flushing(agile_input_event_flushing);
  2533. if (bool(GLOBAL_DEF_BASIC("input_devices/pointing/emulate_touch_from_mouse", false)) &&
  2534. !(editor || project_manager)) {
  2535. if (!DisplayServer::get_singleton()->is_touchscreen_available()) {
  2536. //only if no touchscreen ui hint, set emulation
  2537. id->set_emulate_touch_from_mouse(true);
  2538. }
  2539. }
  2540. id->set_emulate_mouse_from_touch(bool(GLOBAL_DEF_BASIC("input_devices/pointing/emulate_mouse_from_touch", true)));
  2541. }
  2542. GLOBAL_DEF_BASIC("input_devices/pointing/android/enable_long_press_as_right_click", false);
  2543. GLOBAL_DEF_BASIC("input_devices/pointing/android/enable_pan_and_scale_gestures", false);
  2544. GLOBAL_DEF_BASIC(PropertyInfo(Variant::INT, "input_devices/pointing/android/rotary_input_scroll_axis", PROPERTY_HINT_ENUM, "Horizontal,Vertical"), 1);
  2545. OS::get_singleton()->benchmark_end_measure("Startup", "Setup Window and Boot");
  2546. }
  2547. MAIN_PRINT("Main: Load Translations and Remaps");
  2548. /* Setup translations and remaps */
  2549. {
  2550. OS::get_singleton()->benchmark_begin_measure("Startup", "Translations and Remaps");
  2551. translation_server->setup(); //register translations, load them, etc.
  2552. if (!locale.is_empty()) {
  2553. translation_server->set_locale(locale);
  2554. }
  2555. translation_server->load_translations();
  2556. ResourceLoader::load_translation_remaps(); //load remaps for resources
  2557. ResourceLoader::load_path_remaps();
  2558. OS::get_singleton()->benchmark_end_measure("Startup", "Translations and Remaps");
  2559. }
  2560. MAIN_PRINT("Main: Load TextServer");
  2561. /* Setup Text Server */
  2562. {
  2563. OS::get_singleton()->benchmark_begin_measure("Startup", "Text Server");
  2564. /* Enum text drivers */
  2565. GLOBAL_DEF_RST("internationalization/rendering/text_driver", "");
  2566. String text_driver_options;
  2567. for (int i = 0; i < TextServerManager::get_singleton()->get_interface_count(); i++) {
  2568. const String driver_name = TextServerManager::get_singleton()->get_interface(i)->get_name();
  2569. if (driver_name == "Dummy") {
  2570. // Dummy text driver cannot draw any text, making the editor unusable if selected.
  2571. continue;
  2572. }
  2573. if (!text_driver_options.is_empty() && !text_driver_options.contains(",")) {
  2574. // Not the first option; add a comma before it as a separator for the property hint.
  2575. text_driver_options += ",";
  2576. }
  2577. text_driver_options += driver_name;
  2578. }
  2579. ProjectSettings::get_singleton()->set_custom_property_info(PropertyInfo(Variant::STRING, "internationalization/rendering/text_driver", PROPERTY_HINT_ENUM, text_driver_options));
  2580. /* Determine text driver */
  2581. if (text_driver.is_empty()) {
  2582. text_driver = GLOBAL_GET("internationalization/rendering/text_driver");
  2583. }
  2584. if (!text_driver.is_empty()) {
  2585. /* Load user selected text server. */
  2586. for (int i = 0; i < TextServerManager::get_singleton()->get_interface_count(); i++) {
  2587. if (TextServerManager::get_singleton()->get_interface(i)->get_name() == text_driver) {
  2588. text_driver_idx = i;
  2589. break;
  2590. }
  2591. }
  2592. }
  2593. if (text_driver_idx < 0) {
  2594. /* If not selected, use one with the most features available. */
  2595. int max_features = 0;
  2596. for (int i = 0; i < TextServerManager::get_singleton()->get_interface_count(); i++) {
  2597. uint32_t features = TextServerManager::get_singleton()->get_interface(i)->get_features();
  2598. int feature_number = 0;
  2599. while (features) {
  2600. feature_number += features & 1;
  2601. features >>= 1;
  2602. }
  2603. if (feature_number >= max_features) {
  2604. max_features = feature_number;
  2605. text_driver_idx = i;
  2606. }
  2607. }
  2608. }
  2609. if (text_driver_idx >= 0) {
  2610. Ref<TextServer> ts = TextServerManager::get_singleton()->get_interface(text_driver_idx);
  2611. TextServerManager::get_singleton()->set_primary_interface(ts);
  2612. if (ts->has_feature(TextServer::FEATURE_USE_SUPPORT_DATA)) {
  2613. ts->load_support_data("res://" + ts->get_support_data_filename());
  2614. }
  2615. } else {
  2616. ERR_FAIL_V_MSG(ERR_CANT_CREATE, "TextServer: Unable to create TextServer interface.");
  2617. }
  2618. OS::get_singleton()->benchmark_end_measure("Startup", "Text Server");
  2619. }
  2620. MAIN_PRINT("Main: Load Scene Types");
  2621. OS::get_singleton()->benchmark_begin_measure("Startup", "Scene");
  2622. // Initialize ThemeDB early so that scene types can register their theme items.
  2623. // Default theme will be initialized later, after modules and ScriptServer are ready.
  2624. initialize_theme_db();
  2625. register_scene_types();
  2626. register_driver_types();
  2627. register_scene_singletons();
  2628. {
  2629. OS::get_singleton()->benchmark_begin_measure("Scene", "Modules and Extensions");
  2630. initialize_modules(MODULE_INITIALIZATION_LEVEL_SCENE);
  2631. GDExtensionManager::get_singleton()->initialize_extensions(GDExtension::INITIALIZATION_LEVEL_SCENE);
  2632. OS::get_singleton()->benchmark_end_measure("Scene", "Modules and Extensions");
  2633. }
  2634. PackedStringArray extensions;
  2635. extensions.push_back("gd");
  2636. if (ClassDB::class_exists("CSharpScript")) {
  2637. extensions.push_back("cs");
  2638. }
  2639. extensions.push_back("gdshader");
  2640. GLOBAL_DEF_NOVAL(PropertyInfo(Variant::PACKED_STRING_ARRAY, "editor/script/search_in_file_extensions"), extensions); // Note: should be defined after Scene level modules init to see .NET.
  2641. OS::get_singleton()->benchmark_end_measure("Startup", "Scene");
  2642. #ifdef TOOLS_ENABLED
  2643. ClassDB::set_current_api(ClassDB::API_EDITOR);
  2644. register_editor_types();
  2645. {
  2646. OS::get_singleton()->benchmark_begin_measure("Editor", "Modules and Extensions");
  2647. initialize_modules(MODULE_INITIALIZATION_LEVEL_EDITOR);
  2648. GDExtensionManager::get_singleton()->initialize_extensions(GDExtension::INITIALIZATION_LEVEL_EDITOR);
  2649. OS::get_singleton()->benchmark_end_measure("Editor", "Modules and Extensions");
  2650. }
  2651. ClassDB::set_current_api(ClassDB::API_CORE);
  2652. #endif
  2653. MAIN_PRINT("Main: Load Platforms");
  2654. OS::get_singleton()->benchmark_begin_measure("Startup", "Platforms");
  2655. register_platform_apis();
  2656. OS::get_singleton()->benchmark_end_measure("Startup", "Platforms");
  2657. GLOBAL_DEF_BASIC(PropertyInfo(Variant::STRING, "display/mouse_cursor/custom_image", PROPERTY_HINT_FILE, "*.png,*.webp"), String());
  2658. GLOBAL_DEF_BASIC("display/mouse_cursor/custom_image_hotspot", Vector2());
  2659. GLOBAL_DEF_BASIC("display/mouse_cursor/tooltip_position_offset", Point2(10, 10));
  2660. if (String(GLOBAL_GET("display/mouse_cursor/custom_image")) != String()) {
  2661. Ref<Texture2D> cursor = ResourceLoader::load(
  2662. GLOBAL_GET("display/mouse_cursor/custom_image"));
  2663. if (cursor.is_valid()) {
  2664. Vector2 hotspot = GLOBAL_GET("display/mouse_cursor/custom_image_hotspot");
  2665. Input::get_singleton()->set_custom_mouse_cursor(cursor, Input::CURSOR_ARROW, hotspot);
  2666. }
  2667. }
  2668. OS::get_singleton()->benchmark_begin_measure("Startup", "Finalize Setup");
  2669. camera_server = CameraServer::create();
  2670. MAIN_PRINT("Main: Load Physics");
  2671. initialize_physics();
  2672. MAIN_PRINT("Main: Load Navigation");
  2673. initialize_navigation_server();
  2674. register_server_singletons();
  2675. // This loads global classes, so it must happen before custom loaders and savers are registered
  2676. ScriptServer::init_languages();
  2677. theme_db->initialize_theme();
  2678. audio_server->load_default_bus_layout();
  2679. #if defined(MODULE_MONO_ENABLED) && defined(TOOLS_ENABLED)
  2680. // Hacky to have it here, but we don't have good facility yet to let modules
  2681. // register command line options to call at the right time. This needs to happen
  2682. // after init'ing the ScriptServer, but also after init'ing the ThemeDB,
  2683. // for the C# docs generation in the bindings.
  2684. List<String> cmdline_args = OS::get_singleton()->get_cmdline_args();
  2685. BindingsGenerator::handle_cmdline_args(cmdline_args);
  2686. #endif
  2687. if (use_debug_profiler && EngineDebugger::is_active()) {
  2688. // Start the "scripts" profiler, used in local debugging.
  2689. // We could add more, and make the CLI arg require a comma-separated list of profilers.
  2690. EngineDebugger::get_singleton()->profiler_enable("scripts", true);
  2691. }
  2692. if (!project_manager) {
  2693. // If not running the project manager, and now that the engine is
  2694. // able to load resources, load the global shader variables.
  2695. // If running on editor, don't load the textures because the editor
  2696. // may want to import them first. Editor will reload those later.
  2697. rendering_server->global_shader_parameters_load_settings(!editor);
  2698. }
  2699. OS::get_singleton()->benchmark_end_measure("Startup", "Finalize Setup");
  2700. _start_success = true;
  2701. ClassDB::set_current_api(ClassDB::API_NONE); //no more APIs are registered at this point
  2702. print_verbose("CORE API HASH: " + uitos(ClassDB::get_api_hash(ClassDB::API_CORE)));
  2703. print_verbose("EDITOR API HASH: " + uitos(ClassDB::get_api_hash(ClassDB::API_EDITOR)));
  2704. MAIN_PRINT("Main: Done");
  2705. OS::get_singleton()->benchmark_end_measure("Startup", "Main::Setup2");
  2706. return OK;
  2707. }
  2708. void Main::setup_boot_logo() {
  2709. MAIN_PRINT("Main: Load Boot Image");
  2710. #if !defined(TOOLS_ENABLED) && defined(WEB_ENABLED)
  2711. bool show_logo = false;
  2712. #else
  2713. bool show_logo = true;
  2714. #endif
  2715. if (show_logo) { //boot logo!
  2716. const bool boot_logo_image = GLOBAL_DEF_BASIC("application/boot_splash/show_image", true);
  2717. const String boot_logo_path = String(GLOBAL_DEF_BASIC(PropertyInfo(Variant::STRING, "application/boot_splash/image", PROPERTY_HINT_FILE, "*.png"), String())).strip_edges();
  2718. const bool boot_logo_scale = GLOBAL_DEF_BASIC("application/boot_splash/fullsize", true);
  2719. const bool boot_logo_filter = GLOBAL_DEF_BASIC("application/boot_splash/use_filter", true);
  2720. Ref<Image> boot_logo;
  2721. if (boot_logo_image) {
  2722. if (!boot_logo_path.is_empty()) {
  2723. boot_logo.instantiate();
  2724. Error load_err = ImageLoader::load_image(boot_logo_path, boot_logo);
  2725. if (load_err) {
  2726. ERR_PRINT("Non-existing or invalid boot splash at '" + boot_logo_path + "'. Loading default splash.");
  2727. }
  2728. }
  2729. } else {
  2730. // Create a 1×1 transparent image. This will effectively hide the splash image.
  2731. boot_logo.instantiate();
  2732. boot_logo->initialize_data(1, 1, false, Image::FORMAT_RGBA8);
  2733. boot_logo->set_pixel(0, 0, Color(0, 0, 0, 0));
  2734. }
  2735. Color boot_bg_color = GLOBAL_GET("application/boot_splash/bg_color");
  2736. #if defined(TOOLS_ENABLED) && !defined(NO_EDITOR_SPLASH)
  2737. boot_bg_color = GLOBAL_DEF_BASIC("application/boot_splash/bg_color", (editor || project_manager) ? boot_splash_editor_bg_color : boot_splash_bg_color);
  2738. #endif
  2739. if (boot_logo.is_valid()) {
  2740. RenderingServer::get_singleton()->set_boot_image(boot_logo, boot_bg_color, boot_logo_scale, boot_logo_filter);
  2741. } else {
  2742. #ifndef NO_DEFAULT_BOOT_LOGO
  2743. MAIN_PRINT("Main: Create bootsplash");
  2744. #if defined(TOOLS_ENABLED) && !defined(NO_EDITOR_SPLASH)
  2745. Ref<Image> splash = (editor || project_manager) ? memnew(Image(boot_splash_editor_png)) : memnew(Image(boot_splash_png));
  2746. #else
  2747. Ref<Image> splash = memnew(Image(boot_splash_png));
  2748. #endif
  2749. MAIN_PRINT("Main: ClearColor");
  2750. RenderingServer::get_singleton()->set_default_clear_color(boot_bg_color);
  2751. MAIN_PRINT("Main: Image");
  2752. RenderingServer::get_singleton()->set_boot_image(splash, boot_bg_color, false);
  2753. #endif
  2754. }
  2755. #if defined(TOOLS_ENABLED) && defined(MACOS_ENABLED)
  2756. if (DisplayServer::get_singleton()->has_feature(DisplayServer::FEATURE_ICON) && OS::get_singleton()->get_bundle_icon_path().is_empty()) {
  2757. Ref<Image> icon = memnew(Image(app_icon_png));
  2758. DisplayServer::get_singleton()->set_icon(icon);
  2759. }
  2760. #endif
  2761. }
  2762. RenderingServer::get_singleton()->set_default_clear_color(
  2763. GLOBAL_GET("rendering/environment/defaults/default_clear_color"));
  2764. }
  2765. String Main::get_rendering_driver_name() {
  2766. return rendering_driver;
  2767. }
  2768. // everything the main loop needs to know about frame timings
  2769. static MainTimerSync main_timer_sync;
  2770. // Return value should be EXIT_SUCCESS if we start successfully
  2771. // and should move on to `OS::run`, and EXIT_FAILURE otherwise for
  2772. // an early exit with that error code.
  2773. int Main::start() {
  2774. OS::get_singleton()->benchmark_begin_measure("Startup", "Main::Start");
  2775. ERR_FAIL_COND_V(!_start_success, false);
  2776. bool has_icon = false;
  2777. String positional_arg;
  2778. String game_path;
  2779. String script;
  2780. String main_loop_type;
  2781. bool check_only = false;
  2782. #ifdef TOOLS_ENABLED
  2783. String doc_tool_path;
  2784. bool doc_tool_implicit_cwd = false;
  2785. BitField<DocTools::GenerateFlags> gen_flags;
  2786. String _export_preset;
  2787. bool export_debug = false;
  2788. bool export_pack_only = false;
  2789. bool install_android_build_template = false;
  2790. #ifdef MODULE_GDSCRIPT_ENABLED
  2791. String gdscript_docs_path;
  2792. #endif
  2793. #ifndef DISABLE_DEPRECATED
  2794. bool converting_project = false;
  2795. bool validating_converting_project = false;
  2796. #endif // DISABLE_DEPRECATED
  2797. #endif // TOOLS_ENABLED
  2798. main_timer_sync.init(OS::get_singleton()->get_ticks_usec());
  2799. List<String> args = OS::get_singleton()->get_cmdline_args();
  2800. for (List<String>::Element *E = args.front(); E; E = E->next()) {
  2801. // First check parameters that do not have an argument to the right.
  2802. // Doctest Unit Testing Handler
  2803. // Designed to override and pass arguments to the unit test handler.
  2804. if (E->get() == "--check-only") {
  2805. check_only = true;
  2806. #ifdef TOOLS_ENABLED
  2807. } else if (E->get() == "--no-docbase") {
  2808. gen_flags.set_flag(DocTools::GENERATE_FLAG_SKIP_BASIC_TYPES);
  2809. } else if (E->get() == "--gdextension-docs") {
  2810. gen_flags.set_flag(DocTools::GENERATE_FLAG_SKIP_BASIC_TYPES);
  2811. gen_flags.set_flag(DocTools::GENERATE_FLAG_EXTENSION_CLASSES_ONLY);
  2812. #ifndef DISABLE_DEPRECATED
  2813. } else if (E->get() == "--convert-3to4") {
  2814. converting_project = true;
  2815. } else if (E->get() == "--validate-conversion-3to4") {
  2816. validating_converting_project = true;
  2817. #endif // DISABLE_DEPRECATED
  2818. } else if (E->get() == "-e" || E->get() == "--editor") {
  2819. editor = true;
  2820. } else if (E->get() == "-p" || E->get() == "--project-manager") {
  2821. project_manager = true;
  2822. } else if (E->get() == "--install-android-build-template") {
  2823. install_android_build_template = true;
  2824. #endif // TOOLS_ENABLED
  2825. } else if (E->get().length() && E->get()[0] != '-' && positional_arg.is_empty()) {
  2826. positional_arg = E->get();
  2827. if (E->get().ends_with(".scn") ||
  2828. E->get().ends_with(".tscn") ||
  2829. E->get().ends_with(".escn") ||
  2830. E->get().ends_with(".res") ||
  2831. E->get().ends_with(".tres")) {
  2832. // Only consider the positional argument to be a scene path if it ends with
  2833. // a file extension associated with Godot scenes. This makes it possible
  2834. // for projects to parse command-line arguments for custom CLI arguments
  2835. // or other file extensions without trouble. This can be used to implement
  2836. // "drag-and-drop onto executable" logic, which can prove helpful
  2837. // for non-game applications.
  2838. game_path = E->get();
  2839. }
  2840. }
  2841. // Then parameters that have an argument to the right.
  2842. else if (E->next()) {
  2843. bool parsed_pair = true;
  2844. if (E->get() == "-s" || E->get() == "--script") {
  2845. script = E->next()->get();
  2846. } else if (E->get() == "--main-loop") {
  2847. main_loop_type = E->next()->get();
  2848. #ifdef TOOLS_ENABLED
  2849. } else if (E->get() == "--doctool") {
  2850. doc_tool_path = E->next()->get();
  2851. if (doc_tool_path.begins_with("-")) {
  2852. // Assuming other command line arg, so default to cwd.
  2853. doc_tool_path = ".";
  2854. doc_tool_implicit_cwd = true;
  2855. parsed_pair = false;
  2856. }
  2857. #ifdef MODULE_GDSCRIPT_ENABLED
  2858. } else if (E->get() == "--gdscript-docs") {
  2859. gdscript_docs_path = E->next()->get();
  2860. #endif
  2861. } else if (E->get() == "--export-release") {
  2862. ERR_FAIL_COND_V_MSG(!editor && !found_project, EXIT_FAILURE, "Please provide a valid project path when exporting, aborting.");
  2863. editor = true; //needs editor
  2864. _export_preset = E->next()->get();
  2865. } else if (E->get() == "--export-debug") {
  2866. ERR_FAIL_COND_V_MSG(!editor && !found_project, EXIT_FAILURE, "Please provide a valid project path when exporting, aborting.");
  2867. editor = true; //needs editor
  2868. _export_preset = E->next()->get();
  2869. export_debug = true;
  2870. } else if (E->get() == "--export-pack") {
  2871. ERR_FAIL_COND_V_MSG(!editor && !found_project, EXIT_FAILURE, "Please provide a valid project path when exporting, aborting.");
  2872. editor = true;
  2873. _export_preset = E->next()->get();
  2874. export_pack_only = true;
  2875. #endif
  2876. } else {
  2877. // The parameter does not match anything known, don't skip the next argument
  2878. parsed_pair = false;
  2879. }
  2880. if (parsed_pair) {
  2881. E = E->next();
  2882. }
  2883. } else if (E->get().begins_with("--export-")) {
  2884. ERR_FAIL_V_MSG(EXIT_FAILURE, "Missing export preset name, aborting.");
  2885. }
  2886. #ifdef TOOLS_ENABLED
  2887. // Handle case where no path is given to --doctool.
  2888. else if (E->get() == "--doctool") {
  2889. doc_tool_path = ".";
  2890. doc_tool_implicit_cwd = true;
  2891. }
  2892. #endif
  2893. }
  2894. uint64_t minimum_time_msec = GLOBAL_DEF(PropertyInfo(Variant::INT, "application/boot_splash/minimum_display_time", PROPERTY_HINT_RANGE, "0,100,1,or_greater,suffix:ms"), 0);
  2895. if (Engine::get_singleton()->is_editor_hint()) {
  2896. minimum_time_msec = 0;
  2897. }
  2898. #ifdef TOOLS_ENABLED
  2899. #ifdef MODULE_GDSCRIPT_ENABLED
  2900. if (!doc_tool_path.is_empty() && gdscript_docs_path.is_empty()) {
  2901. #else
  2902. if (!doc_tool_path.is_empty()) {
  2903. #endif
  2904. // Needed to instance editor-only classes for their default values
  2905. Engine::get_singleton()->set_editor_hint(true);
  2906. // Translate the class reference only when `-l LOCALE` parameter is given.
  2907. if (!locale.is_empty() && locale != "en") {
  2908. load_doc_translations(locale);
  2909. }
  2910. {
  2911. Ref<DirAccess> da = DirAccess::open(doc_tool_path);
  2912. ERR_FAIL_COND_V_MSG(da.is_null(), EXIT_FAILURE, "Argument supplied to --doctool must be a valid directory path.");
  2913. // Ensure that doctool is running in the root dir, but only if
  2914. // user did not manually specify a path as argument.
  2915. if (doc_tool_implicit_cwd) {
  2916. ERR_FAIL_COND_V_MSG(!da->dir_exists("doc"), EXIT_FAILURE, "--doctool must be run from the Godot repository's root folder, or specify a path that points there.");
  2917. }
  2918. }
  2919. #ifndef MODULE_MONO_ENABLED
  2920. // Hack to define .NET-specific project settings even on non-.NET builds,
  2921. // so that we don't lose their descriptions and default values in DocTools.
  2922. // Default values should be synced with mono_gd/gd_mono.cpp.
  2923. GLOBAL_DEF("dotnet/project/assembly_name", "");
  2924. GLOBAL_DEF("dotnet/project/solution_directory", "");
  2925. GLOBAL_DEF(PropertyInfo(Variant::INT, "dotnet/project/assembly_reload_attempts", PROPERTY_HINT_RANGE, "1,16,1,or_greater"), 3);
  2926. #endif
  2927. Error err;
  2928. DocTools doc;
  2929. doc.generate(gen_flags);
  2930. DocTools docsrc;
  2931. HashMap<String, String> doc_data_classes;
  2932. HashSet<String> checked_paths;
  2933. print_line("Loading docs...");
  2934. const bool gdextension_docs = gen_flags.has_flag(DocTools::GENERATE_FLAG_EXTENSION_CLASSES_ONLY);
  2935. if (!gdextension_docs) {
  2936. for (int i = 0; i < _doc_data_class_path_count; i++) {
  2937. // Custom modules are always located by absolute path.
  2938. String path = _doc_data_class_paths[i].path;
  2939. if (path.is_relative_path()) {
  2940. path = doc_tool_path.path_join(path);
  2941. }
  2942. String name = _doc_data_class_paths[i].name;
  2943. doc_data_classes[name] = path;
  2944. if (!checked_paths.has(path)) {
  2945. checked_paths.insert(path);
  2946. // Create the module documentation directory if it doesn't exist
  2947. Ref<DirAccess> da = DirAccess::create_for_path(path);
  2948. err = da->make_dir_recursive(path);
  2949. ERR_FAIL_COND_V_MSG(err != OK, EXIT_FAILURE, "Error: Can't create directory: " + path + ": " + itos(err));
  2950. print_line("Loading docs from: " + path);
  2951. err = docsrc.load_classes(path);
  2952. ERR_FAIL_COND_V_MSG(err != OK, EXIT_FAILURE, "Error loading docs from: " + path + ": " + itos(err));
  2953. }
  2954. }
  2955. }
  2956. // For GDExtension docs, use a path that is compatible with Godot modules.
  2957. String index_path = gdextension_docs ? doc_tool_path.path_join("doc_classes") : doc_tool_path.path_join("doc/classes");
  2958. // Create the main documentation directory if it doesn't exist
  2959. Ref<DirAccess> da = DirAccess::create_for_path(index_path);
  2960. err = da->make_dir_recursive(index_path);
  2961. ERR_FAIL_COND_V_MSG(err != OK, EXIT_FAILURE, "Error: Can't create index directory: " + index_path + ": " + itos(err));
  2962. print_line("Loading classes from: " + index_path);
  2963. err = docsrc.load_classes(index_path);
  2964. ERR_FAIL_COND_V_MSG(err != OK, EXIT_FAILURE, "Error loading classes from: " + index_path + ": " + itos(err));
  2965. checked_paths.insert(index_path);
  2966. print_line("Merging docs...");
  2967. doc.merge_from(docsrc);
  2968. for (const String &E : checked_paths) {
  2969. print_line("Erasing old docs at: " + E);
  2970. err = DocTools::erase_classes(E);
  2971. ERR_FAIL_COND_V_MSG(err != OK, EXIT_FAILURE, "Error erasing old docs at: " + E + ": " + itos(err));
  2972. }
  2973. print_line("Generating new docs...");
  2974. err = doc.save_classes(index_path, doc_data_classes, !gdextension_docs);
  2975. ERR_FAIL_COND_V_MSG(err != OK, EXIT_FAILURE, "Error saving new docs:" + itos(err));
  2976. print_line("Deleting docs cache...");
  2977. if (FileAccess::exists(EditorHelp::get_cache_full_path())) {
  2978. DirAccess::remove_file_or_error(EditorHelp::get_cache_full_path());
  2979. }
  2980. return EXIT_SUCCESS;
  2981. }
  2982. // GDExtension API and interface.
  2983. {
  2984. if (dump_gdextension_interface) {
  2985. GDExtensionInterfaceDump::generate_gdextension_interface_file("gdextension_interface.h");
  2986. }
  2987. if (dump_extension_api) {
  2988. Engine::get_singleton()->set_editor_hint(true); // "extension_api.json" should always contains editor singletons.
  2989. GDExtensionAPIDump::generate_extension_json_file("extension_api.json", include_docs_in_extension_api_dump);
  2990. }
  2991. if (dump_gdextension_interface || dump_extension_api) {
  2992. return EXIT_SUCCESS;
  2993. }
  2994. if (validate_extension_api) {
  2995. Engine::get_singleton()->set_editor_hint(true); // "extension_api.json" should always contains editor singletons.
  2996. bool valid = GDExtensionAPIDump::validate_extension_json_file(validate_extension_api_file) == OK;
  2997. return valid ? EXIT_SUCCESS : EXIT_FAILURE;
  2998. }
  2999. }
  3000. #ifndef DISABLE_DEPRECATED
  3001. if (converting_project) {
  3002. int ret = ProjectConverter3To4(converter_max_kb_file, converter_max_line_length).convert();
  3003. return ret ? EXIT_SUCCESS : EXIT_FAILURE;
  3004. }
  3005. if (validating_converting_project) {
  3006. bool ret = ProjectConverter3To4(converter_max_kb_file, converter_max_line_length).validate_conversion();
  3007. return ret ? EXIT_SUCCESS : EXIT_FAILURE;
  3008. }
  3009. #endif // DISABLE_DEPRECATED
  3010. #endif // TOOLS_ENABLED
  3011. if (script.is_empty() && game_path.is_empty() && String(GLOBAL_GET("application/run/main_scene")) != "") {
  3012. game_path = GLOBAL_GET("application/run/main_scene");
  3013. }
  3014. #ifdef TOOLS_ENABLED
  3015. if (!editor && !project_manager && !cmdline_tool && script.is_empty() && game_path.is_empty()) {
  3016. // If we end up here, it means we didn't manage to detect what we want to run.
  3017. // Let's throw an error gently. The code leading to this is pretty brittle so
  3018. // this might end up triggered by valid usage, in which case we'll have to
  3019. // fine-tune further.
  3020. OS::get_singleton()->alert("Couldn't detect whether to run the editor, the project manager or a specific project. Aborting.");
  3021. ERR_FAIL_V_MSG(EXIT_FAILURE, "Couldn't detect whether to run the editor, the project manager or a specific project. Aborting.");
  3022. }
  3023. #endif
  3024. MainLoop *main_loop = nullptr;
  3025. if (editor) {
  3026. main_loop = memnew(SceneTree);
  3027. }
  3028. if (main_loop_type.is_empty()) {
  3029. main_loop_type = GLOBAL_GET("application/run/main_loop_type");
  3030. }
  3031. if (!script.is_empty()) {
  3032. Ref<Script> script_res = ResourceLoader::load(script);
  3033. ERR_FAIL_COND_V_MSG(script_res.is_null(), EXIT_FAILURE, "Can't load script: " + script);
  3034. if (check_only) {
  3035. return script_res->is_valid() ? EXIT_SUCCESS : EXIT_FAILURE;
  3036. }
  3037. if (script_res->can_instantiate()) {
  3038. StringName instance_type = script_res->get_instance_base_type();
  3039. Object *obj = ClassDB::instantiate(instance_type);
  3040. MainLoop *script_loop = Object::cast_to<MainLoop>(obj);
  3041. if (!script_loop) {
  3042. if (obj) {
  3043. memdelete(obj);
  3044. }
  3045. OS::get_singleton()->alert(vformat("Can't load the script \"%s\" as it doesn't inherit from SceneTree or MainLoop.", script));
  3046. ERR_FAIL_V_MSG(EXIT_FAILURE, vformat("Can't load the script \"%s\" as it doesn't inherit from SceneTree or MainLoop.", script));
  3047. }
  3048. script_loop->set_script(script_res);
  3049. main_loop = script_loop;
  3050. } else {
  3051. return EXIT_FAILURE;
  3052. }
  3053. } else { // Not based on script path.
  3054. if (!editor && !ClassDB::class_exists(main_loop_type) && ScriptServer::is_global_class(main_loop_type)) {
  3055. String script_path = ScriptServer::get_global_class_path(main_loop_type);
  3056. Ref<Script> script_res = ResourceLoader::load(script_path);
  3057. if (script_res.is_null()) {
  3058. OS::get_singleton()->alert("Error: Could not load MainLoop script type: " + main_loop_type);
  3059. ERR_FAIL_V_MSG(EXIT_FAILURE, vformat("Could not load global class %s.", main_loop_type));
  3060. }
  3061. StringName script_base = script_res->get_instance_base_type();
  3062. Object *obj = ClassDB::instantiate(script_base);
  3063. MainLoop *script_loop = Object::cast_to<MainLoop>(obj);
  3064. if (!script_loop) {
  3065. if (obj) {
  3066. memdelete(obj);
  3067. }
  3068. OS::get_singleton()->alert("Error: Invalid MainLoop script base type: " + script_base);
  3069. ERR_FAIL_V_MSG(EXIT_FAILURE, vformat("The global class %s does not inherit from SceneTree or MainLoop.", main_loop_type));
  3070. }
  3071. script_loop->set_script(script_res);
  3072. main_loop = script_loop;
  3073. }
  3074. }
  3075. if (!main_loop && main_loop_type.is_empty()) {
  3076. main_loop_type = "SceneTree";
  3077. }
  3078. if (!main_loop) {
  3079. if (!ClassDB::class_exists(main_loop_type)) {
  3080. OS::get_singleton()->alert("Error: MainLoop type doesn't exist: " + main_loop_type);
  3081. return EXIT_FAILURE;
  3082. } else {
  3083. Object *ml = ClassDB::instantiate(main_loop_type);
  3084. ERR_FAIL_NULL_V_MSG(ml, EXIT_FAILURE, "Can't instance MainLoop type.");
  3085. main_loop = Object::cast_to<MainLoop>(ml);
  3086. if (!main_loop) {
  3087. memdelete(ml);
  3088. ERR_FAIL_V_MSG(EXIT_FAILURE, "Invalid MainLoop type.");
  3089. }
  3090. }
  3091. }
  3092. OS::get_singleton()->set_main_loop(main_loop);
  3093. SceneTree *sml = Object::cast_to<SceneTree>(main_loop);
  3094. if (sml) {
  3095. #ifdef DEBUG_ENABLED
  3096. if (debug_collisions) {
  3097. sml->set_debug_collisions_hint(true);
  3098. }
  3099. if (debug_paths) {
  3100. sml->set_debug_paths_hint(true);
  3101. }
  3102. if (debug_navigation) {
  3103. sml->set_debug_navigation_hint(true);
  3104. NavigationServer3D::get_singleton()->set_debug_navigation_enabled(true);
  3105. }
  3106. if (debug_avoidance) {
  3107. NavigationServer3D::get_singleton()->set_debug_avoidance_enabled(true);
  3108. }
  3109. if (debug_navigation || debug_avoidance) {
  3110. NavigationServer3D::get_singleton()->set_active(true);
  3111. NavigationServer3D::get_singleton()->set_debug_enabled(true);
  3112. }
  3113. if (debug_canvas_item_redraw) {
  3114. RenderingServer::get_singleton()->canvas_item_set_debug_redraw(true);
  3115. }
  3116. #endif
  3117. if (single_threaded_scene) {
  3118. sml->set_disable_node_threading(true);
  3119. }
  3120. bool embed_subwindows = GLOBAL_GET("display/window/subwindows/embed_subwindows");
  3121. if (single_window || (!project_manager && !editor && embed_subwindows) || !DisplayServer::get_singleton()->has_feature(DisplayServer::Feature::FEATURE_SUBWINDOWS)) {
  3122. sml->get_root()->set_embedding_subwindows(true);
  3123. }
  3124. ResourceLoader::add_custom_loaders();
  3125. ResourceSaver::add_custom_savers();
  3126. if (!project_manager && !editor) { // game
  3127. if (!game_path.is_empty() || !script.is_empty()) {
  3128. //autoload
  3129. OS::get_singleton()->benchmark_begin_measure("Startup", "Load Autoloads");
  3130. HashMap<StringName, ProjectSettings::AutoloadInfo> autoloads = ProjectSettings::get_singleton()->get_autoload_list();
  3131. //first pass, add the constants so they exist before any script is loaded
  3132. for (const KeyValue<StringName, ProjectSettings::AutoloadInfo> &E : autoloads) {
  3133. const ProjectSettings::AutoloadInfo &info = E.value;
  3134. if (info.is_singleton) {
  3135. for (int i = 0; i < ScriptServer::get_language_count(); i++) {
  3136. ScriptServer::get_language(i)->add_global_constant(info.name, Variant());
  3137. }
  3138. }
  3139. }
  3140. //second pass, load into global constants
  3141. List<Node *> to_add;
  3142. for (const KeyValue<StringName, ProjectSettings::AutoloadInfo> &E : autoloads) {
  3143. const ProjectSettings::AutoloadInfo &info = E.value;
  3144. Node *n = nullptr;
  3145. if (ResourceLoader::get_resource_type(info.path) == "PackedScene") {
  3146. // Cache the scene reference before loading it (for cyclic references)
  3147. Ref<PackedScene> scn;
  3148. scn.instantiate();
  3149. scn->set_path(info.path);
  3150. scn->reload_from_file();
  3151. ERR_CONTINUE_MSG(!scn.is_valid(), vformat("Failed to instantiate an autoload, can't load from path: %s.", info.path));
  3152. if (scn.is_valid()) {
  3153. n = scn->instantiate();
  3154. }
  3155. } else {
  3156. Ref<Resource> res = ResourceLoader::load(info.path);
  3157. ERR_CONTINUE_MSG(res.is_null(), vformat("Failed to instantiate an autoload, can't load from path: %s.", info.path));
  3158. Ref<Script> script_res = res;
  3159. if (script_res.is_valid()) {
  3160. StringName ibt = script_res->get_instance_base_type();
  3161. bool valid_type = ClassDB::is_parent_class(ibt, "Node");
  3162. ERR_CONTINUE_MSG(!valid_type, vformat("Failed to instantiate an autoload, script '%s' does not inherit from 'Node'.", info.path));
  3163. Object *obj = ClassDB::instantiate(ibt);
  3164. ERR_CONTINUE_MSG(!obj, vformat("Failed to instantiate an autoload, cannot instantiate '%s'.", ibt));
  3165. n = Object::cast_to<Node>(obj);
  3166. n->set_script(script_res);
  3167. }
  3168. }
  3169. ERR_CONTINUE_MSG(!n, vformat("Failed to instantiate an autoload, path is not pointing to a scene or a script: %s.", info.path));
  3170. n->set_name(info.name);
  3171. //defer so references are all valid on _ready()
  3172. to_add.push_back(n);
  3173. if (info.is_singleton) {
  3174. for (int i = 0; i < ScriptServer::get_language_count(); i++) {
  3175. ScriptServer::get_language(i)->add_global_constant(info.name, n);
  3176. }
  3177. }
  3178. }
  3179. for (Node *E : to_add) {
  3180. sml->get_root()->add_child(E);
  3181. }
  3182. OS::get_singleton()->benchmark_end_measure("Startup", "Load Autoloads");
  3183. }
  3184. }
  3185. #ifdef TOOLS_ENABLED
  3186. #ifdef MODULE_GDSCRIPT_ENABLED
  3187. if (!doc_tool_path.is_empty() && !gdscript_docs_path.is_empty()) {
  3188. DocTools docs;
  3189. Error err;
  3190. Vector<String> paths = get_files_with_extension(gdscript_docs_path, "gd");
  3191. ERR_FAIL_COND_V_MSG(paths.is_empty(), EXIT_FAILURE, "Couldn't find any GDScript files under the given directory: " + gdscript_docs_path);
  3192. for (const String &path : paths) {
  3193. Ref<GDScript> gdscript = ResourceLoader::load(path);
  3194. for (const DocData::ClassDoc &class_doc : gdscript->get_documentation()) {
  3195. docs.add_doc(class_doc);
  3196. }
  3197. }
  3198. if (doc_tool_implicit_cwd) {
  3199. doc_tool_path = "./docs";
  3200. }
  3201. Ref<DirAccess> da = DirAccess::create_for_path(doc_tool_path);
  3202. err = da->make_dir_recursive(doc_tool_path);
  3203. ERR_FAIL_COND_V_MSG(err != OK, EXIT_FAILURE, "Error: Can't create GDScript docs directory: " + doc_tool_path + ": " + itos(err));
  3204. HashMap<String, String> doc_data_classes;
  3205. err = docs.save_classes(doc_tool_path, doc_data_classes, false);
  3206. ERR_FAIL_COND_V_MSG(err != OK, EXIT_FAILURE, "Error saving GDScript docs:" + itos(err));
  3207. return EXIT_SUCCESS;
  3208. }
  3209. #endif // MODULE_GDSCRIPT_ENABLED
  3210. EditorNode *editor_node = nullptr;
  3211. if (editor) {
  3212. OS::get_singleton()->benchmark_begin_measure("Startup", "Editor");
  3213. editor_node = memnew(EditorNode);
  3214. sml->get_root()->add_child(editor_node);
  3215. if (!_export_preset.is_empty()) {
  3216. editor_node->export_preset(_export_preset, positional_arg, export_debug, export_pack_only, install_android_build_template);
  3217. game_path = ""; // Do not load anything.
  3218. }
  3219. OS::get_singleton()->benchmark_end_measure("Startup", "Editor");
  3220. }
  3221. #endif
  3222. sml->set_auto_accept_quit(GLOBAL_GET("application/config/auto_accept_quit"));
  3223. sml->set_quit_on_go_back(GLOBAL_GET("application/config/quit_on_go_back"));
  3224. if (!editor && !project_manager) {
  3225. //standard helpers that can be changed from main config
  3226. String stretch_mode = GLOBAL_GET("display/window/stretch/mode");
  3227. String stretch_aspect = GLOBAL_GET("display/window/stretch/aspect");
  3228. Size2i stretch_size = Size2i(GLOBAL_GET("display/window/size/viewport_width"),
  3229. GLOBAL_GET("display/window/size/viewport_height"));
  3230. real_t stretch_scale = GLOBAL_GET("display/window/stretch/scale");
  3231. String stretch_scale_mode = GLOBAL_GET("display/window/stretch/scale_mode");
  3232. Window::ContentScaleMode cs_sm = Window::CONTENT_SCALE_MODE_DISABLED;
  3233. if (stretch_mode == "canvas_items") {
  3234. cs_sm = Window::CONTENT_SCALE_MODE_CANVAS_ITEMS;
  3235. } else if (stretch_mode == "viewport") {
  3236. cs_sm = Window::CONTENT_SCALE_MODE_VIEWPORT;
  3237. }
  3238. Window::ContentScaleAspect cs_aspect = Window::CONTENT_SCALE_ASPECT_IGNORE;
  3239. if (stretch_aspect == "keep") {
  3240. cs_aspect = Window::CONTENT_SCALE_ASPECT_KEEP;
  3241. } else if (stretch_aspect == "keep_width") {
  3242. cs_aspect = Window::CONTENT_SCALE_ASPECT_KEEP_WIDTH;
  3243. } else if (stretch_aspect == "keep_height") {
  3244. cs_aspect = Window::CONTENT_SCALE_ASPECT_KEEP_HEIGHT;
  3245. } else if (stretch_aspect == "expand") {
  3246. cs_aspect = Window::CONTENT_SCALE_ASPECT_EXPAND;
  3247. }
  3248. Window::ContentScaleStretch cs_stretch = Window::CONTENT_SCALE_STRETCH_FRACTIONAL;
  3249. if (stretch_scale_mode == "integer") {
  3250. cs_stretch = Window::CONTENT_SCALE_STRETCH_INTEGER;
  3251. }
  3252. sml->get_root()->set_content_scale_mode(cs_sm);
  3253. sml->get_root()->set_content_scale_aspect(cs_aspect);
  3254. sml->get_root()->set_content_scale_stretch(cs_stretch);
  3255. sml->get_root()->set_content_scale_size(stretch_size);
  3256. sml->get_root()->set_content_scale_factor(stretch_scale);
  3257. sml->set_auto_accept_quit(GLOBAL_GET("application/config/auto_accept_quit"));
  3258. sml->set_quit_on_go_back(GLOBAL_GET("application/config/quit_on_go_back"));
  3259. String appname = GLOBAL_GET("application/config/name");
  3260. appname = TranslationServer::get_singleton()->translate(appname);
  3261. #ifdef DEBUG_ENABLED
  3262. // Append a suffix to the window title to denote that the project is running
  3263. // from a debug build (including the editor). Since this results in lower performance,
  3264. // this should be clearly presented to the user.
  3265. DisplayServer::get_singleton()->window_set_title(vformat("%s (DEBUG)", appname));
  3266. #else
  3267. DisplayServer::get_singleton()->window_set_title(appname);
  3268. #endif
  3269. bool snap_controls = GLOBAL_GET("gui/common/snap_controls_to_pixels");
  3270. sml->get_root()->set_snap_controls_to_pixels(snap_controls);
  3271. bool font_oversampling = GLOBAL_GET("gui/fonts/dynamic_fonts/use_oversampling");
  3272. sml->get_root()->set_use_font_oversampling(font_oversampling);
  3273. int texture_filter = GLOBAL_GET("rendering/textures/canvas_textures/default_texture_filter");
  3274. int texture_repeat = GLOBAL_GET("rendering/textures/canvas_textures/default_texture_repeat");
  3275. sml->get_root()->set_default_canvas_item_texture_filter(
  3276. Viewport::DefaultCanvasItemTextureFilter(texture_filter));
  3277. sml->get_root()->set_default_canvas_item_texture_repeat(
  3278. Viewport::DefaultCanvasItemTextureRepeat(texture_repeat));
  3279. }
  3280. #ifdef TOOLS_ENABLED
  3281. if (editor) {
  3282. bool editor_embed_subwindows = EditorSettings::get_singleton()->get_setting(
  3283. "interface/editor/single_window_mode");
  3284. if (editor_embed_subwindows) {
  3285. sml->get_root()->set_embedding_subwindows(true);
  3286. }
  3287. }
  3288. #endif
  3289. String local_game_path;
  3290. if (!game_path.is_empty() && !project_manager) {
  3291. local_game_path = game_path.replace("\\", "/");
  3292. if (!local_game_path.begins_with("res://")) {
  3293. bool absolute =
  3294. (local_game_path.size() > 1) && (local_game_path[0] == '/' || local_game_path[1] == ':');
  3295. if (!absolute) {
  3296. if (ProjectSettings::get_singleton()->is_using_datapack()) {
  3297. local_game_path = "res://" + local_game_path;
  3298. } else {
  3299. int sep = local_game_path.rfind("/");
  3300. if (sep == -1) {
  3301. Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
  3302. ERR_FAIL_COND_V(da.is_null(), EXIT_FAILURE);
  3303. local_game_path = da->get_current_dir().path_join(local_game_path);
  3304. } else {
  3305. Ref<DirAccess> da = DirAccess::open(local_game_path.substr(0, sep));
  3306. if (da.is_valid()) {
  3307. local_game_path = da->get_current_dir().path_join(
  3308. local_game_path.substr(sep + 1, local_game_path.length()));
  3309. }
  3310. }
  3311. }
  3312. }
  3313. }
  3314. local_game_path = ProjectSettings::get_singleton()->localize_path(local_game_path);
  3315. #ifdef TOOLS_ENABLED
  3316. if (editor) {
  3317. if (game_path != String(GLOBAL_GET("application/run/main_scene")) || !editor_node->has_scenes_in_session()) {
  3318. Error serr = editor_node->load_scene(local_game_path);
  3319. if (serr != OK) {
  3320. ERR_PRINT("Failed to load scene");
  3321. }
  3322. }
  3323. if (!debug_server_uri.is_empty()) {
  3324. EditorDebuggerNode::get_singleton()->start(debug_server_uri);
  3325. EditorDebuggerNode::get_singleton()->set_keep_open(true);
  3326. }
  3327. }
  3328. #endif
  3329. }
  3330. if (!project_manager && !editor) { // game
  3331. OS::get_singleton()->benchmark_begin_measure("Startup", "Load Game");
  3332. // Load SSL Certificates from Project Settings (or builtin).
  3333. Crypto::load_default_certificates(GLOBAL_GET("network/tls/certificate_bundle_override"));
  3334. if (!game_path.is_empty()) {
  3335. Node *scene = nullptr;
  3336. Ref<PackedScene> scenedata = ResourceLoader::load(local_game_path);
  3337. if (scenedata.is_valid()) {
  3338. scene = scenedata->instantiate();
  3339. }
  3340. ERR_FAIL_NULL_V_MSG(scene, EXIT_FAILURE, "Failed loading scene: " + local_game_path + ".");
  3341. sml->add_current_scene(scene);
  3342. #ifdef MACOS_ENABLED
  3343. String mac_icon_path = GLOBAL_GET("application/config/macos_native_icon");
  3344. if (DisplayServer::get_singleton()->has_feature(DisplayServer::FEATURE_NATIVE_ICON) && !mac_icon_path.is_empty()) {
  3345. DisplayServer::get_singleton()->set_native_icon(mac_icon_path);
  3346. has_icon = true;
  3347. }
  3348. #endif
  3349. #ifdef WINDOWS_ENABLED
  3350. String win_icon_path = GLOBAL_GET("application/config/windows_native_icon");
  3351. if (DisplayServer::get_singleton()->has_feature(DisplayServer::FEATURE_NATIVE_ICON) && !win_icon_path.is_empty()) {
  3352. DisplayServer::get_singleton()->set_native_icon(win_icon_path);
  3353. has_icon = true;
  3354. }
  3355. #endif
  3356. String icon_path = GLOBAL_GET("application/config/icon");
  3357. if (DisplayServer::get_singleton()->has_feature(DisplayServer::FEATURE_ICON) && !icon_path.is_empty() && !has_icon) {
  3358. Ref<Image> icon;
  3359. icon.instantiate();
  3360. if (ImageLoader::load_image(icon_path, icon) == OK) {
  3361. DisplayServer::get_singleton()->set_icon(icon);
  3362. has_icon = true;
  3363. }
  3364. }
  3365. }
  3366. OS::get_singleton()->benchmark_end_measure("Startup", "Load Game");
  3367. }
  3368. #ifdef TOOLS_ENABLED
  3369. if (project_manager) {
  3370. OS::get_singleton()->benchmark_begin_measure("Startup", "Project Manager");
  3371. Engine::get_singleton()->set_editor_hint(true);
  3372. ProjectManager *pmanager = memnew(ProjectManager);
  3373. ProgressDialog *progress_dialog = memnew(ProgressDialog);
  3374. pmanager->add_child(progress_dialog);
  3375. sml->get_root()->add_child(pmanager);
  3376. OS::get_singleton()->benchmark_end_measure("Startup", "Project Manager");
  3377. }
  3378. if (project_manager || editor) {
  3379. // Load SSL Certificates from Editor Settings (or builtin)
  3380. Crypto::load_default_certificates(
  3381. EditorSettings::get_singleton()->get_setting("network/tls/editor_tls_certificates").operator String());
  3382. }
  3383. #endif
  3384. }
  3385. if (DisplayServer::get_singleton()->has_feature(DisplayServer::FEATURE_ICON) && !has_icon && OS::get_singleton()->get_bundle_icon_path().is_empty()) {
  3386. Ref<Image> icon = memnew(Image(app_icon_png));
  3387. DisplayServer::get_singleton()->set_icon(icon);
  3388. }
  3389. if (movie_writer) {
  3390. movie_writer->begin(DisplayServer::get_singleton()->window_get_size(), fixed_fps, Engine::get_singleton()->get_write_movie_path());
  3391. }
  3392. if (minimum_time_msec) {
  3393. uint64_t minimum_time = 1000 * minimum_time_msec;
  3394. uint64_t elapsed_time = OS::get_singleton()->get_ticks_usec();
  3395. if (elapsed_time < minimum_time) {
  3396. OS::get_singleton()->delay_usec(minimum_time - elapsed_time);
  3397. }
  3398. }
  3399. OS::get_singleton()->benchmark_end_measure("Startup", "Main::Start");
  3400. OS::get_singleton()->benchmark_dump();
  3401. return EXIT_SUCCESS;
  3402. }
  3403. /* Main iteration
  3404. *
  3405. * This is the iteration of the engine's game loop, advancing the state of physics,
  3406. * rendering and audio.
  3407. * It's called directly by the platform's OS::run method, where the loop is created
  3408. * and monitored.
  3409. *
  3410. * The OS implementation can impact its draw step with the Main::force_redraw() method.
  3411. */
  3412. uint64_t Main::last_ticks = 0;
  3413. uint32_t Main::frames = 0;
  3414. uint32_t Main::hide_print_fps_attempts = 3;
  3415. uint32_t Main::frame = 0;
  3416. bool Main::force_redraw_requested = false;
  3417. int Main::iterating = 0;
  3418. bool Main::is_iterating() {
  3419. return iterating > 0;
  3420. }
  3421. // For performance metrics.
  3422. static uint64_t physics_process_max = 0;
  3423. static uint64_t process_max = 0;
  3424. static uint64_t navigation_process_max = 0;
  3425. // Return false means iterating further, returning true means `OS::run`
  3426. // will terminate the program. In case of failure, the OS exit code needs
  3427. // to be set explicitly here (defaults to EXIT_SUCCESS).
  3428. bool Main::iteration() {
  3429. iterating++;
  3430. const uint64_t ticks = OS::get_singleton()->get_ticks_usec();
  3431. Engine::get_singleton()->_frame_ticks = ticks;
  3432. main_timer_sync.set_cpu_ticks_usec(ticks);
  3433. main_timer_sync.set_fixed_fps(fixed_fps);
  3434. const uint64_t ticks_elapsed = ticks - last_ticks;
  3435. const int physics_ticks_per_second = Engine::get_singleton()->get_physics_ticks_per_second();
  3436. const double physics_step = 1.0 / physics_ticks_per_second;
  3437. const double time_scale = Engine::get_singleton()->get_time_scale();
  3438. MainFrameTime advance = main_timer_sync.advance(physics_step, physics_ticks_per_second);
  3439. double process_step = advance.process_step;
  3440. double scaled_step = process_step * time_scale;
  3441. Engine::get_singleton()->_process_step = process_step;
  3442. Engine::get_singleton()->_physics_interpolation_fraction = advance.interpolation_fraction;
  3443. uint64_t physics_process_ticks = 0;
  3444. uint64_t process_ticks = 0;
  3445. uint64_t navigation_process_ticks = 0;
  3446. frame += ticks_elapsed;
  3447. last_ticks = ticks;
  3448. const int max_physics_steps = Engine::get_singleton()->get_max_physics_steps_per_frame();
  3449. if (fixed_fps == -1 && advance.physics_steps > max_physics_steps) {
  3450. process_step -= (advance.physics_steps - max_physics_steps) * physics_step;
  3451. advance.physics_steps = max_physics_steps;
  3452. }
  3453. bool exit = false;
  3454. // process all our active interfaces
  3455. #ifndef _3D_DISABLED
  3456. XRServer::get_singleton()->_process();
  3457. #endif // _3D_DISABLED
  3458. NavigationServer2D::get_singleton()->sync();
  3459. NavigationServer3D::get_singleton()->sync();
  3460. for (int iters = 0; iters < advance.physics_steps; ++iters) {
  3461. if (Input::get_singleton()->is_agile_input_event_flushing()) {
  3462. Input::get_singleton()->flush_buffered_events();
  3463. }
  3464. Engine::get_singleton()->_in_physics = true;
  3465. Engine::get_singleton()->_physics_frames++;
  3466. uint64_t physics_begin = OS::get_singleton()->get_ticks_usec();
  3467. #ifndef _3D_DISABLED
  3468. PhysicsServer3D::get_singleton()->sync();
  3469. PhysicsServer3D::get_singleton()->flush_queries();
  3470. #endif // _3D_DISABLED
  3471. // Prepare the fixed timestep interpolated nodes BEFORE they are updated
  3472. // by the physics server, otherwise the current and previous transforms
  3473. // may be the same, and no interpolation takes place.
  3474. OS::get_singleton()->get_main_loop()->iteration_prepare();
  3475. PhysicsServer2D::get_singleton()->sync();
  3476. PhysicsServer2D::get_singleton()->flush_queries();
  3477. if (OS::get_singleton()->get_main_loop()->physics_process(physics_step * time_scale)) {
  3478. #ifndef _3D_DISABLED
  3479. PhysicsServer3D::get_singleton()->end_sync();
  3480. #endif // _3D_DISABLED
  3481. PhysicsServer2D::get_singleton()->end_sync();
  3482. exit = true;
  3483. break;
  3484. }
  3485. uint64_t navigation_begin = OS::get_singleton()->get_ticks_usec();
  3486. NavigationServer3D::get_singleton()->process(physics_step * time_scale);
  3487. navigation_process_ticks = MAX(navigation_process_ticks, OS::get_singleton()->get_ticks_usec() - navigation_begin); // keep the largest one for reference
  3488. navigation_process_max = MAX(OS::get_singleton()->get_ticks_usec() - navigation_begin, navigation_process_max);
  3489. message_queue->flush();
  3490. #ifndef _3D_DISABLED
  3491. PhysicsServer3D::get_singleton()->end_sync();
  3492. PhysicsServer3D::get_singleton()->step(physics_step * time_scale);
  3493. #endif // _3D_DISABLED
  3494. PhysicsServer2D::get_singleton()->end_sync();
  3495. PhysicsServer2D::get_singleton()->step(physics_step * time_scale);
  3496. message_queue->flush();
  3497. physics_process_ticks = MAX(physics_process_ticks, OS::get_singleton()->get_ticks_usec() - physics_begin); // keep the largest one for reference
  3498. physics_process_max = MAX(OS::get_singleton()->get_ticks_usec() - physics_begin, physics_process_max);
  3499. Engine::get_singleton()->_in_physics = false;
  3500. }
  3501. if (Input::get_singleton()->is_agile_input_event_flushing()) {
  3502. Input::get_singleton()->flush_buffered_events();
  3503. }
  3504. uint64_t process_begin = OS::get_singleton()->get_ticks_usec();
  3505. if (OS::get_singleton()->get_main_loop()->process(process_step * time_scale)) {
  3506. exit = true;
  3507. }
  3508. message_queue->flush();
  3509. RenderingServer::get_singleton()->sync(); //sync if still drawing from previous frames.
  3510. if ((DisplayServer::get_singleton()->can_any_window_draw() || DisplayServer::get_singleton()->has_additional_outputs()) &&
  3511. RenderingServer::get_singleton()->is_render_loop_enabled()) {
  3512. if ((!force_redraw_requested) && OS::get_singleton()->is_in_low_processor_usage_mode()) {
  3513. if (RenderingServer::get_singleton()->has_changed()) {
  3514. RenderingServer::get_singleton()->draw(true, scaled_step); // flush visual commands
  3515. Engine::get_singleton()->increment_frames_drawn();
  3516. }
  3517. } else {
  3518. RenderingServer::get_singleton()->draw(true, scaled_step); // flush visual commands
  3519. Engine::get_singleton()->increment_frames_drawn();
  3520. force_redraw_requested = false;
  3521. }
  3522. }
  3523. process_ticks = OS::get_singleton()->get_ticks_usec() - process_begin;
  3524. process_max = MAX(process_ticks, process_max);
  3525. uint64_t frame_time = OS::get_singleton()->get_ticks_usec() - ticks;
  3526. for (int i = 0; i < ScriptServer::get_language_count(); i++) {
  3527. ScriptServer::get_language(i)->frame();
  3528. }
  3529. AudioServer::get_singleton()->update();
  3530. if (EngineDebugger::is_active()) {
  3531. EngineDebugger::get_singleton()->iteration(frame_time, process_ticks, physics_process_ticks, physics_step);
  3532. }
  3533. frames++;
  3534. Engine::get_singleton()->_process_frames++;
  3535. if (frame > 1000000) {
  3536. // Wait a few seconds before printing FPS, as FPS reporting just after the engine has started is inaccurate.
  3537. if (hide_print_fps_attempts == 0) {
  3538. if (editor || project_manager) {
  3539. if (print_fps) {
  3540. print_line(vformat("Editor FPS: %d (%s mspf)", frames, rtos(1000.0 / frames).pad_decimals(2)));
  3541. }
  3542. } else if (print_fps || GLOBAL_GET("debug/settings/stdout/print_fps")) {
  3543. print_line(vformat("Project FPS: %d (%s mspf)", frames, rtos(1000.0 / frames).pad_decimals(2)));
  3544. }
  3545. } else {
  3546. hide_print_fps_attempts--;
  3547. }
  3548. Engine::get_singleton()->_fps = frames;
  3549. performance->set_process_time(USEC_TO_SEC(process_max));
  3550. performance->set_physics_process_time(USEC_TO_SEC(physics_process_max));
  3551. performance->set_navigation_process_time(USEC_TO_SEC(navigation_process_max));
  3552. process_max = 0;
  3553. physics_process_max = 0;
  3554. navigation_process_max = 0;
  3555. frame %= 1000000;
  3556. frames = 0;
  3557. }
  3558. iterating--;
  3559. if (movie_writer) {
  3560. movie_writer->add_frame();
  3561. }
  3562. #ifdef TOOLS_ENABLED
  3563. bool quit_after_timeout = false;
  3564. #endif
  3565. if ((quit_after > 0) && (Engine::get_singleton()->_process_frames >= quit_after)) {
  3566. #ifdef TOOLS_ENABLED
  3567. quit_after_timeout = true;
  3568. #endif
  3569. exit = true;
  3570. }
  3571. #ifdef TOOLS_ENABLED
  3572. if (wait_for_import && EditorFileSystem::get_singleton() && EditorFileSystem::get_singleton()->doing_first_scan()) {
  3573. exit = false;
  3574. }
  3575. #endif
  3576. if (fixed_fps != -1) {
  3577. return exit;
  3578. }
  3579. OS::get_singleton()->add_frame_delay(DisplayServer::get_singleton()->window_can_draw());
  3580. #ifdef TOOLS_ENABLED
  3581. if (auto_build_solutions) {
  3582. auto_build_solutions = false;
  3583. // Only relevant when running the editor.
  3584. if (!editor) {
  3585. OS::get_singleton()->set_exit_code(EXIT_FAILURE);
  3586. ERR_FAIL_V_MSG(true,
  3587. "Command line option --build-solutions was passed, but no project is being edited. Aborting.");
  3588. }
  3589. if (!EditorNode::get_singleton()->call_build()) {
  3590. OS::get_singleton()->set_exit_code(EXIT_FAILURE);
  3591. ERR_FAIL_V_MSG(true,
  3592. "Command line option --build-solutions was passed, but the build callback failed. Aborting.");
  3593. }
  3594. }
  3595. #endif
  3596. #ifdef TOOLS_ENABLED
  3597. if (exit && quit_after_timeout && EditorNode::get_singleton()) {
  3598. EditorNode::get_singleton()->unload_editor_addons();
  3599. }
  3600. #endif
  3601. return exit;
  3602. }
  3603. void Main::force_redraw() {
  3604. force_redraw_requested = true;
  3605. }
  3606. /* Engine deinitialization
  3607. *
  3608. * Responsible for freeing all the memory allocated by previous setup steps,
  3609. * so that the engine closes cleanly without leaking memory or crashing.
  3610. * The order matters as some of those steps are linked with each other.
  3611. */
  3612. void Main::cleanup(bool p_force) {
  3613. OS::get_singleton()->benchmark_begin_measure("Shutdown", "Main::Cleanup");
  3614. if (!p_force) {
  3615. ERR_FAIL_COND(!_start_success);
  3616. }
  3617. #ifdef DEBUG_ENABLED
  3618. if (input) {
  3619. input->flush_frame_parsed_events();
  3620. }
  3621. #endif
  3622. for (int i = 0; i < TextServerManager::get_singleton()->get_interface_count(); i++) {
  3623. TextServerManager::get_singleton()->get_interface(i)->cleanup();
  3624. }
  3625. if (movie_writer) {
  3626. movie_writer->end();
  3627. }
  3628. ResourceLoader::clear_thread_load_tasks();
  3629. ResourceLoader::remove_custom_loaders();
  3630. ResourceSaver::remove_custom_savers();
  3631. PropertyListHelper::clear_base_helpers();
  3632. // Flush before uninitializing the scene, but delete the MessageQueue as late as possible.
  3633. message_queue->flush();
  3634. OS::get_singleton()->delete_main_loop();
  3635. OS::get_singleton()->_cmdline.clear();
  3636. OS::get_singleton()->_user_args.clear();
  3637. OS::get_singleton()->_execpath = "";
  3638. OS::get_singleton()->_local_clipboard = "";
  3639. ResourceLoader::clear_translation_remaps();
  3640. ResourceLoader::clear_path_remaps();
  3641. ScriptServer::finish_languages();
  3642. // Sync pending commands that may have been queued from a different thread during ScriptServer finalization
  3643. RenderingServer::get_singleton()->sync();
  3644. //clear global shader variables before scene and other graphics stuff are deinitialized.
  3645. rendering_server->global_shader_parameters_clear();
  3646. #ifndef _3D_DISABLED
  3647. if (xr_server) {
  3648. // Now that we're unregistering properly in plugins we need to keep access to xr_server for a little longer
  3649. // We do however unset our primary interface
  3650. xr_server->set_primary_interface(Ref<XRInterface>());
  3651. }
  3652. #endif // _3D_DISABLED
  3653. #ifdef TOOLS_ENABLED
  3654. GDExtensionManager::get_singleton()->deinitialize_extensions(GDExtension::INITIALIZATION_LEVEL_EDITOR);
  3655. uninitialize_modules(MODULE_INITIALIZATION_LEVEL_EDITOR);
  3656. unregister_editor_types();
  3657. #endif
  3658. ImageLoader::cleanup();
  3659. GDExtensionManager::get_singleton()->deinitialize_extensions(GDExtension::INITIALIZATION_LEVEL_SCENE);
  3660. uninitialize_modules(MODULE_INITIALIZATION_LEVEL_SCENE);
  3661. unregister_platform_apis();
  3662. unregister_driver_types();
  3663. unregister_scene_types();
  3664. finalize_theme_db();
  3665. // Before deinitializing server extensions, finalize servers which may be loaded as extensions.
  3666. finalize_navigation_server();
  3667. finalize_physics();
  3668. GDExtensionManager::get_singleton()->deinitialize_extensions(GDExtension::INITIALIZATION_LEVEL_SERVERS);
  3669. uninitialize_modules(MODULE_INITIALIZATION_LEVEL_SERVERS);
  3670. unregister_server_types();
  3671. EngineDebugger::deinitialize();
  3672. #ifndef _3D_DISABLED
  3673. if (xr_server) {
  3674. memdelete(xr_server);
  3675. }
  3676. #endif // _3D_DISABLED
  3677. if (audio_server) {
  3678. audio_server->finish();
  3679. memdelete(audio_server);
  3680. }
  3681. if (camera_server) {
  3682. memdelete(camera_server);
  3683. }
  3684. OS::get_singleton()->finalize();
  3685. finalize_display();
  3686. if (input) {
  3687. memdelete(input);
  3688. }
  3689. if (packed_data) {
  3690. memdelete(packed_data);
  3691. }
  3692. if (performance) {
  3693. memdelete(performance);
  3694. }
  3695. if (input_map) {
  3696. memdelete(input_map);
  3697. }
  3698. if (translation_server) {
  3699. memdelete(translation_server);
  3700. }
  3701. if (tsman) {
  3702. memdelete(tsman);
  3703. }
  3704. #ifndef _3D_DISABLED
  3705. if (physics_server_3d_manager) {
  3706. memdelete(physics_server_3d_manager);
  3707. }
  3708. #endif // _3D_DISABLED
  3709. if (physics_server_2d_manager) {
  3710. memdelete(physics_server_2d_manager);
  3711. }
  3712. if (globals) {
  3713. memdelete(globals);
  3714. }
  3715. if (OS::get_singleton()->is_restart_on_exit_set()) {
  3716. //attempt to restart with arguments
  3717. List<String> args = OS::get_singleton()->get_restart_on_exit_arguments();
  3718. OS::get_singleton()->create_instance(args);
  3719. OS::get_singleton()->set_restart_on_exit(false, List<String>()); //clear list (uses memory)
  3720. }
  3721. // Now should be safe to delete MessageQueue (famous last words).
  3722. message_queue->flush();
  3723. memdelete(message_queue);
  3724. #if defined(STEAMAPI_ENABLED)
  3725. if (steam_tracker) {
  3726. memdelete(steam_tracker);
  3727. }
  3728. #endif
  3729. unregister_core_driver_types();
  3730. unregister_core_extensions();
  3731. uninitialize_modules(MODULE_INITIALIZATION_LEVEL_CORE);
  3732. if (engine) {
  3733. memdelete(engine);
  3734. }
  3735. unregister_core_types();
  3736. OS::get_singleton()->benchmark_end_measure("Shutdown", "Main::Cleanup");
  3737. OS::get_singleton()->benchmark_dump();
  3738. OS::get_singleton()->finalize_core();
  3739. }