main.cpp 133 KB

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