main.cpp 103 KB

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