aboutsummaryrefslogtreecommitdiff
path: root/games
Commit message (Expand)AuthorAge
* Mapgen: Various fixes and improvementsparamat2016-01-11
* Minimal: Add mapgen alias for airparamat2015-12-30
* Fix spelling of noise_thresholdJun Zhang2015-12-06
* Fix relief mapping issuesRealBadAngel2015-07-16
* Minimal: Remove recently added unnecessary nodesparamat2015-07-14
* Simpler patch for saplings trying to grow on unknown nodesShadowNinja2015-06-16
* Add list-ringsest312015-06-16
* Don't crash when saplings try to grow on unknown nodesy.st2015-06-15
* Minimal: Add snow biome and jungleleaves nodes. Add mapgen aliasesparamat2015-06-12
* Minimal: Edit mapgen aliases. Use blob ore for clay, update other ores. Updat...paramat2015-06-09
* Fix NDT_GLASSLIKE normalsKahrl2015-01-31
* Remove builtin_biome.lua from builtin and add simple biome minimalparamat2015-01-11
* Add lua exception handling test codesapier2014-08-23
* Minimal game: add /dummyball <count> commandKahrl2014-08-23
* Add minetest.swap_nodeNovatux2013-11-30
* Change default value of is_ground_content to truekwolekr2013-11-30
* Fix possible crash with grass ABM.Novatux2013-11-02
* Fix grass adding/removing ABM.Novatux2013-11-02
* Move the sapling growing and grass adding/removing ABMs to LuaNovatux2013-11-02
* Remove mapgen_air alias (#935)0gb.us2013-10-05
* Add mapgen_stair_cobble alias to minimalSfan52013-09-06
* Add support for different drowning damage and allow drowning in other nodetypesBlockMen2013-08-06
* Add drowningPilzAdam2013-06-19
* Compress texturesDavid Gumberg2013-06-18
* Move scriptapi to separate folder (by sapier)sapier2013-05-25
* Use the group "soil" for nodes that saplings grow onShadowNinja2013-05-20
* games/minimal: Add menu/background.png and menu/icon.pngPerttu Ahola2013-05-02
* Add Mapgen V7, reorganize biomeskwolekr2013-04-07
* unkn own block -> unkn own nodekhonkhortisan2013-04-05
* Add different place sound for nodesPilzAdam2013-03-29
* Use minetest.register_ore() in minimalPilzAdam2013-03-24
* Mapgen indev: float islands, larger far biomesproller2013-03-24
* Liquid fine tuningproller2013-03-14
* new adjustable finite liquidproller2013-02-24
* Readded and optimized mapgen V6kwolekr2013-01-21
* Add initial Lua biomedef support, fixed biome selectionkwolekr2013-01-21
* Add the group attached_nodePilzAdam2012-12-01
* Swap out pixel-perfect nyan cat by request of Chris TorresPerttu Ahola2012-11-09
* Add functions to the default mod of minimal game to support old codePilzAdam2012-11-01
* Move falling to builtinPilzAdam2012-10-31
* Fix crash when furnace is full (minimal game)Perttu Ahola2012-08-12
* Deprecate minetest.add_to_creative_inventory and use group not_in_creative_in...Perttu Ahola2012-07-25
* Add notice in the minimal gamePerttu Ahola2012-07-25
* Improve inventory callbacks a bitPerttu Ahola2012-07-25
* Detached inventory callbacks and reworked node metadata callbacksPerttu Ahola2012-07-25
* Detached inventoriesPerttu Ahola2012-07-24
* Add node timer test in minimal/experimentalPerttu Ahola2012-07-24
* Move /give, /giveme, /spawnentity and /pulverize to builtin/chatcommands.luaPerttu Ahola2012-07-23
* Formspec button_exit[] and image_button_exit[]Perttu Ahola2012-07-22
* Add /test1 command to minimal for testing a more complicated player inventory...Perttu Ahola2012-07-22
' href='#n427'>427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065
/*
Copyright (C) 2014 sapier

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/

#include "touchscreengui.h"
#include "irrlichttypes.h"
#include "irr_v2d.h"
#include "log.h"
#include "keycode.h"
#include "settings.h"
#include "gettime.h"
#include "util/numeric.h"
#include "porting.h"
#include "guiscalingfilter.h"

#include <iostream>
#include <algorithm>

#include <ISceneCollisionManager.h>

// Very slow button repeat frequency (in seconds)
#define SLOW_BUTTON_REPEAT	(1.0f)

using namespace irr::core;

extern Settings *g_settings;

const char** touchgui_button_imagenames = (const char*[]) {
	"up_arrow.png",
	"down_arrow.png",
	"left_arrow.png",
	"right_arrow.png",
	"jump_btn.png",
	"down.png"
};

static irr::EKEY_CODE id2keycode(touch_gui_button_id id)
{
	std::string key = "";
	switch (id) {
		case forward_id:
			key = "forward";
			break;
		case left_id:
			key = "left";
			break;
		case right_id:
			key = "right";
			break;
		case backward_id:
			key = "backward";
			break;
		case inventory_id:
			key = "inventory";
			break;
		case drop_id:
			key = "drop";
			break;
		case jump_id:
			key = "jump";
			break;
		case crunch_id:
			key = "sneak";
			break;
		case fly_id:
			key = "freemove";
			break;
		case noclip_id:
			key = "noclip";
			break;
		case fast_id:
			key = "fastmove";
			break;
		case debug_id:
			key = "toggle_debug";
			break;
		case chat_id:
			key = "chat";
			break;
		case camera_id:
			key = "camera_mode";
			break;
		case range_id:
			key = "rangeselect";
			break;
	}
	assert(key != "");
	return keyname_to_keycode(g_settings->get("keymap_" + key).c_str());
}

TouchScreenGUI *g_touchscreengui;

static void load_button_texture(button_info* btn, const char* path,
		rect<s32> button_rect, ISimpleTextureSource* tsrc, video::IVideoDriver *driver)
{
	unsigned int tid;
	video::ITexture *texture = guiScalingImageButton(driver,
			tsrc->getTexture(path, &tid), button_rect.getWidth(),
			button_rect.getHeight());
	if (texture) {
		btn->guibutton->setUseAlphaChannel(true);
		if (g_settings->getBool("gui_scaling_filter")) {
			rect<s32> txr_rect = rect<s32>(0, 0, button_rect.getWidth(), button_rect.getHeight());
			btn->guibutton->setImage(texture, txr_rect);
			btn->guibutton->setPressedImage(texture, txr_rect);
			btn->guibutton->setScaleImage(false);
		} else {
			btn->guibutton->setImage(texture);
			btn->guibutton->setPressedImage(texture);
			btn->guibutton->setScaleImage(true);
		}
		btn->guibutton->setDrawBorder(false);
		btn->guibutton->setText(L"");
		}
}

AutoHideButtonBar::AutoHideButtonBar(IrrlichtDevice *device,
		IEventReceiver* receiver) :
			m_driver(device->getVideoDriver()),
			m_guienv(device->getGUIEnvironment()),
			m_receiver(receiver)
{
}

void AutoHideButtonBar::init(ISimpleTextureSource* tsrc,
		const char* starter_img, int button_id, v2s32 UpperLeft,
		v2s32 LowerRight, autohide_button_bar_dir dir, float timeout)
{
	m_texturesource = tsrc;

	m_upper_left = UpperLeft;
	m_lower_right = LowerRight;

	/* init settings bar */

	irr::core::rect<int> current_button = rect<s32>(UpperLeft.X, UpperLeft.Y,
			LowerRight.X, LowerRight.Y);

	m_starter.guibutton         = m_guienv->addButton(current_button, 0, button_id, L"", 0);
	m_starter.guibutton->grab();
	m_starter.repeatcounter     = -1;
	m_starter.keycode           = KEY_OEM_8; // use invalid keycode as it's not relevant
	m_starter.immediate_release = true;
	m_starter.ids.clear();

	load_button_texture(&m_starter, starter_img, current_button,
			m_texturesource, m_driver);

	m_dir = dir;
	m_timeout_value = timeout;

	m_initialized = true;
}

AutoHideButtonBar::~AutoHideButtonBar()
{
	if (m_starter.guibutton) {
		m_starter.guibutton->setVisible(false);
		m_starter.guibutton->drop();
	}
}

void AutoHideButtonBar::addButton(touch_gui_button_id button_id,
		const wchar_t* caption, const char* btn_image)
{

	if (!m_initialized) {
		errorstream << "AutoHideButtonBar::addButton not yet initialized!"
				<< std::endl;
		return;
	}
	int button_size = 0;

	if ((m_dir == AHBB_Dir_Top_Bottom) || (m_dir == AHBB_Dir_Bottom_Top)) {
		button_size = m_lower_right.X - m_upper_left.X;
	} else {
		button_size = m_lower_right.Y - m_upper_left.Y;
	}

	irr::core::rect<int> current_button;

	if ((m_dir == AHBB_Dir_Right_Left) || (m_dir == AHBB_Dir_Left_Right)) {

		int x_start = 0;
		int x_end = 0;

		if (m_dir == AHBB_Dir_Left_Right) {
			x_start = m_lower_right.X + (button_size * 1.25 * m_buttons.size())
					+ (button_size * 0.25);
			x_end = x_start + button_size;
		} else {
			x_end = m_upper_left.X - (button_size * 1.25 * m_buttons.size())
					- (button_size * 0.25);
			x_start = x_end - button_size;
		}

		current_button = rect<s32>(x_start, m_upper_left.Y, x_end,
				m_lower_right.Y);
	} else {
		int y_start = 0;
		int y_end = 0;

		if (m_dir == AHBB_Dir_Top_Bottom) {
			y_start = m_lower_right.X + (button_size * 1.25 * m_buttons.size())
					+ (button_size * 0.25);
			y_end = y_start + button_size;
		} else {
			y_end = m_upper_left.X - (button_size * 1.25 * m_buttons.size())
					- (button_size * 0.25);
			y_start = y_end - button_size;
		}

		current_button = rect<s32>(m_upper_left.X, y_start, m_lower_right.Y,
				y_end);
	}

	button_info* btn       = new button_info();
	btn->guibutton         = m_guienv->addButton(current_button, 0, button_id, caption, 0);
	btn->guibutton->grab();
	btn->guibutton->setVisible(false);
	btn->guibutton->setEnabled(false);
	btn->repeatcounter     = -1;
	btn->keycode           = id2keycode(button_id);
	btn->immediate_release = true;
	btn->ids.clear();

	load_button_texture(btn, btn_image, current_button, m_texturesource,
			m_driver);

	m_buttons.push_back(btn);
}

bool AutoHideButtonBar::isButton(const SEvent &event)
{
	IGUIElement* rootguielement = m_guienv->getRootGUIElement();

	if (rootguielement == NULL) {
		return false;
	}

	gui::IGUIElement *element = rootguielement->getElementFromPoint(
			core::position2d<s32>(event.TouchInput.X, event.TouchInput.Y));

	if (element == NULL) {
		return false;
	}

	if (m_active) {
		/* check for all buttons in vector */

		std::vector<button_info*>::iterator iter = m_buttons.begin();

		while (iter != m_buttons.end()) {
			if ((*iter)->guibutton == element) {

				SEvent* translated = new SEvent();
				memset(translated, 0, sizeof(SEvent));
				translated->EventType            = irr::EET_KEY_INPUT_EVENT;
				translated->KeyInput.Key         = (*iter)->keycode;
				translated->KeyInput.Control     = false;
				translated->KeyInput.Shift       = false;
				translated->KeyInput.Char        = 0;

				/* add this event */
				translated->KeyInput.PressedDown = true;
				m_receiver->OnEvent(*translated);

				/* remove this event */
				translated->KeyInput.PressedDown = false;
				m_receiver->OnEvent(*translated);

				delete translated;

				(*iter)->ids.push_back(event.TouchInput.ID);

				m_timeout = 0;

				return true;
			}
			++iter;
		}
	} else {
		/* check for starter button only */
		if (element == m_starter.guibutton) {
			m_starter.ids.push_back(event.TouchInput.ID);
			m_starter.guibutton->setVisible(false);
			m_starter.guibutton->setEnabled(false);
			m_active = true;
			m_timeout = 0;

			std::vector<button_info*>::iterator iter = m_buttons.begin();

			while (iter != m_buttons.end()) {
				(*iter)->guibutton->setVisible(true);
				(*iter)->guibutton->setEnabled(true);
				++iter;
			}

			return true;
		}
	}
	return false;
}

bool AutoHideButtonBar::isReleaseButton(int eventID)
{
	std::vector<int>::iterator id = std::find(m_starter.ids.begin(),
			m_starter.ids.end(), eventID);

	if (id != m_starter.ids.end()) {
		m_starter.ids.erase(id);
		return true;
	}

	std::vector<button_info*>::iterator iter = m_buttons.begin();

	while (iter != m_buttons.end()) {
		std::vector<int>::iterator id = std::find((*iter)->ids.begin(),
				(*iter)->ids.end(), eventID);

		if (id != (*iter)->ids.end()) {
			(*iter)->ids.erase(id);
			// TODO handle settings button release
			return true;
		}
		++iter;
	}

	return false;
}

void AutoHideButtonBar::step(float dtime)
{
	if (m_active) {
		m_timeout += dtime;

		if (m_timeout > m_timeout_value) {
			deactivate();
		}
	}
}

void AutoHideButtonBar::deactivate()
{
	if (m_visible == true) {
		m_starter.guibutton->setVisible(true);
		m_starter.guibutton->setEnabled(true);
	}
	m_active = false;

	std::vector<button_info*>::iterator iter = m_buttons.begin();

	while (iter != m_buttons.end()) {
			(*iter)->guibutton->setVisible(false);
			(*iter)->guibutton->setEnabled(false);
		++iter;
	}
}

void AutoHideButtonBar::hide()
{
	m_visible = false;
	m_starter.guibutton->setVisible(false);
	m_starter.guibutton->setEnabled(false);

	std::vector<button_info*>::iterator iter = m_buttons.begin();

	while (iter != m_buttons.end()) {
		(*iter)->guibutton->setVisible(false);
		(*iter)->guibutton->setEnabled(false);
		++iter;
	}
}

void AutoHideButtonBar::show()
{
	m_visible = true;

	if (m_active) {
		std::vector<button_info*>::iterator iter = m_buttons.begin();

		while (iter != m_buttons.end()) {
			(*iter)->guibutton->setVisible(true);
			(*iter)->guibutton->setEnabled(true);
			++iter;
		}
	} else {
		m_starter.guibutton->setVisible(true);
		m_starter.guibutton->setEnabled(true);
	}
}

TouchScreenGUI::TouchScreenGUI(IrrlichtDevice *device, IEventReceiver* receiver):
	m_device(device),
	m_guienv(device->getGUIEnvironment()),
	m_receiver(receiver),
	m_settingsbar(device, receiver),
	m_rarecontrolsbar(device, receiver)
{
	for (unsigned int i=0; i < after_last_element_id; i++) {
		m_buttons[i].guibutton     =  0;
		m_buttons[i].repeatcounter = -1;
		m_buttons[i].repeatdelay   = BUTTON_REPEAT_DELAY;
	}

	m_screensize = m_device->getVideoDriver()->getScreenSize();
}

void TouchScreenGUI::initButton(touch_gui_button_id id, rect<s32> button_rect,
		std::wstring caption, bool immediate_release, float repeat_delay)
{

	button_info* btn       = &m_buttons[id];
	btn->guibutton         = m_guienv->addButton(button_rect, 0, id, caption.c_str());
	btn->guibutton->grab();
	btn->repeatcounter     = -1;
	btn->repeatdelay       = repeat_delay;
	btn->keycode           = id2keycode(id);
	btn->immediate_release = immediate_release;
	btn->ids.clear();

	load_button_texture(btn,touchgui_button_imagenames[id],button_rect,
			m_texturesource, m_device->getVideoDriver());
}

static int getMaxControlPadSize(float density) {
	return 200 * density * g_settings->getFloat("hud_scaling");
}

int TouchScreenGUI::getGuiButtonSize()
{
	u32 control_pad_size = MYMIN((2 * m_screensize.Y) / 3,
			getMaxControlPadSize(porting::getDisplayDensity()));

	return control_pad_size / 3;
}

void TouchScreenGUI::init(ISimpleTextureSource* tsrc)
{
	assert(tsrc != 0);

	u32 button_size      = getGuiButtonSize();
	m_visible            = true;
	m_texturesource      = tsrc;
	/*
	draw control pad
	0 1 2
	3 4 5
	for now only 0, 1, 2, and 4 are used
	*/
	int number = 0;
	for (int y = 0; y < 2; ++y)
		for (int x = 0; x < 3; ++x, ++number) {
			rect<s32> button_rect(
					x * button_size, m_screensize.Y - button_size * (2 - y),
					(x + 1) * button_size, m_screensize.Y - button_size * (1 - y)
			);
			touch_gui_button_id id = after_last_element_id;
			std::wstring caption;
			switch (number) {
			case 0:
				id = left_id;
				caption = L"<";
				break;
			case 1:
				id = forward_id;
				caption = L"^";
				break;
			case 2:
				id = right_id;
				caption = L">";
				break;
			case 4:
				id = backward_id;
				caption = L"v";
				break;
			}
			if (id != after_last_element_id) {
				initButton(id, button_rect, caption, false);
				}
		}

	/* init jump button */
	initButton(jump_id,
			rect<s32>(m_screensize.X-(1.75*button_size),
					m_screensize.Y - (0.5*button_size),
					m_screensize.X-(0.25*button_size),
					m_screensize.Y),
			L"x",false);

	/* init crunch button */
	initButton(crunch_id,
			rect<s32>(m_screensize.X-(3.25*button_size),
					m_screensize.Y - (0.5*button_size),
					m_screensize.X-(1.75*button_size),
					m_screensize.Y),
			L"H",false);

	m_settingsbar.init(m_texturesource, "gear_icon.png", settings_starter_id,
			v2s32(m_screensize.X - (button_size / 2),
					m_screensize.Y - ((SETTINGS_BAR_Y_OFFSET + 1) * button_size)
							+ (button_size * 0.5)),
			v2s32(m_screensize.X,
					m_screensize.Y - (SETTINGS_BAR_Y_OFFSET * button_size)
							+ (button_size * 0.5)), AHBB_Dir_Right_Left,
			3.0);

	m_settingsbar.addButton(fly_id,    L"fly",       "fly_btn.png");
	m_settingsbar.addButton(noclip_id, L"noclip",    "noclip_btn.png");
	m_settingsbar.addButton(fast_id,   L"fast",      "fast_btn.png");
	m_settingsbar.addButton(debug_id,  L"debug",     "debug_btn.png");
	m_settingsbar.addButton(camera_id, L"camera",    "camera_btn.png");
	m_settingsbar.addButton(range_id,  L"rangeview", "rangeview_btn.png");

	m_rarecontrolsbar.init(m_texturesource, "rare_controls.png",
			rare_controls_starter_id,
			v2s32(0,
					m_screensize.Y
							- ((RARE_CONTROLS_BAR_Y_OFFSET + 1) * button_size)
							+ (button_size * 0.5)),
			v2s32(button_size / 2,
					m_screensize.Y - (RARE_CONTROLS_BAR_Y_OFFSET * button_size)
							+ (button_size * 0.5)), AHBB_Dir_Left_Right,
			2);

	m_rarecontrolsbar.addButton(chat_id,      L"Chat", "chat_btn.png");
	m_rarecontrolsbar.addButton(inventory_id, L"inv",  "inventory_btn.png");
	m_rarecontrolsbar.addButton(drop_id,      L"drop", "drop_btn.png");

}

touch_gui_button_id TouchScreenGUI::getButtonID(s32 x, s32 y)
{
	IGUIElement* rootguielement = m_guienv->getRootGUIElement();

	if (rootguielement != NULL) {
		gui::IGUIElement *element =
				rootguielement->getElementFromPoint(core::position2d<s32>(x,y));

		if (element) {
			for (unsigned int i=0; i < after_last_element_id; i++) {
				if (element == m_buttons[i].guibutton) {
					return (touch_gui_button_id) i;
				}
			}
		}
	}
	return after_last_element_id;
}

touch_gui_button_id TouchScreenGUI::getButtonID(int eventID)
{
	for (unsigned int i=0; i < after_last_element_id; i++) {
		button_info* btn = &m_buttons[i];

		std::vector<int>::iterator id =
				std::find(btn->ids.begin(),btn->ids.end(), eventID);

		if (id != btn->ids.end())
			return (touch_gui_button_id) i;
	}

	return after_last_element_id;
}

bool TouchScreenGUI::isHUDButton(const SEvent &event)
{
	// check if hud item is pressed
	for (std::map<int,rect<s32> >::iterator iter = m_hud_rects.begin();
			iter != m_hud_rects.end(); ++iter) {
		if (iter->second.isPointInside(
				v2s32(event.TouchInput.X,
						event.TouchInput.Y)
			)) {
			if ( iter->first < 8) {
				SEvent* translated = new SEvent();
				memset(translated,0,sizeof(SEvent));
				translated->EventType = irr::EET_KEY_INPUT_EVENT;
				translated->KeyInput.Key         = (irr::EKEY_CODE) (KEY_KEY_1 + iter->first);
				translated->KeyInput.Control     = false;
				translated->KeyInput.Shift       = false;
				translated->KeyInput.PressedDown = true;
				m_receiver->OnEvent(*translated);
				m_hud_ids[event.TouchInput.ID]   = translated->KeyInput.Key;
				delete translated;
				return true;
			}
		}
	}
	return false;
}

bool TouchScreenGUI::isReleaseHUDButton(int eventID)
{
	std::map<int,irr::EKEY_CODE>::iterator iter = m_hud_ids.find(eventID);

	if (iter != m_hud_ids.end()) {
		SEvent* translated = new SEvent();
		memset(translated,0,sizeof(SEvent));
		translated->EventType            = irr::EET_KEY_INPUT_EVENT;
		translated->KeyInput.Key         = iter->second;
		translated->KeyInput.PressedDown = false;
		translated->KeyInput.Control     = false;
		translated->KeyInput.Shift       = false;
		m_receiver->OnEvent(*translated);
		m_hud_ids.erase(iter);
		delete translated;
		return true;
	}
	return false;
}

void TouchScreenGUI::handleButtonEvent(touch_gui_button_id button,
		int eventID, bool action)
{
	button_info* btn = &m_buttons[button];
	SEvent* translated = new SEvent();
	memset(translated,0,sizeof(SEvent));
	translated->EventType            = irr::EET_KEY_INPUT_EVENT;
	translated->KeyInput.Key         = btn->keycode;
	translated->KeyInput.Control     = false;
	translated->KeyInput.Shift       = false;
	translated->KeyInput.Char        = 0;

	/* add this event */
	if (action) {
		assert(std::find(btn->ids.begin(),btn->ids.end(), eventID) == btn->ids.end());

		btn->ids.push_back(eventID);

		if (btn->ids.size() > 1) return;

		btn->repeatcounter = 0;
		translated->KeyInput.PressedDown = true;
		translated->KeyInput.Key = btn->keycode;
		m_receiver->OnEvent(*translated);
	}
	/* remove event */
	if ((!action) || (btn->immediate_release)) {

		std::vector<int>::iterator pos =
				std::find(btn->ids.begin(),btn->ids.end(), eventID);
		/* has to be in touch list */
		assert(pos != btn->ids.end());
		btn->ids.erase(pos);

		if (btn->ids.size() > 0)  { return; }

		translated->KeyInput.PressedDown = false;
		btn->repeatcounter               = -1;
		m_receiver->OnEvent(*translated);
	}
	delete translated;
}


void TouchScreenGUI::handleReleaseEvent(int evt_id)
{
	touch_gui_button_id button = getButtonID(evt_id);

	/* handle button events */
	if (button != after_last_element_id) {
		handleButtonEvent(button, evt_id, false);
	}
	/* handle hud button events */
	else if (isReleaseHUDButton(evt_id)) {
		/* nothing to do here */
	} else if (m_settingsbar.isReleaseButton(evt_id)) {
		/* nothing to do here */
	} else if (m_rarecontrolsbar.isReleaseButton(evt_id)) {
		/* nothing to do here */
	}
	/* handle the point used for moving view */
	else if (evt_id == m_move_id) {
		m_move_id = -1;

		/* if this pointer issued a mouse event issue symmetric release here */
		if (m_move_sent_as_mouse_event) {
			SEvent* translated = new SEvent;
			memset(translated,0,sizeof(SEvent));
			translated->EventType               = EET_MOUSE_INPUT_EVENT;
			translated->MouseInput.X            = m_move_downlocation.X;
			translated->MouseInput.Y            = m_move_downlocation.Y;
			translated->MouseInput.Shift        = false;
			translated->MouseInput.Control      = false;
			translated->MouseInput.ButtonStates = 0;
			translated->MouseInput.Event        = EMIE_LMOUSE_LEFT_UP;
			m_receiver->OnEvent(*translated);
			delete translated;
		}
		else {
			/* do double tap detection */
			doubleTapDetection();
		}
	}
	else {
		infostream
			<< "TouchScreenGUI::translateEvent released unknown button: "
			<< evt_id << std::endl;
	}

	for (std::vector<id_status>::iterator iter = m_known_ids.begin();
			iter != m_known_ids.end(); ++iter) {
		if (iter->id == evt_id) {
			m_known_ids.erase(iter);
			break;
		}
	}
}

void TouchScreenGUI::translateEvent(const SEvent &event)
{
	if (!m_visible) {
		infostream << "TouchScreenGUI::translateEvent got event but not visible?!" << std::endl;
		return;
	}

	if (event.EventType != EET_TOUCH_INPUT_EVENT) {
		return;
	}

	if (event.TouchInput.Event == ETIE_PRESSED_DOWN) {

		/* add to own copy of eventlist ...
		 * android would provide this information but irrlicht guys don't
		 * wanna design a efficient interface
		 */
		id_status toadd;
		toadd.id = event.TouchInput.ID;
		toadd.X  = event.TouchInput.X;
		toadd.Y  = event.TouchInput.Y;
		m_known_ids.push_back(toadd);

		int eventID = event.TouchInput.ID;

		touch_gui_button_id button =
				getButtonID(event.TouchInput.X, event.TouchInput.Y);

		/* handle button events */
		if (button != after_last_element_id) {
			handleButtonEvent(button, eventID, true);
			m_settingsbar.deactivate();
			m_rarecontrolsbar.deactivate();
		} else if (isHUDButton(event)) {
			m_settingsbar.deactivate();
			m_rarecontrolsbar.deactivate();
			/* already handled in isHUDButton() */
		} else if (m_settingsbar.isButton(event)) {
			m_rarecontrolsbar.deactivate();
			/* already handled in isSettingsBarButton() */
		} else if (m_rarecontrolsbar.isButton(event)) {
			m_settingsbar.deactivate();
			/* already handled in isSettingsBarButton() */
		}
		/* handle non button events */
		else {
			m_settingsbar.deactivate();
			m_rarecontrolsbar.deactivate();
			/* if we don't already have a moving point make this the moving one */
			if (m_move_id == -1) {
				m_move_id                  = event.TouchInput.ID;
				m_move_has_really_moved    = false;
				m_move_downtime            = porting::getTimeMs();
				m_move_downlocation        = v2s32(event.TouchInput.X, event.TouchInput.Y);
				m_move_sent_as_mouse_event = false;
			}
		}

		m_pointerpos[event.TouchInput.ID] = v2s32(event.TouchInput.X, event.TouchInput.Y);
	}
	else if (event.TouchInput.Event == ETIE_LEFT_UP) {
		verbosestream << "Up event for pointerid: " << event.TouchInput.ID << std::endl;
		handleReleaseEvent(event.TouchInput.ID);
	}
	else {
		assert(event.TouchInput.Event == ETIE_MOVED);
		int move_idx = event.TouchInput.ID;

		if (m_pointerpos[event.TouchInput.ID] ==
				v2s32(event.TouchInput.X, event.TouchInput.Y)) {
			return;
		}

		if (m_move_id != -1) {
			if ((event.TouchInput.ID == m_move_id) &&
				(!m_move_sent_as_mouse_event)) {

				double distance = sqrt(
						(m_pointerpos[event.TouchInput.ID].X - event.TouchInput.X) *
						(m_pointerpos[event.TouchInput.ID].X - event.TouchInput.X) +
						(m_pointerpos[event.TouchInput.ID].Y - event.TouchInput.Y) *
						(m_pointerpos[event.TouchInput.ID].Y - event.TouchInput.Y));

				if ((distance > g_settings->getU16("touchscreen_threshold")) ||
						(m_move_has_really_moved)) {
					m_move_has_really_moved = true;
					s32 X = event.TouchInput.X;
					s32 Y = event.TouchInput.Y;

					// update camera_yaw and camera_pitch
					s32 dx = X - m_pointerpos[event.TouchInput.ID].X;
					s32 dy = Y - m_pointerpos[event.TouchInput.ID].Y;

					/* adapt to similar behaviour as pc screen */
					double d         = g_settings->getFloat("mouse_sensitivity") *4;
					double old_yaw   = m_camera_yaw_change;
					double old_pitch = m_camera_pitch;

					m_camera_yaw_change -= dx * d;
					m_camera_pitch = MYMIN(MYMAX(m_camera_pitch + (dy * d), -180), 180);

					// update shootline
					m_shootline = m_device
							->getSceneManager()
							->getSceneCollisionManager()
							->getRayFromScreenCoordinates(v2s32(X, Y));
					m_pointerpos[event.TouchInput.ID] = v2s32(X, Y);
				}
			}
			else if ((event.TouchInput.ID == m_move_id) &&
					(m_move_sent_as_mouse_event)) {
				m_shootline = m_device
						->getSceneManager()
						->getSceneCollisionManager()
						->getRayFromScreenCoordinates(
								v2s32(event.TouchInput.X,event.TouchInput.Y));
			}
		} else {
			handleChangedButton(event);
		}
	}
}

void TouchScreenGUI::handleChangedButton(const SEvent &event)
{
	for (unsigned int i = 0; i < after_last_element_id; i++) {

		if (m_buttons[i].ids.empty()) {
			continue;
		}
		for (std::vector<int>::iterator iter = m_buttons[i].ids.begin();
				iter != m_buttons[i].ids.end(); ++iter) {

			if (event.TouchInput.ID == *iter) {

				int current_button_id =
						getButtonID(event.TouchInput.X, event.TouchInput.Y);

				if (current_button_id == i) {
					continue;
				}

				/* remove old button */
				handleButtonEvent((touch_gui_button_id) i,*iter,false);

				if (current_button_id == after_last_element_id) {
					return;
				}
				handleButtonEvent((touch_gui_button_id) current_button_id,*iter,true);
				return;

			}
		}
	}

	int current_button_id = getButtonID(event.TouchInput.X, event.TouchInput.Y);

	if (current_button_id == after_last_element_id) {
		return;
	}

	button_info* btn = &m_buttons[current_button_id];
	if (std::find(btn->ids.begin(),btn->ids.end(), event.TouchInput.ID)
			== btn->ids.end())
	{
		handleButtonEvent((touch_gui_button_id) current_button_id,
				event.TouchInput.ID, true);
	}

}

bool TouchScreenGUI::doubleTapDetection()
{
	m_key_events[0].down_time = m_key_events[1].down_time;
	m_key_events[0].x         = m_key_events[1].x;
	m_key_events[0].y         = m_key_events[1].y;
	m_key_events[1].down_time = m_move_downtime;
	m_key_events[1].x         = m_move_downlocation.X;
	m_key_events[1].y         = m_move_downlocation.Y;

	u64 delta = porting::getDeltaMs(m_key_events[0].down_time, porting::getTimeMs());
	if (delta > 400)
		return false;

	double distance = sqrt(
			(m_key_events[0].x - m_key_events[1].x) * (m_key_events[0].x - m_key_events[1].x) +
			(m_key_events[0].y - m_key_events[1].y) * (m_key_events[0].y - m_key_events[1].y));


	if (distance > (20 + g_settings->getU16("touchscreen_threshold")))
		return false;

	SEvent* translated = new SEvent();
	memset(translated, 0, sizeof(SEvent));
	translated->EventType               = EET_MOUSE_INPUT_EVENT;
	translated->MouseInput.X            = m_key_events[0].x;
	translated->MouseInput.Y            = m_key_events[0].y;
	translated->MouseInput.Shift        = false;
	translated->MouseInput.Control      = false;
	translated->MouseInput.ButtonStates = EMBSM_RIGHT;

	// update shootline
	m_shootline = m_device
			->getSceneManager()
			->getSceneCollisionManager()
			->getRayFromScreenCoordinates(v2s32(m_key_events[0].x, m_key_events[0].y));

	translated->MouseInput.Event = EMIE_RMOUSE_PRESSED_DOWN;
	verbosestream << "TouchScreenGUI::translateEvent right click press" << std::endl;
	m_receiver->OnEvent(*translated);

	translated->MouseInput.ButtonStates = 0;
	translated->MouseInput.Event        = EMIE_RMOUSE_LEFT_UP;
	verbosestream << "TouchScreenGUI::translateEvent right click release" << std::endl;
	m_receiver->OnEvent(*translated);
	delete translated;
	return true;

}

TouchScreenGUI::~TouchScreenGUI()
{
	for (unsigned int i = 0; i < after_last_element_id; i++) {
		button_info* btn = &m_buttons[i];
		if (btn->guibutton != 0) {
			btn->guibutton->drop();
			btn->guibutton = NULL;
		}
	}
}

void TouchScreenGUI::step(float dtime)
{
	/* simulate keyboard repeats */
	for (unsigned int i = 0; i < after_last_element_id; i++) {
		button_info* btn = &m_buttons[i];

		if (btn->ids.size() > 0) {
			btn->repeatcounter += dtime;

			/* in case we're moving around digging does not happen */
			if (m_move_id != -1)
				m_move_has_really_moved = true;

			if (btn->repeatcounter < btn->repeatdelay) continue;

			btn->repeatcounter              = 0;
			SEvent translated;
			memset(&translated, 0, sizeof(SEvent));
			translated.EventType            = irr::EET_KEY_INPUT_EVENT;
			translated.KeyInput.Key         = btn->keycode;
			translated.KeyInput.PressedDown = false;
			m_receiver->OnEvent(translated);

			translated.KeyInput.PressedDown = true;
			m_receiver->OnEvent(translated);
		}
	}

	/* if a new placed pointer isn't moved for some time start digging */
	if ((m_move_id != -1) &&
			(!m_move_has_really_moved) &&
			(!m_move_sent_as_mouse_event)) {

		u64 delta = porting::getDeltaMs(m_move_downtime, porting::getTimeMs());

		if (delta > MIN_DIG_TIME_MS) {
			m_shootline = m_device
					->getSceneManager()
					->getSceneCollisionManager()
					->getRayFromScreenCoordinates(
							v2s32(m_move_downlocation.X,m_move_downlocation.Y));

			SEvent translated;
			memset(&translated, 0, sizeof(SEvent));
			translated.EventType               = EET_MOUSE_INPUT_EVENT;
			translated.MouseInput.X            = m_move_downlocation.X;
			translated.MouseInput.Y            = m_move_downlocation.Y;
			translated.MouseInput.Shift        = false;
			translated.MouseInput.Control      = false;
			translated.MouseInput.ButtonStates = EMBSM_LEFT;
			translated.MouseInput.Event        = EMIE_LMOUSE_PRESSED_DOWN;
			verbosestream << "TouchScreenGUI::step left click press" << std::endl;
			m_receiver->OnEvent(translated);
			m_move_sent_as_mouse_event         = true;
		}
	}

	m_settingsbar.step(dtime);
	m_rarecontrolsbar.step(dtime);
}

void TouchScreenGUI::resetHud()
{
	m_hud_rects.clear();
}

void TouchScreenGUI::registerHudItem(int index, const rect<s32> &rect)
{
	m_hud_rects[index] = rect;
}

void TouchScreenGUI::Toggle(bool visible)
{
	m_visible = visible;
	for (unsigned int i = 0; i < after_last_element_id; i++) {
		button_info* btn = &m_buttons[i];
		if (btn->guibutton != 0) {
			btn->guibutton->setVisible(visible);
		}
	}

	/* clear all active buttons */
	if (!visible) {
		while (m_known_ids.size() > 0) {
			handleReleaseEvent(m_known_ids.begin()->id);
		}

		m_settingsbar.hide();
		m_rarecontrolsbar.hide();
	} else {
		m_settingsbar.show();
		m_rarecontrolsbar.show();
	}
}

void TouchScreenGUI::hide()
{
	if (!m_visible)
		return;

	Toggle(false);
}

void TouchScreenGUI::show()
{
	if (m_visible)
		return;

	Toggle(true);
}
if (waving >= 1) material_type = TILE_MATERIAL_WAVING_PLANTS; break; case NDT_FIRELIKE: solidness = 0; break; case NDT_MESH: case NDT_NODEBOX: solidness = 0; if (waving == 1) { material_type = TILE_MATERIAL_WAVING_PLANTS; } else if (waving == 2) { material_type = TILE_MATERIAL_WAVING_LEAVES; } else if (waving == 3) { material_type = alpha == ALPHAMODE_OPAQUE ? TILE_MATERIAL_WAVING_LIQUID_OPAQUE : (alpha == ALPHAMODE_CLIP ? TILE_MATERIAL_WAVING_LIQUID_BASIC : TILE_MATERIAL_WAVING_LIQUID_TRANSPARENT); } break; case NDT_TORCHLIKE: case NDT_SIGNLIKE: case NDT_FENCELIKE: case NDT_RAILLIKE: solidness = 0; break; case NDT_PLANTLIKE_ROOTED: solidness = 2; break; } if (is_liquid) { if (waving == 3) { material_type = alpha == ALPHAMODE_OPAQUE ? TILE_MATERIAL_WAVING_LIQUID_OPAQUE : (alpha == ALPHAMODE_CLIP ? TILE_MATERIAL_WAVING_LIQUID_BASIC : TILE_MATERIAL_WAVING_LIQUID_TRANSPARENT); } else { material_type = alpha == ALPHAMODE_OPAQUE ? TILE_MATERIAL_LIQUID_OPAQUE : TILE_MATERIAL_LIQUID_TRANSPARENT; } } u32 tile_shader = shdsrc->getShader("nodes_shader", material_type, drawtype); MaterialType overlay_material = material_type; if (overlay_material == TILE_MATERIAL_OPAQUE) overlay_material = TILE_MATERIAL_BASIC; else if (overlay_material == TILE_MATERIAL_LIQUID_OPAQUE) overlay_material = TILE_MATERIAL_LIQUID_TRANSPARENT; u32 overlay_shader = shdsrc->getShader("nodes_shader", overlay_material, drawtype); // Tiles (fill in f->tiles[]) for (u16 j = 0; j < 6; j++) { tiles[j].world_aligned = isWorldAligned(tdef[j].align_style, tsettings.world_aligned_mode, drawtype); fillTileAttribs(tsrc, &tiles[j].layers[0], tiles[j], tdef[j], color, material_type, tile_shader, tdef[j].backface_culling, tsettings); if (!tdef_overlay[j].name.empty()) fillTileAttribs(tsrc, &tiles[j].layers[1], tiles[j], tdef_overlay[j], color, overlay_material, overlay_shader, tdef[j].backface_culling, tsettings); } MaterialType special_material = material_type; if (drawtype == NDT_PLANTLIKE_ROOTED) { if (waving == 1) special_material = TILE_MATERIAL_WAVING_PLANTS; else if (waving == 2) special_material = TILE_MATERIAL_WAVING_LEAVES; } u32 special_shader = shdsrc->getShader("nodes_shader", special_material, drawtype); // Special tiles (fill in f->special_tiles[]) for (u16 j = 0; j < CF_SPECIAL_COUNT; j++) fillTileAttribs(tsrc, &special_tiles[j].layers[0], special_tiles[j], tdef_spec[j], color, special_material, special_shader, tdef_spec[j].backface_culling, tsettings); if (param_type_2 == CPT2_COLOR || param_type_2 == CPT2_COLORED_FACEDIR || param_type_2 == CPT2_COLORED_WALLMOUNTED) palette = tsrc->getPalette(palette_name); if (drawtype == NDT_MESH && !mesh.empty()) { // Meshnode drawtype // Read the mesh and apply scale mesh_ptr[0] = client->getMesh(mesh); if (mesh_ptr[0]){ v3f scale = v3f(1.0, 1.0, 1.0) * BS * visual_scale; scaleMesh(mesh_ptr[0], scale); recalculateBoundingBox(mesh_ptr[0]); meshmanip->recalculateNormals(mesh_ptr[0], true, false); } } //Cache 6dfacedir and wallmounted rotated clones of meshes if (tsettings.enable_mesh_cache && mesh_ptr[0] && (param_type_2 == CPT2_FACEDIR || param_type_2 == CPT2_COLORED_FACEDIR)) { for (u16 j = 1; j < 24; j++) { mesh_ptr[j] = cloneMesh(mesh_ptr[0]); rotateMeshBy6dFacedir(mesh_ptr[j], j); recalculateBoundingBox(mesh_ptr[j]); meshmanip->recalculateNormals(mesh_ptr[j], true, false); } } else if (tsettings.enable_mesh_cache && mesh_ptr[0] && (param_type_2 == CPT2_WALLMOUNTED || param_type_2 == CPT2_COLORED_WALLMOUNTED)) { static const u8 wm_to_6d[6] = { 20, 0, 16 + 1, 12 + 3, 8, 4 + 2 }; for (u16 j = 1; j < 6; j++) { mesh_ptr[j] = cloneMesh(mesh_ptr[0]); rotateMeshBy6dFacedir(mesh_ptr[j], wm_to_6d[j]); recalculateBoundingBox(mesh_ptr[j]); meshmanip->recalculateNormals(mesh_ptr[j], true, false); } rotateMeshBy6dFacedir(mesh_ptr[0], wm_to_6d[0]); recalculateBoundingBox(mesh_ptr[0]); meshmanip->recalculateNormals(mesh_ptr[0], true, false); } } #endif /* NodeDefManager */ NodeDefManager::NodeDefManager() { clear(); } NodeDefManager::~NodeDefManager() { #ifndef SERVER for (ContentFeatures &f : m_content_features) { for (auto &j : f.mesh_ptr) { if (j) j->drop(); } } #endif } void NodeDefManager::clear() { m_content_features.clear(); m_name_id_mapping.clear(); m_name_id_mapping_with_aliases.clear(); m_group_to_items.clear(); m_next_id = 0; m_selection_box_union.reset(0,0,0); m_selection_box_int_union.reset(0,0,0); resetNodeResolveState(); u32 initial_length = 0; initial_length = MYMAX(initial_length, CONTENT_UNKNOWN + 1); initial_length = MYMAX(initial_length, CONTENT_AIR + 1); initial_length = MYMAX(initial_length, CONTENT_IGNORE + 1); m_content_features.resize(initial_length); // Set CONTENT_UNKNOWN { ContentFeatures f; f.name = "unknown"; // Insert directly into containers content_t c = CONTENT_UNKNOWN; m_content_features[c] = f; addNameIdMapping(c, f.name); } // Set CONTENT_AIR { ContentFeatures f; f.name = "air"; f.drawtype = NDT_AIRLIKE; f.param_type = CPT_LIGHT; f.light_propagates = true; f.sunlight_propagates = true; f.walkable = false; f.pointable = false; f.diggable = false; f.buildable_to = true; f.floodable = true; f.is_ground_content = true; // Insert directly into containers content_t c = CONTENT_AIR; m_content_features[c] = f; addNameIdMapping(c, f.name); } // Set CONTENT_IGNORE { ContentFeatures f; f.name = "ignore"; f.drawtype = NDT_AIRLIKE; f.param_type = CPT_NONE; f.light_propagates = false; f.sunlight_propagates = false; f.walkable = false; f.pointable = false; f.diggable = false; f.buildable_to = true; // A way to remove accidental CONTENT_IGNOREs f.is_ground_content = true; // Insert directly into containers content_t c = CONTENT_IGNORE; m_content_features[c] = f; addNameIdMapping(c, f.name); } } bool NodeDefManager::getId(const std::string &name, content_t &result) const { std::unordered_map<std::string, content_t>::const_iterator i = m_name_id_mapping_with_aliases.find(name); if(i == m_name_id_mapping_with_aliases.end()) return false; result = i->second; return true; } content_t NodeDefManager::getId(const std::string &name) const { content_t id = CONTENT_IGNORE; getId(name, id); return id; } bool NodeDefManager::getIds(const std::string &name, std::vector<content_t> &result) const { //TimeTaker t("getIds", NULL, PRECISION_MICRO); if (name.substr(0,6) != "group:") { content_t id = CONTENT_IGNORE; bool exists = getId(name, id); if (exists) result.push_back(id); return exists; } std::string group = name.substr(6); std::unordered_map<std::string, std::vector<content_t>>::const_iterator i = m_group_to_items.find(group); if (i == m_group_to_items.end()) return true; const std::vector<content_t> &items = i->second; result.insert(result.end(), items.begin(), items.end()); //printf("getIds: %dus\n", t.stop()); return true; } const ContentFeatures& NodeDefManager::get(const std::string &name) const { content_t id = CONTENT_UNKNOWN; getId(name, id); return get(id); } // returns CONTENT_IGNORE if no free ID found content_t NodeDefManager::allocateId() { for (content_t id = m_next_id; id >= m_next_id; // overflow? ++id) { while (id >= m_content_features.size()) { m_content_features.emplace_back(); } const ContentFeatures &f = m_content_features[id]; if (f.name.empty()) { m_next_id = id + 1; return id; } } // If we arrive here, an overflow occurred in id. // That means no ID was found return CONTENT_IGNORE; } /*! * Returns the smallest box that contains all boxes * in the vector. Box_union is expanded. * @param[in] boxes the vector containing the boxes * @param[in, out] box_union the union of the arguments */ void boxVectorUnion(const std::vector<aabb3f> &boxes, aabb3f *box_union) { for (const aabb3f &box : boxes) { box_union->addInternalBox(box); } } /*! * Returns a box that contains the nodebox in every case. * The argument node_union is expanded. * @param[in] nodebox the nodebox to be measured * @param[in] features used to decide whether the nodebox * can be rotated * @param[in, out] box_union the union of the arguments */ void getNodeBoxUnion(const NodeBox &nodebox, const ContentFeatures &features, aabb3f *box_union) { switch(nodebox.type) { case NODEBOX_FIXED: case NODEBOX_LEVELED: { // Raw union aabb3f half_processed(0, 0, 0, 0, 0, 0); boxVectorUnion(nodebox.fixed, &half_processed); // Set leveled boxes to maximal if (nodebox.type == NODEBOX_LEVELED) { half_processed.MaxEdge.Y = +BS / 2; } if (features.param_type_2 == CPT2_FACEDIR || features.param_type_2 == CPT2_COLORED_FACEDIR) { // Get maximal coordinate f32 coords[] = { fabsf(half_processed.MinEdge.X), fabsf(half_processed.MinEdge.Y), fabsf(half_processed.MinEdge.Z), fabsf(half_processed.MaxEdge.X), fabsf(half_processed.MaxEdge.Y), fabsf(half_processed.MaxEdge.Z) }; f32 max = 0; for (float coord : coords) { if (max < coord) { max = coord; } } // Add the union of all possible rotated boxes box_union->addInternalPoint(-max, -max, -max); box_union->addInternalPoint(+max, +max, +max); } else { box_union->addInternalBox(half_processed); } break; } case NODEBOX_WALLMOUNTED: { // Add fix boxes box_union->addInternalBox(nodebox.wall_top); box_union->addInternalBox(nodebox.wall_bottom); // Find maximal coordinate in the X-Z plane f32 coords[] = { fabsf(nodebox.wall_side.MinEdge.X), fabsf(nodebox.wall_side.MinEdge.Z), fabsf(nodebox.wall_side.MaxEdge.X), fabsf(nodebox.wall_side.MaxEdge.Z) }; f32 max = 0; for (float coord : coords) { if (max < coord) { max = coord; } } // Add the union of all possible rotated boxes box_union->addInternalPoint(-max, nodebox.wall_side.MinEdge.Y, -max); box_union->addInternalPoint(max, nodebox.wall_side.MaxEdge.Y, max); break; } case NODEBOX_CONNECTED: { // Add all possible connected boxes boxVectorUnion(nodebox.fixed, box_union); boxVectorUnion(nodebox.connect_top, box_union); boxVectorUnion(nodebox.connect_bottom, box_union); boxVectorUnion(nodebox.connect_front, box_union); boxVectorUnion(nodebox.connect_left, box_union); boxVectorUnion(nodebox.connect_back, box_union); boxVectorUnion(nodebox.connect_right, box_union); boxVectorUnion(nodebox.disconnected_top, box_union); boxVectorUnion(nodebox.disconnected_bottom, box_union); boxVectorUnion(nodebox.disconnected_front, box_union); boxVectorUnion(nodebox.disconnected_left, box_union); boxVectorUnion(nodebox.disconnected_back, box_union); boxVectorUnion(nodebox.disconnected_right, box_union); boxVectorUnion(nodebox.disconnected, box_union); boxVectorUnion(nodebox.disconnected_sides, box_union); break; } default: { // NODEBOX_REGULAR box_union->addInternalPoint(-BS / 2, -BS / 2, -BS / 2); box_union->addInternalPoint(+BS / 2, +BS / 2, +BS / 2); } } } inline void NodeDefManager::fixSelectionBoxIntUnion() { m_selection_box_int_union.MinEdge.X = floorf( m_selection_box_union.MinEdge.X / BS + 0.5f); m_selection_box_int_union.MinEdge.Y = floorf( m_selection_box_union.MinEdge.Y / BS + 0.5f); m_selection_box_int_union.MinEdge.Z = floorf( m_selection_box_union.MinEdge.Z / BS + 0.5f); m_selection_box_int_union.MaxEdge.X = ceilf( m_selection_box_union.MaxEdge.X / BS - 0.5f); m_selection_box_int_union.MaxEdge.Y = ceilf( m_selection_box_union.MaxEdge.Y / BS - 0.5f); m_selection_box_int_union.MaxEdge.Z = ceilf( m_selection_box_union.MaxEdge.Z / BS - 0.5f); } void NodeDefManager::eraseIdFromGroups(content_t id) { // For all groups in m_group_to_items... for (auto iter_groups = m_group_to_items.begin(); iter_groups != m_group_to_items.end();) { // Get the group items vector. std::vector<content_t> &items = iter_groups->second; // Remove any occurence of the id in the group items vector. items.erase(std::remove(items.begin(), items.end(), id), items.end()); // If group is empty, erase its vector from the map. if (items.empty()) iter_groups = m_group_to_items.erase(iter_groups); else ++iter_groups; } } // IWritableNodeDefManager content_t NodeDefManager::set(const std::string &name, const ContentFeatures &def) { // Pre-conditions assert(name != ""); assert(name != "ignore"); assert(name == def.name); content_t id = CONTENT_IGNORE; if (!m_name_id_mapping.getId(name, id)) { // ignore aliases // Get new id id = allocateId(); if (id == CONTENT_IGNORE) { warningstream << "NodeDefManager: Absolute " "limit reached" << std::endl; return CONTENT_IGNORE; } assert(id != CONTENT_IGNORE); addNameIdMapping(id, name); } // If there is already ContentFeatures registered for this id, clear old groups if (id < m_content_features.size()) eraseIdFromGroups(id); m_content_features[id] = def; verbosestream << "NodeDefManager: registering content id \"" << id << "\": name=\"" << def.name << "\""<<std::endl; getNodeBoxUnion(def.selection_box, def, &m_selection_box_union); fixSelectionBoxIntUnion(); // Add this content to the list of all groups it belongs to for (const auto &group : def.groups) { const std::string &group_name = group.first; m_group_to_items[group_name].push_back(id); } return id; } content_t NodeDefManager::allocateDummy(const std::string &name) { assert(name != ""); // Pre-condition ContentFeatures f; f.name = name; return set(name, f); } void NodeDefManager::removeNode(const std::string &name) { // Pre-condition assert(name != ""); // Erase name from name ID mapping content_t id = CONTENT_IGNORE; if (m_name_id_mapping.getId(name, id)) { m_name_id_mapping.eraseName(name); m_name_id_mapping_with_aliases.erase(name); } eraseIdFromGroups(id); } void NodeDefManager::updateAliases(IItemDefManager *idef) { std::set<std::string> all; idef->getAll(all); m_name_id_mapping_with_aliases.clear(); for (const std::string &name : all) { const std::string &convert_to = idef->getAlias(name); content_t id; if (m_name_id_mapping.getId(convert_to, id)) { m_name_id_mapping_with_aliases.insert( std::make_pair(name, id)); } } } void NodeDefManager::applyTextureOverrides(const std::vector<TextureOverride> &overrides) { infostream << "NodeDefManager::applyTextureOverrides(): Applying " "overrides to textures" << std::endl; for (const TextureOverride& texture_override : overrides) { content_t id; if (!getId(texture_override.id, id)) continue; // Ignore unknown node ContentFeatures &nodedef = m_content_features[id]; // Override tiles if (texture_override.hasTarget(OverrideTarget::TOP)) nodedef.tiledef[0].name = texture_override.texture; if (texture_override.hasTarget(OverrideTarget::BOTTOM)) nodedef.tiledef[1].name = texture_override.texture; if (texture_override.hasTarget(OverrideTarget::RIGHT)) nodedef.tiledef[2].name = texture_override.texture; if (texture_override.hasTarget(OverrideTarget::LEFT)) nodedef.tiledef[3].name = texture_override.texture; if (texture_override.hasTarget(OverrideTarget::BACK)) nodedef.tiledef[4].name = texture_override.texture; if (texture_override.hasTarget(OverrideTarget::FRONT)) nodedef.tiledef[5].name = texture_override.texture; // Override special tiles, if applicable if (texture_override.hasTarget(OverrideTarget::SPECIAL_1)) nodedef.tiledef_special[0].name = texture_override.texture; if (texture_override.hasTarget(OverrideTarget::SPECIAL_2)) nodedef.tiledef_special[1].name = texture_override.texture; if (texture_override.hasTarget(OverrideTarget::SPECIAL_3)) nodedef.tiledef_special[2].name = texture_override.texture; if (texture_override.hasTarget(OverrideTarget::SPECIAL_4)) nodedef.tiledef_special[3].name = texture_override.texture; if (texture_override.hasTarget(OverrideTarget::SPECIAL_5)) nodedef.tiledef_special[4].name = texture_override.texture; if (texture_override.hasTarget(OverrideTarget::SPECIAL_6)) nodedef.tiledef_special[5].name = texture_override.texture; } } void NodeDefManager::updateTextures(IGameDef *gamedef, void (*progress_callback)(void *progress_args, u32 progress, u32 max_progress), void *progress_callback_args) { #ifndef SERVER infostream << "NodeDefManager::updateTextures(): Updating " "textures in node definitions" << std::endl; Client *client = (Client *)gamedef; ITextureSource *tsrc = client->tsrc(); IShaderSource *shdsrc = client->getShaderSource(); scene::IMeshManipulator *meshmanip = RenderingEngine::get_scene_manager()->getMeshManipulator(); TextureSettings tsettings; tsettings.readSettings(); u32 size = m_content_features.size(); for (u32 i = 0; i < size; i++) { ContentFeatures *f = &(m_content_features[i]); f->updateTextures(tsrc, shdsrc, meshmanip, client, tsettings); progress_callback(progress_callback_args, i, size); } #endif } void NodeDefManager::serialize(std::ostream &os, u16 protocol_version) const { writeU8(os, 1); // version u16 count = 0; std::ostringstream os2(std::ios::binary); for (u32 i = 0; i < m_content_features.size(); i++) { if (i == CONTENT_IGNORE || i == CONTENT_AIR || i == CONTENT_UNKNOWN) continue; const ContentFeatures *f = &m_content_features[i]; if (f->name.empty()) continue; writeU16(os2, i); // Wrap it in a string to allow different lengths without // strict version incompatibilities std::ostringstream wrapper_os(std::ios::binary); f->serialize(wrapper_os, protocol_version); os2<<serializeString16(wrapper_os.str()); // must not overflow u16 next = count + 1; FATAL_ERROR_IF(next < count, "Overflow"); count++; } writeU16(os, count); os << serializeString32(os2.str()); } void NodeDefManager::deSerialize(std::istream &is) { clear(); int version = readU8(is); if (version != 1) throw SerializationError("unsupported NodeDefinitionManager version"); u16 count = readU16(is); std::istringstream is2(deSerializeString32(is), std::ios::binary); ContentFeatures f; for (u16 n = 0; n < count; n++) { u16 i = readU16(is2); // Read it from the string wrapper std::string wrapper = deSerializeString16(is2); std::istringstream wrapper_is(wrapper, std::ios::binary); f.deSerialize(wrapper_is); // Check error conditions if (i == CONTENT_IGNORE || i == CONTENT_AIR || i == CONTENT_UNKNOWN) { warningstream << "NodeDefManager::deSerialize(): " "not changing builtin node " << i << std::endl; continue; } if (f.name.empty()) { warningstream << "NodeDefManager::deSerialize(): " "received empty name" << std::endl; continue; } // Ignore aliases u16 existing_id; if (m_name_id_mapping.getId(f.name, existing_id) && i != existing_id) { warningstream << "NodeDefManager::deSerialize(): " "already defined with different ID: " << f.name << std::endl; continue; } // All is ok, add node definition with the requested ID if (i >= m_content_features.size()) m_content_features.resize((u32)(i) + 1); m_content_features[i] = f; addNameIdMapping(i, f.name); TRACESTREAM(<< "NodeDef: deserialized " << f.name << std::endl); getNodeBoxUnion(f.selection_box, f, &m_selection_box_union); fixSelectionBoxIntUnion(); } // Since liquid_alternative_flowing_id and liquid_alternative_source_id // are not sent, resolve them client-side too. resolveCrossrefs(); } void NodeDefManager::addNameIdMapping(content_t i, std::string name) { m_name_id_mapping.set(i, name); m_name_id_mapping_with_aliases.insert(std::make_pair(name, i)); } NodeDefManager *createNodeDefManager() { return new NodeDefManager(); } void NodeDefManager::pendNodeResolve(NodeResolver *nr) const { nr->m_ndef = this; if (m_node_registration_complete) nr->nodeResolveInternal(); else m_pending_resolve_callbacks.push_back(nr); } bool NodeDefManager::cancelNodeResolveCallback(NodeResolver *nr) const { size_t len = m_pending_resolve_callbacks.size(); for (size_t i = 0; i != len; i++) { if (nr != m_pending_resolve_callbacks[i]) continue; len--; m_pending_resolve_callbacks[i] = m_pending_resolve_callbacks[len]; m_pending_resolve_callbacks.resize(len); return true; } return false; } void NodeDefManager::runNodeResolveCallbacks() { for (size_t i = 0; i != m_pending_resolve_callbacks.size(); i++) { NodeResolver *nr = m_pending_resolve_callbacks[i]; nr->nodeResolveInternal(); } m_pending_resolve_callbacks.clear(); } void NodeDefManager::resetNodeResolveState() { m_node_registration_complete = false; m_pending_resolve_callbacks.clear(); } static void removeDupes(std::vector<content_t> &list) { std::sort(list.begin(), list.end()); auto new_end = std::unique(list.begin(), list.end()); list.erase(new_end, list.end()); } void NodeDefManager::resolveCrossrefs() { for (ContentFeatures &f : m_content_features) { if (f.liquid_type != LIQUID_NONE || f.drawtype == NDT_LIQUID || f.drawtype == NDT_FLOWINGLIQUID) { f.liquid_alternative_flowing_id = getId(f.liquid_alternative_flowing); f.liquid_alternative_source_id = getId(f.liquid_alternative_source); continue; } if (f.drawtype != NDT_NODEBOX || f.node_box.type != NODEBOX_CONNECTED) continue; for (const std::string &name : f.connects_to) { getIds(name, f.connects_to_ids); } removeDupes(f.connects_to_ids); } } bool NodeDefManager::nodeboxConnects(MapNode from, MapNode to, u8 connect_face) const { const ContentFeatures &f1 = get(from); if ((f1.drawtype != NDT_NODEBOX) || (f1.node_box.type != NODEBOX_CONNECTED)) return false; // lookup target in connected set if (!CONTAINS(f1.connects_to_ids, to.param0)) return false; const ContentFeatures &f2 = get(to); if ((f2.drawtype == NDT_NODEBOX) && (f2.node_box.type == NODEBOX_CONNECTED)) // ignores actually looking if back connection exists return CONTAINS(f2.connects_to_ids, from.param0); // does to node declare usable faces? if (f2.connect_sides > 0) { if ((f2.param_type_2 == CPT2_FACEDIR || f2.param_type_2 == CPT2_COLORED_FACEDIR) && (connect_face >= 4)) { static const u8 rot[33 * 4] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 32, 16, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 4 - back 8, 4, 32, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 8 - right 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 8, 4, 32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 16 - front 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 32, 16, 8, 4 // 32 - left }; return (f2.connect_sides & rot[(connect_face * 4) + (to.param2 & 0x1F)]); } return (f2.connect_sides & connect_face); } // the target is just a regular node, so connect no matter back connection return true; } //// //// NodeResolver //// NodeResolver::NodeResolver() { m_nodenames.reserve(16); m_nnlistsizes.reserve(4); } NodeResolver::~NodeResolver() { if (!m_resolve_done && m_ndef) m_ndef->cancelNodeResolveCallback(this); } void NodeResolver::cloneTo(NodeResolver *res) const { FATAL_ERROR_IF(!m_resolve_done, "NodeResolver can only be cloned" " after resolving has completed"); /* We don't actually do anything significant. Since the node resolving has * already completed, the class that called us will already have the * resolved IDs in its data structures (which it copies on its own) */ res->m_ndef = m_ndef; res->m_resolve_done = true; } void NodeResolver::nodeResolveInternal() { m_nodenames_idx = 0; m_nnlistsizes_idx = 0; resolveNodeNames(); m_resolve_done = true; m_nodenames.clear(); m_nnlistsizes.clear(); } bool NodeResolver::getIdFromNrBacklog(content_t *result_out, const std::string &node_alt, content_t c_fallback, bool error_on_fallback) { if (m_nodenames_idx == m_nodenames.size()) { *result_out = c_fallback; errorstream << "NodeResolver: no more nodes in list" << std::endl; return false; } content_t c; std::string name = m_nodenames[m_nodenames_idx++]; bool success = m_ndef->getId(name, c); if (!success && !node_alt.empty()) { name = node_alt; success = m_ndef->getId(name, c); } if (!success) { if (error_on_fallback) errorstream << "NodeResolver: failed to resolve node name '" << name << "'." << std::endl; c = c_fallback; } *result_out = c; return success; } bool NodeResolver::getIdsFromNrBacklog(std::vector<content_t> *result_out, bool all_required, content_t c_fallback) { bool success = true; if (m_nnlistsizes_idx == m_nnlistsizes.size()) { errorstream << "NodeResolver: no more node lists" << std::endl; return false; } size_t length = m_nnlistsizes[m_nnlistsizes_idx++]; while (length--) { if (m_nodenames_idx == m_nodenames.size()) { errorstream << "NodeResolver: no more nodes in list" << std::endl; return false; } content_t c; std::string &name = m_nodenames[m_nodenames_idx++]; if (name.substr(0,6) != "group:") { if (m_ndef->getId(name, c)) { result_out->push_back(c); } else if (all_required) { errorstream << "NodeResolver: failed to resolve node name '" << name << "'." << std::endl; result_out->push_back(c_fallback); success = false; } } else { m_ndef->getIds(name, *result_out); } } return success; }