main.cpp 171 KB

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