main.cpp 133 KB

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