main.cpp 101 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900
  1. /*************************************************************************/
  2. /* main.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
  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_string_names.h"
  33. #include "core/crypto/crypto.h"
  34. #include "core/debugger/engine_debugger.h"
  35. #include "core/extension/extension_api_dump.h"
  36. #include "core/input/input.h"
  37. #include "core/input/input_map.h"
  38. #include "core/io/dir_access.h"
  39. #include "core/io/file_access_network.h"
  40. #include "core/io/file_access_pack.h"
  41. #include "core/io/file_access_zip.h"
  42. #include "core/io/image_loader.h"
  43. #include "core/io/ip.h"
  44. #include "core/io/resource_loader.h"
  45. #include "core/object/message_queue.h"
  46. #include "core/os/os.h"
  47. #include "core/os/time.h"
  48. #include "core/register_core_types.h"
  49. #include "core/string/translation.h"
  50. #include "core/version.h"
  51. #include "core/version_hash.gen.h"
  52. #include "drivers/register_driver_types.h"
  53. #include "main/app_icon.gen.h"
  54. #include "main/main_timer_sync.h"
  55. #include "main/performance.h"
  56. #include "main/splash.gen.h"
  57. #include "modules/register_module_types.h"
  58. #include "platform/register_platform_apis.h"
  59. #include "scene/main/scene_tree.h"
  60. #include "scene/main/window.h"
  61. #include "scene/register_scene_types.h"
  62. #include "scene/resources/packed_scene.h"
  63. #include "servers/audio_server.h"
  64. #include "servers/camera_server.h"
  65. #include "servers/display_server.h"
  66. #include "servers/navigation_server_2d.h"
  67. #include "servers/navigation_server_3d.h"
  68. #include "servers/physics_server_2d.h"
  69. #include "servers/physics_server_3d.h"
  70. #include "servers/register_server_types.h"
  71. #include "servers/rendering/rendering_server_default.h"
  72. #include "servers/text_server.h"
  73. #include "servers/xr_server.h"
  74. #ifdef TESTS_ENABLED
  75. #include "tests/test_main.h"
  76. #endif
  77. #ifdef TOOLS_ENABLED
  78. #include "editor/doc_data_class_path.gen.h"
  79. #include "editor/doc_tools.h"
  80. #include "editor/editor_node.h"
  81. #include "editor/editor_settings.h"
  82. #include "editor/editor_translation.h"
  83. #include "editor/progress_dialog.h"
  84. #include "editor/project_manager.h"
  85. #ifndef NO_EDITOR_SPLASH
  86. #include "main/splash_editor.gen.h"
  87. #endif
  88. #endif
  89. #include "modules/modules_enabled.gen.h" // For mono.
  90. /* Static members */
  91. // Singletons
  92. // Initialized in setup()
  93. static Engine *engine = nullptr;
  94. static ProjectSettings *globals = nullptr;
  95. static Input *input = nullptr;
  96. static InputMap *input_map = nullptr;
  97. static TranslationServer *translation_server = nullptr;
  98. static Performance *performance = nullptr;
  99. static PackedData *packed_data = nullptr;
  100. static Time *time_singleton = nullptr;
  101. #ifdef MINIZIP_ENABLED
  102. static ZipArchive *zip_packed_data = nullptr;
  103. #endif
  104. static FileAccessNetworkClient *file_access_network_client = nullptr;
  105. static MessageQueue *message_queue = nullptr;
  106. // Initialized in setup2()
  107. static AudioServer *audio_server = nullptr;
  108. static DisplayServer *display_server = nullptr;
  109. static RenderingServer *rendering_server = nullptr;
  110. static CameraServer *camera_server = nullptr;
  111. static XRServer *xr_server = nullptr;
  112. static TextServerManager *tsman = nullptr;
  113. static PhysicsServer3D *physics_server = nullptr;
  114. static PhysicsServer2D *physics_2d_server = nullptr;
  115. static NavigationServer3D *navigation_server = nullptr;
  116. static NavigationServer2D *navigation_2d_server = nullptr;
  117. // We error out if setup2() doesn't turn this true
  118. static bool _start_success = false;
  119. // Drivers
  120. String tablet_driver = "";
  121. String text_driver = "";
  122. String rendering_driver = "";
  123. static int text_driver_idx = -1;
  124. static int display_driver_idx = -1;
  125. static int audio_driver_idx = -1;
  126. // Engine config/tools
  127. static bool editor = false;
  128. static bool project_manager = false;
  129. static bool cmdline_tool = false;
  130. static String locale;
  131. static bool show_help = false;
  132. static bool auto_quit = false;
  133. static OS::ProcessID allow_focus_steal_pid = 0;
  134. #ifdef TOOLS_ENABLED
  135. static bool auto_build_solutions = false;
  136. static String debug_server_uri;
  137. #endif
  138. // Display
  139. static DisplayServer::WindowMode window_mode = DisplayServer::WINDOW_MODE_WINDOWED;
  140. static DisplayServer::ScreenOrientation window_orientation = DisplayServer::SCREEN_LANDSCAPE;
  141. static DisplayServer::VSyncMode window_vsync_mode = DisplayServer::VSYNC_ENABLED;
  142. static uint32_t window_flags = 0;
  143. static Size2i window_size = Size2i(1024, 600);
  144. static int init_screen = -1;
  145. static bool init_fullscreen = false;
  146. static bool init_maximized = false;
  147. static bool init_windowed = false;
  148. static bool init_always_on_top = false;
  149. static bool init_use_custom_pos = false;
  150. static Vector2 init_custom_pos;
  151. static bool force_lowdpi = false;
  152. // Debug
  153. static bool use_debug_profiler = false;
  154. #ifdef DEBUG_ENABLED
  155. static bool debug_collisions = false;
  156. static bool debug_navigation = false;
  157. #endif
  158. static int frame_delay = 0;
  159. static bool disable_render_loop = false;
  160. static int fixed_fps = -1;
  161. static bool print_fps = false;
  162. #ifdef TOOLS_ENABLED
  163. static bool dump_extension_api = false;
  164. #endif
  165. bool profile_gpu = false;
  166. /* Helper methods */
  167. // Used by Mono module, should likely be registered in Engine singleton instead
  168. // FIXME: This is also not 100% accurate, `project_manager` is only true when it was requested,
  169. // but not if e.g. we fail to load and project and fallback to the manager.
  170. bool Main::is_project_manager() {
  171. return project_manager;
  172. }
  173. bool Main::is_cmdline_tool() {
  174. return cmdline_tool;
  175. }
  176. static String unescape_cmdline(const String &p_str) {
  177. return p_str.replace("%20", " ");
  178. }
  179. static String get_full_version_string() {
  180. String hash = String(VERSION_HASH);
  181. if (hash.length() != 0) {
  182. hash = "." + hash.left(9);
  183. }
  184. return String(VERSION_FULL_BUILD) + hash;
  185. }
  186. // FIXME: Could maybe be moved to PhysicsServer3DManager and PhysicsServer2DManager directly
  187. // to have less code in main.cpp.
  188. void initialize_physics() {
  189. /// 3D Physics Server
  190. physics_server = PhysicsServer3DManager::new_server(
  191. ProjectSettings::get_singleton()->get(PhysicsServer3DManager::setting_property_name));
  192. if (!physics_server) {
  193. // Physics server not found, Use the default physics
  194. physics_server = PhysicsServer3DManager::new_default_server();
  195. }
  196. ERR_FAIL_COND(!physics_server);
  197. physics_server->init();
  198. /// 2D Physics server
  199. physics_2d_server = PhysicsServer2DManager::new_server(
  200. ProjectSettings::get_singleton()->get(PhysicsServer2DManager::setting_property_name));
  201. if (!physics_2d_server) {
  202. // Physics server not found, Use the default physics
  203. physics_2d_server = PhysicsServer2DManager::new_default_server();
  204. }
  205. ERR_FAIL_COND(!physics_2d_server);
  206. physics_2d_server->init();
  207. }
  208. void finalize_physics() {
  209. physics_server->finish();
  210. memdelete(physics_server);
  211. physics_2d_server->finish();
  212. memdelete(physics_2d_server);
  213. }
  214. void finalize_display() {
  215. rendering_server->finish();
  216. memdelete(rendering_server);
  217. memdelete(display_server);
  218. }
  219. void initialize_navigation_server() {
  220. ERR_FAIL_COND(navigation_server != nullptr);
  221. navigation_server = NavigationServer3DManager::new_default_server();
  222. navigation_2d_server = memnew(NavigationServer2D);
  223. }
  224. void finalize_navigation_server() {
  225. memdelete(navigation_server);
  226. navigation_server = nullptr;
  227. memdelete(navigation_2d_server);
  228. navigation_2d_server = nullptr;
  229. }
  230. //#define DEBUG_INIT
  231. #ifdef DEBUG_INIT
  232. #define MAIN_PRINT(m_txt) print_line(m_txt)
  233. #else
  234. #define MAIN_PRINT(m_txt)
  235. #endif
  236. void Main::print_help(const char *p_binary) {
  237. print_line(String(VERSION_NAME) + " v" + get_full_version_string() + " - " + String(VERSION_WEBSITE));
  238. OS::get_singleton()->print("Free and open source software under the terms of the MIT license.\n");
  239. OS::get_singleton()->print("(c) 2007-2021 Juan Linietsky, Ariel Manzur.\n");
  240. OS::get_singleton()->print("(c) 2014-2021 Godot Engine contributors.\n");
  241. OS::get_singleton()->print("\n");
  242. OS::get_singleton()->print("Usage: %s [options] [path to scene or 'project.godot' file]\n", p_binary);
  243. OS::get_singleton()->print("\n");
  244. OS::get_singleton()->print("General options:\n");
  245. OS::get_singleton()->print(" -h, --help Display this help message.\n");
  246. OS::get_singleton()->print(" --version Display the version string.\n");
  247. OS::get_singleton()->print(" -v, --verbose Use verbose stdout mode.\n");
  248. OS::get_singleton()->print(" --quiet Quiet mode, silences stdout messages. Errors are still displayed.\n");
  249. OS::get_singleton()->print("\n");
  250. OS::get_singleton()->print("Run options:\n");
  251. #ifdef TOOLS_ENABLED
  252. OS::get_singleton()->print(" -e, --editor Start the editor instead of running the scene.\n");
  253. OS::get_singleton()->print(" -p, --project-manager Start the project manager, even if a project is auto-detected.\n");
  254. 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");
  255. #endif
  256. OS::get_singleton()->print(" -q, --quit Quit after the first iteration.\n");
  257. OS::get_singleton()->print(" -l, --language <locale> Use a specific locale (<locale> being a two-letter code).\n");
  258. OS::get_singleton()->print(" --path <directory> Path to a project (<directory> must contain a 'project.godot' file).\n");
  259. OS::get_singleton()->print(" -u, --upwards Scan folders upwards for project.godot file.\n");
  260. OS::get_singleton()->print(" --main-pack <file> Path to a pack (.pck) file to load.\n");
  261. OS::get_singleton()->print(" --render-thread <mode> Render thread mode ('unsafe', 'safe', 'separate').\n");
  262. OS::get_singleton()->print(" --remote-fs <address> Remote filesystem (<host/IP>[:<port>] address).\n");
  263. OS::get_singleton()->print(" --remote-fs-password <password> Password for remote filesystem.\n");
  264. OS::get_singleton()->print(" --audio-driver <driver> Audio driver [");
  265. for (int i = 0; i < AudioDriverManager::get_driver_count(); i++) {
  266. if (i > 0) {
  267. OS::get_singleton()->print(", ");
  268. }
  269. OS::get_singleton()->print("'%s'", AudioDriverManager::get_driver(i)->get_name());
  270. }
  271. OS::get_singleton()->print("].\n");
  272. OS::get_singleton()->print(" --display-driver <driver> Display driver (and rendering driver) [");
  273. for (int i = 0; i < DisplayServer::get_create_function_count(); i++) {
  274. if (i > 0) {
  275. OS::get_singleton()->print(", ");
  276. }
  277. OS::get_singleton()->print("'%s' (", DisplayServer::get_create_function_name(i));
  278. Vector<String> rd = DisplayServer::get_create_function_rendering_drivers(i);
  279. for (int j = 0; j < rd.size(); j++) {
  280. if (j > 0) {
  281. OS::get_singleton()->print(", ");
  282. }
  283. OS::get_singleton()->print("'%s'", rd[j].utf8().get_data());
  284. }
  285. OS::get_singleton()->print(")");
  286. }
  287. OS::get_singleton()->print("].\n");
  288. OS::get_singleton()->print(" --rendering-driver <driver> Rendering driver (depends on display driver).\n");
  289. OS::get_singleton()->print(" --text-driver <driver> Text driver (Fonts, BiDi, shaping)\n");
  290. OS::get_singleton()->print(" --headless Enable headless mode (--display-driver headless --audio-driver Dummy). Useful for servers and with --script.\n");
  291. OS::get_singleton()->print("\n");
  292. OS::get_singleton()->print("Display options:\n");
  293. OS::get_singleton()->print(" -f, --fullscreen Request fullscreen mode.\n");
  294. OS::get_singleton()->print(" -m, --maximized Request a maximized window.\n");
  295. OS::get_singleton()->print(" -w, --windowed Request windowed mode.\n");
  296. OS::get_singleton()->print(" -t, --always-on-top Request an always-on-top window.\n");
  297. OS::get_singleton()->print(" --resolution <W>x<H> Request window resolution.\n");
  298. OS::get_singleton()->print(" --position <X>,<Y> Request window position.\n");
  299. OS::get_singleton()->print(" --low-dpi Force low-DPI mode (macOS and Windows only).\n");
  300. OS::get_singleton()->print(" --single-window Use a single window (no separate subwindows).\n");
  301. OS::get_singleton()->print(" --tablet-driver Pen tablet input driver.\n");
  302. OS::get_singleton()->print("\n");
  303. OS::get_singleton()->print("Debug options:\n");
  304. OS::get_singleton()->print(" -d, --debug Debug (local stdout debugger).\n");
  305. OS::get_singleton()->print(" -b, --breakpoints Breakpoint list as source::line comma-separated pairs, no spaces (use %%20 instead).\n");
  306. OS::get_singleton()->print(" --profiling Enable profiling in the script debugger.\n");
  307. OS::get_singleton()->print(" --vk-layers Enable Vulkan Validation layers for debugging.\n");
  308. #ifdef DEBUG_ENABLED
  309. OS::get_singleton()->print(" --gpu-abort Abort on GPU errors (usually validation layer errors), may help see the problem if your system freezes.\n");
  310. #endif
  311. OS::get_singleton()->print(" --remote-debug <uri> Remote debug (<protocol>://<host/IP>[:<port>], e.g. tcp://127.0.0.1:6007).\n");
  312. #if defined(DEBUG_ENABLED)
  313. OS::get_singleton()->print(" --debug-collisions Show collision shapes when running the scene.\n");
  314. OS::get_singleton()->print(" --debug-navigation Show navigation polygons when running the scene.\n");
  315. #endif
  316. OS::get_singleton()->print(" --frame-delay <ms> Simulate high CPU load (delay each frame by <ms> milliseconds).\n");
  317. OS::get_singleton()->print(" --time-scale <scale> Force time scale (higher values are faster, 1.0 is normal speed).\n");
  318. OS::get_singleton()->print(" --disable-render-loop Disable render loop so rendering only occurs when called explicitly from script.\n");
  319. OS::get_singleton()->print(" --disable-crash-handler Disable crash handler when supported by the platform code.\n");
  320. OS::get_singleton()->print(" --fixed-fps <fps> Force a fixed number of frames per second. This setting disables real-time synchronization.\n");
  321. OS::get_singleton()->print(" --print-fps Print the frames per second to the stdout.\n");
  322. OS::get_singleton()->print(" --profile-gpu Show a simple profile of the tasks that took more time during frame rendering.\n");
  323. OS::get_singleton()->print("\n");
  324. OS::get_singleton()->print("Standalone tools:\n");
  325. OS::get_singleton()->print(" -s, --script <script> Run a script.\n");
  326. OS::get_singleton()->print(" --check-only Only parse for errors and quit (use with --script).\n");
  327. #ifdef TOOLS_ENABLED
  328. OS::get_singleton()->print(" --export <preset> <path> Export the project using the given preset and matching release template. The preset name should match one defined in export_presets.cfg.\n");
  329. 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'). The target directory should exist.\n");
  330. OS::get_singleton()->print(" --export-debug <preset> <path> Same as --export, but using the debug template.\n");
  331. OS::get_singleton()->print(" --export-pack <preset> <path> Same as --export, but only export the game pack for the given preset. The <path> extension determines whether it will be in PCK or ZIP format.\n");
  332. 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");
  333. OS::get_singleton()->print(" --no-docbase Disallow dumping the base types (used with --doctool).\n");
  334. 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");
  335. 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");
  336. #ifdef DEBUG_METHODS_ENABLED
  337. // TODO: Should be removed together with nativescript eventually.
  338. OS::get_singleton()->print(" --gdnative-generate-json-api <path> Generate JSON dump of the Godot API for GDNative bindings and save it on the file specified in <path>.\n");
  339. OS::get_singleton()->print(" --gdnative-generate-json-builtin-api <path> Generate JSON dump of the Godot API of the builtin Variant types and utility functions for GDNative bindings and save it on the file specified in <path>.\n");
  340. #endif
  341. #ifdef TESTS_ENABLED
  342. OS::get_singleton()->print(" --test [--help] Run unit tests. Use --test --help for more information.\n");
  343. #endif
  344. #endif
  345. OS::get_singleton()->print("\n");
  346. }
  347. #ifdef TESTS_ENABLED
  348. // The order is the same as in `Main::setup()`, only core and some editor types
  349. // are initialized here. This also combines `Main::setup2()` initialization.
  350. Error Main::test_setup() {
  351. OS::get_singleton()->initialize();
  352. engine = memnew(Engine);
  353. register_core_types();
  354. register_core_driver_types();
  355. packed_data = memnew(PackedData);
  356. globals = memnew(ProjectSettings);
  357. GLOBAL_DEF("debug/settings/crash_handler/message",
  358. String("Please include this when reporting the bug on https://github.com/godotengine/godot/issues"));
  359. GLOBAL_DEF_RST("rendering/occlusion_culling/bvh_build_quality", 2);
  360. translation_server = memnew(TranslationServer);
  361. tsman = memnew(TextServerManager);
  362. register_core_extensions();
  363. // From `Main::setup2()`.
  364. preregister_module_types();
  365. preregister_server_types();
  366. register_core_singletons();
  367. register_server_types();
  368. translation_server->setup(); //register translations, load them, etc.
  369. if (!locale.is_empty()) {
  370. translation_server->set_locale(locale);
  371. }
  372. translation_server->load_translations();
  373. ResourceLoader::load_translation_remaps(); //load remaps for resources
  374. ResourceLoader::load_path_remaps();
  375. register_scene_types();
  376. #ifdef TOOLS_ENABLED
  377. ClassDB::set_current_api(ClassDB::API_EDITOR);
  378. EditorNode::register_editor_types();
  379. ClassDB::set_current_api(ClassDB::API_CORE);
  380. #endif
  381. register_platform_apis();
  382. register_module_types();
  383. register_driver_types();
  384. // Theme needs modules to be initialized so that sub-resources can be loaded.
  385. initialize_theme();
  386. ERR_FAIL_COND_V(TextServerManager::get_singleton()->get_interface_count() == 0, ERR_CANT_CREATE);
  387. TextServerManager::get_singleton()->set_primary_interface(TextServerManager::get_singleton()->get_interface(0));
  388. ClassDB::set_current_api(ClassDB::API_NONE);
  389. _start_success = true;
  390. return OK;
  391. }
  392. // The order is the same as in `Main::cleanup()`.
  393. void Main::test_cleanup() {
  394. ERR_FAIL_COND(!_start_success);
  395. EngineDebugger::deinitialize();
  396. ResourceLoader::remove_custom_loaders();
  397. ResourceSaver::remove_custom_savers();
  398. unregister_driver_types();
  399. #ifdef TOOLS_ENABLED
  400. EditorNode::unregister_editor_types();
  401. #endif
  402. unregister_module_types();
  403. unregister_platform_apis();
  404. unregister_scene_types();
  405. unregister_server_types();
  406. OS::get_singleton()->finalize();
  407. if (translation_server) {
  408. memdelete(translation_server);
  409. }
  410. if (tsman) {
  411. memdelete(tsman);
  412. }
  413. if (globals) {
  414. memdelete(globals);
  415. }
  416. if (packed_data) {
  417. memdelete(packed_data);
  418. }
  419. if (engine) {
  420. memdelete(engine);
  421. }
  422. unregister_core_driver_types();
  423. unregister_core_types();
  424. OS::get_singleton()->finalize_core();
  425. }
  426. #endif
  427. int Main::test_entrypoint(int argc, char *argv[], bool &tests_need_run) {
  428. #ifdef TESTS_ENABLED
  429. for (int x = 0; x < argc; x++) {
  430. if ((strncmp(argv[x], "--test", 6) == 0) && (strlen(argv[x]) == 6)) {
  431. tests_need_run = true;
  432. // TODO: need to come up with different test contexts.
  433. // Not every test requires high-level functionality like `ClassDB`.
  434. test_setup();
  435. int status = test_main(argc, argv);
  436. test_cleanup();
  437. return status;
  438. }
  439. }
  440. #endif
  441. tests_need_run = false;
  442. return 0;
  443. }
  444. /* Engine initialization
  445. *
  446. * Consists of several methods that are called by each platform's specific main(argc, argv).
  447. * To fully understand engine init, one should therefore start from the platform's main and
  448. * see how it calls into the Main class' methods.
  449. *
  450. * The initialization is typically done in 3 steps (with the setup2 step triggered either
  451. * automatically by setup, or manually in the platform's main).
  452. *
  453. * - setup(execpath, argc, argv, p_second_phase) is the main entry point for all platforms,
  454. * responsible for the initialization of all low level singletons and core types, and parsing
  455. * command line arguments to configure things accordingly.
  456. * If p_second_phase is true, it will chain into setup2() (default behaviour). This is
  457. * disabled on some platforms (Android, iOS, UWP) which trigger the second step in their
  458. * own time.
  459. *
  460. * - setup2(p_main_tid_override) registers high level servers and singletons, displays the
  461. * boot splash, then registers higher level types (scene, editor, etc.).
  462. *
  463. * - start() is the last step and that's where command line tools can run, or the main loop
  464. * can be created eventually and the project settings put into action. That's also where
  465. * the editor node is created, if relevant.
  466. * start() does it own argument parsing for a subset of the command line arguments described
  467. * in help, it's a bit messy and should be globalized with the setup() parsing somehow.
  468. */
  469. Error Main::setup(const char *execpath, int argc, char *argv[], bool p_second_phase) {
  470. OS::get_singleton()->initialize();
  471. engine = memnew(Engine);
  472. MAIN_PRINT("Main: Initialize CORE");
  473. register_core_types();
  474. register_core_driver_types();
  475. MAIN_PRINT("Main: Initialize Globals");
  476. input_map = memnew(InputMap);
  477. time_singleton = memnew(Time);
  478. globals = memnew(ProjectSettings);
  479. register_core_settings(); //here globals are present
  480. translation_server = memnew(TranslationServer);
  481. performance = memnew(Performance);
  482. GDREGISTER_CLASS(Performance);
  483. engine->add_singleton(Engine::Singleton("Performance", performance));
  484. // Only flush stdout in debug builds by default, as spamming `print()` will
  485. // decrease performance if this is enabled.
  486. GLOBAL_DEF_RST("application/run/flush_stdout_on_print", false);
  487. GLOBAL_DEF_RST("application/run/flush_stdout_on_print.debug", true);
  488. GLOBAL_DEF("debug/settings/crash_handler/message",
  489. String("Please include this when reporting the bug on https://github.com/godotengine/godot/issues"));
  490. MAIN_PRINT("Main: Parse CMDLine");
  491. /* argument parsing and main creation */
  492. List<String> args;
  493. List<String> main_args;
  494. for (int i = 0; i < argc; i++) {
  495. args.push_back(String::utf8(argv[i]));
  496. }
  497. List<String>::Element *I = args.front();
  498. while (I) {
  499. I->get() = unescape_cmdline(I->get().strip_edges());
  500. I = I->next();
  501. }
  502. I = args.front();
  503. String display_driver = "";
  504. String audio_driver = "";
  505. String project_path = ".";
  506. bool upwards = false;
  507. String debug_uri = "";
  508. bool skip_breakpoints = false;
  509. String main_pack;
  510. bool quiet_stdout = false;
  511. int rtm = -1;
  512. String remotefs;
  513. String remotefs_pass;
  514. Vector<String> breakpoints;
  515. bool use_custom_res = true;
  516. bool force_res = false;
  517. #ifdef TOOLS_ENABLED
  518. bool found_project = false;
  519. #endif
  520. packed_data = PackedData::get_singleton();
  521. if (!packed_data) {
  522. packed_data = memnew(PackedData);
  523. }
  524. #ifdef MINIZIP_ENABLED
  525. //XXX: always get_singleton() == 0x0
  526. zip_packed_data = ZipArchive::get_singleton();
  527. //TODO: remove this temporary fix
  528. if (!zip_packed_data) {
  529. zip_packed_data = memnew(ZipArchive);
  530. }
  531. packed_data->add_pack_source(zip_packed_data);
  532. #endif
  533. I = args.front();
  534. while (I) {
  535. #ifdef OSX_ENABLED
  536. // Ignore the process serial number argument passed by macOS Gatekeeper.
  537. // Otherwise, Godot would try to open a non-existent project on the first start and abort.
  538. if (I->get().begins_with("-psn_")) {
  539. I = I->next();
  540. continue;
  541. }
  542. #endif
  543. List<String>::Element *N = I->next();
  544. if (I->get() == "-h" || I->get() == "--help" || I->get() == "/?") { // display help
  545. show_help = true;
  546. goto error;
  547. } else if (I->get() == "--version") {
  548. print_line(get_full_version_string());
  549. goto error;
  550. } else if (I->get() == "-v" || I->get() == "--verbose") { // verbose output
  551. OS::get_singleton()->_verbose_stdout = true;
  552. } else if (I->get() == "--quiet") { // quieter output
  553. quiet_stdout = true;
  554. } else if (I->get() == "--audio-driver") { // audio driver
  555. if (I->next()) {
  556. audio_driver = I->next()->get();
  557. bool found = false;
  558. for (int i = 0; i < AudioDriverManager::get_driver_count(); i++) {
  559. if (audio_driver == AudioDriverManager::get_driver(i)->get_name()) {
  560. found = true;
  561. }
  562. }
  563. if (!found) {
  564. OS::get_singleton()->print("Unknown audio driver '%s', aborting.\nValid options are ",
  565. audio_driver.utf8().get_data());
  566. for (int i = 0; i < AudioDriverManager::get_driver_count(); i++) {
  567. if (i == AudioDriverManager::get_driver_count() - 1) {
  568. OS::get_singleton()->print(" and ");
  569. } else if (i != 0) {
  570. OS::get_singleton()->print(", ");
  571. }
  572. OS::get_singleton()->print("'%s'", AudioDriverManager::get_driver(i)->get_name());
  573. }
  574. OS::get_singleton()->print(".\n");
  575. goto error;
  576. }
  577. N = I->next()->next();
  578. } else {
  579. OS::get_singleton()->print("Missing audio driver argument, aborting.\n");
  580. goto error;
  581. }
  582. } else if (I->get() == "--text-driver") {
  583. if (I->next()) {
  584. text_driver = I->next()->get();
  585. N = I->next()->next();
  586. } else {
  587. OS::get_singleton()->print("Missing text driver argument, aborting.\n");
  588. goto error;
  589. }
  590. } else if (I->get() == "--display-driver") { // force video driver
  591. if (I->next()) {
  592. display_driver = I->next()->get();
  593. bool found = false;
  594. for (int i = 0; i < DisplayServer::get_create_function_count(); i++) {
  595. if (display_driver == DisplayServer::get_create_function_name(i)) {
  596. found = true;
  597. }
  598. }
  599. if (!found) {
  600. OS::get_singleton()->print("Unknown display driver '%s', aborting.\nValid options are ",
  601. display_driver.utf8().get_data());
  602. for (int i = 0; i < DisplayServer::get_create_function_count(); i++) {
  603. if (i == DisplayServer::get_create_function_count() - 1) {
  604. OS::get_singleton()->print(" and ");
  605. } else if (i != 0) {
  606. OS::get_singleton()->print(", ");
  607. }
  608. OS::get_singleton()->print("'%s'", DisplayServer::get_create_function_name(i));
  609. }
  610. OS::get_singleton()->print(".\n");
  611. goto error;
  612. }
  613. N = I->next()->next();
  614. } else {
  615. OS::get_singleton()->print("Missing display driver argument, aborting.\n");
  616. goto error;
  617. }
  618. } else if (I->get() == "--rendering-driver") {
  619. if (I->next()) {
  620. rendering_driver = I->next()->get();
  621. // as the rendering drivers available may depend on the display driver selected,
  622. // we can't do an exhaustive check here, but we can look through all the options in
  623. // all the display drivers for a match
  624. bool found = false;
  625. for (int i = 0; i < DisplayServer::get_create_function_count(); i++) {
  626. Vector<String> r_drivers = DisplayServer::get_create_function_rendering_drivers(i);
  627. for (int d = 0; d < r_drivers.size(); d++) {
  628. if (rendering_driver == r_drivers[d]) {
  629. found = true;
  630. break;
  631. }
  632. }
  633. }
  634. if (!found) {
  635. OS::get_singleton()->print("Unknown rendering driver '%s', aborting.\nValid options are ",
  636. rendering_driver.utf8().get_data());
  637. for (int i = 0; i < DisplayServer::get_create_function_count(); i++) {
  638. Vector<String> r_drivers = DisplayServer::get_create_function_rendering_drivers(i);
  639. for (int d = 0; d < r_drivers.size(); d++) {
  640. OS::get_singleton()->print("'%s', ", r_drivers[d].utf8().get_data());
  641. }
  642. }
  643. OS::get_singleton()->print(".\n");
  644. goto error;
  645. }
  646. N = I->next()->next();
  647. } else {
  648. OS::get_singleton()->print("Missing rendering driver argument, aborting.\n");
  649. goto error;
  650. }
  651. } else if (I->get() == "-f" || I->get() == "--fullscreen") { // force fullscreen
  652. init_fullscreen = true;
  653. } else if (I->get() == "-m" || I->get() == "--maximized") { // force maximized window
  654. init_maximized = true;
  655. window_mode = DisplayServer::WINDOW_MODE_MAXIMIZED;
  656. } else if (I->get() == "-w" || I->get() == "--windowed") { // force windowed window
  657. init_windowed = true;
  658. } else if (I->get() == "--vk-layers") {
  659. Engine::singleton->use_validation_layers = true;
  660. #ifdef DEBUG_ENABLED
  661. } else if (I->get() == "--gpu-abort") {
  662. Engine::singleton->abort_on_gpu_errors = true;
  663. #endif
  664. } else if (I->get() == "--tablet-driver") {
  665. if (I->next()) {
  666. tablet_driver = I->next()->get();
  667. N = I->next()->next();
  668. } else {
  669. OS::get_singleton()->print("Missing tablet driver argument, aborting.\n");
  670. goto error;
  671. }
  672. } else if (I->get() == "--single-window") { // force single window
  673. OS::get_singleton()->_single_window = true;
  674. } else if (I->get() == "-t" || I->get() == "--always-on-top") { // force always-on-top window
  675. init_always_on_top = true;
  676. } else if (I->get() == "--resolution") { // force resolution
  677. if (I->next()) {
  678. String vm = I->next()->get();
  679. if (vm.find("x") == -1) { // invalid parameter format
  680. OS::get_singleton()->print("Invalid resolution '%s', it should be e.g. '1280x720'.\n",
  681. vm.utf8().get_data());
  682. goto error;
  683. }
  684. int w = vm.get_slice("x", 0).to_int();
  685. int h = vm.get_slice("x", 1).to_int();
  686. if (w <= 0 || h <= 0) {
  687. OS::get_singleton()->print("Invalid resolution '%s', width and height must be above 0.\n",
  688. vm.utf8().get_data());
  689. goto error;
  690. }
  691. window_size.width = w;
  692. window_size.height = h;
  693. force_res = true;
  694. N = I->next()->next();
  695. } else {
  696. OS::get_singleton()->print("Missing resolution argument, aborting.\n");
  697. goto error;
  698. }
  699. } else if (I->get() == "--position") { // set window position
  700. if (I->next()) {
  701. String vm = I->next()->get();
  702. if (vm.find(",") == -1) { // invalid parameter format
  703. OS::get_singleton()->print("Invalid position '%s', it should be e.g. '80,128'.\n",
  704. vm.utf8().get_data());
  705. goto error;
  706. }
  707. int x = vm.get_slice(",", 0).to_int();
  708. int y = vm.get_slice(",", 1).to_int();
  709. init_custom_pos = Point2(x, y);
  710. init_use_custom_pos = true;
  711. N = I->next()->next();
  712. } else {
  713. OS::get_singleton()->print("Missing position argument, aborting.\n");
  714. goto error;
  715. }
  716. } else if (I->get() == "--low-dpi") { // force low DPI (macOS only)
  717. force_lowdpi = true;
  718. } else if (I->get() == "--headless") { // enable headless mode (no audio, no rendering).
  719. audio_driver = "Dummy";
  720. display_driver = "headless";
  721. } else if (I->get() == "--profiling") { // enable profiling
  722. use_debug_profiler = true;
  723. } else if (I->get() == "-l" || I->get() == "--language") { // language
  724. if (I->next()) {
  725. locale = I->next()->get();
  726. N = I->next()->next();
  727. } else {
  728. OS::get_singleton()->print("Missing language argument, aborting.\n");
  729. goto error;
  730. }
  731. } else if (I->get() == "--remote-fs") { // remote filesystem
  732. if (I->next()) {
  733. remotefs = I->next()->get();
  734. N = I->next()->next();
  735. } else {
  736. OS::get_singleton()->print("Missing remote filesystem address, aborting.\n");
  737. goto error;
  738. }
  739. } else if (I->get() == "--remote-fs-password") { // remote filesystem password
  740. if (I->next()) {
  741. remotefs_pass = I->next()->get();
  742. N = I->next()->next();
  743. } else {
  744. OS::get_singleton()->print("Missing remote filesystem password, aborting.\n");
  745. goto error;
  746. }
  747. } else if (I->get() == "--render-thread") { // render thread mode
  748. if (I->next()) {
  749. if (I->next()->get() == "safe") {
  750. rtm = OS::RENDER_THREAD_SAFE;
  751. } else if (I->next()->get() == "unsafe") {
  752. rtm = OS::RENDER_THREAD_UNSAFE;
  753. } else if (I->next()->get() == "separate") {
  754. rtm = OS::RENDER_SEPARATE_THREAD;
  755. }
  756. N = I->next()->next();
  757. } else {
  758. OS::get_singleton()->print("Missing render thread mode argument, aborting.\n");
  759. goto error;
  760. }
  761. #ifdef TOOLS_ENABLED
  762. } else if (I->get() == "-e" || I->get() == "--editor") { // starts editor
  763. editor = true;
  764. } else if (I->get() == "-p" || I->get() == "--project-manager") { // starts project manager
  765. project_manager = true;
  766. } else if (I->get() == "--debug-server") {
  767. if (I->next()) {
  768. debug_server_uri = I->next()->get();
  769. if (debug_server_uri.find("://") == -1) { // wrong address
  770. OS::get_singleton()->print("Invalid debug server uri. It should be of the form <protocol>://<bind_address>:<port>.\n");
  771. goto error;
  772. }
  773. N = I->next()->next();
  774. } else {
  775. OS::get_singleton()->print("Missing remote debug server uri, aborting.\n");
  776. goto error;
  777. }
  778. } else if (I->get() == "--build-solutions") { // Build the scripting solution such C#
  779. auto_build_solutions = true;
  780. editor = true;
  781. cmdline_tool = true;
  782. #ifdef DEBUG_METHODS_ENABLED
  783. } else if (I->get() == "--gdnative-generate-json-api" || I->get() == "--gdnative-generate-json-builtin-api") {
  784. // Register as an editor instance to use low-end fallback if relevant.
  785. editor = true;
  786. cmdline_tool = true;
  787. // We still pass it to the main arguments since the argument handling itself is not done in this function,
  788. // it's done in nativescript init code.
  789. main_args.push_back(I->get());
  790. #endif
  791. } else if (I->get() == "--dump-extension-api") {
  792. // Register as an editor instance to use low-end fallback if relevant.
  793. editor = true;
  794. cmdline_tool = true;
  795. dump_extension_api = true;
  796. print_line("Dumping Extension API");
  797. // Hack. Not needed but otherwise we end up detecting that this should
  798. // run the project instead of a cmdline tool.
  799. // Needs full refactoring to fix properly.
  800. main_args.push_back(I->get());
  801. } else if (I->get() == "--export" || I->get() == "--export-debug" ||
  802. I->get() == "--export-pack") { // Export project
  803. // Actually handling is done in start().
  804. editor = true;
  805. cmdline_tool = true;
  806. main_args.push_back(I->get());
  807. } else if (I->get() == "--doctool") {
  808. // Actually handling is done in start().
  809. cmdline_tool = true;
  810. main_args.push_back(I->get());
  811. #endif
  812. } else if (I->get() == "--path") { // set path of project to start or edit
  813. if (I->next()) {
  814. String p = I->next()->get();
  815. if (OS::get_singleton()->set_cwd(p) == OK) {
  816. //nothing
  817. } else {
  818. project_path = I->next()->get(); //use project_path instead
  819. }
  820. N = I->next()->next();
  821. } else {
  822. OS::get_singleton()->print("Missing relative or absolute path, aborting.\n");
  823. goto error;
  824. }
  825. } else if (I->get() == "-u" || I->get() == "--upwards") { // scan folders upwards
  826. upwards = true;
  827. } else if (I->get() == "-q" || I->get() == "--quit") { // Auto quit at the end of the first main loop iteration
  828. auto_quit = true;
  829. } else if (I->get().ends_with("project.godot")) {
  830. String path;
  831. String file = I->get();
  832. int sep = MAX(file.rfind("/"), file.rfind("\\"));
  833. if (sep == -1) {
  834. path = ".";
  835. } else {
  836. path = file.substr(0, sep);
  837. }
  838. if (OS::get_singleton()->set_cwd(path) == OK) {
  839. // path already specified, don't override
  840. } else {
  841. project_path = path;
  842. }
  843. #ifdef TOOLS_ENABLED
  844. editor = true;
  845. #endif
  846. } else if (I->get() == "-b" || I->get() == "--breakpoints") { // add breakpoints
  847. if (I->next()) {
  848. String bplist = I->next()->get();
  849. breakpoints = bplist.split(",");
  850. N = I->next()->next();
  851. } else {
  852. OS::get_singleton()->print("Missing list of breakpoints, aborting.\n");
  853. goto error;
  854. }
  855. } else if (I->get() == "--frame-delay") { // force frame delay
  856. if (I->next()) {
  857. frame_delay = I->next()->get().to_int();
  858. N = I->next()->next();
  859. } else {
  860. OS::get_singleton()->print("Missing frame delay argument, aborting.\n");
  861. goto error;
  862. }
  863. } else if (I->get() == "--time-scale") { // force time scale
  864. if (I->next()) {
  865. Engine::get_singleton()->set_time_scale(I->next()->get().to_float());
  866. N = I->next()->next();
  867. } else {
  868. OS::get_singleton()->print("Missing time scale argument, aborting.\n");
  869. goto error;
  870. }
  871. } else if (I->get() == "--main-pack") {
  872. if (I->next()) {
  873. main_pack = I->next()->get();
  874. N = I->next()->next();
  875. } else {
  876. OS::get_singleton()->print("Missing path to main pack file, aborting.\n");
  877. goto error;
  878. };
  879. } else if (I->get() == "-d" || I->get() == "--debug") {
  880. debug_uri = "local://";
  881. OS::get_singleton()->_debug_stdout = true;
  882. #if defined(DEBUG_ENABLED)
  883. } else if (I->get() == "--debug-collisions") {
  884. debug_collisions = true;
  885. } else if (I->get() == "--debug-navigation") {
  886. debug_navigation = true;
  887. } else if (I->get() == "--debug-stringnames") {
  888. StringName::set_debug_stringnames(true);
  889. #endif
  890. } else if (I->get() == "--remote-debug") {
  891. if (I->next()) {
  892. debug_uri = I->next()->get();
  893. if (debug_uri.find("://") == -1) { // wrong address
  894. OS::get_singleton()->print(
  895. "Invalid debug host address, it should be of the form <protocol>://<host/IP>:<port>.\n");
  896. goto error;
  897. }
  898. N = I->next()->next();
  899. } else {
  900. OS::get_singleton()->print("Missing remote debug host address, aborting.\n");
  901. goto error;
  902. }
  903. } else if (I->get() == "--allow_focus_steal_pid") { // not exposed to user
  904. if (I->next()) {
  905. allow_focus_steal_pid = I->next()->get().to_int();
  906. N = I->next()->next();
  907. } else {
  908. OS::get_singleton()->print("Missing editor PID argument, aborting.\n");
  909. goto error;
  910. }
  911. } else if (I->get() == "--disable-render-loop") {
  912. disable_render_loop = true;
  913. } else if (I->get() == "--fixed-fps") {
  914. if (I->next()) {
  915. fixed_fps = I->next()->get().to_int();
  916. N = I->next()->next();
  917. } else {
  918. OS::get_singleton()->print("Missing fixed-fps argument, aborting.\n");
  919. goto error;
  920. }
  921. } else if (I->get() == "--print-fps") {
  922. print_fps = true;
  923. } else if (I->get() == "--profile-gpu") {
  924. profile_gpu = true;
  925. } else if (I->get() == "--disable-crash-handler") {
  926. OS::get_singleton()->disable_crash_handler();
  927. } else if (I->get() == "--skip-breakpoints") {
  928. skip_breakpoints = true;
  929. } else {
  930. main_args.push_back(I->get());
  931. }
  932. I = N;
  933. }
  934. #ifdef TOOLS_ENABLED
  935. if (editor && project_manager) {
  936. OS::get_singleton()->print(
  937. "Error: Command line arguments implied opening both editor and project manager, which is not possible. Aborting.\n");
  938. goto error;
  939. }
  940. #endif
  941. // Network file system needs to be configured before globals, since globals are based on the
  942. // 'project.godot' file which will only be available through the network if this is enabled
  943. FileAccessNetwork::configure();
  944. if (!remotefs.is_empty()) {
  945. file_access_network_client = memnew(FileAccessNetworkClient);
  946. int port;
  947. if (remotefs.find(":") != -1) {
  948. port = remotefs.get_slicec(':', 1).to_int();
  949. remotefs = remotefs.get_slicec(':', 0);
  950. } else {
  951. port = 6010;
  952. }
  953. Error err = file_access_network_client->connect(remotefs, port, remotefs_pass);
  954. if (err) {
  955. OS::get_singleton()->printerr("Could not connect to remotefs: %s:%i.\n", remotefs.utf8().get_data(), port);
  956. goto error;
  957. }
  958. FileAccess::make_default<FileAccessNetwork>(FileAccess::ACCESS_RESOURCES);
  959. }
  960. if (globals->setup(project_path, main_pack, upwards, editor) == OK) {
  961. #ifdef TOOLS_ENABLED
  962. found_project = true;
  963. #endif
  964. } else {
  965. #ifdef TOOLS_ENABLED
  966. editor = false;
  967. #else
  968. 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";
  969. OS::get_singleton()->print("%s", error_msg.utf8().get_data());
  970. OS::get_singleton()->alert(error_msg);
  971. goto error;
  972. #endif
  973. }
  974. // Initialize user data dir.
  975. OS::get_singleton()->ensure_user_data_dir();
  976. ResourceUID::get_singleton()->load_from_cache(); // load UUIDs from cache.
  977. GLOBAL_DEF("memory/limits/multithreaded_server/rid_pool_prealloc", 60);
  978. ProjectSettings::get_singleton()->set_custom_property_info("memory/limits/multithreaded_server/rid_pool_prealloc",
  979. PropertyInfo(Variant::INT,
  980. "memory/limits/multithreaded_server/rid_pool_prealloc",
  981. PROPERTY_HINT_RANGE,
  982. "0,500,1")); // No negative and limit to 500 due to crashes
  983. GLOBAL_DEF("network/limits/debugger/max_chars_per_second", 32768);
  984. ProjectSettings::get_singleton()->set_custom_property_info("network/limits/debugger/max_chars_per_second",
  985. PropertyInfo(Variant::INT,
  986. "network/limits/debugger/max_chars_per_second",
  987. PROPERTY_HINT_RANGE,
  988. "0, 4096, 1, or_greater"));
  989. GLOBAL_DEF("network/limits/debugger/max_queued_messages", 2048);
  990. ProjectSettings::get_singleton()->set_custom_property_info("network/limits/debugger/max_queued_messages",
  991. PropertyInfo(Variant::INT,
  992. "network/limits/debugger/max_queued_messages",
  993. PROPERTY_HINT_RANGE,
  994. "0, 8192, 1, or_greater"));
  995. GLOBAL_DEF("network/limits/debugger/max_errors_per_second", 400);
  996. ProjectSettings::get_singleton()->set_custom_property_info("network/limits/debugger/max_errors_per_second",
  997. PropertyInfo(Variant::INT,
  998. "network/limits/debugger/max_errors_per_second",
  999. PROPERTY_HINT_RANGE,
  1000. "0, 200, 1, or_greater"));
  1001. GLOBAL_DEF("network/limits/debugger/max_warnings_per_second", 400);
  1002. ProjectSettings::get_singleton()->set_custom_property_info("network/limits/debugger/max_warnings_per_second",
  1003. PropertyInfo(Variant::INT,
  1004. "network/limits/debugger/max_warnings_per_second",
  1005. PROPERTY_HINT_RANGE,
  1006. "0, 200, 1, or_greater"));
  1007. EngineDebugger::initialize(debug_uri, skip_breakpoints, breakpoints);
  1008. #ifdef TOOLS_ENABLED
  1009. if (editor) {
  1010. packed_data->set_disabled(true);
  1011. globals->set_disable_feature_overrides(true);
  1012. }
  1013. #endif
  1014. #ifdef TOOLS_ENABLED
  1015. if (editor) {
  1016. Engine::get_singleton()->set_editor_hint(true);
  1017. main_args.push_back("--editor");
  1018. if (!init_windowed) {
  1019. init_maximized = true;
  1020. window_mode = DisplayServer::WINDOW_MODE_MAXIMIZED;
  1021. }
  1022. }
  1023. if (!project_manager && !editor) {
  1024. // If we didn't find a project, we fall back to the project manager.
  1025. project_manager = !found_project && !cmdline_tool;
  1026. }
  1027. #endif
  1028. GLOBAL_DEF("debug/file_logging/enable_file_logging", false);
  1029. // Only file logging by default on desktop platforms as logs can't be
  1030. // accessed easily on mobile/Web platforms (if at all).
  1031. // This also prevents logs from being created for the editor instance, as feature tags
  1032. // are disabled while in the editor (even if they should logically apply).
  1033. GLOBAL_DEF("debug/file_logging/enable_file_logging.pc", true);
  1034. GLOBAL_DEF("debug/file_logging/log_path", "user://logs/godot.log");
  1035. GLOBAL_DEF("debug/file_logging/max_log_files", 5);
  1036. ProjectSettings::get_singleton()->set_custom_property_info("debug/file_logging/max_log_files",
  1037. PropertyInfo(Variant::INT,
  1038. "debug/file_logging/max_log_files",
  1039. PROPERTY_HINT_RANGE,
  1040. "0,20,1,or_greater")); //no negative numbers
  1041. if (!project_manager && !editor && FileAccess::get_create_func(FileAccess::ACCESS_USERDATA) &&
  1042. GLOBAL_GET("debug/file_logging/enable_file_logging")) {
  1043. // Don't create logs for the project manager as they would be written to
  1044. // the current working directory, which is inconvenient.
  1045. String base_path = GLOBAL_GET("debug/file_logging/log_path");
  1046. int max_files = GLOBAL_GET("debug/file_logging/max_log_files");
  1047. OS::get_singleton()->add_logger(memnew(RotatedFileLogger(base_path, max_files)));
  1048. }
  1049. if (main_args.size() == 0 && String(GLOBAL_GET("application/run/main_scene")) == "") {
  1050. #ifdef TOOLS_ENABLED
  1051. if (!editor && !project_manager) {
  1052. #endif
  1053. const String error_msg = "Error: Can't run project: no main scene defined in the project.\n";
  1054. OS::get_singleton()->print("%s", error_msg.utf8().get_data());
  1055. OS::get_singleton()->alert(error_msg);
  1056. goto error;
  1057. #ifdef TOOLS_ENABLED
  1058. }
  1059. #endif
  1060. }
  1061. if (editor || project_manager) {
  1062. Engine::get_singleton()->set_editor_hint(true);
  1063. use_custom_res = false;
  1064. input_map->load_default(); //keys for editor
  1065. } else {
  1066. input_map->load_from_project_settings(); //keys for game
  1067. }
  1068. if (bool(ProjectSettings::get_singleton()->get("application/run/disable_stdout"))) {
  1069. quiet_stdout = true;
  1070. }
  1071. if (bool(ProjectSettings::get_singleton()->get("application/run/disable_stderr"))) {
  1072. _print_error_enabled = false;
  1073. };
  1074. if (quiet_stdout) {
  1075. _print_line_enabled = false;
  1076. }
  1077. Logger::set_flush_stdout_on_print(ProjectSettings::get_singleton()->get("application/run/flush_stdout_on_print"));
  1078. OS::get_singleton()->set_cmdline(execpath, main_args);
  1079. register_core_extensions(); //before display
  1080. // possibly be worth changing the default from vulkan to something lower spec,
  1081. // for the project manager, depending on how smooth the fallback is.
  1082. GLOBAL_DEF_RST("rendering/driver/driver_name", "vulkan");
  1083. // this list is hard coded, which makes it more difficult to add new backends.
  1084. // can potentially be changed to more of a plugin system at a later date.
  1085. ProjectSettings::get_singleton()->set_custom_property_info("rendering/driver/driver_name",
  1086. PropertyInfo(Variant::STRING,
  1087. "rendering/driver/driver_name",
  1088. PROPERTY_HINT_ENUM, "vulkan,opengl3"));
  1089. // if not set on the command line
  1090. if (rendering_driver.is_empty()) {
  1091. rendering_driver = GLOBAL_GET("rendering/driver/driver_name");
  1092. }
  1093. // note this is the desired rendering driver, it doesn't mean we will get it.
  1094. // TODO - make sure this is updated in the case of fallbacks, so that the user interface
  1095. // shows the correct driver string.
  1096. OS::get_singleton()->set_current_rendering_driver_name(rendering_driver);
  1097. // always convert to lower case for consistency in the code
  1098. rendering_driver = rendering_driver.to_lower();
  1099. GLOBAL_DEF_BASIC("display/window/size/width", 1024);
  1100. ProjectSettings::get_singleton()->set_custom_property_info("display/window/size/width",
  1101. PropertyInfo(Variant::INT, "display/window/size/width",
  1102. PROPERTY_HINT_RANGE,
  1103. "0,7680,or_greater")); // 8K resolution
  1104. GLOBAL_DEF_BASIC("display/window/size/height", 600);
  1105. ProjectSettings::get_singleton()->set_custom_property_info("display/window/size/height",
  1106. PropertyInfo(Variant::INT, "display/window/size/height",
  1107. PROPERTY_HINT_RANGE,
  1108. "0,4320,or_greater")); // 8K resolution
  1109. GLOBAL_DEF_BASIC("display/window/size/resizable", true);
  1110. GLOBAL_DEF_BASIC("display/window/size/borderless", false);
  1111. GLOBAL_DEF_BASIC("display/window/size/fullscreen", false);
  1112. GLOBAL_DEF("display/window/size/always_on_top", false);
  1113. GLOBAL_DEF("display/window/size/test_width", 0);
  1114. ProjectSettings::get_singleton()->set_custom_property_info("display/window/size/test_width",
  1115. PropertyInfo(Variant::INT,
  1116. "display/window/size/test_width",
  1117. PROPERTY_HINT_RANGE,
  1118. "0,7680,or_greater")); // 8K resolution
  1119. GLOBAL_DEF("display/window/size/test_height", 0);
  1120. ProjectSettings::get_singleton()->set_custom_property_info("display/window/size/test_height",
  1121. PropertyInfo(Variant::INT,
  1122. "display/window/size/test_height",
  1123. PROPERTY_HINT_RANGE,
  1124. "0,4320,or_greater")); // 8K resolution
  1125. if (use_custom_res) {
  1126. if (!force_res) {
  1127. window_size.width = GLOBAL_GET("display/window/size/width");
  1128. window_size.height = GLOBAL_GET("display/window/size/height");
  1129. if (globals->has_setting("display/window/size/test_width") &&
  1130. globals->has_setting("display/window/size/test_height")) {
  1131. int tw = globals->get("display/window/size/test_width");
  1132. if (tw > 0) {
  1133. window_size.width = tw;
  1134. }
  1135. int th = globals->get("display/window/size/test_height");
  1136. if (th > 0) {
  1137. window_size.height = th;
  1138. }
  1139. }
  1140. }
  1141. if (!bool(GLOBAL_GET("display/window/size/resizable"))) {
  1142. window_flags |= DisplayServer::WINDOW_FLAG_RESIZE_DISABLED_BIT;
  1143. }
  1144. if (bool(GLOBAL_GET("display/window/size/borderless"))) {
  1145. window_flags |= DisplayServer::WINDOW_FLAG_BORDERLESS_BIT;
  1146. }
  1147. if (bool(GLOBAL_GET("display/window/size/fullscreen"))) {
  1148. window_mode = DisplayServer::WINDOW_MODE_FULLSCREEN;
  1149. }
  1150. if (bool(GLOBAL_GET("display/window/size/always_on_top"))) {
  1151. window_flags |= DisplayServer::WINDOW_FLAG_ALWAYS_ON_TOP_BIT;
  1152. }
  1153. }
  1154. GLOBAL_DEF("internationalization/rendering/force_right_to_left_layout_direction", false);
  1155. GLOBAL_DEF("internationalization/locale/include_text_server_data", false);
  1156. if (!force_lowdpi) {
  1157. OS::get_singleton()->_allow_hidpi = GLOBAL_DEF("display/window/dpi/allow_hidpi", false);
  1158. }
  1159. // FIXME: Restore support.
  1160. #if 0
  1161. //OS::get_singleton()->_allow_layered = GLOBAL_DEF("display/window/per_pixel_transparency/allowed", false);
  1162. video_mode.layered = GLOBAL_DEF("display/window/per_pixel_transparency/enabled", false);
  1163. #endif
  1164. if (editor || project_manager) {
  1165. // The editor and project manager always detect and use hiDPI if needed
  1166. OS::get_singleton()->_allow_hidpi = true;
  1167. OS::get_singleton()->_allow_layered = false;
  1168. }
  1169. OS::get_singleton()->_keep_screen_on = GLOBAL_DEF("display/window/energy_saving/keep_screen_on", true);
  1170. if (rtm == -1) {
  1171. rtm = GLOBAL_DEF("rendering/driver/threads/thread_model", OS::RENDER_THREAD_SAFE);
  1172. }
  1173. if (rtm >= 0 && rtm < 3) {
  1174. #ifdef NO_THREADS
  1175. rtm = OS::RENDER_THREAD_UNSAFE; // No threads available on this platform.
  1176. #else
  1177. if (editor) {
  1178. rtm = OS::RENDER_THREAD_SAFE;
  1179. }
  1180. #endif
  1181. OS::get_singleton()->_render_thread_mode = OS::RenderThreadMode(rtm);
  1182. }
  1183. /* Determine audio and video drivers */
  1184. // Display driver, e.g. X11, Wayland.
  1185. // print_line("requested display driver : " + display_driver);
  1186. for (int i = 0; i < DisplayServer::get_create_function_count(); i++) {
  1187. String name = DisplayServer::get_create_function_name(i);
  1188. // print_line("\t" + itos(i) + " : " + name);
  1189. if (display_driver == name) {
  1190. display_driver_idx = i;
  1191. break;
  1192. }
  1193. }
  1194. if (display_driver_idx < 0) {
  1195. display_driver_idx = 0;
  1196. }
  1197. // Store this in a globally accessible place, so we can retrieve the rendering drivers
  1198. // list from the display driver for the editor UI.
  1199. OS::get_singleton()->set_display_driver_id(display_driver_idx);
  1200. GLOBAL_DEF_RST_NOVAL("audio/driver/driver", AudioDriverManager::get_driver(0)->get_name());
  1201. if (audio_driver.is_empty()) { // Specified in project.godot.
  1202. audio_driver = GLOBAL_GET("audio/driver/driver");
  1203. }
  1204. for (int i = 0; i < AudioDriverManager::get_driver_count(); i++) {
  1205. if (audio_driver == AudioDriverManager::get_driver(i)->get_name()) {
  1206. audio_driver_idx = i;
  1207. break;
  1208. }
  1209. }
  1210. if (audio_driver_idx < 0) {
  1211. audio_driver_idx = 0;
  1212. }
  1213. {
  1214. window_orientation = DisplayServer::ScreenOrientation(int(GLOBAL_DEF_BASIC("display/window/handheld/orientation", DisplayServer::ScreenOrientation::SCREEN_LANDSCAPE)));
  1215. }
  1216. {
  1217. window_vsync_mode = DisplayServer::VSyncMode(int(GLOBAL_DEF("display/window/vsync/vsync_mode", DisplayServer::VSyncMode::VSYNC_ENABLED)));
  1218. }
  1219. Engine::get_singleton()->set_physics_ticks_per_second(GLOBAL_DEF_BASIC("physics/common/physics_ticks_per_second", 60));
  1220. ProjectSettings::get_singleton()->set_custom_property_info("physics/common/physics_ticks_per_second",
  1221. PropertyInfo(Variant::INT, "physics/common/physics_ticks_per_second",
  1222. PROPERTY_HINT_RANGE, "1,1000,1"));
  1223. Engine::get_singleton()->set_physics_jitter_fix(GLOBAL_DEF("physics/common/physics_jitter_fix", 0.5));
  1224. Engine::get_singleton()->set_target_fps(GLOBAL_DEF("debug/settings/fps/force_fps", 0));
  1225. ProjectSettings::get_singleton()->set_custom_property_info("debug/settings/fps/force_fps",
  1226. PropertyInfo(Variant::INT,
  1227. "debug/settings/fps/force_fps",
  1228. PROPERTY_HINT_RANGE, "0,1000,1"));
  1229. GLOBAL_DEF("debug/settings/stdout/print_fps", false);
  1230. GLOBAL_DEF("debug/settings/stdout/print_gpu_profile", false);
  1231. GLOBAL_DEF("debug/settings/stdout/verbose_stdout", false);
  1232. if (!OS::get_singleton()->_verbose_stdout) { // Not manually overridden.
  1233. OS::get_singleton()->_verbose_stdout = GLOBAL_GET("debug/settings/stdout/verbose_stdout");
  1234. }
  1235. if (frame_delay == 0) {
  1236. frame_delay = GLOBAL_DEF("application/run/frame_delay_msec", 0);
  1237. ProjectSettings::get_singleton()->set_custom_property_info("application/run/frame_delay_msec",
  1238. PropertyInfo(Variant::INT,
  1239. "application/run/frame_delay_msec",
  1240. PROPERTY_HINT_RANGE,
  1241. "0,100,1,or_greater")); // No negative numbers
  1242. }
  1243. OS::get_singleton()->set_low_processor_usage_mode(GLOBAL_DEF("application/run/low_processor_mode", false));
  1244. OS::get_singleton()->set_low_processor_usage_mode_sleep_usec(
  1245. GLOBAL_DEF("application/run/low_processor_mode_sleep_usec", 6900)); // Roughly 144 FPS
  1246. ProjectSettings::get_singleton()->set_custom_property_info("application/run/low_processor_mode_sleep_usec",
  1247. PropertyInfo(Variant::INT,
  1248. "application/run/low_processor_mode_sleep_usec",
  1249. PROPERTY_HINT_RANGE,
  1250. "0,33200,1,or_greater")); // No negative numbers
  1251. GLOBAL_DEF("display/window/ios/hide_home_indicator", true);
  1252. GLOBAL_DEF("input_devices/pointing/ios/touch_delay", 0.150);
  1253. Engine::get_singleton()->set_frame_delay(frame_delay);
  1254. message_queue = memnew(MessageQueue);
  1255. if (p_second_phase) {
  1256. return setup2();
  1257. }
  1258. return OK;
  1259. error:
  1260. text_driver = "";
  1261. display_driver = "";
  1262. audio_driver = "";
  1263. tablet_driver = "";
  1264. project_path = "";
  1265. args.clear();
  1266. main_args.clear();
  1267. if (show_help) {
  1268. print_help(execpath);
  1269. }
  1270. EngineDebugger::deinitialize();
  1271. if (performance) {
  1272. memdelete(performance);
  1273. }
  1274. if (input_map) {
  1275. memdelete(input_map);
  1276. }
  1277. if (time_singleton) {
  1278. memdelete(time_singleton);
  1279. }
  1280. if (translation_server) {
  1281. memdelete(translation_server);
  1282. }
  1283. if (globals) {
  1284. memdelete(globals);
  1285. }
  1286. if (engine) {
  1287. memdelete(engine);
  1288. }
  1289. if (packed_data) {
  1290. memdelete(packed_data);
  1291. }
  1292. if (file_access_network_client) {
  1293. memdelete(file_access_network_client);
  1294. }
  1295. unregister_core_driver_types();
  1296. unregister_core_types();
  1297. OS::get_singleton()->_cmdline.clear();
  1298. if (message_queue) {
  1299. memdelete(message_queue);
  1300. }
  1301. OS::get_singleton()->finalize_core();
  1302. locale = String();
  1303. return ERR_INVALID_PARAMETER;
  1304. }
  1305. Error Main::setup2(Thread::ID p_main_tid_override) {
  1306. tsman = memnew(TextServerManager);
  1307. preregister_module_types();
  1308. preregister_server_types();
  1309. // Print engine name and version
  1310. print_line(String(VERSION_NAME) + " v" + get_full_version_string() + " - " + String(VERSION_WEBSITE));
  1311. #if !defined(NO_THREADS)
  1312. if (p_main_tid_override) {
  1313. Thread::main_thread_id = p_main_tid_override;
  1314. }
  1315. #endif
  1316. #ifdef TOOLS_ENABLED
  1317. if (editor || project_manager || cmdline_tool) {
  1318. EditorPaths::create();
  1319. }
  1320. #endif
  1321. /* Initialize Input */
  1322. input = memnew(Input);
  1323. /* Initialize Display Server */
  1324. {
  1325. String display_driver = DisplayServer::get_create_function_name(display_driver_idx);
  1326. // rendering_driver now held in static global String in main and initialized in setup()
  1327. Error err;
  1328. display_server = DisplayServer::create(display_driver_idx, rendering_driver, window_mode, window_vsync_mode, window_flags, window_size, err);
  1329. if (err != OK || display_server == nullptr) {
  1330. //ok i guess we can't use this display server, try other ones
  1331. for (int i = 0; i < DisplayServer::get_create_function_count(); i++) {
  1332. if (i == display_driver_idx) {
  1333. continue; //don't try the same twice
  1334. }
  1335. display_server = DisplayServer::create(i, rendering_driver, window_mode, window_vsync_mode, window_flags, window_size, err);
  1336. if (err == OK && display_server != nullptr) {
  1337. break;
  1338. }
  1339. }
  1340. }
  1341. if (err != OK || display_server == nullptr) {
  1342. ERR_PRINT("Unable to create DisplayServer, all display drivers failed.");
  1343. return err;
  1344. }
  1345. }
  1346. if (display_server->has_feature(DisplayServer::FEATURE_ORIENTATION)) {
  1347. display_server->screen_set_orientation(window_orientation);
  1348. }
  1349. if (GLOBAL_GET("debug/settings/stdout/print_fps") || print_fps) {
  1350. // Print requested V-Sync mode at startup to diagnose the printed FPS not going above the monitor refresh rate.
  1351. switch (window_vsync_mode) {
  1352. case DisplayServer::VSyncMode::VSYNC_DISABLED:
  1353. print_line("Requested V-Sync mode: Disabled");
  1354. break;
  1355. case DisplayServer::VSyncMode::VSYNC_ENABLED:
  1356. print_line("Requested V-Sync mode: Enabled - FPS will likely be capped to the monitor refresh rate.");
  1357. break;
  1358. case DisplayServer::VSyncMode::VSYNC_ADAPTIVE:
  1359. print_line("Requested V-Sync mode: Adaptive");
  1360. break;
  1361. case DisplayServer::VSyncMode::VSYNC_MAILBOX:
  1362. print_line("Requested V-Sync mode: Mailbox");
  1363. break;
  1364. }
  1365. }
  1366. /* Initialize Pen Tablet Driver */
  1367. {
  1368. GLOBAL_DEF_RST_NOVAL("input_devices/pen_tablet/driver", "");
  1369. GLOBAL_DEF_RST_NOVAL("input_devices/pen_tablet/driver.windows", "");
  1370. ProjectSettings::get_singleton()->set_custom_property_info("input_devices/pen_tablet/driver.windows", PropertyInfo(Variant::STRING, "input_devices/pen_tablet/driver.windows", PROPERTY_HINT_ENUM, "wintab,winink"));
  1371. }
  1372. if (tablet_driver.is_empty()) { // specified in project.godot
  1373. tablet_driver = GLOBAL_GET("input_devices/pen_tablet/driver");
  1374. if (tablet_driver.is_empty()) {
  1375. tablet_driver = DisplayServer::get_singleton()->tablet_get_driver_name(0);
  1376. }
  1377. }
  1378. for (int i = 0; i < DisplayServer::get_singleton()->tablet_get_driver_count(); i++) {
  1379. if (tablet_driver == DisplayServer::get_singleton()->tablet_get_driver_name(i)) {
  1380. DisplayServer::get_singleton()->tablet_set_current_driver(DisplayServer::get_singleton()->tablet_get_driver_name(i));
  1381. break;
  1382. }
  1383. }
  1384. if (DisplayServer::get_singleton()->tablet_get_current_driver().is_empty()) {
  1385. DisplayServer::get_singleton()->tablet_set_current_driver(DisplayServer::get_singleton()->tablet_get_driver_name(0));
  1386. }
  1387. print_verbose("Using \"" + tablet_driver + "\" pen tablet driver...");
  1388. /* Initialize Rendering Server */
  1389. rendering_server = memnew(RenderingServerDefault(OS::get_singleton()->get_render_thread_mode() == OS::RENDER_SEPARATE_THREAD));
  1390. rendering_server->init();
  1391. //rendering_server->call_set_use_vsync(OS::get_singleton()->_use_vsync);
  1392. rendering_server->set_render_loop_enabled(!disable_render_loop);
  1393. if (profile_gpu || (!editor && bool(GLOBAL_GET("debug/settings/stdout/print_gpu_profile")))) {
  1394. rendering_server->set_print_gpu_profile(true);
  1395. }
  1396. #ifdef UNIX_ENABLED
  1397. // Print warning after initializing the renderer but before initializing audio.
  1398. if (OS::get_singleton()->get_environment("USER") == "root" && !OS::get_singleton()->has_environment("GODOT_SILENCE_ROOT_WARNING")) {
  1399. 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.");
  1400. }
  1401. #endif
  1402. OS::get_singleton()->initialize_joypads();
  1403. /* Initialize Audio Driver */
  1404. AudioDriverManager::initialize(audio_driver_idx);
  1405. print_line(" "); //add a blank line for readability
  1406. if (init_use_custom_pos) {
  1407. display_server->window_set_position(init_custom_pos);
  1408. }
  1409. // right moment to create and initialize the audio server
  1410. audio_server = memnew(AudioServer);
  1411. audio_server->init();
  1412. // also init our xr_server from here
  1413. xr_server = memnew(XRServer);
  1414. register_core_singletons();
  1415. MAIN_PRINT("Main: Setup Logo");
  1416. #if defined(JAVASCRIPT_ENABLED) || defined(ANDROID_ENABLED)
  1417. bool show_logo = false;
  1418. #else
  1419. bool show_logo = true;
  1420. #endif
  1421. if (init_screen != -1) {
  1422. DisplayServer::get_singleton()->window_set_current_screen(init_screen);
  1423. }
  1424. if (init_windowed) {
  1425. //do none..
  1426. } else if (init_maximized) {
  1427. DisplayServer::get_singleton()->window_set_mode(DisplayServer::WINDOW_MODE_MAXIMIZED);
  1428. } else if (init_fullscreen) {
  1429. DisplayServer::get_singleton()->window_set_mode(DisplayServer::WINDOW_MODE_FULLSCREEN);
  1430. }
  1431. if (init_always_on_top) {
  1432. DisplayServer::get_singleton()->window_set_flag(DisplayServer::WINDOW_FLAG_ALWAYS_ON_TOP, true);
  1433. }
  1434. if (allow_focus_steal_pid) {
  1435. DisplayServer::get_singleton()->enable_for_stealing_focus(allow_focus_steal_pid);
  1436. }
  1437. register_server_types();
  1438. MAIN_PRINT("Main: Load Boot Image");
  1439. Color clear = GLOBAL_DEF("rendering/environment/defaults/default_clear_color", Color(0.3, 0.3, 0.3));
  1440. RenderingServer::get_singleton()->set_default_clear_color(clear);
  1441. if (show_logo) { //boot logo!
  1442. const bool boot_logo_image = GLOBAL_DEF("application/boot_splash/show_image", true);
  1443. const String boot_logo_path = String(GLOBAL_DEF("application/boot_splash/image", String())).strip_edges();
  1444. const bool boot_logo_scale = GLOBAL_DEF("application/boot_splash/fullsize", true);
  1445. const bool boot_logo_filter = GLOBAL_DEF("application/boot_splash/use_filter", true);
  1446. ProjectSettings::get_singleton()->set_custom_property_info("application/boot_splash/image",
  1447. PropertyInfo(Variant::STRING,
  1448. "application/boot_splash/image",
  1449. PROPERTY_HINT_FILE, "*.png"));
  1450. Ref<Image> boot_logo;
  1451. if (boot_logo_image) {
  1452. if (!boot_logo_path.is_empty()) {
  1453. boot_logo.instantiate();
  1454. Error load_err = ImageLoader::load_image(boot_logo_path, boot_logo);
  1455. if (load_err) {
  1456. ERR_PRINT("Non-existing or invalid boot splash at '" + boot_logo_path + "'. Loading default splash.");
  1457. }
  1458. }
  1459. } else {
  1460. // Create a 1×1 transparent image. This will effectively hide the splash image.
  1461. boot_logo.instantiate();
  1462. boot_logo->create(1, 1, false, Image::FORMAT_RGBA8);
  1463. boot_logo->set_pixel(0, 0, Color(0, 0, 0, 0));
  1464. }
  1465. #if defined(TOOLS_ENABLED) && !defined(NO_EDITOR_SPLASH)
  1466. const Color boot_bg_color =
  1467. GLOBAL_DEF("application/boot_splash/bg_color",
  1468. (editor || project_manager) ? boot_splash_editor_bg_color : boot_splash_bg_color);
  1469. #else
  1470. const Color boot_bg_color = GLOBAL_DEF("application/boot_splash/bg_color", boot_splash_bg_color);
  1471. #endif
  1472. if (boot_logo.is_valid()) {
  1473. RenderingServer::get_singleton()->set_boot_image(boot_logo, boot_bg_color, boot_logo_scale,
  1474. boot_logo_filter);
  1475. } else {
  1476. #ifndef NO_DEFAULT_BOOT_LOGO
  1477. MAIN_PRINT("Main: Create bootsplash");
  1478. #if defined(TOOLS_ENABLED) && !defined(NO_EDITOR_SPLASH)
  1479. Ref<Image> splash = (editor || project_manager) ? memnew(Image(boot_splash_editor_png)) : memnew(Image(boot_splash_png));
  1480. #else
  1481. Ref<Image> splash = memnew(Image(boot_splash_png));
  1482. #endif
  1483. MAIN_PRINT("Main: ClearColor");
  1484. RenderingServer::get_singleton()->set_default_clear_color(boot_bg_color);
  1485. MAIN_PRINT("Main: Image");
  1486. RenderingServer::get_singleton()->set_boot_image(splash, boot_bg_color, false);
  1487. #endif
  1488. }
  1489. #ifdef TOOLS_ENABLED
  1490. if (OS::get_singleton()->get_bundle_icon_path().is_empty()) {
  1491. Ref<Image> icon = memnew(Image(app_icon_png));
  1492. DisplayServer::get_singleton()->set_icon(icon);
  1493. }
  1494. #endif
  1495. }
  1496. MAIN_PRINT("Main: DCC");
  1497. RenderingServer::get_singleton()->set_default_clear_color(
  1498. GLOBAL_DEF("rendering/environment/defaults/default_clear_color", Color(0.3, 0.3, 0.3)));
  1499. GLOBAL_DEF("application/config/icon", String());
  1500. ProjectSettings::get_singleton()->set_custom_property_info("application/config/icon",
  1501. PropertyInfo(Variant::STRING, "application/config/icon",
  1502. PROPERTY_HINT_FILE, "*.png,*.webp,*.svg,*.svgz"));
  1503. GLOBAL_DEF("application/config/macos_native_icon", String());
  1504. ProjectSettings::get_singleton()->set_custom_property_info("application/config/macos_native_icon",
  1505. PropertyInfo(Variant::STRING,
  1506. "application/config/macos_native_icon",
  1507. PROPERTY_HINT_FILE, "*.icns"));
  1508. GLOBAL_DEF("application/config/windows_native_icon", String());
  1509. ProjectSettings::get_singleton()->set_custom_property_info("application/config/windows_native_icon",
  1510. PropertyInfo(Variant::STRING,
  1511. "application/config/windows_native_icon",
  1512. PROPERTY_HINT_FILE, "*.ico"));
  1513. Input *id = Input::get_singleton();
  1514. if (id) {
  1515. agile_input_event_flushing = GLOBAL_DEF("input_devices/buffering/agile_event_flushing", false);
  1516. if (bool(GLOBAL_DEF("input_devices/pointing/emulate_touch_from_mouse", false)) &&
  1517. !(editor || project_manager)) {
  1518. bool found_touchscreen = false;
  1519. for (int i = 0; i < DisplayServer::get_singleton()->get_screen_count(); i++) {
  1520. if (DisplayServer::get_singleton()->screen_is_touchscreen(i)) {
  1521. found_touchscreen = true;
  1522. }
  1523. }
  1524. if (!found_touchscreen) {
  1525. //only if no touchscreen ui hint, set emulation
  1526. id->set_emulate_touch_from_mouse(true);
  1527. }
  1528. }
  1529. id->set_emulate_mouse_from_touch(bool(GLOBAL_DEF("input_devices/pointing/emulate_mouse_from_touch", true)));
  1530. }
  1531. MAIN_PRINT("Main: Load Translations and Remaps");
  1532. translation_server->setup(); //register translations, load them, etc.
  1533. if (!locale.is_empty()) {
  1534. translation_server->set_locale(locale);
  1535. }
  1536. translation_server->load_translations();
  1537. ResourceLoader::load_translation_remaps(); //load remaps for resources
  1538. ResourceLoader::load_path_remaps();
  1539. MAIN_PRINT("Main: Load TextServer");
  1540. /* Enum text drivers */
  1541. GLOBAL_DEF("internationalization/rendering/text_driver", "");
  1542. String text_driver_options;
  1543. for (int i = 0; i < TextServerManager::get_singleton()->get_interface_count(); i++) {
  1544. if (i > 0) {
  1545. text_driver_options += ",";
  1546. }
  1547. text_driver_options += TextServerManager::get_singleton()->get_interface(i)->get_name();
  1548. }
  1549. ProjectSettings::get_singleton()->set_custom_property_info("internationalization/rendering/text_driver", PropertyInfo(Variant::STRING, "internationalization/rendering/text_driver", PROPERTY_HINT_ENUM, text_driver_options));
  1550. /* Determine text driver */
  1551. if (text_driver.is_empty()) {
  1552. text_driver = GLOBAL_GET("internationalization/rendering/text_driver");
  1553. }
  1554. if (!text_driver.is_empty()) {
  1555. /* Load user selected text server. */
  1556. for (int i = 0; i < TextServerManager::get_singleton()->get_interface_count(); i++) {
  1557. if (TextServerManager::get_singleton()->get_interface(i)->get_name() == text_driver) {
  1558. text_driver_idx = i;
  1559. break;
  1560. }
  1561. }
  1562. }
  1563. if (text_driver_idx < 0) {
  1564. /* If not selected, use one with the most features available. */
  1565. int max_features = 0;
  1566. for (int i = 0; i < TextServerManager::get_singleton()->get_interface_count(); i++) {
  1567. uint32_t features = TextServerManager::get_singleton()->get_interface(i)->get_features();
  1568. int feature_number = 0;
  1569. while (features) {
  1570. feature_number += features & 1;
  1571. features >>= 1;
  1572. }
  1573. if (feature_number >= max_features) {
  1574. max_features = feature_number;
  1575. text_driver_idx = i;
  1576. }
  1577. }
  1578. }
  1579. if (text_driver_idx >= 0) {
  1580. TextServerManager::get_singleton()->set_primary_interface(TextServerManager::get_singleton()->get_interface(text_driver_idx));
  1581. } else {
  1582. ERR_PRINT("TextServer: Unable to create TextServer interface.");
  1583. return ERR_CANT_CREATE;
  1584. }
  1585. MAIN_PRINT("Main: Load Scene Types");
  1586. register_scene_types();
  1587. #ifdef TOOLS_ENABLED
  1588. ClassDB::set_current_api(ClassDB::API_EDITOR);
  1589. EditorNode::register_editor_types();
  1590. ClassDB::set_current_api(ClassDB::API_CORE);
  1591. #endif
  1592. MAIN_PRINT("Main: Load Modules");
  1593. register_platform_apis();
  1594. register_module_types();
  1595. // Theme needs modules to be initialized so that sub-resources can be loaded.
  1596. initialize_theme();
  1597. GLOBAL_DEF("display/mouse_cursor/custom_image", String());
  1598. GLOBAL_DEF("display/mouse_cursor/custom_image_hotspot", Vector2());
  1599. GLOBAL_DEF("display/mouse_cursor/tooltip_position_offset", Point2(10, 10));
  1600. ProjectSettings::get_singleton()->set_custom_property_info("display/mouse_cursor/custom_image",
  1601. PropertyInfo(Variant::STRING,
  1602. "display/mouse_cursor/custom_image",
  1603. PROPERTY_HINT_FILE, "*.png,*.webp"));
  1604. if (String(ProjectSettings::get_singleton()->get("display/mouse_cursor/custom_image")) != String()) {
  1605. Ref<Texture2D> cursor = ResourceLoader::load(
  1606. ProjectSettings::get_singleton()->get("display/mouse_cursor/custom_image"));
  1607. if (cursor.is_valid()) {
  1608. Vector2 hotspot = ProjectSettings::get_singleton()->get("display/mouse_cursor/custom_image_hotspot");
  1609. Input::get_singleton()->set_custom_mouse_cursor(cursor, Input::CURSOR_ARROW, hotspot);
  1610. }
  1611. }
  1612. camera_server = CameraServer::create();
  1613. MAIN_PRINT("Main: Load Physics, Drivers, Scripts");
  1614. initialize_physics();
  1615. initialize_navigation_server();
  1616. register_server_singletons();
  1617. register_driver_types();
  1618. // This loads global classes, so it must happen before custom loaders and savers are registered
  1619. ScriptServer::init_languages();
  1620. audio_server->load_default_bus_layout();
  1621. if (use_debug_profiler && EngineDebugger::is_active()) {
  1622. // Start the "scripts" profiler, used in local debugging.
  1623. // We could add more, and make the CLI arg require a comma-separated list of profilers.
  1624. EngineDebugger::get_singleton()->profiler_enable("scripts", true);
  1625. }
  1626. if (!project_manager) {
  1627. // If not running the project manager, and now that the engine is
  1628. // able to load resources, load the global shader variables.
  1629. // If running on editor, don't load the textures because the editor
  1630. // may want to import them first. Editor will reload those later.
  1631. rendering_server->global_variables_load_settings(!editor);
  1632. }
  1633. _start_success = true;
  1634. ClassDB::set_current_api(ClassDB::API_NONE); //no more APIs are registered at this point
  1635. print_verbose("CORE API HASH: " + uitos(ClassDB::get_api_hash(ClassDB::API_CORE)));
  1636. print_verbose("EDITOR API HASH: " + uitos(ClassDB::get_api_hash(ClassDB::API_EDITOR)));
  1637. MAIN_PRINT("Main: Done");
  1638. return OK;
  1639. }
  1640. // everything the main loop needs to know about frame timings
  1641. static MainTimerSync main_timer_sync;
  1642. bool Main::start() {
  1643. ERR_FAIL_COND_V(!_start_success, false);
  1644. bool hasicon = false;
  1645. String positional_arg;
  1646. String game_path;
  1647. String script;
  1648. bool check_only = false;
  1649. #ifdef TOOLS_ENABLED
  1650. String doc_tool_path;
  1651. bool doc_base = true;
  1652. String _export_preset;
  1653. bool export_debug = false;
  1654. bool export_pack_only = false;
  1655. #endif
  1656. main_timer_sync.init(OS::get_singleton()->get_ticks_usec());
  1657. List<String> args = OS::get_singleton()->get_cmdline_args();
  1658. for (int i = 0; i < args.size(); i++) {
  1659. // First check parameters that do not have an argument to the right.
  1660. // Doctest Unit Testing Handler
  1661. // Designed to override and pass arguments to the unit test handler.
  1662. if (args[i] == "--check-only") {
  1663. check_only = true;
  1664. #ifdef TOOLS_ENABLED
  1665. } else if (args[i] == "--no-docbase") {
  1666. doc_base = false;
  1667. } else if (args[i] == "-e" || args[i] == "--editor") {
  1668. editor = true;
  1669. } else if (args[i] == "-p" || args[i] == "--project-manager") {
  1670. project_manager = true;
  1671. #endif
  1672. } else if (args[i].length() && args[i][0] != '-' && positional_arg.is_empty()) {
  1673. positional_arg = args[i];
  1674. if (args[i].ends_with(".scn") ||
  1675. args[i].ends_with(".tscn") ||
  1676. args[i].ends_with(".escn") ||
  1677. args[i].ends_with(".res") ||
  1678. args[i].ends_with(".tres")) {
  1679. // Only consider the positional argument to be a scene path if it ends with
  1680. // a file extension associated with Godot scenes. This makes it possible
  1681. // for projects to parse command-line arguments for custom CLI arguments
  1682. // or other file extensions without trouble. This can be used to implement
  1683. // "drag-and-drop onto executable" logic, which can prove helpful
  1684. // for non-game applications.
  1685. game_path = args[i];
  1686. }
  1687. }
  1688. // Then parameters that have an argument to the right.
  1689. else if (i < (args.size() - 1)) {
  1690. bool parsed_pair = true;
  1691. if (args[i] == "-s" || args[i] == "--script") {
  1692. script = args[i + 1];
  1693. #ifdef TOOLS_ENABLED
  1694. } else if (args[i] == "--doctool") {
  1695. doc_tool_path = args[i + 1];
  1696. if (doc_tool_path.begins_with("-")) {
  1697. // Assuming other command line arg, so default to cwd.
  1698. doc_tool_path = ".";
  1699. parsed_pair = false;
  1700. }
  1701. } else if (args[i] == "--export") {
  1702. editor = true; //needs editor
  1703. _export_preset = args[i + 1];
  1704. } else if (args[i] == "--export-debug") {
  1705. editor = true; //needs editor
  1706. _export_preset = args[i + 1];
  1707. export_debug = true;
  1708. } else if (args[i] == "--export-pack") {
  1709. editor = true;
  1710. _export_preset = args[i + 1];
  1711. export_pack_only = true;
  1712. #endif
  1713. } else {
  1714. // The parameter does not match anything known, don't skip the next argument
  1715. parsed_pair = false;
  1716. }
  1717. if (parsed_pair) {
  1718. i++;
  1719. }
  1720. }
  1721. #ifdef TOOLS_ENABLED
  1722. // Handle case where no path is given to --doctool.
  1723. else if (args[i] == "--doctool") {
  1724. doc_tool_path = ".";
  1725. }
  1726. #endif
  1727. }
  1728. #ifdef TOOLS_ENABLED
  1729. if (!doc_tool_path.is_empty()) {
  1730. // Needed to instance editor-only classes for their default values
  1731. Engine::get_singleton()->set_editor_hint(true);
  1732. // Translate the class reference only when `-l LOCALE` parameter is given.
  1733. if (!locale.is_empty() && locale != "en") {
  1734. load_doc_translations(locale);
  1735. }
  1736. {
  1737. DirAccessRef da = DirAccess::open(doc_tool_path);
  1738. ERR_FAIL_COND_V_MSG(!da, false, "Argument supplied to --doctool must be a valid directory path.");
  1739. }
  1740. #ifndef MODULE_MONO_ENABLED
  1741. // Hack to define Mono-specific project settings even on non-Mono builds,
  1742. // so that we don't lose their descriptions and default values in DocData.
  1743. // Default values should be synced with mono_gd/gd_mono.cpp.
  1744. GLOBAL_DEF("mono/debugger_agent/port", 23685);
  1745. GLOBAL_DEF("mono/debugger_agent/wait_for_debugger", false);
  1746. GLOBAL_DEF("mono/debugger_agent/wait_timeout", 3000);
  1747. GLOBAL_DEF("mono/profiler/args", "log:calls,alloc,sample,output=output.mlpd");
  1748. GLOBAL_DEF("mono/profiler/enabled", false);
  1749. GLOBAL_DEF("mono/runtime/unhandled_exception_policy", 0);
  1750. #endif
  1751. DocTools doc;
  1752. doc.generate(doc_base);
  1753. DocTools docsrc;
  1754. Map<String, String> doc_data_classes;
  1755. Set<String> checked_paths;
  1756. print_line("Loading docs...");
  1757. for (int i = 0; i < _doc_data_class_path_count; i++) {
  1758. // Custom modules are always located by absolute path.
  1759. String path = _doc_data_class_paths[i].path;
  1760. if (path.is_relative_path()) {
  1761. path = doc_tool_path.plus_file(path);
  1762. }
  1763. String name = _doc_data_class_paths[i].name;
  1764. doc_data_classes[name] = path;
  1765. if (!checked_paths.has(path)) {
  1766. checked_paths.insert(path);
  1767. // Create the module documentation directory if it doesn't exist
  1768. DirAccess *da = DirAccess::create_for_path(path);
  1769. da->make_dir_recursive(path);
  1770. memdelete(da);
  1771. docsrc.load_classes(path);
  1772. print_line("Loading docs from: " + path);
  1773. }
  1774. }
  1775. String index_path = doc_tool_path.plus_file("doc/classes");
  1776. // Create the main documentation directory if it doesn't exist
  1777. DirAccess *da = DirAccess::create_for_path(index_path);
  1778. da->make_dir_recursive(index_path);
  1779. memdelete(da);
  1780. docsrc.load_classes(index_path);
  1781. checked_paths.insert(index_path);
  1782. print_line("Loading docs from: " + index_path);
  1783. print_line("Merging docs...");
  1784. doc.merge_from(docsrc);
  1785. for (Set<String>::Element *E = checked_paths.front(); E; E = E->next()) {
  1786. print_line("Erasing old docs at: " + E->get());
  1787. DocTools::erase_classes(E->get());
  1788. }
  1789. print_line("Generating new docs...");
  1790. doc.save_classes(index_path, doc_data_classes);
  1791. return false;
  1792. }
  1793. if (dump_extension_api) {
  1794. NativeExtensionAPIDump::generate_extension_json_file("extension_api.json");
  1795. return false;
  1796. }
  1797. #endif
  1798. if (script.is_empty() && game_path.is_empty() && String(GLOBAL_GET("application/run/main_scene")) != "") {
  1799. game_path = GLOBAL_GET("application/run/main_scene");
  1800. }
  1801. #ifdef TOOLS_ENABLED
  1802. if (!editor && !project_manager && !cmdline_tool && script.is_empty() && game_path.is_empty()) {
  1803. // If we end up here, it means we didn't manage to detect what we want to run.
  1804. // Let's throw an error gently. The code leading to this is pretty brittle so
  1805. // this might end up triggered by valid usage, in which case we'll have to
  1806. // fine-tune further.
  1807. OS::get_singleton()->alert("Couldn't detect whether to run the editor, the project manager or a specific project. Aborting.");
  1808. ERR_FAIL_V_MSG(false, "Couldn't detect whether to run the editor, the project manager or a specific project. Aborting.");
  1809. }
  1810. #endif
  1811. MainLoop *main_loop = nullptr;
  1812. if (editor) {
  1813. main_loop = memnew(SceneTree);
  1814. }
  1815. String main_loop_type = GLOBAL_DEF("application/run/main_loop_type", "SceneTree");
  1816. if (!script.is_empty()) {
  1817. Ref<Script> script_res = ResourceLoader::load(script);
  1818. ERR_FAIL_COND_V_MSG(script_res.is_null(), false, "Can't load script: " + script);
  1819. if (check_only) {
  1820. if (!script_res->is_valid()) {
  1821. OS::get_singleton()->set_exit_code(EXIT_FAILURE);
  1822. } else {
  1823. OS::get_singleton()->set_exit_code(EXIT_SUCCESS);
  1824. }
  1825. return false;
  1826. }
  1827. if (script_res->can_instantiate()) {
  1828. StringName instance_type = script_res->get_instance_base_type();
  1829. Object *obj = ClassDB::instantiate(instance_type);
  1830. MainLoop *script_loop = Object::cast_to<MainLoop>(obj);
  1831. if (!script_loop) {
  1832. if (obj) {
  1833. memdelete(obj);
  1834. }
  1835. OS::get_singleton()->alert(vformat("Can't load the script \"%s\" as it doesn't inherit from SceneTree or MainLoop.", script));
  1836. ERR_FAIL_V_MSG(false, vformat("Can't load the script \"%s\" as it doesn't inherit from SceneTree or MainLoop.", script));
  1837. }
  1838. script_loop->set_initialize_script(script_res);
  1839. main_loop = script_loop;
  1840. } else {
  1841. return false;
  1842. }
  1843. } else { // Not based on script path.
  1844. if (!editor && !ClassDB::class_exists(main_loop_type) && ScriptServer::is_global_class(main_loop_type)) {
  1845. String script_path = ScriptServer::get_global_class_path(main_loop_type);
  1846. Ref<Script> script_res = ResourceLoader::load(script_path);
  1847. StringName script_base = ScriptServer::get_global_class_native_base(main_loop_type);
  1848. Object *obj = ClassDB::instantiate(script_base);
  1849. MainLoop *script_loop = Object::cast_to<MainLoop>(obj);
  1850. if (!script_loop) {
  1851. if (obj) {
  1852. memdelete(obj);
  1853. }
  1854. OS::get_singleton()->alert("Error: Invalid MainLoop script base type: " + script_base);
  1855. ERR_FAIL_V_MSG(false, vformat("The global class %s does not inherit from SceneTree or MainLoop.", main_loop_type));
  1856. }
  1857. script_loop->set_initialize_script(script_res);
  1858. main_loop = script_loop;
  1859. }
  1860. }
  1861. if (!main_loop && main_loop_type.is_empty()) {
  1862. main_loop_type = "SceneTree";
  1863. }
  1864. if (!main_loop) {
  1865. if (!ClassDB::class_exists(main_loop_type)) {
  1866. OS::get_singleton()->alert("Error: MainLoop type doesn't exist: " + main_loop_type);
  1867. return false;
  1868. } else {
  1869. Object *ml = ClassDB::instantiate(main_loop_type);
  1870. ERR_FAIL_COND_V_MSG(!ml, false, "Can't instance MainLoop type.");
  1871. main_loop = Object::cast_to<MainLoop>(ml);
  1872. if (!main_loop) {
  1873. memdelete(ml);
  1874. ERR_FAIL_V_MSG(false, "Invalid MainLoop type.");
  1875. }
  1876. }
  1877. }
  1878. if (main_loop->is_class("SceneTree")) {
  1879. SceneTree *sml = Object::cast_to<SceneTree>(main_loop);
  1880. #ifdef DEBUG_ENABLED
  1881. if (debug_collisions) {
  1882. sml->set_debug_collisions_hint(true);
  1883. }
  1884. if (debug_navigation) {
  1885. sml->set_debug_navigation_hint(true);
  1886. }
  1887. #endif
  1888. bool embed_subwindows = GLOBAL_DEF("display/window/subwindows/embed_subwindows", true);
  1889. if (OS::get_singleton()->is_single_window() || (!project_manager && !editor && embed_subwindows)) {
  1890. sml->get_root()->set_embed_subwindows_hint(true);
  1891. }
  1892. ResourceLoader::add_custom_loaders();
  1893. ResourceSaver::add_custom_savers();
  1894. if (!project_manager && !editor) { // game
  1895. if (!game_path.is_empty() || !script.is_empty()) {
  1896. //autoload
  1897. OrderedHashMap<StringName, ProjectSettings::AutoloadInfo> autoloads = ProjectSettings::get_singleton()->get_autoload_list();
  1898. //first pass, add the constants so they exist before any script is loaded
  1899. for (OrderedHashMap<StringName, ProjectSettings::AutoloadInfo>::Element E = autoloads.front(); E; E = E.next()) {
  1900. const ProjectSettings::AutoloadInfo &info = E.get();
  1901. if (info.is_singleton) {
  1902. for (int i = 0; i < ScriptServer::get_language_count(); i++) {
  1903. ScriptServer::get_language(i)->add_global_constant(info.name, Variant());
  1904. }
  1905. }
  1906. }
  1907. //second pass, load into global constants
  1908. List<Node *> to_add;
  1909. for (OrderedHashMap<StringName, ProjectSettings::AutoloadInfo>::Element E = autoloads.front(); E; E = E.next()) {
  1910. const ProjectSettings::AutoloadInfo &info = E.get();
  1911. RES res = ResourceLoader::load(info.path);
  1912. ERR_CONTINUE_MSG(res.is_null(), "Can't autoload: " + info.path);
  1913. Node *n = nullptr;
  1914. if (res->is_class("PackedScene")) {
  1915. Ref<PackedScene> ps = res;
  1916. n = ps->instantiate();
  1917. } else if (res->is_class("Script")) {
  1918. Ref<Script> script_res = res;
  1919. StringName ibt = script_res->get_instance_base_type();
  1920. bool valid_type = ClassDB::is_parent_class(ibt, "Node");
  1921. ERR_CONTINUE_MSG(!valid_type, "Script does not inherit a Node: " + info.path);
  1922. Object *obj = ClassDB::instantiate(ibt);
  1923. ERR_CONTINUE_MSG(obj == nullptr,
  1924. "Cannot instance script for autoload, expected 'Node' inheritance, got: " +
  1925. String(ibt));
  1926. n = Object::cast_to<Node>(obj);
  1927. n->set_script(script_res);
  1928. }
  1929. ERR_CONTINUE_MSG(!n, "Path in autoload not a node or script: " + info.path);
  1930. n->set_name(info.name);
  1931. //defer so references are all valid on _ready()
  1932. to_add.push_back(n);
  1933. if (info.is_singleton) {
  1934. for (int i = 0; i < ScriptServer::get_language_count(); i++) {
  1935. ScriptServer::get_language(i)->add_global_constant(info.name, n);
  1936. }
  1937. }
  1938. }
  1939. for (Node *E : to_add) {
  1940. sml->get_root()->add_child(E);
  1941. }
  1942. }
  1943. }
  1944. #ifdef TOOLS_ENABLED
  1945. EditorNode *editor_node = nullptr;
  1946. if (editor) {
  1947. editor_node = memnew(EditorNode);
  1948. sml->get_root()->add_child(editor_node);
  1949. if (!_export_preset.is_empty()) {
  1950. editor_node->export_preset(_export_preset, positional_arg, export_debug, export_pack_only);
  1951. game_path = ""; // Do not load anything.
  1952. }
  1953. }
  1954. #endif
  1955. if (!editor && !project_manager) {
  1956. //standard helpers that can be changed from main config
  1957. String stretch_mode = GLOBAL_DEF_BASIC("display/window/stretch/mode", "disabled");
  1958. String stretch_aspect = GLOBAL_DEF_BASIC("display/window/stretch/aspect", "keep");
  1959. Size2i stretch_size = Size2i(GLOBAL_DEF_BASIC("display/window/size/width", 0),
  1960. GLOBAL_DEF_BASIC("display/window/size/height", 0));
  1961. real_t stretch_scale = GLOBAL_DEF_BASIC("display/window/stretch/scale", 1.0);
  1962. Window::ContentScaleMode cs_sm = Window::CONTENT_SCALE_MODE_DISABLED;
  1963. if (stretch_mode == "canvas_items") {
  1964. cs_sm = Window::CONTENT_SCALE_MODE_CANVAS_ITEMS;
  1965. } else if (stretch_mode == "viewport") {
  1966. cs_sm = Window::CONTENT_SCALE_MODE_VIEWPORT;
  1967. }
  1968. Window::ContentScaleAspect cs_aspect = Window::CONTENT_SCALE_ASPECT_IGNORE;
  1969. if (stretch_aspect == "keep") {
  1970. cs_aspect = Window::CONTENT_SCALE_ASPECT_KEEP;
  1971. } else if (stretch_aspect == "keep_width") {
  1972. cs_aspect = Window::CONTENT_SCALE_ASPECT_KEEP_WIDTH;
  1973. } else if (stretch_aspect == "keep_height") {
  1974. cs_aspect = Window::CONTENT_SCALE_ASPECT_KEEP_HEIGHT;
  1975. } else if (stretch_aspect == "expand") {
  1976. cs_aspect = Window::CONTENT_SCALE_ASPECT_EXPAND;
  1977. }
  1978. sml->get_root()->set_content_scale_mode(cs_sm);
  1979. sml->get_root()->set_content_scale_aspect(cs_aspect);
  1980. sml->get_root()->set_content_scale_size(stretch_size);
  1981. sml->get_root()->set_content_scale_factor(stretch_scale);
  1982. sml->set_auto_accept_quit(GLOBAL_DEF("application/config/auto_accept_quit", true));
  1983. sml->set_quit_on_go_back(GLOBAL_DEF("application/config/quit_on_go_back", true));
  1984. String appname = ProjectSettings::get_singleton()->get("application/config/name");
  1985. appname = TranslationServer::get_singleton()->translate(appname);
  1986. #ifdef DEBUG_ENABLED
  1987. // Append a suffix to the window title to denote that the project is running
  1988. // from a debug build (including the editor). Since this results in lower performance,
  1989. // this should be clearly presented to the user.
  1990. DisplayServer::get_singleton()->window_set_title(vformat("%s (DEBUG)", appname));
  1991. #else
  1992. DisplayServer::get_singleton()->window_set_title(appname);
  1993. #endif
  1994. // Define a very small minimum window size to prevent bugs such as GH-37242.
  1995. // It can still be overridden by the user in a script.
  1996. DisplayServer::get_singleton()->window_set_min_size(Size2i(64, 64));
  1997. bool snap_controls = GLOBAL_DEF("gui/common/snap_controls_to_pixels", true);
  1998. sml->get_root()->set_snap_controls_to_pixels(snap_controls);
  1999. bool font_oversampling = GLOBAL_DEF("gui/fonts/dynamic_fonts/use_oversampling", true);
  2000. sml->get_root()->set_use_font_oversampling(font_oversampling);
  2001. int texture_filter = GLOBAL_DEF("rendering/textures/canvas_textures/default_texture_filter", 1);
  2002. int texture_repeat = GLOBAL_DEF("rendering/textures/canvas_textures/default_texture_repeat", 0);
  2003. sml->get_root()->set_default_canvas_item_texture_filter(
  2004. Viewport::DefaultCanvasItemTextureFilter(texture_filter));
  2005. sml->get_root()->set_default_canvas_item_texture_repeat(
  2006. Viewport::DefaultCanvasItemTextureRepeat(texture_repeat));
  2007. } else {
  2008. GLOBAL_DEF_BASIC("display/window/stretch/mode", "disabled");
  2009. ProjectSettings::get_singleton()->set_custom_property_info("display/window/stretch/mode",
  2010. PropertyInfo(Variant::STRING,
  2011. "display/window/stretch/mode",
  2012. PROPERTY_HINT_ENUM,
  2013. "disabled,canvas_items,viewport"));
  2014. GLOBAL_DEF_BASIC("display/window/stretch/aspect", "keep");
  2015. ProjectSettings::get_singleton()->set_custom_property_info("display/window/stretch/aspect",
  2016. PropertyInfo(Variant::STRING,
  2017. "display/window/stretch/aspect",
  2018. PROPERTY_HINT_ENUM,
  2019. "ignore,keep,keep_width,keep_height,expand"));
  2020. GLOBAL_DEF_BASIC("display/window/stretch/shrink", 1.0);
  2021. ProjectSettings::get_singleton()->set_custom_property_info("display/window/stretch/shrink",
  2022. PropertyInfo(Variant::FLOAT,
  2023. "display/window/stretch/shrink",
  2024. PROPERTY_HINT_RANGE,
  2025. "1.0,8.0,0.1"));
  2026. sml->set_auto_accept_quit(GLOBAL_DEF("application/config/auto_accept_quit", true));
  2027. sml->set_quit_on_go_back(GLOBAL_DEF("application/config/quit_on_go_back", true));
  2028. GLOBAL_DEF_BASIC("gui/common/snap_controls_to_pixels", true);
  2029. GLOBAL_DEF_BASIC("gui/fonts/dynamic_fonts/use_oversampling", true);
  2030. GLOBAL_DEF_BASIC("rendering/textures/canvas_textures/default_texture_filter", 1);
  2031. ProjectSettings::get_singleton()->set_custom_property_info(
  2032. "rendering/textures/canvas_textures/default_texture_filter",
  2033. PropertyInfo(Variant::INT, "rendering/textures/canvas_textures/default_texture_filter", PROPERTY_HINT_ENUM,
  2034. "Nearest,Linear,Linear Mipmap,Nearest Mipmap"));
  2035. GLOBAL_DEF_BASIC("rendering/textures/canvas_textures/default_texture_repeat", 0);
  2036. ProjectSettings::get_singleton()->set_custom_property_info(
  2037. "rendering/textures/canvas_textures/default_texture_repeat",
  2038. PropertyInfo(Variant::INT, "rendering/textures/canvas_textures/default_texture_repeat", PROPERTY_HINT_ENUM,
  2039. "Disable,Enable,Mirror"));
  2040. }
  2041. #ifdef TOOLS_ENABLED
  2042. if (editor) {
  2043. bool editor_embed_subwindows = EditorSettings::get_singleton()->get_setting(
  2044. "interface/editor/single_window_mode");
  2045. if (editor_embed_subwindows) {
  2046. sml->get_root()->set_embed_subwindows_hint(true);
  2047. }
  2048. }
  2049. #endif
  2050. String local_game_path;
  2051. if (!game_path.is_empty() && !project_manager) {
  2052. local_game_path = game_path.replace("\\", "/");
  2053. if (!local_game_path.begins_with("res://")) {
  2054. bool absolute =
  2055. (local_game_path.size() > 1) && (local_game_path[0] == '/' || local_game_path[1] == ':');
  2056. if (!absolute) {
  2057. if (ProjectSettings::get_singleton()->is_using_datapack()) {
  2058. local_game_path = "res://" + local_game_path;
  2059. } else {
  2060. int sep = local_game_path.rfind("/");
  2061. if (sep == -1) {
  2062. DirAccess *da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
  2063. local_game_path = da->get_current_dir().plus_file(local_game_path);
  2064. memdelete(da);
  2065. } else {
  2066. DirAccess *da = DirAccess::open(local_game_path.substr(0, sep));
  2067. if (da) {
  2068. local_game_path = da->get_current_dir().plus_file(
  2069. local_game_path.substr(sep + 1, local_game_path.length()));
  2070. memdelete(da);
  2071. }
  2072. }
  2073. }
  2074. }
  2075. }
  2076. local_game_path = ProjectSettings::get_singleton()->localize_path(local_game_path);
  2077. #ifdef TOOLS_ENABLED
  2078. if (editor) {
  2079. if (game_path != String(GLOBAL_GET("application/run/main_scene")) || !editor_node->has_scenes_in_session()) {
  2080. Error serr = editor_node->load_scene(local_game_path);
  2081. if (serr != OK) {
  2082. ERR_PRINT("Failed to load scene");
  2083. }
  2084. }
  2085. DisplayServer::get_singleton()->set_context(DisplayServer::CONTEXT_EDITOR);
  2086. if (!debug_server_uri.is_empty()) {
  2087. EditorDebuggerNode::get_singleton()->start(debug_server_uri);
  2088. }
  2089. }
  2090. #endif
  2091. if (!editor) {
  2092. DisplayServer::get_singleton()->set_context(DisplayServer::CONTEXT_ENGINE);
  2093. }
  2094. }
  2095. if (!project_manager && !editor) { // game
  2096. // Load SSL Certificates from Project Settings (or builtin).
  2097. Crypto::load_default_certificates(GLOBAL_DEF("network/ssl/certificate_bundle_override", ""));
  2098. if (!game_path.is_empty()) {
  2099. Node *scene = nullptr;
  2100. Ref<PackedScene> scenedata = ResourceLoader::load(local_game_path);
  2101. if (scenedata.is_valid()) {
  2102. scene = scenedata->instantiate();
  2103. }
  2104. ERR_FAIL_COND_V_MSG(!scene, false, "Failed loading scene: " + local_game_path);
  2105. sml->add_current_scene(scene);
  2106. #ifdef OSX_ENABLED
  2107. String mac_iconpath = GLOBAL_DEF("application/config/macos_native_icon", "Variant()");
  2108. if (!mac_iconpath.is_empty()) {
  2109. DisplayServer::get_singleton()->set_native_icon(mac_iconpath);
  2110. hasicon = true;
  2111. }
  2112. #endif
  2113. #ifdef WINDOWS_ENABLED
  2114. String win_iconpath = GLOBAL_DEF("application/config/windows_native_icon", "Variant()");
  2115. if (!win_iconpath.is_empty()) {
  2116. DisplayServer::get_singleton()->set_native_icon(win_iconpath);
  2117. hasicon = true;
  2118. }
  2119. #endif
  2120. String iconpath = GLOBAL_DEF("application/config/icon", "Variant()");
  2121. if ((!iconpath.is_empty()) && (!hasicon)) {
  2122. Ref<Image> icon;
  2123. icon.instantiate();
  2124. if (ImageLoader::load_image(iconpath, icon) == OK) {
  2125. DisplayServer::get_singleton()->set_icon(icon);
  2126. hasicon = true;
  2127. }
  2128. }
  2129. }
  2130. }
  2131. #ifdef TOOLS_ENABLED
  2132. if (project_manager) {
  2133. Engine::get_singleton()->set_editor_hint(true);
  2134. ProjectManager *pmanager = memnew(ProjectManager);
  2135. ProgressDialog *progress_dialog = memnew(ProgressDialog);
  2136. pmanager->add_child(progress_dialog);
  2137. sml->get_root()->add_child(pmanager);
  2138. DisplayServer::get_singleton()->set_context(DisplayServer::CONTEXT_PROJECTMAN);
  2139. }
  2140. if (project_manager || editor) {
  2141. if (DisplayServer::get_singleton()->has_feature(DisplayServer::FEATURE_CONSOLE_WINDOW)) {
  2142. // Hide console window if requested (Windows-only).
  2143. bool hide_console = EditorSettings::get_singleton()->get_setting(
  2144. "interface/editor/hide_console_window");
  2145. DisplayServer::get_singleton()->console_set_visible(!hide_console);
  2146. }
  2147. // Load SSL Certificates from Editor Settings (or builtin)
  2148. Crypto::load_default_certificates(
  2149. EditorSettings::get_singleton()->get_setting("network/ssl/editor_ssl_certificates").operator String());
  2150. }
  2151. #endif
  2152. }
  2153. if (!hasicon && OS::get_singleton()->get_bundle_icon_path().is_empty()) {
  2154. Ref<Image> icon = memnew(Image(app_icon_png));
  2155. DisplayServer::get_singleton()->set_icon(icon);
  2156. }
  2157. OS::get_singleton()->set_main_loop(main_loop);
  2158. return true;
  2159. }
  2160. /* Main iteration
  2161. *
  2162. * This is the iteration of the engine's game loop, advancing the state of physics,
  2163. * rendering and audio.
  2164. * It's called directly by the platform's OS::run method, where the loop is created
  2165. * and monitored.
  2166. *
  2167. * The OS implementation can impact its draw step with the Main::force_redraw() method.
  2168. */
  2169. uint64_t Main::last_ticks = 0;
  2170. uint32_t Main::frames = 0;
  2171. uint32_t Main::frame = 0;
  2172. bool Main::force_redraw_requested = false;
  2173. int Main::iterating = 0;
  2174. bool Main::agile_input_event_flushing = false;
  2175. bool Main::is_iterating() {
  2176. return iterating > 0;
  2177. }
  2178. // For performance metrics.
  2179. static uint64_t physics_process_max = 0;
  2180. static uint64_t process_max = 0;
  2181. bool Main::iteration() {
  2182. //for now do not error on this
  2183. //ERR_FAIL_COND_V(iterating, false);
  2184. iterating++;
  2185. const uint64_t ticks = OS::get_singleton()->get_ticks_usec();
  2186. Engine::get_singleton()->_frame_ticks = ticks;
  2187. main_timer_sync.set_cpu_ticks_usec(ticks);
  2188. main_timer_sync.set_fixed_fps(fixed_fps);
  2189. const uint64_t ticks_elapsed = ticks - last_ticks;
  2190. const int physics_ticks_per_second = Engine::get_singleton()->get_physics_ticks_per_second();
  2191. const double physics_step = 1.0 / physics_ticks_per_second;
  2192. const double time_scale = Engine::get_singleton()->get_time_scale();
  2193. MainFrameTime advance = main_timer_sync.advance(physics_step, physics_ticks_per_second);
  2194. double process_step = advance.process_step;
  2195. double scaled_step = process_step * time_scale;
  2196. Engine::get_singleton()->_process_step = process_step;
  2197. Engine::get_singleton()->_physics_interpolation_fraction = advance.interpolation_fraction;
  2198. uint64_t physics_process_ticks = 0;
  2199. uint64_t process_ticks = 0;
  2200. frame += ticks_elapsed;
  2201. last_ticks = ticks;
  2202. static const int max_physics_steps = 8;
  2203. if (fixed_fps == -1 && advance.physics_steps > max_physics_steps) {
  2204. process_step -= (advance.physics_steps - max_physics_steps) * physics_step;
  2205. advance.physics_steps = max_physics_steps;
  2206. }
  2207. bool exit = false;
  2208. // process all our active interfaces
  2209. XRServer::get_singleton()->_process();
  2210. for (int iters = 0; iters < advance.physics_steps; ++iters) {
  2211. if (Input::get_singleton()->is_using_input_buffering() && agile_input_event_flushing) {
  2212. Input::get_singleton()->flush_buffered_events();
  2213. }
  2214. Engine::get_singleton()->_in_physics = true;
  2215. uint64_t physics_begin = OS::get_singleton()->get_ticks_usec();
  2216. PhysicsServer3D::get_singleton()->sync();
  2217. PhysicsServer3D::get_singleton()->flush_queries();
  2218. PhysicsServer2D::get_singleton()->sync();
  2219. PhysicsServer2D::get_singleton()->flush_queries();
  2220. if (OS::get_singleton()->get_main_loop()->physics_process(physics_step * time_scale)) {
  2221. exit = true;
  2222. break;
  2223. }
  2224. NavigationServer3D::get_singleton_mut()->process(physics_step * time_scale);
  2225. message_queue->flush();
  2226. PhysicsServer3D::get_singleton()->end_sync();
  2227. PhysicsServer3D::get_singleton()->step(physics_step * time_scale);
  2228. PhysicsServer2D::get_singleton()->end_sync();
  2229. PhysicsServer2D::get_singleton()->step(physics_step * time_scale);
  2230. message_queue->flush();
  2231. physics_process_ticks = MAX(physics_process_ticks, OS::get_singleton()->get_ticks_usec() - physics_begin); // keep the largest one for reference
  2232. physics_process_max = MAX(OS::get_singleton()->get_ticks_usec() - physics_begin, physics_process_max);
  2233. Engine::get_singleton()->_physics_frames++;
  2234. Engine::get_singleton()->_in_physics = false;
  2235. }
  2236. if (Input::get_singleton()->is_using_input_buffering() && agile_input_event_flushing) {
  2237. Input::get_singleton()->flush_buffered_events();
  2238. }
  2239. uint64_t process_begin = OS::get_singleton()->get_ticks_usec();
  2240. if (OS::get_singleton()->get_main_loop()->process(process_step * time_scale)) {
  2241. exit = true;
  2242. }
  2243. message_queue->flush();
  2244. RenderingServer::get_singleton()->sync(); //sync if still drawing from previous frames.
  2245. if (DisplayServer::get_singleton()->can_any_window_draw() &&
  2246. RenderingServer::get_singleton()->is_render_loop_enabled()) {
  2247. if ((!force_redraw_requested) && OS::get_singleton()->is_in_low_processor_usage_mode()) {
  2248. if (RenderingServer::get_singleton()->has_changed()) {
  2249. RenderingServer::get_singleton()->draw(true, scaled_step); // flush visual commands
  2250. Engine::get_singleton()->frames_drawn++;
  2251. }
  2252. } else {
  2253. RenderingServer::get_singleton()->draw(true, scaled_step); // flush visual commands
  2254. Engine::get_singleton()->frames_drawn++;
  2255. force_redraw_requested = false;
  2256. }
  2257. }
  2258. process_ticks = OS::get_singleton()->get_ticks_usec() - process_begin;
  2259. process_max = MAX(process_ticks, process_max);
  2260. uint64_t frame_time = OS::get_singleton()->get_ticks_usec() - ticks;
  2261. for (int i = 0; i < ScriptServer::get_language_count(); i++) {
  2262. ScriptServer::get_language(i)->frame();
  2263. }
  2264. AudioServer::get_singleton()->update();
  2265. if (EngineDebugger::is_active()) {
  2266. EngineDebugger::get_singleton()->iteration(frame_time, process_ticks, physics_process_ticks, physics_step);
  2267. }
  2268. frames++;
  2269. Engine::get_singleton()->_process_frames++;
  2270. if (frame > 1000000) {
  2271. if (editor || project_manager) {
  2272. if (print_fps) {
  2273. print_line(vformat("Editor FPS: %d (%s mspf)", frames, rtos(1000.0 / frames).pad_decimals(2)));
  2274. }
  2275. } else if (GLOBAL_GET("debug/settings/stdout/print_fps") || print_fps) {
  2276. print_line(vformat("Project FPS: %d (%s mspf)", frames, rtos(1000.0 / frames).pad_decimals(2)));
  2277. }
  2278. Engine::get_singleton()->_fps = frames;
  2279. performance->set_process_time(USEC_TO_SEC(process_max));
  2280. performance->set_physics_process_time(USEC_TO_SEC(physics_process_max));
  2281. process_max = 0;
  2282. physics_process_max = 0;
  2283. frame %= 1000000;
  2284. frames = 0;
  2285. }
  2286. iterating--;
  2287. // Needed for OSs using input buffering regardless accumulation (like Android)
  2288. if (Input::get_singleton()->is_using_input_buffering() && !agile_input_event_flushing) {
  2289. Input::get_singleton()->flush_buffered_events();
  2290. }
  2291. if (fixed_fps != -1) {
  2292. return exit;
  2293. }
  2294. OS::get_singleton()->add_frame_delay(DisplayServer::get_singleton()->window_can_draw());
  2295. #ifdef TOOLS_ENABLED
  2296. if (auto_build_solutions) {
  2297. auto_build_solutions = false;
  2298. // Only relevant when running the editor.
  2299. if (!editor) {
  2300. ERR_FAIL_V_MSG(true,
  2301. "Command line option --build-solutions was passed, but no project is being edited. Aborting.");
  2302. }
  2303. if (!EditorNode::get_singleton()->call_build()) {
  2304. ERR_FAIL_V_MSG(true,
  2305. "Command line option --build-solutions was passed, but the build callback failed. Aborting.");
  2306. }
  2307. }
  2308. #endif
  2309. return exit || auto_quit;
  2310. }
  2311. void Main::force_redraw() {
  2312. force_redraw_requested = true;
  2313. }
  2314. /* Engine deinitialization
  2315. *
  2316. * Responsible for freeing all the memory allocated by previous setup steps,
  2317. * so that the engine closes cleanly without leaking memory or crashing.
  2318. * The order matters as some of those steps are linked with each other.
  2319. */
  2320. void Main::cleanup(bool p_force) {
  2321. if (!p_force) {
  2322. ERR_FAIL_COND(!_start_success);
  2323. }
  2324. EngineDebugger::deinitialize();
  2325. ResourceLoader::remove_custom_loaders();
  2326. ResourceSaver::remove_custom_savers();
  2327. // Flush before uninitializing the scene, but delete the MessageQueue as late as possible.
  2328. message_queue->flush();
  2329. OS::get_singleton()->delete_main_loop();
  2330. OS::get_singleton()->_cmdline.clear();
  2331. OS::get_singleton()->_execpath = "";
  2332. OS::get_singleton()->_local_clipboard = "";
  2333. ResourceLoader::clear_translation_remaps();
  2334. ResourceLoader::clear_path_remaps();
  2335. ScriptServer::finish_languages();
  2336. // Sync pending commands that may have been queued from a different thread during ScriptServer finalization
  2337. RenderingServer::get_singleton()->sync();
  2338. //clear global shader variables before scene and other graphics stuff are deinitialized.
  2339. rendering_server->global_variables_clear();
  2340. if (xr_server) {
  2341. // Now that we're unregistering properly in plugins we need to keep access to xr_server for a little longer
  2342. // We do however unset our primary interface
  2343. xr_server->set_primary_interface(Ref<XRInterface>());
  2344. }
  2345. unregister_driver_types();
  2346. #ifdef TOOLS_ENABLED
  2347. EditorNode::unregister_editor_types();
  2348. #endif
  2349. ImageLoader::cleanup();
  2350. unregister_module_types();
  2351. unregister_platform_apis();
  2352. unregister_scene_types();
  2353. unregister_server_types();
  2354. if (xr_server) {
  2355. memdelete(xr_server);
  2356. }
  2357. if (audio_server) {
  2358. audio_server->finish();
  2359. memdelete(audio_server);
  2360. }
  2361. if (camera_server) {
  2362. memdelete(camera_server);
  2363. }
  2364. OS::get_singleton()->finalize();
  2365. finalize_physics();
  2366. finalize_navigation_server();
  2367. finalize_display();
  2368. if (input) {
  2369. memdelete(input);
  2370. }
  2371. if (packed_data) {
  2372. memdelete(packed_data);
  2373. }
  2374. if (file_access_network_client) {
  2375. memdelete(file_access_network_client);
  2376. }
  2377. if (performance) {
  2378. memdelete(performance);
  2379. }
  2380. if (input_map) {
  2381. memdelete(input_map);
  2382. }
  2383. if (time_singleton) {
  2384. memdelete(time_singleton);
  2385. }
  2386. if (translation_server) {
  2387. memdelete(translation_server);
  2388. }
  2389. if (tsman) {
  2390. memdelete(tsman);
  2391. }
  2392. if (globals) {
  2393. memdelete(globals);
  2394. }
  2395. if (engine) {
  2396. memdelete(engine);
  2397. }
  2398. if (OS::get_singleton()->is_restart_on_exit_set()) {
  2399. //attempt to restart with arguments
  2400. List<String> args = OS::get_singleton()->get_restart_on_exit_arguments();
  2401. OS::get_singleton()->create_instance(args);
  2402. OS::get_singleton()->set_restart_on_exit(false, List<String>()); //clear list (uses memory)
  2403. }
  2404. // Now should be safe to delete MessageQueue (famous last words).
  2405. message_queue->flush();
  2406. memdelete(message_queue);
  2407. unregister_core_driver_types();
  2408. unregister_core_types();
  2409. OS::get_singleton()->finalize_core();
  2410. }