main.cpp 149 KB

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