main.cpp 139 KB

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