+
+/****************************************************************************
+ Startup
+ ****************************************************************************/
+
+bool Game::init(
+ const std::string &map_dir,
+ std::string *address,
+ u16 port,
+ const SubgameSpec &gamespec)
+{
+ showOverlayMessage("Loading...", 0, 0);
+
+ texture_src = createTextureSource(device);
+ shader_src = createShaderSource(device);
+
+ itemdef_manager = createItemDefManager();
+ nodedef_manager = createNodeDefManager();
+
+ eventmgr = new EventManager();
+ quicktune = new QuicktuneShortcutter();
+
+ if (!(texture_src && shader_src && itemdef_manager && nodedef_manager
+ && eventmgr && quicktune))
+ return false;
+
+ if (!initSound())
+ return false;
+
+ // Create a server if not connecting to an existing one
+ if (*address == "") {
+ if (!createSingleplayerServer(map_dir, gamespec, port, address))
+ return false;
+ }
+
+ return true;
+}
+
+bool Game::initSound()
+{
+#if USE_SOUND
+ if (g_settings->getBool("enable_sound")) {
+ infostream << "Attempting to use OpenAL audio" << std::endl;
+ sound = createOpenALSoundManager(&soundfetcher);
+ if (!sound)
+ infostream << "Failed to initialize OpenAL audio" << std::endl;
+ } else
+ infostream << "Sound disabled." << std::endl;
+#endif
+
+ if (!sound) {
+ infostream << "Using dummy audio." << std::endl;
+ sound = &dummySoundManager;
+ sound_is_dummy = true;
+ }
+
+ soundmaker = new SoundMaker(sound, nodedef_manager);
+ if (!soundmaker)
+ return false;
+
+ soundmaker->registerReceiver(eventmgr);
+
+ return true;
+}
+
+bool Game::createSingleplayerServer(const std::string map_dir,
+ const SubgameSpec &gamespec, u16 port, std::string *address)
+{
+ showOverlayMessage("Creating server...", 0, 5);
+
+ std::string bind_str = g_settings->get("bind_address");
+ Address bind_addr(0, 0, 0, 0, port);
+
+ if (g_settings->getBool("ipv6_server")) {
+ bind_addr.setAddress((IPv6AddressBytes *) NULL);
+ }
+
+ try {
+ bind_addr.Resolve(bind_str.c_str());
+ *address = bind_str;
+ } catch (ResolveError &e) {
+ infostream << "Resolving bind address \"" << bind_str
+ << "\" failed: " << e.what()
+ << " -- Listening on all addresses." << std::endl;
+ }
+
+ if (bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) {
+ *error_message = L"Unable to listen on " +
+ narrow_to_wide(bind_addr.serializeString()) +
+ L" because IPv6 is disabled";
+ errorstream << wide_to_narrow(*error_message) << std::endl;
+ return false;
+ }
+
+ server = new Server(map_dir, gamespec, simple_singleplayer_mode,
+ bind_addr.isIPv6());
+
+ server->start(bind_addr);
+
+ return true;
+}
+
+bool Game::createClient(const std::string &playername,
+ const std::string &password, std::string *address, u16 port,
+ std::wstring *error_message)
+{
+ showOverlayMessage("Creating client...", 0, 10);
+
+ draw_control = new MapDrawControl;
+ if (!draw_control)
+ return false;
+
+ bool could_connect, connect_aborted;
+
+ if (!connectToServer(playername, password, address, port,
+ &could_connect, &connect_aborted))
+ return false;
+
+ if (!could_connect) {
+ if (*error_message == L"" && !connect_aborted) {
+ // Should not happen if error messages are set properly
+ *error_message = L"Connection failed for unknown reason";
+ errorstream << wide_to_narrow(*error_message) << std::endl;
+ }
+ return false;
+ }
+
+ if (!getServerContent(&connect_aborted)) {
+ if (*error_message == L"" && !connect_aborted) {
+ // Should not happen if error messages are set properly
+ *error_message = L"Connection failed for unknown reason";
+ errorstream << wide_to_narrow(*error_message) << std::endl;
+ }
+ return false;
+ }
+
+ // Update cached textures, meshes and materials
+ client->afterContentReceived(device, g_fontengine->getFont());
+
+ /* Camera
+ */
+ camera = new Camera(smgr, *draw_control, gamedef);
+ if (!camera || !camera->successfullyCreated(*error_message))
+ return false;
+
+ /* Clouds
+ */
+ if (m_cache_enable_clouds) {
+ clouds = new Clouds(smgr->getRootSceneNode(), smgr, -1, time(0));
+ if (!clouds) {
+ *error_message = L"Memory allocation error";
+ *error_message += narrow_to_wide(" (clouds)");
+ errorstream << wide_to_narrow(*error_message) << std::endl;
+ return false;
+ }
+ }
+
+ /* Skybox
+ */
+ sky = new Sky(smgr->getRootSceneNode(), smgr, -1);
+ skybox = NULL; // This is used/set later on in the main run loop
+
+ local_inventory = new Inventory(itemdef_manager);
+
+ if (!(sky && local_inventory)) {
+ *error_message = L"Memory allocation error";
+ *error_message += narrow_to_wide(" (sky or local inventory)");
+ errorstream << wide_to_narrow(*error_message) << std::endl;
+ return false;
+ }
+
+ /* Pre-calculated values
+ */
+ video::ITexture *t = texture_src->getTexture("crack_anylength.png");
+ if (t) {
+ v2u32 size = t->getOriginalSize();
+ crack_animation_length = size.Y / size.X;
+ } else {
+ crack_animation_length = 5;
+ }
+
+ if (!initGui(error_message))
+ return false;
+
+ /* Set window caption
+ */
+ core::stringw str = L"Minetest [";
+ str += driver->getName();
+ str += "]";
+ device->setWindowCaption(str.c_str());
+
+ LocalPlayer *player = client->getEnv().getLocalPlayer();
+ player->hurt_tilt_timer = 0;
+ player->hurt_tilt_strength = 0;
+
+ hud = new Hud(driver, smgr, guienv, gamedef, player, local_inventory);
+
+ if (!hud) {
+ *error_message = L"Memory error: could not create HUD";
+ errorstream << wide_to_narrow(*error_message) << std::endl;
+ return false;
+ }
+
+ return true;
+}
+
+bool Game::initGui(std::wstring *error_message)
+{
+ // First line of debug text
+ guitext = guienv->addStaticText(
+ L"Minetest",
+ core::rect<s32>(0, 0, 0, 0),
+ false, false, guiroot);
+
+ // Second line of debug text
+ guitext2 = guienv->addStaticText(
+ L"",
+ core::rect<s32>(0, 0, 0, 0),
+ false, false, guiroot);
+
+ // At the middle of the screen
+ // Object infos are shown in this
+ guitext_info = guienv->addStaticText(
+ L"",
+ core::rect<s32>(0, 0, 400, g_fontengine->getTextHeight() * 5 + 5) + v2s32(100, 200),
+ false, true, guiroot);
+
+ // Status text (displays info when showing and hiding GUI stuff, etc.)
+ guitext_status = guienv->addStaticText(
+ L"<Status>",
+ core::rect<s32>(0, 0, 0, 0),
+ false, false, guiroot);
+ guitext_status->setVisible(false);
+
+ // Chat text
+ guitext_chat = guienv->addStaticText(
+ L"",
+ core::rect<s32>(0, 0, 0, 0),
+ //false, false); // Disable word wrap as of now
+ false, true, guiroot);
+ // Remove stale "recent" chat messages from previous connections
+ chat_backend->clearRecentChat();
+
+ // Chat backend and console
+ gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(),
+ -1, chat_backend, client);
+ if (!gui_chat_console) {
+ *error_message = L"Could not allocate memory for chat console";
+ errorstream << wide_to_narrow(*error_message) << std::endl;
+ return false;
+ }
+
+ // Profiler text (size is updated when text is updated)
+ guitext_profiler = guienv->addStaticText(
+ L"<Profiler>",
+ core::rect<s32>(0, 0, 0, 0),
+ false, false, guiroot);
+ guitext_profiler->setBackgroundColor(video::SColor(120, 0, 0, 0));
+ guitext_profiler->setVisible(false);
+ guitext_profiler->setWordWrap(true);
+
+#ifdef HAVE_TOUCHSCREENGUI
+
+ if (g_touchscreengui)
+ g_touchscreengui->init(texture_src, porting::getDisplayDensity());
+
+#endif
+
+ return true;
+}
+
+bool Game::connectToServer(const std::string &playername,
+ const std::string &password, std::string *address, u16 port,
+ bool *connect_ok, bool *aborted)
+{
+ showOverlayMessage("Resolving address...", 0, 15);
+
+ Address connect_address(0, 0, 0, 0, port);
+
+ try {
+ connect_address.Resolve(address->c_str());
+
+ if (connect_address.isZero()) { // i.e. INADDR_ANY, IN6ADDR_ANY
+ //connect_address.Resolve("localhost");
+ if (connect_address.isIPv6()) {
+ IPv6AddressBytes addr_bytes;
+ addr_bytes.bytes[15] = 1;
+ connect_address.setAddress(&addr_bytes);
+ } else {
+ connect_address.setAddress(127, 0, 0, 1);
+ }
+ }
+ } catch (ResolveError &e) {
+ *error_message = L"Couldn't resolve address: " + narrow_to_wide(e.what());
+ errorstream << wide_to_narrow(*error_message) << std::endl;
+ return false;
+ }
+
+ if (connect_address.isIPv6() && !g_settings->getBool("enable_ipv6")) {
+ *error_message = L"Unable to connect to " +
+ narrow_to_wide(connect_address.serializeString()) +
+ L" because IPv6 is disabled";
+ errorstream << wide_to_narrow(*error_message) << std::endl;
+ return false;
+ }
+
+ client = new Client(device,
+ playername.c_str(), password, simple_singleplayer_mode,
+ *draw_control, texture_src, shader_src,
+ itemdef_manager, nodedef_manager, sound, eventmgr,
+ connect_address.isIPv6());
+
+ if (!client)
+ return false;
+
+ gamedef = client; // Client acts as our GameDef
+
+
+ infostream << "Connecting to server at ";
+ connect_address.print(&infostream);
+ infostream << std::endl;
+
+ client->connect(connect_address);
+
+
+ /*
+ Wait for server to accept connection
+ */
+
+ try {
+ input->clear();
+
+ FpsControl fps_control = { 0 };
+ f32 dtime; // in seconds
+
+ while (device->run()) {
+
+ limitFps(&fps_control, &dtime);
+
+ // Update client and server
+ client->step(dtime);
+
+ if (server != NULL)
+ server->step(dtime);
+
+ // End condition
+ if (client->getState() == LC_Init) {
+ *connect_ok = true;
+ break;
+ }
+
+ // Break conditions
+ if (client->accessDenied()) {
+ *error_message = L"Access denied. Reason: "
+ + client->accessDeniedReason();
+ errorstream << wide_to_narrow(*error_message) << std::endl;
+ break;
+ }
+
+ if (input->wasKeyDown(EscapeKey) || input->wasKeyDown(CancelKey)) {
+ *aborted = true;
+ infostream << "Connect aborted [Escape]" << std::endl;
+ break;
+ }
+
+ // Update status
+ showOverlayMessage("Connecting to server...", dtime, 20);
+ }
+ } catch (con::PeerNotFoundException &e) {
+ // TODO: Should something be done here? At least an info/error
+ // message?
+ return false;
+ }
+
+ return true;
+}
+
+bool Game::getServerContent(bool *aborted)
+{
+ input->clear();
+
+ FpsControl fps_control = { 0 };
+ f32 dtime; // in seconds
+
+ while (device->run()) {
+
+ limitFps(&fps_control, &dtime);
+
+ // Update client and server
+ client->step(dtime);
+
+ if (server != NULL)
+ server->step(dtime);
+
+ // End condition
+ if (client->mediaReceived() && client->itemdefReceived() &&
+ client->nodedefReceived()) {
+ break;
+ }
+
+ // Error conditions
+ if (client->accessDenied()) {
+ *error_message = L"Access denied. Reason: "
+ + client->accessDeniedReason();
+ errorstream << wide_to_narrow(*error_message) << std::endl;
+ return false;
+ }
+
+ if (client->getState() < LC_Init) {
+ *error_message = L"Client disconnected";
+ errorstream << wide_to_narrow(*error_message) << std::endl;
+ return false;
+ }
+
+ if (input->wasKeyDown(EscapeKey) || input->wasKeyDown(CancelKey)) {
+ *aborted = true;
+ infostream << "Connect aborted [Escape]" << std::endl;
+ return false;
+ }
+
+ // Display status
+ int progress = 25;
+
+ if (!client->itemdefReceived()) {
+ wchar_t *text = wgettext("Item definitions...");
+ progress = 25;
+ draw_load_screen(text, device, guienv, dtime, progress);
+ delete[] text;
+ } else if (!client->nodedefReceived()) {
+ wchar_t *text = wgettext("Node definitions...");
+ progress = 30;
+ draw_load_screen(text, device, guienv, dtime, progress);
+ delete[] text;
+ } else {
+ std::stringstream message;
+ message.precision(3);
+ message << gettext("Media...");
+
+ if ((USE_CURL == 0) ||
+ (!g_settings->getBool("enable_remote_media_server"))) {
+ float cur = client->getCurRate();
+ std::string cur_unit = gettext(" KB/s");
+
+ if (cur > 900) {
+ cur /= 1024.0;
+ cur_unit = gettext(" MB/s");
+ }
+
+ message << " ( " << cur << cur_unit << " )";
+ }
+
+ progress = 30 + client->mediaReceiveProgress() * 35 + 0.5;
+ draw_load_screen(narrow_to_wide(message.str().c_str()), device,
+ guienv, dtime, progress);
+ }
+ }
+
+ return true;
+}
+
+
+
+/****************************************************************************
+ Run
+ ****************************************************************************/
+
+inline void Game::updateInteractTimers(GameRunData *args, f32 dtime)
+{
+ if (args->nodig_delay_timer >= 0)
+ args->nodig_delay_timer -= dtime;
+
+ if (args->object_hit_delay_timer >= 0)
+ args->object_hit_delay_timer -= dtime;
+
+ args->time_from_last_punch += dtime;
+}
+
+
+/* returns false if game should exit, otherwise true
+ */
+inline bool Game::checkConnection()
+{
+ if (client->accessDenied()) {
+ *error_message = L"Access denied. Reason: "
+ + client->accessDeniedReason();
+ errorstream << wide_to_narrow(*error_message) << std::endl;
+ return false;
+ }
+
+ return true;
+}
+
+
+/* returns false if game should exit, otherwise true
+ */
+inline bool Game::handleCallbacks()
+{
+ if (g_gamecallback->disconnect_requested) {
+ g_gamecallback->disconnect_requested = false;
+ return false;
+ }
+
+ if (g_gamecallback->changepassword_requested) {
+ (new GUIPasswordChange(guienv, guiroot, -1,
+ &g_menumgr, client))->drop();
+ g_gamecallback->changepassword_requested = false;
+ }
+
+ if (g_gamecallback->changevolume_requested) {
+ (new GUIVolumeChange(guienv, guiroot, -1,
+ &g_menumgr, client))->drop();
+ g_gamecallback->changevolume_requested = false;
+ }
+
+ if (g_gamecallback->keyconfig_requested) {
+ (new GUIKeyChangeMenu(guienv, guiroot, -1,
+ &g_menumgr))->drop();
+ g_gamecallback->keyconfig_requested = false;
+ }
+
+ if (g_gamecallback->keyconfig_changed) {
+ keycache.populate(); // update the cache with new settings
+ g_gamecallback->keyconfig_changed = false;
+ }
+
+ return true;
+}
+
+
+void Game::processQueues()
+{
+ texture_src->processQueue();
+ itemdef_manager->processQueue(gamedef);
+ shader_src->processQueue();
+}
+
+
+void Game::updateProfilers(const GameRunData &run_data, const RunStats &stats,
+ const FpsControl &draw_times, f32 dtime)
+{
+ float profiler_print_interval =
+ g_settings->getFloat("profiler_print_interval");
+ bool print_to_log = true;
+
+ if (profiler_print_interval == 0) {
+ print_to_log = false;
+ profiler_print_interval = 5;
+ }
+
+ if (profiler_interval.step(dtime, profiler_print_interval)) {
+ if (print_to_log) {
+ infostream << "Profiler:" << std::endl;
+ g_profiler->print(infostream);
+ }
+
+ update_profiler_gui(guitext_profiler, g_fontengine,
+ run_data.profiler_current_page, run_data.profiler_max_page,
+ driver->getScreenSize().Height);
+
+ g_profiler->clear();
+ }
+
+ addProfilerGraphs(stats, draw_times, dtime);
+}
+
+
+void Game::addProfilerGraphs(const RunStats &stats,
+ const FpsControl &draw_times, f32 dtime)
+{
+ g_profiler->graphAdd("mainloop_other",
+ draw_times.busy_time / 1000.0f - stats.drawtime / 1000.0f);
+
+ if (draw_times.sleep_time != 0)
+ g_profiler->graphAdd("mainloop_sleep", draw_times.sleep_time / 1000.0f);
+ g_profiler->graphAdd("mainloop_dtime", dtime);
+
+ g_profiler->add("Elapsed time", dtime);
+ g_profiler->avg("FPS", 1. / dtime);
+}
+
+
+void Game::updateStats(RunStats *stats, const FpsControl &draw_times,
+ f32 dtime)
+{
+
+ f32 jitter;
+ Jitter *jp;
+
+ /* Time average and jitter calculation
+ */
+ jp = &stats->dtime_jitter;
+ jp->avg = jp->avg * 0.96 + dtime * 0.04;
+
+ jitter = dtime - jp->avg;
+
+ if (jitter > jp->max)
+ jp->max = jitter;
+
+ jp->counter += dtime;
+
+ if (jp->counter > 0.0) {
+ jp->counter -= 3.0;
+ jp->max_sample = jp->max;
+ jp->max_fraction = jp->max_sample / (jp->avg + 0.001);
+ jp->max = 0.0;
+ }
+
+ /* Busytime average and jitter calculation
+ */
+ jp = &stats->busy_time_jitter;
+ jp->avg = jp->avg + draw_times.busy_time * 0.02;
+
+ jitter = draw_times.busy_time - jp->avg;
+
+ if (jitter > jp->max)
+ jp->max = jitter;
+ if (jitter < jp->min)
+ jp->min = jitter;
+
+ jp->counter += dtime;
+
+ if (jp->counter > 0.0) {
+ jp->counter -= 3.0;
+ jp->max_sample = jp->max;
+ jp->min_sample = jp->min;
+ jp->max = 0.0;
+ jp->min = 0.0;
+ }
+}
+
+
+
+/****************************************************************************
+ Input handling
+ ****************************************************************************/
+
+void Game::processUserInput(VolatileRunFlags *flags,
+ GameRunData *interact_args, f32 dtime)
+{
+ // Reset input if window not active or some menu is active
+ if (device->isWindowActive() == false
+ || noMenuActive() == false
+ || guienv->hasFocus(gui_chat_console)) {
+ input->clear();
+ }
+
+ if (!guienv->hasFocus(gui_chat_console) && gui_chat_console->isOpen()) {
+ gui_chat_console->closeConsoleAtOnce();
+ }
+
+ // Input handler step() (used by the random input generator)
+ input->step(dtime);
+
+#ifdef HAVE_TOUCHSCREENGUI
+
+ if (g_touchscreengui) {
+ g_touchscreengui->step(dtime);
+ }
+
+#endif
+#ifdef __ANDROID__
+
+ if (current_formspec != 0)
+ current_formspec->getAndroidUIInput();
+
+#endif
+
+ // Increase timer for double tap of "keymap_jump"
+ if (m_cache_doubletap_jump && interact_args->jump_timer <= 0.2)
+ interact_args->jump_timer += dtime;
+
+ processKeyboardInput(
+ flags,
+ &interact_args->statustext_time,
+ &interact_args->jump_timer,
+ &interact_args->reset_jump_timer,
+ &interact_args->profiler_current_page,
+ interact_args->profiler_max_page);
+
+ processItemSelection(&interact_args->new_playeritem);
+}
+
+
+void Game::processKeyboardInput(VolatileRunFlags *flags,
+ float *statustext_time,
+ float *jump_timer,
+ bool *reset_jump_timer,
+ u32 *profiler_current_page,
+ u32 profiler_max_page)
+{
+
+ //TimeTaker tt("process kybd input", NULL, PRECISION_NANO);
+
+ if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_DROP])) {
+ dropSelectedItem();
+ } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_INVENTORY])) {
+ openInventory();
+ } else if (input->wasKeyDown(EscapeKey) || input->wasKeyDown(CancelKey)) {
+ show_pause_menu(¤t_formspec, client, gamedef, texture_src, device,
+ simple_singleplayer_mode);
+ } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_CHAT])) {
+ show_chat_menu(¤t_formspec, client, gamedef, texture_src, device,
+ client, "");
+ } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_CMD])) {
+ show_chat_menu(¤t_formspec, client, gamedef, texture_src, device,
+ client, "/");
+ } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_CONSOLE])) {
+ openConsole();
+ } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_FREEMOVE])) {
+ toggleFreeMove(statustext_time);
+ } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_JUMP])) {
+ toggleFreeMoveAlt(statustext_time, jump_timer);
+ *reset_jump_timer = true;
+ } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_FASTMOVE])) {
+ toggleFast(statustext_time);
+ } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_NOCLIP])) {
+ toggleNoClip(statustext_time);
+ } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_SCREENSHOT])) {
+ client->makeScreenshot(device);
+ } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_HUD])) {
+ toggleHud(statustext_time, &flags->show_hud);
+ } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_CHAT])) {
+ toggleChat(statustext_time, &flags->show_chat);
+ } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_FORCE_FOG_OFF])) {
+ toggleFog(statustext_time, &flags->force_fog_off);
+ } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_UPDATE_CAMERA])) {
+ toggleUpdateCamera(statustext_time, &flags->disable_camera_update);
+ } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_DEBUG])) {
+ toggleDebug(statustext_time, &flags->show_debug, &flags->show_profiler_graph);
+ } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_PROFILER])) {
+ toggleProfiler(statustext_time, profiler_current_page, profiler_max_page);
+ } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_INCREASE_VIEWING_RANGE])) {
+ increaseViewRange(statustext_time);
+ } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_DECREASE_VIEWING_RANGE])) {
+ decreaseViewRange(statustext_time);
+ } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_RANGESELECT])) {
+ toggleFullViewRange(statustext_time);
+ } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_QUICKTUNE_NEXT]))
+ quicktune->next();
+ else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_QUICKTUNE_PREV]))
+ quicktune->prev();
+ else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_QUICKTUNE_INC]))
+ quicktune->inc();
+ else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_QUICKTUNE_DEC]))
+ quicktune->dec();
+ else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_DEBUG_STACKS])) {
+ // Print debug stacks
+ dstream << "-----------------------------------------"
+ << std::endl;
+ dstream << DTIME << "Printing debug stacks:" << std::endl;
+ dstream << "-----------------------------------------"
+ << std::endl;
+ debug_stacks_print();
+ }
+
+ if (!input->isKeyDown(getKeySetting("keymap_jump")) && *reset_jump_timer) {
+ *reset_jump_timer = false;
+ *jump_timer = 0.0;
+ }
+
+ //tt.stop();
+
+ if (quicktune->hasMessage()) {
+ std::string msg = quicktune->getMessage();
+ statustext = narrow_to_wide(msg);
+ *statustext_time = 0;
+ }
+}
+
+
+void Game::processItemSelection(u16 *new_playeritem)
+{
+ LocalPlayer *player = client->getEnv().getLocalPlayer();
+
+ /* Item selection using mouse wheel
+ */
+ *new_playeritem = client->getPlayerItem();
+
+ s32 wheel = input->getMouseWheel();
+ u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE - 1,
+ player->hud_hotbar_itemcount - 1);
+
+ if (wheel < 0)
+ *new_playeritem = *new_playeritem < max_item ? *new_playeritem + 1 : 0;
+ else if (wheel > 0)
+ *new_playeritem = *new_playeritem > 0 ? *new_playeritem - 1 : max_item;
+ // else wheel == 0
+
+
+ /* Item selection using keyboard
+ */
+ for (u16 i = 0; i < 10; i++) {
+ static const KeyPress *item_keys[10] = {
+ NumberKey + 1, NumberKey + 2, NumberKey + 3, NumberKey + 4,
+ NumberKey + 5, NumberKey + 6, NumberKey + 7, NumberKey + 8,
+ NumberKey + 9, NumberKey + 0,
+ };
+
+ if (input->wasKeyDown(*item_keys[i])) {
+ if (i < PLAYER_INVENTORY_SIZE && i < player->hud_hotbar_itemcount) {
+ *new_playeritem = i;
+ infostream << "Selected item: " << new_playeritem << std::endl;
+ }
+ break;
+ }
+ }
+}
+
+
+void Game::dropSelectedItem()
+{
+ IDropAction *a = new IDropAction();
+ a->count = 0;
+ a->from_inv.setCurrentPlayer();
+ a->from_list = "main";
+ a->from_i = client->getPlayerItem();
+ client->inventoryAction(a);
+}
+
+
+void Game::openInventory()
+{
+ infostream << "the_game: " << "Launching inventory" << std::endl;
+
+ PlayerInventoryFormSource *fs_src = new PlayerInventoryFormSource(client);
+ TextDest *txt_dst = new TextDestPlayerInventory(client);
+
+ create_formspec_menu(¤t_formspec, client, gamedef, texture_src,
+ device, fs_src, txt_dst, client);
+
+ InventoryLocation inventoryloc;
+ inventoryloc.setCurrentPlayer();
+ current_formspec->setFormSpec(fs_src->getForm(), inventoryloc);
+}
+
+
+void Game::openConsole()
+{
+ if (!gui_chat_console->isOpenInhibited()) {
+ // Open up to over half of the screen
+ gui_chat_console->openConsole(0.6);
+ guienv->setFocus(gui_chat_console);
+ }
+}
+
+
+void Game::toggleFreeMove(float *statustext_time)
+{
+ static const wchar_t *msg[] = { L"free_move disabled", L"free_move enabled" };
+
+ bool free_move = !g_settings->getBool("free_move");
+ g_settings->set("free_move", bool_to_cstr(free_move));
+
+ *statustext_time = 0;
+ statustext = msg[free_move];
+ if (free_move && !client->checkPrivilege("fly"))
+ statustext += L" (note: no 'fly' privilege)";
+}
+
+
+void Game::toggleFreeMoveAlt(float *statustext_time, float *jump_timer)
+{
+ if (m_cache_doubletap_jump && *jump_timer < 0.2f)
+ toggleFreeMove(statustext_time);
+}
+
+
+void Game::toggleFast(float *statustext_time)
+{
+ static const wchar_t *msg[] = { L"fast_move disabled", L"fast_move enabled" };
+ bool fast_move = !g_settings->getBool("fast_move");
+ g_settings->set("fast_move", bool_to_cstr(fast_move));
+
+ *statustext_time = 0;
+ statustext = msg[fast_move];
+
+ if (fast_move && !client->checkPrivilege("fast"))
+ statustext += L" (note: no 'fast' privilege)";
+}
+
+
+void Game::toggleNoClip(float *statustext_time)
+{
+ static const wchar_t *msg[] = { L"noclip disabled", L"noclip enabled" };
+ bool noclip = !g_settings->getBool("noclip");
+ g_settings->set("noclip", bool_to_cstr(noclip));
+
+ *statustext_time = 0;
+ statustext = msg[noclip];
+
+ if (noclip && !client->checkPrivilege("noclip"))
+ statustext += L" (note: no 'noclip' privilege)";
+}
+
+
+void Game::toggleChat(float *statustext_time, bool *flag)
+{
+ static const wchar_t *msg[] = { L"Chat hidden", L"Chat shown" };
+
+ *flag = !*flag;
+ *statustext_time = 0;
+ statustext = msg[*flag];
+}
+
+
+void Game::toggleHud(float *statustext_time, bool *flag)
+{
+ static const wchar_t *msg[] = { L"HUD hidden", L"HUD shown" };
+
+ *flag = !*flag;
+ *statustext_time = 0;
+ statustext = msg[*flag];
+ if (g_settings->getBool("enable_node_highlighting"))
+ client->setHighlighted(client->getHighlighted(), *flag);
+}
+
+
+void Game::toggleFog(float *statustext_time, bool *flag)
+{
+ static const wchar_t *msg[] = { L"Fog enabled", L"Fog disabled" };
+
+ *flag = !*flag;
+ *statustext_time = 0;
+ statustext = msg[*flag];
+}
+
+
+void Game::toggleDebug(float *statustext_time, bool *show_debug,
+ bool *show_profiler_graph)
+{
+ // Initial / 3x toggle: Chat only
+ // 1x toggle: Debug text with chat
+ // 2x toggle: Debug text with profiler graph
+ if (!*show_debug) {
+ *show_debug = true;
+ *show_profiler_graph = false;
+ statustext = L"Debug info shown";
+ } else if (*show_profiler_graph) {
+ *show_debug = false;
+ *show_profiler_graph = false;
+ statustext = L"Debug info and profiler graph hidden";
+ } else {
+ *show_profiler_graph = true;
+ statustext = L"Profiler graph shown";
+ }
+ *statustext_time = 0;
+}
+
+
+void Game::toggleUpdateCamera(float *statustext_time, bool *flag)
+{
+ static const wchar_t *msg[] = {
+ L"Camera update enabled",
+ L"Camera update disabled"
+ };
+
+ *flag = !*flag;
+ *statustext_time = 0;
+ statustext = msg[*flag];
+}
+
+
+void Game::toggleProfiler(float *statustext_time, u32 *profiler_current_page,
+ u32 profiler_max_page)
+{
+ *profiler_current_page = (*profiler_current_page + 1) % (profiler_max_page + 1);
+
+ // FIXME: This updates the profiler with incomplete values
+ update_profiler_gui(guitext_profiler, g_fontengine, *profiler_current_page,
+ profiler_max_page, driver->getScreenSize().Height);
+
+ if (*profiler_current_page != 0) {
+ std::wstringstream sstr;
+ sstr << "Profiler shown (page " << *profiler_current_page
+ << " of " << profiler_max_page << ")";
+ statustext = sstr.str();
+ } else {
+ statustext = L"Profiler hidden";
+ }
+ *statustext_time = 0;
+}
+
+
+void Game::increaseViewRange(float *statustext_time)
+{
+ s16 range = g_settings->getS16("viewing_range_nodes_min");
+ s16 range_new = range + 10;
+ g_settings->set("viewing_range_nodes_min", itos(range_new));
+ statustext = narrow_to_wide("Minimum viewing range changed to "
+ + itos(range_new));
+ *statustext_time = 0;
+}
+
+
+void Game::decreaseViewRange(float *statustext_time)
+{
+ s16 range = g_settings->getS16("viewing_range_nodes_min");
+ s16 range_new = range - 10;
+
+ if (range_new < 0)
+ range_new = range;
+
+ g_settings->set("viewing_range_nodes_min", itos(range_new));
+ statustext = narrow_to_wide("Minimum viewing range changed to "
+ + itos(range_new));
+ *statustext_time = 0;
+}
+
+
+void Game::toggleFullViewRange(float *statustext_time)
+{
+ static const wchar_t *msg[] = {
+ L"Disabled full viewing range",
+ L"Enabled full viewing range"
+ };
+
+ draw_control->range_all = !draw_control->range_all;
+ infostream << msg[draw_control->range_all] << std::endl;
+ statustext = msg[draw_control->range_all];
+ *statustext_time = 0;
+}
+
+
+void Game::updateCameraDirection(CameraOrientation *cam,
+ VolatileRunFlags *flags)
+{
+ if ((device->isWindowActive() && noMenuActive()) || random_input) {
+
+#ifndef __ANDROID__
+ if (!random_input) {
+ // Mac OSX gets upset if this is set every frame
+ if (device->getCursorControl()->isVisible())
+ device->getCursorControl()->setVisible(false);