PageRenderTime 55ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 1ms

/main/main.cpp

https://github.com/Hubich/godot
C++ | 1437 lines | 974 code | 395 blank | 68 comment | 311 complexity | 716678d6488d672c09e1208b4b06a7c7 MD5 | raw file
  1. /*************************************************************************/
  2. /* main.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* http://www.godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  9. /* */
  10. /* Permission is hereby granted, free of charge, to any person obtaining */
  11. /* a copy of this software and associated documentation files (the */
  12. /* "Software"), to deal in the Software without restriction, including */
  13. /* without limitation the rights to use, copy, modify, merge, publish, */
  14. /* distribute, sublicense, and/or sell copies of the Software, and to */
  15. /* permit persons to whom the Software is furnished to do so, subject to */
  16. /* the following conditions: */
  17. /* */
  18. /* The above copyright notice and this permission notice shall be */
  19. /* included in all copies or substantial portions of the Software. */
  20. /* */
  21. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  22. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  23. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
  24. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  25. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  26. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  27. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  28. /*************************************************************************/
  29. #include "main.h"
  30. #include "os/os.h"
  31. #include "globals.h"
  32. #include "splash.h"
  33. #include "core/register_core_types.h"
  34. #include "scene/register_scene_types.h"
  35. #include "drivers/register_driver_types.h"
  36. #include "servers/register_server_types.h"
  37. #include "modules/register_module_types.h"
  38. #include "script_debugger_local.h"
  39. #include "script_debugger_remote.h"
  40. #include "message_queue.h"
  41. #include "path_remap.h"
  42. #include "input_map.h"
  43. #include "io/resource_loader.h"
  44. #include "scene/main/scene_main_loop.h"
  45. #include "scene/io/scene_loader.h"
  46. #include "script_language.h"
  47. #include "io/resource_loader.h"
  48. #include "bin/tests/test_main.h"
  49. #include "os/dir_access.h"
  50. #include "core/io/ip.h"
  51. #include "scene/resources/packed_scene.h"
  52. #include "scene/main/viewport.h"
  53. #ifdef TOOLS_ENABLED
  54. #include "tools/editor/editor_node.h"
  55. #include "tools/editor/project_manager.h"
  56. #include "tools/editor/console.h"
  57. #endif
  58. #include "io/file_access_network.h"
  59. #include "tools/doc/doc_data.h"
  60. #include "servers/spatial_sound_server.h"
  61. #include "servers/spatial_sound_2d_server.h"
  62. #include "servers/physics_2d_server.h"
  63. #include "core/io/stream_peer_tcp.h"
  64. #include "core/os/thread.h"
  65. #include "core/io/file_access_pack.h"
  66. #include "core/io/file_access_zip.h"
  67. #include "translation.h"
  68. #include "version.h"
  69. #include "performance.h"
  70. static Globals *globals=NULL;
  71. static InputMap *input_map=NULL;
  72. static bool _start_success=false;
  73. static ScriptDebugger *script_debugger=NULL;
  74. static MessageQueue *message_queue=NULL;
  75. static Performance *performance = NULL;
  76. static PathRemap *path_remap;
  77. static PackedData *packed_data=NULL;
  78. static FileAccessNetworkClient *file_access_network_client=NULL;
  79. static TranslationServer *translation_server = NULL;
  80. static OS::VideoMode video_mode;
  81. static int video_driver_idx=-1;
  82. static int audio_driver_idx=-1;
  83. static String locale;
  84. static String unescape_cmdline(const String& p_str) {
  85. return p_str.replace("%20"," ");
  86. }
  87. //#define DEBUG_INIT
  88. #ifdef DEBUG_INIT
  89. #define MAIN_PRINT(m_txt) print_line(m_txt)
  90. #else
  91. #define MAIN_PRINT(m_txt)
  92. #endif
  93. void Main::print_help(const char* p_binary) {
  94. OS::get_singleton()->print(VERSION_FULL_NAME" (c) 2008-2010 Juan Linietsky, Ariel Manzur.\n");
  95. OS::get_singleton()->print("Usage: %s [options] [scene]\n",p_binary);
  96. OS::get_singleton()->print("Options:\n");
  97. OS::get_singleton()->print("\t-path [dir] : Path to a game, containing engine.cfg\n");
  98. #ifdef TOOLS_ENABLED
  99. OS::get_singleton()->print("\t-e,-editor : Bring up the editor instead of running the scene.\n");
  100. #endif
  101. OS::get_singleton()->print("\t-test [test] : Run a test.\n");
  102. OS::get_singleton()->print("\t\t(");
  103. const char **test_names=tests_get_names();
  104. const char* coma = "";
  105. while(*test_names) {
  106. OS::get_singleton()->print("%s%s", coma, *test_names);
  107. test_names++;
  108. coma = ", ";
  109. }
  110. OS::get_singleton()->print(")\n");
  111. OS::get_singleton()->print("\t-r WIDTHxHEIGHT\t : Request Screen Resolution\n");
  112. OS::get_singleton()->print("\t-f\t\t : Request Fullscreen\n");
  113. OS::get_singleton()->print("\t-vd DRIVER\t : Video Driver (");
  114. for (int i=0;i<OS::get_singleton()->get_video_driver_count();i++) {
  115. if (i!=0)
  116. OS::get_singleton()->print(", ");
  117. OS::get_singleton()->print("%s",OS::get_singleton()->get_video_driver_name(i));
  118. }
  119. OS::get_singleton()->print(")\n");
  120. OS::get_singleton()->print("\t-ad DRIVER\t : Audio Driver (");
  121. for (int i=0;i<OS::get_singleton()->get_audio_driver_count();i++) {
  122. if (i!=0)
  123. OS::get_singleton()->print(", ");
  124. OS::get_singleton()->print("%s",OS::get_singleton()->get_audio_driver_name(i));
  125. }
  126. OS::get_singleton()->print("\t-rthread <mode>\t : Render Thread Mode ('unsafe', 'safe', 'separate).");
  127. OS::get_singleton()->print(")\n");
  128. OS::get_singleton()->print("\t-s,-script [script] : Run a script.\n");
  129. OS::get_singleton()->print("\t-d,-debug : Debug (local stdout debugger).\n");
  130. OS::get_singleton()->print("\t-rdebug ADDRESS : Remote debug (<ip>:<port> host address).\n");
  131. OS::get_singleton()->print("\t-fdelay [msec]: Simulate high CPU load (delay each frame by [msec]).\n");
  132. OS::get_singleton()->print("\t-bp : breakpoint list as source::line comma separated pairs, no spaces (%%20,%%2C,etc instead).\n");
  133. OS::get_singleton()->print("\t-v : Verbose stdout mode\n");
  134. OS::get_singleton()->print("\t-lang [locale]: Use a specific locale\n");
  135. OS::get_singleton()->print("\t-rfs <host/ip>[:<port>] : Remote FileSystem.\n");
  136. OS::get_singleton()->print("\t-rfs_pass <password> : Password for Remote FileSystem.\n");
  137. #ifdef TOOLS_ENABLED
  138. OS::get_singleton()->print("\t-doctool FILE: Dump the whole engine api to FILE in XML format. If FILE exists, it will be merged.\n");
  139. OS::get_singleton()->print("\t-nodocbase: Disallow dump the base types (used with -doctool).\n");
  140. OS::get_singleton()->print("\t-optimize FILE Save an optimized copy of scene to FILE.\n");
  141. OS::get_singleton()->print("\t-optimize_preset [preset] Use a given preset for optimization.\n");
  142. OS::get_singleton()->print("\t-export [target] Export the project using given export target.\n");
  143. #endif
  144. }
  145. Error Main::setup(const char *execpath,int argc, char *argv[],bool p_second_phase) {
  146. RID_OwnerBase::init_rid();
  147. OS::get_singleton()->initialize_core();
  148. ObjectTypeDB::init();
  149. MAIN_PRINT("Main: Initialize CORE");
  150. register_core_types();
  151. register_core_driver_types();
  152. MAIN_PRINT("Main: Initialize Globals");
  153. Thread::_main_thread_id = Thread::get_caller_ID();
  154. globals = memnew( Globals );
  155. input_map = memnew( InputMap );
  156. path_remap = memnew( PathRemap );
  157. translation_server = memnew( TranslationServer );
  158. performance = memnew( Performance );
  159. globals->add_singleton(Globals::Singleton("Performance",performance));
  160. MAIN_PRINT("Main: Parse CMDLine");
  161. /* argument parsing and main creation */
  162. List<String> args;
  163. List<String> main_args;
  164. for(int i=0;i<argc;i++) {
  165. args.push_back(String::utf8(argv[i]));
  166. }
  167. List<String>::Element *I=args.front();
  168. I=args.front();
  169. while (I) {
  170. I->get()=unescape_cmdline(I->get().strip_escapes());
  171. I=I->next();
  172. }
  173. I=args.front();
  174. video_mode = OS::get_singleton()->get_default_video_mode();
  175. String video_driver="";
  176. String audio_driver="";
  177. String game_path=".";
  178. String debug_mode;
  179. String debug_host;
  180. int rtm=-1;
  181. String remotefs;
  182. String remotefs_pass;
  183. String screen = "";
  184. List<String> pack_list;
  185. Vector<String> breakpoints;
  186. bool use_custom_res=true;
  187. bool force_res=false;
  188. I=args.front();
  189. packed_data = PackedData::get_singleton();
  190. if (!packed_data)
  191. packed_data = memnew(PackedData);
  192. #ifdef MINIZIP_ENABLED
  193. packed_data->add_pack_source(ZipArchive::get_singleton());
  194. #endif
  195. bool editor=false;
  196. while(I) {
  197. List<String>::Element *N=I->next();
  198. if (I->get() == "-noop") {
  199. // no op
  200. } else if (I->get()=="-h" || I->get()=="--help" || I->get()=="/?") { // resolution
  201. goto error;
  202. } else if (I->get()=="-r") { // resolution
  203. if (I->next()) {
  204. String vm=I->next()->get();
  205. if (vm.find("x")==-1) { // invalid parameter format
  206. goto error;
  207. }
  208. int w=vm.get_slice("x",0).to_int();
  209. int h=vm.get_slice("x",1).to_int();
  210. if (w==0 || h==0) {
  211. goto error;
  212. }
  213. video_mode.width=w;
  214. video_mode.height=h;
  215. force_res=true;
  216. N=I->next()->next();
  217. } else {
  218. goto error;
  219. }
  220. } else if (I->get()=="-vd") { // video driver
  221. if (I->next()) {
  222. video_driver=I->next()->get();
  223. N=I->next()->next();
  224. } else {
  225. goto error;
  226. }
  227. } else if (I->get()=="-lang") { // language
  228. if (I->next()) {
  229. locale=I->next()->get();
  230. N=I->next()->next();
  231. } else {
  232. goto error;
  233. }
  234. } else if (I->get()=="-rfs") { // language
  235. if (I->next()) {
  236. remotefs=I->next()->get();
  237. N=I->next()->next();
  238. } else {
  239. goto error;
  240. }
  241. } else if (I->get()=="-rfs_pass") { // language
  242. if (I->next()) {
  243. remotefs_pass=I->next()->get();
  244. N=I->next()->next();
  245. } else {
  246. goto error;
  247. }
  248. } else if (I->get()=="-rthread") { // language
  249. if (I->next()) {
  250. if (I->next()->get()=="safe")
  251. rtm=OS::RENDER_THREAD_SAFE;
  252. else if (I->next()->get()=="unsafe")
  253. rtm=OS::RENDER_THREAD_UNSAFE;
  254. else if (I->next()->get()=="separate")
  255. rtm=OS::RENDER_SEPARATE_THREAD;
  256. N=I->next()->next();
  257. } else {
  258. goto error;
  259. }
  260. } else if (I->get()=="-ad") { // video driver
  261. if (I->next()) {
  262. audio_driver=I->next()->get();
  263. N=I->next()->next();
  264. } else {
  265. goto error;
  266. }
  267. } else if (I->get()=="-f") { // fullscreen
  268. video_mode.fullscreen=true;
  269. } else if (I->get()=="-e" || I->get()=="-editor") { // fonud editor
  270. editor=true;
  271. } else if (I->get()=="-nowindow") { // fullscreen
  272. OS::get_singleton()->set_no_window_mode(true);
  273. } else if (I->get()=="-v") { // fullscreen
  274. OS::get_singleton()->_verbose_stdout=true;
  275. } else if (I->get()=="-path") { // resolution
  276. if (I->next()) {
  277. String p = I->next()->get();
  278. if (OS::get_singleton()->set_cwd(p)==OK) {
  279. //nothing
  280. } else {
  281. game_path=I->next()->get(); //use game_path instead
  282. }
  283. N=I->next()->next();
  284. } else {
  285. goto error;
  286. }
  287. } else if (I->get()=="-bp") { // /breakpoints
  288. if (I->next()) {
  289. String bplist = I->next()->get();
  290. breakpoints= bplist.split(",");
  291. N=I->next()->next();
  292. } else {
  293. goto error;
  294. }
  295. } else if (I->get()=="-fdelay") { // resolution
  296. if (I->next()) {
  297. OS::get_singleton()->set_frame_delay(I->next()->get().to_int());
  298. N=I->next()->next();
  299. } else {
  300. goto error;
  301. }
  302. } else if (I->get() == "-pack") {
  303. if (I->next()) {
  304. pack_list.push_back(I->next()->get());
  305. N = I->next()->next();
  306. } else {
  307. goto error;
  308. };
  309. } else if (I->get()=="-debug" || I->get()=="-d") {
  310. debug_mode="local";
  311. } else if (I->get()=="-editor_scene") {
  312. if (I->next()) {
  313. Globals::get_singleton()->set("editor_scene",game_path=I->next()->get());
  314. } else {
  315. goto error;
  316. }
  317. } else if (I->get()=="-rdebug") {
  318. if (I->next()) {
  319. debug_mode="remote";
  320. debug_host=I->next()->get();
  321. if (debug_host.find(":")==-1) //wrong host
  322. goto error;
  323. N=I->next()->next();
  324. } else {
  325. goto error;
  326. }
  327. } else {
  328. //test for game path
  329. bool gpfound=false;
  330. if (!I->get().begins_with("-") && game_path=="") {
  331. DirAccess* da = DirAccess::open(I->get());
  332. if (da!=NULL) {
  333. game_path=I->get();
  334. gpfound=true;
  335. memdelete(da);
  336. }
  337. }
  338. if (!gpfound) {
  339. main_args.push_back(I->get());
  340. }
  341. }
  342. I=N;
  343. }
  344. if (debug_mode == "remote") {
  345. ScriptDebuggerRemote *sdr = memnew( ScriptDebuggerRemote );
  346. uint16_t debug_port = GLOBAL_DEF("debug/remote_port",6007);
  347. if (debug_host.find(":")!=-1) {
  348. debug_port=debug_host.get_slice(":",1).to_int();
  349. debug_host=debug_host.get_slice(":",0);
  350. }
  351. Error derr = sdr->connect_to_host(debug_host,debug_port);
  352. if (derr!=OK) {
  353. memdelete(sdr);
  354. } else {
  355. script_debugger=sdr;
  356. }
  357. } else if (debug_mode=="local") {
  358. script_debugger = memnew( ScriptDebuggerLocal );
  359. }
  360. if (remotefs!="") {
  361. file_access_network_client=memnew(FileAccessNetworkClient);
  362. int port;
  363. if (remotefs.find(":")!=-1) {
  364. port=remotefs.get_slice(":",1).to_int();
  365. remotefs=remotefs.get_slice(":",0);
  366. } else {
  367. port=6010;
  368. }
  369. Error err = file_access_network_client->connect(remotefs,port,remotefs_pass);
  370. if (err) {
  371. OS::get_singleton()->printerr("Could not connect to remotefs: %s:%i\n",remotefs.utf8().get_data(),port);
  372. goto error;
  373. }
  374. FileAccess::make_default<FileAccessNetwork>(FileAccess::ACCESS_RESOURCES);
  375. }
  376. if (script_debugger) {
  377. //there is a debugger, parse breakpoints
  378. for(int i=0;i<breakpoints.size();i++) {
  379. String bp = breakpoints[i];
  380. int sp=bp.find_last(":");
  381. if (sp==-1) {
  382. ERR_EXPLAIN("Invalid breakpoint: '"+bp+"', expected file:line format.");
  383. ERR_CONTINUE(sp==-1);
  384. }
  385. script_debugger->insert_breakpoint(bp.substr(sp+1,bp.length()).to_int(),bp.substr(0,sp));
  386. }
  387. }
  388. #ifdef TOOLS_ENABLED
  389. if (editor) {
  390. packed_data->set_disabled(true);
  391. globals->set_disable_platform_override(true);
  392. }
  393. #endif
  394. if (globals->setup(game_path)!=OK) {
  395. #ifdef TOOLS_ENABLED
  396. editor=false;
  397. #else
  398. OS::get_singleton()->print("error: Couldn't load game path '%s'\n",game_path.ascii().get_data());
  399. goto error;
  400. #endif
  401. }
  402. if (editor) {
  403. main_args.push_back("-editor");
  404. use_custom_res=false;
  405. }
  406. OS::get_singleton()->set_cmdline(execpath, main_args);
  407. #ifdef TOOLS_ENABLED
  408. if (main_args.size()==0 && (!Globals::get_singleton()->has("application/main_loop_type")) && (!Globals::get_singleton()->has("application/main_scene") || String(Globals::get_singleton()->get("application/main_scene"))==""))
  409. use_custom_res=false; //project manager (run without arguments)
  410. #endif
  411. input_map->load_from_globals();
  412. if (video_driver=="") // specified in engine.cfg
  413. video_driver=_GLOBAL_DEF("display/driver",Variant((const char*)OS::get_singleton()->get_video_driver_name(0)));
  414. if (!force_res && use_custom_res && globals->has("display/width"))
  415. video_mode.width=globals->get("display/width");
  416. if (!force_res &&use_custom_res && globals->has("display/height"))
  417. video_mode.height=globals->get("display/height");
  418. if (use_custom_res && globals->has("display/fullscreen"))
  419. video_mode.fullscreen=globals->get("display/fullscreen");
  420. if (use_custom_res && globals->has("display/resizable"))
  421. video_mode.resizable=globals->get("display/resizable");
  422. GLOBAL_DEF("display/width",video_mode.width);
  423. GLOBAL_DEF("display/height",video_mode.height);
  424. GLOBAL_DEF("display/fullscreen",video_mode.fullscreen);
  425. GLOBAL_DEF("display/resizable",video_mode.resizable);
  426. if (rtm==-1) {
  427. rtm=GLOBAL_DEF("render/thread_model",OS::RENDER_THREAD_SAFE);
  428. }
  429. if (rtm>=0 && rtm<3)
  430. OS::get_singleton()->_render_thread_mode=OS::RenderThreadMode(rtm);
  431. /* Determine Video Driver */
  432. if (audio_driver=="") // specified in engine.cfg
  433. audio_driver=GLOBAL_DEF("audio/driver",OS::get_singleton()->get_audio_driver_name(0));
  434. for (int i=0;i<OS::get_singleton()->get_video_driver_count();i++) {
  435. if (video_driver==OS::get_singleton()->get_video_driver_name(i)) {
  436. video_driver_idx=i;
  437. break;
  438. }
  439. }
  440. if (video_driver_idx<0) {
  441. OS::get_singleton()->alert( "Invalid Video Driver: "+video_driver );
  442. video_driver_idx = 0;
  443. //goto error;
  444. }
  445. for (int i=0;i<OS::get_singleton()->get_audio_driver_count();i++) {
  446. if (audio_driver==OS::get_singleton()->get_audio_driver_name(i)) {
  447. audio_driver_idx=i;
  448. break;
  449. }
  450. }
  451. if (audio_driver_idx<0) {
  452. OS::get_singleton()->alert( "Invalid Audio Driver: "+audio_driver );
  453. goto error;
  454. }
  455. {
  456. String orientation = GLOBAL_DEF("display/orientation","landscape");
  457. if (orientation=="portrait")
  458. OS::get_singleton()->set_screen_orientation(OS::SCREEN_PORTRAIT);
  459. else if (orientation=="reverse_landscape")
  460. OS::get_singleton()->set_screen_orientation(OS::SCREEN_REVERSE_LANDSCAPE);
  461. else if (orientation=="reverse_portrait")
  462. OS::get_singleton()->set_screen_orientation(OS::SCREEN_REVERSE_PORTRAIT);
  463. else if (orientation=="sensor_landscape")
  464. OS::get_singleton()->set_screen_orientation(OS::SCREEN_SENSOR_LANDSCAPE);
  465. else if (orientation=="sensor_portrait")
  466. OS::get_singleton()->set_screen_orientation(OS::SCREEN_SENSOR_PORTRAIT);
  467. else if (orientation=="sensor")
  468. OS::get_singleton()->set_screen_orientation(OS::SCREEN_SENSOR);
  469. else
  470. OS::get_singleton()->set_screen_orientation(OS::SCREEN_LANDSCAPE);
  471. }
  472. OS::get_singleton()->set_iterations_per_second(GLOBAL_DEF("physics/fixed_fps",60));
  473. OS::get_singleton()->set_target_fps(GLOBAL_DEF("application/target_fps",0));
  474. if (!OS::get_singleton()->_verbose_stdout) //overrided
  475. OS::get_singleton()->_verbose_stdout=GLOBAL_DEF("debug/verbose_stdout",false);
  476. message_queue = memnew( MessageQueue );
  477. Globals::get_singleton()->register_global_defaults();
  478. if (p_second_phase)
  479. return setup2();
  480. return OK;
  481. error:
  482. video_driver="";
  483. audio_driver="";
  484. game_path="";
  485. args.clear();
  486. main_args.clear();
  487. print_help(execpath);
  488. if (performance)
  489. memdelete(performance);
  490. if (input_map)
  491. memdelete(input_map);
  492. if (translation_server)
  493. memdelete( translation_server );
  494. if (globals)
  495. memdelete(globals);
  496. if (script_debugger)
  497. memdelete(script_debugger);
  498. if (packed_data)
  499. memdelete(packed_data);
  500. if (file_access_network_client)
  501. memdelete(file_access_network_client);
  502. unregister_core_types();
  503. OS::get_singleton()->_cmdline.clear();
  504. if (message_queue)
  505. memdelete( message_queue);
  506. OS::get_singleton()->finalize_core();
  507. locale=String();
  508. return ERR_INVALID_PARAMETER;
  509. }
  510. Error Main::setup2() {
  511. OS::get_singleton()->initialize(video_mode,video_driver_idx,audio_driver_idx);
  512. register_core_singletons();
  513. MAIN_PRINT("Main: Setup Logo");
  514. bool show_logo=true;
  515. #ifdef JAVASCRIPT_ENABLED
  516. show_logo=false;
  517. #endif
  518. if (show_logo) { //boot logo!
  519. Image boot_logo=GLOBAL_DEF("application/boot_logo",Image());
  520. if (!boot_logo.empty()) {
  521. Color clear = GLOBAL_DEF("render/default_clear_color",Color(0.3,0.3,0.3));
  522. VisualServer::get_singleton()->set_default_clear_color(clear);
  523. Color boot_bg = GLOBAL_DEF("application/boot_bg_color", clear);
  524. VisualServer::get_singleton()->set_boot_image(boot_logo, boot_bg);
  525. #ifndef TOOLS_ENABLED
  526. //no tools, so free the boot logo (no longer needed)
  527. Globals::get_singleton()->set("application/boot_logo",Image());
  528. #endif
  529. } else {
  530. #ifndef NO_DEFAULT_BOOT_LOGO
  531. MAIN_PRINT("Main: Create botsplash");
  532. Image splash(boot_splash_png);
  533. MAIN_PRINT("Main: ClearColor");
  534. VisualServer::get_singleton()->set_default_clear_color(boot_splash_bg_color);
  535. MAIN_PRINT("Main: Image");
  536. VisualServer::get_singleton()->set_boot_image(splash, boot_splash_bg_color);
  537. #endif
  538. MAIN_PRINT("Main: DCC");
  539. VisualServer::get_singleton()->set_default_clear_color(GLOBAL_DEF("render/default_clear_color",Color(0.3,0.3,0.3)));
  540. MAIN_PRINT("Main: END");
  541. }
  542. Image icon(app_icon_png);
  543. OS::get_singleton()->set_icon(icon);
  544. }
  545. GLOBAL_DEF("application/icon",String());
  546. Globals::get_singleton()->set_custom_property_info("application/icon",PropertyInfo(Variant::STRING,"application/icon",PROPERTY_HINT_FILE,"*.png,*.webp"));
  547. MAIN_PRINT("Main: Load Remaps");
  548. path_remap->load_remaps();
  549. MAIN_PRINT("Main: Load Scene Types");
  550. register_scene_types();
  551. register_server_types();
  552. #ifdef TOOLS_ENABLED
  553. EditorNode::register_editor_types();
  554. #endif
  555. MAIN_PRINT("Main: Load Scripts, Modules, Drivers");
  556. register_module_types();
  557. register_driver_types();
  558. MAIN_PRINT("Main: Load Translations");
  559. translation_server->setup(); //register translations, load them, etc.
  560. if (locale!="") {
  561. translation_server->set_locale(locale);
  562. }
  563. translation_server->load_translations();
  564. _start_success=true;
  565. locale=String();
  566. MAIN_PRINT("Main: Done");
  567. return OK;
  568. }
  569. bool Main::start() {
  570. ERR_FAIL_COND_V(!_start_success,false);
  571. bool editor=false;
  572. String doc_tool;
  573. bool doc_base=true;
  574. String game_path;
  575. String script;
  576. String test;
  577. String screen;
  578. String optimize;
  579. String optimize_preset;
  580. String _export_platform;
  581. String _import;
  582. String _import_script;
  583. String dumpstrings;
  584. bool noquit=false;
  585. bool convert_old=false;
  586. bool export_debug=false;
  587. List<String> args = OS::get_singleton()->get_cmdline_args();
  588. for (int i=0;i<args.size();i++) {
  589. if (args[i]=="-doctool" && i <(args.size()-1)) {
  590. doc_tool=args[i+1];
  591. i++;
  592. }else if (args[i]=="-nodocbase") {
  593. doc_base=false;
  594. } else if ((args[i]=="-script" || args[i]=="-s") && i <(args.size()-1)) {
  595. script=args[i+1];
  596. i++;
  597. } else if ((args[i]=="-level" || args[i]=="-l") && i <(args.size()-1)) {
  598. OS::get_singleton()->_custom_level=args[i+1];
  599. i++;
  600. } else if (args[i]=="-test" && i <(args.size()-1)) {
  601. test=args[i+1];
  602. i++;
  603. } else if (args[i]=="-optimize" && i <(args.size()-1)) {
  604. optimize=args[i+1];
  605. i++;
  606. } else if (args[i]=="-optimize_preset" && i <(args.size()-1)) {
  607. optimize_preset=args[i+1];
  608. i++;
  609. } else if (args[i]=="-export" && i <(args.size()-1)) {
  610. editor=true; //needs editor
  611. _export_platform=args[i+1];
  612. i++;
  613. } else if (args[i]=="-export_debug" && i <(args.size()-1)) {
  614. editor=true; //needs editor
  615. _export_platform=args[i+1];
  616. export_debug=true;
  617. i++;
  618. } else if (args[i]=="-import" && i <(args.size()-1)) {
  619. editor=true; //needs editor
  620. _import=args[i+1];
  621. i++;
  622. } else if (args[i]=="-import_script" && i <(args.size()-1)) {
  623. editor=true; //needs editor
  624. _import_script=args[i+1];
  625. i++;
  626. } else if (args[i]=="-noquit" ) {
  627. noquit=true;
  628. } else if (args[i]=="-dumpstrings" && i <(args.size()-1)) {
  629. editor=true; //needs editor
  630. dumpstrings=args[i+1];
  631. i++;
  632. } else if (args[i]=="-editor" || args[i]=="-e") {
  633. editor=true;
  634. } else if (args[i]=="-convert_old") {
  635. convert_old=true;
  636. } else if (args[i].length() && args[i][0] != '-' && game_path == "") {
  637. game_path=args[i];
  638. }
  639. }
  640. if (editor)
  641. Globals::get_singleton()->set("editor_active",true);
  642. String main_loop_type;
  643. #ifdef TOOLS_ENABLED
  644. if(doc_tool!="") {
  645. DocData doc;
  646. doc.generate(doc_base);
  647. DocData docsrc;
  648. if (docsrc.load(doc_tool)==OK) {
  649. print_line("Doc exists. Merging..");
  650. doc.merge_from(docsrc);
  651. } else {
  652. print_line("No Doc exists. Generating empty.");
  653. }
  654. doc.save(doc_tool);
  655. return false;
  656. }
  657. if (optimize!="")
  658. editor=true; //need editor
  659. #endif
  660. if(script=="" && game_path=="" && !editor && String(GLOBAL_DEF("application/main_scene",""))!="") {
  661. game_path=GLOBAL_DEF("application/main_scene","");
  662. }
  663. MainLoop *main_loop=NULL;
  664. if (editor) {
  665. main_loop = memnew(SceneMainLoop);
  666. };
  667. if (test!="") {
  668. #ifdef DEBUG_ENABLED
  669. main_loop = test_main(test,args);
  670. if (!main_loop)
  671. return false;
  672. #endif
  673. } else if (script!="") {
  674. Ref<Script> script_res = ResourceLoader::load(script);
  675. ERR_EXPLAIN("Can't load script: "+script);
  676. ERR_FAIL_COND_V(script_res.is_null(),false);
  677. if( script_res->can_instance() /*&& script_res->inherits_from("SceneMainLoopScripted")*/) {
  678. StringName instance_type=script_res->get_instance_base_type();
  679. Object *obj = ObjectTypeDB::instance(instance_type);
  680. MainLoop *script_loop = obj?obj->cast_to<MainLoop>():NULL;
  681. if (!script_loop) {
  682. if (obj)
  683. memdelete(obj);
  684. ERR_EXPLAIN("Can't load script '"+script+"', it does not inherit from a MainLoop type");
  685. ERR_FAIL_COND_V(!script_loop,false);
  686. }
  687. script_loop->set_init_script(script_res);
  688. main_loop=script_loop;
  689. } else {
  690. return false;
  691. }
  692. } else {
  693. main_loop_type=GLOBAL_DEF("application/main_loop_type","");
  694. }
  695. if (!main_loop && main_loop_type=="")
  696. main_loop_type="SceneMainLoop";
  697. if (!main_loop) {
  698. if (!ObjectTypeDB::type_exists(main_loop_type)) {
  699. OS::get_singleton()->alert("godot: error: MainLoop type doesn't exist: "+main_loop_type);
  700. return false;
  701. } else {
  702. Object *ml = ObjectTypeDB::instance(main_loop_type);
  703. if (!ml) {
  704. ERR_EXPLAIN("Can't instance MainLoop type");
  705. ERR_FAIL_V(false);
  706. }
  707. main_loop=ml->cast_to<MainLoop>();
  708. if (!main_loop) {
  709. memdelete(ml);
  710. ERR_EXPLAIN("Invalid MainLoop type");
  711. ERR_FAIL_V(false);
  712. }
  713. }
  714. }
  715. if (main_loop->is_type("SceneMainLoop")) {
  716. SceneMainLoop *sml = main_loop->cast_to<SceneMainLoop>();
  717. #ifdef TOOLS_ENABLED
  718. EditorNode *editor_node=NULL;
  719. if (editor) {
  720. editor_node = memnew( EditorNode );
  721. sml->get_root()->add_child(editor_node);
  722. //root_node->set_editor(editor);
  723. //startup editor
  724. if (_export_platform!="") {
  725. editor_node->export_platform(_export_platform,game_path,export_debug,"",true);
  726. game_path=""; //no load anything
  727. }
  728. }
  729. #endif
  730. if (!editor) {
  731. //standard helpers that can be changed from main config
  732. String stretch_mode = GLOBAL_DEF("display/stretch_mode","disabled");
  733. String stretch_aspect = GLOBAL_DEF("display/stretch_aspect","ignore");
  734. Size2i stretch_size = Size2(GLOBAL_DEF("display/width",0),GLOBAL_DEF("display/height",0));
  735. SceneMainLoop::StretchMode sml_sm=SceneMainLoop::STRETCH_MODE_DISABLED;
  736. if (stretch_mode=="2d")
  737. sml_sm=SceneMainLoop::STRETCH_MODE_2D;
  738. else if (stretch_mode=="viewport")
  739. sml_sm=SceneMainLoop::STRETCH_MODE_VIEWPORT;
  740. SceneMainLoop::StretchAspect sml_aspect=SceneMainLoop::STRETCH_ASPECT_IGNORE;
  741. if (stretch_aspect=="keep")
  742. sml_aspect=SceneMainLoop::STRETCH_ASPECT_KEEP;
  743. else if (stretch_aspect=="keep_width")
  744. sml_aspect=SceneMainLoop::STRETCH_ASPECT_KEEP_WIDTH;
  745. else if (stretch_aspect=="keep_height")
  746. sml_aspect=SceneMainLoop::STRETCH_ASPECT_KEEP_HEIGHT;
  747. sml->set_screen_stretch(sml_sm,sml_aspect,stretch_size);
  748. sml->set_auto_accept_quit(GLOBAL_DEF("application/auto_accept_quit",true));
  749. String appname = Globals::get_singleton()->get("application/name");
  750. appname = TranslationServer::get_singleton()->translate(appname);
  751. OS::get_singleton()->set_window_title(appname);
  752. } else {
  753. GLOBAL_DEF("display/stretch_mode","disabled");
  754. Globals::get_singleton()->set_custom_property_info("display/stretch_mode",PropertyInfo(Variant::STRING,"display/stretch_mode",PROPERTY_HINT_ENUM,"disabled,2d,viewport"));
  755. GLOBAL_DEF("display/stretch_aspect","ignore");
  756. Globals::get_singleton()->set_custom_property_info("display/stretch_aspect",PropertyInfo(Variant::STRING,"display/stretch_aspect",PROPERTY_HINT_ENUM,"ignore,keep,keep_width,keep_height"));
  757. sml->set_auto_accept_quit(GLOBAL_DEF("application/auto_accept_quit",true));
  758. }
  759. if (game_path!="") {
  760. String local_game_path=game_path.replace("\\","/");
  761. if (!local_game_path.begins_with("res://")) {
  762. bool absolute=(local_game_path.size()>1) && (local_game_path[0]=='/' || local_game_path[1]==':');
  763. if (!absolute) {
  764. if (Globals::get_singleton()->is_using_datapack()) {
  765. local_game_path="res://"+local_game_path;
  766. } else {
  767. int sep=local_game_path.find_last("/");
  768. if (sep==-1) {
  769. DirAccess *da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
  770. local_game_path=da->get_current_dir()+"/"+local_game_path;
  771. memdelete(da) ;
  772. } else {
  773. DirAccess *da = DirAccess::open(local_game_path.substr(0,sep));
  774. if (da) {
  775. local_game_path=da->get_current_dir()+"/"+local_game_path.substr(sep+1,local_game_path.length());;
  776. memdelete(da);
  777. }
  778. }
  779. }
  780. }
  781. }
  782. local_game_path=Globals::get_singleton()->localize_path(local_game_path);
  783. #ifdef TOOLS_ENABLED
  784. if (editor) {
  785. #ifdef OLD_SCENE_FORMAT_ENABLED
  786. if (convert_old)
  787. editor_node->set_convert_old_scene(true);
  788. #endif
  789. if (_import!="") {
  790. //editor_node->import_scene(_import,local_game_path,_import_script);
  791. if (!noquit)
  792. sml->quit();
  793. game_path=""; //no load anything
  794. } else {
  795. Error serr = editor_node->load_scene(local_game_path);
  796. if (serr==OK) {
  797. if (optimize!="") {
  798. editor_node->save_optimized_copy(optimize,optimize_preset);
  799. if (!noquit)
  800. sml->quit();
  801. }
  802. if (dumpstrings!="") {
  803. editor_node->save_translatable_strings(dumpstrings);
  804. if (!noquit)
  805. sml->quit();
  806. }
  807. }
  808. }
  809. //editor_node->set_edited_scene(game);
  810. } else {
  811. #endif
  812. {
  813. //autoload
  814. List<PropertyInfo> props;
  815. Globals::get_singleton()->get_property_list(&props);
  816. for(List<PropertyInfo>::Element *E=props.front();E;E=E->next()) {
  817. String s = E->get().name;
  818. if (!s.begins_with("autoload/"))
  819. continue;
  820. String name = s.get_slice("/",1);
  821. String path = Globals::get_singleton()->get(s);
  822. RES res = ResourceLoader::load(path);
  823. ERR_EXPLAIN("Can't autoload: "+path);
  824. ERR_CONTINUE(res.is_null());
  825. Node *n=NULL;
  826. if (res->is_type("PackedScene")) {
  827. Ref<PackedScene> ps = res;
  828. n=ps->instance();
  829. } else if (res->is_type("Script")) {
  830. Ref<Script> s = res;
  831. StringName ibt = s->get_instance_base_type();
  832. ERR_EXPLAIN("Script does not inherit a Node: "+path);
  833. ERR_CONTINUE( !ObjectTypeDB::is_type(ibt,"Node") );
  834. Object *obj = ObjectTypeDB::instance(ibt);
  835. ERR_EXPLAIN("Cannot instance node for autoload type: "+String(ibt));
  836. ERR_CONTINUE( obj==NULL );
  837. n = obj->cast_to<Node>();
  838. n->set_script(s.get_ref_ptr());
  839. }
  840. ERR_EXPLAIN("Path in autoload not a node or script: "+path);
  841. ERR_CONTINUE(!n);
  842. n->set_name(name);
  843. sml->get_root()->add_child(n);
  844. }
  845. }
  846. Node *scene=NULL;
  847. Ref<PackedScene> scenedata = ResourceLoader::load(local_game_path);
  848. if (scenedata.is_valid())
  849. scene=scenedata->instance();
  850. #ifdef OLD_SCENE_FORMAT_ENABLED
  851. if (!scene) {
  852. scene = SceneLoader::load(local_game_path,true);
  853. }
  854. #endif
  855. ERR_EXPLAIN("Failed loading scene: "+local_game_path);
  856. ERR_FAIL_COND_V(!scene,false)
  857. sml->get_root()->add_child(scene);
  858. String iconpath = GLOBAL_DEF("application/icon","Variant()""");
  859. if (iconpath!="") {
  860. Image icon;
  861. if (icon.load(iconpath)==OK)
  862. OS::get_singleton()->set_icon(icon);
  863. }
  864. //singletons
  865. #ifdef TOOLS_ENABLED
  866. }
  867. #endif
  868. }
  869. #ifdef TOOLS_ENABLED
  870. /*if (_export_platform!="") {
  871. sml->quit();
  872. }*/
  873. /*
  874. if (sml->get_root_node()) {
  875. Console *console = memnew( Console );
  876. sml->get_root_node()->cast_to<RootNode>()->set_console(console);
  877. if (GLOBAL_DEF("console/visible_default",false).operator bool()) {
  878. console->show();
  879. } else {P
  880. console->hide();
  881. };
  882. }
  883. */
  884. if (script=="" && test=="" && game_path=="" && !editor) {
  885. ProjectManager *pmanager = memnew( ProjectManager );
  886. sml->get_root()->add_child(pmanager);
  887. }
  888. #endif
  889. }
  890. OS::get_singleton()->set_main_loop( main_loop );
  891. return true;
  892. }
  893. uint64_t Main::last_ticks=0;
  894. uint64_t Main::target_ticks=0;
  895. float Main::time_accum=0;
  896. uint32_t Main::frames=0;
  897. uint32_t Main::frame=0;
  898. bool Main::force_redraw_requested = false;
  899. static uint64_t fixed_process_max=0;
  900. static uint64_t idle_process_max=0;
  901. bool Main::iteration() {
  902. uint64_t ticks=OS::get_singleton()->get_ticks_usec();
  903. uint64_t ticks_elapsed=ticks-last_ticks;
  904. frame+=ticks_elapsed;
  905. last_ticks=ticks;
  906. double step=(double)ticks_elapsed / 1000000.0;
  907. float frame_slice=1.0/OS::get_singleton()->get_iterations_per_second();
  908. if (step>frame_slice*8)
  909. step=frame_slice*8;
  910. time_accum+=step;
  911. bool exit=false;
  912. int iters = 0;
  913. while(time_accum>frame_slice) {
  914. uint64_t fixed_begin = OS::get_singleton()->get_ticks_usec();
  915. PhysicsServer::get_singleton()->sync();
  916. PhysicsServer::get_singleton()->flush_queries();
  917. Physics2DServer::get_singleton()->sync();
  918. Physics2DServer::get_singleton()->flush_queries();
  919. if (OS::get_singleton()->get_main_loop()->iteration( frame_slice )) {
  920. exit=true;
  921. break;
  922. }
  923. message_queue->flush();
  924. PhysicsServer::get_singleton()->step(frame_slice);
  925. Physics2DServer::get_singleton()->step(frame_slice);
  926. time_accum-=frame_slice;
  927. message_queue->flush();
  928. //if (AudioServer::get_singleton())
  929. // AudioServer::get_singleton()->update();
  930. fixed_process_max=MAX(OS::get_singleton()->get_ticks_usec()-fixed_begin,fixed_process_max);
  931. iters++;
  932. }
  933. uint64_t idle_begin = OS::get_singleton()->get_ticks_usec();
  934. OS::get_singleton()->get_main_loop()->idle( step );
  935. message_queue->flush();
  936. if (SpatialSoundServer::get_singleton())
  937. SpatialSoundServer::get_singleton()->update( step );
  938. if (SpatialSound2DServer::get_singleton())
  939. SpatialSound2DServer::get_singleton()->update( step );
  940. if (OS::get_singleton()->can_draw()) {
  941. if ((!force_redraw_requested) && OS::get_singleton()->is_in_low_processor_usage_mode()) {
  942. if (VisualServer::get_singleton()->has_changed()) {
  943. VisualServer::get_singleton()->draw(); // flush visual commands
  944. OS::get_singleton()->frames_drawn++;
  945. }
  946. } else {
  947. VisualServer::get_singleton()->draw(); // flush visual commands
  948. OS::get_singleton()->frames_drawn++;
  949. force_redraw_requested = false;
  950. }
  951. } else {
  952. VisualServer::get_singleton()->flush(); // flush visual commands
  953. }
  954. if (AudioServer::get_singleton())
  955. AudioServer::get_singleton()->update();
  956. for(int i=0;i<ScriptServer::get_language_count();i++) {
  957. ScriptServer::get_language(i)->frame();
  958. }
  959. idle_process_max=MAX(OS::get_singleton()->get_ticks_usec()-idle_begin,idle_process_max);
  960. if (script_debugger)
  961. script_debugger->idle_poll();
  962. // x11_delay_usec(10000);
  963. frames++;
  964. if (frame>1000000) {
  965. if (GLOBAL_DEF("debug/print_fps", OS::get_singleton()->is_stdout_verbose())) {
  966. print_line("FPS: "+itos(frames));
  967. };
  968. OS::get_singleton()->_fps=frames;
  969. performance->set_process_time(idle_process_max/1000000.0);
  970. performance->set_fixed_process_time(fixed_process_max/1000000.0);
  971. idle_process_max=0;
  972. fixed_process_max=0;
  973. if (GLOBAL_DEF("debug/print_metrics", false)) {
  974. //PerformanceMetrics::print();
  975. };
  976. frame%=1000000;
  977. frames=0;
  978. }
  979. if (OS::get_singleton()->is_in_low_processor_usage_mode() || !OS::get_singleton()->can_draw())
  980. OS::get_singleton()->delay_usec(25000); //apply some delay to force idle time
  981. else {
  982. uint32_t frame_delay = OS::get_singleton()->get_frame_delay();
  983. if (frame_delay)
  984. OS::get_singleton()->delay_usec( OS::get_singleton()->get_frame_delay()*1000 );
  985. }
  986. int taret_fps = OS::get_singleton()->get_target_fps();
  987. if (taret_fps>0) {
  988. uint64_t time_step = 1000000L/taret_fps;
  989. target_ticks += time_step;
  990. uint64_t current_ticks = OS::get_singleton()->get_ticks_usec();
  991. if (current_ticks<target_ticks) OS::get_singleton()->delay_usec(target_ticks-current_ticks);
  992. current_ticks = OS::get_singleton()->get_ticks_usec();
  993. target_ticks = MIN(MAX(target_ticks,current_ticks-time_step),current_ticks+time_step);
  994. }
  995. return exit;
  996. }
  997. void Main::force_redraw() {
  998. force_redraw_requested = true;
  999. };
  1000. void Main::cleanup() {
  1001. ERR_FAIL_COND(!_start_success);
  1002. if (script_debugger)
  1003. memdelete(script_debugger);
  1004. OS::get_singleton()->delete_main_loop();
  1005. OS::get_singleton()->_cmdline.clear();
  1006. OS::get_singleton()->_execpath="";
  1007. OS::get_singleton()->_local_clipboard="";
  1008. #ifdef TOOLS_ENABLED
  1009. EditorNode::unregister_editor_types();
  1010. #endif
  1011. unregister_driver_types();
  1012. unregister_module_types();
  1013. unregister_scene_types();
  1014. unregister_server_types();
  1015. OS::get_singleton()->finalize();
  1016. if (packed_data)
  1017. memdelete(packed_data);
  1018. if (file_access_network_client)
  1019. memdelete(file_access_network_client);
  1020. if (performance)
  1021. memdelete(performance);
  1022. if (input_map)
  1023. memdelete(input_map);
  1024. if (translation_server)
  1025. memdelete( translation_server );
  1026. if (path_remap)
  1027. memdelete(path_remap);
  1028. if (globals)
  1029. memdelete(globals);
  1030. memdelete( message_queue );
  1031. unregister_core_driver_types();
  1032. unregister_core_types();
  1033. //PerformanceMetrics::finish();
  1034. OS::get_singleton()->clear_last_error();
  1035. OS::get_singleton()->finalize_core();
  1036. }