code
string
repo_name
string
path
string
language
string
license
string
size
int64
/* Minetest Copyright (C) 2013 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. */ #pragma once /******************************************************************************/ /* Includes */ /******************************************************************************/ #include "irrlichttypes.h" #include "modalMenu.h" #include "guiFormSpecMenu.h" #include "client/sound.h" #include "client/tile.h" #include "util/enriched_string.h" /******************************************************************************/ /* Typedefs and macros */ /******************************************************************************/ /** texture layer ids */ typedef enum { TEX_LAYER_BACKGROUND = 0, TEX_LAYER_OVERLAY, TEX_LAYER_HEADER, TEX_LAYER_FOOTER, TEX_LAYER_MAX } texture_layer; typedef struct { video::ITexture *texture = nullptr; bool tile; unsigned int minsize; } image_definition; /******************************************************************************/ /* forward declarations */ /******************************************************************************/ class GUIEngine; class MainMenuScripting; class Clouds; struct MainMenuData; /******************************************************************************/ /* declarations */ /******************************************************************************/ /** GUIEngine specific implementation of TextDest used within guiFormSpecMenu */ class TextDestGuiEngine : public TextDest { public: /** * default constructor * @param engine the engine data is transmitted for further processing */ TextDestGuiEngine(GUIEngine* engine) : m_engine(engine) {}; /** * receive fields transmitted by guiFormSpecMenu * @param fields map containing formspec field elements currently active */ void gotText(const StringMap &fields); /** * receive text/events transmitted by guiFormSpecMenu * @param text textual representation of event */ void gotText(const std::wstring &text); private: /** target to transmit data to */ GUIEngine *m_engine = nullptr; }; /** GUIEngine specific implementation of ISimpleTextureSource */ class MenuTextureSource : public ISimpleTextureSource { public: /** * default constructor * @param driver the video driver to load textures from */ MenuTextureSource(video::IVideoDriver *driver) : m_driver(driver) {}; /** * destructor, removes all loaded textures */ virtual ~MenuTextureSource(); /** * get a texture, loading it if required * @param name path to the texture * @param id receives the texture ID, always 0 in this implementation */ video::ITexture *getTexture(const std::string &name, u32 *id = NULL); private: /** driver to get textures from */ video::IVideoDriver *m_driver = nullptr; /** set of texture names to delete */ std::set<std::string> m_to_delete; }; /** GUIEngine specific implementation of OnDemandSoundFetcher */ class MenuMusicFetcher: public OnDemandSoundFetcher { public: /** * get sound file paths according to sound name * @param name sound name * @param dst_paths receives possible paths to sound files * @param dst_datas receives binary sound data (not used here) */ void fetchSounds(const std::string &name, std::set<std::string> &dst_paths, std::set<std::string> &dst_datas); private: /** set of fetched sound names */ std::set<std::string> m_fetched; }; /** implementation of main menu based uppon formspecs */ class GUIEngine { /** grant ModApiMainMenu access to private members */ friend class ModApiMainMenu; friend class ModApiSound; public: /** * default constructor * @param dev device to draw at * @param parent parent gui element * @param menumgr manager to add menus to * @param smgr scene manager to add scene elements to * @param data struct to transfer data to main game handling */ GUIEngine(JoystickController *joystick, gui::IGUIElement *parent, IMenuManager *menumgr, MainMenuData *data, bool &kill); /** default destructor */ virtual ~GUIEngine(); /** * return MainMenuScripting interface */ MainMenuScripting *getScriptIface() { return m_script; } /** * return dir of current menuscript */ std::string getScriptDir() { return m_scriptdir; } /** pass async callback to scriptengine **/ unsigned int queueAsync(const std::string &serialized_fct, const std::string &serialized_params); private: /** find and run the main menu script */ bool loadMainMenuScript(); /** run main menu loop */ void run(); /** update size of topleftext element */ void updateTopLeftTextSize(); /** parent gui element */ gui::IGUIElement *m_parent = nullptr; /** manager to add menus to */ IMenuManager *m_menumanager = nullptr; /** scene manager to add scene elements to */ scene::ISceneManager *m_smgr = nullptr; /** pointer to data beeing transfered back to main game handling */ MainMenuData *m_data = nullptr; /** pointer to texture source */ ISimpleTextureSource *m_texture_source = nullptr; /** pointer to soundmanager*/ ISoundManager *m_sound_manager = nullptr; /** representation of form source to be used in mainmenu formspec */ FormspecFormSource *m_formspecgui = nullptr; /** formspec input receiver */ TextDestGuiEngine *m_buttonhandler = nullptr; /** the formspec menu */ GUIFormSpecMenu *m_menu = nullptr; /** reference to kill variable managed by SIGINT handler */ bool &m_kill; /** variable used to abort menu and return back to main game handling */ bool m_startgame = false; /** scripting interface */ MainMenuScripting *m_script = nullptr; /** script basefolder */ std::string m_scriptdir = ""; /** * draw background layer * @param driver to use for drawing */ void drawBackground(video::IVideoDriver *driver); /** * draw overlay layer * @param driver to use for drawing */ void drawOverlay(video::IVideoDriver *driver); /** * draw header layer * @param driver to use for drawing */ void drawHeader(video::IVideoDriver *driver); /** * draw footer layer * @param driver to use for drawing */ void drawFooter(video::IVideoDriver *driver); /** * load a texture for a specified layer * @param layer draw layer to specify texture * @param texturepath full path of texture to load */ bool setTexture(texture_layer layer, std::string texturepath, bool tile_image, unsigned int minsize); /** * download a file using curl * @param url url to download * @param target file to store to */ static bool downloadFile(const std::string &url, const std::string &target); /** array containing pointers to current specified texture layers */ image_definition m_textures[TEX_LAYER_MAX]; /** * specify text to appear as top left string * @param text to set */ void setTopleftText(const std::string &text); /** pointer to gui element shown at topleft corner */ irr::gui::IGUIStaticText *m_irr_toplefttext = nullptr; /** and text that is in it */ EnrichedString m_toplefttext; /** initialize cloud subsystem */ void cloudInit(); /** do preprocessing for cloud subsystem */ void cloudPreProcess(); /** do postprocessing for cloud subsystem */ void cloudPostProcess(); /** internam data required for drawing clouds */ struct clouddata { /** delta time since last cloud processing */ f32 dtime; /** absolute time of last cloud processing */ u32 lasttime; /** pointer to cloud class */ Clouds *clouds = nullptr; /** camera required for drawing clouds */ scene::ICameraSceneNode *camera = nullptr; }; /** is drawing of clouds enabled atm */ bool m_clouds_enabled = true; /** data used to draw clouds */ clouddata m_cloud; /** start playing a sound and return handle */ s32 playSound(SimpleSoundSpec spec, bool looped); /** stop playing a sound started with playSound() */ void stopSound(s32 handle); };
pgimeno/minetest
src/gui/guiEngine.h
C++
mit
8,876
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> 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 <cstdlib> #include <algorithm> #include <iterator> #include <sstream> #include <limits> #include "guiFormSpecMenu.h" #include "guiTable.h" #include "constants.h" #include "gamedef.h" #include "client/keycode.h" #include "util/strfnd.h" #include <IGUICheckBox.h> #include <IGUIEditBox.h> #include <IGUIButton.h> #include <IGUIStaticText.h> #include <IGUIFont.h> #include <IGUITabControl.h> #include <IGUIComboBox.h> #include "client/renderingengine.h" #include "log.h" #include "client/tile.h" // ITextureSource #include "client/hud.h" // drawItemStack #include "filesys.h" #include "gettime.h" #include "gettext.h" #include "scripting_server.h" #include "mainmenumanager.h" #include "porting.h" #include "settings.h" #include "client/client.h" #include "client/fontengine.h" #include "util/hex.h" #include "util/numeric.h" #include "util/string.h" // for parseColorString() #include "irrlicht_changes/static_text.h" #include "client/guiscalingfilter.h" #include "guiEditBoxWithScrollbar.h" #include "intlGUIEditBox.h" #define MY_CHECKPOS(a,b) \ if (v_pos.size() != 2) { \ errorstream<< "Invalid pos for element " << a << "specified: \"" \ << parts[b] << "\"" << std::endl; \ return; \ } #define MY_CHECKGEOM(a,b) \ if (v_geom.size() != 2) { \ errorstream<< "Invalid pos for element " << a << "specified: \"" \ << parts[b] << "\"" << std::endl; \ return; \ } /* GUIFormSpecMenu */ static unsigned int font_line_height(gui::IGUIFont *font) { return font->getDimension(L"Ay").Height + font->getKerningHeight(); } inline u32 clamp_u8(s32 value) { return (u32) MYMIN(MYMAX(value, 0), 255); } GUIFormSpecMenu::GUIFormSpecMenu(JoystickController *joystick, gui::IGUIElement *parent, s32 id, IMenuManager *menumgr, Client *client, ISimpleTextureSource *tsrc, IFormSource *fsrc, TextDest *tdst, std::string formspecPrepend, bool remap_dbl_click): GUIModalMenu(RenderingEngine::get_gui_env(), parent, id, menumgr), m_invmgr(client), m_tsrc(tsrc), m_client(client), m_formspec_prepend(formspecPrepend), m_form_src(fsrc), m_text_dst(tdst), m_joystick(joystick), m_remap_dbl_click(remap_dbl_click) { current_keys_pending.key_down = false; current_keys_pending.key_up = false; current_keys_pending.key_enter = false; current_keys_pending.key_escape = false; m_doubleclickdetect[0].time = 0; m_doubleclickdetect[1].time = 0; m_doubleclickdetect[0].pos = v2s32(0, 0); m_doubleclickdetect[1].pos = v2s32(0, 0); m_tooltip_show_delay = (u32)g_settings->getS32("tooltip_show_delay"); m_tooltip_append_itemname = g_settings->getBool("tooltip_append_itemname"); } GUIFormSpecMenu::~GUIFormSpecMenu() { removeChildren(); for (auto &table_it : m_tables) { table_it.second->drop(); } delete m_selected_item; delete m_form_src; delete m_text_dst; } void GUIFormSpecMenu::create(GUIFormSpecMenu *&cur_formspec, Client *client, JoystickController *joystick, IFormSource *fs_src, TextDest *txt_dest, const std::string &formspecPrepend) { if (cur_formspec == nullptr) { cur_formspec = new GUIFormSpecMenu(joystick, guiroot, -1, &g_menumgr, client, client->getTextureSource(), fs_src, txt_dest, formspecPrepend); cur_formspec->doPause = false; /* Caution: do not call (*cur_formspec)->drop() here -- the reference might outlive the menu, so we will periodically check if *cur_formspec is the only remaining reference (i.e. the menu was removed) and delete it in that case. */ } else { cur_formspec->setFormspecPrepend(formspecPrepend); cur_formspec->setFormSource(fs_src); cur_formspec->setTextDest(txt_dest); } } void GUIFormSpecMenu::removeChildren() { const core::list<gui::IGUIElement*> &children = getChildren(); while(!children.empty()) { (*children.getLast())->remove(); } if(m_tooltip_element) { m_tooltip_element->remove(); m_tooltip_element->drop(); m_tooltip_element = NULL; } } void GUIFormSpecMenu::setInitialFocus() { // Set initial focus according to following order of precedence: // 1. first empty editbox // 2. first editbox // 3. first table // 4. last button // 5. first focusable (not statictext, not tabheader) // 6. first child element core::list<gui::IGUIElement*> children = getChildren(); // in case "children" contains any NULL elements, remove them for (core::list<gui::IGUIElement*>::Iterator it = children.begin(); it != children.end();) { if (*it) ++it; else it = children.erase(it); } // 1. first empty editbox for (gui::IGUIElement *it : children) { if (it->getType() == gui::EGUIET_EDIT_BOX && it->getText()[0] == 0) { Environment->setFocus(it); return; } } // 2. first editbox for (gui::IGUIElement *it : children) { if (it->getType() == gui::EGUIET_EDIT_BOX) { Environment->setFocus(it); return; } } // 3. first table for (gui::IGUIElement *it : children) { if (it->getTypeName() == std::string("GUITable")) { Environment->setFocus(it); return; } } // 4. last button for (core::list<gui::IGUIElement*>::Iterator it = children.getLast(); it != children.end(); --it) { if ((*it)->getType() == gui::EGUIET_BUTTON) { Environment->setFocus(*it); return; } } // 5. first focusable (not statictext, not tabheader) for (gui::IGUIElement *it : children) { if (it->getType() != gui::EGUIET_STATIC_TEXT && it->getType() != gui::EGUIET_TAB_CONTROL) { Environment->setFocus(it); return; } } // 6. first child element if (children.empty()) Environment->setFocus(this); else Environment->setFocus(*(children.begin())); } GUITable* GUIFormSpecMenu::getTable(const std::string &tablename) { for (auto &table : m_tables) { if (tablename == table.first.fname) return table.second; } return 0; } std::vector<std::string>* GUIFormSpecMenu::getDropDownValues(const std::string &name) { for (auto &dropdown : m_dropdowns) { if (name == dropdown.first.fname) return &dropdown.second; } return NULL; } v2s32 GUIFormSpecMenu::getElementBasePos(bool absolute, const std::vector<std::string> *v_pos) { v2s32 pos = padding; if (absolute) pos += AbsoluteRect.UpperLeftCorner; v2f32 pos_f = v2f32(pos.X, pos.Y) + pos_offset * spacing; if (v_pos) { pos_f.X += stof((*v_pos)[0]) * spacing.X; pos_f.Y += stof((*v_pos)[1]) * spacing.Y; } return v2s32(pos_f.X, pos_f.Y); } void GUIFormSpecMenu::parseSize(parserData* data, const std::string &element) { std::vector<std::string> parts = split(element,','); if (((parts.size() == 2) || parts.size() == 3) || ((parts.size() > 3) && (m_formspec_version > FORMSPEC_API_VERSION))) { if (parts[1].find(';') != std::string::npos) parts[1] = parts[1].substr(0,parts[1].find(';')); data->invsize.X = MYMAX(0, stof(parts[0])); data->invsize.Y = MYMAX(0, stof(parts[1])); lockSize(false); #ifndef __ANDROID__ if (parts.size() == 3) { if (parts[2] == "true") { lockSize(true,v2u32(800,600)); } } #endif data->explicit_size = true; return; } errorstream<< "Invalid size element (" << parts.size() << "): '" << element << "'" << std::endl; } void GUIFormSpecMenu::parseContainer(parserData* data, const std::string &element) { std::vector<std::string> parts = split(element, ','); if (parts.size() >= 2) { if (parts[1].find(';') != std::string::npos) parts[1] = parts[1].substr(0, parts[1].find(';')); container_stack.push(pos_offset); pos_offset.X += MYMAX(0, stof(parts[0])); pos_offset.Y += MYMAX(0, stof(parts[1])); return; } errorstream<< "Invalid container start element (" << parts.size() << "): '" << element << "'" << std::endl; } void GUIFormSpecMenu::parseContainerEnd(parserData* data) { if (container_stack.empty()) { errorstream<< "Invalid container end element, no matching container start element" << std::endl; } else { pos_offset = container_stack.top(); container_stack.pop(); } } void GUIFormSpecMenu::parseList(parserData* data, const std::string &element) { if (m_client == 0) { warningstream<<"invalid use of 'list' with m_client==0"<<std::endl; return; } std::vector<std::string> parts = split(element,';'); if (((parts.size() == 4) || (parts.size() == 5)) || ((parts.size() > 5) && (m_formspec_version > FORMSPEC_API_VERSION))) { std::string location = parts[0]; std::string listname = parts[1]; std::vector<std::string> v_pos = split(parts[2],','); std::vector<std::string> v_geom = split(parts[3],','); std::string startindex; if (parts.size() == 5) startindex = parts[4]; MY_CHECKPOS("list",2); MY_CHECKGEOM("list",3); InventoryLocation loc; if(location == "context" || location == "current_name") loc = m_current_inventory_location; else loc.deSerialize(location); v2s32 pos = getElementBasePos(true, &v_pos); v2s32 geom; geom.X = stoi(v_geom[0]); geom.Y = stoi(v_geom[1]); s32 start_i = 0; if (!startindex.empty()) start_i = stoi(startindex); if (geom.X < 0 || geom.Y < 0 || start_i < 0) { errorstream<< "Invalid list element: '" << element << "'" << std::endl; return; } if(!data->explicit_size) warningstream<<"invalid use of list without a size[] element"<<std::endl; m_inventorylists.emplace_back(loc, listname, pos, geom, start_i); return; } errorstream<< "Invalid list element(" << parts.size() << "): '" << element << "'" << std::endl; } void GUIFormSpecMenu::parseListRing(parserData* data, const std::string &element) { if (m_client == 0) { errorstream << "WARNING: invalid use of 'listring' with m_client==0" << std::endl; return; } std::vector<std::string> parts = split(element, ';'); if (parts.size() == 2) { std::string location = parts[0]; std::string listname = parts[1]; InventoryLocation loc; if (location == "context" || location == "current_name") loc = m_current_inventory_location; else loc.deSerialize(location); m_inventory_rings.emplace_back(loc, listname); return; } if (element.empty() && m_inventorylists.size() > 1) { size_t siz = m_inventorylists.size(); // insert the last two inv list elements into the list ring const ListDrawSpec &spa = m_inventorylists[siz - 2]; const ListDrawSpec &spb = m_inventorylists[siz - 1]; m_inventory_rings.emplace_back(spa.inventoryloc, spa.listname); m_inventory_rings.emplace_back(spb.inventoryloc, spb.listname); return; } errorstream<< "Invalid list ring element(" << parts.size() << ", " << m_inventorylists.size() << "): '" << element << "'" << std::endl; } void GUIFormSpecMenu::parseCheckbox(parserData* data, const std::string &element) { std::vector<std::string> parts = split(element,';'); if (((parts.size() >= 3) && (parts.size() <= 4)) || ((parts.size() > 4) && (m_formspec_version > FORMSPEC_API_VERSION))) { std::vector<std::string> v_pos = split(parts[0],','); std::string name = parts[1]; std::string label = parts[2]; std::string selected; if (parts.size() >= 4) selected = parts[3]; MY_CHECKPOS("checkbox",0); v2s32 pos = getElementBasePos(false, &v_pos); bool fselected = false; if (selected == "true") fselected = true; std::wstring wlabel = translate_string(utf8_to_wide(unescape_string(label))); s32 spacing = Environment->getSkin()->getSize(gui::EGDS_CHECK_BOX_WIDTH) + 7; core::rect<s32> rect = core::rect<s32>( pos.X, pos.Y + ((imgsize.Y / 2) - m_btn_height), pos.X + m_font->getDimension(wlabel.c_str()).Width + spacing, pos.Y + ((imgsize.Y / 2) + m_btn_height)); FieldSpec spec( name, wlabel, //Needed for displaying text on MSVC wlabel, 258+m_fields.size() ); spec.ftype = f_CheckBox; gui::IGUICheckBox* e = Environment->addCheckBox(fselected, rect, this, spec.fid, spec.flabel.c_str()); if (spec.fname == data->focused_fieldname) { Environment->setFocus(e); } m_checkboxes.emplace_back(spec,e); m_fields.push_back(spec); return; } errorstream<< "Invalid checkbox element(" << parts.size() << "): '" << element << "'" << std::endl; } void GUIFormSpecMenu::parseScrollBar(parserData* data, const std::string &element) { std::vector<std::string> parts = split(element,';'); if (parts.size() >= 5) { std::vector<std::string> v_pos = split(parts[0],','); std::vector<std::string> v_dim = split(parts[1],','); std::string name = parts[3]; std::string value = parts[4]; MY_CHECKPOS("scrollbar",0); v2s32 pos = getElementBasePos(false, &v_pos); if (v_dim.size() != 2) { errorstream<< "Invalid size for element " << "scrollbar" << "specified: \"" << parts[1] << "\"" << std::endl; return; } v2s32 dim; dim.X = stof(v_dim[0]) * spacing.X; dim.Y = stof(v_dim[1]) * spacing.Y; core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X + dim.X, pos.Y + dim.Y); FieldSpec spec( name, L"", L"", 258+m_fields.size() ); bool is_horizontal = true; if (parts[2] == "vertical") is_horizontal = false; spec.ftype = f_ScrollBar; spec.send = true; gui::IGUIScrollBar* e = Environment->addScrollBar(is_horizontal,rect,this,spec.fid); e->setMax(1000); e->setMin(0); e->setPos(stoi(parts[4])); e->setSmallStep(10); e->setLargeStep(100); m_scrollbars.emplace_back(spec,e); m_fields.push_back(spec); return; } errorstream<< "Invalid scrollbar element(" << parts.size() << "): '" << element << "'" << std::endl; } void GUIFormSpecMenu::parseImage(parserData* data, const std::string &element) { std::vector<std::string> parts = split(element,';'); if ((parts.size() == 3) || ((parts.size() > 3) && (m_formspec_version > FORMSPEC_API_VERSION))) { std::vector<std::string> v_pos = split(parts[0],','); std::vector<std::string> v_geom = split(parts[1],','); std::string name = unescape_string(parts[2]); MY_CHECKPOS("image", 0); MY_CHECKGEOM("image", 1); v2s32 pos = getElementBasePos(true, &v_pos); v2s32 geom; geom.X = stof(v_geom[0]) * (float)imgsize.X; geom.Y = stof(v_geom[1]) * (float)imgsize.Y; if (!data->explicit_size) warningstream<<"invalid use of image without a size[] element"<<std::endl; m_images.emplace_back(name, pos, geom); return; } if (parts.size() == 2) { std::vector<std::string> v_pos = split(parts[0],','); std::string name = unescape_string(parts[1]); MY_CHECKPOS("image", 0); v2s32 pos = getElementBasePos(true, &v_pos); if (!data->explicit_size) warningstream<<"invalid use of image without a size[] element"<<std::endl; m_images.emplace_back(name, pos); return; } errorstream<< "Invalid image element(" << parts.size() << "): '" << element << "'" << std::endl; } void GUIFormSpecMenu::parseItemImage(parserData* data, const std::string &element) { std::vector<std::string> parts = split(element,';'); if ((parts.size() == 3) || ((parts.size() > 3) && (m_formspec_version > FORMSPEC_API_VERSION))) { std::vector<std::string> v_pos = split(parts[0],','); std::vector<std::string> v_geom = split(parts[1],','); std::string name = parts[2]; MY_CHECKPOS("itemimage",0); MY_CHECKGEOM("itemimage",1); v2s32 pos = getElementBasePos(true, &v_pos); v2s32 geom; geom.X = stof(v_geom[0]) * (float)imgsize.X; geom.Y = stof(v_geom[1]) * (float)imgsize.Y; if(!data->explicit_size) warningstream<<"invalid use of item_image without a size[] element"<<std::endl; m_itemimages.emplace_back("", name, pos, geom); return; } errorstream<< "Invalid ItemImage element(" << parts.size() << "): '" << element << "'" << std::endl; } void GUIFormSpecMenu::parseButton(parserData* data, const std::string &element, const std::string &type) { std::vector<std::string> parts = split(element,';'); if ((parts.size() == 4) || ((parts.size() > 4) && (m_formspec_version > FORMSPEC_API_VERSION))) { std::vector<std::string> v_pos = split(parts[0],','); std::vector<std::string> v_geom = split(parts[1],','); std::string name = parts[2]; std::string label = parts[3]; MY_CHECKPOS("button",0); MY_CHECKGEOM("button",1); v2s32 pos = getElementBasePos(false, &v_pos); v2s32 geom; geom.X = (stof(v_geom[0]) * spacing.X) - (spacing.X - imgsize.X); pos.Y += (stof(v_geom[1]) * (float)imgsize.Y)/2; core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y - m_btn_height, pos.X + geom.X, pos.Y + m_btn_height); if(!data->explicit_size) warningstream<<"invalid use of button without a size[] element"<<std::endl; std::wstring wlabel = translate_string(utf8_to_wide(unescape_string(label))); FieldSpec spec( name, wlabel, L"", 258+m_fields.size() ); spec.ftype = f_Button; if(type == "button_exit") spec.is_exit = true; gui::IGUIButton* e = Environment->addButton(rect, this, spec.fid, spec.flabel.c_str()); if (spec.fname == data->focused_fieldname) { Environment->setFocus(e); } m_fields.push_back(spec); return; } errorstream<< "Invalid button element(" << parts.size() << "): '" << element << "'" << std::endl; } void GUIFormSpecMenu::parseBackground(parserData* data, const std::string &element) { std::vector<std::string> parts = split(element,';'); if (((parts.size() == 3) || (parts.size() == 4)) || ((parts.size() > 4) && (m_formspec_version > FORMSPEC_API_VERSION))) { std::vector<std::string> v_pos = split(parts[0],','); std::vector<std::string> v_geom = split(parts[1],','); std::string name = unescape_string(parts[2]); MY_CHECKPOS("background",0); MY_CHECKGEOM("background",1); v2s32 pos = getElementBasePos(true, &v_pos); pos.X -= (spacing.X - (float)imgsize.X) / 2; pos.Y -= (spacing.Y - (float)imgsize.Y) / 2; v2s32 geom; geom.X = stof(v_geom[0]) * spacing.X; geom.Y = stof(v_geom[1]) * spacing.Y; bool clip = false; if (parts.size() == 4 && is_yes(parts[3])) { pos.X = stoi(v_pos[0]); //acts as offset pos.Y = stoi(v_pos[1]); //acts as offset clip = true; } if (!data->explicit_size && !clip) warningstream << "invalid use of unclipped background without a size[] element" << std::endl; m_backgrounds.emplace_back(name, pos, geom, clip); return; } errorstream<< "Invalid background element(" << parts.size() << "): '" << element << "'" << std::endl; } void GUIFormSpecMenu::parseTableOptions(parserData* data, const std::string &element) { std::vector<std::string> parts = split(element,';'); data->table_options.clear(); for (const std::string &part : parts) { // Parse table option std::string opt = unescape_string(part); data->table_options.push_back(GUITable::splitOption(opt)); } } void GUIFormSpecMenu::parseTableColumns(parserData* data, const std::string &element) { std::vector<std::string> parts = split(element,';'); data->table_columns.clear(); for (const std::string &part : parts) { std::vector<std::string> col_parts = split(part,','); GUITable::TableColumn column; // Parse column type if (!col_parts.empty()) column.type = col_parts[0]; // Parse column options for (size_t j = 1; j < col_parts.size(); ++j) { std::string opt = unescape_string(col_parts[j]); column.options.push_back(GUITable::splitOption(opt)); } data->table_columns.push_back(column); } } void GUIFormSpecMenu::parseTable(parserData* data, const std::string &element) { std::vector<std::string> parts = split(element,';'); if (((parts.size() == 4) || (parts.size() == 5)) || ((parts.size() > 5) && (m_formspec_version > FORMSPEC_API_VERSION))) { std::vector<std::string> v_pos = split(parts[0],','); std::vector<std::string> v_geom = split(parts[1],','); std::string name = parts[2]; std::vector<std::string> items = split(parts[3],','); std::string str_initial_selection; std::string str_transparent = "false"; if (parts.size() >= 5) str_initial_selection = parts[4]; MY_CHECKPOS("table",0); MY_CHECKGEOM("table",1); v2s32 pos = getElementBasePos(false, &v_pos); v2s32 geom; geom.X = stof(v_geom[0]) * spacing.X; geom.Y = stof(v_geom[1]) * spacing.Y; core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y); FieldSpec spec( name, L"", L"", 258+m_fields.size() ); spec.ftype = f_Table; for (std::string &item : items) { item = wide_to_utf8(unescape_translate(utf8_to_wide(unescape_string(item)))); } //now really show table GUITable *e = new GUITable(Environment, this, spec.fid, rect, m_tsrc); if (spec.fname == data->focused_fieldname) { Environment->setFocus(e); } e->setTable(data->table_options, data->table_columns, items); if (data->table_dyndata.find(name) != data->table_dyndata.end()) { e->setDynamicData(data->table_dyndata[name]); } if (!str_initial_selection.empty() && str_initial_selection != "0") e->setSelected(stoi(str_initial_selection)); m_tables.emplace_back(spec, e); m_fields.push_back(spec); return; } errorstream<< "Invalid table element(" << parts.size() << "): '" << element << "'" << std::endl; } void GUIFormSpecMenu::parseTextList(parserData* data, const std::string &element) { std::vector<std::string> parts = split(element,';'); if (((parts.size() == 4) || (parts.size() == 5) || (parts.size() == 6)) || ((parts.size() > 6) && (m_formspec_version > FORMSPEC_API_VERSION))) { std::vector<std::string> v_pos = split(parts[0],','); std::vector<std::string> v_geom = split(parts[1],','); std::string name = parts[2]; std::vector<std::string> items = split(parts[3],','); std::string str_initial_selection; std::string str_transparent = "false"; if (parts.size() >= 5) str_initial_selection = parts[4]; if (parts.size() >= 6) str_transparent = parts[5]; MY_CHECKPOS("textlist",0); MY_CHECKGEOM("textlist",1); v2s32 pos = getElementBasePos(false, &v_pos); v2s32 geom; geom.X = stof(v_geom[0]) * spacing.X; geom.Y = stof(v_geom[1]) * spacing.Y; core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y); FieldSpec spec( name, L"", L"", 258+m_fields.size() ); spec.ftype = f_Table; for (std::string &item : items) { item = wide_to_utf8(unescape_translate(utf8_to_wide(unescape_string(item)))); } //now really show list GUITable *e = new GUITable(Environment, this, spec.fid, rect, m_tsrc); if (spec.fname == data->focused_fieldname) { Environment->setFocus(e); } e->setTextList(items, is_yes(str_transparent)); if (data->table_dyndata.find(name) != data->table_dyndata.end()) { e->setDynamicData(data->table_dyndata[name]); } if (!str_initial_selection.empty() && str_initial_selection != "0") e->setSelected(stoi(str_initial_selection)); m_tables.emplace_back(spec, e); m_fields.push_back(spec); return; } errorstream<< "Invalid textlist element(" << parts.size() << "): '" << element << "'" << std::endl; } void GUIFormSpecMenu::parseDropDown(parserData* data, const std::string &element) { std::vector<std::string> parts = split(element,';'); if ((parts.size() == 5) || ((parts.size() > 5) && (m_formspec_version > FORMSPEC_API_VERSION))) { std::vector<std::string> v_pos = split(parts[0],','); std::string name = parts[2]; std::vector<std::string> items = split(parts[3],','); std::string str_initial_selection; str_initial_selection = parts[4]; MY_CHECKPOS("dropdown",0); v2s32 pos = getElementBasePos(false, &v_pos); s32 width = stof(parts[1]) * spacing.Y; core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X + width, pos.Y + (m_btn_height * 2)); FieldSpec spec( name, L"", L"", 258+m_fields.size() ); spec.ftype = f_DropDown; spec.send = true; //now really show list gui::IGUIComboBox *e = Environment->addComboBox(rect, this,spec.fid); if (spec.fname == data->focused_fieldname) { Environment->setFocus(e); } for (const std::string &item : items) { e->addItem(unescape_translate(unescape_string( utf8_to_wide(item))).c_str()); } if (!str_initial_selection.empty()) e->setSelected(stoi(str_initial_selection)-1); m_fields.push_back(spec); m_dropdowns.emplace_back(spec, std::vector<std::string>()); std::vector<std::string> &values = m_dropdowns.back().second; for (const std::string &item : items) { values.push_back(unescape_string(item)); } return; } errorstream << "Invalid dropdown element(" << parts.size() << "): '" << element << "'" << std::endl; } void GUIFormSpecMenu::parseFieldCloseOnEnter(parserData *data, const std::string &element) { std::vector<std::string> parts = split(element,';'); if (parts.size() == 2 || (parts.size() > 2 && m_formspec_version > FORMSPEC_API_VERSION)) { field_close_on_enter[parts[0]] = is_yes(parts[1]); } } void GUIFormSpecMenu::parsePwdField(parserData* data, const std::string &element) { std::vector<std::string> parts = split(element,';'); if ((parts.size() == 4) || (parts.size() == 5) || ((parts.size() > 5) && (m_formspec_version > FORMSPEC_API_VERSION))) { std::vector<std::string> v_pos = split(parts[0],','); std::vector<std::string> v_geom = split(parts[1],','); std::string name = parts[2]; std::string label = parts[3]; MY_CHECKPOS("pwdfield",0); MY_CHECKGEOM("pwdfield",1); v2s32 pos = getElementBasePos(false, &v_pos); pos -= padding; v2s32 geom; geom.X = (stof(v_geom[0]) * spacing.X) - (spacing.X - imgsize.X); pos.Y += (stof(v_geom[1]) * (float)imgsize.Y)/2; pos.Y -= m_btn_height; geom.Y = m_btn_height*2; core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y); std::wstring wlabel = translate_string(utf8_to_wide(unescape_string(label))); FieldSpec spec( name, wlabel, L"", 258+m_fields.size() ); spec.send = true; gui::IGUIEditBox * e = Environment->addEditBox(0, rect, true, this, spec.fid); if (spec.fname == data->focused_fieldname) { Environment->setFocus(e); } if (label.length() >= 1) { int font_height = g_fontengine->getTextHeight(); rect.UpperLeftCorner.Y -= font_height; rect.LowerRightCorner.Y = rect.UpperLeftCorner.Y + font_height; gui::StaticText::add(Environment, spec.flabel.c_str(), rect, false, true, this, 0); } e->setPasswordBox(true,L'*'); irr::SEvent evt; evt.EventType = EET_KEY_INPUT_EVENT; evt.KeyInput.Key = KEY_END; evt.KeyInput.Char = 0; evt.KeyInput.Control = false; evt.KeyInput.Shift = false; evt.KeyInput.PressedDown = true; e->OnEvent(evt); if (parts.size() >= 5) { // TODO: remove after 2016-11-03 warningstream << "pwdfield: use field_close_on_enter[name, enabled]" << " instead of the 5th param" << std::endl; field_close_on_enter[name] = is_yes(parts[4]); } m_fields.push_back(spec); return; } errorstream<< "Invalid pwdfield element(" << parts.size() << "): '" << element << "'" << std::endl; } void GUIFormSpecMenu::createTextField(parserData *data, FieldSpec &spec, core::rect<s32> &rect, bool is_multiline) { bool is_editable = !spec.fname.empty(); if (!is_editable && !is_multiline) { // spec field id to 0, this stops submit searching for a value that isn't there gui::StaticText::add(Environment, spec.flabel.c_str(), rect, false, true, this, spec.fid); return; } if (is_editable) { spec.send = true; } else if (is_multiline && spec.fdefault.empty() && !spec.flabel.empty()) { // Multiline textareas: swap default and label for backwards compat spec.flabel.swap(spec.fdefault); } gui::IGUIEditBox *e = nullptr; static constexpr bool use_intl_edit_box = USE_FREETYPE && IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 9; if (use_intl_edit_box && g_settings->getBool("freetype")) { e = new gui::intlGUIEditBox(spec.fdefault.c_str(), true, Environment, this, spec.fid, rect, is_editable, is_multiline); e->drop(); } else { if (is_multiline) e = new GUIEditBoxWithScrollBar(spec.fdefault.c_str(), true, Environment, this, spec.fid, rect, is_editable, true); else if (is_editable) e = Environment->addEditBox(spec.fdefault.c_str(), rect, true, this, spec.fid); } if (e) { if (is_editable && spec.fname == data->focused_fieldname) Environment->setFocus(e); if (is_multiline) { e->setMultiLine(true); e->setWordWrap(true); e->setTextAlignment(gui::EGUIA_UPPERLEFT, gui::EGUIA_UPPERLEFT); } else { irr::SEvent evt; evt.EventType = EET_KEY_INPUT_EVENT; evt.KeyInput.Key = KEY_END; evt.KeyInput.Char = 0; evt.KeyInput.Control = 0; evt.KeyInput.Shift = 0; evt.KeyInput.PressedDown = true; e->OnEvent(evt); } } if (!spec.flabel.empty()) { int font_height = g_fontengine->getTextHeight(); rect.UpperLeftCorner.Y -= font_height; rect.LowerRightCorner.Y = rect.UpperLeftCorner.Y + font_height; gui::StaticText::add(Environment, spec.flabel.c_str(), rect, false, true, this, 0); } } void GUIFormSpecMenu::parseSimpleField(parserData* data, std::vector<std::string> &parts) { std::string name = parts[0]; std::string label = parts[1]; std::string default_val = parts[2]; core::rect<s32> rect; if(data->explicit_size) warningstream<<"invalid use of unpositioned \"field\" in inventory"<<std::endl; v2s32 pos = getElementBasePos(false, nullptr); pos.Y = ((m_fields.size()+2)*60); v2s32 size = DesiredRect.getSize(); rect = core::rect<s32>(size.X / 2 - 150, pos.Y, (size.X / 2 - 150) + 300, pos.Y + (m_btn_height*2)); if(m_form_src) default_val = m_form_src->resolveText(default_val); std::wstring wlabel = translate_string(utf8_to_wide(unescape_string(label))); FieldSpec spec( name, wlabel, utf8_to_wide(unescape_string(default_val)), 258+m_fields.size() ); createTextField(data, spec, rect, false); if (parts.size() >= 4) { // TODO: remove after 2016-11-03 warningstream << "field/simple: use field_close_on_enter[name, enabled]" << " instead of the 4th param" << std::endl; field_close_on_enter[name] = is_yes(parts[3]); } m_fields.push_back(spec); } void GUIFormSpecMenu::parseTextArea(parserData* data, std::vector<std::string>& parts, const std::string &type) { std::vector<std::string> v_pos = split(parts[0],','); std::vector<std::string> v_geom = split(parts[1],','); std::string name = parts[2]; std::string label = parts[3]; std::string default_val = parts[4]; MY_CHECKPOS(type,0); MY_CHECKGEOM(type,1); v2s32 pos = getElementBasePos(false, &v_pos); pos -= padding; v2s32 geom; geom.X = (stof(v_geom[0]) * spacing.X) - (spacing.X - imgsize.X); if (type == "textarea") { geom.Y = (stof(v_geom[1]) * (float)imgsize.Y) - (spacing.Y-imgsize.Y); pos.Y += m_btn_height; } else { pos.Y += (stof(v_geom[1]) * (float)imgsize.Y)/2; pos.Y -= m_btn_height; geom.Y = m_btn_height*2; } core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y); if(!data->explicit_size) warningstream<<"invalid use of positioned "<<type<<" without a size[] element"<<std::endl; if(m_form_src) default_val = m_form_src->resolveText(default_val); std::wstring wlabel = translate_string(utf8_to_wide(unescape_string(label))); FieldSpec spec( name, wlabel, utf8_to_wide(unescape_string(default_val)), 258+m_fields.size() ); createTextField(data, spec, rect, type == "textarea"); if (parts.size() >= 6) { // TODO: remove after 2016-11-03 warningstream << "field/textarea: use field_close_on_enter[name, enabled]" << " instead of the 6th param" << std::endl; field_close_on_enter[name] = is_yes(parts[5]); } m_fields.push_back(spec); } void GUIFormSpecMenu::parseField(parserData* data, const std::string &element, const std::string &type) { std::vector<std::string> parts = split(element,';'); if (parts.size() == 3 || parts.size() == 4) { parseSimpleField(data,parts); return; } if ((parts.size() == 5) || (parts.size() == 6) || ((parts.size() > 6) && (m_formspec_version > FORMSPEC_API_VERSION))) { parseTextArea(data,parts,type); return; } errorstream<< "Invalid field element(" << parts.size() << "): '" << element << "'" << std::endl; } void GUIFormSpecMenu::parseLabel(parserData* data, const std::string &element) { std::vector<std::string> parts = split(element,';'); if ((parts.size() == 2) || ((parts.size() > 2) && (m_formspec_version > FORMSPEC_API_VERSION))) { std::vector<std::string> v_pos = split(parts[0],','); std::string text = parts[1]; MY_CHECKPOS("label",0); v2s32 pos = getElementBasePos(false, nullptr); pos.X += stof(v_pos[0]) * spacing.X; pos.Y += (stof(v_pos[1]) + 7.0f / 30.0f) * spacing.Y; if(!data->explicit_size) warningstream<<"invalid use of label without a size[] element"<<std::endl; std::vector<std::string> lines = split(text, '\n'); for (unsigned int i = 0; i != lines.size(); i++) { // Lines are spaced at the nominal distance of // 2/5 inventory slot, even if the font doesn't // quite match that. This provides consistent // form layout, at the expense of sometimes // having sub-optimal spacing for the font. // We multiply by 2 and then divide by 5, rather // than multiply by 0.4, to get exact results // in the integer cases: 0.4 is not exactly // representable in binary floating point. s32 posy = pos.Y + ((float)i) * spacing.Y * 2.0 / 5.0; std::wstring wlabel = utf8_to_wide(unescape_string(lines[i])); core::rect<s32> rect = core::rect<s32>( pos.X, posy - m_btn_height, pos.X + m_font->getDimension(wlabel.c_str()).Width, posy + m_btn_height); FieldSpec spec( "", wlabel, L"", 258+m_fields.size() ); gui::IGUIStaticText *e = gui::StaticText::add(Environment, spec.flabel.c_str(), rect, false, false, this, spec.fid); e->setTextAlignment(gui::EGUIA_UPPERLEFT, gui::EGUIA_CENTER); m_fields.push_back(spec); } return; } errorstream<< "Invalid label element(" << parts.size() << "): '" << element << "'" << std::endl; } void GUIFormSpecMenu::parseVertLabel(parserData* data, const std::string &element) { std::vector<std::string> parts = split(element,';'); if ((parts.size() == 2) || ((parts.size() > 2) && (m_formspec_version > FORMSPEC_API_VERSION))) { std::vector<std::string> v_pos = split(parts[0],','); std::wstring text = unescape_translate( unescape_string(utf8_to_wide(parts[1]))); MY_CHECKPOS("vertlabel",1); v2s32 pos = getElementBasePos(false, &v_pos); core::rect<s32> rect = core::rect<s32>( pos.X, pos.Y+((imgsize.Y/2)- m_btn_height), pos.X+15, pos.Y + font_line_height(m_font) * (text.length()+1) +((imgsize.Y/2)- m_btn_height)); //actually text.length() would be correct but adding +1 avoids to break all mods if(!data->explicit_size) warningstream<<"invalid use of label without a size[] element"<<std::endl; std::wstring label; for (wchar_t i : text) { label += i; label += L"\n"; } FieldSpec spec( "", label, L"", 258+m_fields.size() ); gui::IGUIStaticText *t = gui::StaticText::add(Environment, spec.flabel.c_str(), rect, false, false, this, spec.fid); t->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_CENTER); m_fields.push_back(spec); return; } errorstream<< "Invalid vertlabel element(" << parts.size() << "): '" << element << "'" << std::endl; } void GUIFormSpecMenu::parseImageButton(parserData* data, const std::string &element, const std::string &type) { std::vector<std::string> parts = split(element,';'); if ((((parts.size() >= 5) && (parts.size() <= 8)) && (parts.size() != 6)) || ((parts.size() > 8) && (m_formspec_version > FORMSPEC_API_VERSION))) { std::vector<std::string> v_pos = split(parts[0],','); std::vector<std::string> v_geom = split(parts[1],','); std::string image_name = parts[2]; std::string name = parts[3]; std::string label = parts[4]; MY_CHECKPOS("imagebutton",0); MY_CHECKGEOM("imagebutton",1); v2s32 pos = getElementBasePos(false, &v_pos); v2s32 geom; geom.X = (stof(v_geom[0]) * spacing.X) - (spacing.X - imgsize.X); geom.Y = (stof(v_geom[1]) * spacing.Y) - (spacing.Y - imgsize.Y); bool noclip = false; bool drawborder = true; std::string pressed_image_name; if (parts.size() >= 7) { if (parts[5] == "true") noclip = true; if (parts[6] == "false") drawborder = false; } if (parts.size() >= 8) { pressed_image_name = parts[7]; } core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y); if(!data->explicit_size) warningstream<<"invalid use of image_button without a size[] element"<<std::endl; image_name = unescape_string(image_name); pressed_image_name = unescape_string(pressed_image_name); std::wstring wlabel = utf8_to_wide(unescape_string(label)); FieldSpec spec( name, wlabel, utf8_to_wide(image_name), 258+m_fields.size() ); spec.ftype = f_Button; if(type == "image_button_exit") spec.is_exit = true; video::ITexture *texture = 0; video::ITexture *pressed_texture = 0; texture = m_tsrc->getTexture(image_name); if (!pressed_image_name.empty()) pressed_texture = m_tsrc->getTexture(pressed_image_name); else pressed_texture = texture; gui::IGUIButton *e = Environment->addButton(rect, this, spec.fid, spec.flabel.c_str()); if (spec.fname == data->focused_fieldname) { Environment->setFocus(e); } e->setUseAlphaChannel(true); e->setImage(guiScalingImageButton( Environment->getVideoDriver(), texture, geom.X, geom.Y)); e->setPressedImage(guiScalingImageButton( Environment->getVideoDriver(), pressed_texture, geom.X, geom.Y)); e->setScaleImage(true); e->setNotClipped(noclip); e->setDrawBorder(drawborder); m_fields.push_back(spec); return; } errorstream<< "Invalid imagebutton element(" << parts.size() << "): '" << element << "'" << std::endl; } void GUIFormSpecMenu::parseTabHeader(parserData* data, const std::string &element) { std::vector<std::string> parts = split(element,';'); if (((parts.size() == 4) || (parts.size() == 6)) || ((parts.size() > 6) && (m_formspec_version > FORMSPEC_API_VERSION))) { std::vector<std::string> v_pos = split(parts[0],','); std::string name = parts[1]; std::vector<std::string> buttons = split(parts[2],','); std::string str_index = parts[3]; bool show_background = true; bool show_border = true; int tab_index = stoi(str_index) -1; MY_CHECKPOS("tabheader",0); if (parts.size() == 6) { if (parts[4] == "true") show_background = false; if (parts[5] == "false") show_border = false; } FieldSpec spec( name, L"", L"", 258+m_fields.size() ); spec.ftype = f_TabHeader; v2s32 pos; { v2f32 pos_f = pos_offset * spacing; pos_f.X += stof(v_pos[0]) * spacing.X; pos_f.Y += stof(v_pos[1]) * spacing.Y - m_btn_height * 2; pos = v2s32(pos_f.X, pos_f.Y); } v2s32 geom; geom.X = DesiredRect.getWidth(); geom.Y = m_btn_height*2; core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y); gui::IGUITabControl *e = Environment->addTabControl(rect, this, show_background, show_border, spec.fid); e->setAlignment(irr::gui::EGUIA_UPPERLEFT, irr::gui::EGUIA_UPPERLEFT, irr::gui::EGUIA_UPPERLEFT, irr::gui::EGUIA_LOWERRIGHT); e->setTabHeight(m_btn_height*2); if (spec.fname == data->focused_fieldname) { Environment->setFocus(e); } e->setNotClipped(true); for (const std::string &button : buttons) { e->addTab(unescape_translate(unescape_string( utf8_to_wide(button))).c_str(), -1); } if ((tab_index >= 0) && (buttons.size() < INT_MAX) && (tab_index < (int) buttons.size())) e->setActiveTab(tab_index); m_fields.push_back(spec); return; } errorstream << "Invalid TabHeader element(" << parts.size() << "): '" << element << "'" << std::endl; } void GUIFormSpecMenu::parseItemImageButton(parserData* data, const std::string &element) { if (m_client == 0) { warningstream << "invalid use of item_image_button with m_client==0" << std::endl; return; } std::vector<std::string> parts = split(element,';'); if ((parts.size() == 5) || ((parts.size() > 5) && (m_formspec_version > FORMSPEC_API_VERSION))) { std::vector<std::string> v_pos = split(parts[0],','); std::vector<std::string> v_geom = split(parts[1],','); std::string item_name = parts[2]; std::string name = parts[3]; std::string label = parts[4]; label = unescape_string(label); item_name = unescape_string(item_name); MY_CHECKPOS("itemimagebutton",0); MY_CHECKGEOM("itemimagebutton",1); v2s32 pos = getElementBasePos(false, &v_pos); v2s32 geom; geom.X = (stof(v_geom[0]) * spacing.X) - (spacing.X - imgsize.X); geom.Y = (stof(v_geom[1]) * spacing.Y) - (spacing.Y - imgsize.Y); core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y); if(!data->explicit_size) warningstream<<"invalid use of item_image_button without a size[] element"<<std::endl; IItemDefManager *idef = m_client->idef(); ItemStack item; item.deSerialize(item_name, idef); m_tooltips[name] = TooltipSpec(utf8_to_wide(item.getDefinition(idef).description), m_default_tooltip_bgcolor, m_default_tooltip_color); FieldSpec spec( name, utf8_to_wide(label), utf8_to_wide(item_name), 258 + m_fields.size() ); gui::IGUIButton *e = Environment->addButton(rect, this, spec.fid, L""); if (spec.fname == data->focused_fieldname) { Environment->setFocus(e); } spec.ftype = f_Button; rect+=data->basepos-padding; spec.rect=rect; m_fields.push_back(spec); pos = getElementBasePos(true, &v_pos); m_itemimages.emplace_back("", item_name, e, pos, geom); m_static_texts.emplace_back(utf8_to_wide(label), rect, e); return; } errorstream<< "Invalid ItemImagebutton element(" << parts.size() << "): '" << element << "'" << std::endl; } void GUIFormSpecMenu::parseBox(parserData* data, const std::string &element) { std::vector<std::string> parts = split(element,';'); if ((parts.size() == 3) || ((parts.size() > 3) && (m_formspec_version > FORMSPEC_API_VERSION))) { std::vector<std::string> v_pos = split(parts[0],','); std::vector<std::string> v_geom = split(parts[1],','); MY_CHECKPOS("box",0); MY_CHECKGEOM("box",1); v2s32 pos = getElementBasePos(true, &v_pos); v2s32 geom; geom.X = stof(v_geom[0]) * spacing.X; geom.Y = stof(v_geom[1]) * spacing.Y; video::SColor tmp_color; if (parseColorString(parts[2], tmp_color, false, 0x8C)) { BoxDrawSpec spec(pos, geom, tmp_color); m_boxes.push_back(spec); } else { errorstream<< "Invalid Box element(" << parts.size() << "): '" << element << "' INVALID COLOR" << std::endl; } return; } errorstream<< "Invalid Box element(" << parts.size() << "): '" << element << "'" << std::endl; } void GUIFormSpecMenu::parseBackgroundColor(parserData* data, const std::string &element) { std::vector<std::string> parts = split(element,';'); if (((parts.size() == 1) || (parts.size() == 2)) || ((parts.size() > 2) && (m_formspec_version > FORMSPEC_API_VERSION))) { parseColorString(parts[0], m_bgcolor, false); if (parts.size() == 2) { std::string fullscreen = parts[1]; m_bgfullscreen = is_yes(fullscreen); } return; } errorstream << "Invalid bgcolor element(" << parts.size() << "): '" << element << "'" << std::endl; } void GUIFormSpecMenu::parseListColors(parserData* data, const std::string &element) { std::vector<std::string> parts = split(element,';'); if (((parts.size() == 2) || (parts.size() == 3) || (parts.size() == 5)) || ((parts.size() > 5) && (m_formspec_version > FORMSPEC_API_VERSION))) { parseColorString(parts[0], m_slotbg_n, false); parseColorString(parts[1], m_slotbg_h, false); if (parts.size() >= 3) { if (parseColorString(parts[2], m_slotbordercolor, false)) { m_slotborder = true; } } if (parts.size() == 5) { video::SColor tmp_color; if (parseColorString(parts[3], tmp_color, false)) m_default_tooltip_bgcolor = tmp_color; if (parseColorString(parts[4], tmp_color, false)) m_default_tooltip_color = tmp_color; } return; } errorstream<< "Invalid listcolors element(" << parts.size() << "): '" << element << "'" << std::endl; } void GUIFormSpecMenu::parseTooltip(parserData* data, const std::string &element) { std::vector<std::string> parts = split(element,';'); if (parts.size() < 2) { errorstream << "Invalid tooltip element(" << parts.size() << "): '" << element << "'" << std::endl; return; } // Get mode and check size bool rect_mode = parts[0].find(',') != std::string::npos; size_t base_size = rect_mode ? 3 : 2; if (parts.size() != base_size && parts.size() != base_size + 2) { errorstream << "Invalid tooltip element(" << parts.size() << "): '" << element << "'" << std::endl; return; } // Read colors video::SColor bgcolor = m_default_tooltip_bgcolor; video::SColor color = m_default_tooltip_color; if (parts.size() == base_size + 2 && (!parseColorString(parts[base_size], bgcolor, false) || !parseColorString(parts[base_size + 1], color, false))) { errorstream << "Invalid color in tooltip element(" << parts.size() << "): '" << element << "'" << std::endl; return; } // Make tooltip spec std::string text = unescape_string(parts[rect_mode ? 2 : 1]); TooltipSpec spec(utf8_to_wide(text), bgcolor, color); // Add tooltip if (rect_mode) { std::vector<std::string> v_pos = split(parts[0], ','); std::vector<std::string> v_geom = split(parts[1], ','); MY_CHECKPOS("tooltip", 0); MY_CHECKGEOM("tooltip", 1); v2s32 pos = getElementBasePos(true, &v_pos); v2s32 geom; geom.X = stof(v_geom[0]) * spacing.X; geom.Y = stof(v_geom[1]) * spacing.Y; irr::core::rect<s32> rect(pos, pos + geom); m_tooltip_rects.emplace_back(rect, spec); } else { m_tooltips[parts[0]] = spec; } } bool GUIFormSpecMenu::parseVersionDirect(const std::string &data) { //some prechecks if (data.empty()) return false; std::vector<std::string> parts = split(data,'['); if (parts.size() < 2) { return false; } if (parts[0] != "formspec_version") { return false; } if (is_number(parts[1])) { m_formspec_version = mystoi(parts[1]); return true; } return false; } bool GUIFormSpecMenu::parseSizeDirect(parserData* data, const std::string &element) { if (element.empty()) return false; std::vector<std::string> parts = split(element,'['); if (parts.size() < 2) return false; std::string type = trim(parts[0]); std::string description = trim(parts[1]); if (type != "size" && type != "invsize") return false; if (type == "invsize") log_deprecated("Deprecated formspec element \"invsize\" is used"); parseSize(data, description); return true; } bool GUIFormSpecMenu::parsePositionDirect(parserData *data, const std::string &element) { if (element.empty()) return false; std::vector<std::string> parts = split(element, '['); if (parts.size() != 2) return false; std::string type = trim(parts[0]); std::string description = trim(parts[1]); if (type != "position") return false; parsePosition(data, description); return true; } void GUIFormSpecMenu::parsePosition(parserData *data, const std::string &element) { std::vector<std::string> parts = split(element, ','); if (parts.size() == 2) { data->offset.X = stof(parts[0]); data->offset.Y = stof(parts[1]); return; } errorstream << "Invalid position element (" << parts.size() << "): '" << element << "'" << std::endl; } bool GUIFormSpecMenu::parseAnchorDirect(parserData *data, const std::string &element) { if (element.empty()) return false; std::vector<std::string> parts = split(element, '['); if (parts.size() != 2) return false; std::string type = trim(parts[0]); std::string description = trim(parts[1]); if (type != "anchor") return false; parseAnchor(data, description); return true; } void GUIFormSpecMenu::parseAnchor(parserData *data, const std::string &element) { std::vector<std::string> parts = split(element, ','); if (parts.size() == 2) { data->anchor.X = stof(parts[0]); data->anchor.Y = stof(parts[1]); return; } errorstream << "Invalid anchor element (" << parts.size() << "): '" << element << "'" << std::endl; } void GUIFormSpecMenu::parseElement(parserData* data, const std::string &element) { //some prechecks if (element.empty()) return; std::vector<std::string> parts = split(element,'['); // ugly workaround to keep compatibility if (parts.size() > 2) { if (trim(parts[0]) == "image") { for (unsigned int i=2;i< parts.size(); i++) { parts[1] += "[" + parts[i]; } } else { return; } } if (parts.size() < 2) { return; } std::string type = trim(parts[0]); std::string description = trim(parts[1]); if (type == "container") { parseContainer(data, description); return; } if (type == "container_end") { parseContainerEnd(data); return; } if (type == "list") { parseList(data, description); return; } if (type == "listring") { parseListRing(data, description); return; } if (type == "checkbox") { parseCheckbox(data, description); return; } if (type == "image") { parseImage(data, description); return; } if (type == "item_image") { parseItemImage(data, description); return; } if (type == "button" || type == "button_exit") { parseButton(data, description, type); return; } if (type == "background") { parseBackground(data,description); return; } if (type == "tableoptions"){ parseTableOptions(data,description); return; } if (type == "tablecolumns"){ parseTableColumns(data,description); return; } if (type == "table"){ parseTable(data,description); return; } if (type == "textlist"){ parseTextList(data,description); return; } if (type == "dropdown"){ parseDropDown(data,description); return; } if (type == "field_close_on_enter") { parseFieldCloseOnEnter(data, description); return; } if (type == "pwdfield") { parsePwdField(data,description); return; } if ((type == "field") || (type == "textarea")){ parseField(data,description,type); return; } if (type == "label") { parseLabel(data,description); return; } if (type == "vertlabel") { parseVertLabel(data,description); return; } if (type == "item_image_button") { parseItemImageButton(data,description); return; } if ((type == "image_button") || (type == "image_button_exit")) { parseImageButton(data,description,type); return; } if (type == "tabheader") { parseTabHeader(data,description); return; } if (type == "box") { parseBox(data,description); return; } if (type == "bgcolor") { parseBackgroundColor(data,description); return; } if (type == "listcolors") { parseListColors(data,description); return; } if (type == "tooltip") { parseTooltip(data,description); return; } if (type == "scrollbar") { parseScrollBar(data, description); return; } // Ignore others infostream << "Unknown DrawSpec: type=" << type << ", data=\"" << description << "\"" << std::endl; } void GUIFormSpecMenu::regenerateGui(v2u32 screensize) { /* useless to regenerate without a screensize */ if ((screensize.X <= 0) || (screensize.Y <= 0)) { return; } parserData mydata; //preserve tables for (auto &m_table : m_tables) { std::string tablename = m_table.first.fname; GUITable *table = m_table.second; mydata.table_dyndata[tablename] = table->getDynamicData(); } //set focus if (!m_focused_element.empty()) mydata.focused_fieldname = m_focused_element; //preserve focus gui::IGUIElement *focused_element = Environment->getFocus(); if (focused_element && focused_element->getParent() == this) { s32 focused_id = focused_element->getID(); if (focused_id > 257) { for (const GUIFormSpecMenu::FieldSpec &field : m_fields) { if (field.fid == focused_id) { mydata.focused_fieldname = field.fname; break; } } } } // Remove children removeChildren(); for (auto &table_it : m_tables) { table_it.second->drop(); } mydata.size= v2s32(100,100); mydata.screensize = screensize; mydata.offset = v2f32(0.5f, 0.5f); mydata.anchor = v2f32(0.5f, 0.5f); // Base position of contents of form mydata.basepos = getBasePos(); /* Convert m_init_draw_spec to m_inventorylists */ m_inventorylists.clear(); m_images.clear(); m_backgrounds.clear(); m_itemimages.clear(); m_tables.clear(); m_checkboxes.clear(); m_scrollbars.clear(); m_fields.clear(); m_boxes.clear(); m_tooltips.clear(); m_tooltip_rects.clear(); m_inventory_rings.clear(); m_static_texts.clear(); m_dropdowns.clear(); m_bgfullscreen = false; { v3f formspec_bgcolor = g_settings->getV3F("formspec_default_bg_color"); m_bgcolor = video::SColor( (u8) clamp_u8(g_settings->getS32("formspec_default_bg_opacity")), clamp_u8(myround(formspec_bgcolor.X)), clamp_u8(myround(formspec_bgcolor.Y)), clamp_u8(myround(formspec_bgcolor.Z)) ); } { v3f formspec_bgcolor = g_settings->getV3F("formspec_fullscreen_bg_color"); m_fullscreen_bgcolor = video::SColor( (u8) clamp_u8(g_settings->getS32("formspec_fullscreen_bg_opacity")), clamp_u8(myround(formspec_bgcolor.X)), clamp_u8(myround(formspec_bgcolor.Y)), clamp_u8(myround(formspec_bgcolor.Z)) ); } m_slotbg_n = video::SColor(255,128,128,128); m_slotbg_h = video::SColor(255,192,192,192); m_default_tooltip_bgcolor = video::SColor(255,110,130,60); m_default_tooltip_color = video::SColor(255,255,255,255); m_slotbordercolor = video::SColor(200,0,0,0); m_slotborder = false; // Add tooltip { assert(!m_tooltip_element); // Note: parent != this so that the tooltip isn't clipped by the menu rectangle m_tooltip_element = gui::StaticText::add(Environment, L"", core::rect<s32>(0, 0, 110, 18)); m_tooltip_element->enableOverrideColor(true); m_tooltip_element->setBackgroundColor(m_default_tooltip_bgcolor); m_tooltip_element->setDrawBackground(true); m_tooltip_element->setDrawBorder(true); m_tooltip_element->setOverrideColor(m_default_tooltip_color); m_tooltip_element->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_CENTER); m_tooltip_element->setWordWrap(false); //we're not parent so no autograb for this one! m_tooltip_element->grab(); } std::vector<std::string> elements = split(m_formspec_string,']'); unsigned int i = 0; /* try to read version from first element only */ if (!elements.empty()) { if (parseVersionDirect(elements[0])) { i++; } } /* we need size first in order to calculate image scale */ mydata.explicit_size = false; for (; i< elements.size(); i++) { if (!parseSizeDirect(&mydata, elements[i])) { break; } } /* "position" element is always after "size" element if it used */ for (; i< elements.size(); i++) { if (!parsePositionDirect(&mydata, elements[i])) { break; } } /* "anchor" element is always after "position" (or "size" element) if it used */ for (; i< elements.size(); i++) { if (!parseAnchorDirect(&mydata, elements[i])) { break; } } /* "no_prepend" element is always after "position" (or "size" element) if it used */ bool enable_prepends = true; for (; i < elements.size(); i++) { if (elements[i].empty()) break; std::vector<std::string> parts = split(elements[i], '['); if (trim(parts[0]) == "no_prepend") enable_prepends = false; else break; } if (mydata.explicit_size) { // compute scaling for specified form size if (m_lock) { v2u32 current_screensize = RenderingEngine::get_video_driver()->getScreenSize(); v2u32 delta = current_screensize - m_lockscreensize; if (current_screensize.Y > m_lockscreensize.Y) delta.Y /= 2; else delta.Y = 0; if (current_screensize.X > m_lockscreensize.X) delta.X /= 2; else delta.X = 0; offset = v2s32(delta.X,delta.Y); mydata.screensize = m_lockscreensize; } else { offset = v2s32(0,0); } double gui_scaling = g_settings->getFloat("gui_scaling"); double screen_dpi = RenderingEngine::getDisplayDensity() * 96; double use_imgsize; if (m_lock) { // In fixed-size mode, inventory image size // is 0.53 inch multiplied by the gui_scaling // config parameter. This magic size is chosen // to make the main menu (15.5 inventory images // wide, including border) just fit into the // default window (800 pixels wide) at 96 DPI // and default scaling (1.00). use_imgsize = 0.5555 * screen_dpi * gui_scaling; } else { // In variable-size mode, we prefer to make the // inventory image size 1/15 of screen height, // multiplied by the gui_scaling config parameter. // If the preferred size won't fit the whole // form on the screen, either horizontally or // vertically, then we scale it down to fit. // (The magic numbers in the computation of what // fits arise from the scaling factors in the // following stanza, including the form border, // help text space, and 0.1 inventory slot spare.) // However, a minimum size is also set, that // the image size can't be less than 0.3 inch // multiplied by gui_scaling, even if this means // the form doesn't fit the screen. #ifdef __ANDROID__ // For mobile devices these magic numbers are // different and forms should always use the // maximum screen space available. double prefer_imgsize = mydata.screensize.Y / 10 * gui_scaling; double fitx_imgsize = mydata.screensize.X / ((12.0 / 8.0) * (0.5 + mydata.invsize.X)); double fity_imgsize = mydata.screensize.Y / ((15.0 / 11.0) * (0.85 + mydata.invsize.Y)); use_imgsize = MYMIN(prefer_imgsize, MYMIN(fitx_imgsize, fity_imgsize)); #else double prefer_imgsize = mydata.screensize.Y / 15 * gui_scaling; double fitx_imgsize = mydata.screensize.X / ((5.0 / 4.0) * (0.5 + mydata.invsize.X)); double fity_imgsize = mydata.screensize.Y / ((15.0 / 13.0) * (0.85 * mydata.invsize.Y)); double screen_dpi = RenderingEngine::getDisplayDensity() * 96; double min_imgsize = 0.3 * screen_dpi * gui_scaling; use_imgsize = MYMAX(min_imgsize, MYMIN(prefer_imgsize, MYMIN(fitx_imgsize, fity_imgsize))); #endif } // Everything else is scaled in proportion to the // inventory image size. The inventory slot spacing // is 5/4 image size horizontally and 15/13 image size // vertically. The padding around the form (incorporating // the border of the outer inventory slots) is 3/8 // image size. Font height (baseline to baseline) // is 2/5 vertical inventory slot spacing, and button // half-height is 7/8 of font height. imgsize = v2s32(use_imgsize, use_imgsize); spacing = v2f32(use_imgsize*5.0/4, use_imgsize*15.0/13); padding = v2s32(use_imgsize*3.0/8, use_imgsize*3.0/8); m_btn_height = use_imgsize*15.0/13 * 0.35; m_font = g_fontengine->getFont(); mydata.size = v2s32( padding.X*2+spacing.X*(mydata.invsize.X-1.0)+imgsize.X, padding.Y*2+spacing.Y*(mydata.invsize.Y-1.0)+imgsize.Y + m_btn_height*2.0/3.0 ); DesiredRect = mydata.rect = core::rect<s32>( (s32)((f32)mydata.screensize.X * mydata.offset.X) - (s32)(mydata.anchor.X * (f32)mydata.size.X) + offset.X, (s32)((f32)mydata.screensize.Y * mydata.offset.Y) - (s32)(mydata.anchor.Y * (f32)mydata.size.Y) + offset.Y, (s32)((f32)mydata.screensize.X * mydata.offset.X) + (s32)((1.0 - mydata.anchor.X) * (f32)mydata.size.X) + offset.X, (s32)((f32)mydata.screensize.Y * mydata.offset.Y) + (s32)((1.0 - mydata.anchor.Y) * (f32)mydata.size.Y) + offset.Y ); } else { // Non-size[] form must consist only of text fields and // implicit "Proceed" button. Use default font, and // temporary form size which will be recalculated below. m_font = g_fontengine->getFont(); m_btn_height = font_line_height(m_font) * 0.875; DesiredRect = core::rect<s32>( (s32)((f32)mydata.screensize.X * mydata.offset.X) - (s32)(mydata.anchor.X * 580.0), (s32)((f32)mydata.screensize.Y * mydata.offset.Y) - (s32)(mydata.anchor.Y * 300.0), (s32)((f32)mydata.screensize.X * mydata.offset.X) + (s32)((1.0 - mydata.anchor.X) * 580.0), (s32)((f32)mydata.screensize.Y * mydata.offset.Y) + (s32)((1.0 - mydata.anchor.Y) * 300.0) ); } recalculateAbsolutePosition(false); mydata.basepos = getBasePos(); m_tooltip_element->setOverrideFont(m_font); gui::IGUISkin *skin = Environment->getSkin(); sanity_check(skin); gui::IGUIFont *old_font = skin->getFont(); skin->setFont(m_font); pos_offset = v2f32(); if (enable_prepends) { std::vector<std::string> prepend_elements = split(m_formspec_prepend, ']'); for (const auto &element : prepend_elements) parseElement(&mydata, element); } for (; i< elements.size(); i++) { parseElement(&mydata, elements[i]); } if (!container_stack.empty()) { errorstream << "Invalid formspec string: container was never closed!" << std::endl; } // If there are fields without explicit size[], add a "Proceed" // button and adjust size to fit all the fields. if (!m_fields.empty() && !mydata.explicit_size) { mydata.rect = core::rect<s32>( mydata.screensize.X/2 - 580/2, mydata.screensize.Y/2 - 300/2, mydata.screensize.X/2 + 580/2, mydata.screensize.Y/2 + 240/2+(m_fields.size()*60) ); DesiredRect = mydata.rect; recalculateAbsolutePosition(false); mydata.basepos = getBasePos(); { v2s32 pos = mydata.basepos; pos.Y = ((m_fields.size()+2)*60); v2s32 size = DesiredRect.getSize(); mydata.rect = core::rect<s32>(size.X/2-70, pos.Y, (size.X/2-70)+140, pos.Y + (m_btn_height*2)); const wchar_t *text = wgettext("Proceed"); Environment->addButton(mydata.rect, this, 257, text); delete[] text; } } //set initial focus if parser didn't set it focused_element = Environment->getFocus(); if (!focused_element || !isMyChild(focused_element) || focused_element->getType() == gui::EGUIET_TAB_CONTROL) setInitialFocus(); skin->setFont(old_font); } #ifdef __ANDROID__ bool GUIFormSpecMenu::getAndroidUIInput() { if (!hasAndroidUIInput()) return false; std::string fieldname = m_jni_field_name; m_jni_field_name.clear(); for(std::vector<FieldSpec>::iterator iter = m_fields.begin(); iter != m_fields.end(); ++iter) { if (iter->fname != fieldname) { continue; } IGUIElement* tochange = getElementFromId(iter->fid); if (tochange == 0) { return false; } if (tochange->getType() != irr::gui::EGUIET_EDIT_BOX) { return false; } std::string text = porting::getInputDialogValue(); ((gui::IGUIEditBox *)tochange)->setText(utf8_to_wide(text).c_str()); } return false; } #endif GUIFormSpecMenu::ItemSpec GUIFormSpecMenu::getItemAtPos(v2s32 p) const { core::rect<s32> imgrect(0,0,imgsize.X,imgsize.Y); for (const GUIFormSpecMenu::ListDrawSpec &s : m_inventorylists) { for(s32 i=0; i<s.geom.X*s.geom.Y; i++) { s32 item_i = i + s.start_item_i; s32 x = (i%s.geom.X) * spacing.X; s32 y = (i/s.geom.X) * spacing.Y; v2s32 p0(x,y); core::rect<s32> rect = imgrect + s.pos + p0; if(rect.isPointInside(p)) { return ItemSpec(s.inventoryloc, s.listname, item_i); } } } return ItemSpec(InventoryLocation(), "", -1); } void GUIFormSpecMenu::drawList(const ListDrawSpec &s, int layer, bool &item_hovered) { video::IVideoDriver* driver = Environment->getVideoDriver(); Inventory *inv = m_invmgr->getInventory(s.inventoryloc); if(!inv){ warningstream<<"GUIFormSpecMenu::drawList(): " <<"The inventory location " <<"\""<<s.inventoryloc.dump()<<"\" doesn't exist" <<std::endl; return; } InventoryList *ilist = inv->getList(s.listname); if(!ilist){ warningstream<<"GUIFormSpecMenu::drawList(): " <<"The inventory list \""<<s.listname<<"\" @ \"" <<s.inventoryloc.dump()<<"\" doesn't exist" <<std::endl; return; } core::rect<s32> imgrect(0,0,imgsize.X,imgsize.Y); for (s32 i = 0; i < s.geom.X * s.geom.Y; i++) { s32 item_i = i + s.start_item_i; if (item_i >= (s32)ilist->getSize()) break; s32 x = (i%s.geom.X) * spacing.X; s32 y = (i/s.geom.X) * spacing.Y; v2s32 p(x,y); core::rect<s32> rect = imgrect + s.pos + p; ItemStack item = ilist->getItem(item_i); bool selected = m_selected_item && m_invmgr->getInventory(m_selected_item->inventoryloc) == inv && m_selected_item->listname == s.listname && m_selected_item->i == item_i; bool hovering = rect.isPointInside(m_pointer); ItemRotationKind rotation_kind = selected ? IT_ROT_SELECTED : (hovering ? IT_ROT_HOVERED : IT_ROT_NONE); if (layer == 0) { if (hovering) { item_hovered = true; driver->draw2DRectangle(m_slotbg_h, rect, &AbsoluteClippingRect); } else { driver->draw2DRectangle(m_slotbg_n, rect, &AbsoluteClippingRect); } } //Draw inv slot borders if (m_slotborder) { s32 x1 = rect.UpperLeftCorner.X; s32 y1 = rect.UpperLeftCorner.Y; s32 x2 = rect.LowerRightCorner.X; s32 y2 = rect.LowerRightCorner.Y; s32 border = 1; driver->draw2DRectangle(m_slotbordercolor, core::rect<s32>(v2s32(x1 - border, y1 - border), v2s32(x2 + border, y1)), NULL); driver->draw2DRectangle(m_slotbordercolor, core::rect<s32>(v2s32(x1 - border, y2), v2s32(x2 + border, y2 + border)), NULL); driver->draw2DRectangle(m_slotbordercolor, core::rect<s32>(v2s32(x1 - border, y1), v2s32(x1, y2)), NULL); driver->draw2DRectangle(m_slotbordercolor, core::rect<s32>(v2s32(x2, y1), v2s32(x2 + border, y2)), NULL); } if (layer == 1) { // Draw item stack if (selected) item.takeItem(m_selected_amount); if (!item.empty()) { drawItemStack(driver, m_font, item, rect, &AbsoluteClippingRect, m_client, rotation_kind); } // Draw tooltip std::wstring tooltip_text; if (hovering && !m_selected_item) { const std::string &desc = item.metadata.getString("description"); if (desc.empty()) tooltip_text = utf8_to_wide(item.getDefinition(m_client->idef()).description); else tooltip_text = utf8_to_wide(desc); if (!item.name.empty()) { if (tooltip_text.empty()) tooltip_text = utf8_to_wide(item.name); else if (m_tooltip_append_itemname) tooltip_text += utf8_to_wide("\n[" + item.name + "]"); } } if (!tooltip_text.empty()) { showTooltip(tooltip_text, m_default_tooltip_color, m_default_tooltip_bgcolor); } } } } void GUIFormSpecMenu::drawSelectedItem() { video::IVideoDriver* driver = Environment->getVideoDriver(); if (!m_selected_item) { drawItemStack(driver, m_font, ItemStack(), core::rect<s32>(v2s32(0, 0), v2s32(0, 0)), NULL, m_client, IT_ROT_DRAGGED); return; } Inventory *inv = m_invmgr->getInventory(m_selected_item->inventoryloc); sanity_check(inv); InventoryList *list = inv->getList(m_selected_item->listname); sanity_check(list); ItemStack stack = list->getItem(m_selected_item->i); stack.count = m_selected_amount; core::rect<s32> imgrect(0,0,imgsize.X,imgsize.Y); core::rect<s32> rect = imgrect + (m_pointer - imgrect.getCenter()); rect.constrainTo(driver->getViewPort()); drawItemStack(driver, m_font, stack, rect, NULL, m_client, IT_ROT_DRAGGED); } void GUIFormSpecMenu::drawMenu() { if (m_form_src) { const std::string &newform = m_form_src->getForm(); if (newform != m_formspec_string) { m_formspec_string = newform; regenerateGui(m_screensize_old); } } gui::IGUISkin* skin = Environment->getSkin(); sanity_check(skin != NULL); gui::IGUIFont *old_font = skin->getFont(); skin->setFont(m_font); updateSelectedItem(); video::IVideoDriver* driver = Environment->getVideoDriver(); v2u32 screenSize = driver->getScreenSize(); core::rect<s32> allbg(0, 0, screenSize.X, screenSize.Y); if (m_bgfullscreen) driver->draw2DRectangle(m_fullscreen_bgcolor, allbg, &allbg); else driver->draw2DRectangle(m_bgcolor, AbsoluteRect, &AbsoluteClippingRect); m_tooltip_element->setVisible(false); for (const auto &pair : m_tooltip_rects) { if (pair.first.isPointInside(m_pointer)) { const std::wstring &text = pair.second.tooltip; if (!text.empty()) { showTooltip(text, pair.second.color, pair.second.bgcolor); break; } } } /* Draw backgrounds */ for (const GUIFormSpecMenu::ImageDrawSpec &spec : m_backgrounds) { video::ITexture *texture = m_tsrc->getTexture(spec.name); if (texture != 0) { // Image size on screen core::rect<s32> imgrect(0, 0, spec.geom.X, spec.geom.Y); // Image rectangle on screen core::rect<s32> rect = imgrect + spec.pos; if (spec.clip) { core::dimension2d<s32> absrec_size = AbsoluteRect.getSize(); rect = core::rect<s32>(AbsoluteRect.UpperLeftCorner.X - spec.pos.X, AbsoluteRect.UpperLeftCorner.Y - spec.pos.Y, AbsoluteRect.UpperLeftCorner.X + absrec_size.Width + spec.pos.X, AbsoluteRect.UpperLeftCorner.Y + absrec_size.Height + spec.pos.Y); } const video::SColor color(255,255,255,255); const video::SColor colors[] = {color,color,color,color}; draw2DImageFilterScaled(driver, texture, rect, core::rect<s32>(core::position2d<s32>(0,0), core::dimension2di(texture->getOriginalSize())), NULL/*&AbsoluteClippingRect*/, colors, true); } else { errorstream << "GUIFormSpecMenu::drawMenu() Draw backgrounds unable to load texture:" << std::endl; errorstream << "\t" << spec.name << std::endl; } } /* Draw Boxes */ for (const GUIFormSpecMenu::BoxDrawSpec &spec : m_boxes) { irr::video::SColor todraw = spec.color; core::rect<s32> rect(spec.pos.X,spec.pos.Y, spec.pos.X + spec.geom.X,spec.pos.Y + spec.geom.Y); driver->draw2DRectangle(todraw, rect, 0); } /* Call base class */ gui::IGUIElement::draw(); /* Draw images */ for (const GUIFormSpecMenu::ImageDrawSpec &spec : m_images) { video::ITexture *texture = m_tsrc->getTexture(spec.name); if (texture != 0) { const core::dimension2d<u32>& img_origsize = texture->getOriginalSize(); // Image size on screen core::rect<s32> imgrect; if (spec.scale) imgrect = core::rect<s32>(0,0,spec.geom.X, spec.geom.Y); else { imgrect = core::rect<s32>(0,0,img_origsize.Width,img_origsize.Height); } // Image rectangle on screen core::rect<s32> rect = imgrect + spec.pos; const video::SColor color(255,255,255,255); const video::SColor colors[] = {color,color,color,color}; draw2DImageFilterScaled(driver, texture, rect, core::rect<s32>(core::position2d<s32>(0,0),img_origsize), NULL/*&AbsoluteClippingRect*/, colors, true); } else { errorstream << "GUIFormSpecMenu::drawMenu() Draw images unable to load texture:" << std::endl; errorstream << "\t" << spec.name << std::endl; } } /* Draw item images */ for (const GUIFormSpecMenu::ImageDrawSpec &spec : m_itemimages) { if (m_client == 0) break; IItemDefManager *idef = m_client->idef(); ItemStack item; item.deSerialize(spec.item_name, idef); core::rect<s32> imgrect(0, 0, spec.geom.X, spec.geom.Y); // Viewport rectangle on screen core::rect<s32> rect = imgrect + spec.pos; if (spec.parent_button && spec.parent_button->isPressed()) { #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8) rect += core::dimension2d<s32>( 0.05 * (float)rect.getWidth(), 0.05 * (float)rect.getHeight()); #else rect += core::dimension2d<s32>( skin->getSize(irr::gui::EGDS_BUTTON_PRESSED_IMAGE_OFFSET_X), skin->getSize(irr::gui::EGDS_BUTTON_PRESSED_IMAGE_OFFSET_Y)); #endif } drawItemStack(driver, m_font, item, rect, &AbsoluteClippingRect, m_client, IT_ROT_NONE); } /* Draw items Layer 0: Item slot rectangles Layer 1: Item images; prepare tooltip */ bool item_hovered = false; for (int layer = 0; layer < 2; layer++) { for (const GUIFormSpecMenu::ListDrawSpec &spec : m_inventorylists) { drawList(spec, layer, item_hovered); } } if (!item_hovered) { drawItemStack(driver, m_font, ItemStack(), core::rect<s32>(v2s32(0, 0), v2s32(0, 0)), NULL, m_client, IT_ROT_HOVERED); } /* TODO find way to show tooltips on touchscreen */ #ifndef HAVE_TOUCHSCREENGUI m_pointer = RenderingEngine::get_raw_device()->getCursorControl()->getPosition(); #endif /* Draw static text elements */ for (const GUIFormSpecMenu::StaticTextSpec &spec : m_static_texts) { core::rect<s32> rect = spec.rect; if (spec.parent_button && spec.parent_button->isPressed()) { #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8) rect += core::dimension2d<s32>( 0.05 * (float)rect.getWidth(), 0.05 * (float)rect.getHeight()); #else // Use image offset instead of text's because its a bit smaller // and fits better, also TEXT_OFFSET_X is always 0 rect += core::dimension2d<s32>( skin->getSize(irr::gui::EGDS_BUTTON_PRESSED_IMAGE_OFFSET_X), skin->getSize(irr::gui::EGDS_BUTTON_PRESSED_IMAGE_OFFSET_Y)); #endif } video::SColor color(255, 255, 255, 255); m_font->draw(spec.text.c_str(), rect, color, true, true, &rect); } /* Draw fields/buttons tooltips */ gui::IGUIElement *hovered = Environment->getRootGUIElement()->getElementFromPoint(m_pointer); if (hovered != NULL) { s32 id = hovered->getID(); u64 delta = 0; if (id == -1) { m_old_tooltip_id = id; } else { if (id == m_old_tooltip_id) { delta = porting::getDeltaMs(m_hovered_time, porting::getTimeMs()); } else { m_hovered_time = porting::getTimeMs(); m_old_tooltip_id = id; } } // Find and update the current tooltip if (id != -1 && delta >= m_tooltip_show_delay) { for (const FieldSpec &field : m_fields) { if (field.fid != id) continue; const std::wstring &text = m_tooltips[field.fname].tooltip; if (!text.empty()) showTooltip(text, m_tooltips[field.fname].color, m_tooltips[field.fname].bgcolor); break; } } } m_tooltip_element->draw(); /* Draw dragged item stack */ drawSelectedItem(); skin->setFont(old_font); } void GUIFormSpecMenu::showTooltip(const std::wstring &text, const irr::video::SColor &color, const irr::video::SColor &bgcolor) { const std::wstring ntext = translate_string(text); m_tooltip_element->setOverrideColor(color); m_tooltip_element->setBackgroundColor(bgcolor); setStaticText(m_tooltip_element, ntext.c_str()); // Tooltip size and offset s32 tooltip_width = m_tooltip_element->getTextWidth() + m_btn_height; #if (IRRLICHT_VERSION_MAJOR <= 1 && IRRLICHT_VERSION_MINOR <= 8 && IRRLICHT_VERSION_REVISION < 2) || USE_FREETYPE == 1 std::vector<std::wstring> text_rows = str_split(ntext, L'\n'); s32 tooltip_height = m_tooltip_element->getTextHeight() * text_rows.size() + 5; #else s32 tooltip_height = m_tooltip_element->getTextHeight() + 5; #endif v2u32 screenSize = Environment->getVideoDriver()->getScreenSize(); int tooltip_offset_x = m_btn_height; int tooltip_offset_y = m_btn_height; #ifdef __ANDROID__ tooltip_offset_x *= 3; tooltip_offset_y = 0; if (m_pointer.X > (s32)screenSize.X / 2) tooltip_offset_x = -(tooltip_offset_x + tooltip_width); #endif // Calculate and set the tooltip position s32 tooltip_x = m_pointer.X + tooltip_offset_x; s32 tooltip_y = m_pointer.Y + tooltip_offset_y; if (tooltip_x + tooltip_width > (s32)screenSize.X) tooltip_x = (s32)screenSize.X - tooltip_width - m_btn_height; if (tooltip_y + tooltip_height > (s32)screenSize.Y) tooltip_y = (s32)screenSize.Y - tooltip_height - m_btn_height; m_tooltip_element->setRelativePosition( core::rect<s32>( core::position2d<s32>(tooltip_x, tooltip_y), core::dimension2d<s32>(tooltip_width, tooltip_height) ) ); // Display the tooltip m_tooltip_element->setVisible(true); bringToFront(m_tooltip_element); } void GUIFormSpecMenu::updateSelectedItem() { verifySelectedItem(); // If craftresult is nonempty and nothing else is selected, select it now. if (!m_selected_item) { for (const GUIFormSpecMenu::ListDrawSpec &s : m_inventorylists) { if (s.listname != "craftpreview") continue; Inventory *inv = m_invmgr->getInventory(s.inventoryloc); if (!inv) continue; InventoryList *list = inv->getList("craftresult"); if (!list || list->getSize() == 0) continue; const ItemStack &item = list->getItem(0); if (item.empty()) continue; // Grab selected item from the crafting result list m_selected_item = new ItemSpec; m_selected_item->inventoryloc = s.inventoryloc; m_selected_item->listname = "craftresult"; m_selected_item->i = 0; m_selected_amount = item.count; m_selected_dragging = false; break; } } // If craftresult is selected, keep the whole stack selected if (m_selected_item && m_selected_item->listname == "craftresult") m_selected_amount = verifySelectedItem().count; } ItemStack GUIFormSpecMenu::verifySelectedItem() { // If the selected stack has become empty for some reason, deselect it. // If the selected stack has become inaccessible, deselect it. // If the selected stack has become smaller, adjust m_selected_amount. // Return the selected stack. if(m_selected_item) { if(m_selected_item->isValid()) { Inventory *inv = m_invmgr->getInventory(m_selected_item->inventoryloc); if(inv) { InventoryList *list = inv->getList(m_selected_item->listname); if(list && (u32) m_selected_item->i < list->getSize()) { ItemStack stack = list->getItem(m_selected_item->i); if (!m_selected_swap.empty()) { if (m_selected_swap.name == stack.name && m_selected_swap.count == stack.count) m_selected_swap.clear(); } else { m_selected_amount = std::min(m_selected_amount, stack.count); } if (!stack.empty()) return stack; } } } // selection was not valid delete m_selected_item; m_selected_item = NULL; m_selected_amount = 0; m_selected_dragging = false; } return ItemStack(); } void GUIFormSpecMenu::acceptInput(FormspecQuitMode quitmode=quit_mode_no) { if(m_text_dst) { StringMap fields; if (quitmode == quit_mode_accept) { fields["quit"] = "true"; } if (quitmode == quit_mode_cancel) { fields["quit"] = "true"; m_text_dst->gotText(fields); return; } if (current_keys_pending.key_down) { fields["key_down"] = "true"; current_keys_pending.key_down = false; } if (current_keys_pending.key_up) { fields["key_up"] = "true"; current_keys_pending.key_up = false; } if (current_keys_pending.key_enter) { fields["key_enter"] = "true"; current_keys_pending.key_enter = false; } if (!current_field_enter_pending.empty()) { fields["key_enter_field"] = current_field_enter_pending; current_field_enter_pending = ""; } if (current_keys_pending.key_escape) { fields["key_escape"] = "true"; current_keys_pending.key_escape = false; } for (const GUIFormSpecMenu::FieldSpec &s : m_fields) { if(s.send) { std::string name = s.fname; if (s.ftype == f_Button) { fields[name] = wide_to_utf8(s.flabel); } else if (s.ftype == f_Table) { GUITable *table = getTable(s.fname); if (table) { fields[name] = table->checkEvent(); } } else if(s.ftype == f_DropDown) { // no dynamic cast possible due to some distributions shipped // without rtti support in irrlicht IGUIElement * element = getElementFromId(s.fid); gui::IGUIComboBox *e = NULL; if ((element) && (element->getType() == gui::EGUIET_COMBO_BOX)) { e = static_cast<gui::IGUIComboBox*>(element); } s32 selected = e->getSelected(); if (selected >= 0) { std::vector<std::string> *dropdown_values = getDropDownValues(s.fname); if (dropdown_values && selected < (s32)dropdown_values->size()) { fields[name] = (*dropdown_values)[selected]; } } } else if (s.ftype == f_TabHeader) { // no dynamic cast possible due to some distributions shipped // without rttzi support in irrlicht IGUIElement * element = getElementFromId(s.fid); gui::IGUITabControl *e = NULL; if ((element) && (element->getType() == gui::EGUIET_TAB_CONTROL)) { e = static_cast<gui::IGUITabControl *>(element); } if (e != 0) { std::stringstream ss; ss << (e->getActiveTab() +1); fields[name] = ss.str(); } } else if (s.ftype == f_CheckBox) { // no dynamic cast possible due to some distributions shipped // without rtti support in irrlicht IGUIElement * element = getElementFromId(s.fid); gui::IGUICheckBox *e = NULL; if ((element) && (element->getType() == gui::EGUIET_CHECK_BOX)) { e = static_cast<gui::IGUICheckBox*>(element); } if (e != 0) { if (e->isChecked()) fields[name] = "true"; else fields[name] = "false"; } } else if (s.ftype == f_ScrollBar) { // no dynamic cast possible due to some distributions shipped // without rtti support in irrlicht IGUIElement * element = getElementFromId(s.fid); gui::IGUIScrollBar *e = NULL; if ((element) && (element->getType() == gui::EGUIET_SCROLL_BAR)) { e = static_cast<gui::IGUIScrollBar*>(element); } if (e != 0) { std::stringstream os; os << e->getPos(); if (s.fdefault == L"Changed") fields[name] = "CHG:" + os.str(); else fields[name] = "VAL:" + os.str(); } } else { IGUIElement* e = getElementFromId(s.fid); if(e != NULL) { fields[name] = wide_to_utf8(e->getText()); } } } } m_text_dst->gotText(fields); } } static bool isChild(gui::IGUIElement * tocheck, gui::IGUIElement * parent) { while(tocheck != NULL) { if (tocheck == parent) { return true; } tocheck = tocheck->getParent(); } return false; } bool GUIFormSpecMenu::preprocessEvent(const SEvent& event) { // The IGUITabControl renders visually using the skin's selected // font, which we override for the duration of form drawing, // but computes tab hotspots based on how it would have rendered // using the font that is selected at the time of button release. // To make these two consistent, temporarily override the skin's // font while the IGUITabControl is processing the event. if (event.EventType == EET_MOUSE_INPUT_EVENT && event.MouseInput.Event == EMIE_LMOUSE_LEFT_UP) { s32 x = event.MouseInput.X; s32 y = event.MouseInput.Y; gui::IGUIElement *hovered = Environment->getRootGUIElement()->getElementFromPoint( core::position2d<s32>(x, y)); if (hovered && isMyChild(hovered) && hovered->getType() == gui::EGUIET_TAB_CONTROL) { gui::IGUISkin* skin = Environment->getSkin(); sanity_check(skin != NULL); gui::IGUIFont *old_font = skin->getFont(); skin->setFont(m_font); bool retval = hovered->OnEvent(event); skin->setFont(old_font); return retval; } } // Fix Esc/Return key being eaten by checkboxen and tables if(event.EventType==EET_KEY_INPUT_EVENT) { KeyPress kp(event.KeyInput); if (kp == EscapeKey || kp == CancelKey || kp == getKeySetting("keymap_inventory") || event.KeyInput.Key==KEY_RETURN) { gui::IGUIElement *focused = Environment->getFocus(); if (focused && isMyChild(focused) && (focused->getType() == gui::EGUIET_LIST_BOX || focused->getType() == gui::EGUIET_CHECK_BOX) && (focused->getParent()->getType() != gui::EGUIET_COMBO_BOX || event.KeyInput.Key != KEY_RETURN)) { OnEvent(event); return true; } } } // Mouse wheel events: send to hovered element instead of focused if(event.EventType==EET_MOUSE_INPUT_EVENT && event.MouseInput.Event == EMIE_MOUSE_WHEEL) { s32 x = event.MouseInput.X; s32 y = event.MouseInput.Y; gui::IGUIElement *hovered = Environment->getRootGUIElement()->getElementFromPoint( core::position2d<s32>(x, y)); if (hovered && isMyChild(hovered)) { hovered->OnEvent(event); return true; } } if (event.EventType == EET_MOUSE_INPUT_EVENT) { s32 x = event.MouseInput.X; s32 y = event.MouseInput.Y; gui::IGUIElement *hovered = Environment->getRootGUIElement()->getElementFromPoint( core::position2d<s32>(x, y)); if (event.MouseInput.Event == EMIE_LMOUSE_PRESSED_DOWN) { m_old_tooltip_id = -1; } if (!isChild(hovered,this)) { if (DoubleClickDetection(event)) { return true; } } } if (event.EventType == irr::EET_JOYSTICK_INPUT_EVENT) { /* TODO add a check like: if (event.JoystickEvent != joystick_we_listen_for) return false; */ bool handled = m_joystick->handleEvent(event.JoystickEvent); if (handled) { if (m_joystick->wasKeyDown(KeyType::ESC)) { tryClose(); } else if (m_joystick->wasKeyDown(KeyType::JUMP)) { if (m_allowclose) { acceptInput(quit_mode_accept); quitMenu(); } } } return handled; } return GUIModalMenu::preprocessEvent(event); } /******************************************************************************/ bool GUIFormSpecMenu::DoubleClickDetection(const SEvent event) { /* The following code is for capturing double-clicks of the mouse button * and translating the double-click into an EET_KEY_INPUT_EVENT event * -- which closes the form -- under some circumstances. * * There have been many github issues reporting this as a bug even though it * was an intended feature. For this reason, remapping the double-click as * an ESC must be explicitly set when creating this class via the * /p remap_dbl_click parameter of the constructor. */ if (!m_remap_dbl_click) return false; if (event.MouseInput.Event == EMIE_LMOUSE_PRESSED_DOWN) { m_doubleclickdetect[0].pos = m_doubleclickdetect[1].pos; m_doubleclickdetect[0].time = m_doubleclickdetect[1].time; m_doubleclickdetect[1].pos = m_pointer; m_doubleclickdetect[1].time = porting::getTimeMs(); } else if (event.MouseInput.Event == EMIE_LMOUSE_LEFT_UP) { u64 delta = porting::getDeltaMs(m_doubleclickdetect[0].time, porting::getTimeMs()); if (delta > 400) { return false; } double squaredistance = m_doubleclickdetect[0].pos .getDistanceFromSQ(m_doubleclickdetect[1].pos); if (squaredistance > (30*30)) { return false; } SEvent* translated = new SEvent(); assert(translated != 0); //translate doubleclick to escape memset(translated, 0, sizeof(SEvent)); translated->EventType = irr::EET_KEY_INPUT_EVENT; translated->KeyInput.Key = KEY_ESCAPE; translated->KeyInput.Control = false; translated->KeyInput.Shift = false; translated->KeyInput.PressedDown = true; translated->KeyInput.Char = 0; OnEvent(*translated); // no need to send the key up event as we're already deleted // and no one else did notice this event delete translated; return true; } return false; } void GUIFormSpecMenu::tryClose() { if (m_allowclose) { doPause = false; acceptInput(quit_mode_cancel); quitMenu(); } else { m_text_dst->gotText(L"MenuQuit"); } } enum ButtonEventType : u8 { BET_LEFT, BET_RIGHT, BET_MIDDLE, BET_WHEEL_UP, BET_WHEEL_DOWN, BET_UP, BET_DOWN, BET_MOVE, BET_OTHER }; bool GUIFormSpecMenu::OnEvent(const SEvent& event) { if (event.EventType==EET_KEY_INPUT_EVENT) { KeyPress kp(event.KeyInput); if (event.KeyInput.PressedDown && ( (kp == EscapeKey) || (kp == CancelKey) || ((m_client != NULL) && (kp == getKeySetting("keymap_inventory"))))) { tryClose(); return true; } if (m_client != NULL && event.KeyInput.PressedDown && (kp == getKeySetting("keymap_screenshot"))) { m_client->makeScreenshot(); } if (event.KeyInput.PressedDown && (event.KeyInput.Key==KEY_RETURN || event.KeyInput.Key==KEY_UP || event.KeyInput.Key==KEY_DOWN) ) { switch (event.KeyInput.Key) { case KEY_RETURN: current_keys_pending.key_enter = true; break; case KEY_UP: current_keys_pending.key_up = true; break; case KEY_DOWN: current_keys_pending.key_down = true; break; break; default: //can't happen at all! FATAL_ERROR("Reached a source line that can't ever been reached"); break; } if (current_keys_pending.key_enter && m_allowclose) { acceptInput(quit_mode_accept); quitMenu(); } else { acceptInput(); } return true; } } /* Mouse event other than movement, or crossing the border of inventory field while holding right mouse button */ if (event.EventType == EET_MOUSE_INPUT_EVENT && (event.MouseInput.Event != EMIE_MOUSE_MOVED || (event.MouseInput.Event == EMIE_MOUSE_MOVED && event.MouseInput.isRightPressed() && getItemAtPos(m_pointer).i != getItemAtPos(m_old_pointer).i))) { // Get selected item and hovered/clicked item (s) m_old_tooltip_id = -1; updateSelectedItem(); ItemSpec s = getItemAtPos(m_pointer); Inventory *inv_selected = NULL; Inventory *inv_s = NULL; InventoryList *list_s = NULL; if (m_selected_item) { inv_selected = m_invmgr->getInventory(m_selected_item->inventoryloc); sanity_check(inv_selected); sanity_check(inv_selected->getList(m_selected_item->listname) != NULL); } u32 s_count = 0; if (s.isValid()) do { // breakable inv_s = m_invmgr->getInventory(s.inventoryloc); if (!inv_s) { errorstream << "InventoryMenu: The selected inventory location " << "\"" << s.inventoryloc.dump() << "\" doesn't exist" << std::endl; s.i = -1; // make it invalid again break; } list_s = inv_s->getList(s.listname); if (list_s == NULL) { verbosestream << "InventoryMenu: The selected inventory list \"" << s.listname << "\" does not exist" << std::endl; s.i = -1; // make it invalid again break; } if ((u32)s.i >= list_s->getSize()) { infostream << "InventoryMenu: The selected inventory list \"" << s.listname << "\" is too small (i=" << s.i << ", size=" << list_s->getSize() << ")" << std::endl; s.i = -1; // make it invalid again break; } s_count = list_s->getItem(s.i).count; } while(0); bool identical = m_selected_item && s.isValid() && (inv_selected == inv_s) && (m_selected_item->listname == s.listname) && (m_selected_item->i == s.i); ButtonEventType button = BET_LEFT; ButtonEventType updown = BET_OTHER; switch (event.MouseInput.Event) { case EMIE_LMOUSE_PRESSED_DOWN: button = BET_LEFT; updown = BET_DOWN; break; case EMIE_RMOUSE_PRESSED_DOWN: button = BET_RIGHT; updown = BET_DOWN; break; case EMIE_MMOUSE_PRESSED_DOWN: button = BET_MIDDLE; updown = BET_DOWN; break; case EMIE_MOUSE_WHEEL: button = (event.MouseInput.Wheel > 0) ? BET_WHEEL_UP : BET_WHEEL_DOWN; updown = BET_DOWN; break; case EMIE_LMOUSE_LEFT_UP: button = BET_LEFT; updown = BET_UP; break; case EMIE_RMOUSE_LEFT_UP: button = BET_RIGHT; updown = BET_UP; break; case EMIE_MMOUSE_LEFT_UP: button = BET_MIDDLE; updown = BET_UP; break; case EMIE_MOUSE_MOVED: updown = BET_MOVE; break; default: break; } // Set this number to a positive value to generate a move action // from m_selected_item to s. u32 move_amount = 0; // Set this number to a positive value to generate a move action // from s to the next inventory ring. u32 shift_move_amount = 0; // Set this number to a positive value to generate a drop action // from m_selected_item. u32 drop_amount = 0; // Set this number to a positive value to generate a craft action at s. u32 craft_amount = 0; switch (updown) { case BET_DOWN: // Some mouse button has been pressed //infostream<<"Mouse button "<<button<<" pressed at p=(" // <<p.X<<","<<p.Y<<")"<<std::endl; m_selected_dragging = false; if (s.isValid() && s.listname == "craftpreview") { // Craft preview has been clicked: craft craft_amount = (button == BET_MIDDLE ? 10 : 1); } else if (!m_selected_item) { if (s_count && button != BET_WHEEL_UP) { // Non-empty stack has been clicked: select or shift-move it m_selected_item = new ItemSpec(s); u32 count; if (button == BET_RIGHT) count = (s_count + 1) / 2; else if (button == BET_MIDDLE) count = MYMIN(s_count, 10); else if (button == BET_WHEEL_DOWN) count = 1; else // left count = s_count; if (!event.MouseInput.Shift) { // no shift: select item m_selected_amount = count; m_selected_dragging = button != BET_WHEEL_DOWN; m_auto_place = false; } else { // shift pressed: move item, right click moves 1 shift_move_amount = button == BET_RIGHT ? 1 : count; } } } else { // m_selected_item != NULL assert(m_selected_amount >= 1); if (s.isValid()) { // Clicked a slot: move if (button == BET_RIGHT || button == BET_WHEEL_UP) move_amount = 1; else if (button == BET_MIDDLE) move_amount = MYMIN(m_selected_amount, 10); else if (button == BET_LEFT) move_amount = m_selected_amount; // else wheeldown if (identical) { if (button == BET_WHEEL_DOWN) { if (m_selected_amount < s_count) ++m_selected_amount; } else { if (move_amount >= m_selected_amount) m_selected_amount = 0; else m_selected_amount -= move_amount; move_amount = 0; } } } else if (!getAbsoluteClippingRect().isPointInside(m_pointer) && button != BET_WHEEL_DOWN) { // Clicked outside of the window: drop if (button == BET_RIGHT || button == BET_WHEEL_UP) drop_amount = 1; else if (button == BET_MIDDLE) drop_amount = MYMIN(m_selected_amount, 10); else // left drop_amount = m_selected_amount; } } break; case BET_UP: // Some mouse button has been released //infostream<<"Mouse button "<<button<<" released at p=(" // <<p.X<<","<<p.Y<<")"<<std::endl; if (m_selected_dragging && m_selected_item) { if (s.isValid()) { if (!identical) { // Dragged to different slot: move all selected move_amount = m_selected_amount; } } else if (!getAbsoluteClippingRect().isPointInside(m_pointer)) { // Dragged outside of window: drop all selected drop_amount = m_selected_amount; } } m_selected_dragging = false; // Keep track of whether the mouse button be released // One click is drag without dropping. Click + release // + click changes to drop item when moved mode if (m_selected_item) m_auto_place = true; break; case BET_MOVE: // Mouse has been moved and rmb is down and mouse pointer just // entered a new inventory field (checked in the entry-if, this // is the only action here that is generated by mouse movement) if (m_selected_item && s.isValid()) { // Move 1 item // TODO: middle mouse to move 10 items might be handy if (m_auto_place) { // Only move an item if the destination slot is empty // or contains the same item type as what is going to be // moved InventoryList *list_from = inv_selected->getList(m_selected_item->listname); InventoryList *list_to = list_s; assert(list_from && list_to); ItemStack stack_from = list_from->getItem(m_selected_item->i); ItemStack stack_to = list_to->getItem(s.i); if (stack_to.empty() || stack_to.name == stack_from.name) move_amount = 1; } } break; default: break; } // Possibly send inventory action to server if (move_amount > 0) { // Send IAction::Move assert(m_selected_item && m_selected_item->isValid()); assert(s.isValid()); assert(inv_selected && inv_s); InventoryList *list_from = inv_selected->getList(m_selected_item->listname); InventoryList *list_to = list_s; assert(list_from && list_to); ItemStack stack_from = list_from->getItem(m_selected_item->i); ItemStack stack_to = list_to->getItem(s.i); // Check how many items can be moved move_amount = stack_from.count = MYMIN(move_amount, stack_from.count); ItemStack leftover = stack_to.addItem(stack_from, m_client->idef()); bool move = true; // If source stack cannot be added to destination stack at all, // they are swapped if (leftover.count == stack_from.count && leftover.name == stack_from.name) { if (m_selected_swap.empty()) { m_selected_amount = stack_to.count; m_selected_dragging = false; // WARNING: BLACK MAGIC, BUT IN A REDUCED SET // Skip next validation checks due async inventory calls m_selected_swap = stack_to; } else { move = false; } } // Source stack goes fully into destination stack else if (leftover.empty()) { m_selected_amount -= move_amount; } // Source stack goes partly into destination stack else { move_amount -= leftover.count; m_selected_amount -= move_amount; } if (move) { infostream << "Handing IAction::Move to manager" << std::endl; IMoveAction *a = new IMoveAction(); a->count = move_amount; a->from_inv = m_selected_item->inventoryloc; a->from_list = m_selected_item->listname; a->from_i = m_selected_item->i; a->to_inv = s.inventoryloc; a->to_list = s.listname; a->to_i = s.i; m_invmgr->inventoryAction(a); } } else if (shift_move_amount > 0) { u32 mis = m_inventory_rings.size(); u32 i = 0; for (; i < mis; i++) { const ListRingSpec &sp = m_inventory_rings[i]; if (sp.inventoryloc == s.inventoryloc && sp.listname == s.listname) break; } do { if (i >= mis) // if not found break; u32 to_inv_ind = (i + 1) % mis; const ListRingSpec &to_inv_sp = m_inventory_rings[to_inv_ind]; InventoryList *list_from = list_s; if (!s.isValid()) break; Inventory *inv_to = m_invmgr->getInventory(to_inv_sp.inventoryloc); if (!inv_to) break; InventoryList *list_to = inv_to->getList(to_inv_sp.listname); if (!list_to) break; ItemStack stack_from = list_from->getItem(s.i); assert(shift_move_amount <= stack_from.count); infostream << "Handing IAction::Move to manager" << std::endl; IMoveAction *a = new IMoveAction(); a->count = shift_move_amount; a->from_inv = s.inventoryloc; a->from_list = s.listname; a->from_i = s.i; a->to_inv = to_inv_sp.inventoryloc; a->to_list = to_inv_sp.listname; a->move_somewhere = true; m_invmgr->inventoryAction(a); } while (0); } else if (drop_amount > 0) { // Send IAction::Drop assert(m_selected_item && m_selected_item->isValid()); assert(inv_selected); InventoryList *list_from = inv_selected->getList(m_selected_item->listname); assert(list_from); ItemStack stack_from = list_from->getItem(m_selected_item->i); // Check how many items can be dropped drop_amount = stack_from.count = MYMIN(drop_amount, stack_from.count); assert(drop_amount > 0 && drop_amount <= m_selected_amount); m_selected_amount -= drop_amount; infostream << "Handing IAction::Drop to manager" << std::endl; IDropAction *a = new IDropAction(); a->count = drop_amount; a->from_inv = m_selected_item->inventoryloc; a->from_list = m_selected_item->listname; a->from_i = m_selected_item->i; m_invmgr->inventoryAction(a); } else if (craft_amount > 0) { assert(s.isValid()); // if there are no items selected or the selected item // belongs to craftresult list, proceed with crafting if (m_selected_item == NULL || !m_selected_item->isValid() || m_selected_item->listname == "craftresult") { assert(inv_s); // Send IACTION_CRAFT infostream << "Handing IACTION_CRAFT to manager" << std::endl; ICraftAction *a = new ICraftAction(); a->count = craft_amount; a->craft_inv = s.inventoryloc; m_invmgr->inventoryAction(a); } } // If m_selected_amount has been decreased to zero, deselect if (m_selected_amount == 0) { m_selected_swap.clear(); delete m_selected_item; m_selected_item = NULL; m_selected_amount = 0; m_selected_dragging = false; } m_old_pointer = m_pointer; } if (event.EventType == EET_GUI_EVENT) { if (event.GUIEvent.EventType == gui::EGET_TAB_CHANGED && isVisible()) { // find the element that was clicked for (GUIFormSpecMenu::FieldSpec &s : m_fields) { if ((s.ftype == f_TabHeader) && (s.fid == event.GUIEvent.Caller->getID())) { s.send = true; acceptInput(); s.send = false; return true; } } } if (event.GUIEvent.EventType == gui::EGET_ELEMENT_FOCUS_LOST && isVisible()) { if (!canTakeFocus(event.GUIEvent.Element)) { infostream<<"GUIFormSpecMenu: Not allowing focus change." <<std::endl; // Returning true disables focus change return true; } } if ((event.GUIEvent.EventType == gui::EGET_BUTTON_CLICKED) || (event.GUIEvent.EventType == gui::EGET_CHECKBOX_CHANGED) || (event.GUIEvent.EventType == gui::EGET_COMBO_BOX_CHANGED) || (event.GUIEvent.EventType == gui::EGET_SCROLL_BAR_CHANGED)) { unsigned int btn_id = event.GUIEvent.Caller->getID(); if (btn_id == 257) { if (m_allowclose) { acceptInput(quit_mode_accept); quitMenu(); } else { acceptInput(); m_text_dst->gotText(L"ExitButton"); } // quitMenu deallocates menu return true; } // find the element that was clicked for (GUIFormSpecMenu::FieldSpec &s : m_fields) { // if its a button, set the send field so // lua knows which button was pressed if ((s.ftype == f_Button || s.ftype == f_CheckBox) && s.fid == event.GUIEvent.Caller->getID()) { s.send = true; if (s.is_exit) { if (m_allowclose) { acceptInput(quit_mode_accept); quitMenu(); } else { m_text_dst->gotText(L"ExitButton"); } return true; } acceptInput(quit_mode_no); s.send = false; return true; } else if ((s.ftype == f_DropDown) && (s.fid == event.GUIEvent.Caller->getID())) { // only send the changed dropdown for (GUIFormSpecMenu::FieldSpec &s2 : m_fields) { if (s2.ftype == f_DropDown) { s2.send = false; } } s.send = true; acceptInput(quit_mode_no); // revert configuration to make sure dropdowns are sent on // regular button click for (GUIFormSpecMenu::FieldSpec &s2 : m_fields) { if (s2.ftype == f_DropDown) { s2.send = true; } } return true; } else if ((s.ftype == f_ScrollBar) && (s.fid == event.GUIEvent.Caller->getID())) { s.fdefault = L"Changed"; acceptInput(quit_mode_no); s.fdefault = L""; } } } if (event.GUIEvent.EventType == gui::EGET_EDITBOX_ENTER) { if (event.GUIEvent.Caller->getID() > 257) { bool close_on_enter = true; for (GUIFormSpecMenu::FieldSpec &s : m_fields) { if (s.ftype == f_Unknown && s.fid == event.GUIEvent.Caller->getID()) { current_field_enter_pending = s.fname; std::unordered_map<std::string, bool>::const_iterator it = field_close_on_enter.find(s.fname); if (it != field_close_on_enter.end()) close_on_enter = (*it).second; break; } } if (m_allowclose && close_on_enter) { current_keys_pending.key_enter = true; acceptInput(quit_mode_accept); quitMenu(); } else { current_keys_pending.key_enter = true; acceptInput(); } // quitMenu deallocates menu return true; } } if (event.GUIEvent.EventType == gui::EGET_TABLE_CHANGED) { int current_id = event.GUIEvent.Caller->getID(); if (current_id > 257) { // find the element that was clicked for (GUIFormSpecMenu::FieldSpec &s : m_fields) { // if it's a table, set the send field // so lua knows which table was changed if ((s.ftype == f_Table) && (s.fid == current_id)) { s.send = true; acceptInput(); s.send=false; } } return true; } } } return Parent ? Parent->OnEvent(event) : false; } /** * get name of element by element id * @param id of element * @return name string or empty string */ std::string GUIFormSpecMenu::getNameByID(s32 id) { for (FieldSpec &spec : m_fields) { if (spec.fid == id) { return spec.fname; } } return ""; } /** * get label of element by id * @param id of element * @return label string or empty string */ std::wstring GUIFormSpecMenu::getLabelByID(s32 id) { for (FieldSpec &spec : m_fields) { if (spec.fid == id) { return spec.flabel; } } return L""; }
pgimeno/minetest
src/gui/guiFormSpecMenu.cpp
C++
mit
105,199
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> 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. */ #pragma once #include <utility> #include <stack> #include "irrlichttypes_extrabloated.h" #include "inventorymanager.h" #include "modalMenu.h" #include "guiTable.h" #include "network/networkprotocol.h" #include "client/joystick_controller.h" #include "util/string.h" #include "util/enriched_string.h" class InventoryManager; class ISimpleTextureSource; class Client; typedef enum { f_Button, f_Table, f_TabHeader, f_CheckBox, f_DropDown, f_ScrollBar, f_Unknown } FormspecFieldType; typedef enum { quit_mode_no, quit_mode_accept, quit_mode_cancel } FormspecQuitMode; struct TextDest { virtual ~TextDest() = default; // This is deprecated I guess? -celeron55 virtual void gotText(const std::wstring &text) {} virtual void gotText(const StringMap &fields) = 0; std::string m_formname; }; class IFormSource { public: virtual ~IFormSource() = default; virtual const std::string &getForm() const = 0; // Fill in variables in field text virtual std::string resolveText(const std::string &str) { return str; } }; class GUIFormSpecMenu : public GUIModalMenu { struct ItemSpec { ItemSpec() = default; ItemSpec(const InventoryLocation &a_inventoryloc, const std::string &a_listname, s32 a_i) : inventoryloc(a_inventoryloc), listname(a_listname), i(a_i) { } bool isValid() const { return i != -1; } InventoryLocation inventoryloc; std::string listname; s32 i = -1; }; struct ListDrawSpec { ListDrawSpec() = default; ListDrawSpec(const InventoryLocation &a_inventoryloc, const std::string &a_listname, v2s32 a_pos, v2s32 a_geom, s32 a_start_item_i): inventoryloc(a_inventoryloc), listname(a_listname), pos(a_pos), geom(a_geom), start_item_i(a_start_item_i) { } InventoryLocation inventoryloc; std::string listname; v2s32 pos; v2s32 geom; s32 start_item_i; }; struct ListRingSpec { ListRingSpec() = default; ListRingSpec(const InventoryLocation &a_inventoryloc, const std::string &a_listname): inventoryloc(a_inventoryloc), listname(a_listname) { } InventoryLocation inventoryloc; std::string listname; }; struct ImageDrawSpec { ImageDrawSpec(): parent_button(NULL), clip(false) { } ImageDrawSpec(const std::string &a_name, const std::string &a_item_name, gui::IGUIButton *a_parent_button, const v2s32 &a_pos, const v2s32 &a_geom): name(a_name), item_name(a_item_name), parent_button(a_parent_button), pos(a_pos), geom(a_geom), scale(true), clip(false) { } ImageDrawSpec(const std::string &a_name, const std::string &a_item_name, const v2s32 &a_pos, const v2s32 &a_geom): name(a_name), item_name(a_item_name), parent_button(NULL), pos(a_pos), geom(a_geom), scale(true), clip(false) { } ImageDrawSpec(const std::string &a_name, const v2s32 &a_pos, const v2s32 &a_geom, bool clip=false): name(a_name), parent_button(NULL), pos(a_pos), geom(a_geom), scale(true), clip(clip) { } ImageDrawSpec(const std::string &a_name, const v2s32 &a_pos): name(a_name), parent_button(NULL), pos(a_pos), scale(false), clip(false) { } std::string name; std::string item_name; gui::IGUIButton *parent_button; v2s32 pos; v2s32 geom; bool scale; bool clip; }; struct FieldSpec { FieldSpec() = default; FieldSpec(const std::string &name, const std::wstring &label, const std::wstring &default_text, int id) : fname(name), flabel(label), fdefault(unescape_enriched(translate_string(default_text))), fid(id), send(false), ftype(f_Unknown), is_exit(false) { } std::string fname; std::wstring flabel; std::wstring fdefault; int fid; bool send; FormspecFieldType ftype; bool is_exit; core::rect<s32> rect; }; struct BoxDrawSpec { BoxDrawSpec(v2s32 a_pos, v2s32 a_geom, irr::video::SColor a_color): pos(a_pos), geom(a_geom), color(a_color) { } v2s32 pos; v2s32 geom; irr::video::SColor color; }; struct TooltipSpec { TooltipSpec() = default; TooltipSpec(const std::wstring &a_tooltip, irr::video::SColor a_bgcolor, irr::video::SColor a_color): tooltip(translate_string(a_tooltip)), bgcolor(a_bgcolor), color(a_color) { } std::wstring tooltip; irr::video::SColor bgcolor; irr::video::SColor color; }; struct StaticTextSpec { StaticTextSpec(): parent_button(NULL) { } StaticTextSpec(const std::wstring &a_text, const core::rect<s32> &a_rect): text(a_text), rect(a_rect), parent_button(NULL) { } StaticTextSpec(const std::wstring &a_text, const core::rect<s32> &a_rect, gui::IGUIButton *a_parent_button): text(a_text), rect(a_rect), parent_button(a_parent_button) { } std::wstring text; core::rect<s32> rect; gui::IGUIButton *parent_button; }; public: GUIFormSpecMenu(JoystickController *joystick, gui::IGUIElement* parent, s32 id, IMenuManager *menumgr, Client *client, ISimpleTextureSource *tsrc, IFormSource* fs_src, TextDest* txt_dst, std::string formspecPrepend, bool remap_dbl_click = true); ~GUIFormSpecMenu(); static void create(GUIFormSpecMenu *&cur_formspec, Client *client, JoystickController *joystick, IFormSource *fs_src, TextDest *txt_dest, const std::string &formspecPrepend); void setFormSpec(const std::string &formspec_string, const InventoryLocation &current_inventory_location) { m_formspec_string = formspec_string; m_current_inventory_location = current_inventory_location; regenerateGui(m_screensize_old); } void setFormspecPrepend(const std::string &formspecPrepend) { m_formspec_prepend = formspecPrepend; } // form_src is deleted by this GUIFormSpecMenu void setFormSource(IFormSource *form_src) { delete m_form_src; m_form_src = form_src; } // text_dst is deleted by this GUIFormSpecMenu void setTextDest(TextDest *text_dst) { delete m_text_dst; m_text_dst = text_dst; } void allowClose(bool value) { m_allowclose = value; } void lockSize(bool lock,v2u32 basescreensize=v2u32(0,0)) { m_lock = lock; m_lockscreensize = basescreensize; } void removeChildren(); void setInitialFocus(); void setFocus(const std::string &elementname) { m_focused_element = elementname; } /* Remove and re-add (or reposition) stuff */ void regenerateGui(v2u32 screensize); ItemSpec getItemAtPos(v2s32 p) const; void drawList(const ListDrawSpec &s, int layer, bool &item_hovered); void drawSelectedItem(); void drawMenu(); void updateSelectedItem(); ItemStack verifySelectedItem(); void acceptInput(FormspecQuitMode quitmode); bool preprocessEvent(const SEvent& event); bool OnEvent(const SEvent& event); bool doPause; bool pausesGame() { return doPause; } GUITable* getTable(const std::string &tablename); std::vector<std::string>* getDropDownValues(const std::string &name); #ifdef __ANDROID__ bool getAndroidUIInput(); #endif protected: v2s32 getBasePos() const { return padding + offset + AbsoluteRect.UpperLeftCorner; } std::wstring getLabelByID(s32 id); std::string getNameByID(s32 id); v2s32 getElementBasePos(bool absolute, const std::vector<std::string> *v_pos); v2s32 padding; v2f32 spacing; v2s32 imgsize; v2s32 offset; v2f32 pos_offset; std::stack<v2f32> container_stack; InventoryManager *m_invmgr; ISimpleTextureSource *m_tsrc; Client *m_client; std::string m_formspec_string; std::string m_formspec_prepend; InventoryLocation m_current_inventory_location; std::vector<ListDrawSpec> m_inventorylists; std::vector<ListRingSpec> m_inventory_rings; std::vector<ImageDrawSpec> m_backgrounds; std::vector<ImageDrawSpec> m_images; std::vector<ImageDrawSpec> m_itemimages; std::vector<BoxDrawSpec> m_boxes; std::unordered_map<std::string, bool> field_close_on_enter; std::vector<FieldSpec> m_fields; std::vector<StaticTextSpec> m_static_texts; std::vector<std::pair<FieldSpec,GUITable*> > m_tables; std::vector<std::pair<FieldSpec,gui::IGUICheckBox*> > m_checkboxes; std::map<std::string, TooltipSpec> m_tooltips; std::vector<std::pair<irr::core::rect<s32>, TooltipSpec>> m_tooltip_rects; std::vector<std::pair<FieldSpec,gui::IGUIScrollBar*> > m_scrollbars; std::vector<std::pair<FieldSpec, std::vector<std::string> > > m_dropdowns; ItemSpec *m_selected_item = nullptr; u16 m_selected_amount = 0; bool m_selected_dragging = false; ItemStack m_selected_swap; gui::IGUIStaticText *m_tooltip_element = nullptr; u64 m_tooltip_show_delay; bool m_tooltip_append_itemname; u64 m_hovered_time = 0; s32 m_old_tooltip_id = -1; bool m_auto_place = false; bool m_allowclose = true; bool m_lock = false; v2u32 m_lockscreensize; bool m_bgfullscreen; bool m_slotborder; video::SColor m_bgcolor; video::SColor m_fullscreen_bgcolor; video::SColor m_slotbg_n; video::SColor m_slotbg_h; video::SColor m_slotbordercolor; video::SColor m_default_tooltip_bgcolor; video::SColor m_default_tooltip_color; private: IFormSource *m_form_src; TextDest *m_text_dst; u32 m_formspec_version = 0; std::string m_focused_element = ""; JoystickController *m_joystick; typedef struct { bool explicit_size; v2f invsize; v2s32 size; v2f32 offset; v2f32 anchor; core::rect<s32> rect; v2s32 basepos; v2u32 screensize; std::string focused_fieldname; GUITable::TableOptions table_options; GUITable::TableColumns table_columns; // used to restore table selection/scroll/treeview state std::unordered_map<std::string, GUITable::DynamicData> table_dyndata; } parserData; typedef struct { bool key_up; bool key_down; bool key_enter; bool key_escape; } fs_key_pendig; fs_key_pendig current_keys_pending; std::string current_field_enter_pending = ""; void parseElement(parserData* data, const std::string &element); void parseSize(parserData* data, const std::string &element); void parseContainer(parserData* data, const std::string &element); void parseContainerEnd(parserData* data); void parseList(parserData* data, const std::string &element); void parseListRing(parserData* data, const std::string &element); void parseCheckbox(parserData* data, const std::string &element); void parseImage(parserData* data, const std::string &element); void parseItemImage(parserData* data, const std::string &element); void parseButton(parserData* data, const std::string &element, const std::string &typ); void parseBackground(parserData* data, const std::string &element); void parseTableOptions(parserData* data, const std::string &element); void parseTableColumns(parserData* data, const std::string &element); void parseTable(parserData* data, const std::string &element); void parseTextList(parserData* data, const std::string &element); void parseDropDown(parserData* data, const std::string &element); void parseFieldCloseOnEnter(parserData *data, const std::string &element); void parsePwdField(parserData* data, const std::string &element); void parseField(parserData* data, const std::string &element, const std::string &type); void createTextField(parserData *data, FieldSpec &spec, core::rect<s32> &rect, bool is_multiline); void parseSimpleField(parserData* data,std::vector<std::string> &parts); void parseTextArea(parserData* data,std::vector<std::string>& parts, const std::string &type); void parseLabel(parserData* data, const std::string &element); void parseVertLabel(parserData* data, const std::string &element); void parseImageButton(parserData* data, const std::string &element, const std::string &type); void parseItemImageButton(parserData* data, const std::string &element); void parseTabHeader(parserData* data, const std::string &element); void parseBox(parserData* data, const std::string &element); void parseBackgroundColor(parserData* data, const std::string &element); void parseListColors(parserData* data, const std::string &element); void parseTooltip(parserData* data, const std::string &element); bool parseVersionDirect(const std::string &data); bool parseSizeDirect(parserData* data, const std::string &element); void parseScrollBar(parserData* data, const std::string &element); bool parsePositionDirect(parserData *data, const std::string &element); void parsePosition(parserData *data, const std::string &element); bool parseAnchorDirect(parserData *data, const std::string &element); void parseAnchor(parserData *data, const std::string &element); void tryClose(); void showTooltip(const std::wstring &text, const irr::video::SColor &color, const irr::video::SColor &bgcolor); /** * check if event is part of a double click * @param event event to evaluate * @return true/false if a doubleclick was detected */ bool DoubleClickDetection(const SEvent event); struct clickpos { v2s32 pos; s64 time; }; clickpos m_doubleclickdetect[2]; int m_btn_height; gui::IGUIFont *m_font = nullptr; /* If true, remap a double-click (or double-tap) action to ESC. This is so * that, for example, Android users can double-tap to close a formspec. * * This value can (currently) only be set by the class constructor * and the default value for the setting is true. */ bool m_remap_dbl_click; }; class FormspecFormSource: public IFormSource { public: FormspecFormSource(const std::string &formspec): m_formspec(formspec) { } ~FormspecFormSource() = default; void setForm(const std::string &formspec) { m_formspec = FORMSPEC_VERSION_STRING + formspec; } const std::string &getForm() const { return m_formspec; } std::string m_formspec; };
pgimeno/minetest
src/gui/guiFormSpecMenu.h
C++
mit
14,432
/* Minetest Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com> Copyright (C) 2013 Ciaran Gultnieks <ciaran@ciarang.com> Copyright (C) 2013 teddydestodes <derkomtur@schattengang.net> 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 "guiKeyChangeMenu.h" #include "debug.h" #include "serialization.h" #include <string> #include <IGUICheckBox.h> #include <IGUIEditBox.h> #include <IGUIButton.h> #include <IGUIStaticText.h> #include <IGUIFont.h> #include "settings.h" #include <algorithm> #include "mainmenumanager.h" // for g_gamecallback #define KMaxButtonPerColumns 12 extern MainGameCallback *g_gamecallback; enum { GUI_ID_BACK_BUTTON = 101, GUI_ID_ABORT_BUTTON, GUI_ID_SCROLL_BAR, // buttons GUI_ID_KEY_FORWARD_BUTTON, GUI_ID_KEY_BACKWARD_BUTTON, GUI_ID_KEY_LEFT_BUTTON, GUI_ID_KEY_RIGHT_BUTTON, GUI_ID_KEY_USE_BUTTON, GUI_ID_KEY_FLY_BUTTON, GUI_ID_KEY_FAST_BUTTON, GUI_ID_KEY_JUMP_BUTTON, GUI_ID_KEY_NOCLIP_BUTTON, GUI_ID_KEY_PITCH_MOVE, GUI_ID_KEY_CHAT_BUTTON, GUI_ID_KEY_CMD_BUTTON, GUI_ID_KEY_CMD_LOCAL_BUTTON, GUI_ID_KEY_CONSOLE_BUTTON, GUI_ID_KEY_SNEAK_BUTTON, GUI_ID_KEY_DROP_BUTTON, GUI_ID_KEY_INVENTORY_BUTTON, GUI_ID_KEY_HOTBAR_PREV_BUTTON, GUI_ID_KEY_HOTBAR_NEXT_BUTTON, GUI_ID_KEY_MUTE_BUTTON, GUI_ID_KEY_DEC_VOLUME_BUTTON, GUI_ID_KEY_INC_VOLUME_BUTTON, GUI_ID_KEY_RANGE_BUTTON, GUI_ID_KEY_ZOOM_BUTTON, GUI_ID_KEY_CAMERA_BUTTON, GUI_ID_KEY_MINIMAP_BUTTON, GUI_ID_KEY_SCREENSHOT_BUTTON, GUI_ID_KEY_CHATLOG_BUTTON, GUI_ID_KEY_HUD_BUTTON, GUI_ID_KEY_FOG_BUTTON, GUI_ID_KEY_DEC_RANGE_BUTTON, GUI_ID_KEY_INC_RANGE_BUTTON, GUI_ID_KEY_AUTOFWD_BUTTON, // other GUI_ID_CB_AUX1_DESCENDS, GUI_ID_CB_DOUBLETAP_JUMP, GUI_ID_CB_AUTOJUMP, }; GUIKeyChangeMenu::GUIKeyChangeMenu(gui::IGUIEnvironment* env, gui::IGUIElement* parent, s32 id, IMenuManager *menumgr) : GUIModalMenu(env, parent, id, menumgr) { init_keys(); for (key_setting *ks : key_settings) key_used.push_back(ks->key); } GUIKeyChangeMenu::~GUIKeyChangeMenu() { removeChildren(); for (key_setting *ks : key_settings) { delete[] ks->button_name; delete ks; } key_settings.clear(); } void GUIKeyChangeMenu::removeChildren() { const core::list<gui::IGUIElement*> &children = getChildren(); core::list<gui::IGUIElement*> children_copy; for (gui::IGUIElement*i : children) { children_copy.push_back(i); } for (gui::IGUIElement *i : children_copy) { i->remove(); } } void GUIKeyChangeMenu::regenerateGui(v2u32 screensize) { removeChildren(); const float s = m_gui_scale; DesiredRect = core::rect<s32>( screensize.X / 2 - 835 * s / 2, screensize.Y / 2 - 430 * s / 2, screensize.X / 2 + 835 * s / 2, screensize.Y / 2 + 430 * s / 2 ); recalculateAbsolutePosition(false); v2s32 size = DesiredRect.getSize(); v2s32 topleft(0, 0); { core::rect<s32> rect(0, 0, 600 * s, 40 * s); rect += topleft + v2s32(25 * s, 3 * s); //gui::IGUIStaticText *t = const wchar_t *text = wgettext("Keybindings. (If this menu screws up, remove stuff from minetest.conf)"); Environment->addStaticText(text, rect, false, true, this, -1); delete[] text; //t->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_UPPERLEFT); } // Build buttons v2s32 offset(25 * s, 60 * s); for(size_t i = 0; i < key_settings.size(); i++) { key_setting *k = key_settings.at(i); { core::rect<s32> rect(0, 0, 150 * s, 20 * s); rect += topleft + v2s32(offset.X, offset.Y); Environment->addStaticText(k->button_name, rect, false, true, this, -1); } { core::rect<s32> rect(0, 0, 100 * s, 30 * s); rect += topleft + v2s32(offset.X + 150 * s, offset.Y - 5 * s); const wchar_t *text = wgettext(k->key.name()); k->button = Environment->addButton(rect, this, k->id, text); delete[] text; } if ((i + 1) % KMaxButtonPerColumns == 0) { offset.X += 260 * s; offset.Y = 60 * s; } else { offset += v2s32(0, 25 * s); } } { s32 option_x = offset.X; s32 option_y = offset.Y + 5 * s; u32 option_w = 180 * s; { core::rect<s32> rect(0, 0, option_w, 30 * s); rect += topleft + v2s32(option_x, option_y); const wchar_t *text = wgettext("\"Special\" = climb down"); Environment->addCheckBox(g_settings->getBool("aux1_descends"), rect, this, GUI_ID_CB_AUX1_DESCENDS, text); delete[] text; } offset += v2s32(0, 25 * s); } { s32 option_x = offset.X; s32 option_y = offset.Y + 5 * s; u32 option_w = 280 * s; { core::rect<s32> rect(0, 0, option_w, 30 * s); rect += topleft + v2s32(option_x, option_y); const wchar_t *text = wgettext("Double tap \"jump\" to toggle fly"); Environment->addCheckBox(g_settings->getBool("doubletap_jump"), rect, this, GUI_ID_CB_DOUBLETAP_JUMP, text); delete[] text; } offset += v2s32(0, 25 * s); } { s32 option_x = offset.X; s32 option_y = offset.Y + 5 * s; u32 option_w = 280; { core::rect<s32> rect(0, 0, option_w, 30 * s); rect += topleft + v2s32(option_x, option_y); const wchar_t *text = wgettext("Automatic jumping"); Environment->addCheckBox(g_settings->getBool("autojump"), rect, this, GUI_ID_CB_AUTOJUMP, text); delete[] text; } offset += v2s32(0, 25); } { core::rect<s32> rect(0, 0, 100 * s, 30 * s); rect += topleft + v2s32(size.X / 2 - 105 * s, size.Y - 40 * s); const wchar_t *text = wgettext("Save"); Environment->addButton(rect, this, GUI_ID_BACK_BUTTON, text); delete[] text; } { core::rect<s32> rect(0, 0, 100 * s, 30 * s); rect += topleft + v2s32(size.X / 2 + 5 * s, size.Y - 40 * s); const wchar_t *text = wgettext("Cancel"); Environment->addButton(rect, this, GUI_ID_ABORT_BUTTON, text); delete[] text; } } void GUIKeyChangeMenu::drawMenu() { gui::IGUISkin* skin = Environment->getSkin(); if (!skin) return; video::IVideoDriver* driver = Environment->getVideoDriver(); video::SColor bgcolor(140, 0, 0, 0); driver->draw2DRectangle(bgcolor, AbsoluteRect, &AbsoluteClippingRect); gui::IGUIElement::draw(); } bool GUIKeyChangeMenu::acceptInput() { for (key_setting *k : key_settings) { g_settings->set(k->setting_name, k->key.sym()); } { gui::IGUIElement *e = getElementFromId(GUI_ID_CB_AUX1_DESCENDS); if(e && e->getType() == gui::EGUIET_CHECK_BOX) g_settings->setBool("aux1_descends", ((gui::IGUICheckBox*)e)->isChecked()); } { gui::IGUIElement *e = getElementFromId(GUI_ID_CB_DOUBLETAP_JUMP); if(e && e->getType() == gui::EGUIET_CHECK_BOX) g_settings->setBool("doubletap_jump", ((gui::IGUICheckBox*)e)->isChecked()); } { gui::IGUIElement *e = getElementFromId(GUI_ID_CB_AUTOJUMP); if(e && e->getType() == gui::EGUIET_CHECK_BOX) g_settings->setBool("autojump", ((gui::IGUICheckBox*)e)->isChecked()); } clearKeyCache(); g_gamecallback->signalKeyConfigChange(); return true; } bool GUIKeyChangeMenu::resetMenu() { if (activeKey >= 0) { for (key_setting *k : key_settings) { if (k->id == activeKey) { const wchar_t *text = wgettext(k->key.name()); k->button->setText(text); delete[] text; break; } } activeKey = -1; return false; } return true; } bool GUIKeyChangeMenu::OnEvent(const SEvent& event) { if (event.EventType == EET_KEY_INPUT_EVENT && activeKey >= 0 && event.KeyInput.PressedDown) { bool prefer_character = shift_down; KeyPress kp(event.KeyInput, prefer_character); bool shift_went_down = false; if(!shift_down && (event.KeyInput.Key == irr::KEY_SHIFT || event.KeyInput.Key == irr::KEY_LSHIFT || event.KeyInput.Key == irr::KEY_RSHIFT)) shift_went_down = true; // Remove Key already in use message if(this->key_used_text) { this->key_used_text->remove(); this->key_used_text = NULL; } // Display Key already in use message if (std::find(this->key_used.begin(), this->key_used.end(), kp) != this->key_used.end()) { core::rect < s32 > rect(0, 0, 600, 40); rect += v2s32(0, 0) + v2s32(25, 30); const wchar_t *text = wgettext("Key already in use"); this->key_used_text = Environment->addStaticText(text, rect, false, true, this, -1); delete[] text; //infostream << "Key already in use" << std::endl; } // But go on { key_setting *k = NULL; for (key_setting *ks : key_settings) { if (ks->id == activeKey) { k = ks; break; } } FATAL_ERROR_IF(k == NULL, "Key setting not found"); k->key = kp; const wchar_t *text = wgettext(k->key.name()); k->button->setText(text); delete[] text; this->key_used.push_back(kp); // Allow characters made with shift if(shift_went_down){ shift_down = true; return false; } activeKey = -1; return true; } } else if (event.EventType == EET_KEY_INPUT_EVENT && activeKey < 0 && event.KeyInput.PressedDown && event.KeyInput.Key == irr::KEY_ESCAPE) { quitMenu(); return true; } else if (event.EventType == EET_GUI_EVENT) { if (event.GUIEvent.EventType == gui::EGET_ELEMENT_FOCUS_LOST && isVisible()) { if (!canTakeFocus(event.GUIEvent.Element)) { dstream << "GUIMainMenu: Not allowing focus change." << std::endl; // Returning true disables focus change return true; } } if (event.GUIEvent.EventType == gui::EGET_BUTTON_CLICKED) { switch (event.GUIEvent.Caller->getID()) { case GUI_ID_BACK_BUTTON: //back acceptInput(); quitMenu(); return true; case GUI_ID_ABORT_BUTTON: //abort quitMenu(); return true; default: key_setting *k = NULL; for (key_setting *ks : key_settings) { if (ks->id == event.GUIEvent.Caller->getID()) { k = ks; break; } } FATAL_ERROR_IF(k == NULL, "Key setting not found"); resetMenu(); shift_down = false; activeKey = event.GUIEvent.Caller->getID(); const wchar_t *text = wgettext("press key"); k->button->setText(text); delete[] text; this->key_used.erase(std::remove(this->key_used.begin(), this->key_used.end(), k->key), this->key_used.end()); break; } Environment->setFocus(this); } } return Parent ? Parent->OnEvent(event) : false; } void GUIKeyChangeMenu::add_key(int id, const wchar_t *button_name, const std::string &setting_name) { key_setting *k = new key_setting; k->id = id; k->button_name = button_name; k->setting_name = setting_name; k->key = getKeySetting(k->setting_name.c_str()); key_settings.push_back(k); } void GUIKeyChangeMenu::init_keys() { this->add_key(GUI_ID_KEY_FORWARD_BUTTON, wgettext("Forward"), "keymap_forward"); this->add_key(GUI_ID_KEY_BACKWARD_BUTTON, wgettext("Backward"), "keymap_backward"); this->add_key(GUI_ID_KEY_LEFT_BUTTON, wgettext("Left"), "keymap_left"); this->add_key(GUI_ID_KEY_RIGHT_BUTTON, wgettext("Right"), "keymap_right"); this->add_key(GUI_ID_KEY_USE_BUTTON, wgettext("Special"), "keymap_special1"); this->add_key(GUI_ID_KEY_JUMP_BUTTON, wgettext("Jump"), "keymap_jump"); this->add_key(GUI_ID_KEY_SNEAK_BUTTON, wgettext("Sneak"), "keymap_sneak"); this->add_key(GUI_ID_KEY_DROP_BUTTON, wgettext("Drop"), "keymap_drop"); this->add_key(GUI_ID_KEY_INVENTORY_BUTTON, wgettext("Inventory"), "keymap_inventory"); this->add_key(GUI_ID_KEY_HOTBAR_PREV_BUTTON,wgettext("Prev. item"), "keymap_hotbar_previous"); this->add_key(GUI_ID_KEY_HOTBAR_NEXT_BUTTON,wgettext("Next item"), "keymap_hotbar_next"); this->add_key(GUI_ID_KEY_ZOOM_BUTTON, wgettext("Zoom"), "keymap_zoom"); this->add_key(GUI_ID_KEY_CAMERA_BUTTON, wgettext("Change camera"), "keymap_camera_mode"); this->add_key(GUI_ID_KEY_MINIMAP_BUTTON, wgettext("Toggle minimap"), "keymap_minimap"); this->add_key(GUI_ID_KEY_FLY_BUTTON, wgettext("Toggle fly"), "keymap_freemove"); this->add_key(GUI_ID_KEY_PITCH_MOVE, wgettext("Toggle pitchmove"), "keymap_pitchmove"); this->add_key(GUI_ID_KEY_FAST_BUTTON, wgettext("Toggle fast"), "keymap_fastmove"); this->add_key(GUI_ID_KEY_NOCLIP_BUTTON, wgettext("Toggle noclip"), "keymap_noclip"); this->add_key(GUI_ID_KEY_MUTE_BUTTON, wgettext("Mute"), "keymap_mute"); this->add_key(GUI_ID_KEY_DEC_VOLUME_BUTTON,wgettext("Dec. volume"), "keymap_decrease_volume"); this->add_key(GUI_ID_KEY_INC_VOLUME_BUTTON,wgettext("Inc. volume"), "keymap_increase_volume"); this->add_key(GUI_ID_KEY_AUTOFWD_BUTTON, wgettext("Autoforward"), "keymap_autoforward"); this->add_key(GUI_ID_KEY_CHAT_BUTTON, wgettext("Chat"), "keymap_chat"); this->add_key(GUI_ID_KEY_SCREENSHOT_BUTTON,wgettext("Screenshot"), "keymap_screenshot"); this->add_key(GUI_ID_KEY_RANGE_BUTTON, wgettext("Range select"), "keymap_rangeselect"); this->add_key(GUI_ID_KEY_DEC_RANGE_BUTTON, wgettext("Dec. range"), "keymap_decrease_viewing_range_min"); this->add_key(GUI_ID_KEY_INC_RANGE_BUTTON, wgettext("Inc. range"), "keymap_increase_viewing_range_min"); this->add_key(GUI_ID_KEY_CONSOLE_BUTTON, wgettext("Console"), "keymap_console"); this->add_key(GUI_ID_KEY_CMD_BUTTON, wgettext("Command"), "keymap_cmd"); this->add_key(GUI_ID_KEY_CMD_LOCAL_BUTTON, wgettext("Local command"), "keymap_cmd_local"); this->add_key(GUI_ID_KEY_HUD_BUTTON, wgettext("Toggle HUD"), "keymap_toggle_hud"); this->add_key(GUI_ID_KEY_CHATLOG_BUTTON, wgettext("Toggle chat log"), "keymap_toggle_chat"); this->add_key(GUI_ID_KEY_FOG_BUTTON, wgettext("Toggle fog"), "keymap_toggle_fog"); }
pgimeno/minetest
src/gui/guiKeyChangeMenu.cpp
C++
mit
14,238
/* Minetest Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com> Copyright (C) 2013 Ciaran Gultnieks <ciaran@ciarang.com> Copyright (C) 2013 teddydestodes <derkomtur@schattengang.net> 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. */ #pragma once #include "irrlichttypes_extrabloated.h" #include "modalMenu.h" #include "gettext.h" #include "client/keycode.h" #include <string> #include <vector> struct key_setting { int id; const wchar_t *button_name; KeyPress key; std::string setting_name; gui::IGUIButton *button; }; class GUIKeyChangeMenu : public GUIModalMenu { public: GUIKeyChangeMenu(gui::IGUIEnvironment *env, gui::IGUIElement *parent, s32 id, IMenuManager *menumgr); ~GUIKeyChangeMenu(); void removeChildren(); /* Remove and re-add (or reposition) stuff */ void regenerateGui(v2u32 screensize); void drawMenu(); bool acceptInput(); bool OnEvent(const SEvent &event); bool pausesGame() { return true; } protected: std::wstring getLabelByID(s32 id) { return L""; } std::string getNameByID(s32 id) { return ""; } private: void init_keys(); bool resetMenu(); void add_key(int id, const wchar_t *button_name, const std::string &setting_name); bool shift_down = false; s32 activeKey = -1; std::vector<KeyPress> key_used; gui::IGUIStaticText *key_used_text = nullptr; std::vector<key_setting *> key_settings; };
pgimeno/minetest
src/gui/guiKeyChangeMenu.h
C++
mit
2,051
/* Minetest Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com> 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. */ #pragma once #include "irrlichttypes_extrabloated.h" #include "modalMenu.h" #include <string> #include <list> struct MainMenuDataForScript { MainMenuDataForScript() = default; // Whether the server has requested a reconnect bool reconnect_requested = false; std::string errormessage = ""; }; struct MainMenuData { // Client options std::string servername; std::string serverdescription; std::string address; std::string port; std::string name; std::string password; // Whether to reconnect bool do_reconnect = false; // Server options int selected_world = 0; bool simple_singleplayer_mode = false; // Data to be passed to the script MainMenuDataForScript script_data; MainMenuData() = default; };
pgimeno/minetest
src/gui/guiMainMenu.h
C++
mit
1,514
/* Part of Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> Copyright (C) 2013 Ciaran Gultnieks <ciaran@ciarang.com> Permission to use, copy, modify, and distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "guiPasswordChange.h" #include "client/client.h" #include <IGUICheckBox.h> #include <IGUIEditBox.h> #include <IGUIButton.h> #include <IGUIStaticText.h> #include <IGUIFont.h> #include "porting.h" #include "gettext.h" const int ID_oldPassword = 256; const int ID_newPassword1 = 257; const int ID_newPassword2 = 258; const int ID_change = 259; const int ID_message = 260; const int ID_cancel = 261; GUIPasswordChange::GUIPasswordChange(gui::IGUIEnvironment* env, gui::IGUIElement* parent, s32 id, IMenuManager *menumgr, Client* client ): GUIModalMenu(env, parent, id, menumgr), m_client(client) { } GUIPasswordChange::~GUIPasswordChange() { removeChildren(); } void GUIPasswordChange::removeChildren() { const core::list<gui::IGUIElement *> &children = getChildren(); core::list<gui::IGUIElement *> children_copy; for (gui::IGUIElement *i : children) { children_copy.push_back(i); } for (gui::IGUIElement *i : children_copy) { i->remove(); } } void GUIPasswordChange::regenerateGui(v2u32 screensize) { /* save current input */ acceptInput(); /* Remove stuff */ removeChildren(); /* Calculate new sizes and positions */ const float s = m_gui_scale; DesiredRect = core::rect<s32>( screensize.X / 2 - 580 * s / 2, screensize.Y / 2 - 300 * s / 2, screensize.X / 2 + 580 * s / 2, screensize.Y / 2 + 300 * s / 2 ); recalculateAbsolutePosition(false); v2s32 size = DesiredRect.getSize(); v2s32 topleft_client(40 * s, 0); const wchar_t *text; /* Add stuff */ s32 ypos = 50 * s; { core::rect<s32> rect(0, 0, 150 * s, 20 * s); rect += topleft_client + v2s32(25 * s, ypos + 6 * s); text = wgettext("Old Password"); Environment->addStaticText(text, rect, false, true, this, -1); delete[] text; } { core::rect<s32> rect(0, 0, 230 * s, 30 * s); rect += topleft_client + v2s32(160 * s, ypos); gui::IGUIEditBox *e = Environment->addEditBox( m_oldpass.c_str(), rect, true, this, ID_oldPassword); Environment->setFocus(e); e->setPasswordBox(true); } ypos += 50 * s; { core::rect<s32> rect(0, 0, 150 * s, 20 * s); rect += topleft_client + v2s32(25 * s, ypos + 6 * s); text = wgettext("New Password"); Environment->addStaticText(text, rect, false, true, this, -1); delete[] text; } { core::rect<s32> rect(0, 0, 230 * s, 30 * s); rect += topleft_client + v2s32(160 * s, ypos); gui::IGUIEditBox *e = Environment->addEditBox( m_newpass.c_str(), rect, true, this, ID_newPassword1); e->setPasswordBox(true); } ypos += 50 * s; { core::rect<s32> rect(0, 0, 150 * s, 20 * s); rect += topleft_client + v2s32(25 * s, ypos + 6 * s); text = wgettext("Confirm Password"); Environment->addStaticText(text, rect, false, true, this, -1); delete[] text; } { core::rect<s32> rect(0, 0, 230 * s, 30 * s); rect += topleft_client + v2s32(160 * s, ypos); gui::IGUIEditBox *e = Environment->addEditBox( m_newpass_confirm.c_str(), rect, true, this, ID_newPassword2); e->setPasswordBox(true); } ypos += 50 * s; { core::rect<s32> rect(0, 0, 100 * s, 30 * s); rect = rect + v2s32(size.X / 4 + 56 * s, ypos); text = wgettext("Change"); Environment->addButton(rect, this, ID_change, text); delete[] text; } { core::rect<s32> rect(0, 0, 100 * s, 30 * s); rect = rect + v2s32(size.X / 4 + 185 * s, ypos); text = wgettext("Cancel"); Environment->addButton(rect, this, ID_cancel, text); delete[] text; } ypos += 50 * s; { core::rect<s32> rect(0, 0, 300 * s, 20 * s); rect += topleft_client + v2s32(35 * s, ypos); text = wgettext("Passwords do not match!"); IGUIElement *e = Environment->addStaticText( text, rect, false, true, this, ID_message); e->setVisible(false); delete[] text; } } void GUIPasswordChange::drawMenu() { gui::IGUISkin *skin = Environment->getSkin(); if (!skin) return; video::IVideoDriver *driver = Environment->getVideoDriver(); video::SColor bgcolor(140, 0, 0, 0); driver->draw2DRectangle(bgcolor, AbsoluteRect, &AbsoluteClippingRect); gui::IGUIElement::draw(); #ifdef __ANDROID__ getAndroidUIInput(); #endif } void GUIPasswordChange::acceptInput() { gui::IGUIElement *e; e = getElementFromId(ID_oldPassword); if (e != NULL) m_oldpass = e->getText(); e = getElementFromId(ID_newPassword1); if (e != NULL) m_newpass = e->getText(); e = getElementFromId(ID_newPassword2); if (e != NULL) m_newpass_confirm = e->getText(); } bool GUIPasswordChange::processInput() { if (m_newpass != m_newpass_confirm) { gui::IGUIElement *e = getElementFromId(ID_message); if (e != NULL) e->setVisible(true); return false; } m_client->sendChangePassword(wide_to_utf8(m_oldpass), wide_to_utf8(m_newpass)); return true; } bool GUIPasswordChange::OnEvent(const SEvent &event) { if (event.EventType == EET_KEY_INPUT_EVENT) { // clang-format off if ((event.KeyInput.Key == KEY_ESCAPE || event.KeyInput.Key == KEY_CANCEL) && event.KeyInput.PressedDown) { quitMenu(); return true; } // clang-format on if (event.KeyInput.Key == KEY_RETURN && event.KeyInput.PressedDown) { acceptInput(); if (processInput()) quitMenu(); return true; } } if (event.EventType == EET_GUI_EVENT) { if (event.GUIEvent.EventType == gui::EGET_ELEMENT_FOCUS_LOST && isVisible()) { if (!canTakeFocus(event.GUIEvent.Element)) { dstream << "GUIPasswordChange: Not allowing focus change." << std::endl; // Returning true disables focus change return true; } } if (event.GUIEvent.EventType == gui::EGET_BUTTON_CLICKED) { switch (event.GUIEvent.Caller->getID()) { case ID_change: acceptInput(); if (processInput()) quitMenu(); return true; case ID_cancel: quitMenu(); return true; } } if (event.GUIEvent.EventType == gui::EGET_EDITBOX_ENTER) { switch (event.GUIEvent.Caller->getID()) { case ID_oldPassword: case ID_newPassword1: case ID_newPassword2: acceptInput(); if (processInput()) quitMenu(); return true; } } } return Parent ? Parent->OnEvent(event) : false; } std::string GUIPasswordChange::getNameByID(s32 id) { switch (id) { case ID_oldPassword: return "old_password"; case ID_newPassword1: return "new_password_1"; case ID_newPassword2: return "new_password_2"; } return ""; } #ifdef __ANDROID__ bool GUIPasswordChange::getAndroidUIInput() { if (!hasAndroidUIInput()) return false; gui::IGUIElement *e = nullptr; if (m_jni_field_name == "old_password") e = getElementFromId(ID_oldPassword); else if (m_jni_field_name == "new_password_1") e = getElementFromId(ID_newPassword1); else if (m_jni_field_name == "new_password_2") e = getElementFromId(ID_newPassword2); if (e) { std::string text = porting::getInputDialogValue(); e->setText(utf8_to_wide(text).c_str()); } m_jni_field_name.clear(); return false; } #endif
pgimeno/minetest
src/gui/guiPasswordChange.cpp
C++
mit
7,705
/* Part of Minetest Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com> Copyright (C) 2013 Ciaran Gultnieks <ciaran@ciarang.com> Permission to use, copy, modify, and distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #pragma once #include "irrlichttypes_extrabloated.h" #include "modalMenu.h" #include <string> class Client; class GUIPasswordChange : public GUIModalMenu { public: GUIPasswordChange(gui::IGUIEnvironment *env, gui::IGUIElement *parent, s32 id, IMenuManager *menumgr, Client *client); ~GUIPasswordChange(); void removeChildren(); /* Remove and re-add (or reposition) stuff */ void regenerateGui(v2u32 screensize); void drawMenu(); void acceptInput(); bool processInput(); bool OnEvent(const SEvent &event); #ifdef __ANDROID__ bool getAndroidUIInput(); #endif protected: std::wstring getLabelByID(s32 id) { return L""; } std::string getNameByID(s32 id); private: Client *m_client; std::wstring m_oldpass = L""; std::wstring m_newpass = L""; std::wstring m_newpass_confirm = L""; };
pgimeno/minetest
src/gui/guiPasswordChange.h
C++
mit
1,657
/* Minetest Copyright (C) 2013 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 "guiPathSelectMenu.h" GUIFileSelectMenu::GUIFileSelectMenu(gui::IGUIEnvironment* env, gui::IGUIElement* parent, s32 id, IMenuManager *menumgr, const std::string &title, const std::string &formname, bool is_file_select) : GUIModalMenu(env, parent, id, menumgr), m_title(utf8_to_wide(title)), m_formname(formname), m_file_select_dialog(is_file_select) { } GUIFileSelectMenu::~GUIFileSelectMenu() { removeChildren(); setlocale(LC_NUMERIC, "C"); } void GUIFileSelectMenu::regenerateGui(v2u32 screensize) { removeChildren(); m_fileOpenDialog = 0; core::dimension2du size(600 * m_gui_scale, 400 * m_gui_scale); core::rect<s32> rect(0, 0, screensize.X, screensize.Y); DesiredRect = rect; recalculateAbsolutePosition(false); m_fileOpenDialog = Environment->addFileOpenDialog(m_title.c_str(), false, this, -1); core::position2di pos = core::position2di(screensize.X / 2 - size.Width / 2, screensize.Y / 2 - size.Height / 2); m_fileOpenDialog->setRelativePosition(pos); m_fileOpenDialog->setMinSize(size); } void GUIFileSelectMenu::drawMenu() { gui::IGUISkin *skin = Environment->getSkin(); if (!skin) return; gui::IGUIElement::draw(); } void GUIFileSelectMenu::acceptInput() { if (m_text_dst && !m_formname.empty()) { StringMap fields; if (m_accepted) { std::string path; if (!m_file_select_dialog) { core::string<fschar_t> string = m_fileOpenDialog->getDirectoryName(); path = std::string(string.c_str()); } else { path = wide_to_utf8(m_fileOpenDialog->getFileName()); } fields[m_formname + "_accepted"] = path; } else { fields[m_formname + "_canceled"] = m_formname; } m_text_dst->gotText(fields); } quitMenu(); } bool GUIFileSelectMenu::OnEvent(const SEvent &event) { if (event.EventType == irr::EET_GUI_EVENT) { switch (event.GUIEvent.EventType) { case gui::EGET_ELEMENT_CLOSED: case gui::EGET_FILE_CHOOSE_DIALOG_CANCELLED: m_accepted = false; acceptInput(); return true; case gui::EGET_DIRECTORY_SELECTED: m_accepted = !m_file_select_dialog; acceptInput(); return true; case gui::EGET_FILE_SELECTED: m_accepted = m_file_select_dialog; acceptInput(); return true; default: // ignore this event break; } } return Parent ? Parent->OnEvent(event) : false; }
pgimeno/minetest
src/gui/guiPathSelectMenu.cpp
C++
mit
3,062
/* Minetest Copyright (C) 2013 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. */ #pragma once #include <string> #include "modalMenu.h" #include "IGUIFileOpenDialog.h" #include "guiFormSpecMenu.h" //required because of TextDest only !!! class GUIFileSelectMenu : public GUIModalMenu { public: GUIFileSelectMenu(gui::IGUIEnvironment *env, gui::IGUIElement *parent, s32 id, IMenuManager *menumgr, const std::string &title, const std::string &formid, bool is_file_select); ~GUIFileSelectMenu(); /* Remove and re-add (or reposition) stuff */ void regenerateGui(v2u32 screensize); void drawMenu(); bool OnEvent(const SEvent &event); void setTextDest(TextDest *dest) { m_text_dst = dest; } protected: std::wstring getLabelByID(s32 id) { return L""; } std::string getNameByID(s32 id) { return ""; } private: void acceptInput(); std::wstring m_title; bool m_accepted = false; gui::IGUIFileOpenDialog *m_fileOpenDialog = nullptr; TextDest *m_text_dst = nullptr; std::string m_formname; bool m_file_select_dialog; };
pgimeno/minetest
src/gui/guiPathSelectMenu.h
C++
mit
1,724
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> 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 "guiTable.h" #include <queue> #include <sstream> #include <utility> #include <cstring> #include <IGUISkin.h> #include <IGUIFont.h> #include <IGUIScrollBar.h> #include "client/renderingengine.h" #include "debug.h" #include "log.h" #include "client/tile.h" #include "gettime.h" #include "util/string.h" #include "util/numeric.h" #include "util/string.h" // for parseColorString() #include "settings.h" // for settings #include "porting.h" // for dpi #include "client/guiscalingfilter.h" /* GUITable */ GUITable::GUITable(gui::IGUIEnvironment *env, gui::IGUIElement* parent, s32 id, core::rect<s32> rectangle, ISimpleTextureSource *tsrc ): gui::IGUIElement(gui::EGUIET_ELEMENT, env, parent, id, rectangle), m_tsrc(tsrc) { assert(tsrc != NULL); gui::IGUISkin* skin = Environment->getSkin(); m_font = skin->getFont(); if (m_font) { m_font->grab(); m_rowheight = m_font->getDimension(L"A").Height + 4; m_rowheight = MYMAX(m_rowheight, 1); } const s32 s = skin->getSize(gui::EGDS_SCROLLBAR_SIZE); m_scrollbar = Environment->addScrollBar(false, core::rect<s32>(RelativeRect.getWidth() - s, 0, RelativeRect.getWidth(), RelativeRect.getHeight()), this, -1); m_scrollbar->setSubElement(true); m_scrollbar->setTabStop(false); m_scrollbar->setAlignment(gui::EGUIA_LOWERRIGHT, gui::EGUIA_LOWERRIGHT, gui::EGUIA_UPPERLEFT, gui::EGUIA_LOWERRIGHT); m_scrollbar->setVisible(false); m_scrollbar->setPos(0); setTabStop(true); setTabOrder(-1); updateAbsolutePosition(); float density = RenderingEngine::getDisplayDensity(); #ifdef __ANDROID__ density = 1; // dp scaling is applied by the skin #endif core::rect<s32> relative_rect = m_scrollbar->getRelativePosition(); s32 width = (relative_rect.getWidth() / (2.0 / 3.0)) * density * g_settings->getFloat("gui_scaling"); m_scrollbar->setRelativePosition(core::rect<s32>( relative_rect.LowerRightCorner.X-width,relative_rect.UpperLeftCorner.Y, relative_rect.LowerRightCorner.X,relative_rect.LowerRightCorner.Y )); } GUITable::~GUITable() { for (GUITable::Row &row : m_rows) delete[] row.cells; if (m_font) m_font->drop(); m_scrollbar->remove(); } GUITable::Option GUITable::splitOption(const std::string &str) { size_t equal_pos = str.find('='); if (equal_pos == std::string::npos) return GUITable::Option(str, ""); return GUITable::Option(str.substr(0, equal_pos), str.substr(equal_pos + 1)); } void GUITable::setTextList(const std::vector<std::string> &content, bool transparent) { clear(); if (transparent) { m_background.setAlpha(0); m_border = false; } m_is_textlist = true; s32 empty_string_index = allocString(""); m_rows.resize(content.size()); for (s32 i = 0; i < (s32) content.size(); ++i) { Row *row = &m_rows[i]; row->cells = new Cell[1]; row->cellcount = 1; row->indent = 0; row->visible_index = i; m_visible_rows.push_back(i); Cell *cell = row->cells; cell->xmin = 0; cell->xmax = 0x7fff; // something large enough cell->xpos = 6; cell->content_type = COLUMN_TYPE_TEXT; cell->content_index = empty_string_index; cell->tooltip_index = empty_string_index; cell->color.set(255, 255, 255, 255); cell->color_defined = false; cell->reported_column = 1; // parse row content (color) const std::string &s = content[i]; if (s[0] == '#' && s[1] == '#') { // double # to escape cell->content_index = allocString(s.substr(2)); } else if (s[0] == '#' && s.size() >= 7 && parseColorString( s.substr(0,7), cell->color, false)) { // single # for color cell->color_defined = true; cell->content_index = allocString(s.substr(7)); } else { // no #, just text cell->content_index = allocString(s); } } allocationComplete(); // Clamp scroll bar position updateScrollBar(); } void GUITable::setTable(const TableOptions &options, const TableColumns &columns, std::vector<std::string> &content) { clear(); // Naming conventions: // i is always a row index, 0-based // j is always a column index, 0-based // k is another index, for example an option index // Handle a stupid error case... (issue #1187) if (columns.empty()) { TableColumn text_column; text_column.type = "text"; TableColumns new_columns; new_columns.push_back(text_column); setTable(options, new_columns, content); return; } // Handle table options video::SColor default_color(255, 255, 255, 255); s32 opendepth = 0; for (const Option &option : options) { const std::string &name = option.name; const std::string &value = option.value; if (name == "color") parseColorString(value, m_color, false); else if (name == "background") parseColorString(value, m_background, false); else if (name == "border") m_border = is_yes(value); else if (name == "highlight") parseColorString(value, m_highlight, false); else if (name == "highlight_text") parseColorString(value, m_highlight_text, false); else if (name == "opendepth") opendepth = stoi(value); else errorstream<<"Invalid table option: \""<<name<<"\"" <<" (value=\""<<value<<"\")"<<std::endl; } // Get number of columns and rows // note: error case columns.size() == 0 was handled above s32 colcount = columns.size(); assert(colcount >= 1); // rowcount = ceil(cellcount / colcount) but use integer arithmetic s32 rowcount = (content.size() + colcount - 1) / colcount; assert(rowcount >= 0); // Append empty strings to content if there is an incomplete row s32 cellcount = rowcount * colcount; while (content.size() < (u32) cellcount) content.emplace_back(""); // Create temporary rows (for processing columns) struct TempRow { // Current horizontal position (may different between rows due // to indent/tree columns, or text/image columns with width<0) s32 x; // Tree indentation level s32 indent; // Next cell: Index into m_strings or m_images s32 content_index; // Next cell: Width in pixels s32 content_width; // Vector of completed cells in this row std::vector<Cell> cells; // Stores colors and how long they last (maximum column index) std::vector<std::pair<video::SColor, s32> > colors; TempRow(): x(0), indent(0), content_index(0), content_width(0) {} }; TempRow *rows = new TempRow[rowcount]; // Get em width. Pedantically speaking, the width of "M" is not // necessarily the same as the em width, but whatever, close enough. s32 em = 6; if (m_font) em = m_font->getDimension(L"M").Width; s32 default_tooltip_index = allocString(""); std::map<s32, s32> active_image_indices; // Process content in column-major order for (s32 j = 0; j < colcount; ++j) { // Check column type ColumnType columntype = COLUMN_TYPE_TEXT; if (columns[j].type == "text") columntype = COLUMN_TYPE_TEXT; else if (columns[j].type == "image") columntype = COLUMN_TYPE_IMAGE; else if (columns[j].type == "color") columntype = COLUMN_TYPE_COLOR; else if (columns[j].type == "indent") columntype = COLUMN_TYPE_INDENT; else if (columns[j].type == "tree") columntype = COLUMN_TYPE_TREE; else errorstream<<"Invalid table column type: \"" <<columns[j].type<<"\""<<std::endl; // Process column options s32 padding = myround(0.5 * em); s32 tooltip_index = default_tooltip_index; s32 align = 0; s32 width = 0; s32 span = colcount; if (columntype == COLUMN_TYPE_INDENT) { padding = 0; // default indent padding } if (columntype == COLUMN_TYPE_INDENT || columntype == COLUMN_TYPE_TREE) { width = myround(em * 1.5); // default indent width } for (const Option &option : columns[j].options) { const std::string &name = option.name; const std::string &value = option.value; if (name == "padding") padding = myround(stof(value) * em); else if (name == "tooltip") tooltip_index = allocString(value); else if (name == "align" && value == "left") align = 0; else if (name == "align" && value == "center") align = 1; else if (name == "align" && value == "right") align = 2; else if (name == "align" && value == "inline") align = 3; else if (name == "width") width = myround(stof(value) * em); else if (name == "span" && columntype == COLUMN_TYPE_COLOR) span = stoi(value); else if (columntype == COLUMN_TYPE_IMAGE && !name.empty() && string_allowed(name, "0123456789")) { s32 content_index = allocImage(value); active_image_indices.insert(std::make_pair( stoi(name), content_index)); } else { errorstream<<"Invalid table column option: \""<<name<<"\"" <<" (value=\""<<value<<"\")"<<std::endl; } } // If current column type can use information from "color" columns, // find out which of those is currently active if (columntype == COLUMN_TYPE_TEXT) { for (s32 i = 0; i < rowcount; ++i) { TempRow *row = &rows[i]; while (!row->colors.empty() && row->colors.back().second < j) row->colors.pop_back(); } } // Make template for new cells Cell newcell; newcell.content_type = columntype; newcell.tooltip_index = tooltip_index; newcell.reported_column = j+1; if (columntype == COLUMN_TYPE_TEXT) { // Find right edge of column s32 xmax = 0; for (s32 i = 0; i < rowcount; ++i) { TempRow *row = &rows[i]; row->content_index = allocString(content[i * colcount + j]); const core::stringw &text = m_strings[row->content_index]; row->content_width = m_font ? m_font->getDimension(text.c_str()).Width : 0; row->content_width = MYMAX(row->content_width, width); s32 row_xmax = row->x + padding + row->content_width; xmax = MYMAX(xmax, row_xmax); } // Add a new cell (of text type) to each row for (s32 i = 0; i < rowcount; ++i) { newcell.xmin = rows[i].x + padding; alignContent(&newcell, xmax, rows[i].content_width, align); newcell.content_index = rows[i].content_index; newcell.color_defined = !rows[i].colors.empty(); if (newcell.color_defined) newcell.color = rows[i].colors.back().first; rows[i].cells.push_back(newcell); rows[i].x = newcell.xmax; } } else if (columntype == COLUMN_TYPE_IMAGE) { // Find right edge of column s32 xmax = 0; for (s32 i = 0; i < rowcount; ++i) { TempRow *row = &rows[i]; row->content_index = -1; // Find content_index. Image indices are defined in // column options so check active_image_indices. s32 image_index = stoi(content[i * colcount + j]); std::map<s32, s32>::iterator image_iter = active_image_indices.find(image_index); if (image_iter != active_image_indices.end()) row->content_index = image_iter->second; // Get texture object (might be NULL) video::ITexture *image = NULL; if (row->content_index >= 0) image = m_images[row->content_index]; // Get content width and update xmax row->content_width = image ? image->getOriginalSize().Width : 0; row->content_width = MYMAX(row->content_width, width); s32 row_xmax = row->x + padding + row->content_width; xmax = MYMAX(xmax, row_xmax); } // Add a new cell (of image type) to each row for (s32 i = 0; i < rowcount; ++i) { newcell.xmin = rows[i].x + padding; alignContent(&newcell, xmax, rows[i].content_width, align); newcell.content_index = rows[i].content_index; rows[i].cells.push_back(newcell); rows[i].x = newcell.xmax; } active_image_indices.clear(); } else if (columntype == COLUMN_TYPE_COLOR) { for (s32 i = 0; i < rowcount; ++i) { video::SColor cellcolor(255, 255, 255, 255); if (parseColorString(content[i * colcount + j], cellcolor, true)) rows[i].colors.emplace_back(cellcolor, j+span); } } else if (columntype == COLUMN_TYPE_INDENT || columntype == COLUMN_TYPE_TREE) { // For column type "tree", reserve additional space for +/- // Also enable special processing for treeview-type tables s32 content_width = 0; if (columntype == COLUMN_TYPE_TREE) { content_width = m_font ? m_font->getDimension(L"+").Width : 0; m_has_tree_column = true; } // Add a new cell (of indent or tree type) to each row for (s32 i = 0; i < rowcount; ++i) { TempRow *row = &rows[i]; s32 indentlevel = stoi(content[i * colcount + j]); indentlevel = MYMAX(indentlevel, 0); if (columntype == COLUMN_TYPE_TREE) row->indent = indentlevel; newcell.xmin = row->x + padding; newcell.xpos = newcell.xmin + indentlevel * width; newcell.xmax = newcell.xpos + content_width; newcell.content_index = 0; newcell.color_defined = !rows[i].colors.empty(); if (newcell.color_defined) newcell.color = rows[i].colors.back().first; row->cells.push_back(newcell); row->x = newcell.xmax; } } } // Copy temporary rows to not so temporary rows if (rowcount >= 1) { m_rows.resize(rowcount); for (s32 i = 0; i < rowcount; ++i) { Row *row = &m_rows[i]; row->cellcount = rows[i].cells.size(); row->cells = new Cell[row->cellcount]; memcpy((void*) row->cells, (void*) &rows[i].cells[0], row->cellcount * sizeof(Cell)); row->indent = rows[i].indent; row->visible_index = i; m_visible_rows.push_back(i); } } if (m_has_tree_column) { // Treeview: convert tree to indent cells on leaf rows for (s32 i = 0; i < rowcount; ++i) { if (i == rowcount-1 || m_rows[i].indent >= m_rows[i+1].indent) for (s32 j = 0; j < m_rows[i].cellcount; ++j) if (m_rows[i].cells[j].content_type == COLUMN_TYPE_TREE) m_rows[i].cells[j].content_type = COLUMN_TYPE_INDENT; } // Treeview: close rows according to opendepth option std::set<s32> opened_trees; for (s32 i = 0; i < rowcount; ++i) if (m_rows[i].indent < opendepth) opened_trees.insert(i); setOpenedTrees(opened_trees); } // Delete temporary information used only during setTable() delete[] rows; allocationComplete(); // Clamp scroll bar position updateScrollBar(); } void GUITable::clear() { // Clean up cells and rows for (GUITable::Row &row : m_rows) delete[] row.cells; m_rows.clear(); m_visible_rows.clear(); // Get colors from skin gui::IGUISkin *skin = Environment->getSkin(); m_color = skin->getColor(gui::EGDC_BUTTON_TEXT); m_background = skin->getColor(gui::EGDC_3D_HIGH_LIGHT); m_highlight = skin->getColor(gui::EGDC_HIGH_LIGHT); m_highlight_text = skin->getColor(gui::EGDC_HIGH_LIGHT_TEXT); // Reset members m_is_textlist = false; m_has_tree_column = false; m_selected = -1; m_sel_column = 0; m_sel_doubleclick = false; m_keynav_time = 0; m_keynav_buffer = L""; m_border = true; m_strings.clear(); m_images.clear(); m_alloc_strings.clear(); m_alloc_images.clear(); } std::string GUITable::checkEvent() { s32 sel = getSelected(); assert(sel >= 0); if (sel == 0) { return "INV"; } std::ostringstream os(std::ios::binary); if (m_sel_doubleclick) { os<<"DCL:"; m_sel_doubleclick = false; } else { os<<"CHG:"; } os<<sel; if (!m_is_textlist) { os<<":"<<m_sel_column; } return os.str(); } s32 GUITable::getSelected() const { if (m_selected < 0) return 0; assert(m_selected >= 0 && m_selected < (s32) m_visible_rows.size()); return m_visible_rows[m_selected] + 1; } void GUITable::setSelected(s32 index) { s32 old_selected = m_selected; m_selected = -1; m_sel_column = 0; m_sel_doubleclick = false; --index; // Switch from 1-based indexing to 0-based indexing s32 rowcount = m_rows.size(); if (rowcount == 0 || index < 0) { return; } if (index >= rowcount) { index = rowcount - 1; } // If the selected row is not visible, open its ancestors to make it visible bool selection_invisible = m_rows[index].visible_index < 0; if (selection_invisible) { std::set<s32> opened_trees; getOpenedTrees(opened_trees); s32 indent = m_rows[index].indent; for (s32 j = index - 1; j >= 0; --j) { if (m_rows[j].indent < indent) { opened_trees.insert(j); indent = m_rows[j].indent; } } setOpenedTrees(opened_trees); } if (index >= 0) { m_selected = m_rows[index].visible_index; assert(m_selected >= 0 && m_selected < (s32) m_visible_rows.size()); } if (m_selected != old_selected || selection_invisible) { autoScroll(); } } GUITable::DynamicData GUITable::getDynamicData() const { DynamicData dyndata; dyndata.selected = getSelected(); dyndata.scrollpos = m_scrollbar->getPos(); dyndata.keynav_time = m_keynav_time; dyndata.keynav_buffer = m_keynav_buffer; if (m_has_tree_column) getOpenedTrees(dyndata.opened_trees); return dyndata; } void GUITable::setDynamicData(const DynamicData &dyndata) { if (m_has_tree_column) setOpenedTrees(dyndata.opened_trees); m_keynav_time = dyndata.keynav_time; m_keynav_buffer = dyndata.keynav_buffer; setSelected(dyndata.selected); m_sel_column = 0; m_sel_doubleclick = false; m_scrollbar->setPos(dyndata.scrollpos); } const c8* GUITable::getTypeName() const { return "GUITable"; } void GUITable::updateAbsolutePosition() { IGUIElement::updateAbsolutePosition(); updateScrollBar(); } void GUITable::draw() { if (!IsVisible) return; gui::IGUISkin *skin = Environment->getSkin(); // draw background bool draw_background = m_background.getAlpha() > 0; if (m_border) skin->draw3DSunkenPane(this, m_background, true, draw_background, AbsoluteRect, &AbsoluteClippingRect); else if (draw_background) skin->draw2DRectangle(this, m_background, AbsoluteRect, &AbsoluteClippingRect); // get clipping rect core::rect<s32> client_clip(AbsoluteRect); client_clip.UpperLeftCorner.Y += 1; client_clip.UpperLeftCorner.X += 1; client_clip.LowerRightCorner.Y -= 1; client_clip.LowerRightCorner.X -= 1; if (m_scrollbar->isVisible()) { client_clip.LowerRightCorner.X = m_scrollbar->getAbsolutePosition().UpperLeftCorner.X; } client_clip.clipAgainst(AbsoluteClippingRect); // draw visible rows s32 scrollpos = m_scrollbar->getPos(); s32 row_min = scrollpos / m_rowheight; s32 row_max = (scrollpos + AbsoluteRect.getHeight() - 1) / m_rowheight + 1; row_max = MYMIN(row_max, (s32) m_visible_rows.size()); core::rect<s32> row_rect(AbsoluteRect); if (m_scrollbar->isVisible()) row_rect.LowerRightCorner.X -= skin->getSize(gui::EGDS_SCROLLBAR_SIZE); row_rect.UpperLeftCorner.Y += row_min * m_rowheight - scrollpos; row_rect.LowerRightCorner.Y = row_rect.UpperLeftCorner.Y + m_rowheight; for (s32 i = row_min; i < row_max; ++i) { Row *row = &m_rows[m_visible_rows[i]]; bool is_sel = i == m_selected; video::SColor color = m_color; if (is_sel) { skin->draw2DRectangle(this, m_highlight, row_rect, &client_clip); color = m_highlight_text; } for (s32 j = 0; j < row->cellcount; ++j) drawCell(&row->cells[j], color, row_rect, client_clip); row_rect.UpperLeftCorner.Y += m_rowheight; row_rect.LowerRightCorner.Y += m_rowheight; } // Draw children IGUIElement::draw(); } void GUITable::drawCell(const Cell *cell, video::SColor color, const core::rect<s32> &row_rect, const core::rect<s32> &client_clip) { if ((cell->content_type == COLUMN_TYPE_TEXT) || (cell->content_type == COLUMN_TYPE_TREE)) { core::rect<s32> text_rect = row_rect; text_rect.UpperLeftCorner.X = row_rect.UpperLeftCorner.X + cell->xpos; text_rect.LowerRightCorner.X = row_rect.UpperLeftCorner.X + cell->xmax; if (cell->color_defined) color = cell->color; if (m_font) { if (cell->content_type == COLUMN_TYPE_TEXT) m_font->draw(m_strings[cell->content_index], text_rect, color, false, true, &client_clip); else // tree m_font->draw(cell->content_index ? L"+" : L"-", text_rect, color, false, true, &client_clip); } } else if (cell->content_type == COLUMN_TYPE_IMAGE) { if (cell->content_index < 0) return; video::IVideoDriver *driver = Environment->getVideoDriver(); video::ITexture *image = m_images[cell->content_index]; if (image) { core::position2d<s32> dest_pos = row_rect.UpperLeftCorner; dest_pos.X += cell->xpos; core::rect<s32> source_rect( core::position2d<s32>(0, 0), image->getOriginalSize()); s32 imgh = source_rect.LowerRightCorner.Y; s32 rowh = row_rect.getHeight(); if (imgh < rowh) dest_pos.Y += (rowh - imgh) / 2; else source_rect.LowerRightCorner.Y = rowh; video::SColor color(255, 255, 255, 255); driver->draw2DImage(image, dest_pos, source_rect, &client_clip, color, true); } } } bool GUITable::OnEvent(const SEvent &event) { if (!isEnabled()) return IGUIElement::OnEvent(event); if (event.EventType == EET_KEY_INPUT_EVENT) { if (event.KeyInput.PressedDown && ( event.KeyInput.Key == KEY_DOWN || event.KeyInput.Key == KEY_UP || event.KeyInput.Key == KEY_HOME || event.KeyInput.Key == KEY_END || event.KeyInput.Key == KEY_NEXT || event.KeyInput.Key == KEY_PRIOR)) { s32 offset = 0; switch (event.KeyInput.Key) { case KEY_DOWN: offset = 1; break; case KEY_UP: offset = -1; break; case KEY_HOME: offset = - (s32) m_visible_rows.size(); break; case KEY_END: offset = m_visible_rows.size(); break; case KEY_NEXT: offset = AbsoluteRect.getHeight() / m_rowheight; break; case KEY_PRIOR: offset = - (s32) (AbsoluteRect.getHeight() / m_rowheight); break; default: break; } s32 old_selected = m_selected; s32 rowcount = m_visible_rows.size(); if (rowcount != 0) { m_selected = rangelim(m_selected + offset, 0, rowcount-1); autoScroll(); } if (m_selected != old_selected) sendTableEvent(0, false); return true; } if (event.KeyInput.PressedDown && ( event.KeyInput.Key == KEY_LEFT || event.KeyInput.Key == KEY_RIGHT)) { // Open/close subtree via keyboard if (m_selected >= 0) { int dir = event.KeyInput.Key == KEY_LEFT ? -1 : 1; toggleVisibleTree(m_selected, dir, true); } return true; } else if (!event.KeyInput.PressedDown && ( event.KeyInput.Key == KEY_RETURN || event.KeyInput.Key == KEY_SPACE)) { sendTableEvent(0, true); return true; } else if (event.KeyInput.Key == KEY_ESCAPE || event.KeyInput.Key == KEY_SPACE) { // pass to parent } else if (event.KeyInput.PressedDown && event.KeyInput.Char) { // change selection based on text as it is typed u64 now = porting::getTimeMs(); if (now - m_keynav_time >= 500) m_keynav_buffer = L""; m_keynav_time = now; // add to key buffer if not a key repeat if (!(m_keynav_buffer.size() == 1 && m_keynav_buffer[0] == event.KeyInput.Char)) { m_keynav_buffer.append(event.KeyInput.Char); } // find the selected item, starting at the current selection // don't change selection if the key buffer matches the current item s32 old_selected = m_selected; s32 start = MYMAX(m_selected, 0); s32 rowcount = m_visible_rows.size(); for (s32 k = 1; k < rowcount; ++k) { s32 current = start + k; if (current >= rowcount) current -= rowcount; if (doesRowStartWith(getRow(current), m_keynav_buffer)) { m_selected = current; break; } } autoScroll(); if (m_selected != old_selected) sendTableEvent(0, false); return true; } } if (event.EventType == EET_MOUSE_INPUT_EVENT) { core::position2d<s32> p(event.MouseInput.X, event.MouseInput.Y); if (event.MouseInput.Event == EMIE_MOUSE_WHEEL) { m_scrollbar->setPos(m_scrollbar->getPos() + (event.MouseInput.Wheel < 0 ? -3 : 3) * - (s32) m_rowheight / 2); return true; } // Find hovered row and cell bool really_hovering = false; s32 row_i = getRowAt(p.Y, really_hovering); const Cell *cell = NULL; if (really_hovering) { s32 cell_j = getCellAt(p.X, row_i); if (cell_j >= 0) cell = &(getRow(row_i)->cells[cell_j]); } // Update tooltip setToolTipText(cell ? m_strings[cell->tooltip_index].c_str() : L""); // Fix for #1567/#1806: // IGUIScrollBar passes double click events to its parent, // which we don't want. Detect this case and discard the event if (event.MouseInput.Event != EMIE_MOUSE_MOVED && m_scrollbar->isVisible() && m_scrollbar->isPointInside(p)) return true; if (event.MouseInput.isLeftPressed() && (isPointInside(p) || event.MouseInput.Event == EMIE_MOUSE_MOVED)) { s32 sel_column = 0; bool sel_doubleclick = (event.MouseInput.Event == EMIE_LMOUSE_DOUBLE_CLICK); bool plusminus_clicked = false; // For certain events (left click), report column // Also open/close subtrees when the +/- is clicked if (cell && ( event.MouseInput.Event == EMIE_LMOUSE_PRESSED_DOWN || event.MouseInput.Event == EMIE_LMOUSE_DOUBLE_CLICK || event.MouseInput.Event == EMIE_LMOUSE_TRIPLE_CLICK)) { sel_column = cell->reported_column; if (cell->content_type == COLUMN_TYPE_TREE) plusminus_clicked = true; } if (plusminus_clicked) { if (event.MouseInput.Event == EMIE_LMOUSE_PRESSED_DOWN) { toggleVisibleTree(row_i, 0, false); } } else { // Normal selection s32 old_selected = m_selected; m_selected = row_i; autoScroll(); if (m_selected != old_selected || sel_column >= 1 || sel_doubleclick) { sendTableEvent(sel_column, sel_doubleclick); } // Treeview: double click opens/closes trees if (m_has_tree_column && sel_doubleclick) { toggleVisibleTree(m_selected, 0, false); } } } return true; } if (event.EventType == EET_GUI_EVENT && event.GUIEvent.EventType == gui::EGET_SCROLL_BAR_CHANGED && event.GUIEvent.Caller == m_scrollbar) { // Don't pass events from our scrollbar to the parent return true; } return IGUIElement::OnEvent(event); } /******************************************************************************/ /* GUITable helper functions */ /******************************************************************************/ s32 GUITable::allocString(const std::string &text) { std::map<std::string, s32>::iterator it = m_alloc_strings.find(text); if (it == m_alloc_strings.end()) { s32 id = m_strings.size(); std::wstring wtext = utf8_to_wide(text); m_strings.emplace_back(wtext.c_str()); m_alloc_strings.insert(std::make_pair(text, id)); return id; } return it->second; } s32 GUITable::allocImage(const std::string &imagename) { std::map<std::string, s32>::iterator it = m_alloc_images.find(imagename); if (it == m_alloc_images.end()) { s32 id = m_images.size(); m_images.push_back(m_tsrc->getTexture(imagename)); m_alloc_images.insert(std::make_pair(imagename, id)); return id; } return it->second; } void GUITable::allocationComplete() { // Called when done with creating rows and cells from table data, // i.e. when allocString and allocImage won't be called anymore m_alloc_strings.clear(); m_alloc_images.clear(); } const GUITable::Row* GUITable::getRow(s32 i) const { if (i >= 0 && i < (s32) m_visible_rows.size()) return &m_rows[m_visible_rows[i]]; return NULL; } bool GUITable::doesRowStartWith(const Row *row, const core::stringw &str) const { if (row == NULL) return false; for (s32 j = 0; j < row->cellcount; ++j) { Cell *cell = &row->cells[j]; if (cell->content_type == COLUMN_TYPE_TEXT) { const core::stringw &cellstr = m_strings[cell->content_index]; if (cellstr.size() >= str.size() && str.equals_ignore_case(cellstr.subString(0, str.size()))) return true; } } return false; } s32 GUITable::getRowAt(s32 y, bool &really_hovering) const { really_hovering = false; s32 rowcount = m_visible_rows.size(); if (rowcount == 0) return -1; // Use arithmetic to find row s32 rel_y = y - AbsoluteRect.UpperLeftCorner.Y - 1; s32 i = (rel_y + m_scrollbar->getPos()) / m_rowheight; if (i >= 0 && i < rowcount) { really_hovering = true; return i; } if (i < 0) return 0; return rowcount - 1; } s32 GUITable::getCellAt(s32 x, s32 row_i) const { const Row *row = getRow(row_i); if (row == NULL) return -1; // Use binary search to find cell in row s32 rel_x = x - AbsoluteRect.UpperLeftCorner.X - 1; s32 jmin = 0; s32 jmax = row->cellcount - 1; while (jmin < jmax) { s32 pivot = jmin + (jmax - jmin) / 2; assert(pivot >= 0 && pivot < row->cellcount); const Cell *cell = &row->cells[pivot]; if (rel_x >= cell->xmin && rel_x <= cell->xmax) return pivot; if (rel_x < cell->xmin) jmax = pivot - 1; else jmin = pivot + 1; } if (jmin >= 0 && jmin < row->cellcount && rel_x >= row->cells[jmin].xmin && rel_x <= row->cells[jmin].xmax) return jmin; return -1; } void GUITable::autoScroll() { if (m_selected >= 0) { s32 pos = m_scrollbar->getPos(); s32 maxpos = m_selected * m_rowheight; s32 minpos = maxpos - (AbsoluteRect.getHeight() - m_rowheight); if (pos > maxpos) m_scrollbar->setPos(maxpos); else if (pos < minpos) m_scrollbar->setPos(minpos); } } void GUITable::updateScrollBar() { s32 totalheight = m_rowheight * m_visible_rows.size(); s32 scrollmax = MYMAX(0, totalheight - AbsoluteRect.getHeight()); m_scrollbar->setVisible(scrollmax > 0); m_scrollbar->setMax(scrollmax); m_scrollbar->setSmallStep(m_rowheight); m_scrollbar->setLargeStep(2 * m_rowheight); } void GUITable::sendTableEvent(s32 column, bool doubleclick) { m_sel_column = column; m_sel_doubleclick = doubleclick; if (Parent) { SEvent e; memset(&e, 0, sizeof e); e.EventType = EET_GUI_EVENT; e.GUIEvent.Caller = this; e.GUIEvent.Element = 0; e.GUIEvent.EventType = gui::EGET_TABLE_CHANGED; Parent->OnEvent(e); } } void GUITable::getOpenedTrees(std::set<s32> &opened_trees) const { opened_trees.clear(); s32 rowcount = m_rows.size(); for (s32 i = 0; i < rowcount - 1; ++i) { if (m_rows[i].indent < m_rows[i+1].indent && m_rows[i+1].visible_index != -2) opened_trees.insert(i); } } void GUITable::setOpenedTrees(const std::set<s32> &opened_trees) { s32 old_selected = -1; if (m_selected >= 0) old_selected = m_visible_rows[m_selected]; std::vector<s32> parents; std::vector<s32> closed_parents; m_visible_rows.clear(); for (size_t i = 0; i < m_rows.size(); ++i) { Row *row = &m_rows[i]; // Update list of ancestors while (!parents.empty() && m_rows[parents.back()].indent >= row->indent) parents.pop_back(); while (!closed_parents.empty() && m_rows[closed_parents.back()].indent >= row->indent) closed_parents.pop_back(); assert(closed_parents.size() <= parents.size()); if (closed_parents.empty()) { // Visible row row->visible_index = m_visible_rows.size(); m_visible_rows.push_back(i); } else if (parents.back() == closed_parents.back()) { // Invisible row, direct parent is closed row->visible_index = -2; } else { // Invisible row, direct parent is open, some ancestor is closed row->visible_index = -1; } // If not a leaf, add to parents list if (i < m_rows.size()-1 && row->indent < m_rows[i+1].indent) { parents.push_back(i); s32 content_index = 0; // "-", open if (opened_trees.count(i) == 0) { closed_parents.push_back(i); content_index = 1; // "+", closed } // Update all cells of type "tree" for (s32 j = 0; j < row->cellcount; ++j) if (row->cells[j].content_type == COLUMN_TYPE_TREE) row->cells[j].content_index = content_index; } } updateScrollBar(); // m_selected must be updated since it is a visible row index if (old_selected >= 0) m_selected = m_rows[old_selected].visible_index; } void GUITable::openTree(s32 to_open) { std::set<s32> opened_trees; getOpenedTrees(opened_trees); opened_trees.insert(to_open); setOpenedTrees(opened_trees); } void GUITable::closeTree(s32 to_close) { std::set<s32> opened_trees; getOpenedTrees(opened_trees); opened_trees.erase(to_close); setOpenedTrees(opened_trees); } // The following function takes a visible row index (hidden rows skipped) // dir: -1 = left (close), 0 = auto (toggle), 1 = right (open) void GUITable::toggleVisibleTree(s32 row_i, int dir, bool move_selection) { // Check if the chosen tree is currently open const Row *row = getRow(row_i); if (row == NULL) return; bool was_open = false; for (s32 j = 0; j < row->cellcount; ++j) { if (row->cells[j].content_type == COLUMN_TYPE_TREE) { was_open = row->cells[j].content_index == 0; break; } } // Check if the chosen tree should be opened bool do_open = !was_open; if (dir < 0) do_open = false; else if (dir > 0) do_open = true; // Close or open the tree; the heavy lifting is done by setOpenedTrees if (was_open && !do_open) closeTree(m_visible_rows[row_i]); else if (!was_open && do_open) openTree(m_visible_rows[row_i]); // Change selected row if requested by caller, // this is useful for keyboard navigation if (move_selection) { s32 sel = row_i; if (was_open && do_open) { // Move selection to first child const Row *maybe_child = getRow(sel + 1); if (maybe_child && maybe_child->indent > row->indent) sel++; } else if (!was_open && !do_open) { // Move selection to parent assert(getRow(sel) != NULL); while (sel > 0 && getRow(sel - 1)->indent >= row->indent) sel--; sel--; if (sel < 0) // was root already selected? sel = row_i; } if (sel != m_selected) { m_selected = sel; autoScroll(); sendTableEvent(0, false); } } } void GUITable::alignContent(Cell *cell, s32 xmax, s32 content_width, s32 align) { // requires that cell.xmin, cell.xmax are properly set // align = 0: left aligned, 1: centered, 2: right aligned, 3: inline if (align == 0) { cell->xpos = cell->xmin; cell->xmax = xmax; } else if (align == 1) { cell->xpos = (cell->xmin + xmax - content_width) / 2; cell->xmax = xmax; } else if (align == 2) { cell->xpos = xmax - content_width; cell->xmax = xmax; } else { // inline alignment: the cells of the column don't have an aligned // right border, the right border of each cell depends on the content cell->xpos = cell->xmin; cell->xmax = cell->xmin + content_width; } }
pgimeno/minetest
src/gui/guiTable.cpp
C++
mit
34,855
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> 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. */ #pragma once #include <map> #include <set> #include <string> #include <vector> #include <iostream> #include "irrlichttypes_extrabloated.h" class ISimpleTextureSource; /* A table GUI element for GUIFormSpecMenu. Sends a EGET_TABLE_CHANGED event to the parent when an item is selected or double-clicked. Call checkEvent() to get info. Credits: The interface and implementation of this class are (very) loosely based on the Irrlicht classes CGUITable and CGUIListBox. CGUITable and CGUIListBox are licensed under the Irrlicht license; they are Copyright (C) 2002-2012 Nikolaus Gebhardt */ class GUITable : public gui::IGUIElement { public: /* Stores dynamic data that should be preserved when updating a formspec */ struct DynamicData { s32 selected = 0; s32 scrollpos = 0; s32 keynav_time = 0; core::stringw keynav_buffer; std::set<s32> opened_trees; }; /* An option of the form <name>=<value> */ struct Option { std::string name; std::string value; Option(const std::string &name_, const std::string &value_) : name(name_), value(value_) {} }; /* A list of options that concern the entire table */ typedef std::vector<Option> TableOptions; /* A column with options */ struct TableColumn { std::string type; std::vector<Option> options; }; typedef std::vector<TableColumn> TableColumns; GUITable(gui::IGUIEnvironment *env, gui::IGUIElement *parent, s32 id, core::rect<s32> rectangle, ISimpleTextureSource *tsrc); virtual ~GUITable(); /* Split a string of the form "name=value" into name and value */ static Option splitOption(const std::string &str); /* Set textlist-like options, columns and data */ void setTextList(const std::vector<std::string> &content, bool transparent); /* Set generic table options, columns and content */ // Adds empty strings to end of content if there is an incomplete row void setTable(const TableOptions &options, const TableColumns &columns, std::vector<std::string> &content); /* Clear the table */ void clear(); /* Get info about last event (string such as "CHG:1:2") */ // Call this after EGET_TABLE_CHANGED std::string checkEvent(); /* Get index of currently selected row (first=1; 0 if none selected) */ s32 getSelected() const; /* Set currently selected row (first=1; 0 if none selected) */ // If given index is not visible at the moment, select its parent // Autoscroll to make the selected row fully visible void setSelected(s32 index); /* Get selection, scroll position and opened (sub)trees */ DynamicData getDynamicData() const; /* Set selection, scroll position and opened (sub)trees */ void setDynamicData(const DynamicData &dyndata); /* Returns "GUITable" */ virtual const c8* getTypeName() const; /* Must be called when position or size changes */ virtual void updateAbsolutePosition(); /* Irrlicht draw method */ virtual void draw(); /* Irrlicht event handler */ virtual bool OnEvent(const SEvent &event); protected: enum ColumnType { COLUMN_TYPE_TEXT, COLUMN_TYPE_IMAGE, COLUMN_TYPE_COLOR, COLUMN_TYPE_INDENT, COLUMN_TYPE_TREE, }; struct Cell { s32 xmin; s32 xmax; s32 xpos; ColumnType content_type; s32 content_index; s32 tooltip_index; video::SColor color; bool color_defined; s32 reported_column; }; struct Row { Cell *cells; s32 cellcount; s32 indent; // visible_index >= 0: is index of row in m_visible_rows // visible_index == -1: parent open but other ancestor closed // visible_index == -2: parent closed s32 visible_index; }; // Texture source ISimpleTextureSource *m_tsrc; // Table content (including hidden rows) std::vector<Row> m_rows; // Table content (only visible; indices into m_rows) std::vector<s32> m_visible_rows; bool m_is_textlist = false; bool m_has_tree_column = false; // Selection status s32 m_selected = -1; // index of row (1...n), or 0 if none selected s32 m_sel_column = 0; bool m_sel_doubleclick = false; // Keyboard navigation stuff u64 m_keynav_time = 0; core::stringw m_keynav_buffer = L""; // Drawing and geometry information bool m_border = true; video::SColor m_color = video::SColor(255, 255, 255, 255); video::SColor m_background = video::SColor(255, 0, 0, 0); video::SColor m_highlight = video::SColor(255, 70, 100, 50); video::SColor m_highlight_text = video::SColor(255, 255, 255, 255); s32 m_rowheight = 1; gui::IGUIFont *m_font = nullptr; gui::IGUIScrollBar *m_scrollbar = nullptr; // Allocated strings and images std::vector<core::stringw> m_strings; std::vector<video::ITexture*> m_images; std::map<std::string, s32> m_alloc_strings; std::map<std::string, s32> m_alloc_images; s32 allocString(const std::string &text); s32 allocImage(const std::string &imagename); void allocationComplete(); // Helper for draw() that draws a single cell void drawCell(const Cell *cell, video::SColor color, const core::rect<s32> &rowrect, const core::rect<s32> &client_clip); // Returns the i-th visible row (NULL if i is invalid) const Row *getRow(s32 i) const; // Key navigation helper bool doesRowStartWith(const Row *row, const core::stringw &str) const; // Returns the row at a given screen Y coordinate // Returns index i such that m_rows[i] is valid (or -1 on error) s32 getRowAt(s32 y, bool &really_hovering) const; // Returns the cell at a given screen X coordinate within m_rows[row_i] // Returns index j such that m_rows[row_i].cells[j] is valid // (or -1 on error) s32 getCellAt(s32 x, s32 row_i) const; // Make the selected row fully visible void autoScroll(); // Should be called when m_rowcount or m_rowheight changes void updateScrollBar(); // Sends EET_GUI_EVENT / EGET_TABLE_CHANGED to parent void sendTableEvent(s32 column, bool doubleclick); // Functions that help deal with hidden rows // The following functions take raw row indices (hidden rows not skipped) void getOpenedTrees(std::set<s32> &opened_trees) const; void setOpenedTrees(const std::set<s32> &opened_trees); void openTree(s32 to_open); void closeTree(s32 to_close); // The following function takes a visible row index (hidden rows skipped) // dir: -1 = left (close), 0 = auto (toggle), 1 = right (open) void toggleVisibleTree(s32 row_i, int dir, bool move_selection); // Aligns cell content in column according to alignment specification // align = 0: left aligned, 1: centered, 2: right aligned, 3: inline static void alignContent(Cell *cell, s32 xmax, s32 content_width, s32 align); };
pgimeno/minetest
src/gui/guiTable.h
C++
mit
7,316
/* Part of Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> Copyright (C) 2013 Ciaran Gultnieks <ciaran@ciarang.com> Copyright (C) 2013 RealBadAngel, Maciej Kasatkin <mk@realbadangel.pl> Permission to use, copy, modify, and distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "guiVolumeChange.h" #include "debug.h" #include "serialization.h" #include <string> #include <IGUICheckBox.h> #include <IGUIButton.h> #include <IGUIScrollBar.h> #include <IGUIStaticText.h> #include <IGUIFont.h> #include "settings.h" #include "gettext.h" const int ID_soundText = 263; const int ID_soundExitButton = 264; const int ID_soundSlider = 265; const int ID_soundMuteButton = 266; GUIVolumeChange::GUIVolumeChange(gui::IGUIEnvironment* env, gui::IGUIElement* parent, s32 id, IMenuManager *menumgr ): GUIModalMenu(env, parent, id, menumgr) { } GUIVolumeChange::~GUIVolumeChange() { removeChildren(); } void GUIVolumeChange::removeChildren() { if (gui::IGUIElement *e = getElementFromId(ID_soundText)) e->remove(); if (gui::IGUIElement *e = getElementFromId(ID_soundExitButton)) e->remove(); if (gui::IGUIElement *e = getElementFromId(ID_soundSlider)) e->remove(); } void GUIVolumeChange::regenerateGui(v2u32 screensize) { /* Remove stuff */ removeChildren(); /* Calculate new sizes and positions */ const float s = m_gui_scale; DesiredRect = core::rect<s32>( screensize.X / 2 - 380 * s / 2, screensize.Y / 2 - 200 * s / 2, screensize.X / 2 + 380 * s / 2, screensize.Y / 2 + 200 * s / 2 ); recalculateAbsolutePosition(false); v2s32 size = DesiredRect.getSize(); int volume = (int)(g_settings->getFloat("sound_volume") * 100); /* Add stuff */ { core::rect<s32> rect(0, 0, 160 * s, 20 * s); rect = rect + v2s32(size.X / 2 - 80 * s, size.Y / 2 - 70 * s); const wchar_t *text = wgettext("Sound Volume: "); core::stringw volume_text = text; delete [] text; volume_text += core::stringw(volume) + core::stringw("%"); Environment->addStaticText(volume_text.c_str(), rect, false, true, this, ID_soundText); } { core::rect<s32> rect(0, 0, 80 * s, 30 * s); rect = rect + v2s32(size.X / 2 - 80 * s / 2, size.Y / 2 + 55 * s); const wchar_t *text = wgettext("Exit"); Environment->addButton(rect, this, ID_soundExitButton, text); delete[] text; } { core::rect<s32> rect(0, 0, 300 * s, 20 * s); rect = rect + v2s32(size.X / 2 - 150 * s, size.Y / 2); gui::IGUIScrollBar *e = Environment->addScrollBar(true, rect, this, ID_soundSlider); e->setMax(100); e->setPos(volume); } { core::rect<s32> rect(0, 0, 160 * s, 20 * s); rect = rect + v2s32(size.X / 2 - 80 * s, size.Y / 2 - 35 * s); const wchar_t *text = wgettext("Muted"); Environment->addCheckBox(g_settings->getBool("mute_sound"), rect, this, ID_soundMuteButton, text); delete[] text; } } void GUIVolumeChange::drawMenu() { gui::IGUISkin* skin = Environment->getSkin(); if (!skin) return; video::IVideoDriver* driver = Environment->getVideoDriver(); video::SColor bgcolor(140, 0, 0, 0); driver->draw2DRectangle(bgcolor, AbsoluteRect, &AbsoluteClippingRect); gui::IGUIElement::draw(); } bool GUIVolumeChange::OnEvent(const SEvent& event) { if (event.EventType == EET_KEY_INPUT_EVENT) { if (event.KeyInput.Key == KEY_ESCAPE && event.KeyInput.PressedDown) { quitMenu(); return true; } if (event.KeyInput.Key == KEY_RETURN && event.KeyInput.PressedDown) { quitMenu(); return true; } } else if (event.EventType == EET_GUI_EVENT) { if (event.GUIEvent.EventType == gui::EGET_CHECKBOX_CHANGED) { gui::IGUIElement *e = getElementFromId(ID_soundMuteButton); if (e != NULL && e->getType() == gui::EGUIET_CHECK_BOX) { g_settings->setBool("mute_sound", ((gui::IGUICheckBox*)e)->isChecked()); } Environment->setFocus(this); return true; } if (event.GUIEvent.EventType == gui::EGET_BUTTON_CLICKED) { if (event.GUIEvent.Caller->getID() == ID_soundExitButton) { quitMenu(); return true; } Environment->setFocus(this); } if (event.GUIEvent.EventType == gui::EGET_ELEMENT_FOCUS_LOST && isVisible()) { if (!canTakeFocus(event.GUIEvent.Element)) { dstream << "GUIMainMenu: Not allowing focus change." << std::endl; // Returning true disables focus change return true; } } if (event.GUIEvent.EventType == gui::EGET_SCROLL_BAR_CHANGED) { if (event.GUIEvent.Caller->getID() == ID_soundSlider) { s32 pos = ((gui::IGUIScrollBar*)event.GUIEvent.Caller)->getPos(); g_settings->setFloat("sound_volume", (float) pos / 100); gui::IGUIElement *e = getElementFromId(ID_soundText); const wchar_t *text = wgettext("Sound Volume: "); core::stringw volume_text = text; delete [] text; volume_text += core::stringw(pos) + core::stringw("%"); e->setText(volume_text.c_str()); return true; } } } return Parent ? Parent->OnEvent(event) : false; }
pgimeno/minetest
src/gui/guiVolumeChange.cpp
C++
mit
5,551
/* Part of Minetest Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com> Copyright (C) 2013 Ciaran Gultnieks <ciaran@ciarang.com> Copyright (C) 2013 RealBadAngel, Maciej Kasatkin <mk@realbadangel.pl> Permission to use, copy, modify, and distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #pragma once #include "irrlichttypes_extrabloated.h" #include "modalMenu.h" #include <string> class GUIVolumeChange : public GUIModalMenu { public: GUIVolumeChange(gui::IGUIEnvironment* env, gui::IGUIElement* parent, s32 id, IMenuManager *menumgr); ~GUIVolumeChange(); void removeChildren(); /* Remove and re-add (or reposition) stuff */ void regenerateGui(v2u32 screensize); void drawMenu(); bool OnEvent(const SEvent& event); bool pausesGame() { return true; } protected: std::wstring getLabelByID(s32 id) { return L""; } std::string getNameByID(s32 id) { return ""; } };
pgimeno/minetest
src/gui/guiVolumeChange.h
C++
mit
1,516
// 11.11.2011 11:11 ValkaTR // // This is a copy of intlGUIEditBox from the irrlicht, but with a // fix in the OnEvent function, which doesn't allowed input of // other keyboard layouts than latin-1 // // Characters like: ä ö ü õ ы й ю я ъ № € ° ... // // This fix is only needed for linux, because of a bug // in the CIrrDeviceLinux.cpp:1014-1015 of the irrlicht // // Also locale in the programm should not be changed to // a "C", "POSIX" or whatever, it should be set to "", // or XLookupString will return nothing for the international // characters. // // From the "man setlocale": // // On startup of the main program, the portable "C" locale // is selected as default. A program may be made // portable to all locales by calling: // // setlocale(LC_ALL, ""); // // after program initialization.... // // Copyright (C) 2002-2013 Nikolaus Gebhardt // This file is part of the "Irrlicht Engine". // For conditions of distribution and use, see copyright notice in irrlicht.h #include <util/numeric.h> #include "intlGUIEditBox.h" #include "IGUISkin.h" #include "IGUIEnvironment.h" #include "IGUIFont.h" #include "IVideoDriver.h" //#include "irrlicht/os.cpp" #include "porting.h" //#include "Keycodes.h" #include "log.h" /* todo: optional scrollbars ctrl+left/right to select word double click/ctrl click: word select + drag to select whole words, triple click to select line optional? dragging selected text numerical */ namespace irr { namespace gui { //! constructor intlGUIEditBox::intlGUIEditBox(const wchar_t* text, bool border, IGUIEnvironment* environment, IGUIElement* parent, s32 id, const core::rect<s32>& rectangle, bool writable, bool has_vscrollbar) : IGUIEditBox(environment, parent, id, rectangle), Border(border), FrameRect(rectangle), m_scrollbar_width(0), m_vscrollbar(NULL), m_writable(writable) { #ifdef _DEBUG setDebugName("intlintlGUIEditBox"); #endif Text = text; if (Environment) Operator = Environment->getOSOperator(); if (Operator) Operator->grab(); // this element can be tabbed to setTabStop(true); setTabOrder(-1); IGUISkin *skin = 0; if (Environment) skin = Environment->getSkin(); if (Border && skin) { FrameRect.UpperLeftCorner.X += skin->getSize(EGDS_TEXT_DISTANCE_X)+1; FrameRect.UpperLeftCorner.Y += skin->getSize(EGDS_TEXT_DISTANCE_Y)+1; FrameRect.LowerRightCorner.X -= skin->getSize(EGDS_TEXT_DISTANCE_X)+1; FrameRect.LowerRightCorner.Y -= skin->getSize(EGDS_TEXT_DISTANCE_Y)+1; } if (skin && has_vscrollbar) { m_scrollbar_width = skin->getSize(gui::EGDS_SCROLLBAR_SIZE); if (m_scrollbar_width > 0) { createVScrollBar(); } } breakText(); calculateScrollPos(); setWritable(writable); } //! destructor intlGUIEditBox::~intlGUIEditBox() { if (OverrideFont) OverrideFont->drop(); if (Operator) Operator->drop(); } //! Sets another skin independent font. void intlGUIEditBox::setOverrideFont(IGUIFont* font) { if (OverrideFont == font) return; if (OverrideFont) OverrideFont->drop(); OverrideFont = font; if (OverrideFont) OverrideFont->grab(); breakText(); } IGUIFont * intlGUIEditBox::getOverrideFont() const { return OverrideFont; } //! Get the font which is used right now for drawing IGUIFont* intlGUIEditBox::getActiveFont() const { if ( OverrideFont ) return OverrideFont; IGUISkin* skin = Environment->getSkin(); if (skin) return skin->getFont(); return 0; } //! Sets another color for the text. void intlGUIEditBox::setOverrideColor(video::SColor color) { OverrideColor = color; OverrideColorEnabled = true; } video::SColor intlGUIEditBox::getOverrideColor() const { return OverrideColor; } //! Turns the border on or off void intlGUIEditBox::setDrawBorder(bool border) { Border = border; } //! Sets whether to draw the background void intlGUIEditBox::setDrawBackground(bool draw) { } //! Sets if the text should use the overide color or the color in the gui skin. void intlGUIEditBox::enableOverrideColor(bool enable) { OverrideColorEnabled = enable; } bool intlGUIEditBox::isOverrideColorEnabled() const { return OverrideColorEnabled; } //! Enables or disables word wrap void intlGUIEditBox::setWordWrap(bool enable) { WordWrap = enable; breakText(); } void intlGUIEditBox::updateAbsolutePosition() { core::rect<s32> oldAbsoluteRect(AbsoluteRect); IGUIElement::updateAbsolutePosition(); if ( oldAbsoluteRect != AbsoluteRect ) { breakText(); } } //! Checks if word wrap is enabled bool intlGUIEditBox::isWordWrapEnabled() const { return WordWrap; } //! Enables or disables newlines. void intlGUIEditBox::setMultiLine(bool enable) { MultiLine = enable; } //! Checks if multi line editing is enabled bool intlGUIEditBox::isMultiLineEnabled() const { return MultiLine; } void intlGUIEditBox::setPasswordBox(bool passwordBox, wchar_t passwordChar) { PasswordBox = passwordBox; if (PasswordBox) { PasswordChar = passwordChar; setMultiLine(false); setWordWrap(false); BrokenText.clear(); } } bool intlGUIEditBox::isPasswordBox() const { return PasswordBox; } //! Sets text justification void intlGUIEditBox::setTextAlignment(EGUI_ALIGNMENT horizontal, EGUI_ALIGNMENT vertical) { HAlign = horizontal; VAlign = vertical; } //! called if an event happened. bool intlGUIEditBox::OnEvent(const SEvent& event) { if (IsEnabled) { switch(event.EventType) { case EET_GUI_EVENT: if (event.GUIEvent.EventType == EGET_ELEMENT_FOCUS_LOST) { if (event.GUIEvent.Caller == this) { MouseMarking = false; setTextMarkers(0,0); } } break; case EET_KEY_INPUT_EVENT: { #if (defined(__linux__) || defined(__FreeBSD__)) || defined(__DragonFly__) // ################################################################ // ValkaTR: // This part is the difference from the original intlGUIEditBox // It converts UTF-8 character into a UCS-2 (wchar_t) wchar_t wc = L'_'; mbtowc( &wc, (char *) &event.KeyInput.Char, sizeof(event.KeyInput.Char) ); //printf( "char: %lc (%u) \r\n", wc, wc ); SEvent irrevent(event); irrevent.KeyInput.Char = wc; // ################################################################ if (processKey(irrevent)) return true; #else if (processKey(event)) return true; #endif // defined(linux) break; } case EET_MOUSE_INPUT_EVENT: if (processMouse(event)) return true; break; default: break; } } return IGUIElement::OnEvent(event); } bool intlGUIEditBox::processKey(const SEvent& event) { if (!event.KeyInput.PressedDown) return false; bool textChanged = false; s32 newMarkBegin = MarkBegin; s32 newMarkEnd = MarkEnd; // control shortcut handling if (event.KeyInput.Control) { // german backlash '\' entered with control + '?' if ( event.KeyInput.Char == '\\' ) { inputChar(event.KeyInput.Char); return true; } switch(event.KeyInput.Key) { case KEY_KEY_A: // select all newMarkBegin = 0; newMarkEnd = Text.size(); break; case KEY_KEY_C: // copy to clipboard if (!PasswordBox && Operator && MarkBegin != MarkEnd) { const s32 realmbgn = MarkBegin < MarkEnd ? MarkBegin : MarkEnd; const s32 realmend = MarkBegin < MarkEnd ? MarkEnd : MarkBegin; core::stringc s; s = Text.subString(realmbgn, realmend - realmbgn).c_str(); Operator->copyToClipboard(s.c_str()); } break; case KEY_KEY_X: // cut to the clipboard if (!PasswordBox && Operator && MarkBegin != MarkEnd) { const s32 realmbgn = MarkBegin < MarkEnd ? MarkBegin : MarkEnd; const s32 realmend = MarkBegin < MarkEnd ? MarkEnd : MarkBegin; // copy core::stringc sc; sc = Text.subString(realmbgn, realmend - realmbgn).c_str(); Operator->copyToClipboard(sc.c_str()); if (IsEnabled && m_writable) { // delete core::stringw s; s = Text.subString(0, realmbgn); s.append( Text.subString(realmend, Text.size()-realmend) ); Text = s; CursorPos = realmbgn; newMarkBegin = 0; newMarkEnd = 0; textChanged = true; } } break; case KEY_KEY_V: if (!IsEnabled || !m_writable) break; // paste from the clipboard if (Operator) { const s32 realmbgn = MarkBegin < MarkEnd ? MarkBegin : MarkEnd; const s32 realmend = MarkBegin < MarkEnd ? MarkEnd : MarkBegin; // add new character const c8* p = Operator->getTextFromClipboard(); if (p) { if (MarkBegin == MarkEnd) { // insert text core::stringw s = Text.subString(0, CursorPos); s.append(p); s.append( Text.subString(CursorPos, Text.size()-CursorPos) ); if (!Max || s.size()<=Max) // thx to Fish FH for fix { Text = s; s = p; CursorPos += s.size(); } } else { // replace text core::stringw s = Text.subString(0, realmbgn); s.append(p); s.append( Text.subString(realmend, Text.size()-realmend) ); if (!Max || s.size()<=Max) // thx to Fish FH for fix { Text = s; s = p; CursorPos = realmbgn + s.size(); } } } newMarkBegin = 0; newMarkEnd = 0; textChanged = true; } break; case KEY_HOME: // move/highlight to start of text if (event.KeyInput.Shift) { newMarkEnd = CursorPos; newMarkBegin = 0; CursorPos = 0; } else { CursorPos = 0; newMarkBegin = 0; newMarkEnd = 0; } break; case KEY_END: // move/highlight to end of text if (event.KeyInput.Shift) { newMarkBegin = CursorPos; newMarkEnd = Text.size(); CursorPos = 0; } else { CursorPos = Text.size(); newMarkBegin = 0; newMarkEnd = 0; } break; default: return false; } } // default keyboard handling else switch(event.KeyInput.Key) { case KEY_END: { s32 p = Text.size(); if (WordWrap || MultiLine) { p = getLineFromPos(CursorPos); p = BrokenTextPositions[p] + (s32)BrokenText[p].size(); if (p > 0 && (Text[p-1] == L'\r' || Text[p-1] == L'\n' )) p-=1; } if (event.KeyInput.Shift) { if (MarkBegin == MarkEnd) newMarkBegin = CursorPos; newMarkEnd = p; } else { newMarkBegin = 0; newMarkEnd = 0; } CursorPos = p; BlinkStartTime = porting::getTimeMs(); } break; case KEY_HOME: { s32 p = 0; if (WordWrap || MultiLine) { p = getLineFromPos(CursorPos); p = BrokenTextPositions[p]; } if (event.KeyInput.Shift) { if (MarkBegin == MarkEnd) newMarkBegin = CursorPos; newMarkEnd = p; } else { newMarkBegin = 0; newMarkEnd = 0; } CursorPos = p; BlinkStartTime = porting::getTimeMs(); } break; case KEY_RETURN: if (MultiLine) { inputChar(L'\n'); return true; } else { sendGuiEvent( EGET_EDITBOX_ENTER ); } break; case KEY_LEFT: if (event.KeyInput.Shift) { if (CursorPos > 0) { if (MarkBegin == MarkEnd) newMarkBegin = CursorPos; newMarkEnd = CursorPos-1; } } else { newMarkBegin = 0; newMarkEnd = 0; } if (CursorPos > 0) CursorPos--; BlinkStartTime = porting::getTimeMs(); break; case KEY_RIGHT: if (event.KeyInput.Shift) { if (Text.size() > (u32)CursorPos) { if (MarkBegin == MarkEnd) newMarkBegin = CursorPos; newMarkEnd = CursorPos+1; } } else { newMarkBegin = 0; newMarkEnd = 0; } if (Text.size() > (u32)CursorPos) CursorPos++; BlinkStartTime = porting::getTimeMs(); break; case KEY_UP: if (MultiLine || (WordWrap && BrokenText.size() > 1) ) { s32 lineNo = getLineFromPos(CursorPos); s32 mb = (MarkBegin == MarkEnd) ? CursorPos : (MarkBegin > MarkEnd ? MarkBegin : MarkEnd); if (lineNo > 0) { s32 cp = CursorPos - BrokenTextPositions[lineNo]; if ((s32)BrokenText[lineNo-1].size() < cp) CursorPos = BrokenTextPositions[lineNo-1] + (s32)BrokenText[lineNo-1].size()-1; else CursorPos = BrokenTextPositions[lineNo-1] + cp; } if (event.KeyInput.Shift) { newMarkBegin = mb; newMarkEnd = CursorPos; } else { newMarkBegin = 0; newMarkEnd = 0; } } else { return false; } break; case KEY_DOWN: if (MultiLine || (WordWrap && BrokenText.size() > 1) ) { s32 lineNo = getLineFromPos(CursorPos); s32 mb = (MarkBegin == MarkEnd) ? CursorPos : (MarkBegin < MarkEnd ? MarkBegin : MarkEnd); if (lineNo < (s32)BrokenText.size()-1) { s32 cp = CursorPos - BrokenTextPositions[lineNo]; if ((s32)BrokenText[lineNo+1].size() < cp) CursorPos = BrokenTextPositions[lineNo+1] + BrokenText[lineNo+1].size()-1; else CursorPos = BrokenTextPositions[lineNo+1] + cp; } if (event.KeyInput.Shift) { newMarkBegin = mb; newMarkEnd = CursorPos; } else { newMarkBegin = 0; newMarkEnd = 0; } } else { return false; } break; case KEY_BACK: if (!this->IsEnabled || !m_writable) break; if (!Text.empty()) { core::stringw s; if (MarkBegin != MarkEnd) { // delete marked text const s32 realmbgn = MarkBegin < MarkEnd ? MarkBegin : MarkEnd; const s32 realmend = MarkBegin < MarkEnd ? MarkEnd : MarkBegin; s = Text.subString(0, realmbgn); s.append( Text.subString(realmend, Text.size()-realmend) ); Text = s; CursorPos = realmbgn; } else { // delete text behind cursor if (CursorPos>0) s = Text.subString(0, CursorPos-1); else s = L""; s.append( Text.subString(CursorPos, Text.size()-CursorPos) ); Text = s; --CursorPos; } if (CursorPos < 0) CursorPos = 0; BlinkStartTime = porting::getTimeMs(); newMarkBegin = 0; newMarkEnd = 0; textChanged = true; } break; case KEY_DELETE: if (!this->IsEnabled || !m_writable) break; if (!Text.empty()) { core::stringw s; if (MarkBegin != MarkEnd) { // delete marked text const s32 realmbgn = MarkBegin < MarkEnd ? MarkBegin : MarkEnd; const s32 realmend = MarkBegin < MarkEnd ? MarkEnd : MarkBegin; s = Text.subString(0, realmbgn); s.append( Text.subString(realmend, Text.size()-realmend) ); Text = s; CursorPos = realmbgn; } else { // delete text before cursor s = Text.subString(0, CursorPos); s.append( Text.subString(CursorPos+1, Text.size()-CursorPos-1) ); Text = s; } if (CursorPos > (s32)Text.size()) CursorPos = (s32)Text.size(); BlinkStartTime = porting::getTimeMs(); newMarkBegin = 0; newMarkEnd = 0; textChanged = true; } break; case KEY_ESCAPE: case KEY_TAB: case KEY_SHIFT: case KEY_F1: case KEY_F2: case KEY_F3: case KEY_F4: case KEY_F5: case KEY_F6: case KEY_F7: case KEY_F8: case KEY_F9: case KEY_F10: case KEY_F11: case KEY_F12: case KEY_F13: case KEY_F14: case KEY_F15: case KEY_F16: case KEY_F17: case KEY_F18: case KEY_F19: case KEY_F20: case KEY_F21: case KEY_F22: case KEY_F23: case KEY_F24: // ignore these keys return false; default: inputChar(event.KeyInput.Char); return true; } // Set new text markers setTextMarkers( newMarkBegin, newMarkEnd ); // break the text if it has changed if (textChanged) { breakText(); sendGuiEvent(EGET_EDITBOX_CHANGED); } calculateScrollPos(); return true; } //! draws the element and its children void intlGUIEditBox::draw() { if (!IsVisible) return; const bool focus = Environment->hasFocus(this); IGUISkin* skin = Environment->getSkin(); if (!skin) return; FrameRect = AbsoluteRect; // draw the border if (Border) { if (m_writable) { skin->draw3DSunkenPane(this, skin->getColor(EGDC_WINDOW), false, true, FrameRect, &AbsoluteClippingRect); } FrameRect.UpperLeftCorner.X += skin->getSize(EGDS_TEXT_DISTANCE_X)+1; FrameRect.UpperLeftCorner.Y += skin->getSize(EGDS_TEXT_DISTANCE_Y)+1; FrameRect.LowerRightCorner.X -= skin->getSize(EGDS_TEXT_DISTANCE_X)+1; FrameRect.LowerRightCorner.Y -= skin->getSize(EGDS_TEXT_DISTANCE_Y)+1; } updateVScrollBar(); core::rect<s32> localClipRect = FrameRect; localClipRect.clipAgainst(AbsoluteClippingRect); // draw the text IGUIFont* font = OverrideFont; if (!OverrideFont) font = skin->getFont(); s32 cursorLine = 0; s32 charcursorpos = 0; if (font) { if (LastBreakFont != font) { breakText(); } // calculate cursor pos core::stringw *txtLine = &Text; s32 startPos = 0; core::stringw s, s2; // get mark position const bool ml = (!PasswordBox && (WordWrap || MultiLine)); const s32 realmbgn = MarkBegin < MarkEnd ? MarkBegin : MarkEnd; const s32 realmend = MarkBegin < MarkEnd ? MarkEnd : MarkBegin; const s32 hlineStart = ml ? getLineFromPos(realmbgn) : 0; const s32 hlineCount = ml ? getLineFromPos(realmend) - hlineStart + 1 : 1; const s32 lineCount = ml ? BrokenText.size() : 1; // Save the override color information. // Then, alter it if the edit box is disabled. const bool prevOver = OverrideColorEnabled; const video::SColor prevColor = OverrideColor; if (!Text.empty()) { if (!IsEnabled && !OverrideColorEnabled) { OverrideColorEnabled = true; OverrideColor = skin->getColor(EGDC_GRAY_TEXT); } for (s32 i=0; i < lineCount; ++i) { setTextRect(i); // clipping test - don't draw anything outside the visible area core::rect<s32> c = localClipRect; c.clipAgainst(CurrentTextRect); if (!c.isValid()) continue; // get current line if (PasswordBox) { if (BrokenText.size() != 1) { BrokenText.clear(); BrokenText.push_back(core::stringw()); } if (BrokenText[0].size() != Text.size()) { BrokenText[0] = Text; for (u32 q = 0; q < Text.size(); ++q) { BrokenText[0] [q] = PasswordChar; } } txtLine = &BrokenText[0]; startPos = 0; } else { txtLine = ml ? &BrokenText[i] : &Text; startPos = ml ? BrokenTextPositions[i] : 0; } // draw normal text font->draw(txtLine->c_str(), CurrentTextRect, OverrideColorEnabled ? OverrideColor : skin->getColor(EGDC_BUTTON_TEXT), false, true, &localClipRect); // draw mark and marked text if (focus && MarkBegin != MarkEnd && i >= hlineStart && i < hlineStart + hlineCount) { s32 mbegin = 0, mend = 0; s32 lineStartPos = 0, lineEndPos = txtLine->size(); if (i == hlineStart) { // highlight start is on this line s = txtLine->subString(0, realmbgn - startPos); mbegin = font->getDimension(s.c_str()).Width; // deal with kerning mbegin += font->getKerningWidth( &((*txtLine)[realmbgn - startPos]), realmbgn - startPos > 0 ? &((*txtLine)[realmbgn - startPos - 1]) : 0); lineStartPos = realmbgn - startPos; } if (i == hlineStart + hlineCount - 1) { // highlight end is on this line s2 = txtLine->subString(0, realmend - startPos); mend = font->getDimension(s2.c_str()).Width; lineEndPos = (s32)s2.size(); } else mend = font->getDimension(txtLine->c_str()).Width; CurrentTextRect.UpperLeftCorner.X += mbegin; CurrentTextRect.LowerRightCorner.X = CurrentTextRect.UpperLeftCorner.X + mend - mbegin; // draw mark skin->draw2DRectangle(this, skin->getColor(EGDC_HIGH_LIGHT), CurrentTextRect, &localClipRect); // draw marked text s = txtLine->subString(lineStartPos, lineEndPos - lineStartPos); if (!s.empty()) font->draw(s.c_str(), CurrentTextRect, OverrideColorEnabled ? OverrideColor : skin->getColor(EGDC_HIGH_LIGHT_TEXT), false, true, &localClipRect); } } // Return the override color information to its previous settings. OverrideColorEnabled = prevOver; OverrideColor = prevColor; } // draw cursor if (WordWrap || MultiLine) { cursorLine = getLineFromPos(CursorPos); txtLine = &BrokenText[cursorLine]; startPos = BrokenTextPositions[cursorLine]; } s = txtLine->subString(0,CursorPos-startPos); charcursorpos = font->getDimension(s.c_str()).Width + font->getKerningWidth(L"_", CursorPos-startPos > 0 ? &((*txtLine)[CursorPos-startPos-1]) : 0); if (m_writable) { if (focus && (porting::getTimeMs() - BlinkStartTime) % 700 < 350) { setTextRect(cursorLine); CurrentTextRect.UpperLeftCorner.X += charcursorpos; font->draw(L"_", CurrentTextRect, OverrideColorEnabled ? OverrideColor : skin->getColor(EGDC_BUTTON_TEXT), false, true, &localClipRect); } } } // draw children IGUIElement::draw(); } //! Sets the new caption of this element. void intlGUIEditBox::setText(const wchar_t* text) { Text = text; if (u32(CursorPos) > Text.size()) CursorPos = Text.size(); HScrollPos = 0; breakText(); } //! Enables or disables automatic scrolling with cursor position //! \param enable: If set to true, the text will move around with the cursor position void intlGUIEditBox::setAutoScroll(bool enable) { AutoScroll = enable; } //! Checks to see if automatic scrolling is enabled //! \return true if automatic scrolling is enabled, false if not bool intlGUIEditBox::isAutoScrollEnabled() const { return AutoScroll; } //! Gets the area of the text in the edit box //! \return Returns the size in pixels of the text core::dimension2du intlGUIEditBox::getTextDimension() { core::rect<s32> ret; setTextRect(0); ret = CurrentTextRect; for (u32 i=1; i < BrokenText.size(); ++i) { setTextRect(i); ret.addInternalPoint(CurrentTextRect.UpperLeftCorner); ret.addInternalPoint(CurrentTextRect.LowerRightCorner); } return core::dimension2du(ret.getSize()); } //! Sets the maximum amount of characters which may be entered in the box. //! \param max: Maximum amount of characters. If 0, the character amount is //! infinity. void intlGUIEditBox::setMax(u32 max) { Max = max; if (Text.size() > Max && Max != 0) Text = Text.subString(0, Max); } //! Returns maximum amount of characters, previously set by setMax(); u32 intlGUIEditBox::getMax() const { return Max; } bool intlGUIEditBox::processMouse(const SEvent& event) { switch(event.MouseInput.Event) { case irr::EMIE_LMOUSE_LEFT_UP: if (Environment->hasFocus(this)) { CursorPos = getCursorPos(event.MouseInput.X, event.MouseInput.Y); if (MouseMarking) { setTextMarkers( MarkBegin, CursorPos ); } MouseMarking = false; calculateScrollPos(); return true; } break; case irr::EMIE_MOUSE_MOVED: { if (MouseMarking) { CursorPos = getCursorPos(event.MouseInput.X, event.MouseInput.Y); setTextMarkers( MarkBegin, CursorPos ); calculateScrollPos(); return true; } } break; case EMIE_LMOUSE_PRESSED_DOWN: if (!Environment->hasFocus(this)) { BlinkStartTime = porting::getTimeMs(); MouseMarking = true; CursorPos = getCursorPos(event.MouseInput.X, event.MouseInput.Y); setTextMarkers(CursorPos, CursorPos ); calculateScrollPos(); return true; } else { if (!AbsoluteClippingRect.isPointInside( core::position2d<s32>(event.MouseInput.X, event.MouseInput.Y))) { return false; } // move cursor CursorPos = getCursorPos(event.MouseInput.X, event.MouseInput.Y); s32 newMarkBegin = MarkBegin; if (!MouseMarking) newMarkBegin = CursorPos; MouseMarking = true; setTextMarkers( newMarkBegin, CursorPos); calculateScrollPos(); return true; } break; case EMIE_MOUSE_WHEEL: if (m_vscrollbar && m_vscrollbar->isVisible()) { s32 pos = m_vscrollbar->getPos(); s32 step = m_vscrollbar->getSmallStep(); m_vscrollbar->setPos(pos - event.MouseInput.Wheel * step); } break; default: break; } return false; } s32 intlGUIEditBox::getCursorPos(s32 x, s32 y) { IGUIFont* font = OverrideFont; IGUISkin* skin = Environment->getSkin(); if (!OverrideFont) font = skin->getFont(); const u32 lineCount = (WordWrap || MultiLine) ? BrokenText.size() : 1; core::stringw *txtLine = NULL; s32 startPos = 0; u32 curr_line_idx = 0; x += 3; for (; curr_line_idx < lineCount; ++curr_line_idx) { setTextRect(curr_line_idx); if (curr_line_idx == 0 && y < CurrentTextRect.UpperLeftCorner.Y) y = CurrentTextRect.UpperLeftCorner.Y; if (curr_line_idx == lineCount - 1 && y > CurrentTextRect.LowerRightCorner.Y) y = CurrentTextRect.LowerRightCorner.Y; // is it inside this region? if (y >= CurrentTextRect.UpperLeftCorner.Y && y <= CurrentTextRect.LowerRightCorner.Y) { // we've found the clicked line txtLine = (WordWrap || MultiLine) ? &BrokenText[curr_line_idx] : &Text; startPos = (WordWrap || MultiLine) ? BrokenTextPositions[curr_line_idx] : 0; break; } } if (x < CurrentTextRect.UpperLeftCorner.X) x = CurrentTextRect.UpperLeftCorner.X; else if (x > CurrentTextRect.LowerRightCorner.X) x = CurrentTextRect.LowerRightCorner.X; s32 idx = font->getCharacterFromPos(txtLine->c_str(), x - CurrentTextRect.UpperLeftCorner.X); // Special handling for last line, if we are on limits, add 1 extra shift because idx // will be the last char, not null char of the wstring if (curr_line_idx == lineCount - 1 && x == CurrentTextRect.LowerRightCorner.X) idx++; return rangelim(idx + startPos, 0, S32_MAX); } //! Breaks the single text line. void intlGUIEditBox::breakText() { IGUISkin* skin = Environment->getSkin(); if ((!WordWrap && !MultiLine) || !skin) return; BrokenText.clear(); // need to reallocate :/ BrokenTextPositions.set_used(0); IGUIFont* font = OverrideFont; if (!OverrideFont) font = skin->getFont(); if (!font) return; LastBreakFont = font; core::stringw line; core::stringw word; core::stringw whitespace; s32 lastLineStart = 0; s32 size = Text.size(); s32 length = 0; s32 elWidth = RelativeRect.getWidth() - 6; wchar_t c; for (s32 i=0; i<size; ++i) { c = Text[i]; bool lineBreak = false; if (c == L'\r') // Mac or Windows breaks { lineBreak = true; c = ' '; if (Text[i+1] == L'\n') // Windows breaks { Text.erase(i+1); --size; } } else if (c == L'\n') // Unix breaks { lineBreak = true; c = ' '; } // don't break if we're not a multi-line edit box if (!MultiLine) lineBreak = false; if (c == L' ' || c == 0 || i == (size-1)) { if (!word.empty()) { // here comes the next whitespace, look if // we can break the last word to the next line. s32 whitelgth = font->getDimension(whitespace.c_str()).Width; s32 worldlgth = font->getDimension(word.c_str()).Width; if (WordWrap && length + worldlgth + whitelgth > elWidth) { // break to next line length = worldlgth; BrokenText.push_back(line); BrokenTextPositions.push_back(lastLineStart); lastLineStart = i - (s32)word.size(); line = word; } else { // add word to line line += whitespace; line += word; length += whitelgth + worldlgth; } word = L""; whitespace = L""; } whitespace += c; // compute line break if (lineBreak) { line += whitespace; line += word; BrokenText.push_back(line); BrokenTextPositions.push_back(lastLineStart); lastLineStart = i+1; line = L""; word = L""; whitespace = L""; length = 0; } } else { // yippee this is a word.. word += c; } } line += whitespace; line += word; BrokenText.push_back(line); BrokenTextPositions.push_back(lastLineStart); } void intlGUIEditBox::setTextRect(s32 line) { core::dimension2du d; IGUISkin* skin = Environment->getSkin(); if (!skin) return; IGUIFont* font = OverrideFont ? OverrideFont : skin->getFont(); if (!font) return; // get text dimension const u32 lineCount = (WordWrap || MultiLine) ? BrokenText.size() : 1; if (WordWrap || MultiLine) { d = font->getDimension(BrokenText[line].c_str()); } else { d = font->getDimension(Text.c_str()); d.Height = AbsoluteRect.getHeight(); } d.Height += font->getKerningHeight(); // justification switch (HAlign) { case EGUIA_CENTER: // align to h centre CurrentTextRect.UpperLeftCorner.X = (FrameRect.getWidth()/2) - (d.Width/2); CurrentTextRect.LowerRightCorner.X = (FrameRect.getWidth()/2) + (d.Width/2); break; case EGUIA_LOWERRIGHT: // align to right edge CurrentTextRect.UpperLeftCorner.X = FrameRect.getWidth() - d.Width; CurrentTextRect.LowerRightCorner.X = FrameRect.getWidth(); break; default: // align to left edge CurrentTextRect.UpperLeftCorner.X = 0; CurrentTextRect.LowerRightCorner.X = d.Width; } switch (VAlign) { case EGUIA_CENTER: // align to v centre CurrentTextRect.UpperLeftCorner.Y = (FrameRect.getHeight()/2) - (lineCount*d.Height)/2 + d.Height*line; break; case EGUIA_LOWERRIGHT: // align to bottom edge CurrentTextRect.UpperLeftCorner.Y = FrameRect.getHeight() - lineCount*d.Height + d.Height*line; break; default: // align to top edge CurrentTextRect.UpperLeftCorner.Y = d.Height*line; break; } CurrentTextRect.UpperLeftCorner.X -= HScrollPos; CurrentTextRect.LowerRightCorner.X -= HScrollPos; CurrentTextRect.UpperLeftCorner.Y -= VScrollPos; CurrentTextRect.LowerRightCorner.Y = CurrentTextRect.UpperLeftCorner.Y + d.Height; CurrentTextRect += FrameRect.UpperLeftCorner; } s32 intlGUIEditBox::getLineFromPos(s32 pos) { if (!WordWrap && !MultiLine) return 0; s32 i=0; while (i < (s32)BrokenTextPositions.size()) { if (BrokenTextPositions[i] > pos) return i-1; ++i; } return (s32)BrokenTextPositions.size() - 1; } void intlGUIEditBox::inputChar(wchar_t c) { if (!IsEnabled || !m_writable) return; if (c != 0) { if (Text.size() < Max || Max == 0) { core::stringw s; if (MarkBegin != MarkEnd) { // replace marked text const s32 realmbgn = MarkBegin < MarkEnd ? MarkBegin : MarkEnd; const s32 realmend = MarkBegin < MarkEnd ? MarkEnd : MarkBegin; s = Text.subString(0, realmbgn); s.append(c); s.append( Text.subString(realmend, Text.size()-realmend) ); Text = s; CursorPos = realmbgn+1; } else { // add new character s = Text.subString(0, CursorPos); s.append(c); s.append( Text.subString(CursorPos, Text.size()-CursorPos) ); Text = s; ++CursorPos; } BlinkStartTime = porting::getTimeMs(); setTextMarkers(0, 0); } } breakText(); sendGuiEvent(EGET_EDITBOX_CHANGED); calculateScrollPos(); } void intlGUIEditBox::calculateScrollPos() { if (!AutoScroll) return; // calculate horizontal scroll position s32 cursLine = getLineFromPos(CursorPos); setTextRect(cursLine); // don't do horizontal scrolling when wordwrap is enabled. if (!WordWrap) { // get cursor position IGUISkin* skin = Environment->getSkin(); if (!skin) return; IGUIFont* font = OverrideFont ? OverrideFont : skin->getFont(); if (!font) return; core::stringw *txtLine = MultiLine ? &BrokenText[cursLine] : &Text; s32 cPos = MultiLine ? CursorPos - BrokenTextPositions[cursLine] : CursorPos; s32 cStart = CurrentTextRect.UpperLeftCorner.X + HScrollPos + font->getDimension(txtLine->subString(0, cPos).c_str()).Width; s32 cEnd = cStart + font->getDimension(L"_ ").Width; if (FrameRect.LowerRightCorner.X < cEnd) HScrollPos = cEnd - FrameRect.LowerRightCorner.X; else if (FrameRect.UpperLeftCorner.X > cStart) HScrollPos = cStart - FrameRect.UpperLeftCorner.X; else HScrollPos = 0; // todo: adjust scrollbar } if (!WordWrap && !MultiLine) return; // vertical scroll position if (FrameRect.LowerRightCorner.Y < CurrentTextRect.LowerRightCorner.Y) VScrollPos += CurrentTextRect.LowerRightCorner.Y - FrameRect.LowerRightCorner.Y; // scrolling downwards else if (FrameRect.UpperLeftCorner.Y > CurrentTextRect.UpperLeftCorner.Y) VScrollPos += CurrentTextRect.UpperLeftCorner.Y - FrameRect.UpperLeftCorner.Y; // scrolling upwards // todo: adjust scrollbar if (m_vscrollbar) m_vscrollbar->setPos(VScrollPos); } //! set text markers void intlGUIEditBox::setTextMarkers(s32 begin, s32 end) { if ( begin != MarkBegin || end != MarkEnd ) { MarkBegin = begin; MarkEnd = end; sendGuiEvent(EGET_EDITBOX_MARKING_CHANGED); } } //! send some gui event to parent void intlGUIEditBox::sendGuiEvent(EGUI_EVENT_TYPE type) { if ( Parent ) { SEvent e; e.EventType = EET_GUI_EVENT; e.GUIEvent.Caller = this; e.GUIEvent.Element = 0; e.GUIEvent.EventType = type; Parent->OnEvent(e); } } //! Create a vertical scrollbar void intlGUIEditBox::createVScrollBar() { s32 fontHeight = 1; if (OverrideFont) { fontHeight = OverrideFont->getDimension(L"").Height; } else { if (IGUISkin* skin = Environment->getSkin()) { if (IGUIFont* font = skin->getFont()) { fontHeight = font->getDimension(L"").Height; } } } RelativeRect.LowerRightCorner.X -= m_scrollbar_width + 4; irr::core::rect<s32> scrollbarrect = FrameRect; scrollbarrect.UpperLeftCorner.X += FrameRect.getWidth() - m_scrollbar_width; m_vscrollbar = Environment->addScrollBar(false, scrollbarrect, getParent(), getID()); m_vscrollbar->setVisible(false); m_vscrollbar->setSmallStep(3 * fontHeight); m_vscrollbar->setLargeStep(10 * fontHeight); } //! Update the vertical scrollbar (visibilty & scroll position) void intlGUIEditBox::updateVScrollBar() { if (!m_vscrollbar) return; // OnScrollBarChanged(...) if (m_vscrollbar->getPos() != VScrollPos) { s32 deltaScrollY = m_vscrollbar->getPos() - VScrollPos; CurrentTextRect.UpperLeftCorner.Y -= deltaScrollY; CurrentTextRect.LowerRightCorner.Y -= deltaScrollY; s32 scrollymax = getTextDimension().Height - FrameRect.getHeight(); if (scrollymax != m_vscrollbar->getMax()) { // manage a newline or a deleted line m_vscrollbar->setMax(scrollymax); calculateScrollPos(); } else { // manage a newline or a deleted line VScrollPos = m_vscrollbar->getPos(); } } // check if a vertical scrollbar is needed ? if (getTextDimension().Height > (u32) FrameRect.getHeight()) { s32 scrollymax = getTextDimension().Height - FrameRect.getHeight(); if (scrollymax != m_vscrollbar->getMax()) { m_vscrollbar->setMax(scrollymax); } if (!m_vscrollbar->isVisible() && MultiLine) { AbsoluteRect.LowerRightCorner.X -= m_scrollbar_width; m_vscrollbar->setVisible(true); } } else { if (m_vscrollbar->isVisible()) { AbsoluteRect.LowerRightCorner.X += m_scrollbar_width; VScrollPos = 0; m_vscrollbar->setPos(0); m_vscrollbar->setMax(1); m_vscrollbar->setVisible(false); } } } void intlGUIEditBox::setWritable(bool can_write_text) { m_writable = can_write_text; } //! Writes attributes of the element. void intlGUIEditBox::serializeAttributes(io::IAttributes* out, io::SAttributeReadWriteOptions* options=0) const { // IGUIEditBox::serializeAttributes(out,options); out->addBool ("OverrideColorEnabled",OverrideColorEnabled ); out->addColor ("OverrideColor", OverrideColor); // out->addFont("OverrideFont",OverrideFont); out->addInt ("MaxChars", Max); out->addBool ("WordWrap", WordWrap); out->addBool ("MultiLine", MultiLine); out->addBool ("AutoScroll", AutoScroll); out->addBool ("PasswordBox", PasswordBox); core::stringw ch = L" "; ch[0] = PasswordChar; out->addString("PasswordChar", ch.c_str()); out->addEnum ("HTextAlign", HAlign, GUIAlignmentNames); out->addEnum ("VTextAlign", VAlign, GUIAlignmentNames); out->addBool ("Writable", m_writable); IGUIEditBox::serializeAttributes(out,options); } //! Reads attributes of the element void intlGUIEditBox::deserializeAttributes(io::IAttributes* in, io::SAttributeReadWriteOptions* options=0) { IGUIEditBox::deserializeAttributes(in,options); setOverrideColor(in->getAttributeAsColor("OverrideColor")); enableOverrideColor(in->getAttributeAsBool("OverrideColorEnabled")); setMax(in->getAttributeAsInt("MaxChars")); setWordWrap(in->getAttributeAsBool("WordWrap")); setMultiLine(in->getAttributeAsBool("MultiLine")); setAutoScroll(in->getAttributeAsBool("AutoScroll")); core::stringw ch = in->getAttributeAsStringW("PasswordChar"); if (ch.empty()) setPasswordBox(in->getAttributeAsBool("PasswordBox")); else setPasswordBox(in->getAttributeAsBool("PasswordBox"), ch[0]); setTextAlignment( (EGUI_ALIGNMENT) in->getAttributeAsEnumeration("HTextAlign", GUIAlignmentNames), (EGUI_ALIGNMENT) in->getAttributeAsEnumeration("VTextAlign", GUIAlignmentNames)); setWritable(in->getAttributeAsBool("Writable")); // setOverrideFont(in->getAttributeAsFont("OverrideFont")); } } // end namespace gui } // end namespace irr
pgimeno/minetest
src/gui/intlGUIEditBox.cpp
C++
mit
36,829
// Copyright (C) 2002-2013 Nikolaus Gebhardt // This file is part of the "Irrlicht Engine". // For conditions of distribution and use, see copyright notice in irrlicht.h #pragma once #include "IrrCompileConfig.h" //#ifdef _IRR_COMPILE_WITH_GUI_ #include <IGUIEditBox.h> #include "irrArray.h" #include "IOSOperator.h" #include "IGUIScrollBar.h" namespace irr { namespace gui { class intlGUIEditBox : public IGUIEditBox { public: //! constructor intlGUIEditBox(const wchar_t* text, bool border, IGUIEnvironment* environment, IGUIElement* parent, s32 id, const core::rect<s32>& rectangle, bool writable = true, bool has_vscrollbar = false); //! destructor virtual ~intlGUIEditBox(); //! Sets another skin independent font. virtual void setOverrideFont(IGUIFont* font=0); //! Gets the override font (if any) /** \return The override font (may be 0) */ virtual IGUIFont* getOverrideFont() const; //! Get the font which is used right now for drawing /** Currently this is the override font when one is set and the font of the active skin otherwise */ virtual IGUIFont* getActiveFont() const; //! Sets another color for the text. virtual void setOverrideColor(video::SColor color); //! Gets the override color virtual video::SColor getOverrideColor() const; //! Sets if the text should use the overide color or the //! color in the gui skin. virtual void enableOverrideColor(bool enable); //! Checks if an override color is enabled /** \return true if the override color is enabled, false otherwise */ virtual bool isOverrideColorEnabled(void) const; //! Sets whether to draw the background virtual void setDrawBackground(bool draw); virtual bool isDrawBackgroundEnabled() const { return true; } //! Turns the border on or off virtual void setDrawBorder(bool border); virtual bool isDrawBorderEnabled() const { return Border; } //! Enables or disables word wrap for using the edit box as multiline text editor. virtual void setWordWrap(bool enable); //! Checks if word wrap is enabled //! \return true if word wrap is enabled, false otherwise virtual bool isWordWrapEnabled() const; //! Enables or disables newlines. /** \param enable: If set to true, the EGET_EDITBOX_ENTER event will not be fired, instead a newline character will be inserted. */ virtual void setMultiLine(bool enable); //! Checks if multi line editing is enabled //! \return true if mult-line is enabled, false otherwise virtual bool isMultiLineEnabled() const; //! Enables or disables automatic scrolling with cursor position //! \param enable: If set to true, the text will move around with the cursor position virtual void setAutoScroll(bool enable); //! Checks to see if automatic scrolling is enabled //! \return true if automatic scrolling is enabled, false if not virtual bool isAutoScrollEnabled() const; //! Gets the size area of the text in the edit box //! \return Returns the size in pixels of the text virtual core::dimension2du getTextDimension(); //! Sets text justification virtual void setTextAlignment(EGUI_ALIGNMENT horizontal, EGUI_ALIGNMENT vertical); //! called if an event happened. virtual bool OnEvent(const SEvent& event); //! draws the element and its children virtual void draw(); //! Sets the new caption of this element. virtual void setText(const wchar_t* text); //! Sets the maximum amount of characters which may be entered in the box. //! \param max: Maximum amount of characters. If 0, the character amount is //! infinity. virtual void setMax(u32 max); //! Returns maximum amount of characters, previously set by setMax(); virtual u32 getMax() const; //! Sets whether the edit box is a password box. Setting this to true will /** disable MultiLine, WordWrap and the ability to copy with ctrl+c or ctrl+x \param passwordBox: true to enable password, false to disable \param passwordChar: the character that is displayed instead of letters */ virtual void setPasswordBox(bool passwordBox, wchar_t passwordChar = L'*'); //! Returns true if the edit box is currently a password box. virtual bool isPasswordBox() const; //! Updates the absolute position, splits text if required virtual void updateAbsolutePosition(); //! set true if this EditBox is writable virtual void setWritable(bool can_write_text); //! Writes attributes of the element. virtual void serializeAttributes(io::IAttributes* out, io::SAttributeReadWriteOptions* options) const; //! Reads attributes of the element virtual void deserializeAttributes(io::IAttributes* in, io::SAttributeReadWriteOptions* options); virtual void setCursorChar(const wchar_t cursorChar) {} virtual wchar_t getCursorChar() const { return L'|'; } virtual void setCursorBlinkTime(u32 timeMs) {} virtual u32 getCursorBlinkTime() const { return 500; } protected: //! Breaks the single text line. void breakText(); //! sets the area of the given line void setTextRect(s32 line); //! returns the line number that the cursor is on s32 getLineFromPos(s32 pos); //! adds a letter to the edit box void inputChar(wchar_t c); //! calculates the current scroll position void calculateScrollPos(); //! send some gui event to parent void sendGuiEvent(EGUI_EVENT_TYPE type); //! set text markers void setTextMarkers(s32 begin, s32 end); bool processKey(const SEvent& event); bool processMouse(const SEvent& event); s32 getCursorPos(s32 x, s32 y); //! Create a vertical scrollbar void createVScrollBar(); //! Update the vertical scrollbar (visibilty & scroll position) void updateVScrollBar(); bool MouseMarking = false; bool Border; bool OverrideColorEnabled = false; s32 MarkBegin = 0; s32 MarkEnd = 0; video::SColor OverrideColor = video::SColor(101,255,255,255); gui::IGUIFont *OverrideFont = nullptr; gui::IGUIFont *LastBreakFont = nullptr; IOSOperator *Operator = nullptr; u64 BlinkStartTime = 0; s32 CursorPos = 0; s32 HScrollPos = 0; s32 VScrollPos = 0; // scroll position in characters u32 Max = 0; bool WordWrap = false; bool MultiLine = false; bool AutoScroll = true; bool PasswordBox = false; wchar_t PasswordChar = L'*'; EGUI_ALIGNMENT HAlign = EGUIA_UPPERLEFT; EGUI_ALIGNMENT VAlign = EGUIA_CENTER; core::array<core::stringw> BrokenText; core::array<s32> BrokenTextPositions; core::rect<s32> CurrentTextRect = core::rect<s32>(0,0,1,1); core::rect<s32> FrameRect; // temporary values u32 m_scrollbar_width; IGUIScrollBar *m_vscrollbar; bool m_writable; }; } // end namespace gui } // end namespace irr //#endif // _IRR_COMPILE_WITH_GUI_
pgimeno/minetest
src/gui/intlGUIEditBox.h
C++
mit
6,702
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> 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. */ #pragma once /* All kinds of stuff that needs to be exposed from main.cpp */ #include "modalMenu.h" #include <cassert> #include <list> class IGameCallback { public: virtual void exitToOS() = 0; virtual void keyConfig() = 0; virtual void disconnect() = 0; virtual void changePassword() = 0; virtual void changeVolume() = 0; virtual void signalKeyConfigChange() = 0; }; extern gui::IGUIEnvironment *guienv; extern gui::IGUIStaticText *guiroot; // Handler for the modal menus class MainMenuManager : public IMenuManager { public: virtual void createdMenu(gui::IGUIElement *menu) { #ifndef NDEBUG for (gui::IGUIElement *i : m_stack) { assert(i != menu); } #endif if(!m_stack.empty()) m_stack.back()->setVisible(false); m_stack.push_back(menu); } virtual void deletingMenu(gui::IGUIElement *menu) { // Remove all entries if there are duplicates m_stack.remove(menu); /*core::list<GUIModalMenu*>::Iterator i = m_stack.getLast(); assert(*i == menu); m_stack.erase(i);*/ if(!m_stack.empty()) m_stack.back()->setVisible(true); } // Returns true to prevent further processing virtual bool preprocessEvent(const SEvent& event) { if (m_stack.empty()) return false; GUIModalMenu *mm = dynamic_cast<GUIModalMenu*>(m_stack.back()); return mm && mm->preprocessEvent(event); } u32 menuCount() { return m_stack.size(); } bool pausesGame() { for (gui::IGUIElement *i : m_stack) { GUIModalMenu *mm = dynamic_cast<GUIModalMenu*>(i); if (mm && mm->pausesGame()) return true; } return false; } std::list<gui::IGUIElement*> m_stack; }; extern MainMenuManager g_menumgr; extern bool isMenuActive(); class MainGameCallback : public IGameCallback { public: MainGameCallback() = default; virtual ~MainGameCallback() = default; virtual void exitToOS() { shutdown_requested = true; } virtual void disconnect() { disconnect_requested = true; } virtual void changePassword() { changepassword_requested = true; } virtual void changeVolume() { changevolume_requested = true; } virtual void keyConfig() { keyconfig_requested = true; } virtual void signalKeyConfigChange() { keyconfig_changed = true; } bool disconnect_requested = false; bool changepassword_requested = false; bool changevolume_requested = false; bool keyconfig_requested = false; bool shutdown_requested = false; bool keyconfig_changed = false; }; extern MainGameCallback *g_gamecallback;
pgimeno/minetest
src/gui/mainmenumanager.h
C++
mit
3,251
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> Copyright (C) 2018 stujones11, Stuart Jones <stujones111@gmail.com> 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 <cstdlib> #include "modalMenu.h" #include "gettext.h" #include "porting.h" #include "settings.h" #ifdef HAVE_TOUCHSCREENGUI #include "touchscreengui.h" #endif // clang-format off GUIModalMenu::GUIModalMenu(gui::IGUIEnvironment* env, gui::IGUIElement* parent, s32 id, IMenuManager *menumgr) : IGUIElement(gui::EGUIET_ELEMENT, env, parent, id, core::rect<s32>(0, 0, 100, 100)), #ifdef __ANDROID__ m_jni_field_name(""), #endif m_menumgr(menumgr) { m_gui_scale = g_settings->getFloat("gui_scaling"); #ifdef __ANDROID__ float d = porting::getDisplayDensity(); m_gui_scale *= 1.1 - 0.3 * d + 0.2 * d * d; #endif setVisible(true); Environment->setFocus(this); m_menumgr->createdMenu(this); } // clang-format on GUIModalMenu::~GUIModalMenu() { m_menumgr->deletingMenu(this); } void GUIModalMenu::allowFocusRemoval(bool allow) { m_allow_focus_removal = allow; } bool GUIModalMenu::canTakeFocus(gui::IGUIElement *e) { return (e && (e == this || isMyChild(e))) || m_allow_focus_removal; } void GUIModalMenu::draw() { if (!IsVisible) return; video::IVideoDriver *driver = Environment->getVideoDriver(); v2u32 screensize = driver->getScreenSize(); if (screensize != m_screensize_old) { m_screensize_old = screensize; regenerateGui(screensize); } drawMenu(); } /* This should be called when the menu wants to quit. WARNING: THIS DEALLOCATES THE MENU FROM MEMORY. Return immediately if you call this from the menu itself. (More precisely, this decrements the reference count.) */ void GUIModalMenu::quitMenu() { allowFocusRemoval(true); // This removes Environment's grab on us Environment->removeFocus(this); m_menumgr->deletingMenu(this); this->remove(); #ifdef HAVE_TOUCHSCREENGUI if (g_touchscreengui && m_touchscreen_visible) g_touchscreengui->show(); #endif } void GUIModalMenu::removeChildren() { const core::list<gui::IGUIElement *> &children = getChildren(); core::list<gui::IGUIElement *> children_copy; for (gui::IGUIElement *i : children) { children_copy.push_back(i); } for (gui::IGUIElement *i : children_copy) { i->remove(); } } bool GUIModalMenu::preprocessEvent(const SEvent &event) { #ifdef __ANDROID__ // clang-format off // display software keyboard when clicking edit boxes if (event.EventType == EET_MOUSE_INPUT_EVENT && event.MouseInput.Event == EMIE_LMOUSE_PRESSED_DOWN) { gui::IGUIElement *hovered = Environment->getRootGUIElement()->getElementFromPoint( core::position2d<s32>(event.MouseInput.X, event.MouseInput.Y)); if ((hovered) && (hovered->getType() == irr::gui::EGUIET_EDIT_BOX)) { bool retval = hovered->OnEvent(event); if (retval) Environment->setFocus(hovered); std::string field_name = getNameByID(hovered->getID()); // read-only field if (field_name.empty()) return retval; m_jni_field_name = field_name; std::string message = gettext("Enter "); std::string label = wide_to_utf8(getLabelByID(hovered->getID())); if (label.empty()) label = "text"; message += gettext(label) + ":"; // single line text input int type = 2; // multi line text input if (((gui::IGUIEditBox *)hovered)->isMultiLineEnabled()) type = 1; // passwords are always single line if (((gui::IGUIEditBox *)hovered)->isPasswordBox()) type = 3; porting::showInputDialog(gettext("ok"), "", wide_to_utf8(((gui::IGUIEditBox *)hovered)->getText()), type); return retval; } } if (event.EventType == EET_TOUCH_INPUT_EVENT) { SEvent translated; memset(&translated, 0, sizeof(SEvent)); translated.EventType = EET_MOUSE_INPUT_EVENT; gui::IGUIElement *root = Environment->getRootGUIElement(); if (!root) { errorstream << "GUIModalMenu::preprocessEvent" << " unable to get root element" << std::endl; return false; } gui::IGUIElement *hovered = root->getElementFromPoint( core::position2d<s32>(event.TouchInput.X, event.TouchInput.Y)); translated.MouseInput.X = event.TouchInput.X; translated.MouseInput.Y = event.TouchInput.Y; translated.MouseInput.Control = false; bool dont_send_event = false; if (event.TouchInput.touchedCount == 1) { switch (event.TouchInput.Event) { case ETIE_PRESSED_DOWN: m_pointer = v2s32(event.TouchInput.X, event.TouchInput.Y); translated.MouseInput.Event = EMIE_LMOUSE_PRESSED_DOWN; translated.MouseInput.ButtonStates = EMBSM_LEFT; m_down_pos = m_pointer; break; case ETIE_MOVED: m_pointer = v2s32(event.TouchInput.X, event.TouchInput.Y); translated.MouseInput.Event = EMIE_MOUSE_MOVED; translated.MouseInput.ButtonStates = EMBSM_LEFT; break; case ETIE_LEFT_UP: translated.MouseInput.Event = EMIE_LMOUSE_LEFT_UP; translated.MouseInput.ButtonStates = 0; hovered = root->getElementFromPoint(m_down_pos); // we don't have a valid pointer element use last // known pointer pos translated.MouseInput.X = m_pointer.X; translated.MouseInput.Y = m_pointer.Y; // reset down pos m_down_pos = v2s32(0, 0); break; default: dont_send_event = true; // this is not supposed to happen errorstream << "GUIModalMenu::preprocessEvent" << " unexpected usecase Event=" << event.TouchInput.Event << std::endl; } } else if ((event.TouchInput.touchedCount == 2) && (event.TouchInput.Event == ETIE_PRESSED_DOWN)) { hovered = root->getElementFromPoint(m_down_pos); translated.MouseInput.Event = EMIE_RMOUSE_PRESSED_DOWN; translated.MouseInput.ButtonStates = EMBSM_LEFT | EMBSM_RIGHT; translated.MouseInput.X = m_pointer.X; translated.MouseInput.Y = m_pointer.Y; if (hovered) { hovered->OnEvent(translated); } translated.MouseInput.Event = EMIE_RMOUSE_LEFT_UP; translated.MouseInput.ButtonStates = EMBSM_LEFT; if (hovered) { hovered->OnEvent(translated); } dont_send_event = true; } // ignore unhandled 2 touch events ... accidental moving for example else if (event.TouchInput.touchedCount == 2) { dont_send_event = true; } else if (event.TouchInput.touchedCount > 2) { errorstream << "GUIModalMenu::preprocessEvent" << " to many multitouch events " << event.TouchInput.touchedCount << " ignoring them" << std::endl; } if (dont_send_event) { return true; } // check if translated event needs to be preprocessed again if (preprocessEvent(translated)) { return true; } if (hovered) { grab(); bool retval = hovered->OnEvent(translated); if (event.TouchInput.Event == ETIE_LEFT_UP) { // reset pointer m_pointer = v2s32(0, 0); } drop(); return retval; } } // clang-format on #endif return false; } #ifdef __ANDROID__ bool GUIModalMenu::hasAndroidUIInput() { // no dialog shown if (m_jni_field_name.empty()) { return false; } // still waiting if (porting::getInputDialogState() == -1) { return true; } // no value abort dialog processing if (porting::getInputDialogState() != 0) { m_jni_field_name.clear(); return false; } return true; } #endif
pgimeno/minetest
src/gui/modalMenu.cpp
C++
mit
7,936
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> 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. */ #pragma once #include "irrlichttypes_extrabloated.h" #include "util/string.h" class GUIModalMenu; class IMenuManager { public: // A GUIModalMenu calls these when this class is passed as a parameter virtual void createdMenu(gui::IGUIElement *menu) = 0; virtual void deletingMenu(gui::IGUIElement *menu) = 0; }; // Remember to drop() the menu after creating, so that it can // remove itself when it wants to. class GUIModalMenu : public gui::IGUIElement { public: GUIModalMenu(gui::IGUIEnvironment* env, gui::IGUIElement* parent, s32 id, IMenuManager *menumgr); virtual ~GUIModalMenu(); void allowFocusRemoval(bool allow); bool canTakeFocus(gui::IGUIElement *e); void draw(); void quitMenu(); void removeChildren(); virtual void regenerateGui(v2u32 screensize) = 0; virtual void drawMenu() = 0; virtual bool preprocessEvent(const SEvent& event); virtual bool OnEvent(const SEvent& event) { return false; }; virtual bool pausesGame() { return false; } // Used for pause menu #ifdef __ANDROID__ virtual bool getAndroidUIInput() { return false; } bool hasAndroidUIInput(); #endif protected: virtual std::wstring getLabelByID(s32 id) = 0; virtual std::string getNameByID(s32 id) = 0; v2s32 m_pointer; v2s32 m_old_pointer; // Mouse position after previous mouse event v2u32 m_screensize_old; float m_gui_scale; #ifdef __ANDROID__ v2s32 m_down_pos; std::string m_jni_field_name; #endif #ifdef HAVE_TOUCHSCREENGUI bool m_touchscreen_visible = true; #endif private: IMenuManager *m_menumgr; // This might be necessary to expose to the implementation if it // wants to launch other menus bool m_allow_focus_removal = false; };
pgimeno/minetest
src/gui/modalMenu.h
C++
mit
2,443
/* Minetest Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com> Copyright (C) 2018 nerzhul, Loic Blot <loic.blot@unix-experience.fr> 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 "porting.h" #include "profilergraph.h" #include "util/string.h" void ProfilerGraph::put(const Profiler::GraphValues &values) { m_log.emplace_back(values); while (m_log.size() > m_log_max_size) m_log.erase(m_log.begin()); } void ProfilerGraph::draw(s32 x_left, s32 y_bottom, video::IVideoDriver *driver, gui::IGUIFont *font) const { // Do *not* use UNORDERED_MAP here as the order needs // to be the same for each call to prevent flickering std::map<std::string, Meta> m_meta; for (const Piece &piece : m_log) { for (const auto &i : piece.values) { const std::string &id = i.first; const float &value = i.second; std::map<std::string, Meta>::iterator j = m_meta.find(id); if (j == m_meta.end()) { m_meta[id] = Meta(value); continue; } if (value < j->second.min) j->second.min = value; if (value > j->second.max) j->second.max = value; } } // Assign colors static const video::SColor usable_colors[] = {video::SColor(255, 255, 100, 100), video::SColor(255, 90, 225, 90), video::SColor(255, 100, 100, 255), video::SColor(255, 255, 150, 50), video::SColor(255, 220, 220, 100)}; static const u32 usable_colors_count = sizeof(usable_colors) / sizeof(*usable_colors); u32 next_color_i = 0; for (auto &i : m_meta) { Meta &meta = i.second; video::SColor color(255, 200, 200, 200); if (next_color_i < usable_colors_count) color = usable_colors[next_color_i++]; meta.color = color; } s32 graphh = 50; s32 textx = x_left + m_log_max_size + 15; s32 textx2 = textx + 200 - 15; s32 meta_i = 0; for (const auto &p : m_meta) { const std::string &id = p.first; const Meta &meta = p.second; s32 x = x_left; s32 y = y_bottom - meta_i * 50; float show_min = meta.min; float show_max = meta.max; if (show_min >= -0.0001 && show_max >= -0.0001) { if (show_min <= show_max * 0.5) show_min = 0; } s32 texth = 15; char buf[10]; porting::mt_snprintf(buf, sizeof(buf), "%.3g", show_max); font->draw(utf8_to_wide(buf).c_str(), core::rect<s32>(textx, y - graphh, textx2, y - graphh + texth), meta.color); porting::mt_snprintf(buf, sizeof(buf), "%.3g", show_min); font->draw(utf8_to_wide(buf).c_str(), core::rect<s32>(textx, y - texth, textx2, y), meta.color); font->draw(utf8_to_wide(id).c_str(), core::rect<s32>(textx, y - graphh / 2 - texth / 2, textx2, y - graphh / 2 + texth / 2), meta.color); s32 graph1y = y; s32 graph1h = graphh; bool relativegraph = (show_min != 0 && show_min != show_max); float lastscaledvalue = 0.0; bool lastscaledvalue_exists = false; for (const Piece &piece : m_log) { float value = 0; bool value_exists = false; Profiler::GraphValues::const_iterator k = piece.values.find(id); if (k != piece.values.end()) { value = k->second; value_exists = true; } if (!value_exists) { x++; lastscaledvalue_exists = false; continue; } float scaledvalue = 1.0; if (show_max != show_min) scaledvalue = (value - show_min) / (show_max - show_min); if (scaledvalue == 1.0 && value == 0) { x++; lastscaledvalue_exists = false; continue; } if (relativegraph) { if (lastscaledvalue_exists) { s32 ivalue1 = lastscaledvalue * graph1h; s32 ivalue2 = scaledvalue * graph1h; driver->draw2DLine( v2s32(x - 1, graph1y - ivalue1), v2s32(x, graph1y - ivalue2), meta.color); } lastscaledvalue = scaledvalue; lastscaledvalue_exists = true; } else { s32 ivalue = scaledvalue * graph1h; driver->draw2DLine(v2s32(x, graph1y), v2s32(x, graph1y - ivalue), meta.color); } x++; } meta_i++; } }
pgimeno/minetest
src/gui/profilergraph.cpp
C++
mit
4,570
/* Minetest Copyright (C) 2010-2018 celeron55, Perttu Ahola <celeron55@gmail.com> 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. */ #pragma once #include <SColor.h> #include <deque> #include <utility> #include <IGUIFont.h> #include <IVideoDriver.h> #include "profiler.h" /* Profiler display */ class ProfilerGraph { private: struct Piece { Piece(Profiler::GraphValues v) : values(std::move(v)) {} Profiler::GraphValues values; }; struct Meta { float min; float max; video::SColor color; Meta(float initial = 0, video::SColor color = video::SColor(255, 255, 255, 255)) : min(initial), max(initial), color(color) { } }; std::deque<Piece> m_log; public: u32 m_log_max_size = 200; ProfilerGraph() = default; void put(const Profiler::GraphValues &values); void draw(s32 x_left, s32 y_bottom, video::IVideoDriver *driver, gui::IGUIFont *font) const; };
pgimeno/minetest
src/gui/profilergraph.h
C++
mit
1,553
/* Copyright (C) 2014 sapier Copyright (C) 2018 srifqi, Muhammad Rifqi Priyo Susanto <muhammadrifqipriyosusanto@gmail.com> 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 "client/keycode.h" #include "settings.h" #include "gettime.h" #include "util/numeric.h" #include "porting.h" #include "client/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; const char **touchgui_button_imagenames = (const char *[]) { "jump_btn.png", "down.png", "zoom.png", "aux_btn.png" }; const char **touchgui_joystick_imagenames = (const char *[]) { "joystick_off.png", "joystick_bg.png", "joystick_center.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 zoom_id: key = "zoom"; break; case special1_id: key = "special1"; 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 toggle_chat_id: key = "toggle_chat"; break; case minimap_id: key = "minimap"; 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); } void AutoHideButtonBar::addToggleButton(touch_gui_button_id button_id, const wchar_t *caption, const char *btn_image_1, const char *btn_image_2) { addButton(button_id, caption, btn_image_1); button_info *btn = m_buttons.back(); btn->togglable = 1; btn->textures.push_back(btn_image_1); btn->textures.push_back(btn_image_2); } 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; if ((*iter)->togglable == 1) { (*iter)->togglable = 2; load_button_texture(*iter, (*iter)->textures[1], (*iter)->guibutton->getRelativePosition(), m_texturesource, m_driver); } else if ((*iter)->togglable == 2) { (*iter)->togglable = 1; load_button_texture(*iter, (*iter)->textures[0], (*iter)->guibutton->getRelativePosition(), m_texturesource, m_driver); } 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) { 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_touchscreen_threshold = g_settings->getU16("touchscreen_threshold"); m_fixed_joystick = g_settings->getBool("fixed_virtual_joystick"); m_joystick_triggers_special1 = g_settings->getBool("virtual_joystick_triggers_aux"); 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()); } button_info *TouchScreenGUI::initJoystickButton(touch_gui_button_id id, rect<s32> button_rect, int texture_id, bool visible) { button_info *btn = new button_info(); btn->guibutton = m_guienv->addButton(button_rect, 0, id, L"O"); btn->guibutton->setVisible(visible); btn->guibutton->grab(); btn->ids.clear(); load_button_texture(btn, touchgui_joystick_imagenames[texture_id], button_rect, m_texturesource, m_device->getVideoDriver()); return btn; } 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); u32 button_size = getGuiButtonSize(); m_visible = true; m_texturesource = tsrc; /* Init joystick display "button" * Joystick is placed on bottom left of screen. */ if (m_fixed_joystick) { m_joystick_btn_off = initJoystickButton(joystick_off_id, rect<s32>(button_size, m_screensize.Y - button_size * 4, button_size * 4, m_screensize.Y - button_size), 0); } else { m_joystick_btn_off = initJoystickButton(joystick_off_id, rect<s32>(button_size, m_screensize.Y - button_size * 3, button_size * 3, m_screensize.Y - button_size), 0); } m_joystick_btn_bg = initJoystickButton(joystick_bg_id, rect<s32>(button_size, m_screensize.Y - button_size * 4, button_size * 4, m_screensize.Y - button_size), 1, false); m_joystick_btn_center = initJoystickButton(joystick_center_id, rect<s32>(0, 0, button_size, button_size), 2, false); // init jump button initButton(jump_id, rect<s32>(m_screensize.X - (1.75 * button_size), m_screensize.Y - 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 - button_size, m_screensize.X - (1.75 * button_size), m_screensize.Y), L"H", false); // init zoom button initButton(zoom_id, rect<s32>(m_screensize.X - (1.25 * button_size), m_screensize.Y - (4 * button_size), m_screensize.X - (0.25 * button_size), m_screensize.Y - (3 * button_size)), L"z", false); // init special1/aux button if (!m_joystick_triggers_special1) initButton(special1_id, rect<s32>(m_screensize.X - (1.25 * button_size), m_screensize.Y - (2.5 * button_size), m_screensize.X - (0.25 * button_size), m_screensize.Y - (1.5 * button_size)), L"spc1", false); m_settingsbar.init(m_texturesource, "gear_icon.png", settings_starter_id, v2s32(m_screensize.X - (1.25 * button_size), m_screensize.Y - ((SETTINGS_BAR_Y_OFFSET + 1.0) * button_size) + (0.5 * button_size)), v2s32(m_screensize.X - (0.25 * button_size), m_screensize.Y - (SETTINGS_BAR_Y_OFFSET * button_size) + (0.5 * button_size)), 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_settingsbar.addButton(minimap_id, L"minimap", "minimap_btn.png"); // Chat is shown by default, so chat_hide_btn.png is shown first. m_settingsbar.addToggleButton(toggle_chat_id, L"togglechat", "chat_hide_btn.png", "chat_show_btn.png"); m_rarecontrolsbar.init(m_texturesource, "rare_controls.png", rare_controls_starter_id, v2s32(0.25 * button_size, m_screensize.Y - ((RARE_CONTROLS_BAR_Y_OFFSET + 1.0) * button_size) + (0.5 * button_size)), v2s32(0.75 * button_size, m_screensize.Y - (RARE_CONTROLS_BAR_Y_OFFSET * button_size) + (0.5 * button_size)), AHBB_Dir_Left_Right, 2.0); 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(); } } // handle joystick else if (evt_id == m_joystick_id) { m_joystick_id = -1; // reset joystick for (unsigned int i = 0; i < 4; i ++) m_joystick_status[i] = false; applyJoystickStatus(); m_joystick_btn_off->guibutton->setVisible(true); m_joystick_btn_bg->guibutton->setVisible(false); m_joystick_btn_center->guibutton->setVisible(false); } 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(); u32 button_size = getGuiButtonSize(); s32 dxj = event.TouchInput.X - button_size * 5 / 2; s32 dyj = event.TouchInput.Y - m_screensize.Y + button_size * 5 / 2; /* Select joystick when left 1/3 of screen dragged or * when joystick tapped (fixed joystick position) */ if ((m_fixed_joystick && dxj * dxj + dyj * dyj <= button_size * button_size * 1.5 * 1.5) || (!m_fixed_joystick && event.TouchInput.X < m_screensize.X / 3)) { // If we don't already have a starting point for joystick make this the one. if (m_joystick_id == -1) { m_joystick_id = event.TouchInput.ID; m_joystick_has_really_moved = false; m_joystick_btn_off->guibutton->setVisible(false); m_joystick_btn_bg->guibutton->setVisible(true); m_joystick_btn_center->guibutton->setVisible(true); // If it's a fixed joystick, don't move the joystick "button". if (!m_fixed_joystick) { m_joystick_btn_bg->guibutton->setRelativePosition(v2s32( event.TouchInput.X - button_size * 3 / 2, event.TouchInput.Y - button_size * 3 / 2)); } m_joystick_btn_center->guibutton->setRelativePosition(v2s32( event.TouchInput.X - button_size / 2, event.TouchInput.Y - button_size / 2)); } } else { // 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 > m_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)); } } if (m_joystick_id != -1 && event.TouchInput.ID == m_joystick_id) { u32 button_size = getGuiButtonSize(); s32 X = event.TouchInput.X; s32 Y = event.TouchInput.Y; s32 dx = X - m_pointerpos[event.TouchInput.ID].X; s32 dy = Y - m_pointerpos[event.TouchInput.ID].Y; if (m_fixed_joystick) { dx = X - button_size * 5 / 2; dy = Y - m_screensize.Y + button_size * 5 / 2; } double distance_sq = dx * dx + dy * dy; s32 dxj = event.TouchInput.X - button_size * 5 / 2; s32 dyj = event.TouchInput.Y - m_screensize.Y + button_size * 5 / 2; bool inside_joystick = (dxj * dxj + dyj * dyj <= button_size * button_size * 1.5 * 1.5); if (m_joystick_has_really_moved || (!m_joystick_has_really_moved && inside_joystick) || (!m_fixed_joystick && distance_sq > m_touchscreen_threshold * m_touchscreen_threshold)) { m_joystick_has_really_moved = true; double distance = sqrt(distance_sq); // angle in degrees double angle = acos(dx / distance) * 180 / M_PI; if (dy < 0) angle *= -1; // rotate to make comparing easier angle = fmod(angle + 180 + 22.5, 360); // reset state before applying for (unsigned int i = 0; i < 5; i ++) m_joystick_status[i] = false; if (distance <= m_touchscreen_threshold) { // do nothing } else if (angle < 45) m_joystick_status[j_left] = true; else if (angle < 90) { m_joystick_status[j_forward] = true; m_joystick_status[j_left] = true; } else if (angle < 135) m_joystick_status[j_forward] = true; else if (angle < 180) { m_joystick_status[j_forward] = true; m_joystick_status[j_right] = true; } else if (angle < 225) m_joystick_status[j_right] = true; else if (angle < 270) { m_joystick_status[j_backward] = true; m_joystick_status[j_right] = true; } else if (angle < 315) m_joystick_status[j_backward] = true; else if (angle <= 360) { m_joystick_status[j_backward] = true; m_joystick_status[j_left] = true; } if (distance > button_size) { m_joystick_status[j_special1] = true; // move joystick "button" s32 ndx = (s32) button_size * dx / distance - (s32) button_size / 2; s32 ndy = (s32) button_size * dy / distance - (s32) button_size / 2; if (m_fixed_joystick) { m_joystick_btn_center->guibutton->setRelativePosition(v2s32( button_size * 5 / 2 + ndx, m_screensize.Y - button_size * 5 / 2 + ndy)); } else { m_joystick_btn_center->guibutton->setRelativePosition(v2s32( m_pointerpos[event.TouchInput.ID].X + ndx, m_pointerpos[event.TouchInput.ID].Y + ndy)); } } else { m_joystick_btn_center->guibutton->setRelativePosition(v2s32( X - button_size / 2, Y - button_size / 2)); } } } if (m_move_id == -1 && m_joystick_id == -1) { 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 + m_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; } void TouchScreenGUI::applyJoystickStatus() { for (unsigned int i = 0; i < 5; i ++) { if (i == 4 && !m_joystick_triggers_special1) continue; SEvent translated{}; translated.EventType = irr::EET_KEY_INPUT_EVENT; translated.KeyInput.Key = id2keycode(m_joystick_names[i]); translated.KeyInput.PressedDown = false; m_receiver->OnEvent(translated); if (m_joystick_status[i]) { translated.KeyInput.PressedDown = true; m_receiver->OnEvent(translated); } } } TouchScreenGUI::~TouchScreenGUI() { for (unsigned int i = 0; i < after_last_element_id; i++) { button_info *btn = &m_buttons[i]; if (btn->guibutton) { btn->guibutton->drop(); btn->guibutton = NULL; } } if (m_joystick_btn_off->guibutton) { m_joystick_btn_off->guibutton->drop(); m_joystick_btn_off->guibutton = NULL; } if (m_joystick_btn_bg->guibutton) { m_joystick_btn_bg->guibutton->drop(); m_joystick_btn_bg->guibutton = NULL; } if (m_joystick_btn_center->guibutton) { m_joystick_btn_center->guibutton->drop(); m_joystick_btn_center->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); } } // joystick applyJoystickStatus(); // 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) { btn->guibutton->setVisible(visible); } } if (m_joystick_btn_off->guibutton) { m_joystick_btn_off->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); }
pgimeno/minetest
src/gui/touchscreengui.cpp
C++
mit
36,944
/* 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. */ #pragma once #include <IEventReceiver.h> #include <IGUIButton.h> #include <IGUIEnvironment.h> #include <IrrlichtDevice.h> #include <map> #include <vector> #include "client/tile.h" #include "client/game.h" using namespace irr; using namespace irr::core; using namespace irr::gui; typedef enum { jump_id = 0, crunch_id, zoom_id, special1_id, after_last_element_id, settings_starter_id, rare_controls_starter_id, fly_id, noclip_id, fast_id, debug_id, camera_id, range_id, minimap_id, toggle_chat_id, chat_id, inventory_id, drop_id, forward_id, backward_id, left_id, right_id, joystick_off_id, joystick_bg_id, joystick_center_id } touch_gui_button_id; typedef enum { j_forward = 0, j_backward, j_left, j_right, j_special1 } touch_gui_joystick_move_id; typedef enum { AHBB_Dir_Top_Bottom, AHBB_Dir_Bottom_Top, AHBB_Dir_Left_Right, AHBB_Dir_Right_Left } autohide_button_bar_dir; #define MIN_DIG_TIME_MS 500 #define MAX_TOUCH_COUNT 64 #define BUTTON_REPEAT_DELAY 0.2f #define SETTINGS_BAR_Y_OFFSET 5 #define RARE_CONTROLS_BAR_Y_OFFSET 5 extern const char **touchgui_button_imagenames; extern const char **touchgui_joystick_imagenames; struct button_info { float repeatcounter; float repeatdelay; irr::EKEY_CODE keycode; std::vector<int> ids; IGUIButton *guibutton = nullptr; bool immediate_release; // 0: false, 1: (true) first texture, 2: (true) second texture int togglable = 0; std::vector<const char *> textures; }; class AutoHideButtonBar { public: AutoHideButtonBar(IrrlichtDevice *device, IEventReceiver *receiver); void init(ISimpleTextureSource *tsrc, const char *starter_img, int button_id, v2s32 UpperLeft, v2s32 LowerRight, autohide_button_bar_dir dir, float timeout); ~AutoHideButtonBar(); // add button to be shown void addButton(touch_gui_button_id id, const wchar_t *caption, const char *btn_image); // add toggle button to be shown void addToggleButton(touch_gui_button_id id, const wchar_t *caption, const char *btn_image_1, const char *btn_image_2); // detect settings bar button events bool isButton(const SEvent &event); // handle released hud buttons bool isReleaseButton(int eventID); // step handler void step(float dtime); // deactivate button bar void deactivate(); // hide the whole buttonbar void hide(); // unhide the buttonbar void show(); private: ISimpleTextureSource *m_texturesource = nullptr; irr::video::IVideoDriver *m_driver; IGUIEnvironment *m_guienv; IEventReceiver *m_receiver; button_info m_starter; std::vector<button_info *> m_buttons; v2s32 m_upper_left; v2s32 m_lower_right; // show settings bar bool m_active = false; bool m_visible = true; // settings bar timeout float m_timeout = 0.0f; float m_timeout_value = 3.0f; bool m_initialized = false; autohide_button_bar_dir m_dir = AHBB_Dir_Right_Left; }; class TouchScreenGUI { public: TouchScreenGUI(IrrlichtDevice *device, IEventReceiver *receiver); ~TouchScreenGUI(); void translateEvent(const SEvent &event); void init(ISimpleTextureSource *tsrc); double getYawChange() { double res = m_camera_yaw_change; m_camera_yaw_change = 0; return res; } double getPitch() { return m_camera_pitch; } /*! * Returns a line which describes what the player is pointing at. * The starting point and looking direction are significant, * the line should be scaled to match its length to the actual distance * the player can reach. * The line starts at the camera and ends on the camera's far plane. * The coordinates do not contain the camera offset. */ line3d<f32> getShootline() { return m_shootline; } void step(float dtime); void resetHud(); void registerHudItem(int index, const rect<s32> &rect); void Toggle(bool visible); void hide(); void show(); private: IrrlichtDevice *m_device; IGUIEnvironment *m_guienv; IEventReceiver *m_receiver; ISimpleTextureSource *m_texturesource; v2u32 m_screensize; double m_touchscreen_threshold; std::map<int, rect<s32>> m_hud_rects; std::map<int, irr::EKEY_CODE> m_hud_ids; bool m_visible; // is the gui visible // value in degree double m_camera_yaw_change = 0.0; double m_camera_pitch = 0.0; // forward, backward, left, right touch_gui_button_id m_joystick_names[5] = { forward_id, backward_id, left_id, right_id, special1_id}; bool m_joystick_status[5] = {false, false, false, false, false}; /*! * A line starting at the camera and pointing towards the * selected object. * The line ends on the camera's far plane. * The coordinates do not contain the camera offset. */ line3d<f32> m_shootline; int m_move_id = -1; bool m_move_has_really_moved = false; s64 m_move_downtime = 0; bool m_move_sent_as_mouse_event = false; v2s32 m_move_downlocation = v2s32(-10000, -10000); int m_joystick_id = -1; bool m_joystick_has_really_moved = false; bool m_fixed_joystick = false; bool m_joystick_triggers_special1 = false; button_info *m_joystick_btn_off = nullptr; button_info *m_joystick_btn_bg = nullptr; button_info *m_joystick_btn_center = nullptr; button_info m_buttons[after_last_element_id]; // gui button detection touch_gui_button_id getButtonID(s32 x, s32 y); // gui button by eventID touch_gui_button_id getButtonID(int eventID); // check if a button has changed void handleChangedButton(const SEvent &event); // initialize a button void initButton(touch_gui_button_id id, rect<s32> button_rect, std::wstring caption, bool immediate_release, float repeat_delay = BUTTON_REPEAT_DELAY); // initialize a joystick button button_info *initJoystickButton(touch_gui_button_id id, rect<s32> button_rect, int texture_id, bool visible = true); struct id_status { int id; int X; int Y; }; // vector to store known ids and their initial touch positions std::vector<id_status> m_known_ids; // handle a button event void handleButtonEvent(touch_gui_button_id bID, int eventID, bool action); // handle pressed hud buttons bool isHUDButton(const SEvent &event); // handle released hud buttons bool isReleaseHUDButton(int eventID); // handle double taps bool doubleTapDetection(); // handle release event void handleReleaseEvent(int evt_id); // apply joystick status void applyJoystickStatus(); // get size of regular gui control button int getGuiButtonSize(); // doubleclick detection variables struct key_event { unsigned int down_time; s32 x; s32 y; }; // array for saving last known position of a pointer v2s32 m_pointerpos[MAX_TOUCH_COUNT]; // array for doubletap detection key_event m_key_events[2]; // settings bar AutoHideButtonBar m_settingsbar; // rare controls bar AutoHideButtonBar m_rarecontrolsbar; }; extern TouchScreenGUI *g_touchscreengui;
pgimeno/minetest
src/gui/touchscreengui.h
C++
mit
7,488
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> 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 "httpfetch.h" #include "porting.h" // for sleep_ms(), get_sysinfo(), secure_rand_fill_buf() #include <iostream> #include <sstream> #include <list> #include <map> #include <cerrno> #include <mutex> #include "network/socket.h" // for select() #include "threading/event.h" #include "config.h" #include "exceptions.h" #include "debug.h" #include "log.h" #include "util/container.h" #include "util/thread.h" #include "version.h" #include "settings.h" #include "noise.h" std::mutex g_httpfetch_mutex; std::map<unsigned long, std::queue<HTTPFetchResult> > g_httpfetch_results; PcgRandom g_callerid_randomness; HTTPFetchRequest::HTTPFetchRequest() : timeout(g_settings->getS32("curl_timeout")), connect_timeout(timeout), useragent(std::string(PROJECT_NAME_C "/") + g_version_hash + " (" + porting::get_sysinfo() + ")") { } static void httpfetch_deliver_result(const HTTPFetchResult &fetch_result) { unsigned long caller = fetch_result.caller; if (caller != HTTPFETCH_DISCARD) { MutexAutoLock lock(g_httpfetch_mutex); g_httpfetch_results[caller].push(fetch_result); } } static void httpfetch_request_clear(unsigned long caller); unsigned long httpfetch_caller_alloc() { MutexAutoLock lock(g_httpfetch_mutex); // Check each caller ID except HTTPFETCH_DISCARD const unsigned long discard = HTTPFETCH_DISCARD; for (unsigned long caller = discard + 1; caller != discard; ++caller) { std::map<unsigned long, std::queue<HTTPFetchResult> >::iterator it = g_httpfetch_results.find(caller); if (it == g_httpfetch_results.end()) { verbosestream << "httpfetch_caller_alloc: allocating " << caller << std::endl; // Access element to create it g_httpfetch_results[caller]; return caller; } } FATAL_ERROR("httpfetch_caller_alloc: ran out of caller IDs"); return discard; } unsigned long httpfetch_caller_alloc_secure() { MutexAutoLock lock(g_httpfetch_mutex); // Generate random caller IDs and make sure they're not // already used or equal to HTTPFETCH_DISCARD // Give up after 100 tries to prevent infinite loop u8 tries = 100; unsigned long caller; do { caller = (((u64) g_callerid_randomness.next()) << 32) | g_callerid_randomness.next(); if (--tries < 1) { FATAL_ERROR("httpfetch_caller_alloc_secure: ran out of caller IDs"); return HTTPFETCH_DISCARD; } } while (g_httpfetch_results.find(caller) != g_httpfetch_results.end()); verbosestream << "httpfetch_caller_alloc_secure: allocating " << caller << std::endl; // Access element to create it g_httpfetch_results[caller]; return caller; } void httpfetch_caller_free(unsigned long caller) { verbosestream<<"httpfetch_caller_free: freeing " <<caller<<std::endl; httpfetch_request_clear(caller); if (caller != HTTPFETCH_DISCARD) { MutexAutoLock lock(g_httpfetch_mutex); g_httpfetch_results.erase(caller); } } bool httpfetch_async_get(unsigned long caller, HTTPFetchResult &fetch_result) { MutexAutoLock lock(g_httpfetch_mutex); // Check that caller exists std::map<unsigned long, std::queue<HTTPFetchResult> >::iterator it = g_httpfetch_results.find(caller); if (it == g_httpfetch_results.end()) return false; // Check that result queue is nonempty std::queue<HTTPFetchResult> &caller_results = it->second; if (caller_results.empty()) return false; // Pop first result fetch_result = caller_results.front(); caller_results.pop(); return true; } #if USE_CURL #include <curl/curl.h> /* USE_CURL is on: use cURL based httpfetch implementation */ static size_t httpfetch_writefunction( char *ptr, size_t size, size_t nmemb, void *userdata) { std::ostringstream *stream = (std::ostringstream*)userdata; size_t count = size * nmemb; stream->write(ptr, count); return count; } static size_t httpfetch_discardfunction( char *ptr, size_t size, size_t nmemb, void *userdata) { return size * nmemb; } class CurlHandlePool { std::list<CURL*> handles; public: CurlHandlePool() = default; ~CurlHandlePool() { for (std::list<CURL*>::iterator it = handles.begin(); it != handles.end(); ++it) { curl_easy_cleanup(*it); } } CURL * alloc() { CURL *curl; if (handles.empty()) { curl = curl_easy_init(); if (curl == NULL) { errorstream<<"curl_easy_init returned NULL"<<std::endl; } } else { curl = handles.front(); handles.pop_front(); } return curl; } void free(CURL *handle) { if (handle) handles.push_back(handle); } }; class HTTPFetchOngoing { public: HTTPFetchOngoing(const HTTPFetchRequest &request, CurlHandlePool *pool); ~HTTPFetchOngoing(); CURLcode start(CURLM *multi); const HTTPFetchResult * complete(CURLcode res); const HTTPFetchRequest &getRequest() const { return request; }; const CURL *getEasyHandle() const { return curl; }; private: CurlHandlePool *pool; CURL *curl; CURLM *multi; HTTPFetchRequest request; HTTPFetchResult result; std::ostringstream oss; struct curl_slist *http_header; curl_httppost *post; }; HTTPFetchOngoing::HTTPFetchOngoing(const HTTPFetchRequest &request_, CurlHandlePool *pool_): pool(pool_), curl(NULL), multi(NULL), request(request_), result(request_), oss(std::ios::binary), http_header(NULL), post(NULL) { curl = pool->alloc(); if (curl == NULL) { return; } // Set static cURL options curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1); curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1); curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1); curl_easy_setopt(curl, CURLOPT_MAXREDIRS, 3); curl_easy_setopt(curl, CURLOPT_ENCODING, "gzip"); std::string bind_address = g_settings->get("bind_address"); if (!bind_address.empty()) { curl_easy_setopt(curl, CURLOPT_INTERFACE, bind_address.c_str()); } if (!g_settings->getBool("enable_ipv6")) { curl_easy_setopt(curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4); } #if LIBCURL_VERSION_NUM >= 0x071304 // Restrict protocols so that curl vulnerabilities in // other protocols don't affect us. // These settings were introduced in curl 7.19.4. long protocols = CURLPROTO_HTTP | CURLPROTO_HTTPS | CURLPROTO_FTP | CURLPROTO_FTPS; curl_easy_setopt(curl, CURLOPT_PROTOCOLS, protocols); curl_easy_setopt(curl, CURLOPT_REDIR_PROTOCOLS, protocols); #endif // Set cURL options based on HTTPFetchRequest curl_easy_setopt(curl, CURLOPT_URL, request.url.c_str()); curl_easy_setopt(curl, CURLOPT_TIMEOUT_MS, request.timeout); curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT_MS, request.connect_timeout); if (!request.useragent.empty()) curl_easy_setopt(curl, CURLOPT_USERAGENT, request.useragent.c_str()); // Set up a write callback that writes to the // ostringstream ongoing->oss, unless the data // is to be discarded if (request.caller == HTTPFETCH_DISCARD) { curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, httpfetch_discardfunction); curl_easy_setopt(curl, CURLOPT_WRITEDATA, NULL); } else { curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, httpfetch_writefunction); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &oss); } // Set POST (or GET) data if (request.post_fields.empty() && request.post_data.empty()) { curl_easy_setopt(curl, CURLOPT_HTTPGET, 1); } else if (request.multipart) { curl_httppost *last = NULL; for (StringMap::iterator it = request.post_fields.begin(); it != request.post_fields.end(); ++it) { curl_formadd(&post, &last, CURLFORM_NAMELENGTH, it->first.size(), CURLFORM_PTRNAME, it->first.c_str(), CURLFORM_CONTENTSLENGTH, it->second.size(), CURLFORM_PTRCONTENTS, it->second.c_str(), CURLFORM_END); } curl_easy_setopt(curl, CURLOPT_HTTPPOST, post); // request.post_fields must now *never* be // modified until CURLOPT_HTTPPOST is cleared } else if (request.post_data.empty()) { curl_easy_setopt(curl, CURLOPT_POST, 1); std::string str; for (auto &post_field : request.post_fields) { if (!str.empty()) str += "&"; str += urlencode(post_field.first); str += "="; str += urlencode(post_field.second); } curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, str.size()); curl_easy_setopt(curl, CURLOPT_COPYPOSTFIELDS, str.c_str()); } else { curl_easy_setopt(curl, CURLOPT_POST, 1); curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, request.post_data.size()); curl_easy_setopt(curl, CURLOPT_POSTFIELDS, request.post_data.c_str()); // request.post_data must now *never* be // modified until CURLOPT_POSTFIELDS is cleared } // Set additional HTTP headers for (const std::string &extra_header : request.extra_headers) { http_header = curl_slist_append(http_header, extra_header.c_str()); } curl_easy_setopt(curl, CURLOPT_HTTPHEADER, http_header); if (!g_settings->getBool("curl_verify_cert")) { curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, false); } } CURLcode HTTPFetchOngoing::start(CURLM *multi_) { if (!curl) return CURLE_FAILED_INIT; if (!multi_) { // Easy interface (sync) return curl_easy_perform(curl); } // Multi interface (async) CURLMcode mres = curl_multi_add_handle(multi_, curl); if (mres != CURLM_OK) { errorstream << "curl_multi_add_handle" << " returned error code " << mres << std::endl; return CURLE_FAILED_INIT; } multi = multi_; // store for curl_multi_remove_handle return CURLE_OK; } const HTTPFetchResult * HTTPFetchOngoing::complete(CURLcode res) { result.succeeded = (res == CURLE_OK); result.timeout = (res == CURLE_OPERATION_TIMEDOUT); result.data = oss.str(); // Get HTTP/FTP response code result.response_code = 0; if (curl && (curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &result.response_code) != CURLE_OK)) { // We failed to get a return code, make sure it is still 0 result.response_code = 0; } if (res != CURLE_OK) { errorstream << request.url << " not found (" << curl_easy_strerror(res) << ")" << " (response code " << result.response_code << ")" << std::endl; } return &result; } HTTPFetchOngoing::~HTTPFetchOngoing() { if (multi) { CURLMcode mres = curl_multi_remove_handle(multi, curl); if (mres != CURLM_OK) { errorstream << "curl_multi_remove_handle" << " returned error code " << mres << std::endl; } } // Set safe options for the reusable cURL handle curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, httpfetch_discardfunction); curl_easy_setopt(curl, CURLOPT_WRITEDATA, NULL); curl_easy_setopt(curl, CURLOPT_POSTFIELDS, NULL); if (http_header) { curl_easy_setopt(curl, CURLOPT_HTTPHEADER, NULL); curl_slist_free_all(http_header); } if (post) { curl_easy_setopt(curl, CURLOPT_HTTPPOST, NULL); curl_formfree(post); } // Store the cURL handle for reuse pool->free(curl); } class CurlFetchThread : public Thread { protected: enum RequestType { RT_FETCH, RT_CLEAR, RT_WAKEUP, }; struct Request { RequestType type; HTTPFetchRequest fetch_request; Event *event; }; CURLM *m_multi; MutexedQueue<Request> m_requests; size_t m_parallel_limit; // Variables exclusively used within thread std::vector<HTTPFetchOngoing*> m_all_ongoing; std::list<HTTPFetchRequest> m_queued_fetches; public: CurlFetchThread(int parallel_limit) : Thread("CurlFetch") { if (parallel_limit >= 1) m_parallel_limit = parallel_limit; else m_parallel_limit = 1; } void requestFetch(const HTTPFetchRequest &fetch_request) { Request req; req.type = RT_FETCH; req.fetch_request = fetch_request; req.event = NULL; m_requests.push_back(req); } void requestClear(unsigned long caller, Event *event) { Request req; req.type = RT_CLEAR; req.fetch_request.caller = caller; req.event = event; m_requests.push_back(req); } void requestWakeUp() { Request req; req.type = RT_WAKEUP; req.event = NULL; m_requests.push_back(req); } protected: // Handle a request from some other thread // E.g. new fetch; clear fetches for one caller; wake up void processRequest(const Request &req) { if (req.type == RT_FETCH) { // New fetch, queue until there are less // than m_parallel_limit ongoing fetches m_queued_fetches.push_back(req.fetch_request); // see processQueued() for what happens next } else if (req.type == RT_CLEAR) { unsigned long caller = req.fetch_request.caller; // Abort all ongoing fetches for the caller for (std::vector<HTTPFetchOngoing*>::iterator it = m_all_ongoing.begin(); it != m_all_ongoing.end();) { if ((*it)->getRequest().caller == caller) { delete (*it); it = m_all_ongoing.erase(it); } else { ++it; } } // Also abort all queued fetches for the caller for (std::list<HTTPFetchRequest>::iterator it = m_queued_fetches.begin(); it != m_queued_fetches.end();) { if ((*it).caller == caller) it = m_queued_fetches.erase(it); else ++it; } } else if (req.type == RT_WAKEUP) { // Wakeup: Nothing to do, thread is awake at this point } if (req.event != NULL) req.event->signal(); } // Start new ongoing fetches if m_parallel_limit allows void processQueued(CurlHandlePool *pool) { while (m_all_ongoing.size() < m_parallel_limit && !m_queued_fetches.empty()) { HTTPFetchRequest request = m_queued_fetches.front(); m_queued_fetches.pop_front(); // Create ongoing fetch data and make a cURL handle // Set cURL options based on HTTPFetchRequest HTTPFetchOngoing *ongoing = new HTTPFetchOngoing(request, pool); // Initiate the connection (curl_multi_add_handle) CURLcode res = ongoing->start(m_multi); if (res == CURLE_OK) { m_all_ongoing.push_back(ongoing); } else { httpfetch_deliver_result(*ongoing->complete(res)); delete ongoing; } } } // Process CURLMsg (indicates completion of a fetch) void processCurlMessage(CURLMsg *msg) { // Determine which ongoing fetch the message pertains to size_t i = 0; bool found = false; for (i = 0; i < m_all_ongoing.size(); ++i) { if (m_all_ongoing[i]->getEasyHandle() == msg->easy_handle) { found = true; break; } } if (msg->msg == CURLMSG_DONE && found) { // m_all_ongoing[i] succeeded or failed. HTTPFetchOngoing *ongoing = m_all_ongoing[i]; httpfetch_deliver_result(*ongoing->complete(msg->data.result)); delete ongoing; m_all_ongoing.erase(m_all_ongoing.begin() + i); } } // Wait for a request from another thread, or timeout elapses void waitForRequest(long timeout) { if (m_queued_fetches.empty()) { try { Request req = m_requests.pop_front(timeout); processRequest(req); } catch (ItemNotFoundException &e) {} } } // Wait until some IO happens, or timeout elapses void waitForIO(long timeout) { fd_set read_fd_set; fd_set write_fd_set; fd_set exc_fd_set; int max_fd; long select_timeout = -1; struct timeval select_tv; CURLMcode mres; FD_ZERO(&read_fd_set); FD_ZERO(&write_fd_set); FD_ZERO(&exc_fd_set); mres = curl_multi_fdset(m_multi, &read_fd_set, &write_fd_set, &exc_fd_set, &max_fd); if (mres != CURLM_OK) { errorstream<<"curl_multi_fdset" <<" returned error code "<<mres <<std::endl; select_timeout = 0; } mres = curl_multi_timeout(m_multi, &select_timeout); if (mres != CURLM_OK) { errorstream<<"curl_multi_timeout" <<" returned error code "<<mres <<std::endl; select_timeout = 0; } // Limit timeout so new requests get through if (select_timeout < 0 || select_timeout > timeout) select_timeout = timeout; if (select_timeout > 0) { // in Winsock it is forbidden to pass three empty // fd_sets to select(), so in that case use sleep_ms if (max_fd != -1) { select_tv.tv_sec = select_timeout / 1000; select_tv.tv_usec = (select_timeout % 1000) * 1000; int retval = select(max_fd + 1, &read_fd_set, &write_fd_set, &exc_fd_set, &select_tv); if (retval == -1) { #ifdef _WIN32 errorstream<<"select returned error code " <<WSAGetLastError()<<std::endl; #else errorstream<<"select returned error code " <<errno<<std::endl; #endif } } else { sleep_ms(select_timeout); } } } void *run() { CurlHandlePool pool; m_multi = curl_multi_init(); if (m_multi == NULL) { errorstream<<"curl_multi_init returned NULL\n"; return NULL; } FATAL_ERROR_IF(!m_all_ongoing.empty(), "Expected empty"); while (!stopRequested()) { BEGIN_DEBUG_EXCEPTION_HANDLER /* Handle new async requests */ while (!m_requests.empty()) { Request req = m_requests.pop_frontNoEx(); processRequest(req); } processQueued(&pool); /* Handle ongoing async requests */ int still_ongoing = 0; while (curl_multi_perform(m_multi, &still_ongoing) == CURLM_CALL_MULTI_PERFORM) /* noop */; /* Handle completed async requests */ if (still_ongoing < (int) m_all_ongoing.size()) { CURLMsg *msg; int msgs_in_queue; msg = curl_multi_info_read(m_multi, &msgs_in_queue); while (msg != NULL) { processCurlMessage(msg); msg = curl_multi_info_read(m_multi, &msgs_in_queue); } } /* If there are ongoing requests, wait for data (with a timeout of 100ms so that new requests can be processed). If no ongoing requests, wait for a new request. (Possibly an empty request that signals that the thread should be stopped.) */ if (m_all_ongoing.empty()) waitForRequest(100000000); else waitForIO(100); END_DEBUG_EXCEPTION_HANDLER } // Call curl_multi_remove_handle and cleanup easy handles for (HTTPFetchOngoing *i : m_all_ongoing) { delete i; } m_all_ongoing.clear(); m_queued_fetches.clear(); CURLMcode mres = curl_multi_cleanup(m_multi); if (mres != CURLM_OK) { errorstream<<"curl_multi_cleanup" <<" returned error code "<<mres <<std::endl; } return NULL; } }; CurlFetchThread *g_httpfetch_thread = NULL; void httpfetch_init(int parallel_limit) { verbosestream<<"httpfetch_init: parallel_limit="<<parallel_limit <<std::endl; CURLcode res = curl_global_init(CURL_GLOBAL_DEFAULT); FATAL_ERROR_IF(res != CURLE_OK, "CURL init failed"); g_httpfetch_thread = new CurlFetchThread(parallel_limit); // Initialize g_callerid_randomness for httpfetch_caller_alloc_secure u64 randbuf[2]; porting::secure_rand_fill_buf(randbuf, sizeof(u64) * 2); g_callerid_randomness = PcgRandom(randbuf[0], randbuf[1]); } void httpfetch_cleanup() { verbosestream<<"httpfetch_cleanup: cleaning up"<<std::endl; g_httpfetch_thread->stop(); g_httpfetch_thread->requestWakeUp(); g_httpfetch_thread->wait(); delete g_httpfetch_thread; curl_global_cleanup(); } void httpfetch_async(const HTTPFetchRequest &fetch_request) { g_httpfetch_thread->requestFetch(fetch_request); if (!g_httpfetch_thread->isRunning()) g_httpfetch_thread->start(); } static void httpfetch_request_clear(unsigned long caller) { if (g_httpfetch_thread->isRunning()) { Event event; g_httpfetch_thread->requestClear(caller, &event); event.wait(); } else { g_httpfetch_thread->requestClear(caller, NULL); } } void httpfetch_sync(const HTTPFetchRequest &fetch_request, HTTPFetchResult &fetch_result) { // Create ongoing fetch data and make a cURL handle // Set cURL options based on HTTPFetchRequest CurlHandlePool pool; HTTPFetchOngoing ongoing(fetch_request, &pool); // Do the fetch (curl_easy_perform) CURLcode res = ongoing.start(NULL); // Update fetch result fetch_result = *ongoing.complete(res); } #else // USE_CURL /* USE_CURL is off: Dummy httpfetch implementation that always returns an error. */ void httpfetch_init(int parallel_limit) { } void httpfetch_cleanup() { } void httpfetch_async(const HTTPFetchRequest &fetch_request) { errorstream << "httpfetch_async: unable to fetch " << fetch_request.url << " because USE_CURL=0" << std::endl; HTTPFetchResult fetch_result(fetch_request); // sets succeeded = false etc. httpfetch_deliver_result(fetch_result); } static void httpfetch_request_clear(unsigned long caller) { } void httpfetch_sync(const HTTPFetchRequest &fetch_request, HTTPFetchResult &fetch_result) { errorstream << "httpfetch_sync: unable to fetch " << fetch_request.url << " because USE_CURL=0" << std::endl; fetch_result = HTTPFetchResult(fetch_request); // sets succeeded = false etc. } #endif // USE_CURL
pgimeno/minetest
src/httpfetch.cpp
C++
mit
21,067
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> 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. */ #pragma once #include <vector> #include "util/string.h" #include "config.h" // Can be used in place of "caller" in asynchronous transfers to discard result // (used as default value of "caller") #define HTTPFETCH_DISCARD 0 #define HTTPFETCH_SYNC 1 struct HTTPFetchRequest { std::string url = ""; // Identifies the caller (for asynchronous requests) // Ignored by httpfetch_sync unsigned long caller = HTTPFETCH_DISCARD; // Some number that identifies the request // (when the same caller issues multiple httpfetch_async calls) unsigned long request_id = 0; // Timeout for the whole transfer, in milliseconds long timeout; // Timeout for the connection phase, in milliseconds long connect_timeout; // Indicates if this is multipart/form-data or // application/x-www-form-urlencoded. POST-only. bool multipart = false; // POST fields. Fields are escaped properly. // If this is empty a GET request is done instead. StringMap post_fields; // Raw POST data, overrides post_fields. std::string post_data; // If not empty, should contain entries such as "Accept: text/html" std::vector<std::string> extra_headers; // useragent to use std::string useragent; HTTPFetchRequest(); }; struct HTTPFetchResult { bool succeeded = false; bool timeout = false; long response_code = 0; std::string data = ""; // The caller and request_id from the corresponding HTTPFetchRequest. unsigned long caller = HTTPFETCH_DISCARD; unsigned long request_id = 0; HTTPFetchResult() = default; HTTPFetchResult(const HTTPFetchRequest &fetch_request) : caller(fetch_request.caller), request_id(fetch_request.request_id) { } }; // Initializes the httpfetch module void httpfetch_init(int parallel_limit); // Stops the httpfetch thread and cleans up resources void httpfetch_cleanup(); // Starts an asynchronous HTTP fetch request void httpfetch_async(const HTTPFetchRequest &fetch_request); // If any fetch for the given caller ID is complete, removes it from the // result queue, sets the fetch result and returns true. Otherwise returns false. bool httpfetch_async_get(unsigned long caller, HTTPFetchResult &fetch_result); // Allocates a caller ID for httpfetch_async // Not required if you want to set caller = HTTPFETCH_DISCARD unsigned long httpfetch_caller_alloc(); // Allocates a non-predictable caller ID for httpfetch_async unsigned long httpfetch_caller_alloc_secure(); // Frees a caller ID allocated with httpfetch_caller_alloc // Note: This can be expensive, because the httpfetch thread is told // to stop any ongoing fetches for the given caller. void httpfetch_caller_free(unsigned long caller); // Performs a synchronous HTTP request. This blocks and therefore should // only be used from background threads. void httpfetch_sync(const HTTPFetchRequest &fetch_request, HTTPFetchResult &fetch_result);
pgimeno/minetest
src/httpfetch.h
C++
mit
3,631
/* Minetest Copyright (C) 2010-2018 celeron55, Perttu Ahola <celeron55@gmail.com> 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 "hud.h" #include <cmath> const struct EnumString es_HudElementType[] = { {HUD_ELEM_IMAGE, "image"}, {HUD_ELEM_TEXT, "text"}, {HUD_ELEM_STATBAR, "statbar"}, {HUD_ELEM_INVENTORY, "inventory"}, {HUD_ELEM_WAYPOINT, "waypoint"}, {0, NULL}, }; const struct EnumString es_HudElementStat[] = { {HUD_STAT_POS, "position"}, {HUD_STAT_POS, "pos"}, /* Deprecated, only for compatibility's sake */ {HUD_STAT_NAME, "name"}, {HUD_STAT_SCALE, "scale"}, {HUD_STAT_TEXT, "text"}, {HUD_STAT_NUMBER, "number"}, {HUD_STAT_ITEM, "item"}, {HUD_STAT_DIR, "direction"}, {HUD_STAT_ALIGN, "alignment"}, {HUD_STAT_OFFSET, "offset"}, {HUD_STAT_WORLD_POS, "world_pos"}, {0, NULL}, }; const struct EnumString es_HudBuiltinElement[] = { {HUD_FLAG_HOTBAR_VISIBLE, "hotbar"}, {HUD_FLAG_HEALTHBAR_VISIBLE, "healthbar"}, {HUD_FLAG_CROSSHAIR_VISIBLE, "crosshair"}, {HUD_FLAG_WIELDITEM_VISIBLE, "wielditem"}, {HUD_FLAG_BREATHBAR_VISIBLE, "breathbar"}, {HUD_FLAG_MINIMAP_VISIBLE, "minimap"}, {HUD_FLAG_MINIMAP_RADAR_VISIBLE, "minimap_radar"}, {0, NULL}, };
pgimeno/minetest
src/hud.cpp
C++
mit
1,904
/* Minetest Copyright (C) 2010-2013 kwolekr, Ryan Kwolek <kwolekr@minetest.net> Copyright (C) 2017 red-001 <red-001@outlook.ie> 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. */ #ifndef HUD_HEADER #define HUD_HEADER #include "irrlichttypes_extrabloated.h" #include <string> #include "common/c_types.h" #define HUD_DIR_LEFT_RIGHT 0 #define HUD_DIR_RIGHT_LEFT 1 #define HUD_DIR_TOP_BOTTOM 2 #define HUD_DIR_BOTTOM_TOP 3 #define HUD_CORNER_UPPER 0 #define HUD_CORNER_LOWER 1 #define HUD_CORNER_CENTER 2 // Note that these visibility flags do not determine if the hud items are // actually drawn, but rather, whether to draw the item should the rest // of the game state permit it. #define HUD_FLAG_HOTBAR_VISIBLE (1 << 0) #define HUD_FLAG_HEALTHBAR_VISIBLE (1 << 1) #define HUD_FLAG_CROSSHAIR_VISIBLE (1 << 2) #define HUD_FLAG_WIELDITEM_VISIBLE (1 << 3) #define HUD_FLAG_BREATHBAR_VISIBLE (1 << 4) #define HUD_FLAG_MINIMAP_VISIBLE (1 << 5) #define HUD_FLAG_MINIMAP_RADAR_VISIBLE (1 << 6) #define HUD_PARAM_HOTBAR_ITEMCOUNT 1 #define HUD_PARAM_HOTBAR_IMAGE 2 #define HUD_PARAM_HOTBAR_SELECTED_IMAGE 3 #define HUD_HOTBAR_ITEMCOUNT_DEFAULT 8 #define HUD_HOTBAR_ITEMCOUNT_MAX 32 #define HOTBAR_IMAGE_SIZE 48 enum HudElementType { HUD_ELEM_IMAGE = 0, HUD_ELEM_TEXT = 1, HUD_ELEM_STATBAR = 2, HUD_ELEM_INVENTORY = 3, HUD_ELEM_WAYPOINT = 4, }; enum HudElementStat { HUD_STAT_POS = 0, HUD_STAT_NAME, HUD_STAT_SCALE, HUD_STAT_TEXT, HUD_STAT_NUMBER, HUD_STAT_ITEM, HUD_STAT_DIR, HUD_STAT_ALIGN, HUD_STAT_OFFSET, HUD_STAT_WORLD_POS, HUD_STAT_SIZE }; struct HudElement { HudElementType type; v2f pos; std::string name; v2f scale; std::string text; u32 number; u32 item; u32 dir; v2f align; v2f offset; v3f world_pos; v2s32 size; }; extern const EnumString es_HudElementType[]; extern const EnumString es_HudElementStat[]; extern const EnumString es_HudBuiltinElement[]; #endif
pgimeno/minetest
src/hud.h
C++
mit
2,608
/* Minetest Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com> 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 "inventory.h" #include "serialization.h" #include "debug.h" #include <sstream> #include "log.h" #include "itemdef.h" #include "util/strfnd.h" #include "content_mapnode.h" // For loading legacy MaterialItems #include "nameidmapping.h" // For loading legacy MaterialItems #include "util/serialize.h" #include "util/string.h" /* ItemStack */ static content_t content_translate_from_19_to_internal(content_t c_from) { for (const auto &tt : trans_table_19) { if(tt[1] == c_from) { return tt[0]; } } return c_from; } ItemStack::ItemStack(const std::string &name_, u16 count_, u16 wear_, IItemDefManager *itemdef) : name(itemdef->getAlias(name_)), count(count_), wear(wear_) { if (name.empty() || count == 0) clear(); else if (itemdef->get(name).type == ITEM_TOOL) count = 1; } void ItemStack::serialize(std::ostream &os) const { if (empty()) return; // Check how many parts of the itemstring are needed int parts = 1; if(count != 1) parts = 2; if(wear != 0) parts = 3; if (!metadata.empty()) parts = 4; os<<serializeJsonStringIfNeeded(name); if(parts >= 2) os<<" "<<count; if(parts >= 3) os<<" "<<wear; if (parts >= 4) { os << " "; metadata.serialize(os); } } void ItemStack::deSerialize(std::istream &is, IItemDefManager *itemdef) { clear(); // Read name name = deSerializeJsonStringIfNeeded(is); // Skip space std::string tmp; std::getline(is, tmp, ' '); if(!tmp.empty()) throw SerializationError("Unexpected text after item name"); if(name == "MaterialItem") { // Obsoleted on 2011-07-30 u16 material; is>>material; u16 materialcount; is>>materialcount; // Convert old materials if(material <= 0xff) material = content_translate_from_19_to_internal(material); if(material > 0xfff) throw SerializationError("Too large material number"); // Convert old id to name NameIdMapping legacy_nimap; content_mapnode_get_name_id_mapping(&legacy_nimap); legacy_nimap.getName(material, name); if(name.empty()) name = "unknown_block"; if (itemdef) name = itemdef->getAlias(name); count = materialcount; } else if(name == "MaterialItem2") { // Obsoleted on 2011-11-16 u16 material; is>>material; u16 materialcount; is>>materialcount; if(material > 0xfff) throw SerializationError("Too large material number"); // Convert old id to name NameIdMapping legacy_nimap; content_mapnode_get_name_id_mapping(&legacy_nimap); legacy_nimap.getName(material, name); if(name.empty()) name = "unknown_block"; if (itemdef) name = itemdef->getAlias(name); count = materialcount; } else if(name == "node" || name == "NodeItem" || name == "MaterialItem3" || name == "craft" || name == "CraftItem") { // Obsoleted on 2012-01-07 std::string all; std::getline(is, all, '\n'); // First attempt to read inside "" Strfnd fnd(all); fnd.next("\""); // If didn't skip to end, we have ""s if(!fnd.at_end()){ name = fnd.next("\""); } else { // No luck, just read a word then fnd.start(all); name = fnd.next(" "); } fnd.skip_over(" "); if (itemdef) name = itemdef->getAlias(name); count = stoi(trim(fnd.next(""))); if(count == 0) count = 1; } else if(name == "MBOItem") { // Obsoleted on 2011-10-14 throw SerializationError("MBOItem not supported anymore"); } else if(name == "tool" || name == "ToolItem") { // Obsoleted on 2012-01-07 std::string all; std::getline(is, all, '\n'); // First attempt to read inside "" Strfnd fnd(all); fnd.next("\""); // If didn't skip to end, we have ""s if(!fnd.at_end()){ name = fnd.next("\""); } else { // No luck, just read a word then fnd.start(all); name = fnd.next(" "); } count = 1; // Then read wear fnd.skip_over(" "); if (itemdef) name = itemdef->getAlias(name); wear = stoi(trim(fnd.next(""))); } else { do // This loop is just to allow "break;" { // The real thing // Apply item aliases if (itemdef) name = itemdef->getAlias(name); // Read the count std::string count_str; std::getline(is, count_str, ' '); if (count_str.empty()) { count = 1; break; } count = stoi(count_str); // Read the wear std::string wear_str; std::getline(is, wear_str, ' '); if(wear_str.empty()) break; wear = stoi(wear_str); // Read metadata metadata.deSerialize(is); // In case fields are added after metadata, skip space here: //std::getline(is, tmp, ' '); //if(!tmp.empty()) // throw SerializationError("Unexpected text after metadata"); } while(false); } if (name.empty() || count == 0) clear(); else if (itemdef && itemdef->get(name).type == ITEM_TOOL) count = 1; } void ItemStack::deSerialize(const std::string &str, IItemDefManager *itemdef) { std::istringstream is(str, std::ios::binary); deSerialize(is, itemdef); } std::string ItemStack::getItemString() const { std::ostringstream os(std::ios::binary); serialize(os); return os.str(); } ItemStack ItemStack::addItem(ItemStack newitem, IItemDefManager *itemdef) { // If the item is empty or the position invalid, bail out if(newitem.empty()) { // nothing can be added trivially } // If this is an empty item, it's an easy job. else if(empty()) { const u16 stackMax = newitem.getStackMax(itemdef); *this = newitem; // If the item fits fully, delete it if (count <= stackMax) { newitem.clear(); } else { // Else the item does not fit fully. Return the rest. count = stackMax; newitem.remove(count); } } // If item name or metadata differs, bail out else if (name != newitem.name || metadata != newitem.metadata) { // cannot be added } // If the item fits fully, add counter and delete it else if(newitem.count <= freeSpace(itemdef)) { add(newitem.count); newitem.clear(); } // Else the item does not fit fully. Add all that fits and return // the rest. else { u16 freespace = freeSpace(itemdef); add(freespace); newitem.remove(freespace); } return newitem; } bool ItemStack::itemFits(ItemStack newitem, ItemStack *restitem, IItemDefManager *itemdef) const { // If the item is empty or the position invalid, bail out if(newitem.empty()) { // nothing can be added trivially } // If this is an empty item, it's an easy job. else if(empty()) { const u16 stackMax = newitem.getStackMax(itemdef); // If the item fits fully, delete it if (newitem.count <= stackMax) { newitem.clear(); } else { // Else the item does not fit fully. Return the rest. newitem.remove(stackMax); } } // If item name or metadata differs, bail out else if (name != newitem.name || metadata != newitem.metadata) { // cannot be added } // If the item fits fully, delete it else if(newitem.count <= freeSpace(itemdef)) { newitem.clear(); } // Else the item does not fit fully. Return the rest. else { u16 freespace = freeSpace(itemdef); newitem.remove(freespace); } if(restitem) *restitem = newitem; return newitem.empty(); } ItemStack ItemStack::takeItem(u32 takecount) { if(takecount == 0 || count == 0) return ItemStack(); ItemStack result = *this; if(takecount >= count) { // Take all clear(); } else { // Take part remove(takecount); result.count = takecount; } return result; } ItemStack ItemStack::peekItem(u32 peekcount) const { if(peekcount == 0 || count == 0) return ItemStack(); ItemStack result = *this; if(peekcount < count) result.count = peekcount; return result; } /* Inventory */ InventoryList::InventoryList(const std::string &name, u32 size, IItemDefManager *itemdef): m_name(name), m_size(size), m_itemdef(itemdef) { clearItems(); } void InventoryList::clearItems() { m_items.clear(); for (u32 i=0; i < m_size; i++) { m_items.emplace_back(); } //setDirty(true); } void InventoryList::setSize(u32 newsize) { if(newsize != m_items.size()) m_items.resize(newsize); m_size = newsize; } void InventoryList::setWidth(u32 newwidth) { m_width = newwidth; } void InventoryList::setName(const std::string &name) { m_name = name; } void InventoryList::serialize(std::ostream &os) const { //os.imbue(std::locale("C")); os<<"Width "<<m_width<<"\n"; for (const auto &item : m_items) { if (item.empty()) { os<<"Empty"; } else { os<<"Item "; item.serialize(os); } os<<"\n"; } os<<"EndInventoryList\n"; } void InventoryList::deSerialize(std::istream &is) { //is.imbue(std::locale("C")); clearItems(); u32 item_i = 0; m_width = 0; while (is.good()) { std::string line; std::getline(is, line, '\n'); std::istringstream iss(line); //iss.imbue(std::locale("C")); std::string name; std::getline(iss, name, ' '); if (name == "EndInventoryList") return; // This is a temporary backwards compatibility fix if (name == "end") return; if (name == "Width") { iss >> m_width; if (iss.fail()) throw SerializationError("incorrect width property"); } else if(name == "Item") { if(item_i > getSize() - 1) throw SerializationError("too many items"); ItemStack item; item.deSerialize(iss, m_itemdef); m_items[item_i++] = item; } else if(name == "Empty") { if(item_i > getSize() - 1) throw SerializationError("too many items"); m_items[item_i++].clear(); } } // Contents given to deSerialize() were not terminated properly: throw error. std::ostringstream ss; ss << "Malformatted inventory list. list=" << m_name << ", read " << item_i << " of " << getSize() << " ItemStacks." << std::endl; throw SerializationError(ss.str()); } InventoryList::InventoryList(const InventoryList &other) { *this = other; } InventoryList & InventoryList::operator = (const InventoryList &other) { m_items = other.m_items; m_size = other.m_size; m_width = other.m_width; m_name = other.m_name; m_itemdef = other.m_itemdef; //setDirty(true); return *this; } bool InventoryList::operator == (const InventoryList &other) const { if(m_size != other.m_size) return false; if(m_width != other.m_width) return false; if(m_name != other.m_name) return false; for(u32 i=0; i<m_items.size(); i++) { ItemStack s1 = m_items[i]; ItemStack s2 = other.m_items[i]; if(s1.name != s2.name || s1.wear!= s2.wear || s1.count != s2.count || s1.metadata != s2.metadata) return false; } return true; } const std::string &InventoryList::getName() const { return m_name; } u32 InventoryList::getSize() const { return m_items.size(); } u32 InventoryList::getWidth() const { return m_width; } u32 InventoryList::getUsedSlots() const { u32 num = 0; for (const auto &m_item : m_items) { if (!m_item.empty()) num++; } return num; } u32 InventoryList::getFreeSlots() const { return getSize() - getUsedSlots(); } const ItemStack& InventoryList::getItem(u32 i) const { assert(i < m_size); // Pre-condition return m_items[i]; } ItemStack& InventoryList::getItem(u32 i) { assert(i < m_size); // Pre-condition return m_items[i]; } ItemStack InventoryList::changeItem(u32 i, const ItemStack &newitem) { if(i >= m_items.size()) return newitem; ItemStack olditem = m_items[i]; m_items[i] = newitem; //setDirty(true); return olditem; } void InventoryList::deleteItem(u32 i) { assert(i < m_items.size()); // Pre-condition m_items[i].clear(); } ItemStack InventoryList::addItem(const ItemStack &newitem_) { ItemStack newitem = newitem_; if(newitem.empty()) return newitem; /* First try to find if it could be added to some existing items */ for(u32 i=0; i<m_items.size(); i++) { // Ignore empty slots if(m_items[i].empty()) continue; // Try adding newitem = addItem(i, newitem); if(newitem.empty()) return newitem; // All was eaten } /* Then try to add it to empty slots */ for(u32 i=0; i<m_items.size(); i++) { // Ignore unempty slots if(!m_items[i].empty()) continue; // Try adding newitem = addItem(i, newitem); if(newitem.empty()) return newitem; // All was eaten } // Return leftover return newitem; } ItemStack InventoryList::addItem(u32 i, const ItemStack &newitem) { if(i >= m_items.size()) return newitem; ItemStack leftover = m_items[i].addItem(newitem, m_itemdef); //if(leftover != newitem) // setDirty(true); return leftover; } bool InventoryList::itemFits(const u32 i, const ItemStack &newitem, ItemStack *restitem) const { if(i >= m_items.size()) { if(restitem) *restitem = newitem; return false; } return m_items[i].itemFits(newitem, restitem, m_itemdef); } bool InventoryList::roomForItem(const ItemStack &item_) const { ItemStack item = item_; ItemStack leftover; for(u32 i=0; i<m_items.size(); i++) { if(itemFits(i, item, &leftover)) return true; item = leftover; } return false; } bool InventoryList::containsItem(const ItemStack &item, bool match_meta) const { u32 count = item.count; if (count == 0) return true; for (auto i = m_items.rbegin(); i != m_items.rend(); ++i) { if (count == 0) break; if (i->name == item.name && (!match_meta || (i->metadata == item.metadata))) { if (i->count >= count) return true; count -= i->count; } } return false; } ItemStack InventoryList::removeItem(const ItemStack &item) { ItemStack removed; for (auto i = m_items.rbegin(); i != m_items.rend(); ++i) { if (i->name == item.name) { u32 still_to_remove = item.count - removed.count; removed.addItem(i->takeItem(still_to_remove), m_itemdef); if (removed.count == item.count) break; } } return removed; } ItemStack InventoryList::takeItem(u32 i, u32 takecount) { if(i >= m_items.size()) return ItemStack(); ItemStack taken = m_items[i].takeItem(takecount); //if(!taken.empty()) // setDirty(true); return taken; } void InventoryList::moveItemSomewhere(u32 i, InventoryList *dest, u32 count) { // Take item from source list ItemStack item1; if (count == 0) item1 = changeItem(i, ItemStack()); else item1 = takeItem(i, count); if (item1.empty()) return; // Try to add the item to destination list u32 dest_size = dest->getSize(); // First try all the non-empty slots for (u32 dest_i = 0; dest_i < dest_size; dest_i++) { if (!m_items[dest_i].empty()) { item1 = dest->addItem(dest_i, item1); if (item1.empty()) return; } } // Then try all the empty ones for (u32 dest_i = 0; dest_i < dest_size; dest_i++) { if (m_items[dest_i].empty()) { item1 = dest->addItem(dest_i, item1); if (item1.empty()) return; } } // If we reach this, the item was not fully added // Add the remaining part back to the source item addItem(i, item1); } u32 InventoryList::moveItem(u32 i, InventoryList *dest, u32 dest_i, u32 count, bool swap_if_needed, bool *did_swap) { if(this == dest && i == dest_i) return count; // Take item from source list ItemStack item1; if(count == 0) item1 = changeItem(i, ItemStack()); else item1 = takeItem(i, count); if(item1.empty()) return 0; // Try to add the item to destination list u32 oldcount = item1.count; item1 = dest->addItem(dest_i, item1); // If something is returned, the item was not fully added if(!item1.empty()) { // If olditem is returned, nothing was added. bool nothing_added = (item1.count == oldcount); // If something else is returned, part of the item was left unadded. // Add the other part back to the source item addItem(i, item1); // If olditem is returned, nothing was added. // Swap the items if (nothing_added && swap_if_needed) { // Tell that we swapped if (did_swap != NULL) { *did_swap = true; } // Take item from source list item1 = changeItem(i, ItemStack()); // Adding was not possible, swap the items. ItemStack item2 = dest->changeItem(dest_i, item1); // Put item from destination list to the source list changeItem(i, item2); } } return (oldcount - item1.count); } /* Inventory */ Inventory::~Inventory() { clear(); } void Inventory::clear() { m_dirty = true; for (auto &m_list : m_lists) { delete m_list; } m_lists.clear(); } void Inventory::clearContents() { m_dirty = true; for (InventoryList *list : m_lists) { for (u32 j=0; j<list->getSize(); j++) { list->deleteItem(j); } } } Inventory::Inventory(IItemDefManager *itemdef) { m_dirty = false; m_itemdef = itemdef; } Inventory::Inventory(const Inventory &other) { *this = other; m_dirty = false; } Inventory & Inventory::operator = (const Inventory &other) { // Gracefully handle self assignment if(this != &other) { m_dirty = true; clear(); m_itemdef = other.m_itemdef; for (InventoryList *list : other.m_lists) { m_lists.push_back(new InventoryList(*list)); } } return *this; } bool Inventory::operator == (const Inventory &other) const { if(m_lists.size() != other.m_lists.size()) return false; for(u32 i=0; i<m_lists.size(); i++) { if(*m_lists[i] != *other.m_lists[i]) return false; } return true; } void Inventory::serialize(std::ostream &os) const { for (InventoryList *list : m_lists) { os<<"List "<<list->getName()<<" "<<list->getSize()<<"\n"; list->serialize(os); } os<<"EndInventory\n"; } void Inventory::deSerialize(std::istream &is) { clear(); while (is.good()) { std::string line; std::getline(is, line, '\n'); std::istringstream iss(line); std::string name; std::getline(iss, name, ' '); if (name == "EndInventory") return; // This is a temporary backwards compatibility fix if (name == "end") return; if (name == "List") { std::string listname; u32 listsize; std::getline(iss, listname, ' '); iss>>listsize; InventoryList *list = new InventoryList(listname, listsize, m_itemdef); list->deSerialize(is); m_lists.push_back(list); } else { throw SerializationError("invalid inventory specifier: " + name); } } // Contents given to deSerialize() were not terminated properly: throw error. std::ostringstream ss; ss << "Malformatted inventory (damaged?). " << m_lists.size() << " lists read." << std::endl; throw SerializationError(ss.str()); } InventoryList * Inventory::addList(const std::string &name, u32 size) { m_dirty = true; s32 i = getListIndex(name); if(i != -1) { if(m_lists[i]->getSize() != size) { delete m_lists[i]; m_lists[i] = new InventoryList(name, size, m_itemdef); } return m_lists[i]; } //don't create list with invalid name if (name.find(' ') != std::string::npos) return NULL; InventoryList *list = new InventoryList(name, size, m_itemdef); m_lists.push_back(list); return list; } InventoryList * Inventory::getList(const std::string &name) { s32 i = getListIndex(name); if(i == -1) return NULL; return m_lists[i]; } std::vector<const InventoryList*> Inventory::getLists() { std::vector<const InventoryList*> lists; for (auto list : m_lists) { lists.push_back(list); } return lists; } bool Inventory::deleteList(const std::string &name) { s32 i = getListIndex(name); if(i == -1) return false; m_dirty = true; delete m_lists[i]; m_lists.erase(m_lists.begin() + i); return true; } const InventoryList * Inventory::getList(const std::string &name) const { s32 i = getListIndex(name); if(i == -1) return NULL; return m_lists[i]; } const s32 Inventory::getListIndex(const std::string &name) const { for(u32 i=0; i<m_lists.size(); i++) { if(m_lists[i]->getName() == name) return i; } return -1; } //END
pgimeno/minetest
src/inventory.cpp
C++
mit
20,189
/* Minetest Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com> 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. */ #pragma once #include "itemdef.h" #include "irrlichttypes.h" #include "itemstackmetadata.h" #include <istream> #include <ostream> #include <string> #include <vector> #include <cassert> struct ToolCapabilities; struct ItemStack { ItemStack() = default; ItemStack(const std::string &name_, u16 count_, u16 wear, IItemDefManager *itemdef); ~ItemStack() = default; // Serialization void serialize(std::ostream &os) const; // Deserialization. Pass itemdef unless you don't want aliases resolved. void deSerialize(std::istream &is, IItemDefManager *itemdef = NULL); void deSerialize(const std::string &s, IItemDefManager *itemdef = NULL); // Returns the string used for inventory std::string getItemString() const; /* Quantity methods */ bool empty() const { return count == 0; } void clear() { name = ""; count = 0; wear = 0; metadata.clear(); } void add(u16 n) { count += n; } void remove(u16 n) { assert(count >= n); // Pre-condition count -= n; if(count == 0) clear(); // reset name, wear and metadata too } // Maximum size of a stack u16 getStackMax(IItemDefManager *itemdef) const { return itemdef->get(name).stack_max; } // Number of items that can be added to this stack u16 freeSpace(IItemDefManager *itemdef) const { u16 max = getStackMax(itemdef); if (count >= max) return 0; return max - count; } // Returns false if item is not known and cannot be used bool isKnown(IItemDefManager *itemdef) const { return itemdef->isKnown(name); } // Returns a pointer to the item definition struct, // or a fallback one (name="unknown") if the item is unknown. const ItemDefinition& getDefinition( IItemDefManager *itemdef) const { return itemdef->get(name); } // Get tool digging properties, or those of the hand if not a tool const ToolCapabilities& getToolCapabilities( IItemDefManager *itemdef) const { const ToolCapabilities *item_cap = itemdef->get(name).tool_capabilities; if (item_cap == NULL) // Fall back to the hand's tool capabilities item_cap = itemdef->get("").tool_capabilities; assert(item_cap != NULL); return metadata.getToolCapabilities(*item_cap); // Check for override } // Wear out (only tools) // Returns true if the item is (was) a tool bool addWear(s32 amount, IItemDefManager *itemdef) { if(getDefinition(itemdef).type == ITEM_TOOL) { if(amount > 65535 - wear) clear(); else if(amount < -wear) wear = 0; else wear += amount; return true; } return false; } // If possible, adds newitem to this item. // If cannot be added at all, returns the item back. // If can be added partly, decremented item is returned back. // If can be added fully, empty item is returned. ItemStack addItem(ItemStack newitem, IItemDefManager *itemdef); // Checks whether newitem could be added. // If restitem is non-NULL, it receives the part of newitem that // would be left over after adding. bool itemFits(ItemStack newitem, ItemStack *restitem, // may be NULL IItemDefManager *itemdef) const; // Takes some items. // If there are not enough, takes as many as it can. // Returns empty item if couldn't take any. ItemStack takeItem(u32 takecount); // Similar to takeItem, but keeps this ItemStack intact. ItemStack peekItem(u32 peekcount) const; /* Properties */ std::string name = ""; u16 count = 0; u16 wear = 0; ItemStackMetadata metadata; }; class InventoryList { public: InventoryList(const std::string &name, u32 size, IItemDefManager *itemdef); ~InventoryList() = default; void clearItems(); void setSize(u32 newsize); void setWidth(u32 newWidth); void setName(const std::string &name); void serialize(std::ostream &os) const; void deSerialize(std::istream &is); InventoryList(const InventoryList &other); InventoryList & operator = (const InventoryList &other); bool operator == (const InventoryList &other) const; bool operator != (const InventoryList &other) const { return !(*this == other); } const std::string &getName() const; u32 getSize() const; u32 getWidth() const; // Count used slots u32 getUsedSlots() const; u32 getFreeSlots() const; // Get reference to item const ItemStack& getItem(u32 i) const; ItemStack& getItem(u32 i); // Returns old item. Parameter can be an empty item. ItemStack changeItem(u32 i, const ItemStack &newitem); // Delete item void deleteItem(u32 i); // Adds an item to a suitable place. Returns leftover item (possibly empty). ItemStack addItem(const ItemStack &newitem); // If possible, adds item to given slot. // If cannot be added at all, returns the item back. // If can be added partly, decremented item is returned back. // If can be added fully, empty item is returned. ItemStack addItem(u32 i, const ItemStack &newitem); // Checks whether the item could be added to the given slot // If restitem is non-NULL, it receives the part of newitem that // would be left over after adding. bool itemFits(const u32 i, const ItemStack &newitem, ItemStack *restitem = NULL) const; // Checks whether there is room for a given item bool roomForItem(const ItemStack &item) const; // Checks whether the given count of the given item // exists in this inventory list. // If match_meta is false, only the items' names are compared. bool containsItem(const ItemStack &item, bool match_meta) const; // Removes the given count of the given item name from // this inventory list. Walks the list in reverse order. // If not as many items exist as requested, removes as // many as possible. // Returns the items that were actually removed. ItemStack removeItem(const ItemStack &item); // Takes some items from a slot. // If there are not enough, takes as many as it can. // Returns empty item if couldn't take any. ItemStack takeItem(u32 i, u32 takecount); // Move an item to a different list (or a different stack in the same list) // count is the maximum number of items to move (0 for everything) // returns number of moved items u32 moveItem(u32 i, InventoryList *dest, u32 dest_i, u32 count = 0, bool swap_if_needed = true, bool *did_swap = NULL); // like moveItem, but without a fixed destination index // also with optional rollback recording void moveItemSomewhere(u32 i, InventoryList *dest, u32 count); private: std::vector<ItemStack> m_items; std::string m_name; u32 m_size; u32 m_width = 0; IItemDefManager *m_itemdef; }; class Inventory { public: ~Inventory(); void clear(); void clearContents(); Inventory(IItemDefManager *itemdef); Inventory(const Inventory &other); Inventory & operator = (const Inventory &other); bool operator == (const Inventory &other) const; bool operator != (const Inventory &other) const { return !(*this == other); } void serialize(std::ostream &os) const; void deSerialize(std::istream &is); InventoryList * addList(const std::string &name, u32 size); InventoryList * getList(const std::string &name); const InventoryList * getList(const std::string &name) const; std::vector<const InventoryList*> getLists(); bool deleteList(const std::string &name); // A shorthand for adding items. Returns leftover item (possibly empty). ItemStack addItem(const std::string &listname, const ItemStack &newitem) { m_dirty = true; InventoryList *list = getList(listname); if(list == NULL) return newitem; return list->addItem(newitem); } bool checkModified() const { return m_dirty; } void setModified(const bool x) { m_dirty = x; } private: // -1 if not found const s32 getListIndex(const std::string &name) const; std::vector<InventoryList*> m_lists; IItemDefManager *m_itemdef; bool m_dirty = false; };
pgimeno/minetest
src/inventory.h
C++
mit
8,498
/* Minetest Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com> 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 "inventorymanager.h" #include "debug.h" #include "log.h" #include "serverenvironment.h" #include "scripting_server.h" #include "serverobject.h" #include "settings.h" #include "craftdef.h" #include "rollback_interface.h" #include "util/strfnd.h" #include "util/basic_macros.h" #define PLAYER_TO_SA(p) p->getEnv()->getScriptIface() /* InventoryLocation */ std::string InventoryLocation::dump() const { std::ostringstream os(std::ios::binary); serialize(os); return os.str(); } void InventoryLocation::serialize(std::ostream &os) const { switch (type) { case InventoryLocation::UNDEFINED: os<<"undefined"; break; case InventoryLocation::CURRENT_PLAYER: os<<"current_player"; break; case InventoryLocation::PLAYER: os<<"player:"<<name; break; case InventoryLocation::NODEMETA: os<<"nodemeta:"<<p.X<<","<<p.Y<<","<<p.Z; break; case InventoryLocation::DETACHED: os<<"detached:"<<name; break; default: FATAL_ERROR("Unhandled inventory location type"); } } void InventoryLocation::deSerialize(std::istream &is) { std::string tname; std::getline(is, tname, ':'); if (tname == "undefined") { type = InventoryLocation::UNDEFINED; } else if (tname == "current_player") { type = InventoryLocation::CURRENT_PLAYER; } else if (tname == "player") { type = InventoryLocation::PLAYER; std::getline(is, name, '\n'); } else if (tname == "nodemeta") { type = InventoryLocation::NODEMETA; std::string pos; std::getline(is, pos, '\n'); Strfnd fn(pos); p.X = stoi(fn.next(",")); p.Y = stoi(fn.next(",")); p.Z = stoi(fn.next(",")); } else if (tname == "detached") { type = InventoryLocation::DETACHED; std::getline(is, name, '\n'); } else { infostream<<"Unknown InventoryLocation type=\""<<tname<<"\""<<std::endl; throw SerializationError("Unknown InventoryLocation type"); } } void InventoryLocation::deSerialize(std::string s) { std::istringstream is(s, std::ios::binary); deSerialize(is); } /* InventoryAction */ InventoryAction *InventoryAction::deSerialize(std::istream &is) { std::string type; std::getline(is, type, ' '); InventoryAction *a = nullptr; if (type == "Move") { a = new IMoveAction(is, false); } else if (type == "MoveSomewhere") { a = new IMoveAction(is, true); } else if (type == "Drop") { a = new IDropAction(is); } else if (type == "Craft") { a = new ICraftAction(is); } return a; } /* IMoveAction */ IMoveAction::IMoveAction(std::istream &is, bool somewhere) : move_somewhere(somewhere) { std::string ts; std::getline(is, ts, ' '); count = stoi(ts); std::getline(is, ts, ' '); from_inv.deSerialize(ts); std::getline(is, from_list, ' '); std::getline(is, ts, ' '); from_i = stoi(ts); std::getline(is, ts, ' '); to_inv.deSerialize(ts); std::getline(is, to_list, ' '); if (!somewhere) { std::getline(is, ts, ' '); to_i = stoi(ts); } } void IMoveAction::apply(InventoryManager *mgr, ServerActiveObject *player, IGameDef *gamedef) { Inventory *inv_from = mgr->getInventory(from_inv); Inventory *inv_to = mgr->getInventory(to_inv); if (!inv_from) { infostream << "IMoveAction::apply(): FAIL: source inventory not found: " << "from_inv=\""<<from_inv.dump() << "\"" << ", to_inv=\"" << to_inv.dump() << "\"" << std::endl; return; } if (!inv_to) { infostream << "IMoveAction::apply(): FAIL: destination inventory not found: " << "from_inv=\"" << from_inv.dump() << "\"" << ", to_inv=\"" << to_inv.dump() << "\"" << std::endl; return; } InventoryList *list_from = inv_from->getList(from_list); InventoryList *list_to = inv_to->getList(to_list); /* If a list doesn't exist or the source item doesn't exist */ if (!list_from) { infostream << "IMoveAction::apply(): FAIL: source list not found: " << "from_inv=\"" << from_inv.dump() << "\"" << ", from_list=\"" << from_list << "\"" << std::endl; return; } if (!list_to) { infostream << "IMoveAction::apply(): FAIL: destination list not found: " << "to_inv=\""<<to_inv.dump() << "\"" << ", to_list=\"" << to_list << "\"" << std::endl; return; } if (move_somewhere) { s16 old_to_i = to_i; u16 old_count = count; caused_by_move_somewhere = true; move_somewhere = false; infostream << "IMoveAction::apply(): moving item somewhere" << " msom=" << move_somewhere << " count=" << count << " from inv=\"" << from_inv.dump() << "\"" << " list=\"" << from_list << "\"" << " i=" << from_i << " to inv=\"" << to_inv.dump() << "\"" << " list=\"" << to_list << "\"" << std::endl; // Try to add the item to destination list s16 dest_size = list_to->getSize(); // First try all the non-empty slots for (s16 dest_i = 0; dest_i < dest_size && count > 0; dest_i++) { if (!list_to->getItem(dest_i).empty()) { to_i = dest_i; apply(mgr, player, gamedef); count -= move_count; } } // Then try all the empty ones for (s16 dest_i = 0; dest_i < dest_size && count > 0; dest_i++) { if (list_to->getItem(dest_i).empty()) { to_i = dest_i; apply(mgr, player, gamedef); count -= move_count; } } to_i = old_to_i; count = old_count; caused_by_move_somewhere = false; move_somewhere = true; return; } if ((u16)to_i > list_to->getSize()) { infostream << "IMoveAction::apply(): FAIL: destination index out of bounds: " << "to_i=" << to_i << ", size=" << list_to->getSize() << std::endl; return; } /* Do not handle rollback if both inventories are that of the same player */ bool ignore_rollback = ( from_inv.type == InventoryLocation::PLAYER && from_inv == to_inv); /* Collect information of endpoints */ int try_take_count = count; if (try_take_count == 0) try_take_count = list_from->getItem(from_i).count; int src_can_take_count = 0xffff; int dst_can_put_count = 0xffff; /* Query detached inventories */ // Move occurs in the same detached inventory if (from_inv.type == InventoryLocation::DETACHED && from_inv == to_inv) { src_can_take_count = PLAYER_TO_SA(player)->detached_inventory_AllowMove( *this, try_take_count, player); dst_can_put_count = src_can_take_count; } else { // Destination is detached if (to_inv.type == InventoryLocation::DETACHED) { ItemStack src_item = list_from->getItem(from_i); src_item.count = try_take_count; dst_can_put_count = PLAYER_TO_SA(player)->detached_inventory_AllowPut( *this, src_item, player); } // Source is detached if (from_inv.type == InventoryLocation::DETACHED) { ItemStack src_item = list_from->getItem(from_i); src_item.count = try_take_count; src_can_take_count = PLAYER_TO_SA(player)->detached_inventory_AllowTake( *this, src_item, player); } } /* Query node metadata inventories */ // Both endpoints are nodemeta // Move occurs in the same nodemeta inventory if (from_inv.type == InventoryLocation::NODEMETA && from_inv == to_inv) { src_can_take_count = PLAYER_TO_SA(player)->nodemeta_inventory_AllowMove( *this, try_take_count, player); dst_can_put_count = src_can_take_count; } else { // Destination is nodemeta if (to_inv.type == InventoryLocation::NODEMETA) { ItemStack src_item = list_from->getItem(from_i); src_item.count = try_take_count; dst_can_put_count = PLAYER_TO_SA(player)->nodemeta_inventory_AllowPut( *this, src_item, player); } // Source is nodemeta if (from_inv.type == InventoryLocation::NODEMETA) { ItemStack src_item = list_from->getItem(from_i); src_item.count = try_take_count; src_can_take_count = PLAYER_TO_SA(player)->nodemeta_inventory_AllowTake( *this, src_item, player); } } // Query player inventories // Move occurs in the same player inventory if (from_inv.type == InventoryLocation::PLAYER && from_inv == to_inv) { src_can_take_count = PLAYER_TO_SA(player)->player_inventory_AllowMove( *this, try_take_count, player); dst_can_put_count = src_can_take_count; } else { // Destination is a player if (to_inv.type == InventoryLocation::PLAYER) { ItemStack src_item = list_from->getItem(from_i); src_item.count = try_take_count; dst_can_put_count = PLAYER_TO_SA(player)->player_inventory_AllowPut( *this, src_item, player); } // Source is a player if (from_inv.type == InventoryLocation::PLAYER) { ItemStack src_item = list_from->getItem(from_i); src_item.count = try_take_count; src_can_take_count = PLAYER_TO_SA(player)->player_inventory_AllowTake( *this, src_item, player); } } int old_count = count; /* Modify count according to collected data */ count = try_take_count; if (src_can_take_count != -1 && count > src_can_take_count) count = src_can_take_count; if (dst_can_put_count != -1 && count > dst_can_put_count) count = dst_can_put_count; /* Limit according to source item count */ if (count > list_from->getItem(from_i).count) count = list_from->getItem(from_i).count; /* If no items will be moved, don't go further */ if (count == 0) { infostream<<"IMoveAction::apply(): move was completely disallowed:" <<" count="<<old_count <<" from inv=\""<<from_inv.dump()<<"\"" <<" list=\""<<from_list<<"\"" <<" i="<<from_i <<" to inv=\""<<to_inv.dump()<<"\"" <<" list=\""<<to_list<<"\"" <<" i="<<to_i <<std::endl; return; } ItemStack src_item = list_from->getItem(from_i); src_item.count = count; ItemStack from_stack_was = list_from->getItem(from_i); ItemStack to_stack_was = list_to->getItem(to_i); /* Perform actual move If something is wrong (source item is empty, destination is the same as source), nothing happens */ bool did_swap = false; move_count = list_from->moveItem(from_i, list_to, to_i, count, !caused_by_move_somewhere, &did_swap); // If source is infinite, reset it's stack if (src_can_take_count == -1) { // For the caused_by_move_somewhere == true case we didn't force-put the item, // which guarantees there is no leftover, and code below would duplicate the // (not replaced) to_stack_was item. if (!caused_by_move_somewhere) { // If destination stack is of different type and there are leftover // items, attempt to put the leftover items to a different place in the // destination inventory. // The client-side GUI will try to guess if this happens. if (from_stack_was.name != to_stack_was.name) { for (u32 i = 0; i < list_to->getSize(); i++) { if (list_to->getItem(i).empty()) { list_to->changeItem(i, to_stack_was); break; } } } } if (move_count > 0 || did_swap) { list_from->deleteItem(from_i); list_from->addItem(from_i, from_stack_was); } } // If destination is infinite, reset it's stack and take count from source if (dst_can_put_count == -1) { list_to->deleteItem(to_i); list_to->addItem(to_i, to_stack_was); list_from->deleteItem(from_i); list_from->addItem(from_i, from_stack_was); list_from->takeItem(from_i, count); } infostream << "IMoveAction::apply(): moved" << " msom=" << move_somewhere << " caused=" << caused_by_move_somewhere << " count=" << count << " from inv=\"" << from_inv.dump() << "\"" << " list=\"" << from_list << "\"" << " i=" << from_i << " to inv=\"" << to_inv.dump() << "\"" << " list=\"" << to_list << "\"" << " i=" << to_i << std::endl; // If we are inside the move somewhere loop, we don't need to report // anything if nothing happened (perhaps we don't need to report // anything for caused_by_move_somewhere == true, but this way its safer) if (caused_by_move_somewhere && move_count == 0) return; /* Record rollback information */ if (!ignore_rollback && gamedef->rollback()) { IRollbackManager *rollback = gamedef->rollback(); // If source is not infinite, record item take if (src_can_take_count != -1) { RollbackAction action; std::string loc; { std::ostringstream os(std::ios::binary); from_inv.serialize(os); loc = os.str(); } action.setModifyInventoryStack(loc, from_list, from_i, false, src_item); rollback->reportAction(action); } // If destination is not infinite, record item put if (dst_can_put_count != -1) { RollbackAction action; std::string loc; { std::ostringstream os(std::ios::binary); to_inv.serialize(os); loc = os.str(); } action.setModifyInventoryStack(loc, to_list, to_i, true, src_item); rollback->reportAction(action); } } /* Report move to endpoints */ /* Detached inventories */ // Both endpoints are same detached if (from_inv.type == InventoryLocation::DETACHED && from_inv == to_inv) { PLAYER_TO_SA(player)->detached_inventory_OnMove( *this, count, player); } else { // Destination is detached if (to_inv.type == InventoryLocation::DETACHED) { PLAYER_TO_SA(player)->detached_inventory_OnPut( *this, src_item, player); } // Source is detached if (from_inv.type == InventoryLocation::DETACHED) { PLAYER_TO_SA(player)->detached_inventory_OnTake( *this, src_item, player); } } /* Node metadata inventories */ // Both endpoints are same nodemeta if (from_inv.type == InventoryLocation::NODEMETA && from_inv == to_inv) { PLAYER_TO_SA(player)->nodemeta_inventory_OnMove( *this, count, player); } else { // Destination is nodemeta if (to_inv.type == InventoryLocation::NODEMETA) { PLAYER_TO_SA(player)->nodemeta_inventory_OnPut( *this, src_item, player); } // Source is nodemeta if (from_inv.type == InventoryLocation::NODEMETA) { PLAYER_TO_SA(player)->nodemeta_inventory_OnTake( *this, src_item, player); } } // Player inventories // Both endpoints are same player inventory if (from_inv.type == InventoryLocation::PLAYER && from_inv == to_inv) { PLAYER_TO_SA(player)->player_inventory_OnMove( *this, count, player); } else { // Destination is player inventory if (to_inv.type == InventoryLocation::PLAYER) { PLAYER_TO_SA(player)->player_inventory_OnPut( *this, src_item, player); } // Source is player inventory if (from_inv.type == InventoryLocation::PLAYER) { PLAYER_TO_SA(player)->player_inventory_OnTake( *this, src_item, player); } } mgr->setInventoryModified(from_inv, false); if (inv_from != inv_to) mgr->setInventoryModified(to_inv, false); } void IMoveAction::clientApply(InventoryManager *mgr, IGameDef *gamedef) { // Optional InventoryAction operation that is run on the client // to make lag less apparent. Inventory *inv_from = mgr->getInventory(from_inv); Inventory *inv_to = mgr->getInventory(to_inv); if (!inv_from || !inv_to) return; InventoryLocation current_player; current_player.setCurrentPlayer(); Inventory *inv_player = mgr->getInventory(current_player); if (inv_from != inv_player || inv_to != inv_player) return; InventoryList *list_from = inv_from->getList(from_list); InventoryList *list_to = inv_to->getList(to_list); if (!list_from || !list_to) return; if (!move_somewhere) list_from->moveItem(from_i, list_to, to_i, count); else list_from->moveItemSomewhere(from_i, list_to, count); mgr->setInventoryModified(from_inv); if (inv_from != inv_to) mgr->setInventoryModified(to_inv); } /* IDropAction */ IDropAction::IDropAction(std::istream &is) { std::string ts; std::getline(is, ts, ' '); count = stoi(ts); std::getline(is, ts, ' '); from_inv.deSerialize(ts); std::getline(is, from_list, ' '); std::getline(is, ts, ' '); from_i = stoi(ts); } void IDropAction::apply(InventoryManager *mgr, ServerActiveObject *player, IGameDef *gamedef) { Inventory *inv_from = mgr->getInventory(from_inv); if (!inv_from) { infostream<<"IDropAction::apply(): FAIL: source inventory not found: " <<"from_inv=\""<<from_inv.dump()<<"\""<<std::endl; return; } InventoryList *list_from = inv_from->getList(from_list); /* If a list doesn't exist or the source item doesn't exist */ if (!list_from) { infostream<<"IDropAction::apply(): FAIL: source list not found: " <<"from_inv=\""<<from_inv.dump()<<"\""<<std::endl; return; } if (list_from->getItem(from_i).empty()) { infostream<<"IDropAction::apply(): FAIL: source item not found: " <<"from_inv=\""<<from_inv.dump()<<"\"" <<", from_list=\""<<from_list<<"\"" <<" from_i="<<from_i<<std::endl; return; } /* Do not handle rollback if inventory is player's */ bool ignore_src_rollback = (from_inv.type == InventoryLocation::PLAYER); /* Collect information of endpoints */ int take_count = list_from->getItem(from_i).count; if (count != 0 && count < take_count) take_count = count; int src_can_take_count = take_count; ItemStack src_item = list_from->getItem(from_i); src_item.count = take_count; // Run callbacks depending on source inventory switch (from_inv.type) { case InventoryLocation::DETACHED: src_can_take_count = PLAYER_TO_SA(player)->detached_inventory_AllowTake( *this, src_item, player); break; case InventoryLocation::NODEMETA: src_can_take_count = PLAYER_TO_SA(player)->nodemeta_inventory_AllowTake( *this, src_item, player); break; case InventoryLocation::PLAYER: src_can_take_count = PLAYER_TO_SA(player)->player_inventory_AllowTake( *this, src_item, player); break; default: break; } if (src_can_take_count != -1 && src_can_take_count < take_count) take_count = src_can_take_count; int actually_dropped_count = 0; // Update item due executed callbacks src_item = list_from->getItem(from_i); // Drop the item ItemStack item1 = list_from->getItem(from_i); item1.count = take_count; if(PLAYER_TO_SA(player)->item_OnDrop(item1, player, player->getBasePosition())) { actually_dropped_count = take_count - item1.count; if (actually_dropped_count == 0) { infostream<<"Actually dropped no items"<<std::endl; return; } // If source isn't infinite if (src_can_take_count != -1) { // Take item from source list ItemStack item2 = list_from->takeItem(from_i, actually_dropped_count); if (item2.count != actually_dropped_count) errorstream<<"Could not take dropped count of items"<<std::endl; mgr->setInventoryModified(from_inv, false); } } infostream<<"IDropAction::apply(): dropped " <<" from inv=\""<<from_inv.dump()<<"\"" <<" list=\""<<from_list<<"\"" <<" i="<<from_i <<std::endl; src_item.count = actually_dropped_count; /* Report drop to endpoints */ switch (from_inv.type) { case InventoryLocation::DETACHED: PLAYER_TO_SA(player)->detached_inventory_OnTake( *this, src_item, player); break; case InventoryLocation::NODEMETA: PLAYER_TO_SA(player)->nodemeta_inventory_OnTake( *this, src_item, player); break; case InventoryLocation::PLAYER: PLAYER_TO_SA(player)->player_inventory_OnTake( *this, src_item, player); break; default: break; } /* Record rollback information */ if (!ignore_src_rollback && gamedef->rollback()) { IRollbackManager *rollback = gamedef->rollback(); // If source is not infinite, record item take if (src_can_take_count != -1) { RollbackAction action; std::string loc; { std::ostringstream os(std::ios::binary); from_inv.serialize(os); loc = os.str(); } action.setModifyInventoryStack(loc, from_list, from_i, false, src_item); rollback->reportAction(action); } } } void IDropAction::clientApply(InventoryManager *mgr, IGameDef *gamedef) { // Optional InventoryAction operation that is run on the client // to make lag less apparent. Inventory *inv_from = mgr->getInventory(from_inv); if (!inv_from) return; InventoryLocation current_player; current_player.setCurrentPlayer(); Inventory *inv_player = mgr->getInventory(current_player); if (inv_from != inv_player) return; InventoryList *list_from = inv_from->getList(from_list); if (!list_from) return; if (count == 0) list_from->changeItem(from_i, ItemStack()); else list_from->takeItem(from_i, count); mgr->setInventoryModified(from_inv); } /* ICraftAction */ ICraftAction::ICraftAction(std::istream &is) { std::string ts; std::getline(is, ts, ' '); count = stoi(ts); std::getline(is, ts, ' '); craft_inv.deSerialize(ts); } void ICraftAction::apply(InventoryManager *mgr, ServerActiveObject *player, IGameDef *gamedef) { Inventory *inv_craft = mgr->getInventory(craft_inv); if (!inv_craft) { infostream << "ICraftAction::apply(): FAIL: inventory not found: " << "craft_inv=\"" << craft_inv.dump() << "\"" << std::endl; return; } InventoryList *list_craft = inv_craft->getList("craft"); InventoryList *list_craftresult = inv_craft->getList("craftresult"); InventoryList *list_main = inv_craft->getList("main"); /* If a list doesn't exist or the source item doesn't exist */ if (!list_craft) { infostream << "ICraftAction::apply(): FAIL: craft list not found: " << "craft_inv=\"" << craft_inv.dump() << "\"" << std::endl; return; } if (!list_craftresult) { infostream << "ICraftAction::apply(): FAIL: craftresult list not found: " << "craft_inv=\"" << craft_inv.dump() << "\"" << std::endl; return; } if (list_craftresult->getSize() < 1) { infostream << "ICraftAction::apply(): FAIL: craftresult list too short: " << "craft_inv=\"" << craft_inv.dump() << "\"" << std::endl; return; } ItemStack crafted; ItemStack craftresultitem; int count_remaining = count; std::vector<ItemStack> output_replacements; getCraftingResult(inv_craft, crafted, output_replacements, false, gamedef); PLAYER_TO_SA(player)->item_CraftPredict(crafted, player, list_craft, craft_inv); bool found = !crafted.empty(); while (found && list_craftresult->itemFits(0, crafted)) { InventoryList saved_craft_list = *list_craft; std::vector<ItemStack> temp; // Decrement input and add crafting output getCraftingResult(inv_craft, crafted, temp, true, gamedef); PLAYER_TO_SA(player)->item_OnCraft(crafted, player, &saved_craft_list, craft_inv); list_craftresult->addItem(0, crafted); mgr->setInventoryModified(craft_inv); // Add the new replacements to the list IItemDefManager *itemdef = gamedef->getItemDefManager(); for (auto &itemstack : temp) { for (auto &output_replacement : output_replacements) { if (itemstack.name == output_replacement.name) { itemstack = output_replacement.addItem(itemstack, itemdef); if (itemstack.empty()) continue; } } output_replacements.push_back(itemstack); } actionstream << player->getDescription() << " crafts " << crafted.getItemString() << std::endl; // Decrement counter if (count_remaining == 1) break; if (count_remaining > 1) count_remaining--; // Get next crafting result getCraftingResult(inv_craft, crafted, temp, false, gamedef); PLAYER_TO_SA(player)->item_CraftPredict(crafted, player, list_craft, craft_inv); found = !crafted.empty(); } // Put the replacements in the inventory or drop them on the floor, if // the invenotry is full for (auto &output_replacement : output_replacements) { if (list_main) output_replacement = list_main->addItem(output_replacement); if (output_replacement.empty()) continue; u16 count = output_replacement.count; do { PLAYER_TO_SA(player)->item_OnDrop(output_replacement, player, player->getBasePosition()); if (count >= output_replacement.count) { errorstream << "Couldn't drop replacement stack " << output_replacement.getItemString() << " because drop loop didn't " "decrease count." << std::endl; break; } } while (!output_replacement.empty()); } infostream<<"ICraftAction::apply(): crafted " <<" craft_inv=\""<<craft_inv.dump()<<"\"" <<std::endl; } void ICraftAction::clientApply(InventoryManager *mgr, IGameDef *gamedef) { // Optional InventoryAction operation that is run on the client // to make lag less apparent. } // Crafting helper bool getCraftingResult(Inventory *inv, ItemStack &result, std::vector<ItemStack> &output_replacements, bool decrementInput, IGameDef *gamedef) { result.clear(); // Get the InventoryList in which we will operate InventoryList *clist = inv->getList("craft"); if (!clist) return false; // Mangle crafting grid to an another format CraftInput ci; ci.method = CRAFT_METHOD_NORMAL; ci.width = clist->getWidth() ? clist->getWidth() : 3; for (u16 i=0; i < clist->getSize(); i++) ci.items.push_back(clist->getItem(i)); // Find out what is crafted and add it to result item slot CraftOutput co; bool found = gamedef->getCraftDefManager()->getCraftResult( ci, co, output_replacements, decrementInput, gamedef); if (found) result.deSerialize(co.item, gamedef->getItemDefManager()); if (found && decrementInput) { // CraftInput has been changed, apply changes in clist for (u16 i=0; i < clist->getSize(); i++) { clist->changeItem(i, ci.items[i]); } } return found; }
pgimeno/minetest
src/inventorymanager.cpp
C++
mit
25,586
/* Minetest Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com> 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. */ #pragma once #include "inventory.h" #include <iostream> #include <string> class ServerActiveObject; struct InventoryLocation { enum Type{ UNDEFINED, CURRENT_PLAYER, PLAYER, NODEMETA, DETACHED, } type; std::string name; // PLAYER, DETACHED v3s16 p; // NODEMETA InventoryLocation() { setUndefined(); } void setUndefined() { type = UNDEFINED; } void setCurrentPlayer() { type = CURRENT_PLAYER; } void setPlayer(const std::string &name_) { type = PLAYER; name = name_; } void setNodeMeta(const v3s16 &p_) { type = NODEMETA; p = p_; } void setDetached(const std::string &name_) { type = DETACHED; name = name_; } bool operator==(const InventoryLocation &other) const { if(type != other.type) return false; switch(type){ case UNDEFINED: return false; case CURRENT_PLAYER: return true; case PLAYER: return (name == other.name); case NODEMETA: return (p == other.p); case DETACHED: return (name == other.name); } return false; } bool operator!=(const InventoryLocation &other) const { return !(*this == other); } void applyCurrentPlayer(const std::string &name_) { if(type == CURRENT_PLAYER) setPlayer(name_); } std::string dump() const; void serialize(std::ostream &os) const; void deSerialize(std::istream &is); void deSerialize(std::string s); }; struct InventoryAction; class InventoryManager { public: InventoryManager() = default; virtual ~InventoryManager() = default; // Get an inventory (server and client) virtual Inventory* getInventory(const InventoryLocation &loc){return NULL;} // Set modified (will be saved and sent over network; only on server) virtual void setInventoryModified(const InventoryLocation &loc, bool playerSend = true){} // Send inventory action to server (only on client) virtual void inventoryAction(InventoryAction *a){} }; enum class IAction : u16 { Move, Drop, Craft }; struct InventoryAction { static InventoryAction *deSerialize(std::istream &is); virtual IAction getType() const = 0; virtual void serialize(std::ostream &os) const = 0; virtual void apply(InventoryManager *mgr, ServerActiveObject *player, IGameDef *gamedef) = 0; virtual void clientApply(InventoryManager *mgr, IGameDef *gamedef) = 0; virtual ~InventoryAction() = default;; }; struct MoveAction { InventoryLocation from_inv; std::string from_list; s16 from_i = -1; InventoryLocation to_inv; std::string to_list; s16 to_i = -1; }; struct IMoveAction : public InventoryAction, public MoveAction { // count=0 means "everything" u16 count = 0; bool move_somewhere = false; // treat these as private // related to movement to somewhere bool caused_by_move_somewhere = false; u32 move_count = 0; IMoveAction() = default; IMoveAction(std::istream &is, bool somewhere); IAction getType() const { return IAction::Move; } void serialize(std::ostream &os) const { if (!move_somewhere) os << "Move "; else os << "MoveSomewhere "; os << count << " "; os << from_inv.dump() << " "; os << from_list << " "; os << from_i << " "; os << to_inv.dump() << " "; os << to_list; if (!move_somewhere) os << " " << to_i; } void apply(InventoryManager *mgr, ServerActiveObject *player, IGameDef *gamedef); void clientApply(InventoryManager *mgr, IGameDef *gamedef); }; struct IDropAction : public InventoryAction, public MoveAction { // count=0 means "everything" u16 count = 0; IDropAction() = default; IDropAction(std::istream &is); IAction getType() const { return IAction::Drop; } void serialize(std::ostream &os) const { os<<"Drop "; os<<count<<" "; os<<from_inv.dump()<<" "; os<<from_list<<" "; os<<from_i; } void apply(InventoryManager *mgr, ServerActiveObject *player, IGameDef *gamedef); void clientApply(InventoryManager *mgr, IGameDef *gamedef); }; struct ICraftAction : public InventoryAction { // count=0 means "everything" u16 count = 0; InventoryLocation craft_inv; ICraftAction() = default; ICraftAction(std::istream &is); IAction getType() const { return IAction::Craft; } void serialize(std::ostream &os) const { os<<"Craft "; os<<count<<" "; os<<craft_inv.dump()<<" "; } void apply(InventoryManager *mgr, ServerActiveObject *player, IGameDef *gamedef); void clientApply(InventoryManager *mgr, IGameDef *gamedef); }; // Crafting helper bool getCraftingResult(Inventory *inv, ItemStack &result, std::vector<ItemStack> &output_replacements, bool decrementInput, IGameDef *gamedef);
pgimeno/minetest
src/inventorymanager.h
C++
mit
5,336
/* Minetest Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com> 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. */ #pragma once #include "irrlichttypes.h" #include <aabbox3d.h> typedef core::aabbox3d<f32> aabb3f;
pgimeno/minetest
src/irr_aabb3d.h
C++
mit
891
/* Minetest Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com> 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. */ #pragma once #include "irrlichttypes.h" #include <vector2d.h> typedef core::vector2d<f32> v2f; typedef core::vector2d<s16> v2s16; typedef core::vector2d<s32> v2s32; typedef core::vector2d<u32> v2u32; typedef core::vector2d<f32> v2f32;
pgimeno/minetest
src/irr_v2d.h
C++
mit
1,028
/* Minetest Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com> 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. */ #pragma once #include "irrlichttypes.h" #include <vector3d.h> typedef core::vector3df v3f; typedef core::vector3d<double> v3d; typedef core::vector3d<s16> v3s16; typedef core::vector3d<u16> v3u16; typedef core::vector3d<s32> v3s32;
pgimeno/minetest
src/irr_v3d.h
C++
mit
1,025
/* CGUITTFont FreeType class for Irrlicht Copyright (c) 2009-2010 John Norman Copyright (c) 2016 Nathanaël Courant This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. The original version of this class can be located at: http://irrlicht.suckerfreegames.com/ John Norman john@suckerfreegames.com */ #include <irrlicht.h> #include <iostream> #include "CGUITTFont.h" namespace irr { namespace gui { // Manages the FT_Face cache. struct SGUITTFace : public virtual irr::IReferenceCounted { SGUITTFace() : face_buffer(0), face_buffer_size(0) { memset((void*)&face, 0, sizeof(FT_Face)); } ~SGUITTFace() { FT_Done_Face(face); delete[] face_buffer; } FT_Face face; FT_Byte* face_buffer; FT_Long face_buffer_size; }; // Static variables. FT_Library CGUITTFont::c_library; core::map<io::path, SGUITTFace*> CGUITTFont::c_faces; bool CGUITTFont::c_libraryLoaded = false; scene::IMesh* CGUITTFont::shared_plane_ptr_ = 0; scene::SMesh CGUITTFont::shared_plane_; // /** Checks that no dimension of the FT_BitMap object is negative. If either is * negative, abort execution. */ inline void checkFontBitmapSize(const FT_Bitmap &bits) { if ((s32)bits.rows < 0 || (s32)bits.width < 0) { std::cout << "Insane font glyph size. File: " << __FILE__ << " Line " << __LINE__ << std::endl; abort(); } } video::IImage* SGUITTGlyph::createGlyphImage(const FT_Bitmap& bits, video::IVideoDriver* driver) const { // Make sure our casts to s32 in the loops below will not cause problems checkFontBitmapSize(bits); // Determine what our texture size should be. // Add 1 because textures are inclusive-exclusive. core::dimension2du d(bits.width + 1, bits.rows + 1); core::dimension2du texture_size; //core::dimension2du texture_size(bits.width + 1, bits.rows + 1); // Create and load our image now. video::IImage* image = 0; switch (bits.pixel_mode) { case FT_PIXEL_MODE_MONO: { // Create a blank image and fill it with transparent pixels. texture_size = d.getOptimalSize(true, true); image = driver->createImage(video::ECF_A1R5G5B5, texture_size); image->fill(video::SColor(0, 255, 255, 255)); // Load the monochrome data in. const u32 image_pitch = image->getPitch() / sizeof(u16); u16* image_data = (u16*)image->lock(); u8* glyph_data = bits.buffer; for (s32 y = 0; y < (s32)bits.rows; ++y) { u16* row = image_data; for (s32 x = 0; x < (s32)bits.width; ++x) { // Monochrome bitmaps store 8 pixels per byte. The left-most pixel is the bit 0x80. // So, we go through the data each bit at a time. if ((glyph_data[y * bits.pitch + (x / 8)] & (0x80 >> (x % 8))) != 0) *row = 0xFFFF; ++row; } image_data += image_pitch; } image->unlock(); break; } case FT_PIXEL_MODE_GRAY: { // Create our blank image. texture_size = d.getOptimalSize(!driver->queryFeature(video::EVDF_TEXTURE_NPOT), !driver->queryFeature(video::EVDF_TEXTURE_NSQUARE), true, 0); image = driver->createImage(video::ECF_A8R8G8B8, texture_size); image->fill(video::SColor(0, 255, 255, 255)); // Load the grayscale data in. const float gray_count = static_cast<float>(bits.num_grays); const u32 image_pitch = image->getPitch() / sizeof(u32); u32* image_data = (u32*)image->lock(); u8* glyph_data = bits.buffer; for (s32 y = 0; y < (s32)bits.rows; ++y) { u8* row = glyph_data; for (s32 x = 0; x < (s32)bits.width; ++x) { image_data[y * image_pitch + x] |= static_cast<u32>(255.0f * (static_cast<float>(*row++) / gray_count)) << 24; //data[y * image_pitch + x] |= ((u32)(*bitsdata++) << 24); } glyph_data += bits.pitch; } image->unlock(); break; } default: // TODO: error message? return 0; } return image; } void SGUITTGlyph::preload(u32 char_index, FT_Face face, video::IVideoDriver* driver, u32 font_size, const FT_Int32 loadFlags) { if (isLoaded) return; // Set the size of the glyph. FT_Set_Pixel_Sizes(face, 0, font_size); // Attempt to load the glyph. if (FT_Load_Glyph(face, char_index, loadFlags) != FT_Err_Ok) // TODO: error message? return; FT_GlyphSlot glyph = face->glyph; FT_Bitmap bits = glyph->bitmap; // Setup the glyph information here: advance = glyph->advance; offset = core::vector2di(glyph->bitmap_left, glyph->bitmap_top); // Try to get the last page with available slots. CGUITTGlyphPage* page = parent->getLastGlyphPage(); // If we need to make a new page, do that now. if (!page) { page = parent->createGlyphPage(bits.pixel_mode); if (!page) // TODO: add error message? return; } glyph_page = parent->getLastGlyphPageIndex(); u32 texture_side_length = page->texture->getOriginalSize().Width; core::vector2di page_position( (page->used_slots % (texture_side_length / font_size)) * font_size, (page->used_slots / (texture_side_length / font_size)) * font_size ); source_rect.UpperLeftCorner = page_position; source_rect.LowerRightCorner = core::vector2di(page_position.X + bits.width, page_position.Y + bits.rows); page->dirty = true; ++page->used_slots; --page->available_slots; // We grab the glyph bitmap here so the data won't be removed when the next glyph is loaded. surface = createGlyphImage(bits, driver); // Set our glyph as loaded. isLoaded = true; } void SGUITTGlyph::unload() { if (surface) { surface->drop(); surface = 0; } isLoaded = false; } ////////////////////// CGUITTFont* CGUITTFont::createTTFont(IGUIEnvironment *env, const io::path& filename, const u32 size, const bool antialias, const bool transparency, const u32 shadow, const u32 shadow_alpha) { if (!c_libraryLoaded) { if (FT_Init_FreeType(&c_library)) return 0; c_libraryLoaded = true; } CGUITTFont* font = new CGUITTFont(env); bool ret = font->load(filename, size, antialias, transparency); if (!ret) { font->drop(); return 0; } font->shadow_offset = shadow; font->shadow_alpha = shadow_alpha; return font; } CGUITTFont* CGUITTFont::createTTFont(IrrlichtDevice *device, const io::path& filename, const u32 size, const bool antialias, const bool transparency) { if (!c_libraryLoaded) { if (FT_Init_FreeType(&c_library)) return 0; c_libraryLoaded = true; } CGUITTFont* font = new CGUITTFont(device->getGUIEnvironment()); font->Device = device; bool ret = font->load(filename, size, antialias, transparency); if (!ret) { font->drop(); return 0; } return font; } CGUITTFont* CGUITTFont::create(IGUIEnvironment *env, const io::path& filename, const u32 size, const bool antialias, const bool transparency) { return CGUITTFont::createTTFont(env, filename, size, antialias, transparency); } CGUITTFont* CGUITTFont::create(IrrlichtDevice *device, const io::path& filename, const u32 size, const bool antialias, const bool transparency) { return CGUITTFont::createTTFont(device, filename, size, antialias, transparency); } ////////////////////// //! Constructor. CGUITTFont::CGUITTFont(IGUIEnvironment *env) : use_monochrome(false), use_transparency(true), use_hinting(true), use_auto_hinting(true), batch_load_size(1), Device(0), Environment(env), Driver(0), GlobalKerningWidth(0), GlobalKerningHeight(0) { #ifdef _DEBUG setDebugName("CGUITTFont"); #endif if (Environment) { // don't grab environment, to avoid circular references Driver = Environment->getVideoDriver(); } if (Driver) Driver->grab(); setInvisibleCharacters(L" "); // Glyphs aren't reference counted, so don't try to delete them when we free the array. Glyphs.set_free_when_destroyed(false); } bool CGUITTFont::load(const io::path& filename, const u32 size, const bool antialias, const bool transparency) { // Some sanity checks. if (Environment == 0 || Driver == 0) return false; if (size == 0) return false; if (filename.size() == 0) return false; io::IFileSystem* filesystem = Environment->getFileSystem(); irr::ILogger* logger = (Device != 0 ? Device->getLogger() : 0); this->size = size; this->filename = filename; // Update the font loading flags when the font is first loaded. this->use_monochrome = !antialias; this->use_transparency = transparency; update_load_flags(); // Log. if (logger) logger->log(L"CGUITTFont", core::stringw(core::stringw(L"Creating new font: ") + core::ustring(filename).toWCHAR_s() + L" " + core::stringc(size) + L"pt " + (antialias ? L"+antialias " : L"-antialias ") + (transparency ? L"+transparency" : L"-transparency")).c_str(), irr::ELL_INFORMATION); // Grab the face. SGUITTFace* face = 0; core::map<io::path, SGUITTFace*>::Node* node = c_faces.find(filename); if (node == 0) { face = new SGUITTFace(); c_faces.set(filename, face); if (filesystem) { // Read in the file data. io::IReadFile* file = filesystem->createAndOpenFile(filename); if (file == 0) { if (logger) logger->log(L"CGUITTFont", L"Failed to open the file.", irr::ELL_INFORMATION); c_faces.remove(filename); delete face; face = 0; return false; } face->face_buffer = new FT_Byte[file->getSize()]; file->read(face->face_buffer, file->getSize()); face->face_buffer_size = file->getSize(); file->drop(); // Create the face. if (FT_New_Memory_Face(c_library, face->face_buffer, face->face_buffer_size, 0, &face->face)) { if (logger) logger->log(L"CGUITTFont", L"FT_New_Memory_Face failed.", irr::ELL_INFORMATION); c_faces.remove(filename); delete face; face = 0; return false; } } else { core::ustring converter(filename); if (FT_New_Face(c_library, reinterpret_cast<const char*>(converter.toUTF8_s().c_str()), 0, &face->face)) { if (logger) logger->log(L"CGUITTFont", L"FT_New_Face failed.", irr::ELL_INFORMATION); c_faces.remove(filename); delete face; face = 0; return false; } } } else { // Using another instance of this face. face = node->getValue(); face->grab(); } // Store our face. tt_face = face->face; // Store font metrics. FT_Set_Pixel_Sizes(tt_face, size, 0); font_metrics = tt_face->size->metrics; // Allocate our glyphs. Glyphs.clear(); Glyphs.reallocate(tt_face->num_glyphs); Glyphs.set_used(tt_face->num_glyphs); for (FT_Long i = 0; i < tt_face->num_glyphs; ++i) { Glyphs[i].isLoaded = false; Glyphs[i].glyph_page = 0; Glyphs[i].source_rect = core::recti(); Glyphs[i].offset = core::vector2di(); Glyphs[i].advance = FT_Vector(); Glyphs[i].surface = 0; Glyphs[i].parent = this; } // Cache the first 127 ascii characters. u32 old_size = batch_load_size; batch_load_size = 127; getGlyphIndexByChar((uchar32_t)0); batch_load_size = old_size; return true; } CGUITTFont::~CGUITTFont() { // Delete the glyphs and glyph pages. reset_images(); CGUITTAssistDelete::Delete(Glyphs); //Glyphs.clear(); // We aren't using this face anymore. core::map<io::path, SGUITTFace*>::Node* n = c_faces.find(filename); if (n) { SGUITTFace* f = n->getValue(); // Drop our face. If this was the last face, the destructor will clean up. if (f->drop()) c_faces.remove(filename); // If there are no more faces referenced by FreeType, clean up. if (c_faces.size() == 0) { FT_Done_FreeType(c_library); c_libraryLoaded = false; } } // Drop our driver now. if (Driver) Driver->drop(); } void CGUITTFont::reset_images() { // Delete the glyphs. for (u32 i = 0; i != Glyphs.size(); ++i) Glyphs[i].unload(); // Unload the glyph pages from video memory. for (u32 i = 0; i != Glyph_Pages.size(); ++i) delete Glyph_Pages[i]; Glyph_Pages.clear(); // Always update the internal FreeType loading flags after resetting. update_load_flags(); } void CGUITTFont::update_glyph_pages() const { for (u32 i = 0; i != Glyph_Pages.size(); ++i) { if (Glyph_Pages[i]->dirty) Glyph_Pages[i]->updateTexture(); } } CGUITTGlyphPage* CGUITTFont::getLastGlyphPage() const { CGUITTGlyphPage* page = 0; if (Glyph_Pages.empty()) return 0; else { page = Glyph_Pages[getLastGlyphPageIndex()]; if (page->available_slots == 0) page = 0; } return page; } CGUITTGlyphPage* CGUITTFont::createGlyphPage(const u8& pixel_mode) { CGUITTGlyphPage* page = 0; // Name of our page. io::path name("TTFontGlyphPage_"); name += tt_face->family_name; name += "."; name += tt_face->style_name; name += "."; name += size; name += "_"; name += Glyph_Pages.size(); // The newly created page will be at the end of the collection. // Create the new page. page = new CGUITTGlyphPage(Driver, name); // Determine our maximum texture size. // If we keep getting 0, set it to 1024x1024, as that number is pretty safe. core::dimension2du max_texture_size = max_page_texture_size; if (max_texture_size.Width == 0 || max_texture_size.Height == 0) max_texture_size = Driver->getMaxTextureSize(); if (max_texture_size.Width == 0 || max_texture_size.Height == 0) max_texture_size = core::dimension2du(1024, 1024); // We want to try to put at least 144 glyphs on a single texture. core::dimension2du page_texture_size; if (size <= 21) page_texture_size = core::dimension2du(256, 256); else if (size <= 42) page_texture_size = core::dimension2du(512, 512); else if (size <= 84) page_texture_size = core::dimension2du(1024, 1024); else if (size <= 168) page_texture_size = core::dimension2du(2048, 2048); else page_texture_size = core::dimension2du(4096, 4096); if (page_texture_size.Width > max_texture_size.Width || page_texture_size.Height > max_texture_size.Height) page_texture_size = max_texture_size; if (!page->createPageTexture(pixel_mode, page_texture_size)) { // TODO: add error message? delete page; return 0; } if (page) { // Determine the number of glyph slots on the page and add it to the list of pages. page->available_slots = (page_texture_size.Width / size) * (page_texture_size.Height / size); Glyph_Pages.push_back(page); } return page; } void CGUITTFont::setTransparency(const bool flag) { use_transparency = flag; reset_images(); } void CGUITTFont::setMonochrome(const bool flag) { use_monochrome = flag; reset_images(); } void CGUITTFont::setFontHinting(const bool enable, const bool enable_auto_hinting) { use_hinting = enable; use_auto_hinting = enable_auto_hinting; reset_images(); } void CGUITTFont::draw(const core::stringw& text, const core::rect<s32>& position, video::SColor color, bool hcenter, bool vcenter, const core::rect<s32>* clip) { draw(EnrichedString(std::wstring(text.c_str()), color), position, color, hcenter, vcenter, clip); } void CGUITTFont::draw(const EnrichedString &text, const core::rect<s32>& position, video::SColor color, bool hcenter, bool vcenter, const core::rect<s32>* clip) { std::vector<video::SColor> colors = text.getColors(); if (!Driver) return; // Clear the glyph pages of their render information. for (u32 i = 0; i < Glyph_Pages.size(); ++i) { Glyph_Pages[i]->render_positions.clear(); Glyph_Pages[i]->render_source_rects.clear(); } // Set up some variables. core::dimension2d<s32> textDimension; core::position2d<s32> offset = position.UpperLeftCorner; // Determine offset positions. if (hcenter || vcenter) { textDimension = getDimension(text.c_str()); if (hcenter) offset.X = ((position.getWidth() - textDimension.Width) >> 1) + offset.X; if (vcenter) offset.Y = ((position.getHeight() - textDimension.Height) >> 1) + offset.Y; } // Convert to a unicode string. core::ustring utext = text.getString(); // Set up our render map. core::map<u32, CGUITTGlyphPage*> Render_Map; // Start parsing characters. u32 n; uchar32_t previousChar = 0; core::ustring::const_iterator iter(utext); std::vector<video::SColor> applied_colors; while (!iter.atEnd()) { uchar32_t currentChar = *iter; n = getGlyphIndexByChar(currentChar); bool visible = (Invisible.findFirst(currentChar) == -1); bool lineBreak=false; if (currentChar == L'\r') // Mac or Windows breaks { lineBreak = true; if (*(iter + 1) == (uchar32_t)'\n') // Windows line breaks. currentChar = *(++iter); } else if (currentChar == (uchar32_t)'\n') // Unix breaks { lineBreak = true; } if (lineBreak) { previousChar = 0; offset.Y += font_metrics.height / 64; offset.X = position.UpperLeftCorner.X; if (hcenter) offset.X += (position.getWidth() - textDimension.Width) >> 1; ++iter; continue; } if (n > 0 && visible) { // Calculate the glyph offset. s32 offx = Glyphs[n-1].offset.X; s32 offy = (font_metrics.ascender / 64) - Glyphs[n-1].offset.Y; // Apply kerning. core::vector2di k = getKerning(currentChar, previousChar); offset.X += k.X; offset.Y += k.Y; // Determine rendering information. SGUITTGlyph& glyph = Glyphs[n-1]; CGUITTGlyphPage* const page = Glyph_Pages[glyph.glyph_page]; page->render_positions.push_back(core::position2di(offset.X + offx, offset.Y + offy)); page->render_source_rects.push_back(glyph.source_rect); Render_Map.set(glyph.glyph_page, page); u32 current_color = iter.getPos(); if (current_color < colors.size()) applied_colors.push_back(colors[current_color]); } offset.X += getWidthFromCharacter(currentChar); previousChar = currentChar; ++iter; } // Draw now. update_glyph_pages(); core::map<u32, CGUITTGlyphPage*>::Iterator j = Render_Map.getIterator(); while (!j.atEnd()) { core::map<u32, CGUITTGlyphPage*>::Node* n = j.getNode(); j++; if (n == 0) continue; CGUITTGlyphPage* page = n->getValue(); if (shadow_offset) { for (size_t i = 0; i < page->render_positions.size(); ++i) page->render_positions[i] += core::vector2di(shadow_offset, shadow_offset); Driver->draw2DImageBatch(page->texture, page->render_positions, page->render_source_rects, clip, video::SColor(shadow_alpha,0,0,0), true); for (size_t i = 0; i < page->render_positions.size(); ++i) page->render_positions[i] -= core::vector2di(shadow_offset, shadow_offset); } for (size_t i = 0; i < page->render_positions.size(); ++i) { irr::video::SColor col; if (!applied_colors.empty()) { col = applied_colors[i < applied_colors.size() ? i : 0]; } else { col = irr::video::SColor(255, 255, 255, 255); } if (!use_transparency) col.color |= 0xff000000; Driver->draw2DImage(page->texture, page->render_positions[i], page->render_source_rects[i], clip, col, true); } } } core::dimension2d<u32> CGUITTFont::getCharDimension(const wchar_t ch) const { return core::dimension2d<u32>(getWidthFromCharacter(ch), getHeightFromCharacter(ch)); } core::dimension2d<u32> CGUITTFont::getDimension(const wchar_t* text) const { return getDimension(core::ustring(text)); } core::dimension2d<u32> CGUITTFont::getDimension(const core::ustring& text) const { // Get the maximum font height. Unfortunately, we have to do this hack as // Irrlicht will draw things wrong. In FreeType, the font size is the // maximum size for a single glyph, but that glyph may hang "under" the // draw line, increasing the total font height to beyond the set size. // Irrlicht does not understand this concept when drawing fonts. Also, I // add +1 to give it a 1 pixel blank border. This makes things like // tooltips look nicer. s32 test1 = getHeightFromCharacter((uchar32_t)'g') + 1; s32 test2 = getHeightFromCharacter((uchar32_t)'j') + 1; s32 test3 = getHeightFromCharacter((uchar32_t)'_') + 1; s32 max_font_height = core::max_(test1, core::max_(test2, test3)); core::dimension2d<u32> text_dimension(0, max_font_height); core::dimension2d<u32> line(0, max_font_height); uchar32_t previousChar = 0; core::ustring::const_iterator iter = text.begin(); for (; !iter.atEnd(); ++iter) { uchar32_t p = *iter; bool lineBreak = false; if (p == '\r') // Mac or Windows line breaks. { lineBreak = true; if (*(iter + 1) == '\n') { ++iter; p = *iter; } } else if (p == '\n') // Unix line breaks. { lineBreak = true; } // Kerning. core::vector2di k = getKerning(p, previousChar); line.Width += k.X; previousChar = p; // Check for linebreak. if (lineBreak) { previousChar = 0; text_dimension.Height += line.Height; if (text_dimension.Width < line.Width) text_dimension.Width = line.Width; line.Width = 0; line.Height = max_font_height; continue; } line.Width += getWidthFromCharacter(p); } if (text_dimension.Width < line.Width) text_dimension.Width = line.Width; return text_dimension; } inline u32 CGUITTFont::getWidthFromCharacter(wchar_t c) const { return getWidthFromCharacter((uchar32_t)c); } inline u32 CGUITTFont::getWidthFromCharacter(uchar32_t c) const { // Set the size of the face. // This is because we cache faces and the face may have been set to a different size. //FT_Set_Pixel_Sizes(tt_face, 0, size); u32 n = getGlyphIndexByChar(c); if (n > 0) { int w = Glyphs[n-1].advance.x / 64; return w; } if (c >= 0x2000) return (font_metrics.ascender / 64); else return (font_metrics.ascender / 64) / 2; } inline u32 CGUITTFont::getHeightFromCharacter(wchar_t c) const { return getHeightFromCharacter((uchar32_t)c); } inline u32 CGUITTFont::getHeightFromCharacter(uchar32_t c) const { // Set the size of the face. // This is because we cache faces and the face may have been set to a different size. //FT_Set_Pixel_Sizes(tt_face, 0, size); u32 n = getGlyphIndexByChar(c); if (n > 0) { // Grab the true height of the character, taking into account underhanging glyphs. s32 height = (font_metrics.ascender / 64) - Glyphs[n-1].offset.Y + Glyphs[n-1].source_rect.getHeight(); return height; } if (c >= 0x2000) return (font_metrics.ascender / 64); else return (font_metrics.ascender / 64) / 2; } u32 CGUITTFont::getGlyphIndexByChar(wchar_t c) const { return getGlyphIndexByChar((uchar32_t)c); } u32 CGUITTFont::getGlyphIndexByChar(uchar32_t c) const { // Get the glyph. u32 glyph = FT_Get_Char_Index(tt_face, c); // Check for a valid glyph. If it is invalid, attempt to use the replacement character. if (glyph == 0) glyph = FT_Get_Char_Index(tt_face, core::unicode::UTF_REPLACEMENT_CHARACTER); // If our glyph is already loaded, don't bother doing any batch loading code. if (glyph != 0 && Glyphs[glyph - 1].isLoaded) return glyph; // Determine our batch loading positions. u32 half_size = (batch_load_size / 2); u32 start_pos = 0; if (c > half_size) start_pos = c - half_size; u32 end_pos = start_pos + batch_load_size; // Load all our characters. do { // Get the character we are going to load. u32 char_index = FT_Get_Char_Index(tt_face, start_pos); // If the glyph hasn't been loaded yet, do it now. if (char_index) { SGUITTGlyph& glyph = Glyphs[char_index - 1]; if (!glyph.isLoaded) { glyph.preload(char_index, tt_face, Driver, size, load_flags); Glyph_Pages[glyph.glyph_page]->pushGlyphToBePaged(&glyph); } } } while (++start_pos < end_pos); // Return our original character. return glyph; } s32 CGUITTFont::getCharacterFromPos(const wchar_t* text, s32 pixel_x) const { return getCharacterFromPos(core::ustring(text), pixel_x); } s32 CGUITTFont::getCharacterFromPos(const core::ustring& text, s32 pixel_x) const { s32 x = 0; //s32 idx = 0; u32 character = 0; uchar32_t previousChar = 0; core::ustring::const_iterator iter = text.begin(); while (!iter.atEnd()) { uchar32_t c = *iter; x += getWidthFromCharacter(c); // Kerning. core::vector2di k = getKerning(c, previousChar); x += k.X; if (x >= pixel_x) return character; previousChar = c; ++iter; ++character; } return -1; } void CGUITTFont::setKerningWidth(s32 kerning) { GlobalKerningWidth = kerning; } void CGUITTFont::setKerningHeight(s32 kerning) { GlobalKerningHeight = kerning; } s32 CGUITTFont::getKerningWidth(const wchar_t* thisLetter, const wchar_t* previousLetter) const { if (tt_face == 0) return GlobalKerningWidth; if (thisLetter == 0 || previousLetter == 0) return 0; return getKerningWidth((uchar32_t)*thisLetter, (uchar32_t)*previousLetter); } s32 CGUITTFont::getKerningWidth(const uchar32_t thisLetter, const uchar32_t previousLetter) const { // Return only the kerning width. return getKerning(thisLetter, previousLetter).X; } s32 CGUITTFont::getKerningHeight() const { // FreeType 2 currently doesn't return any height kerning information. return GlobalKerningHeight; } core::vector2di CGUITTFont::getKerning(const wchar_t thisLetter, const wchar_t previousLetter) const { return getKerning((uchar32_t)thisLetter, (uchar32_t)previousLetter); } core::vector2di CGUITTFont::getKerning(const uchar32_t thisLetter, const uchar32_t previousLetter) const { if (tt_face == 0 || thisLetter == 0 || previousLetter == 0) return core::vector2di(); // Set the size of the face. // This is because we cache faces and the face may have been set to a different size. FT_Set_Pixel_Sizes(tt_face, 0, size); core::vector2di ret(GlobalKerningWidth, GlobalKerningHeight); // If we don't have kerning, no point in continuing. if (!FT_HAS_KERNING(tt_face)) return ret; // Get the kerning information. FT_Vector v; FT_Get_Kerning(tt_face, getGlyphIndexByChar(previousLetter), getGlyphIndexByChar(thisLetter), FT_KERNING_DEFAULT, &v); // If we have a scalable font, the return value will be in font points. if (FT_IS_SCALABLE(tt_face)) { // Font points, so divide by 64. ret.X += (v.x / 64); ret.Y += (v.y / 64); } else { // Pixel units. ret.X += v.x; ret.Y += v.y; } return ret; } void CGUITTFont::setInvisibleCharacters(const wchar_t *s) { core::ustring us(s); Invisible = us; } void CGUITTFont::setInvisibleCharacters(const core::ustring& s) { Invisible = s; } video::IImage* CGUITTFont::createTextureFromChar(const uchar32_t& ch) { u32 n = getGlyphIndexByChar(ch); const SGUITTGlyph& glyph = Glyphs[n-1]; CGUITTGlyphPage* page = Glyph_Pages[glyph.glyph_page]; if (page->dirty) page->updateTexture(); video::ITexture* tex = page->texture; // Acquire a read-only lock of the corresponding page texture. #if IRRLICHT_VERSION_MAJOR==1 && IRRLICHT_VERSION_MINOR>=8 void* ptr = tex->lock(video::ETLM_READ_ONLY); #else void* ptr = tex->lock(true); #endif video::ECOLOR_FORMAT format = tex->getColorFormat(); core::dimension2du tex_size = tex->getOriginalSize(); video::IImage* pageholder = Driver->createImageFromData(format, tex_size, ptr, true, false); // Copy the image data out of the page texture. core::dimension2du glyph_size(glyph.source_rect.getSize()); video::IImage* image = Driver->createImage(format, glyph_size); pageholder->copyTo(image, core::position2di(0, 0), glyph.source_rect); tex->unlock(); return image; } video::ITexture* CGUITTFont::getPageTextureByIndex(const u32& page_index) const { if (page_index < Glyph_Pages.size()) return Glyph_Pages[page_index]->texture; else return 0; } void CGUITTFont::createSharedPlane() { /* 2___3 | /| | / | <-- plane mesh is like this, point 2 is (0,0), point 0 is (0, -1) |/ | <-- the texture coords of point 2 is (0,0, point 0 is (0, 1) 0---1 */ using namespace core; using namespace video; using namespace scene; S3DVertex vertices[4]; u16 indices[6] = {0,2,3,3,1,0}; vertices[0] = S3DVertex(vector3df(0,-1,0), vector3df(0,0,-1), SColor(255,255,255,255), vector2df(0,1)); vertices[1] = S3DVertex(vector3df(1,-1,0), vector3df(0,0,-1), SColor(255,255,255,255), vector2df(1,1)); vertices[2] = S3DVertex(vector3df(0, 0,0), vector3df(0,0,-1), SColor(255,255,255,255), vector2df(0,0)); vertices[3] = S3DVertex(vector3df(1, 0,0), vector3df(0,0,-1), SColor(255,255,255,255), vector2df(1,0)); SMeshBuffer* buf = new SMeshBuffer(); buf->append(vertices, 4, indices, 6); shared_plane_.addMeshBuffer( buf ); shared_plane_ptr_ = &shared_plane_; buf->drop(); //the addMeshBuffer method will grab it, so we can drop this ptr. } core::dimension2d<u32> CGUITTFont::getDimensionUntilEndOfLine(const wchar_t* p) const { core::stringw s; for (const wchar_t* temp = p; temp && *temp != '\0' && *temp != L'\r' && *temp != L'\n'; ++temp ) s.append(*temp); return getDimension(s.c_str()); } core::array<scene::ISceneNode*> CGUITTFont::addTextSceneNode(const wchar_t* text, scene::ISceneManager* smgr, scene::ISceneNode* parent, const video::SColor& color, bool center) { using namespace core; using namespace video; using namespace scene; array<scene::ISceneNode*> container; if (!Driver || !smgr) return container; if (!parent) parent = smgr->addEmptySceneNode(smgr->getRootSceneNode(), -1); // if you don't specify parent, then we add a empty node attached to the root node // this is generally undesirable. if (!shared_plane_ptr_) //this points to a static mesh that contains the plane createSharedPlane(); //if it's not initialized, we create one. dimension2d<s32> text_size(getDimension(text)); //convert from unsigned to signed. vector3df start_point(0, 0, 0), offset; /** NOTICE: Because we are considering adding texts into 3D world, all Y axis vectors are inverted. **/ // There's currently no "vertical center" concept when you apply text scene node to the 3D world. if (center) { offset.X = start_point.X = -text_size.Width / 2.f; offset.Y = start_point.Y = +text_size.Height/ 2.f; offset.X += (text_size.Width - getDimensionUntilEndOfLine(text).Width) >> 1; } // the default font material SMaterial mat; mat.setFlag(video::EMF_LIGHTING, true); mat.setFlag(video::EMF_ZWRITE_ENABLE, false); mat.setFlag(video::EMF_NORMALIZE_NORMALS, true); mat.ColorMaterial = video::ECM_NONE; mat.MaterialType = use_transparency ? video::EMT_TRANSPARENT_ALPHA_CHANNEL : video::EMT_SOLID; mat.MaterialTypeParam = 0.01f; mat.DiffuseColor = color; wchar_t current_char = 0, previous_char = 0; u32 n = 0; array<u32> glyph_indices; while (*text) { current_char = *text; bool line_break=false; if (current_char == L'\r') // Mac or Windows breaks { line_break = true; if (*(text + 1) == L'\n') // Windows line breaks. current_char = *(++text); } else if (current_char == L'\n') // Unix breaks { line_break = true; } if (line_break) { previous_char = 0; offset.Y -= tt_face->size->metrics.ascender / 64; offset.X = start_point.X; if (center) offset.X += (text_size.Width - getDimensionUntilEndOfLine(text+1).Width) >> 1; ++text; } else { n = getGlyphIndexByChar(current_char); if (n > 0) { glyph_indices.push_back( n ); // Store glyph size and offset informations. SGUITTGlyph const& glyph = Glyphs[n-1]; u32 texw = glyph.source_rect.getWidth(); u32 texh = glyph.source_rect.getHeight(); s32 offx = glyph.offset.X; s32 offy = (font_metrics.ascender / 64) - glyph.offset.Y; // Apply kerning. vector2di k = getKerning(current_char, previous_char); offset.X += k.X; offset.Y += k.Y; vector3df current_pos(offset.X + offx, offset.Y - offy, 0); dimension2d<u32> letter_size = dimension2d<u32>(texw, texh); // Now we copy planes corresponding to the letter size. IMeshManipulator* mani = smgr->getMeshManipulator(); IMesh* meshcopy = mani->createMeshCopy(shared_plane_ptr_); #if IRRLICHT_VERSION_MAJOR==1 && IRRLICHT_VERSION_MINOR>=8 mani->scale(meshcopy, vector3df((f32)letter_size.Width, (f32)letter_size.Height, 1)); #else mani->scaleMesh(meshcopy, vector3df((f32)letter_size.Width, (f32)letter_size.Height, 1)); #endif ISceneNode* current_node = smgr->addMeshSceneNode(meshcopy, parent, -1, current_pos); meshcopy->drop(); current_node->getMaterial(0) = mat; current_node->setAutomaticCulling(EAC_OFF); current_node->setIsDebugObject(true); //so the picking won't have any effect on individual letter //current_node->setDebugDataVisible(EDS_BBOX); //de-comment this when debugging container.push_back(current_node); } offset.X += getWidthFromCharacter(current_char); previous_char = current_char; ++text; } } update_glyph_pages(); //only after we update the textures can we use the glyph page textures. for (u32 i = 0; i < glyph_indices.size(); ++i) { u32 n = glyph_indices[i]; SGUITTGlyph const& glyph = Glyphs[n-1]; ITexture* current_tex = Glyph_Pages[glyph.glyph_page]->texture; f32 page_texture_size = (f32)current_tex->getSize().Width; //Now we calculate the UV position according to the texture size and the source rect. // // 2___3 // | /| // | / | <-- plane mesh is like this, point 2 is (0,0), point 0 is (0, -1) // |/ | <-- the texture coords of point 2 is (0,0, point 0 is (0, 1) // 0---1 // f32 u1 = glyph.source_rect.UpperLeftCorner.X / page_texture_size; f32 u2 = u1 + (glyph.source_rect.getWidth() / page_texture_size); f32 v1 = glyph.source_rect.UpperLeftCorner.Y / page_texture_size; f32 v2 = v1 + (glyph.source_rect.getHeight() / page_texture_size); //we can be quite sure that this is IMeshSceneNode, because we just added them in the above loop. IMeshSceneNode* node = static_cast<IMeshSceneNode*>(container[i]); S3DVertex* pv = static_cast<S3DVertex*>(node->getMesh()->getMeshBuffer(0)->getVertices()); //pv[0].TCoords.Y = pv[1].TCoords.Y = (letter_size.Height - 1) / static_cast<f32>(letter_size.Height); //pv[1].TCoords.X = pv[3].TCoords.X = (letter_size.Width - 1) / static_cast<f32>(letter_size.Width); pv[0].TCoords = vector2df(u1, v2); pv[1].TCoords = vector2df(u2, v2); pv[2].TCoords = vector2df(u1, v1); pv[3].TCoords = vector2df(u2, v1); container[i]->getMaterial(0).setTexture(0, current_tex); } return container; } } // end namespace gui } // end namespace irr
pgimeno/minetest
src/irrlicht_changes/CGUITTFont.cpp
C++
mit
34,499
/* CGUITTFont FreeType class for Irrlicht Copyright (c) 2009-2010 John Norman Copyright (c) 2016 Nathanaël Courant This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. The original version of this class can be located at: http://irrlicht.suckerfreegames.com/ John Norman john@suckerfreegames.com */ #pragma once #include <irrlicht.h> #include <ft2build.h> #include <vector> #include "irrUString.h" #include "util/enriched_string.h" #include FT_FREETYPE_H namespace irr { namespace gui { struct SGUITTFace; class CGUITTFont; //! Class to assist in deleting glyphs. class CGUITTAssistDelete { public: template <class T, typename TAlloc> static void Delete(core::array<T, TAlloc>& a) { TAlloc allocator; allocator.deallocate(a.pointer()); } }; //! Structure representing a single TrueType glyph. struct SGUITTGlyph { //! Constructor. SGUITTGlyph() : isLoaded(false), glyph_page(0), surface(0), parent(0) {} //! Destructor. ~SGUITTGlyph() { unload(); } //! Preload the glyph. //! The preload process occurs when the program tries to cache the glyph from FT_Library. //! However, it simply defines the SGUITTGlyph's properties and will only create the page //! textures if necessary. The actual creation of the textures should only occur right //! before the batch draw call. void preload(u32 char_index, FT_Face face, video::IVideoDriver* driver, u32 font_size, const FT_Int32 loadFlags); //! Unloads the glyph. void unload(); //! Creates the IImage object from the FT_Bitmap. video::IImage* createGlyphImage(const FT_Bitmap& bits, video::IVideoDriver* driver) const; //! If true, the glyph has been loaded. bool isLoaded; //! The page the glyph is on. u32 glyph_page; //! The source rectangle for the glyph. core::recti source_rect; //! The offset of glyph when drawn. core::vector2di offset; //! Glyph advance information. FT_Vector advance; //! This is just the temporary image holder. After this glyph is paged, //! it will be dropped. mutable video::IImage* surface; //! The pointer pointing to the parent (CGUITTFont) CGUITTFont* parent; }; //! Holds a sheet of glyphs. class CGUITTGlyphPage { public: CGUITTGlyphPage(video::IVideoDriver* Driver, const io::path& texture_name) :texture(0), available_slots(0), used_slots(0), dirty(false), driver(Driver), name(texture_name) {} ~CGUITTGlyphPage() { if (texture) { if (driver) driver->removeTexture(texture); else texture->drop(); } } //! Create the actual page texture, bool createPageTexture(const u8& pixel_mode, const core::dimension2du& texture_size) { if( texture ) return false; bool flgmip = driver->getTextureCreationFlag(video::ETCF_CREATE_MIP_MAPS); driver->setTextureCreationFlag(video::ETCF_CREATE_MIP_MAPS, false); #if IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR > 8 bool flgcpy = driver->getTextureCreationFlag(video::ETCF_ALLOW_MEMORY_COPY); driver->setTextureCreationFlag(video::ETCF_ALLOW_MEMORY_COPY, true); #endif // Set the texture color format. switch (pixel_mode) { case FT_PIXEL_MODE_MONO: texture = driver->addTexture(texture_size, name, video::ECF_A1R5G5B5); break; case FT_PIXEL_MODE_GRAY: default: texture = driver->addTexture(texture_size, name, video::ECF_A8R8G8B8); break; } // Restore our texture creation flags. driver->setTextureCreationFlag(video::ETCF_CREATE_MIP_MAPS, flgmip); #if IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR > 8 driver->setTextureCreationFlag(video::ETCF_ALLOW_MEMORY_COPY, flgcpy); #endif return texture ? true : false; } //! Add the glyph to a list of glyphs to be paged. //! This collection will be cleared after updateTexture is called. void pushGlyphToBePaged(const SGUITTGlyph* glyph) { glyph_to_be_paged.push_back(glyph); } //! Updates the texture atlas with new glyphs. void updateTexture() { if (!dirty) return; void* ptr = texture->lock(); video::ECOLOR_FORMAT format = texture->getColorFormat(); core::dimension2du size = texture->getOriginalSize(); video::IImage* pageholder = driver->createImageFromData(format, size, ptr, true, false); for (u32 i = 0; i < glyph_to_be_paged.size(); ++i) { const SGUITTGlyph* glyph = glyph_to_be_paged[i]; if (glyph && glyph->isLoaded) { if (glyph->surface) { glyph->surface->copyTo(pageholder, glyph->source_rect.UpperLeftCorner); glyph->surface->drop(); glyph->surface = 0; } else { ; // TODO: add error message? //currently, if we failed to create the image, just ignore this operation. } } } pageholder->drop(); texture->unlock(); glyph_to_be_paged.clear(); dirty = false; } video::ITexture* texture; u32 available_slots; u32 used_slots; bool dirty; core::array<core::vector2di> render_positions; core::array<core::recti> render_source_rects; private: core::array<const SGUITTGlyph*> glyph_to_be_paged; video::IVideoDriver* driver; io::path name; }; //! Class representing a TrueType font. class CGUITTFont : public IGUIFont { public: //! Creates a new TrueType font and returns a pointer to it. The pointer must be drop()'ed when finished. //! \param env The IGUIEnvironment the font loads out of. //! \param filename The filename of the font. //! \param size The size of the font glyphs in pixels. Since this is the size of the individual glyphs, the true height of the font may change depending on the characters used. //! \param antialias set the use_monochrome (opposite to antialias) flag //! \param transparency set the use_transparency flag //! \return Returns a pointer to a CGUITTFont. Will return 0 if the font failed to load. static CGUITTFont* createTTFont(IGUIEnvironment *env, const io::path& filename, const u32 size, const bool antialias = true, const bool transparency = true, const u32 shadow = 0, const u32 shadow_alpha = 255); static CGUITTFont* createTTFont(IrrlichtDevice *device, const io::path& filename, const u32 size, const bool antialias = true, const bool transparency = true); static CGUITTFont* create(IGUIEnvironment *env, const io::path& filename, const u32 size, const bool antialias = true, const bool transparency = true); static CGUITTFont* create(IrrlichtDevice *device, const io::path& filename, const u32 size, const bool antialias = true, const bool transparency = true); //! Destructor virtual ~CGUITTFont(); //! Sets the amount of glyphs to batch load. virtual void setBatchLoadSize(u32 batch_size) { batch_load_size = batch_size; } //! Sets the maximum texture size for a page of glyphs. virtual void setMaxPageTextureSize(const core::dimension2du& texture_size) { max_page_texture_size = texture_size; } //! Get the font size. virtual u32 getFontSize() const { return size; } //! Check the font's transparency. virtual bool isTransparent() const { return use_transparency; } //! Check if the font auto-hinting is enabled. //! Auto-hinting is FreeType's built-in font hinting engine. virtual bool useAutoHinting() const { return use_auto_hinting; } //! Check if the font hinting is enabled. virtual bool useHinting() const { return use_hinting; } //! Check if the font is being loaded as a monochrome font. //! The font can either be a 256 color grayscale font, or a 2 color monochrome font. virtual bool useMonochrome() const { return use_monochrome; } //! Tells the font to allow transparency when rendering. //! Default: true. //! \param flag If true, the font draws using transparency. virtual void setTransparency(const bool flag); //! Tells the font to use monochrome rendering. //! Default: false. //! \param flag If true, the font draws using a monochrome image. If false, the font uses a grayscale image. virtual void setMonochrome(const bool flag); //! Enables or disables font hinting. //! Default: Hinting and auto-hinting true. //! \param enable If false, font hinting is turned off. If true, font hinting is turned on. //! \param enable_auto_hinting If true, FreeType uses its own auto-hinting algorithm. If false, it tries to use the algorithm specified by the font. virtual void setFontHinting(const bool enable, const bool enable_auto_hinting = true); //! Draws some text and clips it to the specified rectangle if wanted. virtual void draw(const core::stringw& text, const core::rect<s32>& position, video::SColor color, bool hcenter=false, bool vcenter=false, const core::rect<s32>* clip=0); virtual void draw(const EnrichedString& text, const core::rect<s32>& position, video::SColor color, bool hcenter=false, bool vcenter=false, const core::rect<s32>* clip=0); //! Returns the dimension of a character produced by this font. virtual core::dimension2d<u32> getCharDimension(const wchar_t ch) const; //! Returns the dimension of a text string. virtual core::dimension2d<u32> getDimension(const wchar_t* text) const; virtual core::dimension2d<u32> getDimension(const core::ustring& text) const; //! Calculates the index of the character in the text which is on a specific position. virtual s32 getCharacterFromPos(const wchar_t* text, s32 pixel_x) const; virtual s32 getCharacterFromPos(const core::ustring& text, s32 pixel_x) const; //! Sets global kerning width for the font. virtual void setKerningWidth(s32 kerning); //! Sets global kerning height for the font. virtual void setKerningHeight(s32 kerning); //! Gets kerning values (distance between letters) for the font. If no parameters are provided, virtual s32 getKerningWidth(const wchar_t* thisLetter=0, const wchar_t* previousLetter=0) const; virtual s32 getKerningWidth(const uchar32_t thisLetter=0, const uchar32_t previousLetter=0) const; //! Returns the distance between letters virtual s32 getKerningHeight() const; //! Define which characters should not be drawn by the font. virtual void setInvisibleCharacters(const wchar_t *s); virtual void setInvisibleCharacters(const core::ustring& s); //! Get the last glyph page if there's still available slots. //! If not, it will return zero. CGUITTGlyphPage* getLastGlyphPage() const; //! Create a new glyph page texture. //! \param pixel_mode the pixel mode defined by FT_Pixel_Mode //should be better typed. fix later. CGUITTGlyphPage* createGlyphPage(const u8& pixel_mode); //! Get the last glyph page's index. u32 getLastGlyphPageIndex() const { return Glyph_Pages.size() - 1; } //! Create corresponding character's software image copy from the font, //! so you can use this data just like any ordinary video::IImage. //! \param ch The character you need virtual video::IImage* createTextureFromChar(const uchar32_t& ch); //! This function is for debugging mostly. If the page doesn't exist it returns zero. //! \param page_index Simply return the texture handle of a given page index. virtual video::ITexture* getPageTextureByIndex(const u32& page_index) const; //! Add a list of scene nodes generated by putting font textures on the 3D planes. virtual core::array<scene::ISceneNode*> addTextSceneNode (const wchar_t* text, scene::ISceneManager* smgr, scene::ISceneNode* parent = 0, const video::SColor& color = video::SColor(255, 0, 0, 0), bool center = false ); protected: bool use_monochrome; bool use_transparency; bool use_hinting; bool use_auto_hinting; u32 size; u32 batch_load_size; core::dimension2du max_page_texture_size; private: // Manages the FreeType library. static FT_Library c_library; static core::map<io::path, SGUITTFace*> c_faces; static bool c_libraryLoaded; static scene::IMesh* shared_plane_ptr_; static scene::SMesh shared_plane_; CGUITTFont(IGUIEnvironment *env); bool load(const io::path& filename, const u32 size, const bool antialias, const bool transparency); void reset_images(); void update_glyph_pages() const; void update_load_flags() { // Set up our loading flags. load_flags = FT_LOAD_DEFAULT | FT_LOAD_RENDER; if (!useHinting()) load_flags |= FT_LOAD_NO_HINTING; if (!useAutoHinting()) load_flags |= FT_LOAD_NO_AUTOHINT; if (useMonochrome()) load_flags |= FT_LOAD_MONOCHROME | FT_LOAD_TARGET_MONO | FT_RENDER_MODE_MONO; else load_flags |= FT_LOAD_TARGET_NORMAL; } u32 getWidthFromCharacter(wchar_t c) const; u32 getWidthFromCharacter(uchar32_t c) const; u32 getHeightFromCharacter(wchar_t c) const; u32 getHeightFromCharacter(uchar32_t c) const; u32 getGlyphIndexByChar(wchar_t c) const; u32 getGlyphIndexByChar(uchar32_t c) const; core::vector2di getKerning(const wchar_t thisLetter, const wchar_t previousLetter) const; core::vector2di getKerning(const uchar32_t thisLetter, const uchar32_t previousLetter) const; core::dimension2d<u32> getDimensionUntilEndOfLine(const wchar_t* p) const; void createSharedPlane(); irr::IrrlichtDevice* Device; gui::IGUIEnvironment* Environment; video::IVideoDriver* Driver; io::path filename; FT_Face tt_face; FT_Size_Metrics font_metrics; FT_Int32 load_flags; mutable core::array<CGUITTGlyphPage*> Glyph_Pages; mutable core::array<SGUITTGlyph> Glyphs; s32 GlobalKerningWidth; s32 GlobalKerningHeight; core::ustring Invisible; u32 shadow_offset; u32 shadow_alpha; }; } // end namespace gui } // end namespace irr
pgimeno/minetest
src/irrlicht_changes/CGUITTFont.h
C++
mit
14,536
if (BUILD_CLIENT) set(client_irrlicht_changes_SRCS ${CMAKE_CURRENT_SOURCE_DIR}/static_text.cpp ) if (ENABLE_FREETYPE) set(client_irrlicht_changes_SRCS ${client_irrlicht_changes_SRCS} ${CMAKE_CURRENT_SOURCE_DIR}/CGUITTFont.cpp ) endif() # CMake require us to set a local scope and then parent scope # Else the last set win in parent scope set(client_irrlicht_changes_SRCS ${client_irrlicht_changes_SRCS} PARENT_SCOPE) endif()
pgimeno/minetest
src/irrlicht_changes/CMakeLists.txt
Text
mit
444
/* Basic Unicode string class for Irrlicht. Copyright (c) 2009-2011 John Norman This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. The original version of this class can be located at: http://irrlicht.suckerfreegames.com/ John Norman john@suckerfreegames.com */ #pragma once #if (__cplusplus > 199711L) || (_MSC_VER >= 1600) || defined(__GXX_EXPERIMENTAL_CXX0X__) # define USTRING_CPP0X # if defined(__GXX_EXPERIMENTAL_CXX0X__) && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 5))) # define USTRING_CPP0X_NEWLITERALS # endif #endif #include <stdio.h> #include <string.h> #include <stdlib.h> #include <cstddef> #ifdef _WIN32 #define __BYTE_ORDER 0 #define __LITTLE_ENDIAN 0 #define __BIG_ENDIAN 1 #elif defined(__MACH__) && defined(__APPLE__) #include <machine/endian.h> #elif defined(__FreeBSD__) || defined(__DragonFly__) #include <sys/endian.h> #else #include <endian.h> #endif #ifdef USTRING_CPP0X # include <utility> #endif #ifndef USTRING_NO_STL # include <string> # include <iterator> # include <ostream> #endif #include "irrTypes.h" #include "irrAllocator.h" #include "irrArray.h" #include "irrMath.h" #include "irrString.h" #include "path.h" //! UTF-16 surrogate start values. static const irr::u16 UTF16_HI_SURROGATE = 0xD800; static const irr::u16 UTF16_LO_SURROGATE = 0xDC00; //! Is a UTF-16 code point a surrogate? #define UTF16_IS_SURROGATE(c) (((c) & 0xF800) == 0xD800) #define UTF16_IS_SURROGATE_HI(c) (((c) & 0xFC00) == 0xD800) #define UTF16_IS_SURROGATE_LO(c) (((c) & 0xFC00) == 0xDC00) namespace irr { // Define our character types. #ifdef USTRING_CPP0X_NEWLITERALS // C++0x typedef char32_t uchar32_t; typedef char16_t uchar16_t; typedef char uchar8_t; #else typedef u32 uchar32_t; typedef u16 uchar16_t; typedef u8 uchar8_t; #endif namespace core { namespace unicode { //! The unicode replacement character. Used to replace invalid characters. const irr::u16 UTF_REPLACEMENT_CHARACTER = 0xFFFD; //! Convert a UTF-16 surrogate pair into a UTF-32 character. //! \param high The high value of the pair. //! \param low The low value of the pair. //! \return The UTF-32 character expressed by the surrogate pair. inline uchar32_t toUTF32(uchar16_t high, uchar16_t low) { // Convert the surrogate pair into a single UTF-32 character. uchar32_t x = ((high & ((1 << 6) -1)) << 10) | (low & ((1 << 10) -1)); uchar32_t wu = ((high >> 6) & ((1 << 5) - 1)) + 1; return (wu << 16) | x; } //! Swaps the endianness of a 16-bit value. //! \return The new value. inline uchar16_t swapEndian16(const uchar16_t& c) { return ((c >> 8) & 0x00FF) | ((c << 8) & 0xFF00); } //! Swaps the endianness of a 32-bit value. //! \return The new value. inline uchar32_t swapEndian32(const uchar32_t& c) { return ((c >> 24) & 0x000000FF) | ((c >> 8) & 0x0000FF00) | ((c << 8) & 0x00FF0000) | ((c << 24) & 0xFF000000); } //! The Unicode byte order mark. const u16 BOM = 0xFEFF; //! The size of the Unicode byte order mark in terms of the Unicode character size. const u8 BOM_UTF8_LEN = 3; const u8 BOM_UTF16_LEN = 1; const u8 BOM_UTF32_LEN = 1; //! Unicode byte order marks for file operations. const u8 BOM_ENCODE_UTF8[3] = { 0xEF, 0xBB, 0xBF }; const u8 BOM_ENCODE_UTF16_BE[2] = { 0xFE, 0xFF }; const u8 BOM_ENCODE_UTF16_LE[2] = { 0xFF, 0xFE }; const u8 BOM_ENCODE_UTF32_BE[4] = { 0x00, 0x00, 0xFE, 0xFF }; const u8 BOM_ENCODE_UTF32_LE[4] = { 0xFF, 0xFE, 0x00, 0x00 }; //! The size in bytes of the Unicode byte marks for file operations. const u8 BOM_ENCODE_UTF8_LEN = 3; const u8 BOM_ENCODE_UTF16_LEN = 2; const u8 BOM_ENCODE_UTF32_LEN = 4; //! Unicode encoding type. enum EUTF_ENCODE { EUTFE_NONE = 0, EUTFE_UTF8, EUTFE_UTF16, EUTFE_UTF16_LE, EUTFE_UTF16_BE, EUTFE_UTF32, EUTFE_UTF32_LE, EUTFE_UTF32_BE }; //! Unicode endianness. enum EUTF_ENDIAN { EUTFEE_NATIVE = 0, EUTFEE_LITTLE, EUTFEE_BIG }; //! Returns the specified unicode byte order mark in a byte array. //! The byte order mark is the first few bytes in a text file that signifies its encoding. /** \param mode The Unicode encoding method that we want to get the byte order mark for. If EUTFE_UTF16 or EUTFE_UTF32 is passed, it uses the native system endianness. **/ //! \return An array that contains a byte order mark. inline core::array<u8> getUnicodeBOM(EUTF_ENCODE mode) { #define COPY_ARRAY(source, size) \ memcpy(ret.pointer(), source, size); \ ret.set_used(size) core::array<u8> ret(4); switch (mode) { case EUTFE_UTF8: COPY_ARRAY(BOM_ENCODE_UTF8, BOM_ENCODE_UTF8_LEN); break; case EUTFE_UTF16: #ifdef __BIG_ENDIAN__ COPY_ARRAY(BOM_ENCODE_UTF16_BE, BOM_ENCODE_UTF16_LEN); #else COPY_ARRAY(BOM_ENCODE_UTF16_LE, BOM_ENCODE_UTF16_LEN); #endif break; case EUTFE_UTF16_BE: COPY_ARRAY(BOM_ENCODE_UTF16_BE, BOM_ENCODE_UTF16_LEN); break; case EUTFE_UTF16_LE: COPY_ARRAY(BOM_ENCODE_UTF16_LE, BOM_ENCODE_UTF16_LEN); break; case EUTFE_UTF32: #ifdef __BIG_ENDIAN__ COPY_ARRAY(BOM_ENCODE_UTF32_BE, BOM_ENCODE_UTF32_LEN); #else COPY_ARRAY(BOM_ENCODE_UTF32_LE, BOM_ENCODE_UTF32_LEN); #endif break; case EUTFE_UTF32_BE: COPY_ARRAY(BOM_ENCODE_UTF32_BE, BOM_ENCODE_UTF32_LEN); break; case EUTFE_UTF32_LE: COPY_ARRAY(BOM_ENCODE_UTF32_LE, BOM_ENCODE_UTF32_LEN); break; case EUTFE_NONE: // TODO sapier: fixed warning only, // don't know if something needs to be done here break; } return ret; #undef COPY_ARRAY } //! Detects if the given data stream starts with a unicode BOM. //! \param data The data stream to check. //! \return The unicode BOM associated with the data stream, or EUTFE_NONE if none was found. inline EUTF_ENCODE determineUnicodeBOM(const char* data) { if (memcmp(data, BOM_ENCODE_UTF8, 3) == 0) return EUTFE_UTF8; if (memcmp(data, BOM_ENCODE_UTF16_BE, 2) == 0) return EUTFE_UTF16_BE; if (memcmp(data, BOM_ENCODE_UTF16_LE, 2) == 0) return EUTFE_UTF16_LE; if (memcmp(data, BOM_ENCODE_UTF32_BE, 4) == 0) return EUTFE_UTF32_BE; if (memcmp(data, BOM_ENCODE_UTF32_LE, 4) == 0) return EUTFE_UTF32_LE; return EUTFE_NONE; } } // end namespace unicode //! UTF-16 string class. template <typename TAlloc = irrAllocator<uchar16_t> > class ustring16 { public: ///------------------/// /// iterator classes /// ///------------------/// //! Access an element in a unicode string, allowing one to change it. class _ustring16_iterator_access { public: _ustring16_iterator_access(const ustring16<TAlloc>* s, u32 p) : ref(s), pos(p) {} //! Allow the class to be interpreted as a single UTF-32 character. operator uchar32_t() const { return _get(); } //! Allow one to change the character in the unicode string. //! \param c The new character to use. //! \return Myself. _ustring16_iterator_access& operator=(const uchar32_t c) { _set(c); return *this; } //! Increments the value by 1. //! \return Myself. _ustring16_iterator_access& operator++() { _set(_get() + 1); return *this; } //! Increments the value by 1, returning the old value. //! \return A unicode character. uchar32_t operator++(int) { uchar32_t old = _get(); _set(old + 1); return old; } //! Decrements the value by 1. //! \return Myself. _ustring16_iterator_access& operator--() { _set(_get() - 1); return *this; } //! Decrements the value by 1, returning the old value. //! \return A unicode character. uchar32_t operator--(int) { uchar32_t old = _get(); _set(old - 1); return old; } //! Adds to the value by a specified amount. //! \param val The amount to add to this character. //! \return Myself. _ustring16_iterator_access& operator+=(int val) { _set(_get() + val); return *this; } //! Subtracts from the value by a specified amount. //! \param val The amount to subtract from this character. //! \return Myself. _ustring16_iterator_access& operator-=(int val) { _set(_get() - val); return *this; } //! Multiples the value by a specified amount. //! \param val The amount to multiply this character by. //! \return Myself. _ustring16_iterator_access& operator*=(int val) { _set(_get() * val); return *this; } //! Divides the value by a specified amount. //! \param val The amount to divide this character by. //! \return Myself. _ustring16_iterator_access& operator/=(int val) { _set(_get() / val); return *this; } //! Modulos the value by a specified amount. //! \param val The amount to modulo this character by. //! \return Myself. _ustring16_iterator_access& operator%=(int val) { _set(_get() % val); return *this; } //! Adds to the value by a specified amount. //! \param val The amount to add to this character. //! \return A unicode character. uchar32_t operator+(int val) const { return _get() + val; } //! Subtracts from the value by a specified amount. //! \param val The amount to subtract from this character. //! \return A unicode character. uchar32_t operator-(int val) const { return _get() - val; } //! Multiplies the value by a specified amount. //! \param val The amount to multiply this character by. //! \return A unicode character. uchar32_t operator*(int val) const { return _get() * val; } //! Divides the value by a specified amount. //! \param val The amount to divide this character by. //! \return A unicode character. uchar32_t operator/(int val) const { return _get() / val; } //! Modulos the value by a specified amount. //! \param val The amount to modulo this character by. //! \return A unicode character. uchar32_t operator%(int val) const { return _get() % val; } private: //! Gets a uchar32_t from our current position. uchar32_t _get() const { const uchar16_t* a = ref->c_str(); if (!UTF16_IS_SURROGATE(a[pos])) return static_cast<uchar32_t>(a[pos]); else { if (pos + 1 >= ref->size_raw()) return 0; return unicode::toUTF32(a[pos], a[pos + 1]); } } //! Sets a uchar32_t at our current position. void _set(uchar32_t c) { ustring16<TAlloc>* ref2 = const_cast<ustring16<TAlloc>*>(ref); const uchar16_t* a = ref2->c_str(); if (c > 0xFFFF) { // c will be multibyte, so split it up into the high and low surrogate pairs. uchar16_t x = static_cast<uchar16_t>(c); uchar16_t vh = UTF16_HI_SURROGATE | ((((c >> 16) & ((1 << 5) - 1)) - 1) << 6) | (x >> 10); uchar16_t vl = UTF16_LO_SURROGATE | (x & ((1 << 10) - 1)); // If the previous position was a surrogate pair, just replace them. Else, insert the low pair. if (UTF16_IS_SURROGATE_HI(a[pos]) && pos + 1 != ref2->size_raw()) ref2->replace_raw(vl, static_cast<u32>(pos) + 1); else ref2->insert_raw(vl, static_cast<u32>(pos) + 1); ref2->replace_raw(vh, static_cast<u32>(pos)); } else { // c will be a single byte. uchar16_t vh = static_cast<uchar16_t>(c); // If the previous position was a surrogate pair, remove the extra byte. if (UTF16_IS_SURROGATE_HI(a[pos])) ref2->erase_raw(static_cast<u32>(pos) + 1); ref2->replace_raw(vh, static_cast<u32>(pos)); } } const ustring16<TAlloc>* ref; u32 pos; }; typedef typename ustring16<TAlloc>::_ustring16_iterator_access access; //! Iterator to iterate through a UTF-16 string. #ifndef USTRING_NO_STL class _ustring16_const_iterator : public std::iterator< std::bidirectional_iterator_tag, // iterator_category access, // value_type ptrdiff_t, // difference_type const access, // pointer const access // reference > #else class _ustring16_const_iterator #endif { public: typedef _ustring16_const_iterator _Iter; typedef std::iterator<std::bidirectional_iterator_tag, access, ptrdiff_t, const access, const access> _Base; typedef const access const_pointer; typedef const access const_reference; #ifndef USTRING_NO_STL typedef typename _Base::value_type value_type; typedef typename _Base::difference_type difference_type; typedef typename _Base::difference_type distance_type; typedef typename _Base::pointer pointer; typedef const_reference reference; #else typedef access value_type; typedef u32 difference_type; typedef u32 distance_type; typedef const_pointer pointer; typedef const_reference reference; #endif //! Constructors. _ustring16_const_iterator(const _Iter& i) : ref(i.ref), pos(i.pos) {} _ustring16_const_iterator(const ustring16<TAlloc>& s) : ref(&s), pos(0) {} _ustring16_const_iterator(const ustring16<TAlloc>& s, const u32 p) : ref(&s), pos(0) { if (ref->size_raw() == 0 || p == 0) return; // Go to the appropriate position. u32 i = p; u32 sr = ref->size_raw(); const uchar16_t* a = ref->c_str(); while (i != 0 && pos < sr) { if (UTF16_IS_SURROGATE_HI(a[pos])) pos += 2; else ++pos; --i; } } //! Test for equalness. bool operator==(const _Iter& iter) const { if (ref == iter.ref && pos == iter.pos) return true; return false; } //! Test for unequalness. bool operator!=(const _Iter& iter) const { if (ref != iter.ref || pos != iter.pos) return true; return false; } //! Switch to the next full character in the string. _Iter& operator++() { // ++iterator if (pos == ref->size_raw()) return *this; const uchar16_t* a = ref->c_str(); if (UTF16_IS_SURROGATE_HI(a[pos])) pos += 2; // TODO: check for valid low surrogate? else ++pos; if (pos > ref->size_raw()) pos = ref->size_raw(); return *this; } //! Switch to the next full character in the string, returning the previous position. _Iter operator++(int) { // iterator++ _Iter _tmp(*this); ++*this; return _tmp; } //! Switch to the previous full character in the string. _Iter& operator--() { // --iterator if (pos == 0) return *this; const uchar16_t* a = ref->c_str(); --pos; if (UTF16_IS_SURROGATE_LO(a[pos]) && pos != 0) // low surrogate, go back one more. --pos; return *this; } //! Switch to the previous full character in the string, returning the previous position. _Iter operator--(int) { // iterator-- _Iter _tmp(*this); --*this; return _tmp; } //! Advance a specified number of full characters in the string. //! \return Myself. _Iter& operator+=(const difference_type v) { if (v == 0) return *this; if (v < 0) return operator-=(v * -1); if (pos >= ref->size_raw()) return *this; // Go to the appropriate position. // TODO: Don't force u32 on an x64 OS. Make it agnostic. u32 i = (u32)v; u32 sr = ref->size_raw(); const uchar16_t* a = ref->c_str(); while (i != 0 && pos < sr) { if (UTF16_IS_SURROGATE_HI(a[pos])) pos += 2; else ++pos; --i; } if (pos > sr) pos = sr; return *this; } //! Go back a specified number of full characters in the string. //! \return Myself. _Iter& operator-=(const difference_type v) { if (v == 0) return *this; if (v > 0) return operator+=(v * -1); if (pos == 0) return *this; // Go to the appropriate position. // TODO: Don't force u32 on an x64 OS. Make it agnostic. u32 i = (u32)v; const uchar16_t* a = ref->c_str(); while (i != 0 && pos != 0) { --pos; if (UTF16_IS_SURROGATE_LO(a[pos]) != 0 && pos != 0) --pos; --i; } return *this; } //! Return a new iterator that is a variable number of full characters forward from the current position. _Iter operator+(const difference_type v) const { _Iter ret(*this); ret += v; return ret; } //! Return a new iterator that is a variable number of full characters backward from the current position. _Iter operator-(const difference_type v) const { _Iter ret(*this); ret -= v; return ret; } //! Returns the distance between two iterators. difference_type operator-(const _Iter& iter) const { // Make sure we reference the same object! if (ref != iter.ref) return difference_type(); _Iter i = iter; difference_type ret; // Walk up. if (pos > i.pos) { while (pos > i.pos) { ++i; ++ret; } return ret; } // Walk down. while (pos < i.pos) { --i; --ret; } return ret; } //! Accesses the full character at the iterator's position. const_reference operator*() const { if (pos >= ref->size_raw()) { const uchar16_t* a = ref->c_str(); u32 p = ref->size_raw(); if (UTF16_IS_SURROGATE_LO(a[p])) --p; reference ret(ref, p); return ret; } const_reference ret(ref, pos); return ret; } //! Accesses the full character at the iterator's position. reference operator*() { if (pos >= ref->size_raw()) { const uchar16_t* a = ref->c_str(); u32 p = ref->size_raw(); if (UTF16_IS_SURROGATE_LO(a[p])) --p; reference ret(ref, p); return ret; } reference ret(ref, pos); return ret; } //! Accesses the full character at the iterator's position. const_pointer operator->() const { return operator*(); } //! Accesses the full character at the iterator's position. pointer operator->() { return operator*(); } //! Is the iterator at the start of the string? bool atStart() const { return pos == 0; } //! Is the iterator at the end of the string? bool atEnd() const { const uchar16_t* a = ref->c_str(); if (UTF16_IS_SURROGATE(a[pos])) return (pos + 1) >= ref->size_raw(); else return pos >= ref->size_raw(); } //! Moves the iterator to the start of the string. void toStart() { pos = 0; } //! Moves the iterator to the end of the string. void toEnd() { pos = ref->size_raw(); } //! Returns the iterator's position. //! \return The iterator's position. u32 getPos() const { return pos; } protected: const ustring16<TAlloc>* ref; u32 pos; }; //! Iterator to iterate through a UTF-16 string. class _ustring16_iterator : public _ustring16_const_iterator { public: typedef _ustring16_iterator _Iter; typedef _ustring16_const_iterator _Base; typedef typename _Base::const_pointer const_pointer; typedef typename _Base::const_reference const_reference; typedef typename _Base::value_type value_type; typedef typename _Base::difference_type difference_type; typedef typename _Base::distance_type distance_type; typedef access pointer; typedef access reference; using _Base::pos; using _Base::ref; //! Constructors. _ustring16_iterator(const _Iter& i) : _ustring16_const_iterator(i) {} _ustring16_iterator(const ustring16<TAlloc>& s) : _ustring16_const_iterator(s) {} _ustring16_iterator(const ustring16<TAlloc>& s, const u32 p) : _ustring16_const_iterator(s, p) {} //! Accesses the full character at the iterator's position. reference operator*() const { if (pos >= ref->size_raw()) { const uchar16_t* a = ref->c_str(); u32 p = ref->size_raw(); if (UTF16_IS_SURROGATE_LO(a[p])) --p; reference ret(ref, p); return ret; } reference ret(ref, pos); return ret; } //! Accesses the full character at the iterator's position. reference operator*() { if (pos >= ref->size_raw()) { const uchar16_t* a = ref->c_str(); u32 p = ref->size_raw(); if (UTF16_IS_SURROGATE_LO(a[p])) --p; reference ret(ref, p); return ret; } reference ret(ref, pos); return ret; } //! Accesses the full character at the iterator's position. pointer operator->() const { return operator*(); } //! Accesses the full character at the iterator's position. pointer operator->() { return operator*(); } }; typedef typename ustring16<TAlloc>::_ustring16_iterator iterator; typedef typename ustring16<TAlloc>::_ustring16_const_iterator const_iterator; ///----------------------/// /// end iterator classes /// ///----------------------/// //! Default constructor ustring16() : array(0), allocated(1), used(0) { #if __BYTE_ORDER == __BIG_ENDIAN encoding = unicode::EUTFE_UTF16_BE; #else encoding = unicode::EUTFE_UTF16_LE; #endif array = allocator.allocate(1); // new u16[1]; array[0] = 0x0; } //! Constructor ustring16(const ustring16<TAlloc>& other) : array(0), allocated(0), used(0) { #if __BYTE_ORDER == __BIG_ENDIAN encoding = unicode::EUTFE_UTF16_BE; #else encoding = unicode::EUTFE_UTF16_LE; #endif *this = other; } //! Constructor from other string types template <class B, class A> ustring16(const string<B, A>& other) : array(0), allocated(0), used(0) { #if __BYTE_ORDER == __BIG_ENDIAN encoding = unicode::EUTFE_UTF16_BE; #else encoding = unicode::EUTFE_UTF16_LE; #endif *this = other; } #ifndef USTRING_NO_STL //! Constructor from std::string template <class B, class A, typename Alloc> ustring16(const std::basic_string<B, A, Alloc>& other) : array(0), allocated(0), used(0) { #if __BYTE_ORDER == __BIG_ENDIAN encoding = unicode::EUTFE_UTF16_BE; #else encoding = unicode::EUTFE_UTF16_LE; #endif *this = other.c_str(); } //! Constructor from iterator. template <typename Itr> ustring16(Itr first, Itr last) : array(0), allocated(0), used(0) { #if __BYTE_ORDER == __BIG_ENDIAN encoding = unicode::EUTFE_UTF16_BE; #else encoding = unicode::EUTFE_UTF16_LE; #endif reserve(std::distance(first, last)); array[used] = 0; for (; first != last; ++first) append((uchar32_t)*first); } #endif #ifndef USTRING_CPP0X_NEWLITERALS //! Constructor for copying a character string from a pointer. ustring16(const char* const c) : array(0), allocated(0), used(0) { #if __BYTE_ORDER == __BIG_ENDIAN encoding = unicode::EUTFE_UTF16_BE; #else encoding = unicode::EUTFE_UTF16_LE; #endif loadDataStream(c, strlen(c)); //append((uchar8_t*)c); } //! Constructor for copying a character string from a pointer with a given length. ustring16(const char* const c, u32 length) : array(0), allocated(0), used(0) { #if __BYTE_ORDER == __BIG_ENDIAN encoding = unicode::EUTFE_UTF16_BE; #else encoding = unicode::EUTFE_UTF16_LE; #endif loadDataStream(c, length); } #endif //! Constructor for copying a UTF-8 string from a pointer. ustring16(const uchar8_t* const c) : array(0), allocated(0), used(0) { #if __BYTE_ORDER == __BIG_ENDIAN encoding = unicode::EUTFE_UTF16_BE; #else encoding = unicode::EUTFE_UTF16_LE; #endif append(c); } //! Constructor for copying a UTF-8 string from a single char. ustring16(const char c) : array(0), allocated(0), used(0) { #if __BYTE_ORDER == __BIG_ENDIAN encoding = unicode::EUTFE_UTF16_BE; #else encoding = unicode::EUTFE_UTF16_LE; #endif append((uchar32_t)c); } //! Constructor for copying a UTF-8 string from a pointer with a given length. ustring16(const uchar8_t* const c, u32 length) : array(0), allocated(0), used(0) { #if __BYTE_ORDER == __BIG_ENDIAN encoding = unicode::EUTFE_UTF16_BE; #else encoding = unicode::EUTFE_UTF16_LE; #endif append(c, length); } //! Constructor for copying a UTF-16 string from a pointer. ustring16(const uchar16_t* const c) : array(0), allocated(0), used(0) { #if __BYTE_ORDER == __BIG_ENDIAN encoding = unicode::EUTFE_UTF16_BE; #else encoding = unicode::EUTFE_UTF16_LE; #endif append(c); } //! Constructor for copying a UTF-16 string from a pointer with a given length ustring16(const uchar16_t* const c, u32 length) : array(0), allocated(0), used(0) { #if __BYTE_ORDER == __BIG_ENDIAN encoding = unicode::EUTFE_UTF16_BE; #else encoding = unicode::EUTFE_UTF16_LE; #endif append(c, length); } //! Constructor for copying a UTF-32 string from a pointer. ustring16(const uchar32_t* const c) : array(0), allocated(0), used(0) { #if __BYTE_ORDER == __BIG_ENDIAN encoding = unicode::EUTFE_UTF16_BE; #else encoding = unicode::EUTFE_UTF16_LE; #endif append(c); } //! Constructor for copying a UTF-32 from a pointer with a given length. ustring16(const uchar32_t* const c, u32 length) : array(0), allocated(0), used(0) { #if __BYTE_ORDER == __BIG_ENDIAN encoding = unicode::EUTFE_UTF16_BE; #else encoding = unicode::EUTFE_UTF16_LE; #endif append(c, length); } //! Constructor for copying a wchar_t string from a pointer. ustring16(const wchar_t* const c) : array(0), allocated(0), used(0) { #if __BYTE_ORDER == __BIG_ENDIAN encoding = unicode::EUTFE_UTF16_BE; #else encoding = unicode::EUTFE_UTF16_LE; #endif if (sizeof(wchar_t) == 4) append(reinterpret_cast<const uchar32_t* const>(c)); else if (sizeof(wchar_t) == 2) append(reinterpret_cast<const uchar16_t* const>(c)); else if (sizeof(wchar_t) == 1) append(reinterpret_cast<const uchar8_t* const>(c)); } //! Constructor for copying a wchar_t string from a pointer with a given length. ustring16(const wchar_t* const c, u32 length) : array(0), allocated(0), used(0) { #if __BYTE_ORDER == __BIG_ENDIAN encoding = unicode::EUTFE_UTF16_BE; #else encoding = unicode::EUTFE_UTF16_LE; #endif if (sizeof(wchar_t) == 4) append(reinterpret_cast<const uchar32_t* const>(c), length); else if (sizeof(wchar_t) == 2) append(reinterpret_cast<const uchar16_t* const>(c), length); else if (sizeof(wchar_t) == 1) append(reinterpret_cast<const uchar8_t* const>(c), length); } #ifdef USTRING_CPP0X //! Constructor for moving a ustring16 ustring16(ustring16<TAlloc>&& other) : array(other.array), encoding(other.encoding), allocated(other.allocated), used(other.used) { //std::cout << "MOVE constructor" << std::endl; other.array = 0; other.allocated = 0; other.used = 0; } #endif //! Destructor ~ustring16() { allocator.deallocate(array); // delete [] array; } //! Assignment operator ustring16& operator=(const ustring16<TAlloc>& other) { if (this == &other) return *this; used = other.size_raw(); if (used >= allocated) { allocator.deallocate(array); // delete [] array; allocated = used + 1; array = allocator.allocate(used + 1); //new u16[used]; } const uchar16_t* p = other.c_str(); for (u32 i=0; i<=used; ++i, ++p) array[i] = *p; array[used] = 0; // Validate our new UTF-16 string. validate(); return *this; } #ifdef USTRING_CPP0X //! Move assignment operator ustring16& operator=(ustring16<TAlloc>&& other) { if (this != &other) { //std::cout << "MOVE operator=" << std::endl; allocator.deallocate(array); array = other.array; allocated = other.allocated; encoding = other.encoding; used = other.used; other.array = 0; other.used = 0; } return *this; } #endif //! Assignment operator for other string types template <class B, class A> ustring16<TAlloc>& operator=(const string<B, A>& other) { *this = other.c_str(); return *this; } //! Assignment operator for UTF-8 strings ustring16<TAlloc>& operator=(const uchar8_t* const c) { if (!array) { array = allocator.allocate(1); //new u16[1]; allocated = 1; } used = 0; array[used] = 0x0; if (!c) return *this; //! Append our string now. append(c); return *this; } //! Assignment operator for UTF-16 strings ustring16<TAlloc>& operator=(const uchar16_t* const c) { if (!array) { array = allocator.allocate(1); //new u16[1]; allocated = 1; } used = 0; array[used] = 0x0; if (!c) return *this; //! Append our string now. append(c); return *this; } //! Assignment operator for UTF-32 strings ustring16<TAlloc>& operator=(const uchar32_t* const c) { if (!array) { array = allocator.allocate(1); //new u16[1]; allocated = 1; } used = 0; array[used] = 0x0; if (!c) return *this; //! Append our string now. append(c); return *this; } //! Assignment operator for wchar_t strings. /** Note that this assumes that a correct unicode string is stored in the wchar_t string. Since wchar_t changes depending on its platform, it could either be a UTF-8, -16, or -32 string. This function assumes you are storing the correct unicode encoding inside the wchar_t string. **/ ustring16<TAlloc>& operator=(const wchar_t* const c) { if (sizeof(wchar_t) == 4) *this = reinterpret_cast<const uchar32_t* const>(c); else if (sizeof(wchar_t) == 2) *this = reinterpret_cast<const uchar16_t* const>(c); else if (sizeof(wchar_t) == 1) *this = reinterpret_cast<const uchar8_t* const>(c); return *this; } //! Assignment operator for other strings. /** Note that this assumes that a correct unicode string is stored in the string. **/ template <class B> ustring16<TAlloc>& operator=(const B* const c) { if (sizeof(B) == 4) *this = reinterpret_cast<const uchar32_t* const>(c); else if (sizeof(B) == 2) *this = reinterpret_cast<const uchar16_t* const>(c); else if (sizeof(B) == 1) *this = reinterpret_cast<const uchar8_t* const>(c); return *this; } //! Direct access operator access operator [](const u32 index) { _IRR_DEBUG_BREAK_IF(index>=size()) // bad index iterator iter(*this, index); return iter.operator*(); } //! Direct access operator const access operator [](const u32 index) const { _IRR_DEBUG_BREAK_IF(index>=size()) // bad index const_iterator iter(*this, index); return iter.operator*(); } //! Equality operator bool operator ==(const uchar16_t* const str) const { if (!str) return false; u32 i; for(i=0; array[i] && str[i]; ++i) if (array[i] != str[i]) return false; return !array[i] && !str[i]; } //! Equality operator bool operator ==(const ustring16<TAlloc>& other) const { for(u32 i=0; array[i] && other.array[i]; ++i) if (array[i] != other.array[i]) return false; return used == other.used; } //! Is smaller comparator bool operator <(const ustring16<TAlloc>& other) const { for(u32 i=0; array[i] && other.array[i]; ++i) { s32 diff = array[i] - other.array[i]; if ( diff ) return diff < 0; } return used < other.used; } //! Inequality operator bool operator !=(const uchar16_t* const str) const { return !(*this == str); } //! Inequality operator bool operator !=(const ustring16<TAlloc>& other) const { return !(*this == other); } //! Returns the length of a ustring16 in full characters. //! \return Length of a ustring16 in full characters. u32 size() const { const_iterator i(*this, 0); u32 pos = 0; while (!i.atEnd()) { ++i; ++pos; } return pos; } //! Informs if the ustring is empty or not. //! \return True if the ustring is empty, false if not. bool empty() const { return (size_raw() == 0); } //! Returns a pointer to the raw UTF-16 string data. //! \return pointer to C-style NUL terminated array of UTF-16 code points. const uchar16_t* c_str() const { return array; } //! Compares the first n characters of this string with another. //! \param other Other string to compare to. //! \param n Number of characters to compare. //! \return True if the n first characters of both strings are equal. bool equalsn(const ustring16<TAlloc>& other, u32 n) const { u32 i; const uchar16_t* oa = other.c_str(); for(i=0; array[i] && oa[i] && i < n; ++i) if (array[i] != oa[i]) return false; // if one (or both) of the strings was smaller then they // are only equal if they have the same length return (i == n) || (used == other.used); } //! Compares the first n characters of this string with another. //! \param str Other string to compare to. //! \param n Number of characters to compare. //! \return True if the n first characters of both strings are equal. bool equalsn(const uchar16_t* const str, u32 n) const { if (!str) return false; u32 i; for(i=0; array[i] && str[i] && i < n; ++i) if (array[i] != str[i]) return false; // if one (or both) of the strings was smaller then they // are only equal if they have the same length return (i == n) || (array[i] == 0 && str[i] == 0); } //! Appends a character to this ustring16 //! \param character The character to append. //! \return A reference to our current string. ustring16<TAlloc>& append(uchar32_t character) { if (used + 2 >= allocated) reallocate(used + 2); if (character > 0xFFFF) { used += 2; // character will be multibyte, so split it up into a surrogate pair. uchar16_t x = static_cast<uchar16_t>(character); uchar16_t vh = UTF16_HI_SURROGATE | ((((character >> 16) & ((1 << 5) - 1)) - 1) << 6) | (x >> 10); uchar16_t vl = UTF16_LO_SURROGATE | (x & ((1 << 10) - 1)); array[used-2] = vh; array[used-1] = vl; } else { ++used; array[used-1] = character; } array[used] = 0; return *this; } //! Appends a UTF-8 string to this ustring16 //! \param other The UTF-8 string to append. //! \param length The length of the string to append. //! \return A reference to our current string. ustring16<TAlloc>& append(const uchar8_t* const other, u32 length=0xffffffff) { if (!other) return *this; // Determine if the string is long enough for a BOM. u32 len = 0; const uchar8_t* p = other; do { ++len; } while (*p++ && len < unicode::BOM_ENCODE_UTF8_LEN); // Check for BOM. unicode::EUTF_ENCODE c_bom = unicode::EUTFE_NONE; if (len == unicode::BOM_ENCODE_UTF8_LEN) { if (memcmp(other, unicode::BOM_ENCODE_UTF8, unicode::BOM_ENCODE_UTF8_LEN) == 0) c_bom = unicode::EUTFE_UTF8; } // If a BOM was found, don't include it in the string. const uchar8_t* c2 = other; if (c_bom != unicode::EUTFE_NONE) { c2 = other + unicode::BOM_UTF8_LEN; length -= unicode::BOM_UTF8_LEN; } // Calculate the size of the string to read in. len = 0; p = c2; do { ++len; } while(*p++ && len < length); if (len > length) len = length; // If we need to grow the array, do it now. if (used + len >= allocated) reallocate(used + (len * 2)); u32 start = used; // Convert UTF-8 to UTF-16. u32 pos = start; for (u32 l = 0; l<len;) { ++used; if (((c2[l] >> 6) & 0x03) == 0x02) { // Invalid continuation byte. array[pos++] = unicode::UTF_REPLACEMENT_CHARACTER; ++l; } else if (c2[l] == 0xC0 || c2[l] == 0xC1) { // Invalid byte - overlong encoding. array[pos++] = unicode::UTF_REPLACEMENT_CHARACTER; ++l; } else if ((c2[l] & 0xF8) == 0xF0) { // 4 bytes UTF-8, 2 bytes UTF-16. // Check for a full string. if ((l + 3) >= len) { array[pos++] = unicode::UTF_REPLACEMENT_CHARACTER; l += 3; break; } // Validate. bool valid = true; u8 l2 = 0; if (valid && (((c2[l+1] >> 6) & 0x03) == 0x02)) ++l2; else valid = false; if (valid && (((c2[l+2] >> 6) & 0x03) == 0x02)) ++l2; else valid = false; if (valid && (((c2[l+3] >> 6) & 0x03) == 0x02)) ++l2; else valid = false; if (!valid) { array[pos++] = unicode::UTF_REPLACEMENT_CHARACTER; l += l2; continue; } // Decode. uchar8_t b1 = ((c2[l] & 0x7) << 2) | ((c2[l+1] >> 4) & 0x3); uchar8_t b2 = ((c2[l+1] & 0xF) << 4) | ((c2[l+2] >> 2) & 0xF); uchar8_t b3 = ((c2[l+2] & 0x3) << 6) | (c2[l+3] & 0x3F); uchar32_t v = b3 | ((uchar32_t)b2 << 8) | ((uchar32_t)b1 << 16); // Split v up into a surrogate pair. uchar16_t x = static_cast<uchar16_t>(v); uchar16_t vh = UTF16_HI_SURROGATE | ((((v >> 16) & ((1 << 5) - 1)) - 1) << 6) | (x >> 10); uchar16_t vl = UTF16_LO_SURROGATE | (x & ((1 << 10) - 1)); array[pos++] = vh; array[pos++] = vl; l += 4; ++used; // Using two shorts this time, so increase used by 1. } else if ((c2[l] & 0xF0) == 0xE0) { // 3 bytes UTF-8, 1 byte UTF-16. // Check for a full string. if ((l + 2) >= len) { array[pos++] = unicode::UTF_REPLACEMENT_CHARACTER; l += 2; break; } // Validate. bool valid = true; u8 l2 = 0; if (valid && (((c2[l+1] >> 6) & 0x03) == 0x02)) ++l2; else valid = false; if (valid && (((c2[l+2] >> 6) & 0x03) == 0x02)) ++l2; else valid = false; if (!valid) { array[pos++] = unicode::UTF_REPLACEMENT_CHARACTER; l += l2; continue; } // Decode. uchar8_t b1 = ((c2[l] & 0xF) << 4) | ((c2[l+1] >> 2) & 0xF); uchar8_t b2 = ((c2[l+1] & 0x3) << 6) | (c2[l+2] & 0x3F); uchar16_t ch = b2 | ((uchar16_t)b1 << 8); array[pos++] = ch; l += 3; } else if ((c2[l] & 0xE0) == 0xC0) { // 2 bytes UTF-8, 1 byte UTF-16. // Check for a full string. if ((l + 1) >= len) { array[pos++] = unicode::UTF_REPLACEMENT_CHARACTER; l += 1; break; } // Validate. if (((c2[l+1] >> 6) & 0x03) != 0x02) { array[pos++] = unicode::UTF_REPLACEMENT_CHARACTER; ++l; continue; } // Decode. uchar8_t b1 = (c2[l] >> 2) & 0x7; uchar8_t b2 = ((c2[l] & 0x3) << 6) | (c2[l+1] & 0x3F); uchar16_t ch = b2 | ((uchar16_t)b1 << 8); array[pos++] = ch; l += 2; } else { // 1 byte UTF-8, 1 byte UTF-16. // Validate. if (c2[l] > 0x7F) { // Values above 0xF4 are restricted and aren't used. By now, anything above 0x7F is invalid. array[pos++] = unicode::UTF_REPLACEMENT_CHARACTER; } else array[pos++] = static_cast<uchar16_t>(c2[l]); ++l; } } array[used] = 0; // Validate our new UTF-16 string. validate(); return *this; } //! Appends a UTF-16 string to this ustring16 //! \param other The UTF-16 string to append. //! \param length The length of the string to append. //! \return A reference to our current string. ustring16<TAlloc>& append(const uchar16_t* const other, u32 length=0xffffffff) { if (!other) return *this; // Determine if the string is long enough for a BOM. u32 len = 0; const uchar16_t* p = other; do { ++len; } while (*p++ && len < unicode::BOM_ENCODE_UTF16_LEN); // Check for the BOM to determine the string's endianness. unicode::EUTF_ENDIAN c_end = unicode::EUTFEE_NATIVE; if (memcmp(other, unicode::BOM_ENCODE_UTF16_LE, unicode::BOM_ENCODE_UTF16_LEN) == 0) c_end = unicode::EUTFEE_LITTLE; else if (memcmp(other, unicode::BOM_ENCODE_UTF16_BE, unicode::BOM_ENCODE_UTF16_LEN) == 0) c_end = unicode::EUTFEE_BIG; // If a BOM was found, don't include it in the string. const uchar16_t* c2 = other; if (c_end != unicode::EUTFEE_NATIVE) { c2 = other + unicode::BOM_UTF16_LEN; length -= unicode::BOM_UTF16_LEN; } // Calculate the size of the string to read in. len = 0; p = c2; do { ++len; } while(*p++ && len < length); if (len > length) len = length; // If we need to grow the size of the array, do it now. if (used + len >= allocated) reallocate(used + (len * 2)); u32 start = used; used += len; // Copy the string now. unicode::EUTF_ENDIAN m_end = getEndianness(); for (u32 l = start; l < start + len; ++l) { array[l] = (uchar16_t)c2[l]; if (c_end != unicode::EUTFEE_NATIVE && c_end != m_end) array[l] = unicode::swapEndian16(array[l]); } array[used] = 0; // Validate our new UTF-16 string. validate(); return *this; } //! Appends a UTF-32 string to this ustring16 //! \param other The UTF-32 string to append. //! \param length The length of the string to append. //! \return A reference to our current string. ustring16<TAlloc>& append(const uchar32_t* const other, u32 length=0xffffffff) { if (!other) return *this; // Check for the BOM to determine the string's endianness. unicode::EUTF_ENDIAN c_end = unicode::EUTFEE_NATIVE; if (memcmp(other, unicode::BOM_ENCODE_UTF32_LE, unicode::BOM_ENCODE_UTF32_LEN) == 0) c_end = unicode::EUTFEE_LITTLE; else if (memcmp(other, unicode::BOM_ENCODE_UTF32_BE, unicode::BOM_ENCODE_UTF32_LEN) == 0) c_end = unicode::EUTFEE_BIG; // If a BOM was found, don't include it in the string. const uchar32_t* c2 = other; if (c_end != unicode::EUTFEE_NATIVE) { c2 = other + unicode::BOM_UTF32_LEN; length -= unicode::BOM_UTF32_LEN; } // Calculate the size of the string to read in. u32 len = 0; const uchar32_t* p = c2; do { ++len; } while(*p++ && len < length); if (len > length) len = length; // If we need to grow the size of the array, do it now. // In case all of the UTF-32 string is split into surrogate pairs, do len * 2. if (used + (len * 2) >= allocated) reallocate(used + ((len * 2) * 2)); u32 start = used; // Convert UTF-32 to UTF-16. unicode::EUTF_ENDIAN m_end = getEndianness(); u32 pos = start; for (u32 l = 0; l<len; ++l) { ++used; uchar32_t ch = c2[l]; if (c_end != unicode::EUTFEE_NATIVE && c_end != m_end) ch = unicode::swapEndian32(ch); if (ch > 0xFFFF) { // Split ch up into a surrogate pair as it is over 16 bits long. uchar16_t x = static_cast<uchar16_t>(ch); uchar16_t vh = UTF16_HI_SURROGATE | ((((ch >> 16) & ((1 << 5) - 1)) - 1) << 6) | (x >> 10); uchar16_t vl = UTF16_LO_SURROGATE | (x & ((1 << 10) - 1)); array[pos++] = vh; array[pos++] = vl; ++used; // Using two shorts, so increased used again. } else if (ch >= 0xD800 && ch <= 0xDFFF) { // Between possible UTF-16 surrogates (invalid!) array[pos++] = unicode::UTF_REPLACEMENT_CHARACTER; } else array[pos++] = static_cast<uchar16_t>(ch); } array[used] = 0; // Validate our new UTF-16 string. validate(); return *this; } //! Appends a ustring16 to this ustring16 //! \param other The string to append to this one. //! \return A reference to our current string. ustring16<TAlloc>& append(const ustring16<TAlloc>& other) { const uchar16_t* oa = other.c_str(); u32 len = other.size_raw(); if (used + len >= allocated) reallocate(used + len); for (u32 l=0; l<len; ++l) array[used+l] = oa[l]; used += len; array[used] = 0; return *this; } //! Appends a certain amount of characters of a ustring16 to this ustring16. //! \param other The string to append to this one. //! \param length How many characters of the other string to add to this one. //! \return A reference to our current string. ustring16<TAlloc>& append(const ustring16<TAlloc>& other, u32 length) { if (other.size() == 0) return *this; if (other.size() < length) { append(other); return *this; } if (used + length * 2 >= allocated) reallocate(used + length * 2); const_iterator iter(other, 0); u32 l = length; while (!iter.atEnd() && l) { uchar32_t c = *iter; append(c); ++iter; --l; } return *this; } //! Reserves some memory. //! \param count The amount of characters to reserve. void reserve(u32 count) { if (count < allocated) return; reallocate(count); } //! Finds first occurrence of character. //! \param c The character to search for. //! \return Position where the character has been found, or -1 if not found. s32 findFirst(uchar32_t c) const { const_iterator i(*this, 0); s32 pos = 0; while (!i.atEnd()) { uchar32_t t = *i; if (c == t) return pos; ++pos; ++i; } return -1; } //! Finds first occurrence of a character of a list. //! \param c A list of characters to find. For example if the method should find the first occurrence of 'a' or 'b', this parameter should be "ab". //! \param count The amount of characters in the list. Usually, this should be strlen(c). //! \return Position where one of the characters has been found, or -1 if not found. s32 findFirstChar(const uchar32_t* const c, u32 count=1) const { if (!c || !count) return -1; const_iterator i(*this, 0); s32 pos = 0; while (!i.atEnd()) { uchar32_t t = *i; for (u32 j=0; j<count; ++j) if (t == c[j]) return pos; ++pos; ++i; } return -1; } //! Finds first position of a character not in a given list. //! \param c A list of characters to NOT find. For example if the method should find the first occurrence of a character not 'a' or 'b', this parameter should be "ab". //! \param count The amount of characters in the list. Usually, this should be strlen(c). //! \return Position where the character has been found, or -1 if not found. s32 findFirstCharNotInList(const uchar32_t* const c, u32 count=1) const { if (!c || !count) return -1; const_iterator i(*this, 0); s32 pos = 0; while (!i.atEnd()) { uchar32_t t = *i; u32 j; for (j=0; j<count; ++j) if (t == c[j]) break; if (j==count) return pos; ++pos; ++i; } return -1; } //! Finds last position of a character not in a given list. //! \param c A list of characters to NOT find. For example if the method should find the first occurrence of a character not 'a' or 'b', this parameter should be "ab". //! \param count The amount of characters in the list. Usually, this should be strlen(c). //! \return Position where the character has been found, or -1 if not found. s32 findLastCharNotInList(const uchar32_t* const c, u32 count=1) const { if (!c || !count) return -1; const_iterator i(end()); --i; s32 pos = size() - 1; while (!i.atStart()) { uchar32_t t = *i; u32 j; for (j=0; j<count; ++j) if (t == c[j]) break; if (j==count) return pos; --pos; --i; } return -1; } //! Finds next occurrence of character. //! \param c The character to search for. //! \param startPos The position in the string to start searching. //! \return Position where the character has been found, or -1 if not found. s32 findNext(uchar32_t c, u32 startPos) const { const_iterator i(*this, startPos); s32 pos = startPos; while (!i.atEnd()) { uchar32_t t = *i; if (t == c) return pos; ++pos; ++i; } return -1; } //! Finds last occurrence of character. //! \param c The character to search for. //! \param start The start position of the reverse search ( default = -1, on end ). //! \return Position where the character has been found, or -1 if not found. s32 findLast(uchar32_t c, s32 start = -1) const { u32 s = size(); start = core::clamp ( start < 0 ? (s32)s : start, 0, (s32)s ) - 1; const_iterator i(*this, start); u32 pos = start; while (!i.atStart()) { uchar32_t t = *i; if (t == c) return pos; --pos; --i; } return -1; } //! Finds last occurrence of a character in a list. //! \param c A list of strings to find. For example if the method should find the last occurrence of 'a' or 'b', this parameter should be "ab". //! \param count The amount of characters in the list. Usually, this should be strlen(c). //! \return Position where one of the characters has been found, or -1 if not found. s32 findLastChar(const uchar32_t* const c, u32 count=1) const { if (!c || !count) return -1; const_iterator i(end()); --i; s32 pos = size(); while (!i.atStart()) { uchar32_t t = *i; for (u32 j=0; j<count; ++j) if (t == c[j]) return pos; --pos; --i; } return -1; } //! Finds another ustring16 in this ustring16. //! \param str The string to find. //! \param start The start position of the search. //! \return Positions where the ustring16 has been found, or -1 if not found. s32 find(const ustring16<TAlloc>& str, const u32 start = 0) const { u32 my_size = size(); u32 their_size = str.size(); if (their_size == 0 || my_size - start < their_size) return -1; const_iterator i(*this, start); s32 pos = start; while (!i.atEnd()) { const_iterator i2(i); const_iterator j(str, 0); uchar32_t t1 = (uchar32_t)*i2; uchar32_t t2 = (uchar32_t)*j; while (t1 == t2) { ++i2; ++j; if (j.atEnd()) return pos; t1 = (uchar32_t)*i2; t2 = (uchar32_t)*j; } ++i; ++pos; } return -1; } //! Finds another ustring16 in this ustring16. //! \param str The string to find. //! \param start The start position of the search. //! \return Positions where the string has been found, or -1 if not found. s32 find_raw(const ustring16<TAlloc>& str, const u32 start = 0) const { const uchar16_t* data = str.c_str(); if (data && *data) { u32 len = 0; while (data[len]) ++len; if (len > used) return -1; for (u32 i=start; i<=used-len; ++i) { u32 j=0; while(data[j] && array[i+j] == data[j]) ++j; if (!data[j]) return i; } } return -1; } //! Returns a substring. //! \param begin: Start of substring. //! \param length: Length of substring. //! \return A reference to our current string. ustring16<TAlloc> subString(u32 begin, s32 length) const { u32 len = size(); // if start after ustring16 // or no proper substring length if ((length <= 0) || (begin>=len)) return ustring16<TAlloc>(""); // clamp length to maximal value if ((length+begin) > len) length = len-begin; ustring16<TAlloc> o; o.reserve((length+1) * 2); const_iterator i(*this, begin); while (!i.atEnd() && length) { o.append(*i); ++i; --length; } return o; } //! Appends a character to this ustring16. //! \param c Character to append. //! \return A reference to our current string. ustring16<TAlloc>& operator += (char c) { append((uchar32_t)c); return *this; } //! Appends a character to this ustring16. //! \param c Character to append. //! \return A reference to our current string. ustring16<TAlloc>& operator += (uchar32_t c) { append(c); return *this; } //! Appends a number to this ustring16. //! \param c Number to append. //! \return A reference to our current string. ustring16<TAlloc>& operator += (short c) { append(core::stringc(c)); return *this; } //! Appends a number to this ustring16. //! \param c Number to append. //! \return A reference to our current string. ustring16<TAlloc>& operator += (unsigned short c) { append(core::stringc(c)); return *this; } #ifdef USTRING_CPP0X_NEWLITERALS //! Appends a number to this ustring16. //! \param c Number to append. //! \return A reference to our current string. ustring16<TAlloc>& operator += (int c) { append(core::stringc(c)); return *this; } //! Appends a number to this ustring16. //! \param c Number to append. //! \return A reference to our current string. ustring16<TAlloc>& operator += (unsigned int c) { append(core::stringc(c)); return *this; } #endif //! Appends a number to this ustring16. //! \param c Number to append. //! \return A reference to our current string. ustring16<TAlloc>& operator += (long c) { append(core::stringc(c)); return *this; } //! Appends a number to this ustring16. //! \param c Number to append. //! \return A reference to our current string. ustring16<TAlloc>& operator += (unsigned long c) { append(core::stringc(c)); return *this; } //! Appends a number to this ustring16. //! \param c Number to append. //! \return A reference to our current string. ustring16<TAlloc>& operator += (double c) { append(core::stringc(c)); return *this; } //! Appends a char ustring16 to this ustring16. //! \param c Char ustring16 to append. //! \return A reference to our current string. ustring16<TAlloc>& operator += (const uchar16_t* const c) { append(c); return *this; } //! Appends a ustring16 to this ustring16. //! \param other ustring16 to append. //! \return A reference to our current string. ustring16<TAlloc>& operator += (const ustring16<TAlloc>& other) { append(other); return *this; } //! Replaces all characters of a given type with another one. //! \param toReplace Character to replace. //! \param replaceWith Character replacing the old one. //! \return A reference to our current string. ustring16<TAlloc>& replace(uchar32_t toReplace, uchar32_t replaceWith) { iterator i(*this, 0); while (!i.atEnd()) { typename ustring16<TAlloc>::access a = *i; if ((uchar32_t)a == toReplace) a = replaceWith; ++i; } return *this; } //! Replaces all instances of a string with another one. //! \param toReplace The string to replace. //! \param replaceWith The string replacing the old one. //! \return A reference to our current string. ustring16<TAlloc>& replace(const ustring16<TAlloc>& toReplace, const ustring16<TAlloc>& replaceWith) { if (toReplace.size() == 0) return *this; const uchar16_t* other = toReplace.c_str(); const uchar16_t* replace = replaceWith.c_str(); const u32 other_size = toReplace.size_raw(); const u32 replace_size = replaceWith.size_raw(); // Determine the delta. The algorithm will change depending on the delta. s32 delta = replace_size - other_size; // A character for character replace. The string will not shrink or grow. if (delta == 0) { s32 pos = 0; while ((pos = find_raw(other, pos)) != -1) { for (u32 i = 0; i < replace_size; ++i) array[pos + i] = replace[i]; ++pos; } return *this; } // We are going to be removing some characters. The string will shrink. if (delta < 0) { u32 i = 0; for (u32 pos = 0; pos <= used; ++i, ++pos) { // Is this potentially a match? if (array[pos] == *other) { // Check to see if we have a match. u32 j; for (j = 0; j < other_size; ++j) { if (array[pos + j] != other[j]) break; } // If we have a match, replace characters. if (j == other_size) { for (j = 0; j < replace_size; ++j) array[i + j] = replace[j]; i += replace_size - 1; pos += other_size - 1; continue; } } // No match found, just copy characters. array[i - 1] = array[pos]; } array[i] = 0; used = i; return *this; } // We are going to be adding characters, so the string size will increase. // Count the number of times toReplace exists in the string so we can allocate the new size. u32 find_count = 0; s32 pos = 0; while ((pos = find_raw(other, pos)) != -1) { ++find_count; ++pos; } // Re-allocate the string now, if needed. u32 len = delta * find_count; if (used + len >= allocated) reallocate(used + len); // Start replacing. pos = 0; while ((pos = find_raw(other, pos)) != -1) { uchar16_t* start = array + pos + other_size - 1; uchar16_t* ptr = array + used; uchar16_t* end = array + used + delta; // Shift characters to make room for the string. while (ptr != start) { *end = *ptr; --ptr; --end; } // Add the new string now. for (u32 i = 0; i < replace_size; ++i) array[pos + i] = replace[i]; pos += replace_size; used += delta; } // Terminate the string and return ourself. array[used] = 0; return *this; } //! Removes characters from a ustring16.. //! \param c The character to remove. //! \return A reference to our current string. ustring16<TAlloc>& remove(uchar32_t c) { u32 pos = 0; u32 found = 0; u32 len = (c > 0xFFFF ? 2 : 1); // Remove characters equal to the size of c as a UTF-16 character. for (u32 i=0; i<=used; ++i) { uchar32_t uc32 = 0; if (!UTF16_IS_SURROGATE_HI(array[i])) uc32 |= array[i]; else if (i + 1 <= used) { // Convert the surrogate pair into a single UTF-32 character. uc32 = unicode::toUTF32(array[i], array[i + 1]); } u32 len2 = (uc32 > 0xFFFF ? 2 : 1); if (uc32 == c) { found += len; continue; } array[pos++] = array[i]; if (len2 == 2) array[pos++] = array[++i]; } used -= found; array[used] = 0; return *this; } //! Removes a ustring16 from the ustring16. //! \param toRemove The string to remove. //! \return A reference to our current string. ustring16<TAlloc>& remove(const ustring16<TAlloc>& toRemove) { u32 size = toRemove.size_raw(); if (size == 0) return *this; const uchar16_t* tra = toRemove.c_str(); u32 pos = 0; u32 found = 0; for (u32 i=0; i<=used; ++i) { u32 j = 0; while (j < size) { if (array[i + j] != tra[j]) break; ++j; } if (j == size) { found += size; i += size - 1; continue; } array[pos++] = array[i]; } used -= found; array[used] = 0; return *this; } //! Removes characters from the ustring16. //! \param characters The characters to remove. //! \return A reference to our current string. ustring16<TAlloc>& removeChars(const ustring16<TAlloc>& characters) { if (characters.size_raw() == 0) return *this; u32 pos = 0; u32 found = 0; const_iterator iter(characters); for (u32 i=0; i<=used; ++i) { uchar32_t uc32 = 0; if (!UTF16_IS_SURROGATE_HI(array[i])) uc32 |= array[i]; else if (i + 1 <= used) { // Convert the surrogate pair into a single UTF-32 character. uc32 = unicode::toUTF32(array[i], array[i+1]); } u32 len2 = (uc32 > 0xFFFF ? 2 : 1); bool cont = false; iter.toStart(); while (!iter.atEnd()) { uchar32_t c = *iter; if (uc32 == c) { found += (c > 0xFFFF ? 2 : 1); // Remove characters equal to the size of c as a UTF-16 character. ++i; cont = true; break; } ++iter; } if (cont) continue; array[pos++] = array[i]; if (len2 == 2) array[pos++] = array[++i]; } used -= found; array[used] = 0; return *this; } //! Trims the ustring16. //! Removes the specified characters (by default, Latin-1 whitespace) from the begining and the end of the ustring16. //! \param whitespace The characters that are to be considered as whitespace. //! \return A reference to our current string. ustring16<TAlloc>& trim(const ustring16<TAlloc>& whitespace = " \t\n\r") { core::array<uchar32_t> utf32white = whitespace.toUTF32(); // find start and end of the substring without the specified characters const s32 begin = findFirstCharNotInList(utf32white.const_pointer(), whitespace.used + 1); if (begin == -1) return (*this=""); const s32 end = findLastCharNotInList(utf32white.const_pointer(), whitespace.used + 1); return (*this = subString(begin, (end +1) - begin)); } //! Erases a character from the ustring16. //! May be slow, because all elements following after the erased element have to be copied. //! \param index Index of element to be erased. //! \return A reference to our current string. ustring16<TAlloc>& erase(u32 index) { _IRR_DEBUG_BREAK_IF(index>used) // access violation iterator i(*this, index); uchar32_t t = *i; u32 len = (t > 0xFFFF ? 2 : 1); for (u32 j = static_cast<u32>(i.getPos()) + len; j <= used; ++j) array[j - len] = array[j]; used -= len; array[used] = 0; return *this; } //! Validate the existing ustring16, checking for valid surrogate pairs and checking for proper termination. //! \return A reference to our current string. ustring16<TAlloc>& validate() { // Validate all unicode characters. for (u32 i=0; i<allocated; ++i) { // Terminate on existing null. if (array[i] == 0) { used = i; return *this; } if (UTF16_IS_SURROGATE(array[i])) { if (((i+1) >= allocated) || UTF16_IS_SURROGATE_LO(array[i])) array[i] = unicode::UTF_REPLACEMENT_CHARACTER; else if (UTF16_IS_SURROGATE_HI(array[i]) && !UTF16_IS_SURROGATE_LO(array[i+1])) array[i] = unicode::UTF_REPLACEMENT_CHARACTER; ++i; } if (array[i] >= 0xFDD0 && array[i] <= 0xFDEF) array[i] = unicode::UTF_REPLACEMENT_CHARACTER; } // terminate used = 0; if (allocated > 0) { used = allocated - 1; array[used] = 0; } return *this; } //! Gets the last char of the ustring16, or 0. //! \return The last char of the ustring16, or 0. uchar32_t lastChar() const { if (used < 1) return 0; if (UTF16_IS_SURROGATE_LO(array[used-1])) { // Make sure we have a paired surrogate. if (used < 2) return 0; // Check for an invalid surrogate. if (!UTF16_IS_SURROGATE_HI(array[used-2])) return 0; // Convert the surrogate pair into a single UTF-32 character. return unicode::toUTF32(array[used-2], array[used-1]); } else { return array[used-1]; } } //! Split the ustring16 into parts. /** This method will split a ustring16 at certain delimiter characters into the container passed in as reference. The type of the container has to be given as template parameter. It must provide a push_back and a size method. \param ret The result container \param c C-style ustring16 of delimiter characters \param count Number of delimiter characters \param ignoreEmptyTokens Flag to avoid empty substrings in the result container. If two delimiters occur without a character in between, an empty substring would be placed in the result. If this flag is set, only non-empty strings are stored. \param keepSeparators Flag which allows to add the separator to the result ustring16. If this flag is true, the concatenation of the substrings results in the original ustring16. Otherwise, only the characters between the delimiters are returned. \return The number of resulting substrings */ template<class container> u32 split(container& ret, const uchar32_t* const c, u32 count=1, bool ignoreEmptyTokens=true, bool keepSeparators=false) const { if (!c) return 0; const_iterator i(*this); const u32 oldSize=ret.size(); u32 pos = 0; u32 lastpos = 0; u32 lastpospos = 0; bool lastWasSeparator = false; while (!i.atEnd()) { uchar32_t ch = *i; bool foundSeparator = false; for (u32 j=0; j<count; ++j) { if (ch == c[j]) { if ((!ignoreEmptyTokens || pos - lastpos != 0) && !lastWasSeparator) ret.push_back(ustring16<TAlloc>(&array[lastpospos], pos - lastpos)); foundSeparator = true; lastpos = (keepSeparators ? pos : pos + 1); lastpospos = (keepSeparators ? i.getPos() : i.getPos() + 1); break; } } lastWasSeparator = foundSeparator; ++pos; ++i; } u32 s = size() + 1; if (s > lastpos) ret.push_back(ustring16<TAlloc>(&array[lastpospos], s - lastpos)); return ret.size()-oldSize; } //! Split the ustring16 into parts. /** This method will split a ustring16 at certain delimiter characters into the container passed in as reference. The type of the container has to be given as template parameter. It must provide a push_back and a size method. \param ret The result container \param c A unicode string of delimiter characters \param ignoreEmptyTokens Flag to avoid empty substrings in the result container. If two delimiters occur without a character in between, an empty substring would be placed in the result. If this flag is set, only non-empty strings are stored. \param keepSeparators Flag which allows to add the separator to the result ustring16. If this flag is true, the concatenation of the substrings results in the original ustring16. Otherwise, only the characters between the delimiters are returned. \return The number of resulting substrings */ template<class container> u32 split(container& ret, const ustring16<TAlloc>& c, bool ignoreEmptyTokens=true, bool keepSeparators=false) const { core::array<uchar32_t> v = c.toUTF32(); return split(ret, v.pointer(), v.size(), ignoreEmptyTokens, keepSeparators); } //! Gets the size of the allocated memory buffer for the string. //! \return The size of the allocated memory buffer. u32 capacity() const { return allocated; } //! Returns the raw number of UTF-16 code points in the string which includes the individual surrogates. //! \return The raw number of UTF-16 code points, excluding the trialing NUL. u32 size_raw() const { return used; } //! Inserts a character into the string. //! \param c The character to insert. //! \param pos The position to insert the character. //! \return A reference to our current string. ustring16<TAlloc>& insert(uchar32_t c, u32 pos) { u8 len = (c > 0xFFFF ? 2 : 1); if (used + len >= allocated) reallocate(used + len); used += len; iterator iter(*this, pos); for (u32 i = used - 2; i > iter.getPos(); --i) array[i] = array[i - len]; if (c > 0xFFFF) { // c will be multibyte, so split it up into a surrogate pair. uchar16_t x = static_cast<uchar16_t>(c); uchar16_t vh = UTF16_HI_SURROGATE | ((((c >> 16) & ((1 << 5) - 1)) - 1) << 6) | (x >> 10); uchar16_t vl = UTF16_LO_SURROGATE | (x & ((1 << 10) - 1)); array[iter.getPos()] = vh; array[iter.getPos()+1] = vl; } else { array[iter.getPos()] = static_cast<uchar16_t>(c); } array[used] = 0; return *this; } //! Inserts a string into the string. //! \param c The string to insert. //! \param pos The position to insert the string. //! \return A reference to our current string. ustring16<TAlloc>& insert(const ustring16<TAlloc>& c, u32 pos) { u32 len = c.size_raw(); if (len == 0) return *this; if (used + len >= allocated) reallocate(used + len); used += len; iterator iter(*this, pos); for (u32 i = used - 2; i > iter.getPos() + len; --i) array[i] = array[i - len]; const uchar16_t* s = c.c_str(); for (u32 i = 0; i < len; ++i) { array[pos++] = *s; ++s; } array[used] = 0; return *this; } //! Inserts a character into the string. //! \param c The character to insert. //! \param pos The position to insert the character. //! \return A reference to our current string. ustring16<TAlloc>& insert_raw(uchar16_t c, u32 pos) { if (used + 1 >= allocated) reallocate(used + 1); ++used; for (u32 i = used - 1; i > pos; --i) array[i] = array[i - 1]; array[pos] = c; array[used] = 0; return *this; } //! Removes a character from string. //! \param pos Position of the character to remove. //! \return A reference to our current string. ustring16<TAlloc>& erase_raw(u32 pos) { for (u32 i=pos; i<=used; ++i) { array[i] = array[i + 1]; } --used; array[used] = 0; return *this; } //! Replaces a character in the string. //! \param c The new character. //! \param pos The position of the character to replace. //! \return A reference to our current string. ustring16<TAlloc>& replace_raw(uchar16_t c, u32 pos) { array[pos] = c; return *this; } //! Returns an iterator to the beginning of the string. //! \return An iterator to the beginning of the string. iterator begin() { iterator i(*this, 0); return i; } //! Returns an iterator to the beginning of the string. //! \return An iterator to the beginning of the string. const_iterator begin() const { const_iterator i(*this, 0); return i; } //! Returns an iterator to the beginning of the string. //! \return An iterator to the beginning of the string. const_iterator cbegin() const { const_iterator i(*this, 0); return i; } //! Returns an iterator to the end of the string. //! \return An iterator to the end of the string. iterator end() { iterator i(*this, 0); i.toEnd(); return i; } //! Returns an iterator to the end of the string. //! \return An iterator to the end of the string. const_iterator end() const { const_iterator i(*this, 0); i.toEnd(); return i; } //! Returns an iterator to the end of the string. //! \return An iterator to the end of the string. const_iterator cend() const { const_iterator i(*this, 0); i.toEnd(); return i; } //! Converts the string to a UTF-8 encoded string. //! \param addBOM If true, the proper unicode byte-order mark will be prefixed to the string. //! \return A string containing the UTF-8 encoded string. core::string<uchar8_t> toUTF8_s(const bool addBOM = false) const { core::string<uchar8_t> ret; ret.reserve(used * 4 + (addBOM ? unicode::BOM_UTF8_LEN : 0) + 1); const_iterator iter(*this, 0); // Add the byte order mark if the user wants it. if (addBOM) { ret.append(unicode::BOM_ENCODE_UTF8[0]); ret.append(unicode::BOM_ENCODE_UTF8[1]); ret.append(unicode::BOM_ENCODE_UTF8[2]); } while (!iter.atEnd()) { uchar32_t c = *iter; if (c > 0xFFFF) { // 4 bytes uchar8_t b1 = (0x1E << 3) | ((c >> 18) & 0x7); uchar8_t b2 = (0x2 << 6) | ((c >> 12) & 0x3F); uchar8_t b3 = (0x2 << 6) | ((c >> 6) & 0x3F); uchar8_t b4 = (0x2 << 6) | (c & 0x3F); ret.append(b1); ret.append(b2); ret.append(b3); ret.append(b4); } else if (c > 0x7FF) { // 3 bytes uchar8_t b1 = (0xE << 4) | ((c >> 12) & 0xF); uchar8_t b2 = (0x2 << 6) | ((c >> 6) & 0x3F); uchar8_t b3 = (0x2 << 6) | (c & 0x3F); ret.append(b1); ret.append(b2); ret.append(b3); } else if (c > 0x7F) { // 2 bytes uchar8_t b1 = (0x6 << 5) | ((c >> 6) & 0x1F); uchar8_t b2 = (0x2 << 6) | (c & 0x3F); ret.append(b1); ret.append(b2); } else { // 1 byte ret.append(static_cast<uchar8_t>(c)); } ++iter; } return ret; } //! Converts the string to a UTF-8 encoded string array. //! \param addBOM If true, the proper unicode byte-order mark will be prefixed to the string. //! \return An array containing the UTF-8 encoded string. core::array<uchar8_t> toUTF8(const bool addBOM = false) const { core::array<uchar8_t> ret(used * 4 + (addBOM ? unicode::BOM_UTF8_LEN : 0) + 1); const_iterator iter(*this, 0); // Add the byte order mark if the user wants it. if (addBOM) { ret.push_back(unicode::BOM_ENCODE_UTF8[0]); ret.push_back(unicode::BOM_ENCODE_UTF8[1]); ret.push_back(unicode::BOM_ENCODE_UTF8[2]); } while (!iter.atEnd()) { uchar32_t c = *iter; if (c > 0xFFFF) { // 4 bytes uchar8_t b1 = (0x1E << 3) | ((c >> 18) & 0x7); uchar8_t b2 = (0x2 << 6) | ((c >> 12) & 0x3F); uchar8_t b3 = (0x2 << 6) | ((c >> 6) & 0x3F); uchar8_t b4 = (0x2 << 6) | (c & 0x3F); ret.push_back(b1); ret.push_back(b2); ret.push_back(b3); ret.push_back(b4); } else if (c > 0x7FF) { // 3 bytes uchar8_t b1 = (0xE << 4) | ((c >> 12) & 0xF); uchar8_t b2 = (0x2 << 6) | ((c >> 6) & 0x3F); uchar8_t b3 = (0x2 << 6) | (c & 0x3F); ret.push_back(b1); ret.push_back(b2); ret.push_back(b3); } else if (c > 0x7F) { // 2 bytes uchar8_t b1 = (0x6 << 5) | ((c >> 6) & 0x1F); uchar8_t b2 = (0x2 << 6) | (c & 0x3F); ret.push_back(b1); ret.push_back(b2); } else { // 1 byte ret.push_back(static_cast<uchar8_t>(c)); } ++iter; } ret.push_back(0); return ret; } #ifdef USTRING_CPP0X_NEWLITERALS // C++0x //! Converts the string to a UTF-16 encoded string. //! \param endian The desired endianness of the string. //! \param addBOM If true, the proper unicode byte-order mark will be prefixed to the string. //! \return A string containing the UTF-16 encoded string. core::string<char16_t> toUTF16_s(const unicode::EUTF_ENDIAN endian = unicode::EUTFEE_NATIVE, const bool addBOM = false) const { core::string<char16_t> ret; ret.reserve(used + (addBOM ? unicode::BOM_UTF16_LEN : 0) + 1); // Add the BOM if specified. if (addBOM) { if (endian == unicode::EUTFEE_NATIVE) ret[0] = unicode::BOM; else if (endian == unicode::EUTFEE_LITTLE) { uchar8_t* ptr8 = reinterpret_cast<uchar8_t*>(&ret[0]); *ptr8++ = unicode::BOM_ENCODE_UTF16_LE[0]; *ptr8 = unicode::BOM_ENCODE_UTF16_LE[1]; } else { uchar8_t* ptr8 = reinterpret_cast<uchar8_t*>(&ret[0]); *ptr8++ = unicode::BOM_ENCODE_UTF16_BE[0]; *ptr8 = unicode::BOM_ENCODE_UTF16_BE[1]; } } ret.append(array); if (endian != unicode::EUTFEE_NATIVE && getEndianness() != endian) { char16_t* ptr = ret.c_str(); for (u32 i = 0; i < ret.size(); ++i) *ptr++ = unicode::swapEndian16(*ptr); } return ret; } #endif //! Converts the string to a UTF-16 encoded string array. //! Unfortunately, no toUTF16_s() version exists due to limitations with Irrlicht's string class. //! \param endian The desired endianness of the string. //! \param addBOM If true, the proper unicode byte-order mark will be prefixed to the string. //! \return An array containing the UTF-16 encoded string. core::array<uchar16_t> toUTF16(const unicode::EUTF_ENDIAN endian = unicode::EUTFEE_NATIVE, const bool addBOM = false) const { core::array<uchar16_t> ret(used + (addBOM ? unicode::BOM_UTF16_LEN : 0) + 1); uchar16_t* ptr = ret.pointer(); // Add the BOM if specified. if (addBOM) { if (endian == unicode::EUTFEE_NATIVE) *ptr = unicode::BOM; else if (endian == unicode::EUTFEE_LITTLE) { uchar8_t* ptr8 = reinterpret_cast<uchar8_t*>(ptr); *ptr8++ = unicode::BOM_ENCODE_UTF16_LE[0]; *ptr8 = unicode::BOM_ENCODE_UTF16_LE[1]; } else { uchar8_t* ptr8 = reinterpret_cast<uchar8_t*>(ptr); *ptr8++ = unicode::BOM_ENCODE_UTF16_BE[0]; *ptr8 = unicode::BOM_ENCODE_UTF16_BE[1]; } ++ptr; } memcpy((void*)ptr, (void*)array, used * sizeof(uchar16_t)); if (endian != unicode::EUTFEE_NATIVE && getEndianness() != endian) { for (u32 i = 0; i <= used; ++i) ptr[i] = unicode::swapEndian16(ptr[i]); } ret.set_used(used + (addBOM ? unicode::BOM_UTF16_LEN : 0)); ret.push_back(0); return ret; } #ifdef USTRING_CPP0X_NEWLITERALS // C++0x //! Converts the string to a UTF-32 encoded string. //! \param endian The desired endianness of the string. //! \param addBOM If true, the proper unicode byte-order mark will be prefixed to the string. //! \return A string containing the UTF-32 encoded string. core::string<char32_t> toUTF32_s(const unicode::EUTF_ENDIAN endian = unicode::EUTFEE_NATIVE, const bool addBOM = false) const { core::string<char32_t> ret; ret.reserve(size() + 1 + (addBOM ? unicode::BOM_UTF32_LEN : 0)); const_iterator iter(*this, 0); // Add the BOM if specified. if (addBOM) { if (endian == unicode::EUTFEE_NATIVE) ret.append(unicode::BOM); else { union { uchar32_t full; u8 chunk[4]; } t; if (endian == unicode::EUTFEE_LITTLE) { t.chunk[0] = unicode::BOM_ENCODE_UTF32_LE[0]; t.chunk[1] = unicode::BOM_ENCODE_UTF32_LE[1]; t.chunk[2] = unicode::BOM_ENCODE_UTF32_LE[2]; t.chunk[3] = unicode::BOM_ENCODE_UTF32_LE[3]; } else { t.chunk[0] = unicode::BOM_ENCODE_UTF32_BE[0]; t.chunk[1] = unicode::BOM_ENCODE_UTF32_BE[1]; t.chunk[2] = unicode::BOM_ENCODE_UTF32_BE[2]; t.chunk[3] = unicode::BOM_ENCODE_UTF32_BE[3]; } ret.append(t.full); } } while (!iter.atEnd()) { uchar32_t c = *iter; if (endian != unicode::EUTFEE_NATIVE && getEndianness() != endian) c = unicode::swapEndian32(c); ret.append(c); ++iter; } return ret; } #endif //! Converts the string to a UTF-32 encoded string array. //! Unfortunately, no toUTF32_s() version exists due to limitations with Irrlicht's string class. //! \param endian The desired endianness of the string. //! \param addBOM If true, the proper unicode byte-order mark will be prefixed to the string. //! \return An array containing the UTF-32 encoded string. core::array<uchar32_t> toUTF32(const unicode::EUTF_ENDIAN endian = unicode::EUTFEE_NATIVE, const bool addBOM = false) const { core::array<uchar32_t> ret(size() + (addBOM ? unicode::BOM_UTF32_LEN : 0) + 1); const_iterator iter(*this, 0); // Add the BOM if specified. if (addBOM) { if (endian == unicode::EUTFEE_NATIVE) ret.push_back(unicode::BOM); else { union { uchar32_t full; u8 chunk[4]; } t; if (endian == unicode::EUTFEE_LITTLE) { t.chunk[0] = unicode::BOM_ENCODE_UTF32_LE[0]; t.chunk[1] = unicode::BOM_ENCODE_UTF32_LE[1]; t.chunk[2] = unicode::BOM_ENCODE_UTF32_LE[2]; t.chunk[3] = unicode::BOM_ENCODE_UTF32_LE[3]; } else { t.chunk[0] = unicode::BOM_ENCODE_UTF32_BE[0]; t.chunk[1] = unicode::BOM_ENCODE_UTF32_BE[1]; t.chunk[2] = unicode::BOM_ENCODE_UTF32_BE[2]; t.chunk[3] = unicode::BOM_ENCODE_UTF32_BE[3]; } ret.push_back(t.full); } } ret.push_back(0); while (!iter.atEnd()) { uchar32_t c = *iter; if (endian != unicode::EUTFEE_NATIVE && getEndianness() != endian) c = unicode::swapEndian32(c); ret.push_back(c); ++iter; } return ret; } //! Converts the string to a wchar_t encoded string. /** The size of a wchar_t changes depending on the platform. This function will store a correct UTF-8, -16, or -32 encoded string depending on the size of a wchar_t. **/ //! \param endian The desired endianness of the string. //! \param addBOM If true, the proper unicode byte-order mark will be prefixed to the string. //! \return A string containing the wchar_t encoded string. core::string<wchar_t> toWCHAR_s(const unicode::EUTF_ENDIAN endian = unicode::EUTFEE_NATIVE, const bool addBOM = false) const { if (sizeof(wchar_t) == 4) { core::array<uchar32_t> a(toUTF32(endian, addBOM)); core::stringw ret(a.pointer()); return ret; } else if (sizeof(wchar_t) == 2) { if (endian == unicode::EUTFEE_NATIVE && addBOM == false) { core::stringw ret(array); return ret; } else { core::array<uchar16_t> a(toUTF16(endian, addBOM)); core::stringw ret(a.pointer()); return ret; } } else if (sizeof(wchar_t) == 1) { core::array<uchar8_t> a(toUTF8(addBOM)); core::stringw ret(a.pointer()); return ret; } // Shouldn't happen. return core::stringw(); } //! Converts the string to a wchar_t encoded string array. /** The size of a wchar_t changes depending on the platform. This function will store a correct UTF-8, -16, or -32 encoded string depending on the size of a wchar_t. **/ //! \param endian The desired endianness of the string. //! \param addBOM If true, the proper unicode byte-order mark will be prefixed to the string. //! \return An array containing the wchar_t encoded string. core::array<wchar_t> toWCHAR(const unicode::EUTF_ENDIAN endian = unicode::EUTFEE_NATIVE, const bool addBOM = false) const { if (sizeof(wchar_t) == 4) { core::array<uchar32_t> a(toUTF32(endian, addBOM)); core::array<wchar_t> ret(a.size()); ret.set_used(a.size()); memcpy((void*)ret.pointer(), (void*)a.pointer(), a.size() * sizeof(uchar32_t)); return ret; } if (sizeof(wchar_t) == 2) { if (endian == unicode::EUTFEE_NATIVE && addBOM == false) { core::array<wchar_t> ret(used); ret.set_used(used); memcpy((void*)ret.pointer(), (void*)array, used * sizeof(uchar16_t)); return ret; } else { core::array<uchar16_t> a(toUTF16(endian, addBOM)); core::array<wchar_t> ret(a.size()); ret.set_used(a.size()); memcpy((void*)ret.pointer(), (void*)a.pointer(), a.size() * sizeof(uchar16_t)); return ret; } } if (sizeof(wchar_t) == 1) { core::array<uchar8_t> a(toUTF8(addBOM)); core::array<wchar_t> ret(a.size()); ret.set_used(a.size()); memcpy((void*)ret.pointer(), (void*)a.pointer(), a.size() * sizeof(uchar8_t)); return ret; } // Shouldn't happen. return core::array<wchar_t>(); } //! Converts the string to a properly encoded io::path string. //! \param endian The desired endianness of the string. //! \param addBOM If true, the proper unicode byte-order mark will be prefixed to the string. //! \return An io::path string containing the properly encoded string. io::path toPATH_s(const unicode::EUTF_ENDIAN endian = unicode::EUTFEE_NATIVE, const bool addBOM = false) const { #if defined(_IRR_WCHAR_FILESYSTEM) return toWCHAR_s(endian, addBOM); #else return toUTF8_s(addBOM); #endif } //! Loads an unknown stream of data. //! Will attempt to determine if the stream is unicode data. Useful for loading from files. //! \param data The data stream to load from. //! \param data_size The length of the data string. //! \return A reference to our current string. ustring16<TAlloc>& loadDataStream(const char* data, size_t data_size) { // Clear our string. *this = ""; if (!data) return *this; unicode::EUTF_ENCODE e = unicode::determineUnicodeBOM(data); switch (e) { default: case unicode::EUTFE_UTF8: append((uchar8_t*)data, data_size); break; case unicode::EUTFE_UTF16: case unicode::EUTFE_UTF16_BE: case unicode::EUTFE_UTF16_LE: append((uchar16_t*)data, data_size / 2); break; case unicode::EUTFE_UTF32: case unicode::EUTFE_UTF32_BE: case unicode::EUTFE_UTF32_LE: append((uchar32_t*)data, data_size / 4); break; } return *this; } //! Gets the encoding of the Unicode string this class contains. //! \return An enum describing the current encoding of this string. const unicode::EUTF_ENCODE getEncoding() const { return encoding; } //! Gets the endianness of the Unicode string this class contains. //! \return An enum describing the endianness of this string. const unicode::EUTF_ENDIAN getEndianness() const { if (encoding == unicode::EUTFE_UTF16_LE || encoding == unicode::EUTFE_UTF32_LE) return unicode::EUTFEE_LITTLE; else return unicode::EUTFEE_BIG; } private: //! Reallocate the string, making it bigger or smaller. //! \param new_size The new size of the string. void reallocate(u32 new_size) { uchar16_t* old_array = array; array = allocator.allocate(new_size + 1); //new u16[new_size]; allocated = new_size + 1; if (old_array == 0) return; u32 amount = used < new_size ? used : new_size; for (u32 i=0; i<=amount; ++i) array[i] = old_array[i]; if (allocated <= used) used = allocated - 1; array[used] = 0; allocator.deallocate(old_array); // delete [] old_array; } //--- member variables uchar16_t* array; unicode::EUTF_ENCODE encoding; u32 allocated; u32 used; TAlloc allocator; //irrAllocator<uchar16_t> allocator; }; typedef ustring16<irrAllocator<uchar16_t> > ustring; //! Appends two ustring16s. template <typename TAlloc> inline ustring16<TAlloc> operator+(const ustring16<TAlloc>& left, const ustring16<TAlloc>& right) { ustring16<TAlloc> ret(left); ret += right; return ret; } //! Appends a ustring16 and a null-terminated unicode string. template <typename TAlloc, class B> inline ustring16<TAlloc> operator+(const ustring16<TAlloc>& left, const B* const right) { ustring16<TAlloc> ret(left); ret += right; return ret; } //! Appends a ustring16 and a null-terminated unicode string. template <class B, typename TAlloc> inline ustring16<TAlloc> operator+(const B* const left, const ustring16<TAlloc>& right) { ustring16<TAlloc> ret(left); ret += right; return ret; } //! Appends a ustring16 and an Irrlicht string. template <typename TAlloc, typename B, typename BAlloc> inline ustring16<TAlloc> operator+(const ustring16<TAlloc>& left, const string<B, BAlloc>& right) { ustring16<TAlloc> ret(left); ret += right; return ret; } //! Appends a ustring16 and an Irrlicht string. template <typename TAlloc, typename B, typename BAlloc> inline ustring16<TAlloc> operator+(const string<B, BAlloc>& left, const ustring16<TAlloc>& right) { ustring16<TAlloc> ret(left); ret += right; return ret; } //! Appends a ustring16 and a std::basic_string. template <typename TAlloc, typename B, typename A, typename BAlloc> inline ustring16<TAlloc> operator+(const ustring16<TAlloc>& left, const std::basic_string<B, A, BAlloc>& right) { ustring16<TAlloc> ret(left); ret += right; return ret; } //! Appends a ustring16 and a std::basic_string. template <typename TAlloc, typename B, typename A, typename BAlloc> inline ustring16<TAlloc> operator+(const std::basic_string<B, A, BAlloc>& left, const ustring16<TAlloc>& right) { ustring16<TAlloc> ret(left); ret += right; return ret; } //! Appends a ustring16 and a char. template <typename TAlloc> inline ustring16<TAlloc> operator+(const ustring16<TAlloc>& left, const char right) { ustring16<TAlloc> ret(left); ret += right; return ret; } //! Appends a ustring16 and a char. template <typename TAlloc> inline ustring16<TAlloc> operator+(const char left, const ustring16<TAlloc>& right) { ustring16<TAlloc> ret(left); ret += right; return ret; } #ifdef USTRING_CPP0X_NEWLITERALS //! Appends a ustring16 and a uchar32_t. template <typename TAlloc> inline ustring16<TAlloc> operator+(const ustring16<TAlloc>& left, const uchar32_t right) { ustring16<TAlloc> ret(left); ret += right; return ret; } //! Appends a ustring16 and a uchar32_t. template <typename TAlloc> inline ustring16<TAlloc> operator+(const uchar32_t left, const ustring16<TAlloc>& right) { ustring16<TAlloc> ret(left); ret += right; return ret; } #endif //! Appends a ustring16 and a short. template <typename TAlloc> inline ustring16<TAlloc> operator+(const ustring16<TAlloc>& left, const short right) { ustring16<TAlloc> ret(left); ret += core::stringc(right); return ret; } //! Appends a ustring16 and a short. template <typename TAlloc> inline ustring16<TAlloc> operator+(const short left, const ustring16<TAlloc>& right) { ustring16<TAlloc> ret((core::stringc(left))); ret += right; return ret; } //! Appends a ustring16 and an unsigned short. template <typename TAlloc> inline ustring16<TAlloc> operator+(const ustring16<TAlloc>& left, const unsigned short right) { ustring16<TAlloc> ret(left); ret += core::stringc(right); return ret; } //! Appends a ustring16 and an unsigned short. template <typename TAlloc> inline ustring16<TAlloc> operator+(const unsigned short left, const ustring16<TAlloc>& right) { ustring16<TAlloc> ret((core::stringc(left))); ret += right; return ret; } //! Appends a ustring16 and an int. template <typename TAlloc> inline ustring16<TAlloc> operator+(const ustring16<TAlloc>& left, const int right) { ustring16<TAlloc> ret(left); ret += core::stringc(right); return ret; } //! Appends a ustring16 and an int. template <typename TAlloc> inline ustring16<TAlloc> operator+(const int left, const ustring16<TAlloc>& right) { ustring16<TAlloc> ret((core::stringc(left))); ret += right; return ret; } //! Appends a ustring16 and an unsigned int. template <typename TAlloc> inline ustring16<TAlloc> operator+(const ustring16<TAlloc>& left, const unsigned int right) { ustring16<TAlloc> ret(left); ret += core::stringc(right); return ret; } //! Appends a ustring16 and an unsigned int. template <typename TAlloc> inline ustring16<TAlloc> operator+(const unsigned int left, const ustring16<TAlloc>& right) { ustring16<TAlloc> ret((core::stringc(left))); ret += right; return ret; } //! Appends a ustring16 and a long. template <typename TAlloc> inline ustring16<TAlloc> operator+(const ustring16<TAlloc>& left, const long right) { ustring16<TAlloc> ret(left); ret += core::stringc(right); return ret; } //! Appends a ustring16 and a long. template <typename TAlloc> inline ustring16<TAlloc> operator+(const long left, const ustring16<TAlloc>& right) { ustring16<TAlloc> ret((core::stringc(left))); ret += right; return ret; } //! Appends a ustring16 and an unsigned long. template <typename TAlloc> inline ustring16<TAlloc> operator+(const ustring16<TAlloc>& left, const unsigned long right) { ustring16<TAlloc> ret(left); ret += core::stringc(right); return ret; } //! Appends a ustring16 and an unsigned long. template <typename TAlloc> inline ustring16<TAlloc> operator+(const unsigned long left, const ustring16<TAlloc>& right) { ustring16<TAlloc> ret((core::stringc(left))); ret += right; return ret; } //! Appends a ustring16 and a float. template <typename TAlloc> inline ustring16<TAlloc> operator+(const ustring16<TAlloc>& left, const float right) { ustring16<TAlloc> ret(left); ret += core::stringc(right); return ret; } //! Appends a ustring16 and a float. template <typename TAlloc> inline ustring16<TAlloc> operator+(const float left, const ustring16<TAlloc>& right) { ustring16<TAlloc> ret((core::stringc(left))); ret += right; return ret; } //! Appends a ustring16 and a double. template <typename TAlloc> inline ustring16<TAlloc> operator+(const ustring16<TAlloc>& left, const double right) { ustring16<TAlloc> ret(left); ret += core::stringc(right); return ret; } //! Appends a ustring16 and a double. template <typename TAlloc> inline ustring16<TAlloc> operator+(const double left, const ustring16<TAlloc>& right) { ustring16<TAlloc> ret((core::stringc(left))); ret += right; return ret; } #ifdef USTRING_CPP0X //! Appends two ustring16s. template <typename TAlloc> inline ustring16<TAlloc>&& operator+(const ustring16<TAlloc>& left, ustring16<TAlloc>&& right) { //std::cout << "MOVE operator+(&, &&)" << std::endl; right.insert(left, 0); return std::move(right); } //! Appends two ustring16s. template <typename TAlloc> inline ustring16<TAlloc>&& operator+(ustring16<TAlloc>&& left, const ustring16<TAlloc>& right) { //std::cout << "MOVE operator+(&&, &)" << std::endl; left.append(right); return std::move(left); } //! Appends two ustring16s. template <typename TAlloc> inline ustring16<TAlloc>&& operator+(ustring16<TAlloc>&& left, ustring16<TAlloc>&& right) { //std::cout << "MOVE operator+(&&, &&)" << std::endl; if ((right.size_raw() <= left.capacity() - left.size_raw()) || (right.capacity() - right.size_raw() < left.size_raw())) { left.append(right); return std::move(left); } else { right.insert(left, 0); return std::move(right); } } //! Appends a ustring16 and a null-terminated unicode string. template <typename TAlloc, class B> inline ustring16<TAlloc>&& operator+(ustring16<TAlloc>&& left, const B* const right) { //std::cout << "MOVE operator+(&&, B*)" << std::endl; left.append(right); return std::move(left); } //! Appends a ustring16 and a null-terminated unicode string. template <class B, typename TAlloc> inline ustring16<TAlloc>&& operator+(const B* const left, ustring16<TAlloc>&& right) { //std::cout << "MOVE operator+(B*, &&)" << std::endl; right.insert(left, 0); return std::move(right); } //! Appends a ustring16 and an Irrlicht string. template <typename TAlloc, typename B, typename BAlloc> inline ustring16<TAlloc>&& operator+(const string<B, BAlloc>& left, ustring16<TAlloc>&& right) { //std::cout << "MOVE operator+(&, &&)" << std::endl; right.insert(left, 0); return std::move(right); } //! Appends a ustring16 and an Irrlicht string. template <typename TAlloc, typename B, typename BAlloc> inline ustring16<TAlloc>&& operator+(ustring16<TAlloc>&& left, const string<B, BAlloc>& right) { //std::cout << "MOVE operator+(&&, &)" << std::endl; left.append(right); return std::move(left); } //! Appends a ustring16 and a std::basic_string. template <typename TAlloc, typename B, typename A, typename BAlloc> inline ustring16<TAlloc>&& operator+(const std::basic_string<B, A, BAlloc>& left, ustring16<TAlloc>&& right) { //std::cout << "MOVE operator+(&, &&)" << std::endl; right.insert(core::ustring16<TAlloc>(left), 0); return std::move(right); } //! Appends a ustring16 and a std::basic_string. template <typename TAlloc, typename B, typename A, typename BAlloc> inline ustring16<TAlloc>&& operator+(ustring16<TAlloc>&& left, const std::basic_string<B, A, BAlloc>& right) { //std::cout << "MOVE operator+(&&, &)" << std::endl; left.append(right); return std::move(left); } //! Appends a ustring16 and a char. template <typename TAlloc> inline ustring16<TAlloc> operator+(ustring16<TAlloc>&& left, const char right) { left.append((uchar32_t)right); return std::move(left); } //! Appends a ustring16 and a char. template <typename TAlloc> inline ustring16<TAlloc> operator+(const char left, ustring16<TAlloc>&& right) { right.insert((uchar32_t)left, 0); return std::move(right); } #ifdef USTRING_CPP0X_NEWLITERALS //! Appends a ustring16 and a uchar32_t. template <typename TAlloc> inline ustring16<TAlloc> operator+(ustring16<TAlloc>&& left, const uchar32_t right) { left.append(right); return std::move(left); } //! Appends a ustring16 and a uchar32_t. template <typename TAlloc> inline ustring16<TAlloc> operator+(const uchar32_t left, ustring16<TAlloc>&& right) { right.insert(left, 0); return std::move(right); } #endif //! Appends a ustring16 and a short. template <typename TAlloc> inline ustring16<TAlloc> operator+(ustring16<TAlloc>&& left, const short right) { left.append(core::stringc(right)); return std::move(left); } //! Appends a ustring16 and a short. template <typename TAlloc> inline ustring16<TAlloc> operator+(const short left, ustring16<TAlloc>&& right) { right.insert(core::stringc(left), 0); return std::move(right); } //! Appends a ustring16 and an unsigned short. template <typename TAlloc> inline ustring16<TAlloc> operator+(ustring16<TAlloc>&& left, const unsigned short right) { left.append(core::stringc(right)); return std::move(left); } //! Appends a ustring16 and an unsigned short. template <typename TAlloc> inline ustring16<TAlloc> operator+(const unsigned short left, ustring16<TAlloc>&& right) { right.insert(core::stringc(left), 0); return std::move(right); } //! Appends a ustring16 and an int. template <typename TAlloc> inline ustring16<TAlloc> operator+(ustring16<TAlloc>&& left, const int right) { left.append(core::stringc(right)); return std::move(left); } //! Appends a ustring16 and an int. template <typename TAlloc> inline ustring16<TAlloc> operator+(const int left, ustring16<TAlloc>&& right) { right.insert(core::stringc(left), 0); return std::move(right); } //! Appends a ustring16 and an unsigned int. template <typename TAlloc> inline ustring16<TAlloc> operator+(ustring16<TAlloc>&& left, const unsigned int right) { left.append(core::stringc(right)); return std::move(left); } //! Appends a ustring16 and an unsigned int. template <typename TAlloc> inline ustring16<TAlloc> operator+(const unsigned int left, ustring16<TAlloc>&& right) { right.insert(core::stringc(left), 0); return std::move(right); } //! Appends a ustring16 and a long. template <typename TAlloc> inline ustring16<TAlloc> operator+(ustring16<TAlloc>&& left, const long right) { left.append(core::stringc(right)); return std::move(left); } //! Appends a ustring16 and a long. template <typename TAlloc> inline ustring16<TAlloc> operator+(const long left, ustring16<TAlloc>&& right) { right.insert(core::stringc(left), 0); return std::move(right); } //! Appends a ustring16 and an unsigned long. template <typename TAlloc> inline ustring16<TAlloc> operator+(ustring16<TAlloc>&& left, const unsigned long right) { left.append(core::stringc(right)); return std::move(left); } //! Appends a ustring16 and an unsigned long. template <typename TAlloc> inline ustring16<TAlloc> operator+(const unsigned long left, ustring16<TAlloc>&& right) { right.insert(core::stringc(left), 0); return std::move(right); } //! Appends a ustring16 and a float. template <typename TAlloc> inline ustring16<TAlloc> operator+(ustring16<TAlloc>&& left, const float right) { left.append(core::stringc(right)); return std::move(left); } //! Appends a ustring16 and a float. template <typename TAlloc> inline ustring16<TAlloc> operator+(const float left, ustring16<TAlloc>&& right) { right.insert(core::stringc(left), 0); return std::move(right); } //! Appends a ustring16 and a double. template <typename TAlloc> inline ustring16<TAlloc> operator+(ustring16<TAlloc>&& left, const double right) { left.append(core::stringc(right)); return std::move(left); } //! Appends a ustring16 and a double. template <typename TAlloc> inline ustring16<TAlloc> operator+(const double left, ustring16<TAlloc>&& right) { right.insert(core::stringc(left), 0); return std::move(right); } #endif #ifndef USTRING_NO_STL //! Writes a ustring16 to an ostream. template <typename TAlloc> inline std::ostream& operator<<(std::ostream& out, const ustring16<TAlloc>& in) { out << in.toUTF8_s().c_str(); return out; } //! Writes a ustring16 to a wostream. template <typename TAlloc> inline std::wostream& operator<<(std::wostream& out, const ustring16<TAlloc>& in) { out << in.toWCHAR_s().c_str(); return out; } #endif #ifndef USTRING_NO_STL namespace unicode { //! Hashing algorithm for hashing a ustring. Used for things like unordered_maps. //! Algorithm taken from std::hash<std::string>. class hash : public std::unary_function<core::ustring, size_t> { public: size_t operator()(const core::ustring& s) const { size_t ret = 2166136261U; size_t index = 0; size_t stride = 1 + s.size_raw() / 10; core::ustring::const_iterator i = s.begin(); while (i != s.end()) { // TODO: Don't force u32 on an x64 OS. Make it agnostic. ret = 16777619U * ret ^ (size_t)s[(u32)index]; index += stride; i += stride; } return (ret); } }; } // end namespace unicode #endif } // end namespace core } // end namespace irr
pgimeno/minetest
src/irrlicht_changes/irrUString.h
C++
mit
97,781
// Copyright (C) 2002-2012 Nikolaus Gebhardt // Copyright (C) 2016 Nathanaël Courant: // Modified the functions to use EnrichedText instead of string. // This file is part of the "Irrlicht Engine". // For conditions of distribution and use, see copyright notice in irrlicht.h #include "static_text.h" #ifdef _IRR_COMPILE_WITH_GUI_ #include <IGUIFont.h> #include <IVideoDriver.h> #include <rect.h> #include <SColor.h> #if USE_FREETYPE #include "CGUITTFont.h" #endif #include "util/string.h" namespace irr { #if USE_FREETYPE namespace gui { //! constructor StaticText::StaticText(const EnrichedString &text, bool border, IGUIEnvironment* environment, IGUIElement* parent, s32 id, const core::rect<s32>& rectangle, bool background) : IGUIStaticText(environment, parent, id, rectangle), HAlign(EGUIA_UPPERLEFT), VAlign(EGUIA_UPPERLEFT), Border(border), OverrideColorEnabled(false), OverrideBGColorEnabled(false), WordWrap(false), Background(background), RestrainTextInside(true), RightToLeft(false), OverrideColor(video::SColor(101,255,255,255)), BGColor(video::SColor(101,210,210,210)), OverrideFont(0), LastBreakFont(0) { #ifdef _DEBUG setDebugName("StaticText"); #endif Text = text.c_str(); cText = text; if (environment && environment->getSkin()) { BGColor = environment->getSkin()->getColor(gui::EGDC_3D_FACE); } } //! destructor StaticText::~StaticText() { if (OverrideFont) OverrideFont->drop(); } //! draws the element and its children void StaticText::draw() { if (!IsVisible) return; IGUISkin* skin = Environment->getSkin(); if (!skin) return; video::IVideoDriver* driver = Environment->getVideoDriver(); core::rect<s32> frameRect(AbsoluteRect); // draw background if (Background) { if ( !OverrideBGColorEnabled ) // skin-colors can change BGColor = skin->getColor(gui::EGDC_3D_FACE); driver->draw2DRectangle(BGColor, frameRect, &AbsoluteClippingRect); } // draw the border if (Border) { skin->draw3DSunkenPane(this, 0, true, false, frameRect, &AbsoluteClippingRect); frameRect.UpperLeftCorner.X += skin->getSize(EGDS_TEXT_DISTANCE_X); } // draw the text if (cText.size()) { IGUIFont* font = getActiveFont(); if (font) { if (!WordWrap) { // TODO: add colors here if (VAlign == EGUIA_LOWERRIGHT) { frameRect.UpperLeftCorner.Y = frameRect.LowerRightCorner.Y - font->getDimension(L"A").Height - font->getKerningHeight(); } if (HAlign == EGUIA_LOWERRIGHT) { frameRect.UpperLeftCorner.X = frameRect.LowerRightCorner.X - font->getDimension(cText.c_str()).Width; } irr::gui::CGUITTFont *tmp = static_cast<irr::gui::CGUITTFont*>(font); tmp->draw(cText, frameRect, OverrideColorEnabled ? OverrideColor : skin->getColor(isEnabled() ? EGDC_BUTTON_TEXT : EGDC_GRAY_TEXT), HAlign == EGUIA_CENTER, VAlign == EGUIA_CENTER, (RestrainTextInside ? &AbsoluteClippingRect : NULL)); } else { if (font != LastBreakFont) breakText(); core::rect<s32> r = frameRect; s32 height = font->getDimension(L"A").Height + font->getKerningHeight(); s32 totalHeight = height * BrokenText.size(); if (VAlign == EGUIA_CENTER) { r.UpperLeftCorner.Y = r.getCenter().Y - (totalHeight / 2); } else if (VAlign == EGUIA_LOWERRIGHT) { r.UpperLeftCorner.Y = r.LowerRightCorner.Y - totalHeight; } irr::video::SColor previous_color(255, 255, 255, 255); for (u32 i=0; i<BrokenText.size(); ++i) { if (HAlign == EGUIA_LOWERRIGHT) { r.UpperLeftCorner.X = frameRect.LowerRightCorner.X - font->getDimension(BrokenText[i].c_str()).Width; } //std::vector<irr::video::SColor> colors; //std::wstring str; EnrichedString str = BrokenText[i]; //str = colorizeText(BrokenText[i].c_str(), colors, previous_color); //if (!colors.empty()) // previous_color = colors[colors.size() - 1]; irr::gui::CGUITTFont *tmp = static_cast<irr::gui::CGUITTFont*>(font); tmp->draw(str, r, previous_color, // FIXME HAlign == EGUIA_CENTER, false, (RestrainTextInside ? &AbsoluteClippingRect : NULL)); r.LowerRightCorner.Y += height; r.UpperLeftCorner.Y += height; } } } } IGUIElement::draw(); } //! Sets another skin independent font. void StaticText::setOverrideFont(IGUIFont* font) { if (OverrideFont == font) return; if (OverrideFont) OverrideFont->drop(); OverrideFont = font; if (OverrideFont) OverrideFont->grab(); breakText(); } //! Gets the override font (if any) IGUIFont * StaticText::getOverrideFont() const { return OverrideFont; } //! Get the font which is used right now for drawing IGUIFont* StaticText::getActiveFont() const { if ( OverrideFont ) return OverrideFont; IGUISkin* skin = Environment->getSkin(); if (skin) return skin->getFont(); return 0; } //! Sets another color for the text. void StaticText::setOverrideColor(video::SColor color) { OverrideColor = color; OverrideColorEnabled = true; } //! Sets another color for the text. void StaticText::setBackgroundColor(video::SColor color) { BGColor = color; OverrideBGColorEnabled = true; Background = true; } //! Sets whether to draw the background void StaticText::setDrawBackground(bool draw) { Background = draw; } //! Gets the background color video::SColor StaticText::getBackgroundColor() const { return BGColor; } //! Checks if background drawing is enabled bool StaticText::isDrawBackgroundEnabled() const { return Background; } //! Sets whether to draw the border void StaticText::setDrawBorder(bool draw) { Border = draw; } //! Checks if border drawing is enabled bool StaticText::isDrawBorderEnabled() const { return Border; } void StaticText::setTextRestrainedInside(bool restrainTextInside) { RestrainTextInside = restrainTextInside; } bool StaticText::isTextRestrainedInside() const { return RestrainTextInside; } void StaticText::setTextAlignment(EGUI_ALIGNMENT horizontal, EGUI_ALIGNMENT vertical) { HAlign = horizontal; VAlign = vertical; } #if IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR <= 7 const video::SColor& StaticText::getOverrideColor() const #else video::SColor StaticText::getOverrideColor() const #endif { return OverrideColor; } //! Sets if the static text should use the overide color or the //! color in the gui skin. void StaticText::enableOverrideColor(bool enable) { OverrideColorEnabled = enable; } bool StaticText::isOverrideColorEnabled() const { return OverrideColorEnabled; } //! Enables or disables word wrap for using the static text as //! multiline text control. void StaticText::setWordWrap(bool enable) { WordWrap = enable; breakText(); } bool StaticText::isWordWrapEnabled() const { return WordWrap; } void StaticText::setRightToLeft(bool rtl) { if (RightToLeft != rtl) { RightToLeft = rtl; breakText(); } } bool StaticText::isRightToLeft() const { return RightToLeft; } //! Breaks the single text line. void StaticText::breakText() { if (!WordWrap) return; BrokenText.clear(); IGUISkin* skin = Environment->getSkin(); IGUIFont* font = getActiveFont(); if (!font) return; LastBreakFont = font; EnrichedString line; EnrichedString word; EnrichedString whitespace; s32 size = cText.size(); s32 length = 0; s32 elWidth = RelativeRect.getWidth(); if (Border) elWidth -= 2*skin->getSize(EGDS_TEXT_DISTANCE_X); wchar_t c; //std::vector<irr::video::SColor> colors; // We have to deal with right-to-left and left-to-right differently // However, most parts of the following code is the same, it's just // some order and boundaries which change. if (!RightToLeft) { // regular (left-to-right) for (s32 i=0; i<size; ++i) { c = cText.getString()[i]; bool lineBreak = false; if (c == L'\r') // Mac or Windows breaks { lineBreak = true; //if (Text[i+1] == L'\n') // Windows breaks //{ // Text.erase(i+1); // --size; //} c = '\0'; } else if (c == L'\n') // Unix breaks { lineBreak = true; c = '\0'; } bool isWhitespace = (c == L' ' || c == 0); if ( !isWhitespace ) { // part of a word //word += c; word.addChar(cText, i); } if ( isWhitespace || i == (size-1)) { if (word.size()) { // here comes the next whitespace, look if // we must break the last word to the next line. const s32 whitelgth = font->getDimension(whitespace.c_str()).Width; //const std::wstring sanitized = removeEscapes(word.c_str()); const s32 wordlgth = font->getDimension(word.c_str()).Width; if (wordlgth > elWidth) { // This word is too long to fit in the available space, look for // the Unicode Soft HYphen (SHY / 00AD) character for a place to // break the word at int where = core::stringw(word.c_str()).findFirst( wchar_t(0x00AD) ); if (where != -1) { EnrichedString first = word.substr(0, where); EnrichedString second = word.substr(where, word.size() - where); first.addCharNoColor(L'-'); BrokenText.push_back(line + first); const s32 secondLength = font->getDimension(second.c_str()).Width; length = secondLength; line = second; } else { // No soft hyphen found, so there's nothing more we can do // break to next line if (length) BrokenText.push_back(line); length = wordlgth; line = word; } } else if (length && (length + wordlgth + whitelgth > elWidth)) { // break to next line BrokenText.push_back(line); length = wordlgth; line = word; } else { // add word to line line += whitespace; line += word; length += whitelgth + wordlgth; } word.clear(); whitespace.clear(); } if ( isWhitespace && c != 0) { whitespace.addChar(cText, i); } // compute line break if (lineBreak) { line += whitespace; line += word; BrokenText.push_back(line); line.clear(); word.clear(); whitespace.clear(); length = 0; } } } line += whitespace; line += word; BrokenText.push_back(line); } else { // right-to-left for (s32 i=size; i>=0; --i) { c = cText.getString()[i]; bool lineBreak = false; if (c == L'\r') // Mac or Windows breaks { lineBreak = true; //if ((i>0) && Text[i-1] == L'\n') // Windows breaks //{ // Text.erase(i-1); // --size; //} c = '\0'; } else if (c == L'\n') // Unix breaks { lineBreak = true; c = '\0'; } if (c==L' ' || c==0 || i==0) { if (word.size()) { // here comes the next whitespace, look if // we must break the last word to the next line. const s32 whitelgth = font->getDimension(whitespace.c_str()).Width; const s32 wordlgth = font->getDimension(word.c_str()).Width; if (length && (length + wordlgth + whitelgth > elWidth)) { // break to next line BrokenText.push_back(line); length = wordlgth; line = word; } else { // add word to line line = whitespace + line; line = word + line; length += whitelgth + wordlgth; } word.clear(); whitespace.clear(); } if (c != 0) // whitespace = core::stringw(&c, 1) + whitespace; whitespace = cText.substr(i, 1) + whitespace; // compute line break if (lineBreak) { line = whitespace + line; line = word + line; BrokenText.push_back(line); line.clear(); word.clear(); whitespace.clear(); length = 0; } } else { // yippee this is a word.. //word = core::stringw(&c, 1) + word; word = cText.substr(i, 1) + word; } } line = whitespace + line; line = word + line; BrokenText.push_back(line); } } //! Sets the new caption of this element. void StaticText::setText(const wchar_t* text) { setText(EnrichedString(text)); } //! Sets the new caption of this element. void StaticText::setText(const EnrichedString &text) { IGUIElement::setText(text.c_str()); cText = text; if (text.hasBackground()) { setBackgroundColor(text.getBackground()); } breakText(); } void StaticText::updateAbsolutePosition() { IGUIElement::updateAbsolutePosition(); breakText(); } //! Returns the height of the text in pixels when it is drawn. s32 StaticText::getTextHeight() const { IGUIFont* font = getActiveFont(); if (!font) return 0; s32 height = font->getDimension(L"A").Height + font->getKerningHeight(); if (WordWrap) height *= BrokenText.size(); return height; } s32 StaticText::getTextWidth() const { IGUIFont * font = getActiveFont(); if(!font) return 0; if(WordWrap) { s32 widest = 0; for(u32 line = 0; line < BrokenText.size(); ++line) { s32 width = font->getDimension(BrokenText[line].c_str()).Width; if(width > widest) widest = width; } return widest; } else { return font->getDimension(cText.c_str()).Width; } } //! Writes attributes of the element. //! Implement this to expose the attributes of your element for //! scripting languages, editors, debuggers or xml serialization purposes. void StaticText::serializeAttributes(io::IAttributes* out, io::SAttributeReadWriteOptions* options=0) const { IGUIStaticText::serializeAttributes(out,options); out->addBool ("Border", Border); out->addBool ("OverrideColorEnabled",OverrideColorEnabled); out->addBool ("OverrideBGColorEnabled",OverrideBGColorEnabled); out->addBool ("WordWrap", WordWrap); out->addBool ("Background", Background); out->addBool ("RightToLeft", RightToLeft); out->addBool ("RestrainTextInside", RestrainTextInside); out->addColor ("OverrideColor", OverrideColor); out->addColor ("BGColor", BGColor); out->addEnum ("HTextAlign", HAlign, GUIAlignmentNames); out->addEnum ("VTextAlign", VAlign, GUIAlignmentNames); // out->addFont ("OverrideFont", OverrideFont); } //! Reads attributes of the element void StaticText::deserializeAttributes(io::IAttributes* in, io::SAttributeReadWriteOptions* options=0) { IGUIStaticText::deserializeAttributes(in,options); Border = in->getAttributeAsBool("Border"); enableOverrideColor(in->getAttributeAsBool("OverrideColorEnabled")); OverrideBGColorEnabled = in->getAttributeAsBool("OverrideBGColorEnabled"); setWordWrap(in->getAttributeAsBool("WordWrap")); Background = in->getAttributeAsBool("Background"); RightToLeft = in->getAttributeAsBool("RightToLeft"); RestrainTextInside = in->getAttributeAsBool("RestrainTextInside"); OverrideColor = in->getAttributeAsColor("OverrideColor"); BGColor = in->getAttributeAsColor("BGColor"); setTextAlignment( (EGUI_ALIGNMENT) in->getAttributeAsEnumeration("HTextAlign", GUIAlignmentNames), (EGUI_ALIGNMENT) in->getAttributeAsEnumeration("VTextAlign", GUIAlignmentNames)); // OverrideFont = in->getAttributeAsFont("OverrideFont"); } } // end namespace gui #endif // USE_FREETYPE } // end namespace irr #endif // _IRR_COMPILE_WITH_GUI_
pgimeno/minetest
src/irrlicht_changes/static_text.cpp
C++
mit
15,162
// Copyright (C) 2002-2012 Nikolaus Gebhardt // Copyright (C) 2016 Nathanaël Courant // Modified this class to work with EnrichedStrings too // This file is part of the "Irrlicht Engine". // For conditions of distribution and use, see copyright notice in irrlicht.h #pragma once #include "IrrCompileConfig.h" #ifdef _IRR_COMPILE_WITH_GUI_ #include "IGUIStaticText.h" #include "irrArray.h" #include "log.h" #include <vector> #include "util/enriched_string.h" #include "config.h" #include <IGUIEnvironment.h> #if USE_FREETYPE namespace irr { namespace gui { const EGUI_ELEMENT_TYPE EGUIET_ENRICHED_STATIC_TEXT = (EGUI_ELEMENT_TYPE)(0x1000); class StaticText : public IGUIStaticText { public: //! constructor StaticText(const EnrichedString &text, bool border, IGUIEnvironment* environment, IGUIElement* parent, s32 id, const core::rect<s32>& rectangle, bool background = false); //! destructor virtual ~StaticText(); static irr::gui::IGUIStaticText *add( irr::gui::IGUIEnvironment *guienv, const EnrichedString &text, const core::rect< s32 > &rectangle, bool border = false, bool wordWrap = true, irr::gui::IGUIElement *parent = NULL, s32 id = -1, bool fillBackground = false) { if (parent == NULL) { // parent is NULL, so we must find one, or we need not to drop // result, but then there will be a memory leak. // // What Irrlicht does is to use guienv as a parent, but the problem // is that guienv is here only an IGUIEnvironment, while it is a // CGUIEnvironment in Irrlicht, which inherits from both IGUIElement // and IGUIEnvironment. // // A solution would be to dynamic_cast guienv to a // IGUIElement*, but Irrlicht is shipped without rtti support // in some distributions, causing the dymanic_cast to segfault. // // Thus, to find the parent, we create a dummy StaticText and ask // for its parent, and then remove it. irr::gui::IGUIStaticText *dummy_text = guienv->addStaticText(L"", rectangle, border, wordWrap, parent, id, fillBackground); parent = dummy_text->getParent(); dummy_text->remove(); } irr::gui::IGUIStaticText *result = new irr::gui::StaticText( text, border, guienv, parent, id, rectangle, fillBackground); result->setWordWrap(wordWrap); result->drop(); return result; } static irr::gui::IGUIStaticText *add( irr::gui::IGUIEnvironment *guienv, const wchar_t *text, const core::rect< s32 > &rectangle, bool border = false, bool wordWrap = true, irr::gui::IGUIElement *parent = NULL, s32 id = -1, bool fillBackground = false) { return add(guienv, EnrichedString(text), rectangle, border, wordWrap, parent, id, fillBackground); } //! draws the element and its children virtual void draw(); //! Sets another skin independent font. virtual void setOverrideFont(IGUIFont* font=0); //! Gets the override font (if any) virtual IGUIFont* getOverrideFont() const; //! Get the font which is used right now for drawing virtual IGUIFont* getActiveFont() const; //! Sets another color for the text. virtual void setOverrideColor(video::SColor color); //! Sets another color for the background. virtual void setBackgroundColor(video::SColor color); //! Sets whether to draw the background virtual void setDrawBackground(bool draw); //! Gets the background color virtual video::SColor getBackgroundColor() const; //! Checks if background drawing is enabled virtual bool isDrawBackgroundEnabled() const; //! Sets whether to draw the border virtual void setDrawBorder(bool draw); //! Checks if border drawing is enabled virtual bool isDrawBorderEnabled() const; //! Sets alignment mode for text virtual void setTextAlignment(EGUI_ALIGNMENT horizontal, EGUI_ALIGNMENT vertical); //! Gets the override color #if IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR <= 7 virtual const video::SColor& getOverrideColor() const; #else virtual video::SColor getOverrideColor() const; #endif //! Sets if the static text should use the overide color or the //! color in the gui skin. virtual void enableOverrideColor(bool enable); //! Checks if an override color is enabled virtual bool isOverrideColorEnabled() const; //! Set whether the text in this label should be clipped if it goes outside bounds virtual void setTextRestrainedInside(bool restrainedInside); //! Checks if the text in this label should be clipped if it goes outside bounds virtual bool isTextRestrainedInside() const; //! Enables or disables word wrap for using the static text as //! multiline text control. virtual void setWordWrap(bool enable); //! Checks if word wrap is enabled virtual bool isWordWrapEnabled() const; //! Sets the new caption of this element. virtual void setText(const wchar_t* text); //! Returns the height of the text in pixels when it is drawn. virtual s32 getTextHeight() const; //! Returns the width of the current text, in the current font virtual s32 getTextWidth() const; //! Updates the absolute position, splits text if word wrap is enabled virtual void updateAbsolutePosition(); //! Set whether the string should be interpreted as right-to-left (RTL) text /** \note This component does not implement the Unicode bidi standard, the text of the component should be already RTL if you call this. The main difference when RTL is enabled is that the linebreaks for multiline elements are performed starting from the end. */ virtual void setRightToLeft(bool rtl); //! Checks if the text should be interpreted as right-to-left text virtual bool isRightToLeft() const; //! Writes attributes of the element. virtual void serializeAttributes(io::IAttributes* out, io::SAttributeReadWriteOptions* options) const; //! Reads attributes of the element virtual void deserializeAttributes(io::IAttributes* in, io::SAttributeReadWriteOptions* options); virtual bool hasType(EGUI_ELEMENT_TYPE t) const { return (t == EGUIET_ENRICHED_STATIC_TEXT) || (t == EGUIET_STATIC_TEXT); }; virtual bool hasType(EGUI_ELEMENT_TYPE t) { return (t == EGUIET_ENRICHED_STATIC_TEXT) || (t == EGUIET_STATIC_TEXT); }; void setText(const EnrichedString &text); private: //! Breaks the single text line. void breakText(); EGUI_ALIGNMENT HAlign, VAlign; bool Border; bool OverrideColorEnabled; bool OverrideBGColorEnabled; bool WordWrap; bool Background; bool RestrainTextInside; bool RightToLeft; video::SColor OverrideColor, BGColor; gui::IGUIFont* OverrideFont; gui::IGUIFont* LastBreakFont; // stored because: if skin changes, line break must be recalculated. EnrichedString cText; core::array< EnrichedString > BrokenText; }; } // end namespace gui } // end namespace irr inline void setStaticText(irr::gui::IGUIStaticText *static_text, const EnrichedString &text) { // dynamic_cast not possible due to some distributions shipped // without rtti support in irrlicht if (static_text->hasType(irr::gui::EGUIET_ENRICHED_STATIC_TEXT)) { irr::gui::StaticText* stext = static_cast<irr::gui::StaticText*>(static_text); stext->setText(text); } else { static_text->setText(text.c_str()); } } #else // USE_FREETYPE namespace irr { namespace gui { class StaticText { public: static irr::gui::IGUIStaticText *add( irr::gui::IGUIEnvironment *guienv, const EnrichedString &text, const core::rect< s32 > &rectangle, bool border = false, bool wordWrap = true, irr::gui::IGUIElement *parent = NULL, s32 id = -1, bool fillBackground = false) { return guienv->addStaticText(text.c_str(), rectangle, border, wordWrap, parent, id, fillBackground); } }; } // end namespace gui } // end namespace irr inline void setStaticText(irr::gui::IGUIStaticText *static_text, const EnrichedString &text) { static_text->setText(text.c_str()); } #endif inline void setStaticText(irr::gui::IGUIStaticText *static_text, const wchar_t *text) { auto color = static_text->isOverrideColorEnabled() ? static_text->getOverrideColor() : irr::video::SColor(255, 255, 255, 255); setStaticText(static_text, EnrichedString(text, color)); } #endif // _IRR_COMPILE_WITH_GUI_
pgimeno/minetest
src/irrlicht_changes/static_text.h
C++
mit
8,282
/* Minetest Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com> 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. */ #pragma once /* Ensure that <stdint.h> is included before <irrTypes.h>, unless building on * MSVC, to address an irrlicht issue: https://sourceforge.net/p/irrlicht/bugs/433/ * * TODO: Decide whether or not we support non-compliant C++ compilers like old * versions of MSCV. If we do not then <stdint.h> can always be included * regardless of the compiler. */ #ifndef _MSC_VER # include <cstdint> #endif #include <irrTypes.h> using namespace irr; namespace irr { // Irrlicht 1.8+ defines 64bit unsigned symbol in irrTypes.h #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8) #ifdef _MSC_VER // Windows typedef long long s64; typedef unsigned long long u64; #else // Posix typedef int64_t s64; typedef uint64_t u64; #endif #endif #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR >= 9) namespace core { template <typename T> inline T roundingError(); template <> inline s16 roundingError() { return 0; } } #endif } #define S8_MIN (-0x7F - 1) #define S16_MIN (-0x7FFF - 1) #define S32_MIN (-0x7FFFFFFF - 1) #define S64_MIN (-0x7FFFFFFFFFFFFFFF - 1) #define S8_MAX 0x7F #define S16_MAX 0x7FFF #define S32_MAX 0x7FFFFFFF #define S64_MAX 0x7FFFFFFFFFFFFFFF #define U8_MAX 0xFF #define U16_MAX 0xFFFF #define U32_MAX 0xFFFFFFFF #define U64_MAX 0xFFFFFFFFFFFFFFFF
pgimeno/minetest
src/irrlichttypes.h
C++
mit
2,115
/* Minetest Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com> 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. */ #pragma once #include "irrlichttypes.h" #include "irr_v2d.h" #include "irr_v3d.h" #include "irr_aabb3d.h" #include <SColor.h>
pgimeno/minetest
src/irrlichttypes_bloated.h
C++
mit
919
/* Minetest Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com> 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. */ #pragma once #include "irrlichttypes_bloated.h" #ifndef SERVER #include <IMesh.h> #include <IImage.h> #include <IrrlichtDevice.h> #include <IMeshSceneNode.h> #include <IDummyTransformationSceneNode.h> #include <SMesh.h> #include <ISceneManager.h> #include <IMeshBuffer.h> #include <SMeshBuffer.h> #include <IGUIElement.h> #include <IGUIEnvironment.h> #endif
pgimeno/minetest
src/irrlichttypes_extrabloated.h
C++
mit
1,150
/* Minetest Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com> Copyright (C) 2013 Kahrl <kahrl@gmx.net> 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 "itemdef.h" #include "nodedef.h" #include "tool.h" #include "inventory.h" #ifndef SERVER #include "client/mapblock_mesh.h" #include "client/mesh.h" #include "client/wieldmesh.h" #include "client/tile.h" #include "client/client.h" #endif #include "log.h" #include "settings.h" #include "util/serialize.h" #include "util/container.h" #include "util/thread.h" #include <map> #include <set> #ifdef __ANDROID__ #include <GLES/gl.h> #endif /* ItemDefinition */ ItemDefinition::ItemDefinition() { resetInitial(); } ItemDefinition::ItemDefinition(const ItemDefinition &def) { resetInitial(); *this = def; } ItemDefinition& ItemDefinition::operator=(const ItemDefinition &def) { if(this == &def) return *this; reset(); type = def.type; name = def.name; description = def.description; inventory_image = def.inventory_image; inventory_overlay = def.inventory_overlay; wield_image = def.wield_image; wield_overlay = def.wield_overlay; wield_scale = def.wield_scale; stack_max = def.stack_max; usable = def.usable; liquids_pointable = def.liquids_pointable; if(def.tool_capabilities) { tool_capabilities = new ToolCapabilities( *def.tool_capabilities); } groups = def.groups; node_placement_prediction = def.node_placement_prediction; sound_place = def.sound_place; sound_place_failed = def.sound_place_failed; range = def.range; palette_image = def.palette_image; color = def.color; return *this; } ItemDefinition::~ItemDefinition() { reset(); } void ItemDefinition::resetInitial() { // Initialize pointers to NULL so reset() does not delete undefined pointers tool_capabilities = NULL; reset(); } void ItemDefinition::reset() { type = ITEM_NONE; name = ""; description = ""; inventory_image = ""; inventory_overlay = ""; wield_image = ""; wield_overlay = ""; palette_image = ""; color = video::SColor(0xFFFFFFFF); wield_scale = v3f(1.0, 1.0, 1.0); stack_max = 99; usable = false; liquids_pointable = false; delete tool_capabilities; tool_capabilities = NULL; groups.clear(); sound_place = SimpleSoundSpec(); sound_place_failed = SimpleSoundSpec(); range = -1; node_placement_prediction = ""; } void ItemDefinition::serialize(std::ostream &os, u16 protocol_version) const { // protocol_version >= 37 u8 version = 6; writeU8(os, version); writeU8(os, type); os << serializeString(name); os << serializeString(description); os << serializeString(inventory_image); os << serializeString(wield_image); writeV3F32(os, wield_scale); writeS16(os, stack_max); writeU8(os, usable); writeU8(os, liquids_pointable); std::string tool_capabilities_s; if (tool_capabilities) { std::ostringstream tmp_os(std::ios::binary); tool_capabilities->serialize(tmp_os, protocol_version); tool_capabilities_s = tmp_os.str(); } os << serializeString(tool_capabilities_s); writeU16(os, groups.size()); for (const auto &group : groups) { os << serializeString(group.first); writeS16(os, group.second); } os << serializeString(node_placement_prediction); // Version from ContentFeatures::serialize to keep in sync sound_place.serialize(os, CONTENTFEATURES_VERSION); sound_place_failed.serialize(os, CONTENTFEATURES_VERSION); writeF32(os, range); os << serializeString(palette_image); writeARGB8(os, color); os << serializeString(inventory_overlay); os << serializeString(wield_overlay); } void ItemDefinition::deSerialize(std::istream &is) { // Reset everything reset(); // Deserialize int version = readU8(is); if (version < 6) throw SerializationError("unsupported ItemDefinition version"); type = (enum ItemType)readU8(is); name = deSerializeString(is); description = deSerializeString(is); inventory_image = deSerializeString(is); wield_image = deSerializeString(is); wield_scale = readV3F32(is); stack_max = readS16(is); usable = readU8(is); liquids_pointable = readU8(is); std::string tool_capabilities_s = deSerializeString(is); if (!tool_capabilities_s.empty()) { std::istringstream tmp_is(tool_capabilities_s, std::ios::binary); tool_capabilities = new ToolCapabilities; tool_capabilities->deSerialize(tmp_is); } groups.clear(); u32 groups_size = readU16(is); for(u32 i=0; i<groups_size; i++){ std::string name = deSerializeString(is); int value = readS16(is); groups[name] = value; } node_placement_prediction = deSerializeString(is); // Version from ContentFeatures::serialize to keep in sync sound_place.deSerialize(is, CONTENTFEATURES_VERSION); sound_place_failed.deSerialize(is, CONTENTFEATURES_VERSION); range = readF32(is); palette_image = deSerializeString(is); color = readARGB8(is); inventory_overlay = deSerializeString(is); wield_overlay = deSerializeString(is); // If you add anything here, insert it primarily inside the try-catch // block to not need to increase the version. //try { //} catch(SerializationError &e) {}; } /* CItemDefManager */ // SUGG: Support chains of aliases? class CItemDefManager: public IWritableItemDefManager { #ifndef SERVER struct ClientCached { video::ITexture *inventory_texture; ItemMesh wield_mesh; Palette *palette; ClientCached(): inventory_texture(NULL), palette(NULL) {} }; #endif public: CItemDefManager() { #ifndef SERVER m_main_thread = std::this_thread::get_id(); #endif clear(); } virtual ~CItemDefManager() { #ifndef SERVER const std::vector<ClientCached*> &values = m_clientcached.getValues(); for (ClientCached *cc : values) { if (cc->wield_mesh.mesh) cc->wield_mesh.mesh->drop(); delete cc; } #endif for (auto &item_definition : m_item_definitions) { delete item_definition.second; } m_item_definitions.clear(); } virtual const ItemDefinition& get(const std::string &name_) const { // Convert name according to possible alias std::string name = getAlias(name_); // Get the definition std::map<std::string, ItemDefinition*>::const_iterator i; i = m_item_definitions.find(name); if(i == m_item_definitions.end()) i = m_item_definitions.find("unknown"); assert(i != m_item_definitions.end()); return *(i->second); } virtual const std::string &getAlias(const std::string &name) const { StringMap::const_iterator it = m_aliases.find(name); if (it != m_aliases.end()) return it->second; return name; } virtual void getAll(std::set<std::string> &result) const { result.clear(); for (const auto &item_definition : m_item_definitions) { result.insert(item_definition.first); } for (const auto &alias : m_aliases) { result.insert(alias.first); } } virtual bool isKnown(const std::string &name_) const { // Convert name according to possible alias std::string name = getAlias(name_); // Get the definition std::map<std::string, ItemDefinition*>::const_iterator i; return m_item_definitions.find(name) != m_item_definitions.end(); } #ifndef SERVER public: ClientCached* createClientCachedDirect(const std::string &name, Client *client) const { infostream<<"Lazily creating item texture and mesh for \"" <<name<<"\""<<std::endl; // This is not thread-safe sanity_check(std::this_thread::get_id() == m_main_thread); // Skip if already in cache ClientCached *cc = NULL; m_clientcached.get(name, &cc); if(cc) return cc; ITextureSource *tsrc = client->getTextureSource(); const ItemDefinition &def = get(name); // Create new ClientCached cc = new ClientCached(); // Create an inventory texture cc->inventory_texture = NULL; if (!def.inventory_image.empty()) cc->inventory_texture = tsrc->getTexture(def.inventory_image); ItemStack item = ItemStack(); item.name = def.name; getItemMesh(client, item, &(cc->wield_mesh)); cc->palette = tsrc->getPalette(def.palette_image); // Put in cache m_clientcached.set(name, cc); return cc; } ClientCached* getClientCached(const std::string &name, Client *client) const { ClientCached *cc = NULL; m_clientcached.get(name, &cc); if (cc) return cc; if (std::this_thread::get_id() == m_main_thread) { return createClientCachedDirect(name, client); } // We're gonna ask the result to be put into here static ResultQueue<std::string, ClientCached*, u8, u8> result_queue; // Throw a request in m_get_clientcached_queue.add(name, 0, 0, &result_queue); try { while(true) { // Wait result for a second GetResult<std::string, ClientCached*, u8, u8> result = result_queue.pop_front(1000); if (result.key == name) { return result.item; } } } catch(ItemNotFoundException &e) { errorstream << "Waiting for clientcached " << name << " timed out." << std::endl; return &m_dummy_clientcached; } } // Get item inventory texture virtual video::ITexture* getInventoryTexture(const std::string &name, Client *client) const { ClientCached *cc = getClientCached(name, client); if(!cc) return NULL; return cc->inventory_texture; } // Get item wield mesh virtual ItemMesh* getWieldMesh(const std::string &name, Client *client) const { ClientCached *cc = getClientCached(name, client); if(!cc) return NULL; return &(cc->wield_mesh); } // Get item palette virtual Palette* getPalette(const std::string &name, Client *client) const { ClientCached *cc = getClientCached(name, client); if(!cc) return NULL; return cc->palette; } virtual video::SColor getItemstackColor(const ItemStack &stack, Client *client) const { // Look for direct color definition const std::string &colorstring = stack.metadata.getString("color", 0); video::SColor directcolor; if (!colorstring.empty() && parseColorString(colorstring, directcolor, true)) return directcolor; // See if there is a palette Palette *palette = getPalette(stack.name, client); const std::string &index = stack.metadata.getString("palette_index", 0); if (palette && !index.empty()) return (*palette)[mystoi(index, 0, 255)]; // Fallback color return get(stack.name).color; } #endif void clear() { for(std::map<std::string, ItemDefinition*>::const_iterator i = m_item_definitions.begin(); i != m_item_definitions.end(); ++i) { delete i->second; } m_item_definitions.clear(); m_aliases.clear(); // Add the four builtin items: // "" is the hand // "unknown" is returned whenever an undefined item // is accessed (is also the unknown node) // "air" is the air node // "ignore" is the ignore node ItemDefinition* hand_def = new ItemDefinition; hand_def->name = ""; hand_def->wield_image = "wieldhand.png"; hand_def->tool_capabilities = new ToolCapabilities; m_item_definitions.insert(std::make_pair("", hand_def)); ItemDefinition* unknown_def = new ItemDefinition; unknown_def->type = ITEM_NODE; unknown_def->name = "unknown"; m_item_definitions.insert(std::make_pair("unknown", unknown_def)); ItemDefinition* air_def = new ItemDefinition; air_def->type = ITEM_NODE; air_def->name = "air"; m_item_definitions.insert(std::make_pair("air", air_def)); ItemDefinition* ignore_def = new ItemDefinition; ignore_def->type = ITEM_NODE; ignore_def->name = "ignore"; m_item_definitions.insert(std::make_pair("ignore", ignore_def)); } virtual void registerItem(const ItemDefinition &def) { verbosestream<<"ItemDefManager: registering \""<<def.name<<"\""<<std::endl; // Ensure that the "" item (the hand) always has ToolCapabilities if (def.name.empty()) FATAL_ERROR_IF(!def.tool_capabilities, "Hand does not have ToolCapabilities"); if(m_item_definitions.count(def.name) == 0) m_item_definitions[def.name] = new ItemDefinition(def); else *(m_item_definitions[def.name]) = def; // Remove conflicting alias if it exists bool alias_removed = (m_aliases.erase(def.name) != 0); if(alias_removed) infostream<<"ItemDefManager: erased alias "<<def.name <<" because item was defined"<<std::endl; } virtual void unregisterItem(const std::string &name) { verbosestream<<"ItemDefManager: unregistering \""<<name<<"\""<<std::endl; delete m_item_definitions[name]; m_item_definitions.erase(name); } virtual void registerAlias(const std::string &name, const std::string &convert_to) { if (m_item_definitions.find(name) == m_item_definitions.end()) { verbosestream<<"ItemDefManager: setting alias "<<name <<" -> "<<convert_to<<std::endl; m_aliases[name] = convert_to; } } void serialize(std::ostream &os, u16 protocol_version) { writeU8(os, 0); // version u16 count = m_item_definitions.size(); writeU16(os, count); for (std::map<std::string, ItemDefinition *>::const_iterator it = m_item_definitions.begin(); it != m_item_definitions.end(); ++it) { ItemDefinition *def = it->second; // Serialize ItemDefinition and write wrapped in a string std::ostringstream tmp_os(std::ios::binary); def->serialize(tmp_os, protocol_version); os << serializeString(tmp_os.str()); } writeU16(os, m_aliases.size()); for (StringMap::const_iterator it = m_aliases.begin(); it != m_aliases.end(); ++it) { os << serializeString(it->first); os << serializeString(it->second); } } void deSerialize(std::istream &is) { // Clear everything clear(); // Deserialize int version = readU8(is); if(version != 0) throw SerializationError("unsupported ItemDefManager version"); u16 count = readU16(is); for(u16 i=0; i<count; i++) { // Deserialize a string and grab an ItemDefinition from it std::istringstream tmp_is(deSerializeString(is), std::ios::binary); ItemDefinition def; def.deSerialize(tmp_is); // Register registerItem(def); } u16 num_aliases = readU16(is); for(u16 i=0; i<num_aliases; i++) { std::string name = deSerializeString(is); std::string convert_to = deSerializeString(is); registerAlias(name, convert_to); } } void processQueue(IGameDef *gamedef) { #ifndef SERVER //NOTE this is only thread safe for ONE consumer thread! while(!m_get_clientcached_queue.empty()) { GetRequest<std::string, ClientCached*, u8, u8> request = m_get_clientcached_queue.pop(); m_get_clientcached_queue.pushResult(request, createClientCachedDirect(request.key, (Client *)gamedef)); } #endif } private: // Key is name std::map<std::string, ItemDefinition*> m_item_definitions; // Aliases StringMap m_aliases; #ifndef SERVER // The id of the thread that is allowed to use irrlicht directly std::thread::id m_main_thread; // A reference to this can be returned when nothing is found, to avoid NULLs mutable ClientCached m_dummy_clientcached; // Cached textures and meshes mutable MutexedMap<std::string, ClientCached*> m_clientcached; // Queued clientcached fetches (to be processed by the main thread) mutable RequestQueue<std::string, ClientCached*, u8, u8> m_get_clientcached_queue; #endif }; IWritableItemDefManager* createItemDefManager() { return new CItemDefManager(); }
pgimeno/minetest
src/itemdef.cpp
C++
mit
15,762
/* Minetest Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com> Copyright (C) 2013 Kahrl <kahrl@gmx.net> 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. */ #pragma once #include "irrlichttypes_extrabloated.h" #include <string> #include <iostream> #include <set> #include "itemgroup.h" #include "sound.h" class IGameDef; class Client; struct ToolCapabilities; #ifndef SERVER #include "client/tile.h" struct ItemMesh; struct ItemStack; #endif /* Base item definition */ enum ItemType { ITEM_NONE, ITEM_NODE, ITEM_CRAFT, ITEM_TOOL, }; struct ItemDefinition { /* Basic item properties */ ItemType type; std::string name; // "" = hand std::string description; // Shown in tooltip. /* Visual properties */ std::string inventory_image; // Optional for nodes, mandatory for tools/craftitems std::string inventory_overlay; // Overlay of inventory_image. std::string wield_image; // If empty, inventory_image or mesh (only nodes) is used std::string wield_overlay; // Overlay of wield_image. std::string palette_image; // If specified, the item will be colorized based on this video::SColor color; // The fallback color of the node. v3f wield_scale; /* Item stack and interaction properties */ u16 stack_max; bool usable; bool liquids_pointable; // May be NULL. If non-NULL, deleted by destructor ToolCapabilities *tool_capabilities; ItemGroupList groups; SimpleSoundSpec sound_place; SimpleSoundSpec sound_place_failed; f32 range; // Client shall immediately place this node when player places the item. // Server will update the precise end result a moment later. // "" = no prediction std::string node_placement_prediction; /* Some helpful methods */ ItemDefinition(); ItemDefinition(const ItemDefinition &def); ItemDefinition& operator=(const ItemDefinition &def); ~ItemDefinition(); void reset(); void serialize(std::ostream &os, u16 protocol_version) const; void deSerialize(std::istream &is); private: void resetInitial(); }; class IItemDefManager { public: IItemDefManager() = default; virtual ~IItemDefManager() = default; // Get item definition virtual const ItemDefinition& get(const std::string &name) const=0; // Get alias definition virtual const std::string &getAlias(const std::string &name) const=0; // Get set of all defined item names and aliases virtual void getAll(std::set<std::string> &result) const=0; // Check if item is known virtual bool isKnown(const std::string &name) const=0; #ifndef SERVER // Get item inventory texture virtual video::ITexture* getInventoryTexture(const std::string &name, Client *client) const=0; // Get item wield mesh virtual ItemMesh* getWieldMesh(const std::string &name, Client *client) const=0; // Get item palette virtual Palette* getPalette(const std::string &name, Client *client) const = 0; // Returns the base color of an item stack: the color of all // tiles that do not define their own color. virtual video::SColor getItemstackColor(const ItemStack &stack, Client *client) const = 0; #endif virtual void serialize(std::ostream &os, u16 protocol_version)=0; }; class IWritableItemDefManager : public IItemDefManager { public: IWritableItemDefManager() = default; virtual ~IWritableItemDefManager() = default; // Get item definition virtual const ItemDefinition& get(const std::string &name) const=0; // Get alias definition virtual const std::string &getAlias(const std::string &name) const=0; // Get set of all defined item names and aliases virtual void getAll(std::set<std::string> &result) const=0; // Check if item is known virtual bool isKnown(const std::string &name) const=0; #ifndef SERVER // Get item inventory texture virtual video::ITexture* getInventoryTexture(const std::string &name, Client *client) const=0; // Get item wield mesh virtual ItemMesh* getWieldMesh(const std::string &name, Client *client) const=0; #endif // Remove all registered item and node definitions and aliases // Then re-add the builtin item definitions virtual void clear()=0; // Register item definition virtual void registerItem(const ItemDefinition &def)=0; virtual void unregisterItem(const std::string &name)=0; // Set an alias so that items named <name> will load as <convert_to>. // Alias is not set if <name> has already been defined. // Alias will be removed if <name> is defined at a later point of time. virtual void registerAlias(const std::string &name, const std::string &convert_to)=0; virtual void serialize(std::ostream &os, u16 protocol_version)=0; virtual void deSerialize(std::istream &is)=0; // Do stuff asked by threads that can only be done in the main thread virtual void processQueue(IGameDef *gamedef)=0; }; IWritableItemDefManager* createItemDefManager();
pgimeno/minetest
src/itemdef.h
C++
mit
5,436
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> 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. */ #pragma once #include <string> #include <unordered_map> typedef std::unordered_map<std::string, int> ItemGroupList; static inline int itemgroup_get(const ItemGroupList &groups, const std::string &name) { ItemGroupList::const_iterator i = groups.find(name); if (i == groups.end()) return 0; return i->second; }
pgimeno/minetest
src/itemgroup.h
C++
mit
1,103
/* Minetest Copyright (C) 2017-8 rubenwardy <rw@rubenwardy.com> 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 "itemstackmetadata.h" #include "util/serialize.h" #include "util/strfnd.h" #define DESERIALIZE_START '\x01' #define DESERIALIZE_KV_DELIM '\x02' #define DESERIALIZE_PAIR_DELIM '\x03' #define DESERIALIZE_START_STR "\x01" #define DESERIALIZE_KV_DELIM_STR "\x02" #define DESERIALIZE_PAIR_DELIM_STR "\x03" #define TOOLCAP_KEY "tool_capabilities" void ItemStackMetadata::clear() { Metadata::clear(); updateToolCapabilities(); } bool ItemStackMetadata::setString(const std::string &name, const std::string &var) { bool result = Metadata::setString(name, var); if (name == TOOLCAP_KEY) updateToolCapabilities(); return result; } void ItemStackMetadata::serialize(std::ostream &os) const { std::ostringstream os2; os2 << DESERIALIZE_START; for (const auto &stringvar : m_stringvars) { if (!stringvar.first.empty() || !stringvar.second.empty()) os2 << stringvar.first << DESERIALIZE_KV_DELIM << stringvar.second << DESERIALIZE_PAIR_DELIM; } os << serializeJsonStringIfNeeded(os2.str()); } void ItemStackMetadata::deSerialize(std::istream &is) { std::string in = deSerializeJsonStringIfNeeded(is); m_stringvars.clear(); if (!in.empty()) { if (in[0] == DESERIALIZE_START) { Strfnd fnd(in); fnd.to(1); while (!fnd.at_end()) { std::string name = fnd.next(DESERIALIZE_KV_DELIM_STR); std::string var = fnd.next(DESERIALIZE_PAIR_DELIM_STR); m_stringvars[name] = var; } } else { // BACKWARDS COMPATIBILITY m_stringvars[""] = in; } } updateToolCapabilities(); } void ItemStackMetadata::updateToolCapabilities() { if (contains(TOOLCAP_KEY)) { toolcaps_overridden = true; toolcaps_override = ToolCapabilities(); std::istringstream is(getString(TOOLCAP_KEY)); toolcaps_override.deserializeJson(is); } else { toolcaps_overridden = false; } } void ItemStackMetadata::setToolCapabilities(const ToolCapabilities &caps) { std::ostringstream os; caps.serializeJson(os); setString(TOOLCAP_KEY, os.str()); } void ItemStackMetadata::clearToolCapabilities() { setString(TOOLCAP_KEY, ""); }
pgimeno/minetest
src/itemstackmetadata.cpp
C++
mit
2,831
/* Minetest Copyright (C) 2017-8 rubenwardy <rw@rubenwardy.com> 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. */ #pragma once #include "metadata.h" #include "tool.h" class Inventory; class IItemDefManager; class ItemStackMetadata : public Metadata { public: ItemStackMetadata() : toolcaps_overridden(false) {} // Overrides void clear() override; bool setString(const std::string &name, const std::string &var) override; void serialize(std::ostream &os) const; void deSerialize(std::istream &is); const ToolCapabilities &getToolCapabilities( const ToolCapabilities &default_caps) const { return toolcaps_overridden ? toolcaps_override : default_caps; } void setToolCapabilities(const ToolCapabilities &caps); void clearToolCapabilities(); private: void updateToolCapabilities(); bool toolcaps_overridden; ToolCapabilities toolcaps_override; };
pgimeno/minetest
src/itemstackmetadata.h
C++
mit
1,530
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> 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 "light.h" #include <cmath> #include "util/numeric.h" #include "settings.h" #ifndef SERVER static u8 light_LUT[LIGHT_SUN + 1]; // The const ref to light_LUT is what is actually used in the code const u8 *light_decode_table = light_LUT; struct LightingParams { float a, b, c; // polynomial coefficients float boost, center, sigma; // normal boost parameters float gamma; }; static LightingParams params; float decode_light_f(float x) { if (x >= 1.0f) // x is equal to 1.0f half the time return 1.0f; x = std::fmax(x, 0.0f); float brightness = ((params.a * x + params.b) * x + params.c) * x; brightness += params.boost * std::exp(-0.5f * sqr((x - params.center) / params.sigma)); if (brightness <= 0.0f) // may happen if parameters are insane return 0.0f; if (brightness >= 1.0f) return 1.0f; return powf(brightness, 1.0f / params.gamma); } // Initialize or update the light value tables using the specified gamma void set_light_table(float gamma) { // Lighting curve derivatives const float alpha = g_settings->getFloat("lighting_alpha"); const float beta = g_settings->getFloat("lighting_beta"); // Lighting curve coefficients params.a = alpha + beta - 2.0f; params.b = 3.0f - 2.0f * alpha - beta; params.c = alpha; // Mid boost params.boost = g_settings->getFloat("lighting_boost"); params.center = g_settings->getFloat("lighting_boost_center"); params.sigma = g_settings->getFloat("lighting_boost_spread"); // Gamma correction params.gamma = rangelim(gamma, 0.5f, 3.0f); // Boundary values should be fixed light_LUT[0] = 0; light_LUT[LIGHT_SUN] = 255; for (size_t i = 1; i < LIGHT_SUN; i++) { float brightness = decode_light_f((float)i / LIGHT_SUN); // Strictly speaking, rangelim is not necessary here—if the implementation // is conforming. But we don’t want problems in any case. light_LUT[i] = rangelim((s32)(255.0f * brightness), 0, 255); // Ensure light brightens with each level if (i > 1 && light_LUT[i] <= light_LUT[i - 1]) light_LUT[i] = light_LUT[i - 1] + 1; } } #endif
pgimeno/minetest
src/light.cpp
C++
mit
2,835
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> 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. */ #pragma once #include <cassert> #include "irrlichttypes.h" /* Lower level lighting stuff */ // This directly sets the range of light. // Actually this is not the real maximum, and this is not the brightest, the // brightest is LIGHT_SUN. // If changed, this constant as defined in builtin/game/constants.lua must // also be changed. #define LIGHT_MAX 14 // Light is stored as 4 bits, thus 15 is the maximum. // This brightness is reserved for sunlight #define LIGHT_SUN 15 #ifndef SERVER /** * \internal * * \warning DO NOT USE this directly; it is here simply so that decode_light() * can be inlined. * * Array size is #LIGHTMAX+1 * * The array is a lookup table to convert the internal representation of light * (brightness) to the display brightness. * */ extern const u8 *light_decode_table; // 0 <= light <= LIGHT_SUN // 0 <= return value <= 255 inline u8 decode_light(u8 light) { // assert(light <= LIGHT_SUN); if (light > LIGHT_SUN) light = LIGHT_SUN; return light_decode_table[light]; } // 0.0 <= light <= 1.0 // 0.0 <= return value <= 1.0 float decode_light_f(float light_f); void set_light_table(float gamma); #endif // ifndef SERVER // 0 <= daylight_factor <= 1000 // 0 <= lightday, lightnight <= LIGHT_SUN // 0 <= return value <= LIGHT_SUN inline u8 blend_light(u32 daylight_factor, u8 lightday, u8 lightnight) { u32 c = 1000; u32 l = ((daylight_factor * lightday + (c - daylight_factor) * lightnight)) / c; if (l > LIGHT_SUN) l = LIGHT_SUN; return l; }
pgimeno/minetest
src/light.h
C++
mit
2,283
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> 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 "log.h" #include "threading/mutex_auto_lock.h" #include "debug.h" #include "gettime.h" #include "porting.h" #include "config.h" #include "exceptions.h" #include "util/numeric.h" #include "log.h" #include <sstream> #include <iostream> #include <algorithm> #include <cerrno> #include <cstring> const int BUFFER_LENGTH = 256; class StringBuffer : public std::streambuf { public: StringBuffer() { buffer_index = 0; } int overflow(int c); virtual void flush(const std::string &buf) = 0; std::streamsize xsputn(const char *s, std::streamsize n); void push_back(char c); private: char buffer[BUFFER_LENGTH]; int buffer_index; }; class LogBuffer : public StringBuffer { public: LogBuffer(Logger &logger, LogLevel lev) : logger(logger), level(lev) {} void flush(const std::string &buffer); private: Logger &logger; LogLevel level; }; class RawLogBuffer : public StringBuffer { public: void flush(const std::string &buffer); }; //// //// Globals //// Logger g_logger; StreamLogOutput stdout_output(std::cout); StreamLogOutput stderr_output(std::cerr); std::ostream null_stream(NULL); RawLogBuffer raw_buf; LogBuffer none_buf(g_logger, LL_NONE); LogBuffer error_buf(g_logger, LL_ERROR); LogBuffer warning_buf(g_logger, LL_WARNING); LogBuffer action_buf(g_logger, LL_ACTION); LogBuffer info_buf(g_logger, LL_INFO); LogBuffer verbose_buf(g_logger, LL_VERBOSE); // Connection std::ostream *dout_con_ptr = &null_stream; std::ostream *derr_con_ptr = &verbosestream; // Server std::ostream *dout_server_ptr = &infostream; std::ostream *derr_server_ptr = &errorstream; #ifndef SERVER // Client std::ostream *dout_client_ptr = &infostream; std::ostream *derr_client_ptr = &errorstream; #endif std::ostream rawstream(&raw_buf); std::ostream dstream(&none_buf); std::ostream errorstream(&error_buf); std::ostream warningstream(&warning_buf); std::ostream actionstream(&action_buf); std::ostream infostream(&info_buf); std::ostream verbosestream(&verbose_buf); // Android #ifdef __ANDROID__ static unsigned int g_level_to_android[] = { ANDROID_LOG_INFO, // LL_NONE //ANDROID_LOG_FATAL, ANDROID_LOG_ERROR, // LL_ERROR ANDROID_LOG_WARN, // LL_WARNING ANDROID_LOG_WARN, // LL_ACTION //ANDROID_LOG_INFO, ANDROID_LOG_DEBUG, // LL_INFO ANDROID_LOG_VERBOSE, // LL_VERBOSE }; class AndroidSystemLogOutput : public ICombinedLogOutput { public: AndroidSystemLogOutput() { g_logger.addOutput(this); } ~AndroidSystemLogOutput() { g_logger.removeOutput(this); } void logRaw(LogLevel lev, const std::string &line) { STATIC_ASSERT(ARRLEN(g_level_to_android) == LL_MAX, mismatch_between_android_and_internal_loglevels); __android_log_print(g_level_to_android[lev], PROJECT_NAME_C, "%s", line.c_str()); } }; AndroidSystemLogOutput g_android_log_output; #endif /////////////////////////////////////////////////////////////////////////////// //// //// Logger //// LogLevel Logger::stringToLevel(const std::string &name) { if (name == "none") return LL_NONE; else if (name == "error") return LL_ERROR; else if (name == "warning") return LL_WARNING; else if (name == "action") return LL_ACTION; else if (name == "info") return LL_INFO; else if (name == "verbose") return LL_VERBOSE; else return LL_MAX; } void Logger::addOutput(ILogOutput *out) { addOutputMaxLevel(out, (LogLevel)(LL_MAX - 1)); } void Logger::addOutput(ILogOutput *out, LogLevel lev) { m_outputs[lev].push_back(out); } void Logger::addOutputMasked(ILogOutput *out, LogLevelMask mask) { for (size_t i = 0; i < LL_MAX; i++) { if (mask & LOGLEVEL_TO_MASKLEVEL(i)) m_outputs[i].push_back(out); } } void Logger::addOutputMaxLevel(ILogOutput *out, LogLevel lev) { assert(lev < LL_MAX); for (size_t i = 0; i <= lev; i++) m_outputs[i].push_back(out); } LogLevelMask Logger::removeOutput(ILogOutput *out) { LogLevelMask ret_mask = 0; for (size_t i = 0; i < LL_MAX; i++) { std::vector<ILogOutput *>::iterator it; it = std::find(m_outputs[i].begin(), m_outputs[i].end(), out); if (it != m_outputs[i].end()) { ret_mask |= LOGLEVEL_TO_MASKLEVEL(i); m_outputs[i].erase(it); } } return ret_mask; } void Logger::setLevelSilenced(LogLevel lev, bool silenced) { m_silenced_levels[lev] = silenced; } void Logger::registerThread(const std::string &name) { std::thread::id id = std::this_thread::get_id(); MutexAutoLock lock(m_mutex); m_thread_names[id] = name; } void Logger::deregisterThread() { std::thread::id id = std::this_thread::get_id(); MutexAutoLock lock(m_mutex); m_thread_names.erase(id); } const std::string Logger::getLevelLabel(LogLevel lev) { static const std::string names[] = { "", "ERROR", "WARNING", "ACTION", "INFO", "VERBOSE", }; assert(lev < LL_MAX && lev >= 0); STATIC_ASSERT(ARRLEN(names) == LL_MAX, mismatch_between_loglevel_names_and_enum); return names[lev]; } LogColor Logger::color_mode = LOG_COLOR_AUTO; const std::string Logger::getThreadName() { std::map<std::thread::id, std::string>::const_iterator it; std::thread::id id = std::this_thread::get_id(); it = m_thread_names.find(id); if (it != m_thread_names.end()) return it->second; std::ostringstream os; os << "#0x" << std::hex << id; return os.str(); } void Logger::log(LogLevel lev, const std::string &text) { if (m_silenced_levels[lev]) return; const std::string thread_name = getThreadName(); const std::string label = getLevelLabel(lev); const std::string timestamp = getTimestamp(); std::ostringstream os(std::ios_base::binary); os << timestamp << ": " << label << "[" << thread_name << "]: " << text; logToOutputs(lev, os.str(), timestamp, thread_name, text); } void Logger::logRaw(LogLevel lev, const std::string &text) { if (m_silenced_levels[lev]) return; logToOutputsRaw(lev, text); } void Logger::logToOutputsRaw(LogLevel lev, const std::string &line) { MutexAutoLock lock(m_mutex); for (size_t i = 0; i != m_outputs[lev].size(); i++) m_outputs[lev][i]->logRaw(lev, line); } void Logger::logToOutputs(LogLevel lev, const std::string &combined, const std::string &time, const std::string &thread_name, const std::string &payload_text) { MutexAutoLock lock(m_mutex); for (size_t i = 0; i != m_outputs[lev].size(); i++) m_outputs[lev][i]->log(lev, combined, time, thread_name, payload_text); } //// //// *LogOutput methods //// void FileLogOutput::open(const std::string &filename) { m_stream.open(filename.c_str(), std::ios::app | std::ios::ate); if (!m_stream.good()) throw FileNotGoodException("Failed to open log file " + filename + ": " + strerror(errno)); m_stream << "\n\n" "-------------" << std::endl << " Separator" << std::endl << "-------------\n" << std::endl; } //// //// *Buffer methods //// int StringBuffer::overflow(int c) { push_back(c); return c; } std::streamsize StringBuffer::xsputn(const char *s, std::streamsize n) { for (int i = 0; i < n; ++i) push_back(s[i]); return n; } void StringBuffer::push_back(char c) { if (c == '\n' || c == '\r') { if (buffer_index) flush(std::string(buffer, buffer_index)); buffer_index = 0; } else { buffer[buffer_index++] = c; if (buffer_index >= BUFFER_LENGTH) { flush(std::string(buffer, buffer_index)); buffer_index = 0; } } } void LogBuffer::flush(const std::string &buffer) { logger.log(level, buffer); } void RawLogBuffer::flush(const std::string &buffer) { g_logger.logRaw(LL_NONE, buffer); }
pgimeno/minetest
src/log.cpp
C++
mit
8,258
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> 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. */ #pragma once #include <map> #include <queue> #include <string> #include <fstream> #include <thread> #include <mutex> #if !defined(_WIN32) // POSIX #include <unistd.h> #endif #include "irrlichttypes.h" class ILogOutput; enum LogLevel { LL_NONE, // Special level that is always printed LL_ERROR, LL_WARNING, LL_ACTION, // In-game actions LL_INFO, LL_VERBOSE, LL_MAX, }; enum LogColor { LOG_COLOR_NEVER, LOG_COLOR_ALWAYS, LOG_COLOR_AUTO, }; typedef u8 LogLevelMask; #define LOGLEVEL_TO_MASKLEVEL(x) (1 << x) class Logger { public: void addOutput(ILogOutput *out); void addOutput(ILogOutput *out, LogLevel lev); void addOutputMasked(ILogOutput *out, LogLevelMask mask); void addOutputMaxLevel(ILogOutput *out, LogLevel lev); LogLevelMask removeOutput(ILogOutput *out); void setLevelSilenced(LogLevel lev, bool silenced); void registerThread(const std::string &name); void deregisterThread(); void log(LogLevel lev, const std::string &text); // Logs without a prefix void logRaw(LogLevel lev, const std::string &text); void setTraceEnabled(bool enable) { m_trace_enabled = enable; } bool getTraceEnabled() { return m_trace_enabled; } static LogLevel stringToLevel(const std::string &name); static const std::string getLevelLabel(LogLevel lev); static LogColor color_mode; private: void logToOutputsRaw(LogLevel, const std::string &line); void logToOutputs(LogLevel, const std::string &combined, const std::string &time, const std::string &thread_name, const std::string &payload_text); const std::string getThreadName(); std::vector<ILogOutput *> m_outputs[LL_MAX]; // Should implement atomic loads and stores (even though it's only // written to when one thread has access currently). // Works on all known architectures (x86, ARM, MIPS). volatile bool m_silenced_levels[LL_MAX]; std::map<std::thread::id, std::string> m_thread_names; mutable std::mutex m_mutex; bool m_trace_enabled; }; class ILogOutput { public: virtual void logRaw(LogLevel, const std::string &line) = 0; virtual void log(LogLevel, const std::string &combined, const std::string &time, const std::string &thread_name, const std::string &payload_text) = 0; }; class ICombinedLogOutput : public ILogOutput { public: void log(LogLevel lev, const std::string &combined, const std::string &time, const std::string &thread_name, const std::string &payload_text) { logRaw(lev, combined); } }; class StreamLogOutput : public ICombinedLogOutput { public: StreamLogOutput(std::ostream &stream) : m_stream(stream) { #if !defined(_WIN32) is_tty = isatty(fileno(stdout)); #else is_tty = false; #endif } void logRaw(LogLevel lev, const std::string &line) { bool colored_message = (Logger::color_mode == LOG_COLOR_ALWAYS) || (Logger::color_mode == LOG_COLOR_AUTO && is_tty); if (colored_message) switch (lev) { case LL_ERROR: // error is red m_stream << "\033[91m"; break; case LL_WARNING: // warning is yellow m_stream << "\033[93m"; break; case LL_INFO: // info is a bit dark m_stream << "\033[37m"; break; case LL_VERBOSE: // verbose is darker than info m_stream << "\033[2m"; break; default: // action is white colored_message = false; } m_stream << line << std::endl; if (colored_message) // reset to white color m_stream << "\033[0m"; } private: std::ostream &m_stream; bool is_tty; }; class FileLogOutput : public ICombinedLogOutput { public: void open(const std::string &filename); void logRaw(LogLevel lev, const std::string &line) { m_stream << line << std::endl; } private: std::ofstream m_stream; }; class LogOutputBuffer : public ICombinedLogOutput { public: LogOutputBuffer(Logger &logger, LogLevel lev) : m_logger(logger) { m_logger.addOutput(this, lev); } ~LogOutputBuffer() { m_logger.removeOutput(this); } void logRaw(LogLevel lev, const std::string &line) { m_buffer.push(line); } bool empty() { return m_buffer.empty(); } std::string get() { if (empty()) return ""; std::string s = m_buffer.front(); m_buffer.pop(); return s; } private: std::queue<std::string> m_buffer; Logger &m_logger; }; extern StreamLogOutput stdout_output; extern StreamLogOutput stderr_output; extern std::ostream null_stream; extern std::ostream *dout_con_ptr; extern std::ostream *derr_con_ptr; extern std::ostream *dout_server_ptr; extern std::ostream *derr_server_ptr; #ifndef SERVER extern std::ostream *dout_client_ptr; extern std::ostream *derr_client_ptr; #endif extern Logger g_logger; // Writes directly to all LL_NONE log outputs for g_logger with no prefix. extern std::ostream rawstream; extern std::ostream errorstream; extern std::ostream warningstream; extern std::ostream actionstream; extern std::ostream infostream; extern std::ostream verbosestream; extern std::ostream dstream; #define TRACEDO(x) do { \ if (g_logger.getTraceEnabled()) { \ x; \ } \ } while (0) #define TRACESTREAM(x) TRACEDO(verbosestream x) #define dout_con (*dout_con_ptr) #define derr_con (*derr_con_ptr) #define dout_server (*dout_server_ptr) #ifndef SERVER #define dout_client (*dout_client_ptr) #endif
pgimeno/minetest
src/log.h
C++
mit
6,058
/* Minetest Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com> 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 "irrlicht.h" // createDevice #include "irrlichttypes_extrabloated.h" #include "chat_interface.h" #include "debug.h" #include "unittest/test.h" #include "server.h" #include "filesys.h" #include "version.h" #include "client/game.h" #include "defaultsettings.h" #include "gettext.h" #include "log.h" #include "quicktune.h" #include "httpfetch.h" #include "gameparams.h" #include "database/database.h" #include "config.h" #include "player.h" #include "porting.h" #include "network/socket.h" #if USE_CURSES #include "terminal_chat_console.h" #endif #ifndef SERVER #include "gui/guiMainMenu.h" #include "client/clientlauncher.h" #include "gui/guiEngine.h" #include "gui/mainmenumanager.h" #endif #ifdef HAVE_TOUCHSCREENGUI #include "gui/touchscreengui.h" #endif #if !defined(SERVER) && \ (IRRLICHT_VERSION_MAJOR == 1) && \ (IRRLICHT_VERSION_MINOR == 8) && \ (IRRLICHT_VERSION_REVISION == 2) #error "Irrlicht 1.8.2 is known to be broken - please update Irrlicht to version >= 1.8.3" #endif #define DEBUGFILE "debug.txt" #define DEFAULT_SERVER_PORT 30000 typedef std::map<std::string, ValueSpec> OptionList; /********************************************************************** * Private functions **********************************************************************/ static bool get_cmdline_opts(int argc, char *argv[], Settings *cmd_args); static void set_allowed_options(OptionList *allowed_options); static void print_help(const OptionList &allowed_options); static void print_allowed_options(const OptionList &allowed_options); static void print_version(); static void print_worldspecs(const std::vector<WorldSpec> &worldspecs, std::ostream &os, bool print_name = true, bool print_path = true); static void print_modified_quicktune_values(); static void list_game_ids(); static void list_worlds(bool print_name, bool print_path); static void setup_log_params(const Settings &cmd_args); static bool create_userdata_path(); static bool init_common(const Settings &cmd_args, int argc, char *argv[]); static void startup_message(); static bool read_config_file(const Settings &cmd_args); static void init_log_streams(const Settings &cmd_args); static bool game_configure(GameParams *game_params, const Settings &cmd_args); static void game_configure_port(GameParams *game_params, const Settings &cmd_args); static bool game_configure_world(GameParams *game_params, const Settings &cmd_args); static bool get_world_from_cmdline(GameParams *game_params, const Settings &cmd_args); static bool get_world_from_config(GameParams *game_params, const Settings &cmd_args); static bool auto_select_world(GameParams *game_params); static std::string get_clean_world_path(const std::string &path); static bool game_configure_subgame(GameParams *game_params, const Settings &cmd_args); static bool get_game_from_cmdline(GameParams *game_params, const Settings &cmd_args); static bool determine_subgame(GameParams *game_params); static bool run_dedicated_server(const GameParams &game_params, const Settings &cmd_args); static bool migrate_map_database(const GameParams &game_params, const Settings &cmd_args); /**********************************************************************/ FileLogOutput file_log_output; static OptionList allowed_options; int main(int argc, char *argv[]) { int retval; debug_set_exception_handler(); g_logger.registerThread("Main"); g_logger.addOutputMaxLevel(&stderr_output, LL_ACTION); Settings cmd_args; bool cmd_args_ok = get_cmdline_opts(argc, argv, &cmd_args); if (!cmd_args_ok || cmd_args.getFlag("help") || cmd_args.exists("nonopt1")) { porting::attachOrCreateConsole(); print_help(allowed_options); return cmd_args_ok ? 0 : 1; } if (cmd_args.getFlag("console")) porting::attachOrCreateConsole(); if (cmd_args.getFlag("version")) { porting::attachOrCreateConsole(); print_version(); return 0; } setup_log_params(cmd_args); porting::signal_handler_init(); #ifdef __ANDROID__ porting::initAndroid(); porting::initializePathsAndroid(); #else porting::initializePaths(); #endif if (!create_userdata_path()) { errorstream << "Cannot create user data directory" << std::endl; return 1; } // Debug handler BEGIN_DEBUG_EXCEPTION_HANDLER // List gameids if requested if (cmd_args.exists("gameid") && cmd_args.get("gameid") == "list") { list_game_ids(); return 0; } // List worlds, world names, and world paths if requested if (cmd_args.exists("worldlist")) { if (cmd_args.get("worldlist") == "name") { list_worlds(true, false); } else if (cmd_args.get("worldlist") == "path") { list_worlds(false, true); } else { list_worlds(true, true); } return 0; } if (!init_common(cmd_args, argc, argv)) return 1; if (g_settings->getBool("enable_console")) porting::attachOrCreateConsole(); #ifndef __ANDROID__ // Run unit tests if (cmd_args.getFlag("run-unittests")) { return run_tests(); } #endif GameParams game_params; #ifdef SERVER porting::attachOrCreateConsole(); game_params.is_dedicated_server = true; #else const bool isServer = cmd_args.getFlag("server"); if (isServer) porting::attachOrCreateConsole(); game_params.is_dedicated_server = isServer; #endif if (!game_configure(&game_params, cmd_args)) return 1; sanity_check(!game_params.world_path.empty()); infostream << "Using commanded world path [" << game_params.world_path << "]" << std::endl; if (game_params.is_dedicated_server) return run_dedicated_server(game_params, cmd_args) ? 0 : 1; #ifndef SERVER ClientLauncher launcher; retval = launcher.run(game_params, cmd_args) ? 0 : 1; #else retval = 0; #endif // Update configuration file if (!g_settings_path.empty()) g_settings->updateConfigFile(g_settings_path.c_str()); print_modified_quicktune_values(); // Stop httpfetch thread (if started) httpfetch_cleanup(); END_DEBUG_EXCEPTION_HANDLER return retval; } /***************************************************************************** * Startup / Init *****************************************************************************/ static bool get_cmdline_opts(int argc, char *argv[], Settings *cmd_args) { set_allowed_options(&allowed_options); return cmd_args->parseCommandLine(argc, argv, allowed_options); } static void set_allowed_options(OptionList *allowed_options) { allowed_options->clear(); allowed_options->insert(std::make_pair("help", ValueSpec(VALUETYPE_FLAG, _("Show allowed options")))); allowed_options->insert(std::make_pair("version", ValueSpec(VALUETYPE_FLAG, _("Show version information")))); allowed_options->insert(std::make_pair("config", ValueSpec(VALUETYPE_STRING, _("Load configuration from specified file")))); allowed_options->insert(std::make_pair("port", ValueSpec(VALUETYPE_STRING, _("Set network port (UDP)")))); allowed_options->insert(std::make_pair("run-unittests", ValueSpec(VALUETYPE_FLAG, _("Run the unit tests and exit")))); allowed_options->insert(std::make_pair("map-dir", ValueSpec(VALUETYPE_STRING, _("Same as --world (deprecated)")))); allowed_options->insert(std::make_pair("world", ValueSpec(VALUETYPE_STRING, _("Set world path (implies local game)")))); allowed_options->insert(std::make_pair("worldname", ValueSpec(VALUETYPE_STRING, _("Set world by name (implies local game)")))); allowed_options->insert(std::make_pair("worldlist", ValueSpec(VALUETYPE_STRING, _("Get list of worlds (implies local game) ('path' lists paths, " "'name' lists names, 'both' lists both)")))); allowed_options->insert(std::make_pair("quiet", ValueSpec(VALUETYPE_FLAG, _("Print to console errors only")))); #if !defined(_WIN32) allowed_options->insert(std::make_pair("color", ValueSpec(VALUETYPE_STRING, _("Coloured logs ('always', 'never' or 'auto'), defaults to 'auto'" )))); #else allowed_options->insert(std::make_pair("color", ValueSpec(VALUETYPE_STRING, _("Coloured logs ('always' or 'never'), defaults to 'never'" )))); #endif allowed_options->insert(std::make_pair("info", ValueSpec(VALUETYPE_FLAG, _("Print more information to console")))); allowed_options->insert(std::make_pair("verbose", ValueSpec(VALUETYPE_FLAG, _("Print even more information to console")))); allowed_options->insert(std::make_pair("trace", ValueSpec(VALUETYPE_FLAG, _("Print enormous amounts of information to log and console")))); allowed_options->insert(std::make_pair("logfile", ValueSpec(VALUETYPE_STRING, _("Set logfile path ('' = no logging)")))); allowed_options->insert(std::make_pair("gameid", ValueSpec(VALUETYPE_STRING, _("Set gameid (\"--gameid list\" prints available ones)")))); allowed_options->insert(std::make_pair("migrate", ValueSpec(VALUETYPE_STRING, _("Migrate from current map backend to another (Only works when using minetestserver or with --server)")))); allowed_options->insert(std::make_pair("migrate-players", ValueSpec(VALUETYPE_STRING, _("Migrate from current players backend to another (Only works when using minetestserver or with --server)")))); allowed_options->insert(std::make_pair("migrate-auth", ValueSpec(VALUETYPE_STRING, _("Migrate from current auth backend to another (Only works when using minetestserver or with --server)")))); allowed_options->insert(std::make_pair("terminal", ValueSpec(VALUETYPE_FLAG, _("Feature an interactive terminal (Only works when using minetestserver or with --server)")))); #ifndef SERVER allowed_options->insert(std::make_pair("videomodes", ValueSpec(VALUETYPE_FLAG, _("Show available video modes")))); allowed_options->insert(std::make_pair("speedtests", ValueSpec(VALUETYPE_FLAG, _("Run speed tests")))); allowed_options->insert(std::make_pair("address", ValueSpec(VALUETYPE_STRING, _("Address to connect to. ('' = local game)")))); allowed_options->insert(std::make_pair("random-input", ValueSpec(VALUETYPE_FLAG, _("Enable random user input, for testing")))); allowed_options->insert(std::make_pair("server", ValueSpec(VALUETYPE_FLAG, _("Run dedicated server")))); allowed_options->insert(std::make_pair("name", ValueSpec(VALUETYPE_STRING, _("Set player name")))); allowed_options->insert(std::make_pair("password", ValueSpec(VALUETYPE_STRING, _("Set password")))); allowed_options->insert(std::make_pair("password-file", ValueSpec(VALUETYPE_STRING, _("Set password from contents of file")))); allowed_options->insert(std::make_pair("go", ValueSpec(VALUETYPE_FLAG, _("Disable main menu")))); allowed_options->insert(std::make_pair("console", ValueSpec(VALUETYPE_FLAG, _("Starts with the console (Windows only)")))); #endif } static void print_help(const OptionList &allowed_options) { std::cout << _("Allowed options:") << std::endl; print_allowed_options(allowed_options); } static void print_allowed_options(const OptionList &allowed_options) { for (const auto &allowed_option : allowed_options) { std::ostringstream os1(std::ios::binary); os1 << " --" << allowed_option.first; if (allowed_option.second.type != VALUETYPE_FLAG) os1 << _(" <value>"); std::cout << padStringRight(os1.str(), 30); if (allowed_option.second.help) std::cout << allowed_option.second.help; std::cout << std::endl; } } static void print_version() { std::cout << PROJECT_NAME_C " " << g_version_hash << " (" << porting::getPlatformName() << ")" << std::endl; #ifndef SERVER std::cout << "Using Irrlicht " IRRLICHT_SDK_VERSION << std::endl; #endif std::cout << g_build_info << std::endl; } static void list_game_ids() { std::set<std::string> gameids = getAvailableGameIds(); for (const std::string &gameid : gameids) std::cout << gameid <<std::endl; } static void list_worlds(bool print_name, bool print_path) { std::cout << _("Available worlds:") << std::endl; std::vector<WorldSpec> worldspecs = getAvailableWorlds(); print_worldspecs(worldspecs, std::cout, print_name, print_path); } static void print_worldspecs(const std::vector<WorldSpec> &worldspecs, std::ostream &os, bool print_name, bool print_path) { for (const WorldSpec &worldspec : worldspecs) { std::string name = worldspec.name; std::string path = worldspec.path; if (print_name && print_path) { os << "\t" << name << "\t\t" << path << std::endl; } else if (print_name) { os << "\t" << name << std::endl; } else if (print_path) { os << "\t" << path << std::endl; } } } static void print_modified_quicktune_values() { bool header_printed = false; std::vector<std::string> names = getQuicktuneNames(); for (const std::string &name : names) { QuicktuneValue val = getQuicktuneValue(name); if (!val.modified) continue; if (!header_printed) { dstream << "Modified quicktune values:" << std::endl; header_printed = true; } dstream << name << " = " << val.getString() << std::endl; } } static void setup_log_params(const Settings &cmd_args) { // Quiet mode, print errors only if (cmd_args.getFlag("quiet")) { g_logger.removeOutput(&stderr_output); g_logger.addOutputMaxLevel(&stderr_output, LL_ERROR); } // Coloured log messages (see log.h) std::string color_mode; if (cmd_args.exists("color")) { color_mode = cmd_args.get("color"); #if !defined(_WIN32) } else { char *color_mode_env = getenv("MT_LOGCOLOR"); if (color_mode_env) color_mode = color_mode_env; #endif } if (color_mode != "") { if (color_mode == "auto") Logger::color_mode = LOG_COLOR_AUTO; else if (color_mode == "always") Logger::color_mode = LOG_COLOR_ALWAYS; else if (color_mode == "never") Logger::color_mode = LOG_COLOR_NEVER; else errorstream << "Invalid color mode: " << color_mode << std::endl; } // If trace is enabled, enable logging of certain things if (cmd_args.getFlag("trace")) { dstream << _("Enabling trace level debug output") << std::endl; g_logger.setTraceEnabled(true); dout_con_ptr = &verbosestream; // This is somewhat old socket_enable_debug_output = true; // Sockets doesn't use log.h } // In certain cases, output info level on stderr if (cmd_args.getFlag("info") || cmd_args.getFlag("verbose") || cmd_args.getFlag("trace") || cmd_args.getFlag("speedtests")) g_logger.addOutput(&stderr_output, LL_INFO); // In certain cases, output verbose level on stderr if (cmd_args.getFlag("verbose") || cmd_args.getFlag("trace")) g_logger.addOutput(&stderr_output, LL_VERBOSE); } static bool create_userdata_path() { bool success; #ifdef __ANDROID__ if (!fs::PathExists(porting::path_user)) { success = fs::CreateDir(porting::path_user); } else { success = true; } porting::copyAssets(); #else // Create user data directory success = fs::CreateDir(porting::path_user); #endif return success; } static bool init_common(const Settings &cmd_args, int argc, char *argv[]) { startup_message(); set_default_settings(g_settings); // Initialize sockets sockets_init(); atexit(sockets_cleanup); if (!read_config_file(cmd_args)) return false; init_log_streams(cmd_args); // Initialize random seed srand(time(0)); mysrand(time(0)); // Initialize HTTP fetcher httpfetch_init(g_settings->getS32("curl_parallel_limit")); init_gettext(porting::path_locale.c_str(), g_settings->get("language"), argc, argv); return true; } static void startup_message() { infostream << PROJECT_NAME << " " << _("with") << " SER_FMT_VER_HIGHEST_READ=" << (int)SER_FMT_VER_HIGHEST_READ << ", " << g_build_info << std::endl; } static bool read_config_file(const Settings &cmd_args) { // Path of configuration file in use sanity_check(g_settings_path == ""); // Sanity check if (cmd_args.exists("config")) { bool r = g_settings->readConfigFile(cmd_args.get("config").c_str()); if (!r) { errorstream << "Could not read configuration from \"" << cmd_args.get("config") << "\"" << std::endl; return false; } g_settings_path = cmd_args.get("config"); } else { std::vector<std::string> filenames; filenames.push_back(porting::path_user + DIR_DELIM + "minetest.conf"); // Legacy configuration file location filenames.push_back(porting::path_user + DIR_DELIM + ".." + DIR_DELIM + "minetest.conf"); #if RUN_IN_PLACE // Try also from a lower level (to aid having the same configuration // for many RUN_IN_PLACE installs) filenames.push_back(porting::path_user + DIR_DELIM + ".." + DIR_DELIM + ".." + DIR_DELIM + "minetest.conf"); #endif for (const std::string &filename : filenames) { bool r = g_settings->readConfigFile(filename.c_str()); if (r) { g_settings_path = filename; break; } } // If no path found, use the first one (menu creates the file) if (g_settings_path.empty()) g_settings_path = filenames[0]; } return true; } static void init_log_streams(const Settings &cmd_args) { std::string log_filename = porting::path_user + DIR_DELIM + DEBUGFILE; if (cmd_args.exists("logfile")) log_filename = cmd_args.get("logfile"); g_logger.removeOutput(&file_log_output); std::string conf_loglev = g_settings->get("debug_log_level"); // Old integer format if (std::isdigit(conf_loglev[0])) { warningstream << "Deprecated use of debug_log_level with an " "integer value; please update your configuration." << std::endl; static const char *lev_name[] = {"", "error", "action", "info", "verbose"}; int lev_i = atoi(conf_loglev.c_str()); if (lev_i < 0 || lev_i >= (int)ARRLEN(lev_name)) { warningstream << "Supplied invalid debug_log_level!" " Assuming action level." << std::endl; lev_i = 2; } conf_loglev = lev_name[lev_i]; } if (log_filename.empty() || conf_loglev.empty()) // No logging return; LogLevel log_level = Logger::stringToLevel(conf_loglev); if (log_level == LL_MAX) { warningstream << "Supplied unrecognized debug_log_level; " "using maximum." << std::endl; } verbosestream << "log_filename = " << log_filename << std::endl; file_log_output.open(log_filename); g_logger.addOutputMaxLevel(&file_log_output, log_level); } static bool game_configure(GameParams *game_params, const Settings &cmd_args) { game_configure_port(game_params, cmd_args); if (!game_configure_world(game_params, cmd_args)) { errorstream << "No world path specified or found." << std::endl; return false; } game_configure_subgame(game_params, cmd_args); return true; } static void game_configure_port(GameParams *game_params, const Settings &cmd_args) { if (cmd_args.exists("port")) game_params->socket_port = cmd_args.getU16("port"); else game_params->socket_port = g_settings->getU16("port"); if (game_params->socket_port == 0) game_params->socket_port = DEFAULT_SERVER_PORT; } static bool game_configure_world(GameParams *game_params, const Settings &cmd_args) { if (get_world_from_cmdline(game_params, cmd_args)) return true; if (get_world_from_config(game_params, cmd_args)) return true; return auto_select_world(game_params); } static bool get_world_from_cmdline(GameParams *game_params, const Settings &cmd_args) { std::string commanded_world; // World name std::string commanded_worldname; if (cmd_args.exists("worldname")) commanded_worldname = cmd_args.get("worldname"); // If a world name was specified, convert it to a path if (!commanded_worldname.empty()) { // Get information about available worlds std::vector<WorldSpec> worldspecs = getAvailableWorlds(); bool found = false; for (const WorldSpec &worldspec : worldspecs) { std::string name = worldspec.name; if (name == commanded_worldname) { dstream << _("Using world specified by --worldname on the " "command line") << std::endl; commanded_world = worldspec.path; found = true; break; } } if (!found) { dstream << _("World") << " '" << commanded_worldname << _("' not available. Available worlds:") << std::endl; print_worldspecs(worldspecs, dstream); return false; } game_params->world_path = get_clean_world_path(commanded_world); return !commanded_world.empty(); } if (cmd_args.exists("world")) commanded_world = cmd_args.get("world"); else if (cmd_args.exists("map-dir")) commanded_world = cmd_args.get("map-dir"); else if (cmd_args.exists("nonopt0")) // First nameless argument commanded_world = cmd_args.get("nonopt0"); game_params->world_path = get_clean_world_path(commanded_world); return !commanded_world.empty(); } static bool get_world_from_config(GameParams *game_params, const Settings &cmd_args) { // World directory std::string commanded_world; if (g_settings->exists("map-dir")) commanded_world = g_settings->get("map-dir"); game_params->world_path = get_clean_world_path(commanded_world); return !commanded_world.empty(); } static bool auto_select_world(GameParams *game_params) { // No world was specified; try to select it automatically // Get information about available worlds verbosestream << _("Determining world path") << std::endl; std::vector<WorldSpec> worldspecs = getAvailableWorlds(); std::string world_path; // If there is only a single world, use it if (worldspecs.size() == 1) { world_path = worldspecs[0].path; dstream <<_("Automatically selecting world at") << " [" << world_path << "]" << std::endl; // If there are multiple worlds, list them } else if (worldspecs.size() > 1 && game_params->is_dedicated_server) { std::cerr << _("Multiple worlds are available.") << std::endl; std::cerr << _("Please select one using --worldname <name>" " or --world <path>") << std::endl; print_worldspecs(worldspecs, std::cerr); return false; // If there are no worlds, automatically create a new one } else { // This is the ultimate default world path world_path = porting::path_user + DIR_DELIM + "worlds" + DIR_DELIM + "world"; infostream << "Creating default world at [" << world_path << "]" << std::endl; } assert(world_path != ""); // Post-condition game_params->world_path = world_path; return true; } static std::string get_clean_world_path(const std::string &path) { const std::string worldmt = "world.mt"; std::string clean_path; if (path.size() > worldmt.size() && path.substr(path.size() - worldmt.size()) == worldmt) { dstream << _("Supplied world.mt file - stripping it off.") << std::endl; clean_path = path.substr(0, path.size() - worldmt.size()); } else { clean_path = path; } return path; } static bool game_configure_subgame(GameParams *game_params, const Settings &cmd_args) { bool success; success = get_game_from_cmdline(game_params, cmd_args); if (!success) success = determine_subgame(game_params); return success; } static bool get_game_from_cmdline(GameParams *game_params, const Settings &cmd_args) { SubgameSpec commanded_gamespec; if (cmd_args.exists("gameid")) { std::string gameid = cmd_args.get("gameid"); commanded_gamespec = findSubgame(gameid); if (!commanded_gamespec.isValid()) { errorstream << "Game \"" << gameid << "\" not found" << std::endl; return false; } dstream << _("Using game specified by --gameid on the command line") << std::endl; game_params->game_spec = commanded_gamespec; return true; } return false; } static bool determine_subgame(GameParams *game_params) { SubgameSpec gamespec; assert(game_params->world_path != ""); // Pre-condition verbosestream << _("Determining gameid/gamespec") << std::endl; // If world doesn't exist if (!game_params->world_path.empty() && !getWorldExists(game_params->world_path)) { // Try to take gamespec from command line if (game_params->game_spec.isValid()) { gamespec = game_params->game_spec; infostream << "Using commanded gameid [" << gamespec.id << "]" << std::endl; } else { // Otherwise we will be using "minetest" gamespec = findSubgame(g_settings->get("default_game")); infostream << "Using default gameid [" << gamespec.id << "]" << std::endl; if (!gamespec.isValid()) { errorstream << "Subgame specified in default_game [" << g_settings->get("default_game") << "] is invalid." << std::endl; return false; } } } else { // World exists std::string world_gameid = getWorldGameId(game_params->world_path, false); // If commanded to use a gameid, do so if (game_params->game_spec.isValid()) { gamespec = game_params->game_spec; if (game_params->game_spec.id != world_gameid) { warningstream << "Using commanded gameid [" << gamespec.id << "]" << " instead of world gameid [" << world_gameid << "]" << std::endl; } } else { // If world contains an embedded game, use it; // Otherwise find world from local system. gamespec = findWorldSubgame(game_params->world_path); infostream << "Using world gameid [" << gamespec.id << "]" << std::endl; } } if (!gamespec.isValid()) { errorstream << "Subgame [" << gamespec.id << "] could not be found." << std::endl; return false; } game_params->game_spec = gamespec; return true; } /***************************************************************************** * Dedicated server *****************************************************************************/ static bool run_dedicated_server(const GameParams &game_params, const Settings &cmd_args) { verbosestream << _("Using world path") << " [" << game_params.world_path << "]" << std::endl; verbosestream << _("Using gameid") << " [" << game_params.game_spec.id << "]" << std::endl; // Bind address std::string bind_str = g_settings->get("bind_address"); Address bind_addr(0, 0, 0, 0, game_params.socket_port); if (g_settings->getBool("ipv6_server")) { bind_addr.setAddress((IPv6AddressBytes*) NULL); } try { bind_addr.Resolve(bind_str.c_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")) { errorstream << "Unable to listen on " << bind_addr.serializeString() << L" because IPv6 is disabled" << std::endl; return false; } // Database migration if (cmd_args.exists("migrate")) return migrate_map_database(game_params, cmd_args); if (cmd_args.exists("migrate-players")) return ServerEnvironment::migratePlayersDatabase(game_params, cmd_args); if (cmd_args.exists("migrate-auth")) return ServerEnvironment::migrateAuthDatabase(game_params, cmd_args); if (cmd_args.exists("terminal")) { #if USE_CURSES bool name_ok = true; std::string admin_nick = g_settings->get("name"); name_ok = name_ok && !admin_nick.empty(); name_ok = name_ok && string_allowed(admin_nick, PLAYERNAME_ALLOWED_CHARS); if (!name_ok) { if (admin_nick.empty()) { errorstream << "No name given for admin. " << "Please check your minetest.conf that it " << "contains a 'name = ' to your main admin account." << std::endl; } else { errorstream << "Name for admin '" << admin_nick << "' is not valid. " << "Please check that it only contains allowed characters. " << "Valid characters are: " << PLAYERNAME_ALLOWED_CHARS_USER_EXPL << std::endl; } return false; } ChatInterface iface; bool &kill = *porting::signal_handler_killstatus(); try { // Create server Server server(game_params.world_path, game_params.game_spec, false, bind_addr, true, &iface); server.init(); g_term_console.setup(&iface, &kill, admin_nick); g_term_console.start(); server.start(); // Run server dedicated_server_loop(server, kill); } catch (const ModError &e) { g_term_console.stopAndWaitforThread(); errorstream << "ModError: " << e.what() << std::endl; return false; } catch (const ServerError &e) { g_term_console.stopAndWaitforThread(); errorstream << "ServerError: " << e.what() << std::endl; return false; } // Tell the console to stop, and wait for it to finish, // only then leave context and free iface g_term_console.stop(); g_term_console.wait(); g_term_console.clearKillStatus(); } else { #else errorstream << "Cmd arg --terminal passed, but " << "compiled without ncurses. Ignoring." << std::endl; } { #endif try { // Create server Server server(game_params.world_path, game_params.game_spec, false, bind_addr, true); server.init(); server.start(); // Run server bool &kill = *porting::signal_handler_killstatus(); dedicated_server_loop(server, kill); } catch (const ModError &e) { errorstream << "ModError: " << e.what() << std::endl; return false; } catch (const ServerError &e) { errorstream << "ServerError: " << e.what() << std::endl; return false; } } return true; } static bool migrate_map_database(const GameParams &game_params, const Settings &cmd_args) { std::string migrate_to = cmd_args.get("migrate"); Settings world_mt; std::string world_mt_path = game_params.world_path + DIR_DELIM + "world.mt"; if (!world_mt.readConfigFile(world_mt_path.c_str())) { errorstream << "Cannot read world.mt!" << std::endl; return false; } if (!world_mt.exists("backend")) { errorstream << "Please specify your current backend in world.mt:" << std::endl << " backend = {sqlite3|leveldb|redis|dummy|postgresql}" << std::endl; return false; } std::string backend = world_mt.get("backend"); if (backend == migrate_to) { errorstream << "Cannot migrate: new backend is same" << " as the old one" << std::endl; return false; } MapDatabase *old_db = ServerMap::createDatabase(backend, game_params.world_path, world_mt), *new_db = ServerMap::createDatabase(migrate_to, game_params.world_path, world_mt); u32 count = 0; time_t last_update_time = 0; bool &kill = *porting::signal_handler_killstatus(); std::vector<v3s16> blocks; old_db->listAllLoadableBlocks(blocks); new_db->beginSave(); for (std::vector<v3s16>::const_iterator it = blocks.begin(); it != blocks.end(); ++it) { if (kill) return false; std::string data; old_db->loadBlock(*it, &data); if (!data.empty()) { new_db->saveBlock(*it, data); } else { errorstream << "Failed to load block " << PP(*it) << ", skipping it." << std::endl; } if (++count % 0xFF == 0 && time(NULL) - last_update_time >= 1) { std::cerr << " Migrated " << count << " blocks, " << (100.0 * count / blocks.size()) << "% completed.\r"; new_db->endSave(); new_db->beginSave(); last_update_time = time(NULL); } } std::cerr << std::endl; new_db->endSave(); delete old_db; delete new_db; actionstream << "Successfully migrated " << count << " blocks" << std::endl; world_mt.set("backend", migrate_to); if (!world_mt.updateConfigFile(world_mt_path.c_str())) errorstream << "Failed to update world.mt!" << std::endl; else actionstream << "world.mt updated" << std::endl; return true; }
pgimeno/minetest
src/main.cpp
C++
mit
31,704
/* Minetest Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com> 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 "map.h" #include "mapsector.h" #include "mapblock.h" #include "filesys.h" #include "voxel.h" #include "voxelalgorithms.h" #include "porting.h" #include "serialization.h" #include "nodemetadata.h" #include "settings.h" #include "log.h" #include "profiler.h" #include "nodedef.h" #include "gamedef.h" #include "util/directiontables.h" #include "util/basic_macros.h" #include "rollback_interface.h" #include "environment.h" #include "reflowscan.h" #include "emerge.h" #include "mapgen/mapgen_v6.h" #include "mapgen/mg_biome.h" #include "config.h" #include "server.h" #include "database/database.h" #include "database/database-dummy.h" #include "database/database-sqlite3.h" #include "script/scripting_server.h" #include <deque> #include <queue> #if USE_LEVELDB #include "database/database-leveldb.h" #endif #if USE_REDIS #include "database/database-redis.h" #endif #if USE_POSTGRESQL #include "database/database-postgresql.h" #endif /* Map */ Map::Map(std::ostream &dout, IGameDef *gamedef): m_dout(dout), m_gamedef(gamedef), m_nodedef(gamedef->ndef()) { } Map::~Map() { /* Free all MapSectors */ for (auto &sector : m_sectors) { delete sector.second; } } void Map::addEventReceiver(MapEventReceiver *event_receiver) { m_event_receivers.insert(event_receiver); } void Map::removeEventReceiver(MapEventReceiver *event_receiver) { m_event_receivers.erase(event_receiver); } void Map::dispatchEvent(MapEditEvent *event) { for (MapEventReceiver *event_receiver : m_event_receivers) { event_receiver->onMapEditEvent(event); } } MapSector * Map::getSectorNoGenerateNoExNoLock(v2s16 p) { if(m_sector_cache != NULL && p == m_sector_cache_p){ MapSector * sector = m_sector_cache; return sector; } std::map<v2s16, MapSector*>::iterator n = m_sectors.find(p); if (n == m_sectors.end()) return NULL; MapSector *sector = n->second; // Cache the last result m_sector_cache_p = p; m_sector_cache = sector; return sector; } MapSector * Map::getSectorNoGenerateNoEx(v2s16 p) { return getSectorNoGenerateNoExNoLock(p); } MapSector * Map::getSectorNoGenerate(v2s16 p) { MapSector *sector = getSectorNoGenerateNoEx(p); if(sector == NULL) throw InvalidPositionException(); return sector; } MapBlock * Map::getBlockNoCreateNoEx(v3s16 p3d) { v2s16 p2d(p3d.X, p3d.Z); MapSector * sector = getSectorNoGenerateNoEx(p2d); if(sector == NULL) return NULL; MapBlock *block = sector->getBlockNoCreateNoEx(p3d.Y); return block; } MapBlock * Map::getBlockNoCreate(v3s16 p3d) { MapBlock *block = getBlockNoCreateNoEx(p3d); if(block == NULL) throw InvalidPositionException(); return block; } bool Map::isNodeUnderground(v3s16 p) { v3s16 blockpos = getNodeBlockPos(p); try{ MapBlock * block = getBlockNoCreate(blockpos); return block->getIsUnderground(); } catch(InvalidPositionException &e) { return false; } } bool Map::isValidPosition(v3s16 p) { v3s16 blockpos = getNodeBlockPos(p); MapBlock *block = getBlockNoCreateNoEx(blockpos); return (block != NULL); } // Returns a CONTENT_IGNORE node if not found MapNode Map::getNodeNoEx(v3s16 p, bool *is_valid_position) { v3s16 blockpos = getNodeBlockPos(p); MapBlock *block = getBlockNoCreateNoEx(blockpos); if (block == NULL) { if (is_valid_position != NULL) *is_valid_position = false; return {CONTENT_IGNORE}; } v3s16 relpos = p - blockpos*MAP_BLOCKSIZE; bool is_valid_p; MapNode node = block->getNodeNoCheck(relpos, &is_valid_p); if (is_valid_position != NULL) *is_valid_position = is_valid_p; return node; } #if 0 // Deprecated // throws InvalidPositionException if not found // TODO: Now this is deprecated, getNodeNoEx should be renamed MapNode Map::getNode(v3s16 p) { v3s16 blockpos = getNodeBlockPos(p); MapBlock *block = getBlockNoCreateNoEx(blockpos); if (block == NULL) throw InvalidPositionException(); v3s16 relpos = p - blockpos*MAP_BLOCKSIZE; bool is_valid_position; MapNode node = block->getNodeNoCheck(relpos, &is_valid_position); if (!is_valid_position) throw InvalidPositionException(); return node; } #endif // throws InvalidPositionException if not found void Map::setNode(v3s16 p, MapNode & n) { v3s16 blockpos = getNodeBlockPos(p); MapBlock *block = getBlockNoCreate(blockpos); v3s16 relpos = p - blockpos*MAP_BLOCKSIZE; // Never allow placing CONTENT_IGNORE, it fucks up stuff if(n.getContent() == CONTENT_IGNORE){ bool temp_bool; errorstream<<"Map::setNode(): Not allowing to place CONTENT_IGNORE" <<" while trying to replace \"" <<m_nodedef->get(block->getNodeNoCheck(relpos, &temp_bool)).name <<"\" at "<<PP(p)<<" (block "<<PP(blockpos)<<")"<<std::endl; return; } block->setNodeNoCheck(relpos, n); } void Map::addNodeAndUpdate(v3s16 p, MapNode n, std::map<v3s16, MapBlock*> &modified_blocks, bool remove_metadata) { // Collect old node for rollback RollbackNode rollback_oldnode(this, p, m_gamedef); // This is needed for updating the lighting MapNode oldnode = getNodeNoEx(p); // Remove node metadata if (remove_metadata) { removeNodeMetadata(p); } // Set the node on the map // Ignore light (because calling voxalgo::update_lighting_nodes) n.setLight(LIGHTBANK_DAY, 0, m_nodedef); n.setLight(LIGHTBANK_NIGHT, 0, m_nodedef); setNode(p, n); // Update lighting std::vector<std::pair<v3s16, MapNode> > oldnodes; oldnodes.emplace_back(p, oldnode); voxalgo::update_lighting_nodes(this, oldnodes, modified_blocks); for (auto &modified_block : modified_blocks) { modified_block.second->expireDayNightDiff(); } // Report for rollback if(m_gamedef->rollback()) { RollbackNode rollback_newnode(this, p, m_gamedef); RollbackAction action; action.setSetNode(p, rollback_oldnode, rollback_newnode); m_gamedef->rollback()->reportAction(action); } /* Add neighboring liquid nodes and this node to transform queue. (it's vital for the node itself to get updated last, if it was removed.) */ for (const v3s16 &dir : g_7dirs) { v3s16 p2 = p + dir; bool is_valid_position; MapNode n2 = getNodeNoEx(p2, &is_valid_position); if(is_valid_position && (m_nodedef->get(n2).isLiquid() || n2.getContent() == CONTENT_AIR)) m_transforming_liquid.push_back(p2); } } void Map::removeNodeAndUpdate(v3s16 p, std::map<v3s16, MapBlock*> &modified_blocks) { addNodeAndUpdate(p, MapNode(CONTENT_AIR), modified_blocks, true); } bool Map::addNodeWithEvent(v3s16 p, MapNode n, bool remove_metadata) { MapEditEvent event; event.type = remove_metadata ? MEET_ADDNODE : MEET_SWAPNODE; event.p = p; event.n = n; bool succeeded = true; try{ std::map<v3s16, MapBlock*> modified_blocks; addNodeAndUpdate(p, n, modified_blocks, remove_metadata); // Copy modified_blocks to event for (auto &modified_block : modified_blocks) { event.modified_blocks.insert(modified_block.first); } } catch(InvalidPositionException &e){ succeeded = false; } dispatchEvent(&event); return succeeded; } bool Map::removeNodeWithEvent(v3s16 p) { MapEditEvent event; event.type = MEET_REMOVENODE; event.p = p; bool succeeded = true; try{ std::map<v3s16, MapBlock*> modified_blocks; removeNodeAndUpdate(p, modified_blocks); // Copy modified_blocks to event for (auto &modified_block : modified_blocks) { event.modified_blocks.insert(modified_block.first); } } catch(InvalidPositionException &e){ succeeded = false; } dispatchEvent(&event); return succeeded; } struct TimeOrderedMapBlock { MapSector *sect; MapBlock *block; TimeOrderedMapBlock(MapSector *sect, MapBlock *block) : sect(sect), block(block) {} bool operator<(const TimeOrderedMapBlock &b) const { return block->getUsageTimer() < b.block->getUsageTimer(); }; }; /* Updates usage timers */ void Map::timerUpdate(float dtime, float unload_timeout, u32 max_loaded_blocks, std::vector<v3s16> *unloaded_blocks) { bool save_before_unloading = (mapType() == MAPTYPE_SERVER); // Profile modified reasons Profiler modprofiler; std::vector<v2s16> sector_deletion_queue; u32 deleted_blocks_count = 0; u32 saved_blocks_count = 0; u32 block_count_all = 0; beginSave(); // If there is no practical limit, we spare creation of mapblock_queue if (max_loaded_blocks == U32_MAX) { for (auto &sector_it : m_sectors) { MapSector *sector = sector_it.second; bool all_blocks_deleted = true; MapBlockVect blocks; sector->getBlocks(blocks); for (MapBlock *block : blocks) { block->incrementUsageTimer(dtime); if (block->refGet() == 0 && block->getUsageTimer() > unload_timeout) { v3s16 p = block->getPos(); // Save if modified if (block->getModified() != MOD_STATE_CLEAN && save_before_unloading) { modprofiler.add(block->getModifiedReasonString(), 1); if (!saveBlock(block)) continue; saved_blocks_count++; } // Delete from memory sector->deleteBlock(block); if (unloaded_blocks) unloaded_blocks->push_back(p); deleted_blocks_count++; } else { all_blocks_deleted = false; block_count_all++; } } if (all_blocks_deleted) { sector_deletion_queue.push_back(sector_it.first); } } } else { std::priority_queue<TimeOrderedMapBlock> mapblock_queue; for (auto &sector_it : m_sectors) { MapSector *sector = sector_it.second; MapBlockVect blocks; sector->getBlocks(blocks); for (MapBlock *block : blocks) { block->incrementUsageTimer(dtime); mapblock_queue.push(TimeOrderedMapBlock(sector, block)); } } block_count_all = mapblock_queue.size(); // Delete old blocks, and blocks over the limit from the memory while (!mapblock_queue.empty() && (mapblock_queue.size() > max_loaded_blocks || mapblock_queue.top().block->getUsageTimer() > unload_timeout)) { TimeOrderedMapBlock b = mapblock_queue.top(); mapblock_queue.pop(); MapBlock *block = b.block; if (block->refGet() != 0) continue; v3s16 p = block->getPos(); // Save if modified if (block->getModified() != MOD_STATE_CLEAN && save_before_unloading) { modprofiler.add(block->getModifiedReasonString(), 1); if (!saveBlock(block)) continue; saved_blocks_count++; } // Delete from memory b.sect->deleteBlock(block); if (unloaded_blocks) unloaded_blocks->push_back(p); deleted_blocks_count++; block_count_all--; } // Delete empty sectors for (auto &sector_it : m_sectors) { if (sector_it.second->empty()) { sector_deletion_queue.push_back(sector_it.first); } } } endSave(); // Finally delete the empty sectors deleteSectors(sector_deletion_queue); if(deleted_blocks_count != 0) { PrintInfo(infostream); // ServerMap/ClientMap: infostream<<"Unloaded "<<deleted_blocks_count <<" blocks from memory"; if(save_before_unloading) infostream<<", of which "<<saved_blocks_count<<" were written"; infostream<<", "<<block_count_all<<" blocks in memory"; infostream<<"."<<std::endl; if(saved_blocks_count != 0){ PrintInfo(infostream); // ServerMap/ClientMap: infostream<<"Blocks modified by: "<<std::endl; modprofiler.print(infostream); } } } void Map::unloadUnreferencedBlocks(std::vector<v3s16> *unloaded_blocks) { timerUpdate(0.0, -1.0, 0, unloaded_blocks); } void Map::deleteSectors(std::vector<v2s16> &sectorList) { for (v2s16 j : sectorList) { MapSector *sector = m_sectors[j]; // If sector is in sector cache, remove it from there if(m_sector_cache == sector) m_sector_cache = NULL; // Remove from map and delete m_sectors.erase(j); delete sector; } } void Map::PrintInfo(std::ostream &out) { out<<"Map: "; } #define WATER_DROP_BOOST 4 enum NeighborType : u8 { NEIGHBOR_UPPER, NEIGHBOR_SAME_LEVEL, NEIGHBOR_LOWER }; struct NodeNeighbor { MapNode n; NeighborType t; v3s16 p; NodeNeighbor() : n(CONTENT_AIR), t(NEIGHBOR_SAME_LEVEL) { } NodeNeighbor(const MapNode &node, NeighborType n_type, const v3s16 &pos) : n(node), t(n_type), p(pos) { } }; void Map::transforming_liquid_add(v3s16 p) { m_transforming_liquid.push_back(p); } void Map::transformLiquids(std::map<v3s16, MapBlock*> &modified_blocks, ServerEnvironment *env) { u32 loopcount = 0; u32 initial_size = m_transforming_liquid.size(); /*if(initial_size != 0) infostream<<"transformLiquids(): initial_size="<<initial_size<<std::endl;*/ // list of nodes that due to viscosity have not reached their max level height std::deque<v3s16> must_reflow; std::vector<std::pair<v3s16, MapNode> > changed_nodes; u32 liquid_loop_max = g_settings->getS32("liquid_loop_max"); u32 loop_max = liquid_loop_max; #if 0 /* If liquid_loop_max is not keeping up with the queue size increase * loop_max up to a maximum of liquid_loop_max * dedicated_server_step. */ if (m_transforming_liquid.size() > loop_max * 2) { // "Burst" mode float server_step = g_settings->getFloat("dedicated_server_step"); if (m_transforming_liquid_loop_count_multiplier - 1.0 < server_step) m_transforming_liquid_loop_count_multiplier *= 1.0 + server_step / 10; } else { m_transforming_liquid_loop_count_multiplier = 1.0; } loop_max *= m_transforming_liquid_loop_count_multiplier; #endif while (m_transforming_liquid.size() != 0) { // This should be done here so that it is done when continue is used if (loopcount >= initial_size || loopcount >= loop_max) break; loopcount++; /* Get a queued transforming liquid node */ v3s16 p0 = m_transforming_liquid.front(); m_transforming_liquid.pop_front(); MapNode n0 = getNodeNoEx(p0); /* Collect information about current node */ s8 liquid_level = -1; // The liquid node which will be placed there if // the liquid flows into this node. content_t liquid_kind = CONTENT_IGNORE; // The node which will be placed there if liquid // can't flow into this node. content_t floodable_node = CONTENT_AIR; const ContentFeatures &cf = m_nodedef->get(n0); LiquidType liquid_type = cf.liquid_type; switch (liquid_type) { case LIQUID_SOURCE: liquid_level = LIQUID_LEVEL_SOURCE; liquid_kind = m_nodedef->getId(cf.liquid_alternative_flowing); break; case LIQUID_FLOWING: liquid_level = (n0.param2 & LIQUID_LEVEL_MASK); liquid_kind = n0.getContent(); break; case LIQUID_NONE: // if this node is 'floodable', it *could* be transformed // into a liquid, otherwise, continue with the next node. if (!cf.floodable) continue; floodable_node = n0.getContent(); liquid_kind = CONTENT_AIR; break; } /* Collect information about the environment */ const v3s16 *dirs = g_6dirs; NodeNeighbor sources[6]; // surrounding sources int num_sources = 0; NodeNeighbor flows[6]; // surrounding flowing liquid nodes int num_flows = 0; NodeNeighbor airs[6]; // surrounding air int num_airs = 0; NodeNeighbor neutrals[6]; // nodes that are solid or another kind of liquid int num_neutrals = 0; bool flowing_down = false; bool ignored_sources = false; for (u16 i = 0; i < 6; i++) { NeighborType nt = NEIGHBOR_SAME_LEVEL; switch (i) { case 1: nt = NEIGHBOR_UPPER; break; case 4: nt = NEIGHBOR_LOWER; break; default: break; } v3s16 npos = p0 + dirs[i]; NodeNeighbor nb(getNodeNoEx(npos), nt, npos); const ContentFeatures &cfnb = m_nodedef->get(nb.n); switch (m_nodedef->get(nb.n.getContent()).liquid_type) { case LIQUID_NONE: if (cfnb.floodable) { airs[num_airs++] = nb; // if the current node is a water source the neighbor // should be enqueded for transformation regardless of whether the // current node changes or not. if (nb.t != NEIGHBOR_UPPER && liquid_type != LIQUID_NONE) m_transforming_liquid.push_back(npos); // if the current node happens to be a flowing node, it will start to flow down here. if (nb.t == NEIGHBOR_LOWER) flowing_down = true; } else { neutrals[num_neutrals++] = nb; if (nb.n.getContent() == CONTENT_IGNORE) { // If node below is ignore prevent water from // spreading outwards and otherwise prevent from // flowing away as ignore node might be the source if (nb.t == NEIGHBOR_LOWER) flowing_down = true; else ignored_sources = true; } } break; case LIQUID_SOURCE: // if this node is not (yet) of a liquid type, choose the first liquid type we encounter if (liquid_kind == CONTENT_AIR) liquid_kind = m_nodedef->getId(cfnb.liquid_alternative_flowing); if (m_nodedef->getId(cfnb.liquid_alternative_flowing) != liquid_kind) { neutrals[num_neutrals++] = nb; } else { // Do not count bottom source, it will screw things up if(dirs[i].Y != -1) sources[num_sources++] = nb; } break; case LIQUID_FLOWING: // if this node is not (yet) of a liquid type, choose the first liquid type we encounter if (liquid_kind == CONTENT_AIR) liquid_kind = m_nodedef->getId(cfnb.liquid_alternative_flowing); if (m_nodedef->getId(cfnb.liquid_alternative_flowing) != liquid_kind) { neutrals[num_neutrals++] = nb; } else { flows[num_flows++] = nb; if (nb.t == NEIGHBOR_LOWER) flowing_down = true; } break; } } /* decide on the type (and possibly level) of the current node */ content_t new_node_content; s8 new_node_level = -1; s8 max_node_level = -1; u8 range = m_nodedef->get(liquid_kind).liquid_range; if (range > LIQUID_LEVEL_MAX + 1) range = LIQUID_LEVEL_MAX + 1; if ((num_sources >= 2 && m_nodedef->get(liquid_kind).liquid_renewable) || liquid_type == LIQUID_SOURCE) { // liquid_kind will be set to either the flowing alternative of the node (if it's a liquid) // or the flowing alternative of the first of the surrounding sources (if it's air), so // it's perfectly safe to use liquid_kind here to determine the new node content. new_node_content = m_nodedef->getId(m_nodedef->get(liquid_kind).liquid_alternative_source); } else if (num_sources >= 1 && sources[0].t != NEIGHBOR_LOWER) { // liquid_kind is set properly, see above max_node_level = new_node_level = LIQUID_LEVEL_MAX; if (new_node_level >= (LIQUID_LEVEL_MAX + 1 - range)) new_node_content = liquid_kind; else new_node_content = floodable_node; } else if (ignored_sources && liquid_level >= 0) { // Maybe there are neighbouring sources that aren't loaded yet // so prevent flowing away. new_node_level = liquid_level; new_node_content = liquid_kind; } else { // no surrounding sources, so get the maximum level that can flow into this node for (u16 i = 0; i < num_flows; i++) { u8 nb_liquid_level = (flows[i].n.param2 & LIQUID_LEVEL_MASK); switch (flows[i].t) { case NEIGHBOR_UPPER: if (nb_liquid_level + WATER_DROP_BOOST > max_node_level) { max_node_level = LIQUID_LEVEL_MAX; if (nb_liquid_level + WATER_DROP_BOOST < LIQUID_LEVEL_MAX) max_node_level = nb_liquid_level + WATER_DROP_BOOST; } else if (nb_liquid_level > max_node_level) { max_node_level = nb_liquid_level; } break; case NEIGHBOR_LOWER: break; case NEIGHBOR_SAME_LEVEL: if ((flows[i].n.param2 & LIQUID_FLOW_DOWN_MASK) != LIQUID_FLOW_DOWN_MASK && nb_liquid_level > 0 && nb_liquid_level - 1 > max_node_level) max_node_level = nb_liquid_level - 1; break; } } u8 viscosity = m_nodedef->get(liquid_kind).liquid_viscosity; if (viscosity > 1 && max_node_level != liquid_level) { // amount to gain, limited by viscosity // must be at least 1 in absolute value s8 level_inc = max_node_level - liquid_level; if (level_inc < -viscosity || level_inc > viscosity) new_node_level = liquid_level + level_inc/viscosity; else if (level_inc < 0) new_node_level = liquid_level - 1; else if (level_inc > 0) new_node_level = liquid_level + 1; if (new_node_level != max_node_level) must_reflow.push_back(p0); } else { new_node_level = max_node_level; } if (max_node_level >= (LIQUID_LEVEL_MAX + 1 - range)) new_node_content = liquid_kind; else new_node_content = floodable_node; } /* check if anything has changed. if not, just continue with the next node. */ if (new_node_content == n0.getContent() && (m_nodedef->get(n0.getContent()).liquid_type != LIQUID_FLOWING || ((n0.param2 & LIQUID_LEVEL_MASK) == (u8)new_node_level && ((n0.param2 & LIQUID_FLOW_DOWN_MASK) == LIQUID_FLOW_DOWN_MASK) == flowing_down))) continue; /* update the current node */ MapNode n00 = n0; //bool flow_down_enabled = (flowing_down && ((n0.param2 & LIQUID_FLOW_DOWN_MASK) != LIQUID_FLOW_DOWN_MASK)); if (m_nodedef->get(new_node_content).liquid_type == LIQUID_FLOWING) { // set level to last 3 bits, flowing down bit to 4th bit n0.param2 = (flowing_down ? LIQUID_FLOW_DOWN_MASK : 0x00) | (new_node_level & LIQUID_LEVEL_MASK); } else { // set the liquid level and flow bit to 0 n0.param2 = ~(LIQUID_LEVEL_MASK | LIQUID_FLOW_DOWN_MASK); } // change the node. n0.setContent(new_node_content); // on_flood() the node if (floodable_node != CONTENT_AIR) { if (env->getScriptIface()->node_on_flood(p0, n00, n0)) continue; } // Ignore light (because calling voxalgo::update_lighting_nodes) n0.setLight(LIGHTBANK_DAY, 0, m_nodedef); n0.setLight(LIGHTBANK_NIGHT, 0, m_nodedef); // Find out whether there is a suspect for this action std::string suspect; if (m_gamedef->rollback()) suspect = m_gamedef->rollback()->getSuspect(p0, 83, 1); if (m_gamedef->rollback() && !suspect.empty()) { // Blame suspect RollbackScopeActor rollback_scope(m_gamedef->rollback(), suspect, true); // Get old node for rollback RollbackNode rollback_oldnode(this, p0, m_gamedef); // Set node setNode(p0, n0); // Report RollbackNode rollback_newnode(this, p0, m_gamedef); RollbackAction action; action.setSetNode(p0, rollback_oldnode, rollback_newnode); m_gamedef->rollback()->reportAction(action); } else { // Set node setNode(p0, n0); } v3s16 blockpos = getNodeBlockPos(p0); MapBlock *block = getBlockNoCreateNoEx(blockpos); if (block != NULL) { modified_blocks[blockpos] = block; changed_nodes.emplace_back(p0, n00); } /* enqueue neighbors for update if neccessary */ switch (m_nodedef->get(n0.getContent()).liquid_type) { case LIQUID_SOURCE: case LIQUID_FLOWING: // make sure source flows into all neighboring nodes for (u16 i = 0; i < num_flows; i++) if (flows[i].t != NEIGHBOR_UPPER) m_transforming_liquid.push_back(flows[i].p); for (u16 i = 0; i < num_airs; i++) if (airs[i].t != NEIGHBOR_UPPER) m_transforming_liquid.push_back(airs[i].p); break; case LIQUID_NONE: // this flow has turned to air; neighboring flows might need to do the same for (u16 i = 0; i < num_flows; i++) m_transforming_liquid.push_back(flows[i].p); break; } } //infostream<<"Map::transformLiquids(): loopcount="<<loopcount<<std::endl; for (auto &iter : must_reflow) m_transforming_liquid.push_back(iter); voxalgo::update_lighting_nodes(this, changed_nodes, modified_blocks); /* ---------------------------------------------------------------------- * Manage the queue so that it does not grow indefinately */ u16 time_until_purge = g_settings->getU16("liquid_queue_purge_time"); if (time_until_purge == 0) return; // Feature disabled time_until_purge *= 1000; // seconds -> milliseconds u64 curr_time = porting::getTimeMs(); u32 prev_unprocessed = m_unprocessed_count; m_unprocessed_count = m_transforming_liquid.size(); // if unprocessed block count is decreasing or stable if (m_unprocessed_count <= prev_unprocessed) { m_queue_size_timer_started = false; } else { if (!m_queue_size_timer_started) m_inc_trending_up_start_time = curr_time; m_queue_size_timer_started = true; } // Account for curr_time overflowing if (m_queue_size_timer_started && m_inc_trending_up_start_time > curr_time) m_queue_size_timer_started = false; /* If the queue has been growing for more than liquid_queue_purge_time seconds * and the number of unprocessed blocks is still > liquid_loop_max then we * cannot keep up; dump the oldest blocks from the queue so that the queue * has liquid_loop_max items in it */ if (m_queue_size_timer_started && curr_time - m_inc_trending_up_start_time > time_until_purge && m_unprocessed_count > liquid_loop_max) { size_t dump_qty = m_unprocessed_count - liquid_loop_max; infostream << "transformLiquids(): DUMPING " << dump_qty << " blocks from the queue" << std::endl; while (dump_qty--) m_transforming_liquid.pop_front(); m_queue_size_timer_started = false; // optimistically assume we can keep up now m_unprocessed_count = m_transforming_liquid.size(); } } std::vector<v3s16> Map::findNodesWithMetadata(v3s16 p1, v3s16 p2) { std::vector<v3s16> positions_with_meta; sortBoxVerticies(p1, p2); v3s16 bpmin = getNodeBlockPos(p1); v3s16 bpmax = getNodeBlockPos(p2); VoxelArea area(p1, p2); for (s16 z = bpmin.Z; z <= bpmax.Z; z++) for (s16 y = bpmin.Y; y <= bpmax.Y; y++) for (s16 x = bpmin.X; x <= bpmax.X; x++) { v3s16 blockpos(x, y, z); MapBlock *block = getBlockNoCreateNoEx(blockpos); if (!block) { verbosestream << "Map::getNodeMetadata(): Need to emerge " << PP(blockpos) << std::endl; block = emergeBlock(blockpos, false); } if (!block) { infostream << "WARNING: Map::getNodeMetadata(): Block not found" << std::endl; continue; } v3s16 p_base = blockpos * MAP_BLOCKSIZE; std::vector<v3s16> keys = block->m_node_metadata.getAllKeys(); for (size_t i = 0; i != keys.size(); i++) { v3s16 p(keys[i] + p_base); if (!area.contains(p)) continue; positions_with_meta.push_back(p); } } return positions_with_meta; } NodeMetadata *Map::getNodeMetadata(v3s16 p) { v3s16 blockpos = getNodeBlockPos(p); v3s16 p_rel = p - blockpos*MAP_BLOCKSIZE; MapBlock *block = getBlockNoCreateNoEx(blockpos); if(!block){ infostream<<"Map::getNodeMetadata(): Need to emerge " <<PP(blockpos)<<std::endl; block = emergeBlock(blockpos, false); } if(!block){ warningstream<<"Map::getNodeMetadata(): Block not found" <<std::endl; return NULL; } NodeMetadata *meta = block->m_node_metadata.get(p_rel); return meta; } bool Map::setNodeMetadata(v3s16 p, NodeMetadata *meta) { v3s16 blockpos = getNodeBlockPos(p); v3s16 p_rel = p - blockpos*MAP_BLOCKSIZE; MapBlock *block = getBlockNoCreateNoEx(blockpos); if(!block){ infostream<<"Map::setNodeMetadata(): Need to emerge " <<PP(blockpos)<<std::endl; block = emergeBlock(blockpos, false); } if(!block){ warningstream<<"Map::setNodeMetadata(): Block not found" <<std::endl; return false; } block->m_node_metadata.set(p_rel, meta); return true; } void Map::removeNodeMetadata(v3s16 p) { v3s16 blockpos = getNodeBlockPos(p); v3s16 p_rel = p - blockpos*MAP_BLOCKSIZE; MapBlock *block = getBlockNoCreateNoEx(blockpos); if(block == NULL) { warningstream<<"Map::removeNodeMetadata(): Block not found" <<std::endl; return; } block->m_node_metadata.remove(p_rel); } NodeTimer Map::getNodeTimer(v3s16 p) { v3s16 blockpos = getNodeBlockPos(p); v3s16 p_rel = p - blockpos*MAP_BLOCKSIZE; MapBlock *block = getBlockNoCreateNoEx(blockpos); if(!block){ infostream<<"Map::getNodeTimer(): Need to emerge " <<PP(blockpos)<<std::endl; block = emergeBlock(blockpos, false); } if(!block){ warningstream<<"Map::getNodeTimer(): Block not found" <<std::endl; return NodeTimer(); } NodeTimer t = block->m_node_timers.get(p_rel); NodeTimer nt(t.timeout, t.elapsed, p); return nt; } void Map::setNodeTimer(const NodeTimer &t) { v3s16 p = t.position; v3s16 blockpos = getNodeBlockPos(p); v3s16 p_rel = p - blockpos*MAP_BLOCKSIZE; MapBlock *block = getBlockNoCreateNoEx(blockpos); if(!block){ infostream<<"Map::setNodeTimer(): Need to emerge " <<PP(blockpos)<<std::endl; block = emergeBlock(blockpos, false); } if(!block){ warningstream<<"Map::setNodeTimer(): Block not found" <<std::endl; return; } NodeTimer nt(t.timeout, t.elapsed, p_rel); block->m_node_timers.set(nt); } void Map::removeNodeTimer(v3s16 p) { v3s16 blockpos = getNodeBlockPos(p); v3s16 p_rel = p - blockpos*MAP_BLOCKSIZE; MapBlock *block = getBlockNoCreateNoEx(blockpos); if(block == NULL) { warningstream<<"Map::removeNodeTimer(): Block not found" <<std::endl; return; } block->m_node_timers.remove(p_rel); } bool Map::isOccluded(v3s16 p0, v3s16 p1, float step, float stepfac, float start_off, float end_off, u32 needed_count) { float d0 = (float)BS * p0.getDistanceFrom(p1); v3s16 u0 = p1 - p0; v3f uf = v3f(u0.X, u0.Y, u0.Z) * BS; uf.normalize(); v3f p0f = v3f(p0.X, p0.Y, p0.Z) * BS; u32 count = 0; for(float s=start_off; s<d0+end_off; s+=step){ v3f pf = p0f + uf * s; v3s16 p = floatToInt(pf, BS); MapNode n = getNodeNoEx(p); const ContentFeatures &f = m_nodedef->get(n); if(f.drawtype == NDT_NORMAL){ // not transparent, see ContentFeature::updateTextures count++; if(count >= needed_count) return true; } step *= stepfac; } return false; } bool Map::isBlockOccluded(MapBlock *block, v3s16 cam_pos_nodes) { v3s16 cpn = block->getPos() * MAP_BLOCKSIZE; cpn += v3s16(MAP_BLOCKSIZE / 2, MAP_BLOCKSIZE / 2, MAP_BLOCKSIZE / 2); float step = BS * 1; float stepfac = 1.1; float startoff = BS * 1; // The occlusion search of 'isOccluded()' must stop short of the target // point by distance 'endoff' (end offset) to not enter the target mapblock. // For the 8 mapblock corners 'endoff' must therefore be the maximum diagonal // of a mapblock, because we must consider all view angles. // sqrt(1^2 + 1^2 + 1^2) = 1.732 float endoff = -BS * MAP_BLOCKSIZE * 1.732050807569; s16 bs2 = MAP_BLOCKSIZE / 2 + 1; // to reduce the likelihood of falsely occluded blocks // require at least two solid blocks // this is a HACK, we should think of a more precise algorithm u32 needed_count = 2; return ( // For the central point of the mapblock 'endoff' can be halved isOccluded(cam_pos_nodes, cpn, step, stepfac, startoff, endoff / 2.0f, needed_count) && isOccluded(cam_pos_nodes, cpn + v3s16(bs2,bs2,bs2), step, stepfac, startoff, endoff, needed_count) && isOccluded(cam_pos_nodes, cpn + v3s16(bs2,bs2,-bs2), step, stepfac, startoff, endoff, needed_count) && isOccluded(cam_pos_nodes, cpn + v3s16(bs2,-bs2,bs2), step, stepfac, startoff, endoff, needed_count) && isOccluded(cam_pos_nodes, cpn + v3s16(bs2,-bs2,-bs2), step, stepfac, startoff, endoff, needed_count) && isOccluded(cam_pos_nodes, cpn + v3s16(-bs2,bs2,bs2), step, stepfac, startoff, endoff, needed_count) && isOccluded(cam_pos_nodes, cpn + v3s16(-bs2,bs2,-bs2), step, stepfac, startoff, endoff, needed_count) && isOccluded(cam_pos_nodes, cpn + v3s16(-bs2,-bs2,bs2), step, stepfac, startoff, endoff, needed_count) && isOccluded(cam_pos_nodes, cpn + v3s16(-bs2,-bs2,-bs2), step, stepfac, startoff, endoff, needed_count)); } /* ServerMap */ ServerMap::ServerMap(const std::string &savedir, IGameDef *gamedef, EmergeManager *emerge): Map(dout_server, gamedef), settings_mgr(g_settings, savedir + DIR_DELIM + "map_meta.txt"), m_emerge(emerge) { verbosestream<<FUNCTION_NAME<<std::endl; // Tell the EmergeManager about our MapSettingsManager emerge->map_settings_mgr = &settings_mgr; /* Try to load map; if not found, create a new one. */ // Determine which database backend to use std::string conf_path = savedir + DIR_DELIM + "world.mt"; Settings conf; bool succeeded = conf.readConfigFile(conf_path.c_str()); if (!succeeded || !conf.exists("backend")) { // fall back to sqlite3 conf.set("backend", "sqlite3"); } std::string backend = conf.get("backend"); dbase = createDatabase(backend, savedir, conf); if (conf.exists("readonly_backend")) { std::string readonly_dir = savedir + DIR_DELIM + "readonly"; dbase_ro = createDatabase(conf.get("readonly_backend"), readonly_dir, conf); } if (!conf.updateConfigFile(conf_path.c_str())) errorstream << "ServerMap::ServerMap(): Failed to update world.mt!" << std::endl; m_savedir = savedir; m_map_saving_enabled = false; try { // If directory exists, check contents and load if possible if (fs::PathExists(m_savedir)) { // If directory is empty, it is safe to save into it. if (fs::GetDirListing(m_savedir).empty()) { infostream<<"ServerMap: Empty save directory is valid." <<std::endl; m_map_saving_enabled = true; } else { if (settings_mgr.loadMapMeta()) { infostream << "ServerMap: Metadata loaded from " << savedir << std::endl; } else { infostream << "ServerMap: Metadata could not be loaded " "from " << savedir << ", assuming valid save " "directory." << std::endl; } m_map_saving_enabled = true; // Map loaded, not creating new one return; } } // If directory doesn't exist, it is safe to save to it else{ m_map_saving_enabled = true; } } catch(std::exception &e) { warningstream<<"ServerMap: Failed to load map from "<<savedir <<", exception: "<<e.what()<<std::endl; infostream<<"Please remove the map or fix it."<<std::endl; warningstream<<"Map saving will be disabled."<<std::endl; } } ServerMap::~ServerMap() { verbosestream<<FUNCTION_NAME<<std::endl; try { if (m_map_saving_enabled) { // Save only changed parts save(MOD_STATE_WRITE_AT_UNLOAD); infostream << "ServerMap: Saved map to " << m_savedir << std::endl; } else { infostream << "ServerMap: Map not saved" << std::endl; } } catch(std::exception &e) { infostream<<"ServerMap: Failed to save map to "<<m_savedir <<", exception: "<<e.what()<<std::endl; } /* Close database if it was opened */ delete dbase; if (dbase_ro) delete dbase_ro; #if 0 /* Free all MapChunks */ core::map<v2s16, MapChunk*>::Iterator i = m_chunks.getIterator(); for(; i.atEnd() == false; i++) { MapChunk *chunk = i.getNode()->getValue(); delete chunk; } #endif } MapgenParams *ServerMap::getMapgenParams() { // getMapgenParams() should only ever be called after Server is initialized assert(settings_mgr.mapgen_params != NULL); return settings_mgr.mapgen_params; } u64 ServerMap::getSeed() { return getMapgenParams()->seed; } s16 ServerMap::getWaterLevel() { return getMapgenParams()->water_level; } bool ServerMap::blockpos_over_mapgen_limit(v3s16 p) { const s16 mapgen_limit_bp = rangelim( getMapgenParams()->mapgen_limit, 0, MAX_MAP_GENERATION_LIMIT) / MAP_BLOCKSIZE; return p.X < -mapgen_limit_bp || p.X > mapgen_limit_bp || p.Y < -mapgen_limit_bp || p.Y > mapgen_limit_bp || p.Z < -mapgen_limit_bp || p.Z > mapgen_limit_bp; } bool ServerMap::initBlockMake(v3s16 blockpos, BlockMakeData *data) { s16 csize = getMapgenParams()->chunksize; v3s16 bpmin = EmergeManager::getContainingChunk(blockpos, csize); v3s16 bpmax = bpmin + v3s16(1, 1, 1) * (csize - 1); bool enable_mapgen_debug_info = m_emerge->enable_mapgen_debug_info; EMERGE_DBG_OUT("initBlockMake(): " PP(bpmin) " - " PP(bpmax)); v3s16 extra_borders(1, 1, 1); v3s16 full_bpmin = bpmin - extra_borders; v3s16 full_bpmax = bpmax + extra_borders; // Do nothing if not inside mapgen limits (+-1 because of neighbors) if (blockpos_over_mapgen_limit(full_bpmin) || blockpos_over_mapgen_limit(full_bpmax)) return false; data->seed = getSeed(); data->blockpos_min = bpmin; data->blockpos_max = bpmax; data->blockpos_requested = blockpos; data->nodedef = m_nodedef; /* Create the whole area of this and the neighboring blocks */ for (s16 x = full_bpmin.X; x <= full_bpmax.X; x++) for (s16 z = full_bpmin.Z; z <= full_bpmax.Z; z++) { v2s16 sectorpos(x, z); // Sector metadata is loaded from disk if not already loaded. MapSector *sector = createSector(sectorpos); FATAL_ERROR_IF(sector == NULL, "createSector() failed"); for (s16 y = full_bpmin.Y; y <= full_bpmax.Y; y++) { v3s16 p(x, y, z); MapBlock *block = emergeBlock(p, false); if (block == NULL) { block = createBlock(p); // Block gets sunlight if this is true. // Refer to the map generator heuristics. bool ug = m_emerge->isBlockUnderground(p); block->setIsUnderground(ug); } } } /* Now we have a big empty area. Make a ManualMapVoxelManipulator that contains this and the neighboring blocks */ data->vmanip = new MMVManip(this); data->vmanip->initialEmerge(full_bpmin, full_bpmax); // Note: we may need this again at some point. #if 0 // Ensure none of the blocks to be generated were marked as // containing CONTENT_IGNORE for (s16 z = blockpos_min.Z; z <= blockpos_max.Z; z++) { for (s16 y = blockpos_min.Y; y <= blockpos_max.Y; y++) { for (s16 x = blockpos_min.X; x <= blockpos_max.X; x++) { core::map<v3s16, u8>::Node *n; n = data->vmanip->m_loaded_blocks.find(v3s16(x, y, z)); if (n == NULL) continue; u8 flags = n->getValue(); flags &= ~VMANIP_BLOCK_CONTAINS_CIGNORE; n->setValue(flags); } } } #endif // Data is ready now. return true; } void ServerMap::finishBlockMake(BlockMakeData *data, std::map<v3s16, MapBlock*> *changed_blocks) { v3s16 bpmin = data->blockpos_min; v3s16 bpmax = data->blockpos_max; v3s16 extra_borders(1, 1, 1); bool enable_mapgen_debug_info = m_emerge->enable_mapgen_debug_info; EMERGE_DBG_OUT("finishBlockMake(): " PP(bpmin) " - " PP(bpmax)); /* Blit generated stuff to map NOTE: blitBackAll adds nearly everything to changed_blocks */ data->vmanip->blitBackAll(changed_blocks); EMERGE_DBG_OUT("finishBlockMake: changed_blocks.size()=" << changed_blocks->size()); /* Copy transforming liquid information */ while (data->transforming_liquid.size()) { m_transforming_liquid.push_back(data->transforming_liquid.front()); data->transforming_liquid.pop_front(); } for (auto &changed_block : *changed_blocks) { MapBlock *block = changed_block.second; if (!block) continue; /* Update day/night difference cache of the MapBlocks */ block->expireDayNightDiff(); /* Set block as modified */ block->raiseModified(MOD_STATE_WRITE_NEEDED, MOD_REASON_EXPIRE_DAYNIGHTDIFF); } /* Set central blocks as generated */ for (s16 x = bpmin.X; x <= bpmax.X; x++) for (s16 z = bpmin.Z; z <= bpmax.Z; z++) for (s16 y = bpmin.Y; y <= bpmax.Y; y++) { MapBlock *block = getBlockNoCreateNoEx(v3s16(x, y, z)); if (!block) continue; block->setGenerated(true); } /* Save changed parts of map NOTE: Will be saved later. */ //save(MOD_STATE_WRITE_AT_UNLOAD); } MapSector *ServerMap::createSector(v2s16 p2d) { /* Check if it exists already in memory */ MapSector *sector = getSectorNoGenerateNoEx(p2d); if (sector) return sector; /* Do not create over max mapgen limit */ const s16 max_limit_bp = MAX_MAP_GENERATION_LIMIT / MAP_BLOCKSIZE; if (p2d.X < -max_limit_bp || p2d.X > max_limit_bp || p2d.Y < -max_limit_bp || p2d.Y > max_limit_bp) throw InvalidPositionException("createSector(): pos. over max mapgen limit"); /* Generate blank sector */ sector = new MapSector(this, p2d, m_gamedef); // Sector position on map in nodes //v2s16 nodepos2d = p2d * MAP_BLOCKSIZE; /* Insert to container */ m_sectors[p2d] = sector; return sector; } #if 0 /* This is a quick-hand function for calling makeBlock(). */ MapBlock * ServerMap::generateBlock( v3s16 p, std::map<v3s16, MapBlock*> &modified_blocks ) { bool enable_mapgen_debug_info = g_settings->getBool("enable_mapgen_debug_info"); TimeTaker timer("generateBlock"); //MapBlock *block = original_dummy; v2s16 p2d(p.X, p.Z); v2s16 p2d_nodes = p2d * MAP_BLOCKSIZE; /* Do not generate over-limit */ if(blockpos_over_limit(p)) { infostream<<FUNCTION_NAME<<": Block position over limit"<<std::endl; throw InvalidPositionException("generateBlock(): pos. over limit"); } /* Create block make data */ BlockMakeData data; initBlockMake(&data, p); /* Generate block */ { TimeTaker t("mapgen::make_block()"); mapgen->makeChunk(&data); //mapgen::make_block(&data); if(enable_mapgen_debug_info == false) t.stop(true); // Hide output } /* Blit data back on map, update lighting, add mobs and whatever this does */ finishBlockMake(&data, modified_blocks); /* Get central block */ MapBlock *block = getBlockNoCreateNoEx(p); #if 0 /* Check result */ if(block) { bool erroneus_content = false; for(s16 z0=0; z0<MAP_BLOCKSIZE; z0++) for(s16 y0=0; y0<MAP_BLOCKSIZE; y0++) for(s16 x0=0; x0<MAP_BLOCKSIZE; x0++) { v3s16 p(x0,y0,z0); MapNode n = block->getNode(p); if(n.getContent() == CONTENT_IGNORE) { infostream<<"CONTENT_IGNORE at " <<"("<<p.X<<","<<p.Y<<","<<p.Z<<")" <<std::endl; erroneus_content = true; assert(0); } } if(erroneus_content) { assert(0); } } #endif #if 0 /* Generate a completely empty block */ if(block) { for(s16 z0=0; z0<MAP_BLOCKSIZE; z0++) for(s16 x0=0; x0<MAP_BLOCKSIZE; x0++) { for(s16 y0=0; y0<MAP_BLOCKSIZE; y0++) { MapNode n; n.setContent(CONTENT_AIR); block->setNode(v3s16(x0,y0,z0), n); } } } #endif if(enable_mapgen_debug_info == false) timer.stop(true); // Hide output return block; } #endif MapBlock * ServerMap::createBlock(v3s16 p) { /* Do not create over max mapgen limit */ if (blockpos_over_max_limit(p)) throw InvalidPositionException("createBlock(): pos. over max mapgen limit"); v2s16 p2d(p.X, p.Z); s16 block_y = p.Y; /* This will create or load a sector if not found in memory. If block exists on disk, it will be loaded. NOTE: On old save formats, this will be slow, as it generates lighting on blocks for them. */ MapSector *sector; try { sector = createSector(p2d); } catch (InvalidPositionException &e) { infostream<<"createBlock: createSector() failed"<<std::endl; throw e; } /* Try to get a block from the sector */ MapBlock *block = sector->getBlockNoCreateNoEx(block_y); if (block) { if(block->isDummy()) block->unDummify(); return block; } // Create blank block = sector->createBlankBlock(block_y); return block; } MapBlock * ServerMap::emergeBlock(v3s16 p, bool create_blank) { { MapBlock *block = getBlockNoCreateNoEx(p); if (block && !block->isDummy()) return block; } { MapBlock *block = loadBlock(p); if(block) return block; } if (create_blank) { MapSector *sector = createSector(v2s16(p.X, p.Z)); MapBlock *block = sector->createBlankBlock(p.Y); return block; } return NULL; } MapBlock *ServerMap::getBlockOrEmerge(v3s16 p3d) { MapBlock *block = getBlockNoCreateNoEx(p3d); if (block == NULL) m_emerge->enqueueBlockEmerge(PEER_ID_INEXISTENT, p3d, false); return block; } // N.B. This requires no synchronization, since data will not be modified unless // the VoxelManipulator being updated belongs to the same thread. void ServerMap::updateVManip(v3s16 pos) { Mapgen *mg = m_emerge->getCurrentMapgen(); if (!mg) return; MMVManip *vm = mg->vm; if (!vm) return; if (!vm->m_area.contains(pos)) return; s32 idx = vm->m_area.index(pos); vm->m_data[idx] = getNodeNoEx(pos); vm->m_flags[idx] &= ~VOXELFLAG_NO_DATA; vm->m_is_dirty = true; } s16 ServerMap::findGroundLevel(v2s16 p2d) { #if 0 /* Uh, just do something random... */ // Find existing map from top to down s16 max=63; s16 min=-64; v3s16 p(p2d.X, max, p2d.Y); for(; p.Y>min; p.Y--) { MapNode n = getNodeNoEx(p); if(n.getContent() != CONTENT_IGNORE) break; } if(p.Y == min) goto plan_b; // If this node is not air, go to plan b if(getNodeNoEx(p).getContent() != CONTENT_AIR) goto plan_b; // Search existing walkable and return it for(; p.Y>min; p.Y--) { MapNode n = getNodeNoEx(p); if(content_walkable(n.d) && n.getContent() != CONTENT_IGNORE) return p.Y; } // Move to plan b plan_b: #endif /* Determine from map generator noise functions */ s16 level = m_emerge->getGroundLevelAtPoint(p2d); return level; //double level = base_rock_level_2d(m_seed, p2d) + AVERAGE_MUD_AMOUNT; //return (s16)level; } bool ServerMap::loadFromFolders() { if (!dbase->initialized() && !fs::PathExists(m_savedir + DIR_DELIM + "map.sqlite")) return true; return false; } void ServerMap::createDirs(std::string path) { if (!fs::CreateAllDirs(path)) { m_dout<<"ServerMap: Failed to create directory " <<"\""<<path<<"\""<<std::endl; throw BaseException("ServerMap failed to create directory"); } } std::string ServerMap::getSectorDir(v2s16 pos, int layout) { char cc[9]; switch(layout) { case 1: porting::mt_snprintf(cc, sizeof(cc), "%.4x%.4x", (unsigned int) pos.X & 0xffff, (unsigned int) pos.Y & 0xffff); return m_savedir + DIR_DELIM + "sectors" + DIR_DELIM + cc; case 2: porting::mt_snprintf(cc, sizeof(cc), (std::string("%.3x") + DIR_DELIM + "%.3x").c_str(), (unsigned int) pos.X & 0xfff, (unsigned int) pos.Y & 0xfff); return m_savedir + DIR_DELIM + "sectors2" + DIR_DELIM + cc; default: assert(false); return ""; } } v2s16 ServerMap::getSectorPos(const std::string &dirname) { unsigned int x = 0, y = 0; int r; std::string component; fs::RemoveLastPathComponent(dirname, &component, 1); if(component.size() == 8) { // Old layout r = sscanf(component.c_str(), "%4x%4x", &x, &y); } else if(component.size() == 3) { // New layout fs::RemoveLastPathComponent(dirname, &component, 2); r = sscanf(component.c_str(), (std::string("%3x") + DIR_DELIM + "%3x").c_str(), &x, &y); // Sign-extend the 12 bit values up to 16 bits... if(x & 0x800) x |= 0xF000; if(y & 0x800) y |= 0xF000; } else { r = -1; } FATAL_ERROR_IF(r != 2, "getSectorPos()"); v2s16 pos((s16)x, (s16)y); return pos; } v3s16 ServerMap::getBlockPos(const std::string &sectordir, const std::string &blockfile) { v2s16 p2d = getSectorPos(sectordir); if(blockfile.size() != 4){ throw InvalidFilenameException("Invalid block filename"); } unsigned int y; int r = sscanf(blockfile.c_str(), "%4x", &y); if(r != 1) throw InvalidFilenameException("Invalid block filename"); return v3s16(p2d.X, y, p2d.Y); } std::string ServerMap::getBlockFilename(v3s16 p) { char cc[5]; porting::mt_snprintf(cc, sizeof(cc), "%.4x", (unsigned int)p.Y&0xffff); return cc; } void ServerMap::save(ModifiedState save_level) { if (!m_map_saving_enabled) { warningstream<<"Not saving map, saving disabled."<<std::endl; return; } if(save_level == MOD_STATE_CLEAN) infostream<<"ServerMap: Saving whole map, this can take time." <<std::endl; if (m_map_metadata_changed || save_level == MOD_STATE_CLEAN) { if (settings_mgr.saveMapMeta()) m_map_metadata_changed = false; } // Profile modified reasons Profiler modprofiler; u32 block_count = 0; u32 block_count_all = 0; // Number of blocks in memory // Don't do anything with sqlite unless something is really saved bool save_started = false; for (auto &sector_it : m_sectors) { MapSector *sector = sector_it.second; MapBlockVect blocks; sector->getBlocks(blocks); for (MapBlock *block : blocks) { block_count_all++; if(block->getModified() >= (u32)save_level) { // Lazy beginSave() if(!save_started) { beginSave(); save_started = true; } modprofiler.add(block->getModifiedReasonString(), 1); saveBlock(block); block_count++; } } } if(save_started) endSave(); /* Only print if something happened or saved whole map */ if(save_level == MOD_STATE_CLEAN || block_count != 0) { infostream<<"ServerMap: Written: " <<block_count<<" block files" <<", "<<block_count_all<<" blocks in memory." <<std::endl; PrintInfo(infostream); // ServerMap/ClientMap: infostream<<"Blocks modified by: "<<std::endl; modprofiler.print(infostream); } } void ServerMap::listAllLoadableBlocks(std::vector<v3s16> &dst) { if (loadFromFolders()) { errorstream << "Map::listAllLoadableBlocks(): Result will be missing " << "all blocks that are stored in flat files." << std::endl; } dbase->listAllLoadableBlocks(dst); if (dbase_ro) dbase_ro->listAllLoadableBlocks(dst); } void ServerMap::listAllLoadedBlocks(std::vector<v3s16> &dst) { for (auto &sector_it : m_sectors) { MapSector *sector = sector_it.second; MapBlockVect blocks; sector->getBlocks(blocks); for (MapBlock *block : blocks) { v3s16 p = block->getPos(); dst.push_back(p); } } } MapDatabase *ServerMap::createDatabase( const std::string &name, const std::string &savedir, Settings &conf) { if (name == "sqlite3") return new MapDatabaseSQLite3(savedir); if (name == "dummy") return new Database_Dummy(); #if USE_LEVELDB if (name == "leveldb") return new Database_LevelDB(savedir); #endif #if USE_REDIS if (name == "redis") return new Database_Redis(conf); #endif #if USE_POSTGRESQL if (name == "postgresql") { std::string connect_string; conf.getNoEx("pgsql_connection", connect_string); return new MapDatabasePostgreSQL(connect_string); } #endif throw BaseException(std::string("Database backend ") + name + " not supported."); } void ServerMap::beginSave() { dbase->beginSave(); } void ServerMap::endSave() { dbase->endSave(); } bool ServerMap::saveBlock(MapBlock *block) { return saveBlock(block, dbase); } bool ServerMap::saveBlock(MapBlock *block, MapDatabase *db) { v3s16 p3d = block->getPos(); // Dummy blocks are not written if (block->isDummy()) { warningstream << "saveBlock: Not writing dummy block " << PP(p3d) << std::endl; return true; } // Format used for writing u8 version = SER_FMT_VER_HIGHEST_WRITE; /* [0] u8 serialization version [1] data */ std::ostringstream o(std::ios_base::binary); o.write((char*) &version, 1); block->serialize(o, version, true); bool ret = db->saveBlock(p3d, o.str()); if (ret) { // We just wrote it to the disk so clear modified flag block->resetModified(); } return ret; } void ServerMap::loadBlock(const std::string &sectordir, const std::string &blockfile, MapSector *sector, bool save_after_load) { std::string fullpath = sectordir + DIR_DELIM + blockfile; try { std::ifstream is(fullpath.c_str(), std::ios_base::binary); if (!is.good()) throw FileNotGoodException("Cannot open block file"); v3s16 p3d = getBlockPos(sectordir, blockfile); v2s16 p2d(p3d.X, p3d.Z); assert(sector->getPos() == p2d); u8 version = SER_FMT_VER_INVALID; is.read((char*)&version, 1); if(is.fail()) throw SerializationError("ServerMap::loadBlock(): Failed" " to read MapBlock version"); /*u32 block_size = MapBlock::serializedLength(version); SharedBuffer<u8> data(block_size); is.read((char*)*data, block_size);*/ // This will always return a sector because we're the server //MapSector *sector = emergeSector(p2d); MapBlock *block = NULL; bool created_new = false; block = sector->getBlockNoCreateNoEx(p3d.Y); if(block == NULL) { block = sector->createBlankBlockNoInsert(p3d.Y); created_new = true; } // Read basic data block->deSerialize(is, version, true); // If it's a new block, insert it to the map if (created_new) { sector->insertBlock(block); ReflowScan scanner(this, m_emerge->ndef); scanner.scan(block, &m_transforming_liquid); } /* Save blocks loaded in old format in new format */ if(version < SER_FMT_VER_HIGHEST_WRITE || save_after_load) { saveBlock(block); // Should be in database now, so delete the old file fs::RecursiveDelete(fullpath); } // We just loaded it from the disk, so it's up-to-date. block->resetModified(); } catch(SerializationError &e) { warningstream<<"Invalid block data on disk " <<"fullpath="<<fullpath <<" (SerializationError). " <<"what()="<<e.what() <<std::endl; // Ignoring. A new one will be generated. abort(); // TODO: Backup file; name is in fullpath. } } void ServerMap::loadBlock(std::string *blob, v3s16 p3d, MapSector *sector, bool save_after_load) { try { std::istringstream is(*blob, std::ios_base::binary); u8 version = SER_FMT_VER_INVALID; is.read((char*)&version, 1); if(is.fail()) throw SerializationError("ServerMap::loadBlock(): Failed" " to read MapBlock version"); MapBlock *block = NULL; bool created_new = false; block = sector->getBlockNoCreateNoEx(p3d.Y); if(block == NULL) { block = sector->createBlankBlockNoInsert(p3d.Y); created_new = true; } // Read basic data block->deSerialize(is, version, true); // If it's a new block, insert it to the map if (created_new) { sector->insertBlock(block); ReflowScan scanner(this, m_emerge->ndef); scanner.scan(block, &m_transforming_liquid); } /* Save blocks loaded in old format in new format */ //if(version < SER_FMT_VER_HIGHEST_READ || save_after_load) // Only save if asked to; no need to update version if(save_after_load) saveBlock(block); // We just loaded it from, so it's up-to-date. block->resetModified(); } catch(SerializationError &e) { errorstream<<"Invalid block data in database" <<" ("<<p3d.X<<","<<p3d.Y<<","<<p3d.Z<<")" <<" (SerializationError): "<<e.what()<<std::endl; // TODO: Block should be marked as invalid in memory so that it is // not touched but the game can run if(g_settings->getBool("ignore_world_load_errors")){ errorstream<<"Ignoring block load error. Duck and cover! " <<"(ignore_world_load_errors)"<<std::endl; } else { throw SerializationError("Invalid block data in database"); } } } MapBlock* ServerMap::loadBlock(v3s16 blockpos) { bool created_new = (getBlockNoCreateNoEx(blockpos) == NULL); v2s16 p2d(blockpos.X, blockpos.Z); std::string ret; dbase->loadBlock(blockpos, &ret); if (!ret.empty()) { loadBlock(&ret, blockpos, createSector(p2d), false); } else if (dbase_ro) { dbase_ro->loadBlock(blockpos, &ret); if (!ret.empty()) { loadBlock(&ret, blockpos, createSector(p2d), false); } } else { // Not found in database, try the files // The directory layout we're going to load from. // 1 - original sectors/xxxxzzzz/ // 2 - new sectors2/xxx/zzz/ // If we load from anything but the latest structure, we will // immediately save to the new one, and remove the old. std::string sectordir1 = getSectorDir(p2d, 1); std::string sectordir; if (fs::PathExists(sectordir1)) { sectordir = sectordir1; } else { sectordir = getSectorDir(p2d, 2); } /* Make sure sector is loaded */ MapSector *sector = getSectorNoGenerateNoEx(p2d); /* Make sure file exists */ std::string blockfilename = getBlockFilename(blockpos); if (!fs::PathExists(sectordir + DIR_DELIM + blockfilename)) return NULL; /* Load block and save it to the database */ loadBlock(sectordir, blockfilename, sector, true); } MapBlock *block = getBlockNoCreateNoEx(blockpos); if (created_new && (block != NULL)) { std::map<v3s16, MapBlock*> modified_blocks; // Fix lighting if necessary voxalgo::update_block_border_lighting(this, block, modified_blocks); if (!modified_blocks.empty()) { //Modified lighting, send event MapEditEvent event; event.type = MEET_OTHER; std::map<v3s16, MapBlock *>::iterator it; for (it = modified_blocks.begin(); it != modified_blocks.end(); ++it) event.modified_blocks.insert(it->first); dispatchEvent(&event); } } return block; } bool ServerMap::deleteBlock(v3s16 blockpos) { if (!dbase->deleteBlock(blockpos)) return false; MapBlock *block = getBlockNoCreateNoEx(blockpos); if (block) { v2s16 p2d(blockpos.X, blockpos.Z); MapSector *sector = getSectorNoGenerateNoEx(p2d); if (!sector) return false; sector->deleteBlock(block); } return true; } void ServerMap::PrintInfo(std::ostream &out) { out<<"ServerMap: "; } bool ServerMap::repairBlockLight(v3s16 blockpos, std::map<v3s16, MapBlock *> *modified_blocks) { MapBlock *block = emergeBlock(blockpos, false); if (!block || !block->isGenerated()) return false; voxalgo::repair_block_light(this, block, modified_blocks); return true; } MMVManip::MMVManip(Map *map): VoxelManipulator(), m_map(map) { } void MMVManip::initialEmerge(v3s16 blockpos_min, v3s16 blockpos_max, bool load_if_inexistent) { TimeTaker timer1("initialEmerge", &emerge_time); // Units of these are MapBlocks v3s16 p_min = blockpos_min; v3s16 p_max = blockpos_max; VoxelArea block_area_nodes (p_min*MAP_BLOCKSIZE, (p_max+1)*MAP_BLOCKSIZE-v3s16(1,1,1)); u32 size_MB = block_area_nodes.getVolume()*4/1000000; if(size_MB >= 1) { infostream<<"initialEmerge: area: "; block_area_nodes.print(infostream); infostream<<" ("<<size_MB<<"MB)"; infostream<<std::endl; } addArea(block_area_nodes); for(s32 z=p_min.Z; z<=p_max.Z; z++) for(s32 y=p_min.Y; y<=p_max.Y; y++) for(s32 x=p_min.X; x<=p_max.X; x++) { u8 flags = 0; MapBlock *block; v3s16 p(x,y,z); std::map<v3s16, u8>::iterator n; n = m_loaded_blocks.find(p); if(n != m_loaded_blocks.end()) continue; bool block_data_inexistent = false; try { TimeTaker timer2("emerge load", &emerge_load_time); block = m_map->getBlockNoCreate(p); if(block->isDummy()) block_data_inexistent = true; else block->copyTo(*this); } catch(InvalidPositionException &e) { block_data_inexistent = true; } if(block_data_inexistent) { if (load_if_inexistent && !blockpos_over_max_limit(p)) { ServerMap *svrmap = (ServerMap *)m_map; block = svrmap->emergeBlock(p, false); if (block == NULL) block = svrmap->createBlock(p); block->copyTo(*this); } else { flags |= VMANIP_BLOCK_DATA_INEXIST; /* Mark area inexistent */ VoxelArea a(p*MAP_BLOCKSIZE, (p+1)*MAP_BLOCKSIZE-v3s16(1,1,1)); // Fill with VOXELFLAG_NO_DATA for(s32 z=a.MinEdge.Z; z<=a.MaxEdge.Z; z++) for(s32 y=a.MinEdge.Y; y<=a.MaxEdge.Y; y++) { s32 i = m_area.index(a.MinEdge.X,y,z); memset(&m_flags[i], VOXELFLAG_NO_DATA, MAP_BLOCKSIZE); } } } /*else if (block->getNode(0, 0, 0).getContent() == CONTENT_IGNORE) { // Mark that block was loaded as blank flags |= VMANIP_BLOCK_CONTAINS_CIGNORE; }*/ m_loaded_blocks[p] = flags; } m_is_dirty = false; } void MMVManip::blitBackAll(std::map<v3s16, MapBlock*> *modified_blocks, bool overwrite_generated) { if(m_area.getExtent() == v3s16(0,0,0)) return; /* Copy data of all blocks */ for (auto &loaded_block : m_loaded_blocks) { v3s16 p = loaded_block.first; MapBlock *block = m_map->getBlockNoCreateNoEx(p); bool existed = !(loaded_block.second & VMANIP_BLOCK_DATA_INEXIST); if (!existed || (block == NULL) || (!overwrite_generated && block->isGenerated())) continue; block->copyFrom(*this); block->raiseModified(MOD_STATE_WRITE_NEEDED, MOD_REASON_VMANIP); if(modified_blocks) (*modified_blocks)[p] = block; } } //END
pgimeno/minetest
src/map.cpp
C++
mit
60,044
/* Minetest Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com> 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. */ #pragma once #include <iostream> #include <sstream> #include <set> #include <map> #include <list> #include "irrlichttypes_bloated.h" #include "mapnode.h" #include "constants.h" #include "voxel.h" #include "modifiedstate.h" #include "util/container.h" #include "nodetimer.h" #include "map_settings_manager.h" #include "debug.h" class Settings; class MapDatabase; class ClientMap; class MapSector; class ServerMapSector; class MapBlock; class NodeMetadata; class IGameDef; class IRollbackManager; class EmergeManager; class ServerEnvironment; struct BlockMakeData; /* MapEditEvent */ #define MAPTYPE_BASE 0 #define MAPTYPE_SERVER 1 #define MAPTYPE_CLIENT 2 enum MapEditEventType{ // Node added (changed from air or something else to something) MEET_ADDNODE, // Node removed (changed to air) MEET_REMOVENODE, // Node swapped (changed without metadata change) MEET_SWAPNODE, // Node metadata changed MEET_BLOCK_NODE_METADATA_CHANGED, // Anything else (modified_blocks are set unsent) MEET_OTHER }; struct MapEditEvent { MapEditEventType type = MEET_OTHER; v3s16 p; MapNode n = CONTENT_AIR; std::set<v3s16> modified_blocks; bool is_private_change = false; MapEditEvent() = default; MapEditEvent * clone() { MapEditEvent *event = new MapEditEvent(); event->type = type; event->p = p; event->n = n; event->modified_blocks = modified_blocks; event->is_private_change = is_private_change; return event; } VoxelArea getArea() { switch(type){ case MEET_ADDNODE: return VoxelArea(p); case MEET_REMOVENODE: return VoxelArea(p); case MEET_SWAPNODE: return VoxelArea(p); case MEET_BLOCK_NODE_METADATA_CHANGED: { v3s16 np1 = p*MAP_BLOCKSIZE; v3s16 np2 = np1 + v3s16(1,1,1)*MAP_BLOCKSIZE - v3s16(1,1,1); return VoxelArea(np1, np2); } case MEET_OTHER: { VoxelArea a; for (v3s16 p : modified_blocks) { v3s16 np1 = p*MAP_BLOCKSIZE; v3s16 np2 = np1 + v3s16(1,1,1)*MAP_BLOCKSIZE - v3s16(1,1,1); a.addPoint(np1); a.addPoint(np2); } return a; } } return VoxelArea(); } }; class MapEventReceiver { public: // event shall be deleted by caller after the call. virtual void onMapEditEvent(MapEditEvent *event) = 0; }; class Map /*: public NodeContainer*/ { public: Map(std::ostream &dout, IGameDef *gamedef); virtual ~Map(); DISABLE_CLASS_COPY(Map); virtual s32 mapType() const { return MAPTYPE_BASE; } /* Drop (client) or delete (server) the map. */ virtual void drop() { delete this; } void addEventReceiver(MapEventReceiver *event_receiver); void removeEventReceiver(MapEventReceiver *event_receiver); // event shall be deleted by caller after the call. void dispatchEvent(MapEditEvent *event); // On failure returns NULL MapSector * getSectorNoGenerateNoExNoLock(v2s16 p2d); // Same as the above (there exists no lock anymore) MapSector * getSectorNoGenerateNoEx(v2s16 p2d); // On failure throws InvalidPositionException MapSector * getSectorNoGenerate(v2s16 p2d); // Gets an existing sector or creates an empty one //MapSector * getSectorCreate(v2s16 p2d); /* This is overloaded by ClientMap and ServerMap to allow their differing fetch methods. */ virtual MapSector * emergeSector(v2s16 p){ return NULL; } // Returns InvalidPositionException if not found MapBlock * getBlockNoCreate(v3s16 p); // Returns NULL if not found MapBlock * getBlockNoCreateNoEx(v3s16 p); /* Server overrides */ virtual MapBlock * emergeBlock(v3s16 p, bool create_blank=true) { return getBlockNoCreateNoEx(p); } inline const NodeDefManager * getNodeDefManager() { return m_nodedef; } // Returns InvalidPositionException if not found bool isNodeUnderground(v3s16 p); bool isValidPosition(v3s16 p); // throws InvalidPositionException if not found void setNode(v3s16 p, MapNode & n); // Returns a CONTENT_IGNORE node if not found // If is_valid_position is not NULL then this will be set to true if the // position is valid, otherwise false MapNode getNodeNoEx(v3s16 p, bool *is_valid_position = NULL); /* These handle lighting but not faces. */ void addNodeAndUpdate(v3s16 p, MapNode n, std::map<v3s16, MapBlock*> &modified_blocks, bool remove_metadata = true); void removeNodeAndUpdate(v3s16 p, std::map<v3s16, MapBlock*> &modified_blocks); /* Wrappers for the latter ones. These emit events. Return true if succeeded, false if not. */ bool addNodeWithEvent(v3s16 p, MapNode n, bool remove_metadata = true); bool removeNodeWithEvent(v3s16 p); // Call these before and after saving of many blocks virtual void beginSave() {} virtual void endSave() {} virtual void save(ModifiedState save_level) { FATAL_ERROR("FIXME"); } // Server implements these. // Client leaves them as no-op. virtual bool saveBlock(MapBlock *block) { return false; } virtual bool deleteBlock(v3s16 blockpos) { return false; } /* Updates usage timers and unloads unused blocks and sectors. Saves modified blocks before unloading on MAPTYPE_SERVER. */ void timerUpdate(float dtime, float unload_timeout, u32 max_loaded_blocks, std::vector<v3s16> *unloaded_blocks=NULL); /* Unloads all blocks with a zero refCount(). Saves modified blocks before unloading on MAPTYPE_SERVER. */ void unloadUnreferencedBlocks(std::vector<v3s16> *unloaded_blocks=NULL); // Deletes sectors and their blocks from memory // Takes cache into account // If deleted sector is in sector cache, clears cache void deleteSectors(std::vector<v2s16> &list); // For debug printing. Prints "Map: ", "ServerMap: " or "ClientMap: " virtual void PrintInfo(std::ostream &out); void transformLiquids(std::map<v3s16, MapBlock*> & modified_blocks, ServerEnvironment *env); /* Node metadata These are basically coordinate wrappers to MapBlock */ std::vector<v3s16> findNodesWithMetadata(v3s16 p1, v3s16 p2); NodeMetadata *getNodeMetadata(v3s16 p); /** * Sets metadata for a node. * This method sets the metadata for a given node. * On success, it returns @c true and the object pointed to * by @p meta is then managed by the system and should * not be deleted by the caller. * * In case of failure, the method returns @c false and the * caller is still responsible for deleting the object! * * @param p node coordinates * @param meta pointer to @c NodeMetadata object * @return @c true on success, false on failure */ bool setNodeMetadata(v3s16 p, NodeMetadata *meta); void removeNodeMetadata(v3s16 p); /* Node Timers These are basically coordinate wrappers to MapBlock */ NodeTimer getNodeTimer(v3s16 p); void setNodeTimer(const NodeTimer &t); void removeNodeTimer(v3s16 p); /* Misc. */ std::map<v2s16, MapSector*> *getSectorsPtr(){return &m_sectors;} /* Variables */ void transforming_liquid_add(v3s16 p); bool isBlockOccluded(MapBlock *block, v3s16 cam_pos_nodes); protected: friend class LuaVoxelManip; std::ostream &m_dout; // A bit deprecated, could be removed IGameDef *m_gamedef; std::set<MapEventReceiver*> m_event_receivers; std::map<v2s16, MapSector*> m_sectors; // Be sure to set this to NULL when the cached sector is deleted MapSector *m_sector_cache = nullptr; v2s16 m_sector_cache_p; // Queued transforming water nodes UniqueQueue<v3s16> m_transforming_liquid; // This stores the properties of the nodes on the map. const NodeDefManager *m_nodedef; bool isOccluded(v3s16 p0, v3s16 p1, float step, float stepfac, float start_off, float end_off, u32 needed_count); private: f32 m_transforming_liquid_loop_count_multiplier = 1.0f; u32 m_unprocessed_count = 0; u64 m_inc_trending_up_start_time = 0; // milliseconds bool m_queue_size_timer_started = false; }; /* ServerMap This is the only map class that is able to generate map. */ class ServerMap : public Map { public: /* savedir: directory to which map data should be saved */ ServerMap(const std::string &savedir, IGameDef *gamedef, EmergeManager *emerge); ~ServerMap(); s32 mapType() const { return MAPTYPE_SERVER; } /* Get a sector from somewhere. - Check memory - Check disk (doesn't load blocks) - Create blank one */ MapSector *createSector(v2s16 p); /* Blocks are generated by using these and makeBlock(). */ bool blockpos_over_mapgen_limit(v3s16 p); bool initBlockMake(v3s16 blockpos, BlockMakeData *data); void finishBlockMake(BlockMakeData *data, std::map<v3s16, MapBlock*> *changed_blocks); /* Get a block from somewhere. - Memory - Create blank */ MapBlock *createBlock(v3s16 p); /* Forcefully get a block from somewhere. - Memory - Load from disk - Create blank filled with CONTENT_IGNORE */ MapBlock *emergeBlock(v3s16 p, bool create_blank=true); /* Try to get a block. If it does not exist in memory, add it to the emerge queue. - Memory - Emerge Queue (deferred disk or generate) */ MapBlock *getBlockOrEmerge(v3s16 p3d); // Helper for placing objects on ground level s16 findGroundLevel(v2s16 p2d); /* Misc. helper functions for fiddling with directory and file names when saving */ void createDirs(std::string path); // returns something like "map/sectors/xxxxxxxx" std::string getSectorDir(v2s16 pos, int layout = 2); // dirname: final directory name v2s16 getSectorPos(const std::string &dirname); v3s16 getBlockPos(const std::string &sectordir, const std::string &blockfile); static std::string getBlockFilename(v3s16 p); /* Database functions */ static MapDatabase *createDatabase(const std::string &name, const std::string &savedir, Settings &conf); // Returns true if the database file does not exist bool loadFromFolders(); // Call these before and after saving of blocks void beginSave(); void endSave(); void save(ModifiedState save_level); void listAllLoadableBlocks(std::vector<v3s16> &dst); void listAllLoadedBlocks(std::vector<v3s16> &dst); MapgenParams *getMapgenParams(); bool saveBlock(MapBlock *block); static bool saveBlock(MapBlock *block, MapDatabase *db); // This will generate a sector with getSector if not found. void loadBlock(const std::string &sectordir, const std::string &blockfile, MapSector *sector, bool save_after_load=false); MapBlock* loadBlock(v3s16 p); // Database version void loadBlock(std::string *blob, v3s16 p3d, MapSector *sector, bool save_after_load=false); bool deleteBlock(v3s16 blockpos); void updateVManip(v3s16 pos); // For debug printing virtual void PrintInfo(std::ostream &out); bool isSavingEnabled(){ return m_map_saving_enabled; } u64 getSeed(); s16 getWaterLevel(); /*! * Fixes lighting in one map block. * May modify other blocks as well, as light can spread * out of the specified block. * Returns false if the block is not generated (so nothing * changed), true otherwise. */ bool repairBlockLight(v3s16 blockpos, std::map<v3s16, MapBlock *> *modified_blocks); MapSettingsManager settings_mgr; private: // Emerge manager EmergeManager *m_emerge; std::string m_savedir; bool m_map_saving_enabled; #if 0 // Chunk size in MapSectors // If 0, chunks are disabled. s16 m_chunksize; // Chunks core::map<v2s16, MapChunk*> m_chunks; #endif /* Metadata is re-written on disk only if this is true. This is reset to false when written on disk. */ bool m_map_metadata_changed = true; MapDatabase *dbase = nullptr; MapDatabase *dbase_ro = nullptr; }; #define VMANIP_BLOCK_DATA_INEXIST 1 #define VMANIP_BLOCK_CONTAINS_CIGNORE 2 class MMVManip : public VoxelManipulator { public: MMVManip(Map *map); virtual ~MMVManip() = default; virtual void clear() { VoxelManipulator::clear(); m_loaded_blocks.clear(); } void initialEmerge(v3s16 blockpos_min, v3s16 blockpos_max, bool load_if_inexistent = true); // This is much faster with big chunks of generated data void blitBackAll(std::map<v3s16, MapBlock*> * modified_blocks, bool overwrite_generated = true); bool m_is_dirty = false; protected: Map *m_map; /* key = blockpos value = flags describing the block */ std::map<v3s16, u8> m_loaded_blocks; };
pgimeno/minetest
src/map.h
C++
mit
12,858
/* Minetest Copyright (C) 2010-2013 kwolekr, Ryan Kwolek <kwolekr@minetest.net> 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 "debug.h" #include "filesys.h" #include "log.h" #include "mapgen/mapgen.h" #include "settings.h" #include "map_settings_manager.h" MapSettingsManager::MapSettingsManager(Settings *user_settings, const std::string &map_meta_path): m_map_meta_path(map_meta_path), m_map_settings(new Settings()), m_user_settings(user_settings) { assert(m_user_settings != NULL); } MapSettingsManager::~MapSettingsManager() { delete m_map_settings; delete mapgen_params; } bool MapSettingsManager::getMapSetting( const std::string &name, std::string *value_out) { if (m_map_settings->getNoEx(name, *value_out)) return true; // Compatibility kludge if (m_user_settings == g_settings && name == "seed") return m_user_settings->getNoEx("fixed_map_seed", *value_out); return m_user_settings->getNoEx(name, *value_out); } bool MapSettingsManager::getMapSettingNoiseParams( const std::string &name, NoiseParams *value_out) { return m_map_settings->getNoiseParams(name, *value_out) || m_user_settings->getNoiseParams(name, *value_out); } bool MapSettingsManager::setMapSetting( const std::string &name, const std::string &value, bool override_meta) { if (mapgen_params) return false; if (override_meta) m_map_settings->set(name, value); else m_map_settings->setDefault(name, value); return true; } bool MapSettingsManager::setMapSettingNoiseParams( const std::string &name, const NoiseParams *value, bool override_meta) { if (mapgen_params) return false; m_map_settings->setNoiseParams(name, *value, !override_meta); return true; } bool MapSettingsManager::loadMapMeta() { std::ifstream is(m_map_meta_path.c_str(), std::ios_base::binary); if (!is.good()) { errorstream << "loadMapMeta: could not open " << m_map_meta_path << std::endl; return false; } if (!m_map_settings->parseConfigLines(is, "[end_of_params]")) { errorstream << "loadMapMeta: [end_of_params] not found!" << std::endl; return false; } return true; } bool MapSettingsManager::saveMapMeta() { // If mapgen params haven't been created yet; abort if (!mapgen_params) return false; if (!fs::CreateAllDirs(fs::RemoveLastPathComponent(m_map_meta_path))) { errorstream << "saveMapMeta: could not create dirs to " << m_map_meta_path; return false; } std::ostringstream oss(std::ios_base::binary); Settings conf; mapgen_params->MapgenParams::writeParams(&conf); mapgen_params->writeParams(&conf); conf.writeLines(oss); // NOTE: If there are ever types of map settings other than // those relating to map generation, save them here oss << "[end_of_params]\n"; if (!fs::safeWriteToFile(m_map_meta_path, oss.str())) { errorstream << "saveMapMeta: could not write " << m_map_meta_path << std::endl; return false; } return true; } MapgenParams *MapSettingsManager::makeMapgenParams() { if (mapgen_params) return mapgen_params; assert(m_user_settings != NULL); assert(m_map_settings != NULL); // At this point, we have (in order of precedence): // 1). m_mapgen_settings->m_settings containing map_meta.txt settings or // explicit overrides from scripts // 2). m_mapgen_settings->m_defaults containing script-set mgparams without // overrides // 3). g_settings->m_settings containing all user-specified config file // settings // 4). g_settings->m_defaults containing any low-priority settings from // scripts, e.g. mods using Lua as an enhanced config file) // Now, get the mapgen type so we can create the appropriate MapgenParams std::string mg_name; MapgenType mgtype = getMapSetting("mg_name", &mg_name) ? Mapgen::getMapgenType(mg_name) : MAPGEN_DEFAULT; if (mgtype == MAPGEN_INVALID) { errorstream << "EmergeManager: mapgen '" << mg_name << "' not valid; falling back to " << Mapgen::getMapgenName(MAPGEN_DEFAULT) << std::endl; mgtype = MAPGEN_DEFAULT; } // Create our MapgenParams MapgenParams *params = Mapgen::createMapgenParams(mgtype); if (!params) return nullptr; params->mgtype = mgtype; // Load the rest of the mapgen params from our active settings params->MapgenParams::readParams(m_user_settings); params->MapgenParams::readParams(m_map_settings); params->readParams(m_user_settings); params->readParams(m_map_settings); // Hold onto our params mapgen_params = params; return params; }
pgimeno/minetest
src/map_settings_manager.cpp
C++
mit
5,112
/* Minetest Copyright (C) 2010-2013 kwolekr, Ryan Kwolek <kwolekr@minetest.net> 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. */ #pragma once #include <string> class Settings; struct NoiseParams; struct MapgenParams; /* MapSettingsManager is a centralized object for management (creating, loading, storing, saving, etc.) of config settings related to the Map. It has two phases: the initial r/w "gather and modify settings" state, and the final r/o "read and save settings" state. The typical use case is, in order, as follows: - Create a MapSettingsManager object - Try to load map metadata into it from the metadata file - Manually view and modify the current configuration as desired through a Settings-like interface - When all modifications are finished, create a 'Parameters' object containing the finalized, active parameters. This could be passed along to whichever Map-related objects that may require it. - Save these active settings to the metadata file when requested */ class MapSettingsManager { public: MapSettingsManager(Settings *user_settings, const std::string &map_meta_path); ~MapSettingsManager(); // Finalized map generation parameters MapgenParams *mapgen_params = nullptr; bool getMapSetting(const std::string &name, std::string *value_out); bool getMapSettingNoiseParams( const std::string &name, NoiseParams *value_out); // Note: Map config becomes read-only after makeMapgenParams() gets called // (i.e. mapgen_params is non-NULL). Attempts to set map config after // params have been finalized will result in failure. bool setMapSetting(const std::string &name, const std::string &value, bool override_meta = false); bool setMapSettingNoiseParams(const std::string &name, const NoiseParams *value, bool override_meta = false); bool loadMapMeta(); bool saveMapMeta(); MapgenParams *makeMapgenParams(); private: std::string m_map_meta_path; Settings *m_map_settings; Settings *m_user_settings; };
pgimeno/minetest
src/map_settings_manager.h
C++
mit
2,641
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> 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 "mapblock.h" #include <sstream> #include "map.h" #include "light.h" #include "nodedef.h" #include "nodemetadata.h" #include "gamedef.h" #include "log.h" #include "nameidmapping.h" #include "content_mapnode.h" // For legacy name-id mapping #include "content_nodemeta.h" // For legacy deserialization #include "serialization.h" #ifndef SERVER #include "client/mapblock_mesh.h" #endif #include "porting.h" #include "util/string.h" #include "util/serialize.h" #include "util/basic_macros.h" static const char *modified_reason_strings[] = { "initial", "reallocate", "setIsUnderground", "setLightingExpired", "setGenerated", "setNode", "setNodeNoCheck", "setTimestamp", "NodeMetaRef::reportMetadataChange", "clearAllObjects", "Timestamp expired (step)", "addActiveObjectRaw", "removeRemovedObjects/remove", "removeRemovedObjects/deactivate", "Stored list cleared in activateObjects due to overflow", "deactivateFarObjects: Static data moved in", "deactivateFarObjects: Static data moved out", "deactivateFarObjects: Static data changed considerably", "finishBlockMake: expireDayNightDiff", "unknown", }; /* MapBlock */ MapBlock::MapBlock(Map *parent, v3s16 pos, IGameDef *gamedef, bool dummy): m_parent(parent), m_pos(pos), m_pos_relative(pos * MAP_BLOCKSIZE), m_gamedef(gamedef) { if (!dummy) reallocate(); } MapBlock::~MapBlock() { #ifndef SERVER { delete mesh; mesh = nullptr; } #endif delete[] data; } bool MapBlock::isValidPositionParent(v3s16 p) { if (isValidPosition(p)) { return true; } return m_parent->isValidPosition(getPosRelative() + p); } MapNode MapBlock::getNodeParent(v3s16 p, bool *is_valid_position) { if (!isValidPosition(p)) return m_parent->getNodeNoEx(getPosRelative() + p, is_valid_position); if (!data) { if (is_valid_position) *is_valid_position = false; return {CONTENT_IGNORE}; } if (is_valid_position) *is_valid_position = true; return data[p.Z * zstride + p.Y * ystride + p.X]; } std::string MapBlock::getModifiedReasonString() { std::string reason; const u32 ubound = MYMIN(sizeof(m_modified_reason) * CHAR_BIT, ARRLEN(modified_reason_strings)); for (u32 i = 0; i != ubound; i++) { if ((m_modified_reason & (1 << i)) == 0) continue; reason += modified_reason_strings[i]; reason += ", "; } if (reason.length() > 2) reason.resize(reason.length() - 2); return reason; } void MapBlock::copyTo(VoxelManipulator &dst) { v3s16 data_size(MAP_BLOCKSIZE, MAP_BLOCKSIZE, MAP_BLOCKSIZE); VoxelArea data_area(v3s16(0,0,0), data_size - v3s16(1,1,1)); // Copy from data to VoxelManipulator dst.copyFrom(data, data_area, v3s16(0,0,0), getPosRelative(), data_size); } void MapBlock::copyFrom(VoxelManipulator &dst) { v3s16 data_size(MAP_BLOCKSIZE, MAP_BLOCKSIZE, MAP_BLOCKSIZE); VoxelArea data_area(v3s16(0,0,0), data_size - v3s16(1,1,1)); // Copy from VoxelManipulator to data dst.copyTo(data, data_area, v3s16(0,0,0), getPosRelative(), data_size); } void MapBlock::actuallyUpdateDayNightDiff() { const NodeDefManager *nodemgr = m_gamedef->ndef(); // Running this function un-expires m_day_night_differs m_day_night_differs_expired = false; if (!data) { m_day_night_differs = false; return; } bool differs = false; /* Check if any lighting value differs */ MapNode previous_n(CONTENT_IGNORE); for (u32 i = 0; i < nodecount; i++) { MapNode n = data[i]; // If node is identical to previous node, don't verify if it differs if (n == previous_n) continue; differs = !n.isLightDayNightEq(nodemgr); if (differs) break; previous_n = n; } /* If some lighting values differ, check if the whole thing is just air. If it is just air, differs = false */ if (differs) { bool only_air = true; for (u32 i = 0; i < nodecount; i++) { MapNode &n = data[i]; if (n.getContent() != CONTENT_AIR) { only_air = false; break; } } if (only_air) differs = false; } // Set member variable m_day_night_differs = differs; } void MapBlock::expireDayNightDiff() { if (!data) { m_day_night_differs = false; m_day_night_differs_expired = false; return; } m_day_night_differs_expired = true; } s16 MapBlock::getGroundLevel(v2s16 p2d) { if(isDummy()) return -3; try { s16 y = MAP_BLOCKSIZE-1; for(; y>=0; y--) { MapNode n = getNodeRef(p2d.X, y, p2d.Y); if (m_gamedef->ndef()->get(n).walkable) { if(y == MAP_BLOCKSIZE-1) return -2; return y; } } return -1; } catch(InvalidPositionException &e) { return -3; } } /* Serialization */ // List relevant id-name pairs for ids in the block using nodedef // Renumbers the content IDs (starting at 0 and incrementing // use static memory requires about 65535 * sizeof(int) ram in order to be // sure we can handle all content ids. But it's absolutely worth it as it's // a speedup of 4 for one of the major time consuming functions on storing // mapblocks. static content_t getBlockNodeIdMapping_mapping[USHRT_MAX + 1]; static void getBlockNodeIdMapping(NameIdMapping *nimap, MapNode *nodes, const NodeDefManager *nodedef) { memset(getBlockNodeIdMapping_mapping, 0xFF, (USHRT_MAX + 1) * sizeof(content_t)); std::set<content_t> unknown_contents; content_t id_counter = 0; for (u32 i = 0; i < MapBlock::nodecount; i++) { content_t global_id = nodes[i].getContent(); content_t id = CONTENT_IGNORE; // Try to find an existing mapping if (getBlockNodeIdMapping_mapping[global_id] != 0xFFFF) { id = getBlockNodeIdMapping_mapping[global_id]; } else { // We have to assign a new mapping id = id_counter++; getBlockNodeIdMapping_mapping[global_id] = id; const ContentFeatures &f = nodedef->get(global_id); const std::string &name = f.name; if (name.empty()) unknown_contents.insert(global_id); else nimap->set(id, name); } // Update the MapNode nodes[i].setContent(id); } for (u16 unknown_content : unknown_contents) { errorstream << "getBlockNodeIdMapping(): IGNORING ERROR: " << "Name for node id " << unknown_content << " not known" << std::endl; } } // Correct ids in the block to match nodedef based on names. // Unknown ones are added to nodedef. // Will not update itself to match id-name pairs in nodedef. static void correctBlockNodeIds(const NameIdMapping *nimap, MapNode *nodes, IGameDef *gamedef) { const NodeDefManager *nodedef = gamedef->ndef(); // This means the block contains incorrect ids, and we contain // the information to convert those to names. // nodedef contains information to convert our names to globally // correct ids. std::unordered_set<content_t> unnamed_contents; std::unordered_set<std::string> unallocatable_contents; bool previous_exists = false; content_t previous_local_id = CONTENT_IGNORE; content_t previous_global_id = CONTENT_IGNORE; for (u32 i = 0; i < MapBlock::nodecount; i++) { content_t local_id = nodes[i].getContent(); // If previous node local_id was found and same than before, don't lookup maps // apply directly previous resolved id // This permits to massively improve loading performance when nodes are similar // example: default:air, default:stone are massively present if (previous_exists && local_id == previous_local_id) { nodes[i].setContent(previous_global_id); continue; } std::string name; if (!nimap->getName(local_id, name)) { unnamed_contents.insert(local_id); previous_exists = false; continue; } content_t global_id; if (!nodedef->getId(name, global_id)) { global_id = gamedef->allocateUnknownNodeId(name); if (global_id == CONTENT_IGNORE) { unallocatable_contents.insert(name); previous_exists = false; continue; } } nodes[i].setContent(global_id); // Save previous node local_id & global_id result previous_local_id = local_id; previous_global_id = global_id; previous_exists = true; } for (const content_t c: unnamed_contents) { errorstream << "correctBlockNodeIds(): IGNORING ERROR: " << "Block contains id " << c << " with no name mapping" << std::endl; } for (const std::string &node_name: unallocatable_contents) { errorstream << "correctBlockNodeIds(): IGNORING ERROR: " << "Could not allocate global id for node name \"" << node_name << "\"" << std::endl; } } void MapBlock::serialize(std::ostream &os, u8 version, bool disk) { if(!ser_ver_supported(version)) throw VersionMismatchException("ERROR: MapBlock format not supported"); if (!data) throw SerializationError("ERROR: Not writing dummy block."); FATAL_ERROR_IF(version < SER_FMT_VER_LOWEST_WRITE, "Serialisation version error"); // First byte u8 flags = 0; if(is_underground) flags |= 0x01; if(getDayNightDiff()) flags |= 0x02; if (!m_generated) flags |= 0x08; writeU8(os, flags); if (version >= 27) { writeU16(os, m_lighting_complete); } /* Bulk node data */ NameIdMapping nimap; if(disk) { MapNode *tmp_nodes = new MapNode[nodecount]; for(u32 i=0; i<nodecount; i++) tmp_nodes[i] = data[i]; getBlockNodeIdMapping(&nimap, tmp_nodes, m_gamedef->ndef()); u8 content_width = 2; u8 params_width = 2; writeU8(os, content_width); writeU8(os, params_width); MapNode::serializeBulk(os, version, tmp_nodes, nodecount, content_width, params_width, true); delete[] tmp_nodes; } else { u8 content_width = 2; u8 params_width = 2; writeU8(os, content_width); writeU8(os, params_width); MapNode::serializeBulk(os, version, data, nodecount, content_width, params_width, true); } /* Node metadata */ std::ostringstream oss(std::ios_base::binary); m_node_metadata.serialize(oss, version, disk); compressZlib(oss.str(), os); /* Data that goes to disk, but not the network */ if(disk) { if(version <= 24){ // Node timers m_node_timers.serialize(os, version); } // Static objects m_static_objects.serialize(os); // Timestamp writeU32(os, getTimestamp()); // Write block-specific node definition id mapping nimap.serialize(os); if(version >= 25){ // Node timers m_node_timers.serialize(os, version); } } } void MapBlock::serializeNetworkSpecific(std::ostream &os) { if (!data) { throw SerializationError("ERROR: Not writing dummy block."); } writeU8(os, 2); // version } void MapBlock::deSerialize(std::istream &is, u8 version, bool disk) { if(!ser_ver_supported(version)) throw VersionMismatchException("ERROR: MapBlock format not supported"); TRACESTREAM(<<"MapBlock::deSerialize "<<PP(getPos())<<std::endl); m_day_night_differs_expired = false; if(version <= 21) { deSerialize_pre22(is, version, disk); return; } u8 flags = readU8(is); is_underground = (flags & 0x01) != 0; m_day_night_differs = (flags & 0x02) != 0; if (version < 27) m_lighting_complete = 0xFFFF; else m_lighting_complete = readU16(is); m_generated = (flags & 0x08) == 0; /* Bulk node data */ TRACESTREAM(<<"MapBlock::deSerialize "<<PP(getPos()) <<": Bulk node data"<<std::endl); u8 content_width = readU8(is); u8 params_width = readU8(is); if(content_width != 1 && content_width != 2) throw SerializationError("MapBlock::deSerialize(): invalid content_width"); if(params_width != 2) throw SerializationError("MapBlock::deSerialize(): invalid params_width"); MapNode::deSerializeBulk(is, version, data, nodecount, content_width, params_width, true); /* NodeMetadata */ TRACESTREAM(<<"MapBlock::deSerialize "<<PP(getPos()) <<": Node metadata"<<std::endl); // Ignore errors try { std::ostringstream oss(std::ios_base::binary); decompressZlib(is, oss); std::istringstream iss(oss.str(), std::ios_base::binary); if (version >= 23) m_node_metadata.deSerialize(iss, m_gamedef->idef()); else content_nodemeta_deserialize_legacy(iss, &m_node_metadata, &m_node_timers, m_gamedef->idef()); } catch(SerializationError &e) { warningstream<<"MapBlock::deSerialize(): Ignoring an error" <<" while deserializing node metadata at (" <<PP(getPos())<<": "<<e.what()<<std::endl; } /* Data that is only on disk */ if(disk) { // Node timers if(version == 23){ // Read unused zero readU8(is); } if(version == 24){ TRACESTREAM(<<"MapBlock::deSerialize "<<PP(getPos()) <<": Node timers (ver==24)"<<std::endl); m_node_timers.deSerialize(is, version); } // Static objects TRACESTREAM(<<"MapBlock::deSerialize "<<PP(getPos()) <<": Static objects"<<std::endl); m_static_objects.deSerialize(is); // Timestamp TRACESTREAM(<<"MapBlock::deSerialize "<<PP(getPos()) <<": Timestamp"<<std::endl); setTimestamp(readU32(is)); m_disk_timestamp = m_timestamp; // Dynamically re-set ids based on node names TRACESTREAM(<<"MapBlock::deSerialize "<<PP(getPos()) <<": NameIdMapping"<<std::endl); NameIdMapping nimap; nimap.deSerialize(is); correctBlockNodeIds(&nimap, data, m_gamedef); if(version >= 25){ TRACESTREAM(<<"MapBlock::deSerialize "<<PP(getPos()) <<": Node timers (ver>=25)"<<std::endl); m_node_timers.deSerialize(is, version); } } TRACESTREAM(<<"MapBlock::deSerialize "<<PP(getPos()) <<": Done."<<std::endl); } void MapBlock::deSerializeNetworkSpecific(std::istream &is) { try { readU8(is); //const u8 version = readU8(is); //if (version != 1) //throw SerializationError("unsupported MapBlock version"); } catch(SerializationError &e) { warningstream<<"MapBlock::deSerializeNetworkSpecific(): Ignoring an error" <<": "<<e.what()<<std::endl; } } /* Legacy serialization */ void MapBlock::deSerialize_pre22(std::istream &is, u8 version, bool disk) { // Initialize default flags is_underground = false; m_day_night_differs = false; m_lighting_complete = 0xFFFF; m_generated = true; // Make a temporary buffer u32 ser_length = MapNode::serializedLength(version); SharedBuffer<u8> databuf_nodelist(nodecount * ser_length); // These have no compression if (version <= 3 || version == 5 || version == 6) { char tmp; is.read(&tmp, 1); if (is.gcount() != 1) throw SerializationError(std::string(FUNCTION_NAME) + ": not enough input data"); is_underground = tmp; is.read((char *)*databuf_nodelist, nodecount * ser_length); if ((u32)is.gcount() != nodecount * ser_length) throw SerializationError(std::string(FUNCTION_NAME) + ": not enough input data"); } else if (version <= 10) { u8 t8; is.read((char *)&t8, 1); is_underground = t8; { // Uncompress and set material data std::ostringstream os(std::ios_base::binary); decompress(is, os, version); std::string s = os.str(); if (s.size() != nodecount) throw SerializationError(std::string(FUNCTION_NAME) + ": not enough input data"); for (u32 i = 0; i < s.size(); i++) { databuf_nodelist[i*ser_length] = s[i]; } } { // Uncompress and set param data std::ostringstream os(std::ios_base::binary); decompress(is, os, version); std::string s = os.str(); if (s.size() != nodecount) throw SerializationError(std::string(FUNCTION_NAME) + ": not enough input data"); for (u32 i = 0; i < s.size(); i++) { databuf_nodelist[i*ser_length + 1] = s[i]; } } if (version >= 10) { // Uncompress and set param2 data std::ostringstream os(std::ios_base::binary); decompress(is, os, version); std::string s = os.str(); if (s.size() != nodecount) throw SerializationError(std::string(FUNCTION_NAME) + ": not enough input data"); for (u32 i = 0; i < s.size(); i++) { databuf_nodelist[i*ser_length + 2] = s[i]; } } } else { // All other versions (10 to 21) u8 flags; is.read((char*)&flags, 1); is_underground = (flags & 0x01) != 0; m_day_night_differs = (flags & 0x02) != 0; if(version >= 18) m_generated = (flags & 0x08) == 0; // Uncompress data std::ostringstream os(std::ios_base::binary); decompress(is, os, version); std::string s = os.str(); if (s.size() != nodecount * 3) throw SerializationError(std::string(FUNCTION_NAME) + ": decompress resulted in size other than nodecount*3"); // deserialize nodes from buffer for (u32 i = 0; i < nodecount; i++) { databuf_nodelist[i*ser_length] = s[i]; databuf_nodelist[i*ser_length + 1] = s[i+nodecount]; databuf_nodelist[i*ser_length + 2] = s[i+nodecount*2]; } /* NodeMetadata */ if (version >= 14) { // Ignore errors try { if (version <= 15) { std::string data = deSerializeString(is); std::istringstream iss(data, std::ios_base::binary); content_nodemeta_deserialize_legacy(iss, &m_node_metadata, &m_node_timers, m_gamedef->idef()); } else { //std::string data = deSerializeLongString(is); std::ostringstream oss(std::ios_base::binary); decompressZlib(is, oss); std::istringstream iss(oss.str(), std::ios_base::binary); content_nodemeta_deserialize_legacy(iss, &m_node_metadata, &m_node_timers, m_gamedef->idef()); } } catch(SerializationError &e) { warningstream<<"MapBlock::deSerialize(): Ignoring an error" <<" while deserializing node metadata"<<std::endl; } } } // Deserialize node data for (u32 i = 0; i < nodecount; i++) { data[i].deSerialize(&databuf_nodelist[i * ser_length], version); } if (disk) { /* Versions up from 9 have block objects. (DEPRECATED) */ if (version >= 9) { u16 count = readU16(is); // Not supported and length not known if count is not 0 if(count != 0){ warningstream<<"MapBlock::deSerialize_pre22(): " <<"Ignoring stuff coming at and after MBOs"<<std::endl; return; } } /* Versions up from 15 have static objects. */ if (version >= 15) m_static_objects.deSerialize(is); // Timestamp if (version >= 17) { setTimestamp(readU32(is)); m_disk_timestamp = m_timestamp; } else { setTimestamp(BLOCK_TIMESTAMP_UNDEFINED); } // Dynamically re-set ids based on node names NameIdMapping nimap; // If supported, read node definition id mapping if (version >= 21) { nimap.deSerialize(is); // Else set the legacy mapping } else { content_mapnode_get_name_id_mapping(&nimap); } correctBlockNodeIds(&nimap, data, m_gamedef); } // Legacy data changes // This code has to convert from pre-22 to post-22 format. const NodeDefManager *nodedef = m_gamedef->ndef(); for(u32 i=0; i<nodecount; i++) { const ContentFeatures &f = nodedef->get(data[i].getContent()); // Mineral if(nodedef->getId("default:stone") == data[i].getContent() && data[i].getParam1() == 1) { data[i].setContent(nodedef->getId("default:stone_with_coal")); data[i].setParam1(0); } else if(nodedef->getId("default:stone") == data[i].getContent() && data[i].getParam1() == 2) { data[i].setContent(nodedef->getId("default:stone_with_iron")); data[i].setParam1(0); } // facedir_simple if(f.legacy_facedir_simple) { data[i].setParam2(data[i].getParam1()); data[i].setParam1(0); } // wall_mounted if(f.legacy_wallmounted) { u8 wallmounted_new_to_old[8] = {0x04, 0x08, 0x01, 0x02, 0x10, 0x20, 0, 0}; u8 dir_old_format = data[i].getParam2(); u8 dir_new_format = 0; for(u8 j=0; j<8; j++) { if((dir_old_format & wallmounted_new_to_old[j]) != 0) { dir_new_format = j; break; } } data[i].setParam2(dir_new_format); } } } /* Get a quick string to describe what a block actually contains */ std::string analyze_block(MapBlock *block) { if(block == NULL) return "NULL"; std::ostringstream desc; v3s16 p = block->getPos(); char spos[25]; porting::mt_snprintf(spos, sizeof(spos), "(%2d,%2d,%2d), ", p.X, p.Y, p.Z); desc<<spos; switch(block->getModified()) { case MOD_STATE_CLEAN: desc<<"CLEAN, "; break; case MOD_STATE_WRITE_AT_UNLOAD: desc<<"WRITE_AT_UNLOAD, "; break; case MOD_STATE_WRITE_NEEDED: desc<<"WRITE_NEEDED, "; break; default: desc<<"unknown getModified()="+itos(block->getModified())+", "; } if(block->isGenerated()) desc<<"is_gen [X], "; else desc<<"is_gen [ ], "; if(block->getIsUnderground()) desc<<"is_ug [X], "; else desc<<"is_ug [ ], "; desc<<"lighting_complete: "<<block->getLightingComplete()<<", "; if(block->isDummy()) { desc<<"Dummy, "; } else { bool full_ignore = true; bool some_ignore = false; bool full_air = true; bool some_air = false; for(s16 z0=0; z0<MAP_BLOCKSIZE; z0++) for(s16 y0=0; y0<MAP_BLOCKSIZE; y0++) for(s16 x0=0; x0<MAP_BLOCKSIZE; x0++) { v3s16 p(x0,y0,z0); MapNode n = block->getNodeNoEx(p); content_t c = n.getContent(); if(c == CONTENT_IGNORE) some_ignore = true; else full_ignore = false; if(c == CONTENT_AIR) some_air = true; else full_air = false; } desc<<"content {"; std::ostringstream ss; if(full_ignore) ss<<"IGNORE (full), "; else if(some_ignore) ss<<"IGNORE, "; if(full_air) ss<<"AIR (full), "; else if(some_air) ss<<"AIR, "; if(ss.str().size()>=2) desc<<ss.str().substr(0, ss.str().size()-2); desc<<"}, "; } return desc.str().substr(0, desc.str().size()-2); } //END
pgimeno/minetest
src/mapblock.cpp
C++
mit
21,892
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> 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. */ #pragma once #include <set> #include "irr_v3d.h" #include "mapnode.h" #include "exceptions.h" #include "constants.h" #include "staticobject.h" #include "nodemetadata.h" #include "nodetimer.h" #include "modifiedstate.h" #include "util/numeric.h" // getContainerPos #include "settings.h" #include "mapgen/mapgen.h" class Map; class NodeMetadataList; class IGameDef; class MapBlockMesh; class VoxelManipulator; #define BLOCK_TIMESTAMP_UNDEFINED 0xffffffff //// //// MapBlock modified reason flags //// #define MOD_REASON_INITIAL (1 << 0) #define MOD_REASON_REALLOCATE (1 << 1) #define MOD_REASON_SET_IS_UNDERGROUND (1 << 2) #define MOD_REASON_SET_LIGHTING_COMPLETE (1 << 3) #define MOD_REASON_SET_GENERATED (1 << 4) #define MOD_REASON_SET_NODE (1 << 5) #define MOD_REASON_SET_NODE_NO_CHECK (1 << 6) #define MOD_REASON_SET_TIMESTAMP (1 << 7) #define MOD_REASON_REPORT_META_CHANGE (1 << 8) #define MOD_REASON_CLEAR_ALL_OBJECTS (1 << 9) #define MOD_REASON_BLOCK_EXPIRED (1 << 10) #define MOD_REASON_ADD_ACTIVE_OBJECT_RAW (1 << 11) #define MOD_REASON_REMOVE_OBJECTS_REMOVE (1 << 12) #define MOD_REASON_REMOVE_OBJECTS_DEACTIVATE (1 << 13) #define MOD_REASON_TOO_MANY_OBJECTS (1 << 14) #define MOD_REASON_STATIC_DATA_ADDED (1 << 15) #define MOD_REASON_STATIC_DATA_REMOVED (1 << 16) #define MOD_REASON_STATIC_DATA_CHANGED (1 << 17) #define MOD_REASON_EXPIRE_DAYNIGHTDIFF (1 << 18) #define MOD_REASON_VMANIP (1 << 19) #define MOD_REASON_UNKNOWN (1 << 20) //// //// MapBlock itself //// class MapBlock { public: MapBlock(Map *parent, v3s16 pos, IGameDef *gamedef, bool dummy=false); ~MapBlock(); /*virtual u16 nodeContainerId() const { return NODECONTAINER_ID_MAPBLOCK; }*/ Map * getParent() { return m_parent; } void reallocate() { delete[] data; data = new MapNode[nodecount]; for (u32 i = 0; i < nodecount; i++) data[i] = MapNode(CONTENT_IGNORE); raiseModified(MOD_STATE_WRITE_NEEDED, MOD_REASON_REALLOCATE); } MapNode* getData() { return data; } //// //// Modification tracking methods //// void raiseModified(u32 mod, u32 reason=MOD_REASON_UNKNOWN) { if (mod > m_modified) { m_modified = mod; m_modified_reason = reason; if (m_modified >= MOD_STATE_WRITE_AT_UNLOAD) m_disk_timestamp = m_timestamp; } else if (mod == m_modified) { m_modified_reason |= reason; } if (mod == MOD_STATE_WRITE_NEEDED) contents_cached = false; } inline u32 getModified() { return m_modified; } inline u32 getModifiedReason() { return m_modified_reason; } std::string getModifiedReasonString(); inline void resetModified() { m_modified = MOD_STATE_CLEAN; m_modified_reason = 0; } //// //// Flags //// inline bool isDummy() { return !data; } inline void unDummify() { assert(isDummy()); // Pre-condition reallocate(); } // is_underground getter/setter inline bool getIsUnderground() { return is_underground; } inline void setIsUnderground(bool a_is_underground) { is_underground = a_is_underground; raiseModified(MOD_STATE_WRITE_NEEDED, MOD_REASON_SET_IS_UNDERGROUND); } inline void setLightingComplete(u16 newflags) { if (newflags != m_lighting_complete) { m_lighting_complete = newflags; raiseModified(MOD_STATE_WRITE_NEEDED, MOD_REASON_SET_LIGHTING_COMPLETE); } } inline u16 getLightingComplete() { return m_lighting_complete; } inline void setLightingComplete(LightBank bank, u8 direction, bool is_complete) { assert(direction >= 0 && direction <= 5); if (bank == LIGHTBANK_NIGHT) { direction += 6; } u16 newflags = m_lighting_complete; if (is_complete) { newflags |= 1 << direction; } else { newflags &= ~(1 << direction); } setLightingComplete(newflags); } inline bool isLightingComplete(LightBank bank, u8 direction) { assert(direction >= 0 && direction <= 5); if (bank == LIGHTBANK_NIGHT) { direction += 6; } return (m_lighting_complete & (1 << direction)) != 0; } inline bool isGenerated() { return m_generated; } inline void setGenerated(bool b) { if (b != m_generated) { raiseModified(MOD_STATE_WRITE_NEEDED, MOD_REASON_SET_GENERATED); m_generated = b; } } //// //// Position stuff //// inline v3s16 getPos() { return m_pos; } inline v3s16 getPosRelative() { return m_pos_relative; } inline core::aabbox3d<s16> getBox() { return core::aabbox3d<s16>(getPosRelative(), getPosRelative() + v3s16(MAP_BLOCKSIZE, MAP_BLOCKSIZE, MAP_BLOCKSIZE) - v3s16(1,1,1)); } //// //// Regular MapNode get-setters //// inline bool isValidPosition(s16 x, s16 y, s16 z) { return data && x >= 0 && x < MAP_BLOCKSIZE && y >= 0 && y < MAP_BLOCKSIZE && z >= 0 && z < MAP_BLOCKSIZE; } inline bool isValidPosition(v3s16 p) { return isValidPosition(p.X, p.Y, p.Z); } inline MapNode getNode(s16 x, s16 y, s16 z, bool *valid_position) { *valid_position = isValidPosition(x, y, z); if (!*valid_position) return {CONTENT_IGNORE}; return data[z * zstride + y * ystride + x]; } inline MapNode getNode(v3s16 p, bool *valid_position) { return getNode(p.X, p.Y, p.Z, valid_position); } inline MapNode getNodeNoEx(v3s16 p) { bool is_valid; return getNode(p.X, p.Y, p.Z, &is_valid); } inline void setNode(s16 x, s16 y, s16 z, MapNode & n) { if (!isValidPosition(x, y, z)) throw InvalidPositionException(); data[z * zstride + y * ystride + x] = n; raiseModified(MOD_STATE_WRITE_NEEDED, MOD_REASON_SET_NODE); } inline void setNode(v3s16 p, MapNode & n) { setNode(p.X, p.Y, p.Z, n); } //// //// Non-checking variants of the above //// inline MapNode getNodeNoCheck(s16 x, s16 y, s16 z, bool *valid_position) { *valid_position = data != nullptr; if (!*valid_position) return {CONTENT_IGNORE}; return data[z * zstride + y * ystride + x]; } inline MapNode getNodeNoCheck(v3s16 p, bool *valid_position) { return getNodeNoCheck(p.X, p.Y, p.Z, valid_position); } //// //// Non-checking, unsafe variants of the above //// MapBlock must be loaded by another function in the same scope/function //// Caller must ensure that this is not a dummy block (by calling isDummy()) //// inline const MapNode &getNodeUnsafe(s16 x, s16 y, s16 z) { return data[z * zstride + y * ystride + x]; } inline const MapNode &getNodeUnsafe(v3s16 &p) { return getNodeUnsafe(p.X, p.Y, p.Z); } inline void setNodeNoCheck(s16 x, s16 y, s16 z, MapNode & n) { if (!data) throw InvalidPositionException(); data[z * zstride + y * ystride + x] = n; raiseModified(MOD_STATE_WRITE_NEEDED, MOD_REASON_SET_NODE_NO_CHECK); } inline void setNodeNoCheck(v3s16 p, MapNode & n) { setNodeNoCheck(p.X, p.Y, p.Z, n); } // These functions consult the parent container if the position // is not valid on this MapBlock. bool isValidPositionParent(v3s16 p); MapNode getNodeParent(v3s16 p, bool *is_valid_position = NULL); void setNodeParent(v3s16 p, MapNode & n); inline void drawbox(s16 x0, s16 y0, s16 z0, s16 w, s16 h, s16 d, MapNode node) { for (u16 z = 0; z < d; z++) for (u16 y = 0; y < h; y++) for (u16 x = 0; x < w; x++) setNode(x0 + x, y0 + y, z0 + z, node); } // Copies data to VoxelManipulator to getPosRelative() void copyTo(VoxelManipulator &dst); // Copies data from VoxelManipulator getPosRelative() void copyFrom(VoxelManipulator &dst); // Update day-night lighting difference flag. // Sets m_day_night_differs to appropriate value. // These methods don't care about neighboring blocks. void actuallyUpdateDayNightDiff(); // Call this to schedule what the previous function does to be done // when the value is actually needed. void expireDayNightDiff(); inline bool getDayNightDiff() { if (m_day_night_differs_expired) actuallyUpdateDayNightDiff(); return m_day_night_differs; } //// //// Miscellaneous stuff //// /* Tries to measure ground level. Return value: -1 = only air -2 = only ground -3 = random fail 0...MAP_BLOCKSIZE-1 = ground level */ s16 getGroundLevel(v2s16 p2d); //// //// Timestamp (see m_timestamp) //// // NOTE: BLOCK_TIMESTAMP_UNDEFINED=0xffffffff means there is no timestamp. inline void setTimestamp(u32 time) { m_timestamp = time; raiseModified(MOD_STATE_WRITE_AT_UNLOAD, MOD_REASON_SET_TIMESTAMP); } inline void setTimestampNoChangedFlag(u32 time) { m_timestamp = time; } inline u32 getTimestamp() { return m_timestamp; } inline u32 getDiskTimestamp() { return m_disk_timestamp; } //// //// Usage timer (see m_usage_timer) //// inline void resetUsageTimer() { m_usage_timer = 0; } inline void incrementUsageTimer(float dtime) { m_usage_timer += dtime; } inline float getUsageTimer() { return m_usage_timer; } //// //// Reference counting (see m_refcount) //// inline void refGrab() { m_refcount++; } inline void refDrop() { m_refcount--; } inline int refGet() { return m_refcount; } //// //// Node Timers //// inline NodeTimer getNodeTimer(const v3s16 &p) { return m_node_timers.get(p); } inline void removeNodeTimer(const v3s16 &p) { m_node_timers.remove(p); } inline void setNodeTimer(const NodeTimer &t) { m_node_timers.set(t); } inline void clearNodeTimers() { m_node_timers.clear(); } //// //// Serialization /// // These don't write or read version by itself // Set disk to true for on-disk format, false for over-the-network format // Precondition: version >= SER_FMT_VER_LOWEST_WRITE void serialize(std::ostream &os, u8 version, bool disk); // If disk == true: In addition to doing other things, will add // unknown blocks from id-name mapping to wndef void deSerialize(std::istream &is, u8 version, bool disk); void serializeNetworkSpecific(std::ostream &os); void deSerializeNetworkSpecific(std::istream &is); private: /* Private methods */ void deSerialize_pre22(std::istream &is, u8 version, bool disk); /* Used only internally, because changes can't be tracked */ inline MapNode &getNodeRef(s16 x, s16 y, s16 z) { if (!isValidPosition(x, y, z)) throw InvalidPositionException(); return data[z * zstride + y * ystride + x]; } inline MapNode &getNodeRef(v3s16 &p) { return getNodeRef(p.X, p.Y, p.Z); } public: /* Public member variables */ #ifndef SERVER // Only on client MapBlockMesh *mesh = nullptr; #endif NodeMetadataList m_node_metadata; NodeTimerList m_node_timers; StaticObjectList m_static_objects; static const u32 ystride = MAP_BLOCKSIZE; static const u32 zstride = MAP_BLOCKSIZE * MAP_BLOCKSIZE; static const u32 nodecount = MAP_BLOCKSIZE * MAP_BLOCKSIZE * MAP_BLOCKSIZE; //// ABM optimizations //// // Cache of content types std::unordered_set<content_t> contents; // True if content types are cached bool contents_cached = false; // True if we never want to cache content types for this block bool do_not_cache_contents = false; private: /* Private member variables */ // NOTE: Lots of things rely on this being the Map Map *m_parent; // Position in blocks on parent v3s16 m_pos; /* This is the precalculated m_pos_relative value * This caches the value, improving performance by removing 3 s16 multiplications * at runtime on each getPosRelative call * For a 5 minutes runtime with valgrind this removes 3 * 19M s16 multiplications * The gain can be estimated in Release Build to 3 * 100M multiply operations for 5 mins */ v3s16 m_pos_relative; IGameDef *m_gamedef; /* If NULL, block is a dummy block. Dummy blocks are used for caching not-found-on-disk blocks. */ MapNode *data = nullptr; /* - On the server, this is used for telling whether the block has been modified from the one on disk. - On the client, this is used for nothing. */ u32 m_modified = MOD_STATE_WRITE_NEEDED; u32 m_modified_reason = MOD_REASON_INITIAL; /* When propagating sunlight and the above block doesn't exist, sunlight is assumed if this is false. In practice this is set to true if the block is completely undeground with nothing visible above the ground except caves. */ bool is_underground = false; /*! * Each bit indicates if light spreading was finished * in a direction. (Because the neighbor could also be unloaded.) * Bits (most significant first): * nothing, nothing, nothing, nothing, * night X-, night Y-, night Z-, night Z+, night Y+, night X+, * day X-, day Y-, day Z-, day Z+, day Y+, day X+. */ u16 m_lighting_complete = 0xFFFF; // Whether day and night lighting differs bool m_day_night_differs = false; bool m_day_night_differs_expired = true; bool m_generated = false; /* When block is removed from active blocks, this is set to gametime. Value BLOCK_TIMESTAMP_UNDEFINED=0xffffffff means there is no timestamp. */ u32 m_timestamp = BLOCK_TIMESTAMP_UNDEFINED; // The on-disk (or to-be on-disk) timestamp value u32 m_disk_timestamp = BLOCK_TIMESTAMP_UNDEFINED; /* When the block is accessed, this is set to 0. Map will unload the block when this reaches a timeout. */ float m_usage_timer = 0; /* Reference count; currently used for determining if this block is in the list of blocks to be drawn. */ int m_refcount = 0; }; typedef std::vector<MapBlock*> MapBlockVect; inline bool objectpos_over_limit(v3f p) { const float max_limit_bs = MAX_MAP_GENERATION_LIMIT * BS; return p.X < -max_limit_bs || p.X > max_limit_bs || p.Y < -max_limit_bs || p.Y > max_limit_bs || p.Z < -max_limit_bs || p.Z > max_limit_bs; } inline bool blockpos_over_max_limit(v3s16 p) { const s16 max_limit_bp = MAX_MAP_GENERATION_LIMIT / MAP_BLOCKSIZE; return p.X < -max_limit_bp || p.X > max_limit_bp || p.Y < -max_limit_bp || p.Y > max_limit_bp || p.Z < -max_limit_bp || p.Z > max_limit_bp; } /* Returns the position of the block where the node is located */ inline v3s16 getNodeBlockPos(const v3s16 &p) { return getContainerPos(p, MAP_BLOCKSIZE); } inline void getNodeBlockPosWithOffset(const v3s16 &p, v3s16 &block, v3s16 &offset) { getContainerPosWithOffset(p, MAP_BLOCKSIZE, block, offset); } /* Get a quick string to describe what a block actually contains */ std::string analyze_block(MapBlock *block);
pgimeno/minetest
src/mapblock.h
C++
mit
15,194
set(mapgen_SRCS ${CMAKE_CURRENT_SOURCE_DIR}/cavegen.cpp ${CMAKE_CURRENT_SOURCE_DIR}/dungeongen.cpp ${CMAKE_CURRENT_SOURCE_DIR}/mapgen_carpathian.cpp ${CMAKE_CURRENT_SOURCE_DIR}/mapgen.cpp ${CMAKE_CURRENT_SOURCE_DIR}/mapgen_flat.cpp ${CMAKE_CURRENT_SOURCE_DIR}/mapgen_fractal.cpp ${CMAKE_CURRENT_SOURCE_DIR}/mapgen_singlenode.cpp ${CMAKE_CURRENT_SOURCE_DIR}/mapgen_v5.cpp ${CMAKE_CURRENT_SOURCE_DIR}/mapgen_v6.cpp ${CMAKE_CURRENT_SOURCE_DIR}/mapgen_v7.cpp ${CMAKE_CURRENT_SOURCE_DIR}/mapgen_valleys.cpp ${CMAKE_CURRENT_SOURCE_DIR}/mg_biome.cpp ${CMAKE_CURRENT_SOURCE_DIR}/mg_decoration.cpp ${CMAKE_CURRENT_SOURCE_DIR}/mg_ore.cpp ${CMAKE_CURRENT_SOURCE_DIR}/mg_schematic.cpp ${CMAKE_CURRENT_SOURCE_DIR}/treegen.cpp PARENT_SCOPE )
pgimeno/minetest
src/mapgen/CMakeLists.txt
Text
mit
745
/* Minetest Copyright (C) 2010-2018 celeron55, Perttu Ahola <celeron55@gmail.com> Copyright (C) 2010-2018 kwolekr, Ryan Kwolek <kwolekr@minetest.net> Copyright (C) 2015-2018 paramat 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 "util/numeric.h" #include <cmath> #include "map.h" #include "mapgen.h" #include "mapgen_v5.h" #include "mapgen_v6.h" #include "mapgen_v7.h" #include "mg_biome.h" #include "cavegen.h" static NoiseParams nparams_caveliquids(0, 1, v3f(150.0, 150.0, 150.0), 776, 3, 0.6, 2.0); //// //// CavesNoiseIntersection //// CavesNoiseIntersection::CavesNoiseIntersection( const NodeDefManager *nodedef, BiomeManager *biomemgr, v3s16 chunksize, NoiseParams *np_cave1, NoiseParams *np_cave2, s32 seed, float cave_width) { assert(nodedef); assert(biomemgr); m_ndef = nodedef; m_bmgr = biomemgr; m_csize = chunksize; m_cave_width = cave_width; m_ystride = m_csize.X; m_zstride_1d = m_csize.X * (m_csize.Y + 1); // Noises are created using 1-down overgeneration // A Nx-by-1-by-Nz-sized plane is at the bottom of the desired for // re-carving the solid overtop placed for blocking sunlight noise_cave1 = new Noise(np_cave1, seed, m_csize.X, m_csize.Y + 1, m_csize.Z); noise_cave2 = new Noise(np_cave2, seed, m_csize.X, m_csize.Y + 1, m_csize.Z); } CavesNoiseIntersection::~CavesNoiseIntersection() { delete noise_cave1; delete noise_cave2; } void CavesNoiseIntersection::generateCaves(MMVManip *vm, v3s16 nmin, v3s16 nmax, u8 *biomemap) { assert(vm); assert(biomemap); noise_cave1->perlinMap3D(nmin.X, nmin.Y - 1, nmin.Z); noise_cave2->perlinMap3D(nmin.X, nmin.Y - 1, nmin.Z); const v3s16 &em = vm->m_area.getExtent(); u32 index2d = 0; // Biomemap index for (s16 z = nmin.Z; z <= nmax.Z; z++) for (s16 x = nmin.X; x <= nmax.X; x++, index2d++) { bool column_is_open = false; // Is column open to overground bool is_under_river = false; // Is column under river water bool is_under_tunnel = false; // Is tunnel or is under tunnel bool is_top_filler_above = false; // Is top or filler above node // Indexes at column top u32 vi = vm->m_area.index(x, nmax.Y, z); u32 index3d = (z - nmin.Z) * m_zstride_1d + m_csize.Y * m_ystride + (x - nmin.X); // 3D noise index // Biome of column Biome *biome = (Biome *)m_bmgr->getRaw(biomemap[index2d]); u16 depth_top = biome->depth_top; u16 base_filler = depth_top + biome->depth_filler; u16 depth_riverbed = biome->depth_riverbed; u16 nplaced = 0; // Don't excavate the overgenerated stone at nmax.Y + 1, // this creates a 'roof' over the tunnel, preventing light in // tunnels at mapchunk borders when generating mapchunks upwards. // This 'roof' is removed when the mapchunk above is generated. for (s16 y = nmax.Y; y >= nmin.Y - 1; y--, index3d -= m_ystride, VoxelArea::add_y(em, vi, -1)) { content_t c = vm->m_data[vi].getContent(); if (c == CONTENT_AIR || c == biome->c_water_top || c == biome->c_water) { column_is_open = true; is_top_filler_above = false; continue; } if (c == biome->c_river_water) { column_is_open = true; is_under_river = true; is_top_filler_above = false; continue; } // Ground float d1 = contour(noise_cave1->result[index3d]); float d2 = contour(noise_cave2->result[index3d]); if (d1 * d2 > m_cave_width && m_ndef->get(c).is_ground_content) { // In tunnel and ground content, excavate vm->m_data[vi] = MapNode(CONTENT_AIR); is_under_tunnel = true; // If tunnel roof is top or filler, replace with stone if (is_top_filler_above) vm->m_data[vi + em.X] = MapNode(biome->c_stone); is_top_filler_above = false; } else if (column_is_open && is_under_tunnel && (c == biome->c_stone || c == biome->c_filler)) { // Tunnel entrance floor, place biome surface nodes if (is_under_river) { if (nplaced < depth_riverbed) { vm->m_data[vi] = MapNode(biome->c_riverbed); is_top_filler_above = true; nplaced++; } else { // Disable top/filler placement column_is_open = false; is_under_river = false; is_under_tunnel = false; } } else if (nplaced < depth_top) { vm->m_data[vi] = MapNode(biome->c_top); is_top_filler_above = true; nplaced++; } else if (nplaced < base_filler) { vm->m_data[vi] = MapNode(biome->c_filler); is_top_filler_above = true; nplaced++; } else { // Disable top/filler placement column_is_open = false; is_under_tunnel = false; } } else { // Not tunnel or tunnel entrance floor // Check node for possible replacing with stone for tunnel roof if (c == biome->c_top || c == biome->c_filler) is_top_filler_above = true; column_is_open = false; } } } } //// //// CavernsNoise //// CavernsNoise::CavernsNoise( const NodeDefManager *nodedef, v3s16 chunksize, NoiseParams *np_cavern, s32 seed, float cavern_limit, float cavern_taper, float cavern_threshold) { assert(nodedef); m_ndef = nodedef; m_csize = chunksize; m_cavern_limit = cavern_limit; m_cavern_taper = cavern_taper; m_cavern_threshold = cavern_threshold; m_ystride = m_csize.X; m_zstride_1d = m_csize.X * (m_csize.Y + 1); // Noise is created using 1-down overgeneration // A Nx-by-1-by-Nz-sized plane is at the bottom of the desired for // re-carving the solid overtop placed for blocking sunlight noise_cavern = new Noise(np_cavern, seed, m_csize.X, m_csize.Y + 1, m_csize.Z); c_water_source = m_ndef->getId("mapgen_water_source"); if (c_water_source == CONTENT_IGNORE) c_water_source = CONTENT_AIR; c_lava_source = m_ndef->getId("mapgen_lava_source"); if (c_lava_source == CONTENT_IGNORE) c_lava_source = CONTENT_AIR; } CavernsNoise::~CavernsNoise() { delete noise_cavern; } bool CavernsNoise::generateCaverns(MMVManip *vm, v3s16 nmin, v3s16 nmax) { assert(vm); // Calculate noise noise_cavern->perlinMap3D(nmin.X, nmin.Y - 1, nmin.Z); // Cache cavern_amp values float *cavern_amp = new float[m_csize.Y + 1]; u8 cavern_amp_index = 0; // Index zero at column top for (s16 y = nmax.Y; y >= nmin.Y - 1; y--, cavern_amp_index++) { cavern_amp[cavern_amp_index] = MYMIN((m_cavern_limit - y) / (float)m_cavern_taper, 1.0f); } //// Place nodes bool near_cavern = false; const v3s16 &em = vm->m_area.getExtent(); u32 index2d = 0; for (s16 z = nmin.Z; z <= nmax.Z; z++) for (s16 x = nmin.X; x <= nmax.X; x++, index2d++) { // Reset cave_amp index to column top cavern_amp_index = 0; // Initial voxelmanip index at column top u32 vi = vm->m_area.index(x, nmax.Y, z); // Initial 3D noise index at column top u32 index3d = (z - nmin.Z) * m_zstride_1d + m_csize.Y * m_ystride + (x - nmin.X); // Don't excavate the overgenerated stone at node_max.Y + 1, // this creates a 'roof' over the cavern, preventing light in // caverns at mapchunk borders when generating mapchunks upwards. // This 'roof' is excavated when the mapchunk above is generated. for (s16 y = nmax.Y; y >= nmin.Y - 1; y--, index3d -= m_ystride, VoxelArea::add_y(em, vi, -1), cavern_amp_index++) { content_t c = vm->m_data[vi].getContent(); float n_absamp_cavern = std::fabs(noise_cavern->result[index3d]) * cavern_amp[cavern_amp_index]; // Disable CavesRandomWalk at a safe distance from caverns // to avoid excessively spreading liquids in caverns. if (n_absamp_cavern > m_cavern_threshold - 0.1f) { near_cavern = true; if (n_absamp_cavern > m_cavern_threshold && m_ndef->get(c).is_ground_content) vm->m_data[vi] = MapNode(CONTENT_AIR); } } } delete[] cavern_amp; return near_cavern; } //// //// CavesRandomWalk //// CavesRandomWalk::CavesRandomWalk( const NodeDefManager *ndef, GenerateNotifier *gennotify, s32 seed, int water_level, content_t water_source, content_t lava_source, int lava_depth, BiomeGen *biomegen) { assert(ndef); this->ndef = ndef; this->gennotify = gennotify; this->seed = seed; this->water_level = water_level; this->np_caveliquids = &nparams_caveliquids; this->lava_depth = lava_depth; this->bmgn = biomegen; c_water_source = water_source; if (c_water_source == CONTENT_IGNORE) c_water_source = ndef->getId("mapgen_water_source"); if (c_water_source == CONTENT_IGNORE) c_water_source = CONTENT_AIR; c_lava_source = lava_source; if (c_lava_source == CONTENT_IGNORE) c_lava_source = ndef->getId("mapgen_lava_source"); if (c_lava_source == CONTENT_IGNORE) c_lava_source = CONTENT_AIR; } void CavesRandomWalk::makeCave(MMVManip *vm, v3s16 nmin, v3s16 nmax, PseudoRandom *ps, bool is_large_cave, int max_stone_height, s16 *heightmap) { assert(vm); assert(ps); this->vm = vm; this->ps = ps; this->node_min = nmin; this->node_max = nmax; this->heightmap = heightmap; this->large_cave = is_large_cave; this->ystride = nmax.X - nmin.X + 1; // Set initial parameters from randomness int dswitchint = ps->range(1, 14); flooded = ps->range(1, 2) == 2; if (large_cave) { part_max_length_rs = ps->range(2, 4); tunnel_routepoints = ps->range(5, ps->range(15, 30)); min_tunnel_diameter = 5; max_tunnel_diameter = ps->range(7, ps->range(8, 24)); } else { part_max_length_rs = ps->range(2, 9); tunnel_routepoints = ps->range(10, ps->range(15, 30)); min_tunnel_diameter = 2; max_tunnel_diameter = ps->range(2, 6); } large_cave_is_flat = (ps->range(0, 1) == 0); main_direction = v3f(0, 0, 0); // Allowed route area size in nodes ar = node_max - node_min + v3s16(1, 1, 1); // Area starting point in nodes of = node_min; // Allow a bit more //(this should be more than the maximum radius of the tunnel) const s16 insure = 10; s16 more = MYMAX(MAP_BLOCKSIZE - max_tunnel_diameter / 2 - insure, 1); ar += v3s16(1, 0, 1) * more * 2; of -= v3s16(1, 0, 1) * more; route_y_min = 0; // Allow half a diameter + 7 over stone surface route_y_max = -of.Y + max_stone_height + max_tunnel_diameter / 2 + 7; // Limit maximum to area route_y_max = rangelim(route_y_max, 0, ar.Y - 1); if (large_cave) { s16 minpos = 0; if (node_min.Y < water_level && node_max.Y > water_level) { minpos = water_level - max_tunnel_diameter / 3 - of.Y; route_y_max = water_level + max_tunnel_diameter / 3 - of.Y; } route_y_min = ps->range(minpos, minpos + max_tunnel_diameter); route_y_min = rangelim(route_y_min, 0, route_y_max); } s16 route_start_y_min = route_y_min; s16 route_start_y_max = route_y_max; route_start_y_min = rangelim(route_start_y_min, 0, ar.Y - 1); route_start_y_max = rangelim(route_start_y_max, route_start_y_min, ar.Y - 1); // Randomize starting position orp.Z = (float)(ps->next() % ar.Z) + 0.5f; orp.Y = (float)(ps->range(route_start_y_min, route_start_y_max)) + 0.5f; orp.X = (float)(ps->next() % ar.X) + 0.5f; // Add generation notify begin event if (gennotify) { v3s16 abs_pos(of.X + orp.X, of.Y + orp.Y, of.Z + orp.Z); GenNotifyType notifytype = large_cave ? GENNOTIFY_LARGECAVE_BEGIN : GENNOTIFY_CAVE_BEGIN; gennotify->addEvent(notifytype, abs_pos); } // Generate some tunnel starting from orp for (u16 j = 0; j < tunnel_routepoints; j++) makeTunnel(j % dswitchint == 0); // Add generation notify end event if (gennotify) { v3s16 abs_pos(of.X + orp.X, of.Y + orp.Y, of.Z + orp.Z); GenNotifyType notifytype = large_cave ? GENNOTIFY_LARGECAVE_END : GENNOTIFY_CAVE_END; gennotify->addEvent(notifytype, abs_pos); } } void CavesRandomWalk::makeTunnel(bool dirswitch) { if (dirswitch && !large_cave) { main_direction.Z = ((float)(ps->next() % 20) - (float)10) / 10; main_direction.Y = ((float)(ps->next() % 20) - (float)10) / 30; main_direction.X = ((float)(ps->next() % 20) - (float)10) / 10; main_direction *= (float)ps->range(0, 10) / 10; } // Randomize size s16 min_d = min_tunnel_diameter; s16 max_d = max_tunnel_diameter; rs = ps->range(min_d, max_d); s16 rs_part_max_length_rs = rs * part_max_length_rs; v3s16 maxlen; if (large_cave) { maxlen = v3s16( rs_part_max_length_rs, rs_part_max_length_rs / 2, rs_part_max_length_rs ); } else { maxlen = v3s16( rs_part_max_length_rs, ps->range(1, rs_part_max_length_rs), rs_part_max_length_rs ); } v3f vec; // Jump downward sometimes if (!large_cave && ps->range(0, 12) == 0) { vec.Z = (float)(ps->next() % (maxlen.Z * 1)) - (float)maxlen.Z / 2; vec.Y = (float)(ps->next() % (maxlen.Y * 2)) - (float)maxlen.Y; vec.X = (float)(ps->next() % (maxlen.X * 1)) - (float)maxlen.X / 2; } else { vec.Z = (float)(ps->next() % (maxlen.Z * 1)) - (float)maxlen.Z / 2; vec.Y = (float)(ps->next() % (maxlen.Y * 1)) - (float)maxlen.Y / 2; vec.X = (float)(ps->next() % (maxlen.X * 1)) - (float)maxlen.X / 2; } // Do not make caves that are above ground. // It is only necessary to check the startpoint and endpoint. v3s16 p1 = v3s16(orp.X, orp.Y, orp.Z) + of + rs / 2; v3s16 p2 = v3s16(vec.X, vec.Y, vec.Z) + p1; if (isPosAboveSurface(p1) || isPosAboveSurface(p2)) return; vec += main_direction; v3f rp = orp + vec; if (rp.X < 0) rp.X = 0; else if (rp.X >= ar.X) rp.X = ar.X - 1; if (rp.Y < route_y_min) rp.Y = route_y_min; else if (rp.Y >= route_y_max) rp.Y = route_y_max - 1; if (rp.Z < 0) rp.Z = 0; else if (rp.Z >= ar.Z) rp.Z = ar.Z - 1; vec = rp - orp; float veclen = vec.getLength(); if (veclen < 0.05f) veclen = 1.0f; // Every second section is rough bool randomize_xz = (ps->range(1, 2) == 1); // Carve routes for (float f = 0.f; f < 1.0f; f += 1.0f / veclen) carveRoute(vec, f, randomize_xz); orp = rp; } void CavesRandomWalk::carveRoute(v3f vec, float f, bool randomize_xz) { MapNode airnode(CONTENT_AIR); MapNode waternode(c_water_source); MapNode lavanode(c_lava_source); v3s16 startp(orp.X, orp.Y, orp.Z); startp += of; v3f fp = orp + vec * f; fp.X += 0.1f * ps->range(-10, 10); fp.Z += 0.1f * ps->range(-10, 10); v3s16 cp(fp.X, fp.Y, fp.Z); // Get biome at 'cp + of', the absolute centre point of this route v3s16 cpabs = cp + of; MapNode liquidnode = CONTENT_IGNORE; if (bmgn) { Biome *biome = nullptr; if (cpabs.X < node_min.X || cpabs.X > node_max.X || cpabs.Z < node_min.Z || cpabs.Z > node_max.Z) // Point is outside heat and humidity noise maps so use point noise // calculations. biome = (Biome *)bmgn->calcBiomeAtPoint(cpabs); else // Point is inside heat and humidity noise maps so use them biome = (Biome *)bmgn->getBiomeAtPoint(cpabs); if (biome->c_cave_liquid != CONTENT_IGNORE) liquidnode = biome->c_cave_liquid; } if (liquidnode == CONTENT_IGNORE) { // Fallback to classic behaviour using point 'startp' float nval = NoisePerlin3D(np_caveliquids, startp.X, startp.Y, startp.Z, seed); liquidnode = (nval < 0.40f && node_max.Y < lava_depth) ? lavanode : waternode; } s16 d0 = -rs / 2; s16 d1 = d0 + rs; if (randomize_xz) { d0 += ps->range(-1, 1); d1 += ps->range(-1, 1); } bool flat_cave_floor = !large_cave && ps->range(0, 2) == 2; for (s16 z0 = d0; z0 <= d1; z0++) { s16 si = rs / 2 - MYMAX(0, abs(z0) - rs / 7 - 1); for (s16 x0 = -si - ps->range(0,1); x0 <= si - 1 + ps->range(0,1); x0++) { s16 maxabsxz = MYMAX(abs(x0), abs(z0)); s16 si2 = rs / 2 - MYMAX(0, maxabsxz - rs / 7 - 1); for (s16 y0 = -si2; y0 <= si2; y0++) { // Make better floors in small caves if (flat_cave_floor && y0 <= -rs / 2 && rs <= 7) continue; if (large_cave_is_flat) { // Make large caves not so tall if (rs > 7 && abs(y0) >= rs / 3) continue; } v3s16 p(cp.X + x0, cp.Y + y0, cp.Z + z0); p += of; if (!vm->m_area.contains(p)) continue; u32 i = vm->m_area.index(p); content_t c = vm->m_data[i].getContent(); if (!ndef->get(c).is_ground_content) continue; if (large_cave) { int full_ymin = node_min.Y - MAP_BLOCKSIZE; int full_ymax = node_max.Y + MAP_BLOCKSIZE; if (flooded && full_ymin < water_level && full_ymax > water_level) vm->m_data[i] = (p.Y <= water_level) ? waternode : airnode; else if (flooded && full_ymax < water_level) vm->m_data[i] = (p.Y < startp.Y - 4) ? liquidnode : airnode; else vm->m_data[i] = airnode; } else { vm->m_data[i] = airnode; vm->m_flags[i] |= VMANIP_FLAG_CAVE; } } } } } inline bool CavesRandomWalk::isPosAboveSurface(v3s16 p) { if (heightmap != NULL && p.Z >= node_min.Z && p.Z <= node_max.Z && p.X >= node_min.X && p.X <= node_max.X) { u32 index = (p.Z - node_min.Z) * ystride + (p.X - node_min.X); if (heightmap[index] < p.Y) return true; } else if (p.Y > water_level) { return true; } return false; } //// //// CavesV6 //// CavesV6::CavesV6(const NodeDefManager *ndef, GenerateNotifier *gennotify, int water_level, content_t water_source, content_t lava_source) { assert(ndef); this->ndef = ndef; this->gennotify = gennotify; this->water_level = water_level; c_water_source = water_source; if (c_water_source == CONTENT_IGNORE) c_water_source = ndef->getId("mapgen_water_source"); if (c_water_source == CONTENT_IGNORE) c_water_source = CONTENT_AIR; c_lava_source = lava_source; if (c_lava_source == CONTENT_IGNORE) c_lava_source = ndef->getId("mapgen_lava_source"); if (c_lava_source == CONTENT_IGNORE) c_lava_source = CONTENT_AIR; } void CavesV6::makeCave(MMVManip *vm, v3s16 nmin, v3s16 nmax, PseudoRandom *ps, PseudoRandom *ps2, bool is_large_cave, int max_stone_height, s16 *heightmap) { assert(vm); assert(ps); assert(ps2); this->vm = vm; this->ps = ps; this->ps2 = ps2; this->node_min = nmin; this->node_max = nmax; this->heightmap = heightmap; this->large_cave = is_large_cave; this->ystride = nmax.X - nmin.X + 1; // Set initial parameters from randomness min_tunnel_diameter = 2; max_tunnel_diameter = ps->range(2, 6); int dswitchint = ps->range(1, 14); if (large_cave) { part_max_length_rs = ps->range(2, 4); tunnel_routepoints = ps->range(5, ps->range(15, 30)); min_tunnel_diameter = 5; max_tunnel_diameter = ps->range(7, ps->range(8, 24)); } else { part_max_length_rs = ps->range(2, 9); tunnel_routepoints = ps->range(10, ps->range(15, 30)); } large_cave_is_flat = (ps->range(0, 1) == 0); main_direction = v3f(0, 0, 0); // Allowed route area size in nodes ar = node_max - node_min + v3s16(1, 1, 1); // Area starting point in nodes of = node_min; // Allow a bit more //(this should be more than the maximum radius of the tunnel) const s16 max_spread_amount = MAP_BLOCKSIZE; const s16 insure = 10; s16 more = MYMAX(max_spread_amount - max_tunnel_diameter / 2 - insure, 1); ar += v3s16(1, 0, 1) * more * 2; of -= v3s16(1, 0, 1) * more; route_y_min = 0; // Allow half a diameter + 7 over stone surface route_y_max = -of.Y + max_stone_height + max_tunnel_diameter / 2 + 7; // Limit maximum to area route_y_max = rangelim(route_y_max, 0, ar.Y - 1); if (large_cave) { s16 minpos = 0; if (node_min.Y < water_level && node_max.Y > water_level) { minpos = water_level - max_tunnel_diameter / 3 - of.Y; route_y_max = water_level + max_tunnel_diameter / 3 - of.Y; } route_y_min = ps->range(minpos, minpos + max_tunnel_diameter); route_y_min = rangelim(route_y_min, 0, route_y_max); } s16 route_start_y_min = route_y_min; s16 route_start_y_max = route_y_max; route_start_y_min = rangelim(route_start_y_min, 0, ar.Y - 1); route_start_y_max = rangelim(route_start_y_max, route_start_y_min, ar.Y - 1); // Randomize starting position orp.Z = (float)(ps->next() % ar.Z) + 0.5f; orp.Y = (float)(ps->range(route_start_y_min, route_start_y_max)) + 0.5f; orp.X = (float)(ps->next() % ar.X) + 0.5f; // Add generation notify begin event if (gennotify != NULL) { v3s16 abs_pos(of.X + orp.X, of.Y + orp.Y, of.Z + orp.Z); GenNotifyType notifytype = large_cave ? GENNOTIFY_LARGECAVE_BEGIN : GENNOTIFY_CAVE_BEGIN; gennotify->addEvent(notifytype, abs_pos); } // Generate some tunnel starting from orp for (u16 j = 0; j < tunnel_routepoints; j++) makeTunnel(j % dswitchint == 0); // Add generation notify end event if (gennotify != NULL) { v3s16 abs_pos(of.X + orp.X, of.Y + orp.Y, of.Z + orp.Z); GenNotifyType notifytype = large_cave ? GENNOTIFY_LARGECAVE_END : GENNOTIFY_CAVE_END; gennotify->addEvent(notifytype, abs_pos); } } void CavesV6::makeTunnel(bool dirswitch) { if (dirswitch && !large_cave) { main_direction.Z = ((float)(ps->next() % 20) - (float)10) / 10; main_direction.Y = ((float)(ps->next() % 20) - (float)10) / 30; main_direction.X = ((float)(ps->next() % 20) - (float)10) / 10; main_direction *= (float)ps->range(0, 10) / 10; } // Randomize size s16 min_d = min_tunnel_diameter; s16 max_d = max_tunnel_diameter; rs = ps->range(min_d, max_d); s16 rs_part_max_length_rs = rs * part_max_length_rs; v3s16 maxlen; if (large_cave) { maxlen = v3s16( rs_part_max_length_rs, rs_part_max_length_rs / 2, rs_part_max_length_rs ); } else { maxlen = v3s16( rs_part_max_length_rs, ps->range(1, rs_part_max_length_rs), rs_part_max_length_rs ); } v3f vec; vec.Z = (float)(ps->next() % maxlen.Z) - (float)maxlen.Z / 2; vec.Y = (float)(ps->next() % maxlen.Y) - (float)maxlen.Y / 2; vec.X = (float)(ps->next() % maxlen.X) - (float)maxlen.X / 2; // Jump downward sometimes if (!large_cave && ps->range(0, 12) == 0) { vec.Z = (float)(ps->next() % maxlen.Z) - (float)maxlen.Z / 2; vec.Y = (float)(ps->next() % (maxlen.Y * 2)) - (float)maxlen.Y; vec.X = (float)(ps->next() % maxlen.X) - (float)maxlen.X / 2; } // Do not make caves that are entirely above ground, to fix shadow bugs // caused by overgenerated large caves. // It is only necessary to check the startpoint and endpoint. v3s16 p1 = v3s16(orp.X, orp.Y, orp.Z) + of + rs / 2; v3s16 p2 = v3s16(vec.X, vec.Y, vec.Z) + p1; // If startpoint and endpoint are above ground, disable placement of nodes // in carveRoute while still running all PseudoRandom calls to ensure caves // are consistent with existing worlds. bool tunnel_above_ground = p1.Y > getSurfaceFromHeightmap(p1) && p2.Y > getSurfaceFromHeightmap(p2); vec += main_direction; v3f rp = orp + vec; if (rp.X < 0) rp.X = 0; else if (rp.X >= ar.X) rp.X = ar.X - 1; if (rp.Y < route_y_min) rp.Y = route_y_min; else if (rp.Y >= route_y_max) rp.Y = route_y_max - 1; if (rp.Z < 0) rp.Z = 0; else if (rp.Z >= ar.Z) rp.Z = ar.Z - 1; vec = rp - orp; float veclen = vec.getLength(); // As odd as it sounds, veclen is *exactly* 0.0 sometimes, causing a FPE if (veclen < 0.05f) veclen = 1.0f; // Every second section is rough bool randomize_xz = (ps2->range(1, 2) == 1); // Carve routes for (float f = 0.f; f < 1.0f; f += 1.0f / veclen) carveRoute(vec, f, randomize_xz, tunnel_above_ground); orp = rp; } void CavesV6::carveRoute(v3f vec, float f, bool randomize_xz, bool tunnel_above_ground) { MapNode airnode(CONTENT_AIR); MapNode waternode(c_water_source); MapNode lavanode(c_lava_source); v3s16 startp(orp.X, orp.Y, orp.Z); startp += of; v3f fp = orp + vec * f; fp.X += 0.1f * ps->range(-10, 10); fp.Z += 0.1f * ps->range(-10, 10); v3s16 cp(fp.X, fp.Y, fp.Z); s16 d0 = -rs / 2; s16 d1 = d0 + rs; if (randomize_xz) { d0 += ps->range(-1, 1); d1 += ps->range(-1, 1); } for (s16 z0 = d0; z0 <= d1; z0++) { s16 si = rs / 2 - MYMAX(0, abs(z0) - rs / 7 - 1); for (s16 x0 = -si - ps->range(0,1); x0 <= si - 1 + ps->range(0,1); x0++) { if (tunnel_above_ground) continue; s16 maxabsxz = MYMAX(abs(x0), abs(z0)); s16 si2 = rs / 2 - MYMAX(0, maxabsxz - rs / 7 - 1); for (s16 y0 = -si2; y0 <= si2; y0++) { if (large_cave_is_flat) { // Make large caves not so tall if (rs > 7 && abs(y0) >= rs / 3) continue; } v3s16 p(cp.X + x0, cp.Y + y0, cp.Z + z0); p += of; if (!vm->m_area.contains(p)) continue; u32 i = vm->m_area.index(p); content_t c = vm->m_data[i].getContent(); if (!ndef->get(c).is_ground_content) continue; if (large_cave) { int full_ymin = node_min.Y - MAP_BLOCKSIZE; int full_ymax = node_max.Y + MAP_BLOCKSIZE; if (full_ymin < water_level && full_ymax > water_level) { vm->m_data[i] = (p.Y <= water_level) ? waternode : airnode; } else if (full_ymax < water_level) { vm->m_data[i] = (p.Y < startp.Y - 2) ? lavanode : airnode; } else { vm->m_data[i] = airnode; } } else { if (c == CONTENT_AIR) continue; vm->m_data[i] = airnode; vm->m_flags[i] |= VMANIP_FLAG_CAVE; } } } } } inline s16 CavesV6::getSurfaceFromHeightmap(v3s16 p) { if (heightmap != NULL && p.Z >= node_min.Z && p.Z <= node_max.Z && p.X >= node_min.X && p.X <= node_max.X) { u32 index = (p.Z - node_min.Z) * ystride + (p.X - node_min.X); return heightmap[index]; } return water_level; }
pgimeno/minetest
src/mapgen/cavegen.cpp
C++
mit
25,698
/* Minetest Copyright (C) 2010-2018 kwolekr, Ryan Kwolek <kwolekr@minetest.net> Copyright (C) 2015-2018 paramat 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. */ #pragma once #define VMANIP_FLAG_CAVE VOXELFLAG_CHECKED1 class GenerateNotifier; /* CavesNoiseIntersection is a cave digging algorithm that carves smooth, web-like, continuous tunnels at points where the density of the intersection between two separate 3d noises is above a certain value. This value, cave_width, can be modified to set the effective width of these tunnels. This algorithm is relatively heavyweight, taking ~80ms to generate an 80x80x80 chunk of map on a modern processor. Use sparingly! TODO(hmmmm): Remove dependency on biomes TODO(hmmmm): Find alternative to overgeneration as solution for sunlight issue */ class CavesNoiseIntersection { public: CavesNoiseIntersection(const NodeDefManager *nodedef, BiomeManager *biomemgr, v3s16 chunksize, NoiseParams *np_cave1, NoiseParams *np_cave2, s32 seed, float cave_width); ~CavesNoiseIntersection(); void generateCaves(MMVManip *vm, v3s16 nmin, v3s16 nmax, u8 *biomemap); private: const NodeDefManager *m_ndef; BiomeManager *m_bmgr; // configurable parameters v3s16 m_csize; float m_cave_width; // intermediate state variables u16 m_ystride; u16 m_zstride_1d; Noise *noise_cave1; Noise *noise_cave2; }; /* CavernsNoise is a cave digging algorithm */ class CavernsNoise { public: CavernsNoise(const NodeDefManager *nodedef, v3s16 chunksize, NoiseParams *np_cavern, s32 seed, float cavern_limit, float cavern_taper, float cavern_threshold); ~CavernsNoise(); bool generateCaverns(MMVManip *vm, v3s16 nmin, v3s16 nmax); private: const NodeDefManager *m_ndef; // configurable parameters v3s16 m_csize; float m_cavern_limit; float m_cavern_taper; float m_cavern_threshold; // intermediate state variables u16 m_ystride; u16 m_zstride_1d; Noise *noise_cavern; content_t c_water_source; content_t c_lava_source; }; /* CavesRandomWalk is an implementation of a cave-digging algorithm that operates on the principle of a "random walk" to approximate the stochiastic activity of cavern development. In summary, this algorithm works by carving a randomly sized tunnel in a random direction a random amount of times, randomly varying in width. All randomness here is uniformly distributed; alternative distributions have not yet been implemented. This algorithm is very fast, executing in less than 1ms on average for an 80x80x80 chunk of map on a modern processor. */ class CavesRandomWalk { public: MMVManip *vm; const NodeDefManager *ndef; GenerateNotifier *gennotify; s16 *heightmap; BiomeGen *bmgn; // configurable parameters s32 seed; int water_level; int lava_depth; NoiseParams *np_caveliquids; // intermediate state variables u16 ystride; s16 min_tunnel_diameter; s16 max_tunnel_diameter; u16 tunnel_routepoints; int part_max_length_rs; bool large_cave; bool large_cave_is_flat; bool flooded; v3s16 node_min; v3s16 node_max; v3f orp; // starting point, relative to caved space v3s16 of; // absolute coordinates of caved space v3s16 ar; // allowed route area s16 rs; // tunnel radius size v3f main_direction; s16 route_y_min; s16 route_y_max; PseudoRandom *ps; content_t c_water_source; content_t c_lava_source; // ndef is a mandatory parameter. // If gennotify is NULL, generation events are not logged. // If biomegen is NULL, cave liquids have classic behaviour. CavesRandomWalk(const NodeDefManager *ndef, GenerateNotifier *gennotify = NULL, s32 seed = 0, int water_level = 1, content_t water_source = CONTENT_IGNORE, content_t lava_source = CONTENT_IGNORE, int lava_depth = -256, BiomeGen *biomegen = NULL); // vm and ps are mandatory parameters. // If heightmap is NULL, the surface level at all points is assumed to // be water_level. void makeCave(MMVManip *vm, v3s16 nmin, v3s16 nmax, PseudoRandom *ps, bool is_large_cave, int max_stone_height, s16 *heightmap); private: void makeTunnel(bool dirswitch); void carveRoute(v3f vec, float f, bool randomize_xz); inline bool isPosAboveSurface(v3s16 p); }; /* CavesV6 is the original version of caves used with Mapgen V6. Though it uses the same fundamental algorithm as CavesRandomWalk, it is made separate to preserve the exact sequence of PseudoRandom calls - any change to this ordering results in the output being radically different. Because caves in Mapgen V6 are responsible for a large portion of the basic terrain shape, modifying this will break our contract of reverse compatibility for a 'stable' mapgen such as V6. tl;dr, *** DO NOT TOUCH THIS CLASS UNLESS YOU KNOW WHAT YOU ARE DOING *** */ class CavesV6 { public: MMVManip *vm; const NodeDefManager *ndef; GenerateNotifier *gennotify; PseudoRandom *ps; PseudoRandom *ps2; // configurable parameters s16 *heightmap; content_t c_water_source; content_t c_lava_source; int water_level; // intermediate state variables u16 ystride; s16 min_tunnel_diameter; s16 max_tunnel_diameter; u16 tunnel_routepoints; int part_max_length_rs; bool large_cave; bool large_cave_is_flat; v3s16 node_min; v3s16 node_max; v3f orp; // starting point, relative to caved space v3s16 of; // absolute coordinates of caved space v3s16 ar; // allowed route area s16 rs; // tunnel radius size v3f main_direction; s16 route_y_min; s16 route_y_max; // ndef is a mandatory parameter. // If gennotify is NULL, generation events are not logged. CavesV6(const NodeDefManager *ndef, GenerateNotifier *gennotify = NULL, int water_level = 1, content_t water_source = CONTENT_IGNORE, content_t lava_source = CONTENT_IGNORE); // vm, ps, and ps2 are mandatory parameters. // If heightmap is NULL, the surface level at all points is assumed to // be water_level. void makeCave(MMVManip *vm, v3s16 nmin, v3s16 nmax, PseudoRandom *ps, PseudoRandom *ps2, bool is_large_cave, int max_stone_height, s16 *heightmap = NULL); private: void makeTunnel(bool dirswitch); void carveRoute(v3f vec, float f, bool randomize_xz, bool tunnel_above_ground); inline s16 getSurfaceFromHeightmap(v3s16 p); };
pgimeno/minetest
src/mapgen/cavegen.h
C++
mit
6,860
/* Minetest Copyright (C) 2010-2018 celeron55, Perttu Ahola <celeron55@gmail.com> Copyright (C) 2015-2018 paramat 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 "dungeongen.h" #include <cmath> #include "mapgen.h" #include "voxel.h" #include "noise.h" #include "mapblock.h" #include "mapnode.h" #include "map.h" #include "nodedef.h" #include "settings.h" //#define DGEN_USE_TORCHES NoiseParams nparams_dungeon_density(0.9, 0.5, v3f(500.0, 500.0, 500.0), 0, 2, 0.8, 2.0); NoiseParams nparams_dungeon_alt_wall(-0.4, 1.0, v3f(40.0, 40.0, 40.0), 32474, 6, 1.1, 2.0); /////////////////////////////////////////////////////////////////////////////// DungeonGen::DungeonGen(const NodeDefManager *ndef, GenerateNotifier *gennotify, DungeonParams *dparams) { assert(ndef); this->ndef = ndef; this->gennotify = gennotify; #ifdef DGEN_USE_TORCHES c_torch = ndef->getId("default:torch"); #endif if (dparams) { dp = *dparams; } else { // Default dungeon parameters dp.seed = 0; dp.c_wall = ndef->getId("mapgen_cobble"); dp.c_alt_wall = ndef->getId("mapgen_mossycobble"); dp.c_stair = ndef->getId("mapgen_stair_cobble"); dp.diagonal_dirs = false; dp.only_in_ground = true; dp.holesize = v3s16(1, 2, 1); dp.corridor_len_min = 1; dp.corridor_len_max = 13; dp.room_size_min = v3s16(4, 4, 4); dp.room_size_max = v3s16(8, 6, 8); dp.room_size_large_min = v3s16(8, 8, 8); dp.room_size_large_max = v3s16(16, 16, 16); dp.rooms_min = 2; dp.rooms_max = 16; dp.notifytype = GENNOTIFY_DUNGEON; dp.np_density = nparams_dungeon_density; dp.np_alt_wall = nparams_dungeon_alt_wall; } } void DungeonGen::generate(MMVManip *vm, u32 bseed, v3s16 nmin, v3s16 nmax) { assert(vm); //TimeTaker t("gen dungeons"); float nval_density = NoisePerlin3D(&dp.np_density, nmin.X, nmin.Y, nmin.Z, dp.seed); if (nval_density < 1.0f) return; static const bool preserve_ignore = !g_settings->getBool("projecting_dungeons"); this->vm = vm; this->blockseed = bseed; random.seed(bseed + 2); // Dungeon generator doesn't modify places which have this set vm->clearFlag(VMANIP_FLAG_DUNGEON_INSIDE | VMANIP_FLAG_DUNGEON_PRESERVE); if (dp.only_in_ground) { // Set all air and liquid drawtypes to be untouchable to make dungeons // open to air and liquids. // Optionally set ignore to be untouchable to prevent projecting dungeons. // Like randomwalk caves, preserve nodes that have 'is_ground_content = false', // to avoid dungeons that generate out beyond the edge of a mapchunk destroying // nodes added by mods in 'register_on_generated()'. for (s16 z = nmin.Z; z <= nmax.Z; z++) { for (s16 y = nmin.Y; y <= nmax.Y; y++) { u32 i = vm->m_area.index(nmin.X, y, z); for (s16 x = nmin.X; x <= nmax.X; x++) { content_t c = vm->m_data[i].getContent(); NodeDrawType dtype = ndef->get(c).drawtype; if (dtype == NDT_AIRLIKE || dtype == NDT_LIQUID || (preserve_ignore && c == CONTENT_IGNORE) || !ndef->get(c).is_ground_content) vm->m_flags[i] |= VMANIP_FLAG_DUNGEON_PRESERVE; i++; } } } } // Add them for (u32 i = 0; i < std::floor(nval_density); i++) makeDungeon(v3s16(1, 1, 1) * MAP_BLOCKSIZE); // Optionally convert some structure to alternative structure if (dp.c_alt_wall == CONTENT_IGNORE) return; for (s16 z = nmin.Z; z <= nmax.Z; z++) for (s16 y = nmin.Y; y <= nmax.Y; y++) { u32 i = vm->m_area.index(nmin.X, y, z); for (s16 x = nmin.X; x <= nmax.X; x++) { if (vm->m_data[i].getContent() == dp.c_wall) { if (NoisePerlin3D(&dp.np_alt_wall, x, y, z, blockseed) > 0.0f) vm->m_data[i].setContent(dp.c_alt_wall); } i++; } } //printf("== gen dungeons: %dms\n", t.stop()); } void DungeonGen::makeDungeon(v3s16 start_padding) { const v3s16 &areasize = vm->m_area.getExtent(); v3s16 roomsize; v3s16 roomplace; /* Find place for first room. There is a 1 in 4 chance of the first room being 'large', all other rooms are not 'large'. */ bool fits = false; for (u32 i = 0; i < 100 && !fits; i++) { bool is_large_room = ((random.next() & 3) == 1); if (is_large_room) { roomsize.Z = random.range( dp.room_size_large_min.Z, dp.room_size_large_max.Z); roomsize.Y = random.range( dp.room_size_large_min.Y, dp.room_size_large_max.Y); roomsize.X = random.range( dp.room_size_large_min.X, dp.room_size_large_max.X); } else { roomsize.Z = random.range(dp.room_size_min.Z, dp.room_size_max.Z); roomsize.Y = random.range(dp.room_size_min.Y, dp.room_size_max.Y); roomsize.X = random.range(dp.room_size_min.X, dp.room_size_max.X); } // start_padding is used to disallow starting the generation of // a dungeon in a neighboring generation chunk roomplace = vm->m_area.MinEdge + start_padding; roomplace.Z += random.range(0, areasize.Z - roomsize.Z - start_padding.Z); roomplace.Y += random.range(0, areasize.Y - roomsize.Y - start_padding.Y); roomplace.X += random.range(0, areasize.X - roomsize.X - start_padding.X); /* Check that we're not putting the room to an unknown place, otherwise it might end up floating in the air */ fits = true; for (s16 z = 0; z < roomsize.Z; z++) for (s16 y = 0; y < roomsize.Y; y++) for (s16 x = 0; x < roomsize.X; x++) { v3s16 p = roomplace + v3s16(x, y, z); u32 vi = vm->m_area.index(p); if ((vm->m_flags[vi] & VMANIP_FLAG_DUNGEON_UNTOUCHABLE) || vm->m_data[vi].getContent() == CONTENT_IGNORE) { fits = false; break; } } } // No place found if (!fits) return; /* Stores the center position of the last room made, so that a new corridor can be started from the last room instead of the new room, if chosen so. */ v3s16 last_room_center = roomplace + v3s16(roomsize.X / 2, 1, roomsize.Z / 2); u32 room_count = random.range(dp.rooms_min, dp.rooms_max); for (u32 i = 0; i < room_count; i++) { // Make a room to the determined place makeRoom(roomsize, roomplace); v3s16 room_center = roomplace + v3s16(roomsize.X / 2, 1, roomsize.Z / 2); if (gennotify) gennotify->addEvent(dp.notifytype, room_center); #ifdef DGEN_USE_TORCHES // Place torch at room center (for testing) vm->m_data[vm->m_area.index(room_center)] = MapNode(c_torch); #endif // Quit if last room if (i == room_count - 1) break; // Determine walker start position bool start_in_last_room = (random.range(0, 2) != 0); v3s16 walker_start_place; if (start_in_last_room) { walker_start_place = last_room_center; } else { walker_start_place = room_center; // Store center of current room as the last one last_room_center = room_center; } // Create walker and find a place for a door v3s16 doorplace; v3s16 doordir; m_pos = walker_start_place; if (!findPlaceForDoor(doorplace, doordir)) return; if (random.range(0, 1) == 0) // Make the door makeDoor(doorplace, doordir); else // Don't actually make a door doorplace -= doordir; // Make a random corridor starting from the door v3s16 corridor_end; v3s16 corridor_end_dir; makeCorridor(doorplace, doordir, corridor_end, corridor_end_dir); // Find a place for a random sized room roomsize.Z = random.range(dp.room_size_min.Z, dp.room_size_max.Z); roomsize.Y = random.range(dp.room_size_min.Y, dp.room_size_max.Y); roomsize.X = random.range(dp.room_size_min.X, dp.room_size_max.X); m_pos = corridor_end; m_dir = corridor_end_dir; if (!findPlaceForRoomDoor(roomsize, doorplace, doordir, roomplace)) return; if (random.range(0, 1) == 0) // Make the door makeDoor(doorplace, doordir); else // Don't actually make a door roomplace -= doordir; } } void DungeonGen::makeRoom(v3s16 roomsize, v3s16 roomplace) { MapNode n_wall(dp.c_wall); MapNode n_air(CONTENT_AIR); // Make +-X walls for (s16 z = 0; z < roomsize.Z; z++) for (s16 y = 0; y < roomsize.Y; y++) { { v3s16 p = roomplace + v3s16(0, y, z); if (!vm->m_area.contains(p)) continue; u32 vi = vm->m_area.index(p); if (vm->m_flags[vi] & VMANIP_FLAG_DUNGEON_UNTOUCHABLE) continue; vm->m_data[vi] = n_wall; } { v3s16 p = roomplace + v3s16(roomsize.X - 1, y, z); if (!vm->m_area.contains(p)) continue; u32 vi = vm->m_area.index(p); if (vm->m_flags[vi] & VMANIP_FLAG_DUNGEON_UNTOUCHABLE) continue; vm->m_data[vi] = n_wall; } } // Make +-Z walls for (s16 x = 0; x < roomsize.X; x++) for (s16 y = 0; y < roomsize.Y; y++) { { v3s16 p = roomplace + v3s16(x, y, 0); if (!vm->m_area.contains(p)) continue; u32 vi = vm->m_area.index(p); if (vm->m_flags[vi] & VMANIP_FLAG_DUNGEON_UNTOUCHABLE) continue; vm->m_data[vi] = n_wall; } { v3s16 p = roomplace + v3s16(x, y, roomsize.Z - 1); if (!vm->m_area.contains(p)) continue; u32 vi = vm->m_area.index(p); if (vm->m_flags[vi] & VMANIP_FLAG_DUNGEON_UNTOUCHABLE) continue; vm->m_data[vi] = n_wall; } } // Make +-Y walls (floor and ceiling) for (s16 z = 0; z < roomsize.Z; z++) for (s16 x = 0; x < roomsize.X; x++) { { v3s16 p = roomplace + v3s16(x, 0, z); if (!vm->m_area.contains(p)) continue; u32 vi = vm->m_area.index(p); if (vm->m_flags[vi] & VMANIP_FLAG_DUNGEON_UNTOUCHABLE) continue; vm->m_data[vi] = n_wall; } { v3s16 p = roomplace + v3s16(x,roomsize. Y - 1, z); if (!vm->m_area.contains(p)) continue; u32 vi = vm->m_area.index(p); if (vm->m_flags[vi] & VMANIP_FLAG_DUNGEON_UNTOUCHABLE) continue; vm->m_data[vi] = n_wall; } } // Fill with air for (s16 z = 1; z < roomsize.Z - 1; z++) for (s16 y = 1; y < roomsize.Y - 1; y++) for (s16 x = 1; x < roomsize.X - 1; x++) { v3s16 p = roomplace + v3s16(x, y, z); if (!vm->m_area.contains(p)) continue; u32 vi = vm->m_area.index(p); vm->m_flags[vi] |= VMANIP_FLAG_DUNGEON_UNTOUCHABLE; vm->m_data[vi] = n_air; } } void DungeonGen::makeFill(v3s16 place, v3s16 size, u8 avoid_flags, MapNode n, u8 or_flags) { for (s16 z = 0; z < size.Z; z++) for (s16 y = 0; y < size.Y; y++) for (s16 x = 0; x < size.X; x++) { v3s16 p = place + v3s16(x, y, z); if (!vm->m_area.contains(p)) continue; u32 vi = vm->m_area.index(p); if (vm->m_flags[vi] & avoid_flags) continue; vm->m_flags[vi] |= or_flags; vm->m_data[vi] = n; } } void DungeonGen::makeHole(v3s16 place) { makeFill(place, dp.holesize, 0, MapNode(CONTENT_AIR), VMANIP_FLAG_DUNGEON_INSIDE); } void DungeonGen::makeDoor(v3s16 doorplace, v3s16 doordir) { makeHole(doorplace); #ifdef DGEN_USE_TORCHES // Place torch (for testing) vm->m_data[vm->m_area.index(doorplace)] = MapNode(c_torch); #endif } void DungeonGen::makeCorridor(v3s16 doorplace, v3s16 doordir, v3s16 &result_place, v3s16 &result_dir) { makeHole(doorplace); v3s16 p0 = doorplace; v3s16 dir = doordir; u32 length = random.range(dp.corridor_len_min, dp.corridor_len_max); u32 partlength = random.range(dp.corridor_len_min, dp.corridor_len_max); u32 partcount = 0; s16 make_stairs = 0; if (random.next() % 2 == 0 && partlength >= 3) make_stairs = random.next() % 2 ? 1 : -1; for (u32 i = 0; i < length; i++) { v3s16 p = p0 + dir; if (partcount != 0) p.Y += make_stairs; // Check segment of minimum size corridor is in voxelmanip if (vm->m_area.contains(p) && vm->m_area.contains(p + v3s16(0, 1, 0))) { if (make_stairs) { makeFill(p + v3s16(-1, -1, -1), dp.holesize + v3s16(2, 3, 2), VMANIP_FLAG_DUNGEON_UNTOUCHABLE, MapNode(dp.c_wall), 0); makeFill(p, dp.holesize, VMANIP_FLAG_DUNGEON_UNTOUCHABLE, MapNode(CONTENT_AIR), VMANIP_FLAG_DUNGEON_INSIDE); makeFill(p - dir, dp.holesize, VMANIP_FLAG_DUNGEON_UNTOUCHABLE, MapNode(CONTENT_AIR), VMANIP_FLAG_DUNGEON_INSIDE); // TODO: fix stairs code so it works 100% // (quite difficult) // exclude stairs from the bottom step // exclude stairs from diagonal steps if (((dir.X ^ dir.Z) & 1) && (((make_stairs == 1) && i != 0) || ((make_stairs == -1) && i != length - 1))) { // rotate face 180 deg if // making stairs backwards int facedir = dir_to_facedir(dir * make_stairs); v3s16 ps = p; u16 stair_width = (dir.Z != 0) ? dp.holesize.X : dp.holesize.Z; // Stair width direction vector v3s16 swv = (dir.Z != 0) ? v3s16(1, 0, 0) : v3s16(0, 0, 1); for (u16 st = 0; st < stair_width; st++) { if (make_stairs == -1) { u32 vi = vm->m_area.index(ps.X - dir.X, ps.Y - 1, ps.Z - dir.Z); if (vm->m_area.contains(ps + v3s16(-dir.X, -1, -dir.Z)) && vm->m_data[vi].getContent() == dp.c_wall) { vm->m_flags[vi] |= VMANIP_FLAG_DUNGEON_UNTOUCHABLE; vm->m_data[vi] = MapNode(dp.c_stair, 0, facedir); } } else if (make_stairs == 1) { u32 vi = vm->m_area.index(ps.X, ps.Y - 1, ps.Z); if (vm->m_area.contains(ps + v3s16(0, -1, 0)) && vm->m_data[vi].getContent() == dp.c_wall) { vm->m_flags[vi] |= VMANIP_FLAG_DUNGEON_UNTOUCHABLE; vm->m_data[vi] = MapNode(dp.c_stair, 0, facedir); } } ps += swv; } } } else { makeFill(p + v3s16(-1, -1, -1), dp.holesize + v3s16(2, 2, 2), VMANIP_FLAG_DUNGEON_UNTOUCHABLE, MapNode(dp.c_wall), 0); makeHole(p); } p0 = p; } else { // Can't go here, turn away dir = turn_xz(dir, random.range(0, 1)); make_stairs = -make_stairs; partcount = 0; partlength = random.range(1, length); continue; } partcount++; if (partcount >= partlength) { partcount = 0; random_turn(random, dir); partlength = random.range(1, length); make_stairs = 0; if (random.next() % 2 == 0 && partlength >= 3) make_stairs = random.next() % 2 ? 1 : -1; } } result_place = p0; result_dir = dir; } bool DungeonGen::findPlaceForDoor(v3s16 &result_place, v3s16 &result_dir) { for (u32 i = 0; i < 100; i++) { v3s16 p = m_pos + m_dir; v3s16 p1 = p + v3s16(0, 1, 0); if (!vm->m_area.contains(p) || !vm->m_area.contains(p1) || i % 4 == 0) { randomizeDir(); continue; } if (vm->getNodeNoExNoEmerge(p).getContent() == dp.c_wall && vm->getNodeNoExNoEmerge(p1).getContent() == dp.c_wall) { // Found wall, this is a good place! result_place = p; result_dir = m_dir; // Randomize next direction randomizeDir(); return true; } /* Determine where to move next */ // Jump one up if the actual space is there if (vm->getNodeNoExNoEmerge(p + v3s16(0, 0, 0)).getContent() == dp.c_wall && vm->getNodeNoExNoEmerge(p + v3s16(0, 1, 0)).getContent() == CONTENT_AIR && vm->getNodeNoExNoEmerge(p + v3s16(0, 2, 0)).getContent() == CONTENT_AIR) p += v3s16(0,1,0); // Jump one down if the actual space is there if (vm->getNodeNoExNoEmerge(p + v3s16(0, 1, 0)).getContent() == dp.c_wall && vm->getNodeNoExNoEmerge(p + v3s16(0, 0, 0)).getContent() == CONTENT_AIR && vm->getNodeNoExNoEmerge(p + v3s16(0, -1, 0)).getContent() == CONTENT_AIR) p += v3s16(0, -1, 0); // Check if walking is now possible if (vm->getNodeNoExNoEmerge(p).getContent() != CONTENT_AIR || vm->getNodeNoExNoEmerge(p + v3s16(0, 1, 0)).getContent() != CONTENT_AIR) { // Cannot continue walking here randomizeDir(); continue; } // Move there m_pos = p; } return false; } bool DungeonGen::findPlaceForRoomDoor(v3s16 roomsize, v3s16 &result_doorplace, v3s16 &result_doordir, v3s16 &result_roomplace) { for (s16 trycount = 0; trycount < 30; trycount++) { v3s16 doorplace; v3s16 doordir; bool r = findPlaceForDoor(doorplace, doordir); if (!r) continue; v3s16 roomplace; // X east, Z north, Y up if (doordir == v3s16(1, 0, 0)) // X+ roomplace = doorplace + v3s16(0, -1, random.range(-roomsize.Z + 2, -2)); if (doordir == v3s16(-1, 0, 0)) // X- roomplace = doorplace + v3s16(-roomsize.X + 1, -1, random.range(-roomsize.Z + 2, -2)); if (doordir == v3s16(0, 0, 1)) // Z+ roomplace = doorplace + v3s16(random.range(-roomsize.X + 2, -2), -1, 0); if (doordir == v3s16(0, 0, -1)) // Z- roomplace = doorplace + v3s16(random.range(-roomsize.X + 2, -2), -1, -roomsize.Z + 1); // Check fit bool fits = true; for (s16 z = 1; z < roomsize.Z - 1; z++) for (s16 y = 1; y < roomsize.Y - 1; y++) for (s16 x = 1; x < roomsize.X - 1; x++) { v3s16 p = roomplace + v3s16(x, y, z); if (!vm->m_area.contains(p)) { fits = false; break; } if (vm->m_flags[vm->m_area.index(p)] & VMANIP_FLAG_DUNGEON_INSIDE) { fits = false; break; } } if (!fits) { // Find new place continue; } result_doorplace = doorplace; result_doordir = doordir; result_roomplace = roomplace; return true; } return false; } v3s16 rand_ortho_dir(PseudoRandom &random, bool diagonal_dirs) { // Make diagonal directions somewhat rare if (diagonal_dirs && (random.next() % 4 == 0)) { v3s16 dir; int trycount = 0; do { trycount++; dir.Z = random.next() % 3 - 1; dir.Y = 0; dir.X = random.next() % 3 - 1; } while ((dir.X == 0 || dir.Z == 0) && trycount < 10); return dir; } if (random.next() % 2 == 0) return random.next() % 2 ? v3s16(-1, 0, 0) : v3s16(1, 0, 0); return random.next() % 2 ? v3s16(0, 0, -1) : v3s16(0, 0, 1); } v3s16 turn_xz(v3s16 olddir, int t) { v3s16 dir; if (t == 0) { // Turn right dir.X = olddir.Z; dir.Z = -olddir.X; dir.Y = olddir.Y; } else { // Turn left dir.X = -olddir.Z; dir.Z = olddir.X; dir.Y = olddir.Y; } return dir; } void random_turn(PseudoRandom &random, v3s16 &dir) { int turn = random.range(0, 2); if (turn == 0) { // Go straight: nothing to do return; } else if (turn == 1) { // Turn right dir = turn_xz(dir, 0); } else { // Turn left dir = turn_xz(dir, 1); } } int dir_to_facedir(v3s16 d) { if (abs(d.X) > abs(d.Z)) return d.X < 0 ? 3 : 1; return d.Z < 0 ? 2 : 0; }
pgimeno/minetest
src/mapgen/dungeongen.cpp
C++
mit
18,617
/* Minetest Copyright (C) 2010-2018 celeron55, Perttu Ahola <celeron55@gmail.com> Copyright (C) 2015-2018 paramat 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. */ #pragma once #include "voxel.h" #include "noise.h" #include "mapgen.h" #define VMANIP_FLAG_DUNGEON_INSIDE VOXELFLAG_CHECKED1 #define VMANIP_FLAG_DUNGEON_PRESERVE VOXELFLAG_CHECKED2 #define VMANIP_FLAG_DUNGEON_UNTOUCHABLE (\ VMANIP_FLAG_DUNGEON_INSIDE|VMANIP_FLAG_DUNGEON_PRESERVE) class MMVManip; class NodeDefManager; v3s16 rand_ortho_dir(PseudoRandom &random, bool diagonal_dirs); v3s16 turn_xz(v3s16 olddir, int t); void random_turn(PseudoRandom &random, v3s16 &dir); int dir_to_facedir(v3s16 d); struct DungeonParams { s32 seed; content_t c_wall; content_t c_alt_wall; content_t c_stair; bool diagonal_dirs; bool only_in_ground; v3s16 holesize; u16 corridor_len_min; u16 corridor_len_max; v3s16 room_size_min; v3s16 room_size_max; v3s16 room_size_large_min; v3s16 room_size_large_max; u16 rooms_min; u16 rooms_max; GenNotifyType notifytype; NoiseParams np_density; NoiseParams np_alt_wall; }; class DungeonGen { public: MMVManip *vm = nullptr; const NodeDefManager *ndef; GenerateNotifier *gennotify; u32 blockseed; PseudoRandom random; v3s16 csize; content_t c_torch; DungeonParams dp; // RoomWalker v3s16 m_pos; v3s16 m_dir; DungeonGen(const NodeDefManager *ndef, GenerateNotifier *gennotify, DungeonParams *dparams); void generate(MMVManip *vm, u32 bseed, v3s16 full_node_min, v3s16 full_node_max); void makeDungeon(v3s16 start_padding); void makeRoom(v3s16 roomsize, v3s16 roomplace); void makeCorridor(v3s16 doorplace, v3s16 doordir, v3s16 &result_place, v3s16 &result_dir); void makeDoor(v3s16 doorplace, v3s16 doordir); void makeFill(v3s16 place, v3s16 size, u8 avoid_flags, MapNode n, u8 or_flags); void makeHole(v3s16 place); bool findPlaceForDoor(v3s16 &result_place, v3s16 &result_dir); bool findPlaceForRoomDoor(v3s16 roomsize, v3s16 &result_doorplace, v3s16 &result_doordir, v3s16 &result_roomplace); inline void randomizeDir() { m_dir = rand_ortho_dir(random, dp.diagonal_dirs); } }; extern NoiseParams nparams_dungeon_density; extern NoiseParams nparams_dungeon_alt_wall;
pgimeno/minetest
src/mapgen/dungeongen.h
C++
mit
2,887
/* Minetest Copyright (C) 2010-2018 celeron55, Perttu Ahola <celeron55@gmail.com> Copyright (C) 2013-2018 kwolekr, Ryan Kwolek <kwolekr@minetest.net> Copyright (C) 2015-2018 paramat 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 "mapgen.h" #include "voxel.h" #include "noise.h" #include "gamedef.h" #include "mg_biome.h" #include "mapblock.h" #include "mapnode.h" #include "map.h" #include "content_sao.h" #include "nodedef.h" #include "emerge.h" #include "voxelalgorithms.h" #include "porting.h" #include "profiler.h" #include "settings.h" #include "treegen.h" #include "serialization.h" #include "util/serialize.h" #include "util/numeric.h" #include "filesys.h" #include "log.h" #include "mapgen_carpathian.h" #include "mapgen_flat.h" #include "mapgen_fractal.h" #include "mapgen_v5.h" #include "mapgen_v6.h" #include "mapgen_v7.h" #include "mapgen_valleys.h" #include "mapgen_singlenode.h" #include "cavegen.h" #include "dungeongen.h" FlagDesc flagdesc_mapgen[] = { {"caves", MG_CAVES}, {"dungeons", MG_DUNGEONS}, {"light", MG_LIGHT}, {"decorations", MG_DECORATIONS}, {"biomes", MG_BIOMES}, {NULL, 0} }; FlagDesc flagdesc_gennotify[] = { {"dungeon", 1 << GENNOTIFY_DUNGEON}, {"temple", 1 << GENNOTIFY_TEMPLE}, {"cave_begin", 1 << GENNOTIFY_CAVE_BEGIN}, {"cave_end", 1 << GENNOTIFY_CAVE_END}, {"large_cave_begin", 1 << GENNOTIFY_LARGECAVE_BEGIN}, {"large_cave_end", 1 << GENNOTIFY_LARGECAVE_END}, {"decoration", 1 << GENNOTIFY_DECORATION}, {NULL, 0} }; struct MapgenDesc { const char *name; bool is_user_visible; }; //// //// Built-in mapgens //// static MapgenDesc g_reg_mapgens[] = { {"v5", true}, {"v6", true}, {"v7", true}, {"flat", true}, {"fractal", true}, {"valleys", true}, {"singlenode", true}, {"carpathian", true}, }; STATIC_ASSERT( ARRLEN(g_reg_mapgens) == MAPGEN_INVALID, registered_mapgens_is_wrong_size); //// //// Mapgen //// Mapgen::Mapgen(int mapgenid, MapgenParams *params, EmergeManager *emerge) : gennotify(emerge->gen_notify_on, &emerge->gen_notify_on_deco_ids) { id = mapgenid; water_level = params->water_level; mapgen_limit = params->mapgen_limit; flags = params->flags; csize = v3s16(1, 1, 1) * (params->chunksize * MAP_BLOCKSIZE); /* We are losing half our entropy by doing this, but it is necessary to preserve reverse compatibility. If the top half of our current 64 bit seeds ever starts getting used, existing worlds will break due to a different hash outcome and no way to differentiate between versions. A solution could be to add a new bit to designate that the top half of the seed value should be used, essentially a 1-bit version code, but this would require increasing the total size of a seed to 9 bytes (yuck) It's probably okay if this never gets fixed. 4.2 billion possibilities ought to be enough for anyone. */ seed = (s32)params->seed; ndef = emerge->ndef; } MapgenType Mapgen::getMapgenType(const std::string &mgname) { for (size_t i = 0; i != ARRLEN(g_reg_mapgens); i++) { if (mgname == g_reg_mapgens[i].name) return (MapgenType)i; } return MAPGEN_INVALID; } const char *Mapgen::getMapgenName(MapgenType mgtype) { size_t index = (size_t)mgtype; if (index == MAPGEN_INVALID || index >= ARRLEN(g_reg_mapgens)) return "invalid"; return g_reg_mapgens[index].name; } Mapgen *Mapgen::createMapgen(MapgenType mgtype, MapgenParams *params, EmergeManager *emerge) { switch (mgtype) { case MAPGEN_CARPATHIAN: return new MapgenCarpathian((MapgenCarpathianParams *)params, emerge); case MAPGEN_FLAT: return new MapgenFlat((MapgenFlatParams *)params, emerge); case MAPGEN_FRACTAL: return new MapgenFractal((MapgenFractalParams *)params, emerge); case MAPGEN_SINGLENODE: return new MapgenSinglenode((MapgenSinglenodeParams *)params, emerge); case MAPGEN_V5: return new MapgenV5((MapgenV5Params *)params, emerge); case MAPGEN_V6: return new MapgenV6((MapgenV6Params *)params, emerge); case MAPGEN_V7: return new MapgenV7((MapgenV7Params *)params, emerge); case MAPGEN_VALLEYS: return new MapgenValleys((MapgenValleysParams *)params, emerge); default: return nullptr; } } MapgenParams *Mapgen::createMapgenParams(MapgenType mgtype) { switch (mgtype) { case MAPGEN_CARPATHIAN: return new MapgenCarpathianParams; case MAPGEN_FLAT: return new MapgenFlatParams; case MAPGEN_FRACTAL: return new MapgenFractalParams; case MAPGEN_SINGLENODE: return new MapgenSinglenodeParams; case MAPGEN_V5: return new MapgenV5Params; case MAPGEN_V6: return new MapgenV6Params; case MAPGEN_V7: return new MapgenV7Params; case MAPGEN_VALLEYS: return new MapgenValleysParams; default: return nullptr; } } void Mapgen::getMapgenNames(std::vector<const char *> *mgnames, bool include_hidden) { for (u32 i = 0; i != ARRLEN(g_reg_mapgens); i++) { if (include_hidden || g_reg_mapgens[i].is_user_visible) mgnames->push_back(g_reg_mapgens[i].name); } } u32 Mapgen::getBlockSeed(v3s16 p, s32 seed) { return (u32)seed + p.Z * 38134234 + p.Y * 42123 + p.X * 23; } u32 Mapgen::getBlockSeed2(v3s16 p, s32 seed) { u32 n = 1619 * p.X + 31337 * p.Y + 52591 * p.Z + 1013 * seed; n = (n >> 13) ^ n; return (n * (n * n * 60493 + 19990303) + 1376312589); } // Returns Y one under area minimum if not found s16 Mapgen::findGroundLevelFull(v2s16 p2d) { const v3s16 &em = vm->m_area.getExtent(); s16 y_nodes_max = vm->m_area.MaxEdge.Y; s16 y_nodes_min = vm->m_area.MinEdge.Y; u32 i = vm->m_area.index(p2d.X, y_nodes_max, p2d.Y); s16 y; for (y = y_nodes_max; y >= y_nodes_min; y--) { MapNode &n = vm->m_data[i]; if (ndef->get(n).walkable) break; VoxelArea::add_y(em, i, -1); } return (y >= y_nodes_min) ? y : y_nodes_min - 1; } // Returns -MAX_MAP_GENERATION_LIMIT if not found s16 Mapgen::findGroundLevel(v2s16 p2d, s16 ymin, s16 ymax) { const v3s16 &em = vm->m_area.getExtent(); u32 i = vm->m_area.index(p2d.X, ymax, p2d.Y); s16 y; for (y = ymax; y >= ymin; y--) { MapNode &n = vm->m_data[i]; if (ndef->get(n).walkable) break; VoxelArea::add_y(em, i, -1); } return (y >= ymin) ? y : -MAX_MAP_GENERATION_LIMIT; } // Returns -MAX_MAP_GENERATION_LIMIT if not found or if ground is found first s16 Mapgen::findLiquidSurface(v2s16 p2d, s16 ymin, s16 ymax) { const v3s16 &em = vm->m_area.getExtent(); u32 i = vm->m_area.index(p2d.X, ymax, p2d.Y); s16 y; for (y = ymax; y >= ymin; y--) { MapNode &n = vm->m_data[i]; if (ndef->get(n).walkable) return -MAX_MAP_GENERATION_LIMIT; if (ndef->get(n).isLiquid()) break; VoxelArea::add_y(em, i, -1); } return (y >= ymin) ? y : -MAX_MAP_GENERATION_LIMIT; } void Mapgen::updateHeightmap(v3s16 nmin, v3s16 nmax) { if (!heightmap) return; //TimeTaker t("Mapgen::updateHeightmap", NULL, PRECISION_MICRO); int index = 0; for (s16 z = nmin.Z; z <= nmax.Z; z++) { for (s16 x = nmin.X; x <= nmax.X; x++, index++) { s16 y = findGroundLevel(v2s16(x, z), nmin.Y, nmax.Y); heightmap[index] = y; } } } void Mapgen::getSurfaces(v2s16 p2d, s16 ymin, s16 ymax, std::vector<s16> &floors, std::vector<s16> &ceilings) { const v3s16 &em = vm->m_area.getExtent(); bool is_walkable = false; u32 vi = vm->m_area.index(p2d.X, ymax, p2d.Y); MapNode mn_max = vm->m_data[vi]; bool walkable_above = ndef->get(mn_max).walkable; VoxelArea::add_y(em, vi, -1); for (s16 y = ymax - 1; y >= ymin; y--) { MapNode mn = vm->m_data[vi]; is_walkable = ndef->get(mn).walkable; if (is_walkable && !walkable_above) { floors.push_back(y); } else if (!is_walkable && walkable_above) { ceilings.push_back(y + 1); } VoxelArea::add_y(em, vi, -1); walkable_above = is_walkable; } } inline bool Mapgen::isLiquidHorizontallyFlowable(u32 vi, v3s16 em) { u32 vi_neg_x = vi; VoxelArea::add_x(em, vi_neg_x, -1); if (vm->m_data[vi_neg_x].getContent() != CONTENT_IGNORE) { const ContentFeatures &c_nx = ndef->get(vm->m_data[vi_neg_x]); if (c_nx.floodable && !c_nx.isLiquid()) return true; } u32 vi_pos_x = vi; VoxelArea::add_x(em, vi_pos_x, +1); if (vm->m_data[vi_pos_x].getContent() != CONTENT_IGNORE) { const ContentFeatures &c_px = ndef->get(vm->m_data[vi_pos_x]); if (c_px.floodable && !c_px.isLiquid()) return true; } u32 vi_neg_z = vi; VoxelArea::add_z(em, vi_neg_z, -1); if (vm->m_data[vi_neg_z].getContent() != CONTENT_IGNORE) { const ContentFeatures &c_nz = ndef->get(vm->m_data[vi_neg_z]); if (c_nz.floodable && !c_nz.isLiquid()) return true; } u32 vi_pos_z = vi; VoxelArea::add_z(em, vi_pos_z, +1); if (vm->m_data[vi_pos_z].getContent() != CONTENT_IGNORE) { const ContentFeatures &c_pz = ndef->get(vm->m_data[vi_pos_z]); if (c_pz.floodable && !c_pz.isLiquid()) return true; } return false; } void Mapgen::updateLiquid(UniqueQueue<v3s16> *trans_liquid, v3s16 nmin, v3s16 nmax) { bool isignored, isliquid, wasignored, wasliquid, waschecked, waspushed; const v3s16 &em = vm->m_area.getExtent(); for (s16 z = nmin.Z + 1; z <= nmax.Z - 1; z++) for (s16 x = nmin.X + 1; x <= nmax.X - 1; x++) { wasignored = true; wasliquid = false; waschecked = false; waspushed = false; u32 vi = vm->m_area.index(x, nmax.Y, z); for (s16 y = nmax.Y; y >= nmin.Y; y--) { isignored = vm->m_data[vi].getContent() == CONTENT_IGNORE; isliquid = ndef->get(vm->m_data[vi]).isLiquid(); if (isignored || wasignored || isliquid == wasliquid) { // Neither topmost node of liquid column nor topmost node below column waschecked = false; waspushed = false; } else if (isliquid) { // This is the topmost node in the column bool ispushed = false; if (isLiquidHorizontallyFlowable(vi, em)) { trans_liquid->push_back(v3s16(x, y, z)); ispushed = true; } // Remember waschecked and waspushed to avoid repeated // checks/pushes in case the column consists of only this node waschecked = true; waspushed = ispushed; } else { // This is the topmost node below a liquid column u32 vi_above = vi; VoxelArea::add_y(em, vi_above, 1); if (!waspushed && (ndef->get(vm->m_data[vi]).floodable || (!waschecked && isLiquidHorizontallyFlowable(vi_above, em)))) { // Push back the lowest node in the column which is one // node above this one trans_liquid->push_back(v3s16(x, y + 1, z)); } } wasliquid = isliquid; wasignored = isignored; VoxelArea::add_y(em, vi, -1); } } } void Mapgen::setLighting(u8 light, v3s16 nmin, v3s16 nmax) { ScopeProfiler sp(g_profiler, "EmergeThread: mapgen lighting update", SPT_AVG); VoxelArea a(nmin, nmax); for (int z = a.MinEdge.Z; z <= a.MaxEdge.Z; z++) { for (int y = a.MinEdge.Y; y <= a.MaxEdge.Y; y++) { u32 i = vm->m_area.index(a.MinEdge.X, y, z); for (int x = a.MinEdge.X; x <= a.MaxEdge.X; x++, i++) vm->m_data[i].param1 = light; } } } void Mapgen::lightSpread(VoxelArea &a, v3s16 p, u8 light) { if (light <= 1 || !a.contains(p)) return; u32 vi = vm->m_area.index(p); MapNode &n = vm->m_data[vi]; // Decay light in each of the banks separately u8 light_day = light & 0x0F; if (light_day > 0) light_day -= 0x01; u8 light_night = light & 0xF0; if (light_night > 0) light_night -= 0x10; // Bail out only if we have no more light from either bank to propogate, or // we hit a solid block that light cannot pass through. if ((light_day <= (n.param1 & 0x0F) && light_night <= (n.param1 & 0xF0)) || !ndef->get(n).light_propagates) return; // Since this recursive function only terminates when there is no light from // either bank left, we need to take the max of both banks into account for // the case where spreading has stopped for one light bank but not the other. light = MYMAX(light_day, n.param1 & 0x0F) | MYMAX(light_night, n.param1 & 0xF0); n.param1 = light; lightSpread(a, p + v3s16(0, 0, 1), light); lightSpread(a, p + v3s16(0, 1, 0), light); lightSpread(a, p + v3s16(1, 0, 0), light); lightSpread(a, p - v3s16(0, 0, 1), light); lightSpread(a, p - v3s16(0, 1, 0), light); lightSpread(a, p - v3s16(1, 0, 0), light); } void Mapgen::calcLighting(v3s16 nmin, v3s16 nmax, v3s16 full_nmin, v3s16 full_nmax, bool propagate_shadow) { ScopeProfiler sp(g_profiler, "EmergeThread: mapgen lighting update", SPT_AVG); //TimeTaker t("updateLighting"); propagateSunlight(nmin, nmax, propagate_shadow); spreadLight(full_nmin, full_nmax); //printf("updateLighting: %dms\n", t.stop()); } void Mapgen::propagateSunlight(v3s16 nmin, v3s16 nmax, bool propagate_shadow) { //TimeTaker t("propagateSunlight"); VoxelArea a(nmin, nmax); bool block_is_underground = (water_level >= nmax.Y); const v3s16 &em = vm->m_area.getExtent(); // NOTE: Direct access to the low 4 bits of param1 is okay here because, // by definition, sunlight will never be in the night lightbank. for (int z = a.MinEdge.Z; z <= a.MaxEdge.Z; z++) { for (int x = a.MinEdge.X; x <= a.MaxEdge.X; x++) { // see if we can get a light value from the overtop u32 i = vm->m_area.index(x, a.MaxEdge.Y + 1, z); if (vm->m_data[i].getContent() == CONTENT_IGNORE) { if (block_is_underground) continue; } else if ((vm->m_data[i].param1 & 0x0F) != LIGHT_SUN && propagate_shadow) { continue; } VoxelArea::add_y(em, i, -1); for (int y = a.MaxEdge.Y; y >= a.MinEdge.Y; y--) { MapNode &n = vm->m_data[i]; if (!ndef->get(n).sunlight_propagates) break; n.param1 = LIGHT_SUN; VoxelArea::add_y(em, i, -1); } } } //printf("propagateSunlight: %dms\n", t.stop()); } void Mapgen::spreadLight(v3s16 nmin, v3s16 nmax) { //TimeTaker t("spreadLight"); VoxelArea a(nmin, nmax); for (int z = a.MinEdge.Z; z <= a.MaxEdge.Z; z++) { for (int y = a.MinEdge.Y; y <= a.MaxEdge.Y; y++) { u32 i = vm->m_area.index(a.MinEdge.X, y, z); for (int x = a.MinEdge.X; x <= a.MaxEdge.X; x++, i++) { MapNode &n = vm->m_data[i]; if (n.getContent() == CONTENT_IGNORE) continue; const ContentFeatures &cf = ndef->get(n); if (!cf.light_propagates) continue; // TODO(hmmmmm): Abstract away direct param1 accesses with a // wrapper, but something lighter than MapNode::get/setLight u8 light_produced = cf.light_source; if (light_produced) n.param1 = light_produced | (light_produced << 4); u8 light = n.param1; if (light) { lightSpread(a, v3s16(x, y, z + 1), light); lightSpread(a, v3s16(x, y + 1, z ), light); lightSpread(a, v3s16(x + 1, y, z ), light); lightSpread(a, v3s16(x, y, z - 1), light); lightSpread(a, v3s16(x, y - 1, z ), light); lightSpread(a, v3s16(x - 1, y, z ), light); } } } } //printf("spreadLight: %dms\n", t.stop()); } //// //// MapgenBasic //// MapgenBasic::MapgenBasic(int mapgenid, MapgenParams *params, EmergeManager *emerge) : Mapgen(mapgenid, params, emerge) { this->m_emerge = emerge; this->m_bmgr = emerge->biomemgr; //// Here, 'stride' refers to the number of elements needed to skip to index //// an adjacent element for that coordinate in noise/height/biome maps //// (*not* vmanip content map!) // Note there is no X stride explicitly defined. Items adjacent in the X // coordinate are assumed to be adjacent in memory as well (i.e. stride of 1). // Number of elements to skip to get to the next Y coordinate this->ystride = csize.X; // Number of elements to skip to get to the next Z coordinate this->zstride = csize.X * csize.Y; // Z-stride value for maps oversized for 1-down overgeneration this->zstride_1d = csize.X * (csize.Y + 1); // Z-stride value for maps oversized for 1-up 1-down overgeneration this->zstride_1u1d = csize.X * (csize.Y + 2); //// Allocate heightmap this->heightmap = new s16[csize.X * csize.Z]; //// Initialize biome generator // TODO(hmmmm): should we have a way to disable biomemanager biomes? biomegen = m_bmgr->createBiomeGen(BIOMEGEN_ORIGINAL, params->bparams, csize); biomemap = biomegen->biomemap; //// Look up some commonly used content c_stone = ndef->getId("mapgen_stone"); c_desert_stone = ndef->getId("mapgen_desert_stone"); c_sandstone = ndef->getId("mapgen_sandstone"); c_water_source = ndef->getId("mapgen_water_source"); c_river_water_source = ndef->getId("mapgen_river_water_source"); c_lava_source = ndef->getId("mapgen_lava_source"); // Fall back to more basic content if not defined // river_water_source cannot fallback to water_source because river water // needs to be non-renewable and have a short flow range. if (c_desert_stone == CONTENT_IGNORE) c_desert_stone = c_stone; if (c_sandstone == CONTENT_IGNORE) c_sandstone = c_stone; //// Content used for dungeon generation c_cobble = ndef->getId("mapgen_cobble"); c_mossycobble = ndef->getId("mapgen_mossycobble"); c_stair_cobble = ndef->getId("mapgen_stair_cobble"); c_stair_desert_stone = ndef->getId("mapgen_stair_desert_stone"); c_sandstonebrick = ndef->getId("mapgen_sandstonebrick"); c_stair_sandstone_block = ndef->getId("mapgen_stair_sandstone_block"); // Fall back to more basic content if not defined if (c_mossycobble == CONTENT_IGNORE) c_mossycobble = c_cobble; if (c_stair_cobble == CONTENT_IGNORE) c_stair_cobble = c_cobble; if (c_stair_desert_stone == CONTENT_IGNORE) c_stair_desert_stone = c_desert_stone; if (c_sandstonebrick == CONTENT_IGNORE) c_sandstonebrick = c_sandstone; if (c_stair_sandstone_block == CONTENT_IGNORE) c_stair_sandstone_block = c_sandstonebrick; } MapgenBasic::~MapgenBasic() { delete biomegen; delete []heightmap; } void MapgenBasic::generateBiomes() { // can't generate biomes without a biome generator! assert(biomegen); assert(biomemap); const v3s16 &em = vm->m_area.getExtent(); u32 index = 0; noise_filler_depth->perlinMap2D(node_min.X, node_min.Z); for (s16 z = node_min.Z; z <= node_max.Z; z++) for (s16 x = node_min.X; x <= node_max.X; x++, index++) { Biome *biome = NULL; biome_t water_biome_index = 0; u16 depth_top = 0; u16 base_filler = 0; u16 depth_water_top = 0; u16 depth_riverbed = 0; s16 biome_y_min = -MAX_MAP_GENERATION_LIMIT; u32 vi = vm->m_area.index(x, node_max.Y, z); // Check node at base of mapchunk above, either a node of a previously // generated mapchunk or if not, a node of overgenerated base terrain. content_t c_above = vm->m_data[vi + em.X].getContent(); bool air_above = c_above == CONTENT_AIR; bool river_water_above = c_above == c_river_water_source; bool water_above = c_above == c_water_source || river_water_above; biomemap[index] = BIOME_NONE; // If there is air or water above enable top/filler placement, otherwise force // nplaced to stone level by setting a number exceeding any possible filler depth. u16 nplaced = (air_above || water_above) ? 0 : U16_MAX; for (s16 y = node_max.Y; y >= node_min.Y; y--) { content_t c = vm->m_data[vi].getContent(); // Biome is (re)calculated: // 1. At the surface of stone below air or water. // 2. At the surface of water below air. // 3. When stone or water is detected but biome has not yet been calculated. // 4. When stone or water is detected just below a biome's lower limit. bool is_stone_surface = (c == c_stone) && (air_above || water_above || !biome || y < biome_y_min); // 1, 3, 4 bool is_water_surface = (c == c_water_source || c == c_river_water_source) && (air_above || !biome || y < biome_y_min); // 2, 3, 4 if (is_stone_surface || is_water_surface) { // (Re)calculate biome biome = biomegen->getBiomeAtIndex(index, v3s16(x, y, z)); // Add biome to biomemap at first stone surface detected if (biomemap[index] == BIOME_NONE && is_stone_surface) biomemap[index] = biome->index; // Store biome of first water surface detected, as a fallback // entry for the biomemap. if (water_biome_index == 0 && is_water_surface) water_biome_index = biome->index; depth_top = biome->depth_top; base_filler = MYMAX(depth_top + biome->depth_filler + noise_filler_depth->result[index], 0.0f); depth_water_top = biome->depth_water_top; depth_riverbed = biome->depth_riverbed; biome_y_min = biome->min_pos.Y; } if (c == c_stone) { content_t c_below = vm->m_data[vi - em.X].getContent(); // If the node below isn't solid, make this node stone, so that // any top/filler nodes above are structurally supported. // This is done by aborting the cycle of top/filler placement // immediately by forcing nplaced to stone level. if (c_below == CONTENT_AIR || c_below == c_water_source || c_below == c_river_water_source) nplaced = U16_MAX; if (river_water_above) { if (nplaced < depth_riverbed) { vm->m_data[vi] = MapNode(biome->c_riverbed); nplaced++; } else { nplaced = U16_MAX; // Disable top/filler placement river_water_above = false; } } else if (nplaced < depth_top) { vm->m_data[vi] = MapNode(biome->c_top); nplaced++; } else if (nplaced < base_filler) { vm->m_data[vi] = MapNode(biome->c_filler); nplaced++; } else { vm->m_data[vi] = MapNode(biome->c_stone); nplaced = U16_MAX; // Disable top/filler placement } air_above = false; water_above = false; } else if (c == c_water_source) { vm->m_data[vi] = MapNode((y > (s32)(water_level - depth_water_top)) ? biome->c_water_top : biome->c_water); nplaced = 0; // Enable top/filler placement for next surface air_above = false; water_above = true; } else if (c == c_river_water_source) { vm->m_data[vi] = MapNode(biome->c_river_water); nplaced = 0; // Enable riverbed placement for next surface air_above = false; water_above = true; river_water_above = true; } else if (c == CONTENT_AIR) { nplaced = 0; // Enable top/filler placement for next surface air_above = true; water_above = false; } else { // Possible various nodes overgenerated from neighbouring mapchunks nplaced = U16_MAX; // Disable top/filler placement air_above = false; water_above = false; } VoxelArea::add_y(em, vi, -1); } // If no stone surface detected in mapchunk column and a water surface // biome fallback exists, add it to the biomemap. This avoids water // surface decorations failing in deep water. if (biomemap[index] == BIOME_NONE && water_biome_index != 0) biomemap[index] = water_biome_index; } } void MapgenBasic::dustTopNodes() { if (node_max.Y < water_level) return; const v3s16 &em = vm->m_area.getExtent(); u32 index = 0; for (s16 z = node_min.Z; z <= node_max.Z; z++) for (s16 x = node_min.X; x <= node_max.X; x++, index++) { Biome *biome = (Biome *)m_bmgr->getRaw(biomemap[index]); if (biome->c_dust == CONTENT_IGNORE) continue; // Check if mapchunk above has generated, if so, drop dust from 16 nodes // above current mapchunk top, above decorations that will extend above // the current mapchunk. If the mapchunk above has not generated, it // will provide this required dust when it does. u32 vi = vm->m_area.index(x, full_node_max.Y, z); content_t c_full_max = vm->m_data[vi].getContent(); s16 y_start; if (c_full_max == CONTENT_AIR) { y_start = full_node_max.Y - 1; } else if (c_full_max == CONTENT_IGNORE) { vi = vm->m_area.index(x, node_max.Y + 1, z); content_t c_max = vm->m_data[vi].getContent(); if (c_max == CONTENT_AIR) y_start = node_max.Y; else continue; } else { continue; } vi = vm->m_area.index(x, y_start, z); for (s16 y = y_start; y >= node_min.Y - 1; y--) { if (vm->m_data[vi].getContent() != CONTENT_AIR) break; VoxelArea::add_y(em, vi, -1); } content_t c = vm->m_data[vi].getContent(); NodeDrawType dtype = ndef->get(c).drawtype; // Only place on cubic, walkable, non-dust nodes. // Dust check needed due to avoid double layer of dust caused by // dropping dust from 16 nodes above mapchunk top. if ((dtype == NDT_NORMAL || dtype == NDT_ALLFACES || dtype == NDT_ALLFACES_OPTIONAL || dtype == NDT_GLASSLIKE || dtype == NDT_GLASSLIKE_FRAMED || dtype == NDT_GLASSLIKE_FRAMED_OPTIONAL) && ndef->get(c).walkable && c != biome->c_dust) { VoxelArea::add_y(em, vi, 1); vm->m_data[vi] = MapNode(biome->c_dust); } } } void MapgenBasic::generateCavesNoiseIntersection(s16 max_stone_y) { if (node_min.Y > max_stone_y) return; CavesNoiseIntersection caves_noise(ndef, m_bmgr, csize, &np_cave1, &np_cave2, seed, cave_width); caves_noise.generateCaves(vm, node_min, node_max, biomemap); } void MapgenBasic::generateCavesRandomWalk(s16 max_stone_y, s16 large_cave_depth) { if (node_min.Y > max_stone_y || node_max.Y > large_cave_depth) return; PseudoRandom ps(blockseed + 21343); u32 bruises_count = ps.range(0, 2); for (u32 i = 0; i < bruises_count; i++) { CavesRandomWalk cave(ndef, &gennotify, seed, water_level, c_water_source, c_lava_source, lava_depth, biomegen); cave.makeCave(vm, node_min, node_max, &ps, true, max_stone_y, heightmap); } } bool MapgenBasic::generateCavernsNoise(s16 max_stone_y) { if (node_min.Y > max_stone_y || node_min.Y > cavern_limit) return false; CavernsNoise caverns_noise(ndef, csize, &np_cavern, seed, cavern_limit, cavern_taper, cavern_threshold); return caverns_noise.generateCaverns(vm, node_min, node_max); } void MapgenBasic::generateDungeons(s16 max_stone_y) { if (max_stone_y < node_min.Y) return; // Get biome at mapchunk midpoint v3s16 chunk_mid = node_min + (node_max - node_min) / v3s16(2, 2, 2); Biome *biome = (Biome *)biomegen->getBiomeAtPoint(chunk_mid); DungeonParams dp; dp.seed = seed; dp.only_in_ground = true; dp.corridor_len_min = 1; dp.corridor_len_max = 13; dp.rooms_min = 2; dp.rooms_max = 16; dp.np_density = nparams_dungeon_density; dp.np_alt_wall = nparams_dungeon_alt_wall; // Biome-defined dungeon nodes if (biome->c_dungeon != CONTENT_IGNORE) { dp.c_wall = biome->c_dungeon; // If 'node_dungeon_alt' is not defined by biome, it and dp.c_alt_wall // become CONTENT_IGNORE which skips the alt wall node placement loop in // dungeongen.cpp. dp.c_alt_wall = biome->c_dungeon_alt; // Stairs fall back to 'c_dungeon' if not defined by biome dp.c_stair = (biome->c_dungeon_stair != CONTENT_IGNORE) ? biome->c_dungeon_stair : biome->c_dungeon; dp.diagonal_dirs = false; dp.holesize = v3s16(2, 2, 2); dp.room_size_min = v3s16(6, 4, 6); dp.room_size_max = v3s16(10, 6, 10); dp.room_size_large_min = v3s16(10, 8, 10); dp.room_size_large_max = v3s16(18, 16, 18); dp.notifytype = GENNOTIFY_DUNGEON; // Otherwise classic behaviour } else if (biome->c_stone == c_stone) { dp.c_wall = c_cobble; dp.c_alt_wall = c_mossycobble; dp.c_stair = c_stair_cobble; dp.diagonal_dirs = false; dp.holesize = v3s16(1, 2, 1); dp.room_size_min = v3s16(4, 4, 4); dp.room_size_max = v3s16(8, 6, 8); dp.room_size_large_min = v3s16(8, 8, 8); dp.room_size_large_max = v3s16(16, 16, 16); dp.notifytype = GENNOTIFY_DUNGEON; } else if (biome->c_stone == c_desert_stone) { dp.c_wall = c_desert_stone; dp.c_alt_wall = CONTENT_IGNORE; dp.c_stair = c_stair_desert_stone; dp.diagonal_dirs = true; dp.holesize = v3s16(2, 3, 2); dp.room_size_min = v3s16(6, 9, 6); dp.room_size_max = v3s16(10, 11, 10); dp.room_size_large_min = v3s16(10, 13, 10); dp.room_size_large_max = v3s16(18, 21, 18); dp.notifytype = GENNOTIFY_TEMPLE; } else if (biome->c_stone == c_sandstone) { dp.c_wall = c_sandstonebrick; dp.c_alt_wall = CONTENT_IGNORE; dp.c_stair = c_stair_sandstone_block; dp.diagonal_dirs = false; dp.holesize = v3s16(2, 2, 2); dp.room_size_min = v3s16(6, 4, 6); dp.room_size_max = v3s16(10, 6, 10); dp.room_size_large_min = v3s16(10, 8, 10); dp.room_size_large_max = v3s16(18, 16, 18); dp.notifytype = GENNOTIFY_DUNGEON; // Fallback to using biome 'node_stone' } else { dp.c_wall = biome->c_stone; dp.c_alt_wall = CONTENT_IGNORE; dp.c_stair = biome->c_stone; dp.diagonal_dirs = false; dp.holesize = v3s16(2, 2, 2); dp.room_size_min = v3s16(6, 4, 6); dp.room_size_max = v3s16(10, 6, 10); dp.room_size_large_min = v3s16(10, 8, 10); dp.room_size_large_max = v3s16(18, 16, 18); dp.notifytype = GENNOTIFY_DUNGEON; } DungeonGen dgen(ndef, &gennotify, &dp); dgen.generate(vm, blockseed, full_node_min, full_node_max); } //// //// GenerateNotifier //// GenerateNotifier::GenerateNotifier(u32 notify_on, std::set<u32> *notify_on_deco_ids) { m_notify_on = notify_on; m_notify_on_deco_ids = notify_on_deco_ids; } void GenerateNotifier::setNotifyOn(u32 notify_on) { m_notify_on = notify_on; } void GenerateNotifier::setNotifyOnDecoIds(std::set<u32> *notify_on_deco_ids) { m_notify_on_deco_ids = notify_on_deco_ids; } bool GenerateNotifier::addEvent(GenNotifyType type, v3s16 pos, u32 id) { if (!(m_notify_on & (1 << type))) return false; if (type == GENNOTIFY_DECORATION && m_notify_on_deco_ids->find(id) == m_notify_on_deco_ids->end()) return false; GenNotifyEvent gne; gne.type = type; gne.pos = pos; gne.id = id; m_notify_events.push_back(gne); return true; } void GenerateNotifier::getEvents( std::map<std::string, std::vector<v3s16> > &event_map) { std::list<GenNotifyEvent>::iterator it; for (it = m_notify_events.begin(); it != m_notify_events.end(); ++it) { GenNotifyEvent &gn = *it; std::string name = (gn.type == GENNOTIFY_DECORATION) ? "decoration#"+ itos(gn.id) : flagdesc_gennotify[gn.type].name; event_map[name].push_back(gn.pos); } } void GenerateNotifier::clearEvents() { m_notify_events.clear(); } //// //// MapgenParams //// MapgenParams::~MapgenParams() { delete bparams; } void MapgenParams::readParams(const Settings *settings) { std::string seed_str; const char *seed_name = (settings == g_settings) ? "fixed_map_seed" : "seed"; if (settings->getNoEx(seed_name, seed_str)) { if (!seed_str.empty()) seed = read_seed(seed_str.c_str()); else myrand_bytes(&seed, sizeof(seed)); } std::string mg_name; if (settings->getNoEx("mg_name", mg_name)) { mgtype = Mapgen::getMapgenType(mg_name); if (mgtype == MAPGEN_INVALID) mgtype = MAPGEN_DEFAULT; } settings->getS16NoEx("water_level", water_level); settings->getS16NoEx("mapgen_limit", mapgen_limit); settings->getS16NoEx("chunksize", chunksize); settings->getFlagStrNoEx("mg_flags", flags, flagdesc_mapgen); delete bparams; bparams = BiomeManager::createBiomeParams(BIOMEGEN_ORIGINAL); if (bparams) { bparams->readParams(settings); bparams->seed = seed; } } void MapgenParams::writeParams(Settings *settings) const { settings->set("mg_name", Mapgen::getMapgenName(mgtype)); settings->setU64("seed", seed); settings->setS16("water_level", water_level); settings->setS16("mapgen_limit", mapgen_limit); settings->setS16("chunksize", chunksize); settings->setFlagStr("mg_flags", flags, flagdesc_mapgen, U32_MAX); if (bparams) bparams->writeParams(settings); } // Calculate exact edges of the outermost mapchunks that are within the // set 'mapgen_limit'. void MapgenParams::calcMapgenEdges() { // Central chunk offset, in blocks s16 ccoff_b = -chunksize / 2; // Chunksize, in nodes s32 csize_n = chunksize * MAP_BLOCKSIZE; // Minp/maxp of central chunk, in nodes s16 ccmin = ccoff_b * MAP_BLOCKSIZE; s16 ccmax = ccmin + csize_n - 1; // Fullminp/fullmaxp of central chunk, in nodes s16 ccfmin = ccmin - MAP_BLOCKSIZE; s16 ccfmax = ccmax + MAP_BLOCKSIZE; // Effective mapgen limit, in blocks // Uses same calculation as ServerMap::blockpos_over_mapgen_limit(v3s16 p) s16 mapgen_limit_b = rangelim(mapgen_limit, 0, MAX_MAP_GENERATION_LIMIT) / MAP_BLOCKSIZE; // Effective mapgen limits, in nodes s16 mapgen_limit_min = -mapgen_limit_b * MAP_BLOCKSIZE; s16 mapgen_limit_max = (mapgen_limit_b + 1) * MAP_BLOCKSIZE - 1; // Number of complete chunks from central chunk fullminp/fullmaxp // to effective mapgen limits. s16 numcmin = MYMAX((ccfmin - mapgen_limit_min) / csize_n, 0); s16 numcmax = MYMAX((mapgen_limit_max - ccfmax) / csize_n, 0); // Mapgen edges, in nodes mapgen_edge_min = ccmin - numcmin * csize_n; mapgen_edge_max = ccmax + numcmax * csize_n; m_mapgen_edges_calculated = true; } s32 MapgenParams::getSpawnRangeMax() { if (!m_mapgen_edges_calculated) calcMapgenEdges(); return MYMIN(-mapgen_edge_min, mapgen_edge_max); }
pgimeno/minetest
src/mapgen/mapgen.cpp
C++
mit
33,730
/* Minetest Copyright (C) 2010-2018 celeron55, Perttu Ahola <celeron55@gmail.com> Copyright (C) 2013-2018 kwolekr, Ryan Kwolek <kwolekr@minetest.net> Copyright (C) 2015-2018 paramat 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. */ #pragma once #include "noise.h" #include "nodedef.h" #include "util/string.h" #include "util/container.h" #define MAPGEN_DEFAULT MAPGEN_V7 #define MAPGEN_DEFAULT_NAME "v7" /////////////////// Mapgen flags #define MG_TREES 0x01 // Deprecated. Moved into mgv6 flags #define MG_CAVES 0x02 #define MG_DUNGEONS 0x04 #define MG_FLAT 0x08 // Deprecated. Moved into mgv6 flags #define MG_LIGHT 0x10 #define MG_DECORATIONS 0x20 #define MG_BIOMES 0x40 typedef u8 biome_t; // copy from mg_biome.h to avoid an unnecessary include class Settings; class MMVManip; class NodeDefManager; extern FlagDesc flagdesc_mapgen[]; extern FlagDesc flagdesc_gennotify[]; class Biome; class BiomeGen; struct BiomeParams; class BiomeManager; class EmergeManager; class MapBlock; class VoxelManipulator; struct BlockMakeData; class VoxelArea; class Map; enum MapgenObject { MGOBJ_VMANIP, MGOBJ_HEIGHTMAP, MGOBJ_BIOMEMAP, MGOBJ_HEATMAP, MGOBJ_HUMIDMAP, MGOBJ_GENNOTIFY }; enum GenNotifyType { GENNOTIFY_DUNGEON, GENNOTIFY_TEMPLE, GENNOTIFY_CAVE_BEGIN, GENNOTIFY_CAVE_END, GENNOTIFY_LARGECAVE_BEGIN, GENNOTIFY_LARGECAVE_END, GENNOTIFY_DECORATION, NUM_GENNOTIFY_TYPES }; struct GenNotifyEvent { GenNotifyType type; v3s16 pos; u32 id; }; class GenerateNotifier { public: GenerateNotifier() = default; GenerateNotifier(u32 notify_on, std::set<u32> *notify_on_deco_ids); void setNotifyOn(u32 notify_on); void setNotifyOnDecoIds(std::set<u32> *notify_on_deco_ids); bool addEvent(GenNotifyType type, v3s16 pos, u32 id=0); void getEvents(std::map<std::string, std::vector<v3s16> > &event_map); void clearEvents(); private: u32 m_notify_on = 0; std::set<u32> *m_notify_on_deco_ids; std::list<GenNotifyEvent> m_notify_events; }; enum MapgenType { MAPGEN_V5, MAPGEN_V6, MAPGEN_V7, MAPGEN_FLAT, MAPGEN_FRACTAL, MAPGEN_VALLEYS, MAPGEN_SINGLENODE, MAPGEN_CARPATHIAN, MAPGEN_INVALID, }; struct MapgenParams { MapgenParams() = default; virtual ~MapgenParams(); MapgenType mgtype = MAPGEN_DEFAULT; s16 chunksize = 5; u64 seed = 0; s16 water_level = 1; s16 mapgen_limit = MAX_MAP_GENERATION_LIMIT; u32 flags = MG_CAVES | MG_LIGHT | MG_DECORATIONS | MG_BIOMES; BiomeParams *bparams = nullptr; s16 mapgen_edge_min = -MAX_MAP_GENERATION_LIMIT; s16 mapgen_edge_max = MAX_MAP_GENERATION_LIMIT; virtual void readParams(const Settings *settings); virtual void writeParams(Settings *settings) const; s32 getSpawnRangeMax(); private: void calcMapgenEdges(); bool m_mapgen_edges_calculated = false; }; /* Generic interface for map generators. All mapgens must inherit this class. If a feature exposed by a public member pointer is not supported by a certain mapgen, it must be set to NULL. Apart from makeChunk, getGroundLevelAtPoint, and getSpawnLevelAtPoint, all methods can be used by constructing a Mapgen base class and setting the appropriate public members (e.g. vm, ndef, and so on). */ class Mapgen { public: s32 seed = 0; int water_level = 0; int mapgen_limit = 0; u32 flags = 0; bool generating = false; int id = -1; MMVManip *vm = nullptr; const NodeDefManager *ndef = nullptr; u32 blockseed; s16 *heightmap = nullptr; biome_t *biomemap = nullptr; v3s16 csize; BiomeGen *biomegen = nullptr; GenerateNotifier gennotify; Mapgen() = default; Mapgen(int mapgenid, MapgenParams *params, EmergeManager *emerge); virtual ~Mapgen() = default; DISABLE_CLASS_COPY(Mapgen); virtual MapgenType getType() const { return MAPGEN_INVALID; } static u32 getBlockSeed(v3s16 p, s32 seed); static u32 getBlockSeed2(v3s16 p, s32 seed); s16 findGroundLevelFull(v2s16 p2d); s16 findGroundLevel(v2s16 p2d, s16 ymin, s16 ymax); s16 findLiquidSurface(v2s16 p2d, s16 ymin, s16 ymax); void updateHeightmap(v3s16 nmin, v3s16 nmax); void getSurfaces(v2s16 p2d, s16 ymin, s16 ymax, std::vector<s16> &floors, std::vector<s16> &ceilings); void updateLiquid(UniqueQueue<v3s16> *trans_liquid, v3s16 nmin, v3s16 nmax); void setLighting(u8 light, v3s16 nmin, v3s16 nmax); void lightSpread(VoxelArea &a, v3s16 p, u8 light); void calcLighting(v3s16 nmin, v3s16 nmax, v3s16 full_nmin, v3s16 full_nmax, bool propagate_shadow = true); void propagateSunlight(v3s16 nmin, v3s16 nmax, bool propagate_shadow); void spreadLight(v3s16 nmin, v3s16 nmax); virtual void makeChunk(BlockMakeData *data) {} virtual int getGroundLevelAtPoint(v2s16 p) { return 0; } // getSpawnLevelAtPoint() is a function within each mapgen that returns a // suitable y co-ordinate for player spawn ('suitable' usually meaning // within 16 nodes of water_level). If a suitable spawn level cannot be // found at the specified (X, Z) 'MAX_MAP_GENERATION_LIMIT' is returned to // signify this and to cause Server::findSpawnPos() to try another (X, Z). virtual int getSpawnLevelAtPoint(v2s16 p) { return 0; } // Mapgen management functions static MapgenType getMapgenType(const std::string &mgname); static const char *getMapgenName(MapgenType mgtype); static Mapgen *createMapgen(MapgenType mgtype, MapgenParams *params, EmergeManager *emerge); static MapgenParams *createMapgenParams(MapgenType mgtype); static void getMapgenNames(std::vector<const char *> *mgnames, bool include_hidden); private: // isLiquidHorizontallyFlowable() is a helper function for updateLiquid() // that checks whether there are floodable nodes without liquid beneath // the node at index vi. inline bool isLiquidHorizontallyFlowable(u32 vi, v3s16 em); }; /* MapgenBasic is a Mapgen implementation that handles basic functionality the majority of conventional mapgens will probably want to use, but isn't generic enough to be included as part of the base Mapgen class (such as generating biome terrain over terrain node skeletons, generating caves, dungeons, etc.) Inherit MapgenBasic instead of Mapgen to add this basic functionality to your mapgen without having to reimplement it. Feel free to override any of these methods if you desire different or more advanced behavior. Note that you must still create your own generateTerrain implementation when inheriting MapgenBasic. */ class MapgenBasic : public Mapgen { public: MapgenBasic(int mapgenid, MapgenParams *params, EmergeManager *emerge); virtual ~MapgenBasic(); virtual void generateBiomes(); virtual void dustTopNodes(); virtual void generateCavesNoiseIntersection(s16 max_stone_y); virtual void generateCavesRandomWalk(s16 max_stone_y, s16 large_cave_depth); virtual bool generateCavernsNoise(s16 max_stone_y); virtual void generateDungeons(s16 max_stone_y); protected: EmergeManager *m_emerge; BiomeManager *m_bmgr; Noise *noise_filler_depth; v3s16 node_min; v3s16 node_max; v3s16 full_node_min; v3s16 full_node_max; // Content required for generateBiomes content_t c_stone; content_t c_desert_stone; content_t c_sandstone; content_t c_water_source; content_t c_river_water_source; content_t c_lava_source; // Content required for generateDungeons content_t c_cobble; content_t c_stair_cobble; content_t c_mossycobble; content_t c_stair_desert_stone; content_t c_sandstonebrick; content_t c_stair_sandstone_block; int ystride; int zstride; int zstride_1d; int zstride_1u1d; u32 spflags; NoiseParams np_cave1; NoiseParams np_cave2; NoiseParams np_cavern; float cave_width; float cavern_limit; float cavern_taper; float cavern_threshold; int lava_depth; };
pgimeno/minetest
src/mapgen/mapgen.h
C++
mit
8,316
/* Minetest Copyright (C) 2017-2018 vlapsley, Vaughan Lapsley <vlapsley@gmail.com> Copyright (C) 2010-2018 paramat Copyright (C) 2010-2018 kwolekr, Ryan Kwolek <kwolekr@minetest.net> 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 <cmath> #include "mapgen.h" #include "voxel.h" #include "noise.h" #include "mapblock.h" #include "mapnode.h" #include "map.h" #include "content_sao.h" #include "nodedef.h" #include "voxelalgorithms.h" //#include "profiler.h" // For TimeTaker #include "settings.h" // For g_settings #include "emerge.h" #include "dungeongen.h" #include "cavegen.h" #include "mg_biome.h" #include "mg_ore.h" #include "mg_decoration.h" #include "mapgen_carpathian.h" FlagDesc flagdesc_mapgen_carpathian[] = { {"caverns", MGCARPATHIAN_CAVERNS}, {NULL, 0} }; /////////////////////////////////////////////////////////////////////////////// MapgenCarpathian::MapgenCarpathian(MapgenCarpathianParams *params, EmergeManager *emerge) : MapgenBasic(MAPGEN_CARPATHIAN, params, emerge) { base_level = params->base_level; spflags = params->spflags; cave_width = params->cave_width; large_cave_depth = params->large_cave_depth; lava_depth = params->lava_depth; cavern_limit = params->cavern_limit; cavern_taper = params->cavern_taper; cavern_threshold = params->cavern_threshold; dungeon_ymin = params->dungeon_ymin; dungeon_ymax = params->dungeon_ymax; grad_wl = 1 - water_level; //// 2D Terrain noise noise_filler_depth = new Noise(&params->np_filler_depth, seed, csize.X, csize.Z); noise_height1 = new Noise(&params->np_height1, seed, csize.X, csize.Z); noise_height2 = new Noise(&params->np_height2, seed, csize.X, csize.Z); noise_height3 = new Noise(&params->np_height3, seed, csize.X, csize.Z); noise_height4 = new Noise(&params->np_height4, seed, csize.X, csize.Z); noise_hills_terrain = new Noise(&params->np_hills_terrain, seed, csize.X, csize.Z); noise_ridge_terrain = new Noise(&params->np_ridge_terrain, seed, csize.X, csize.Z); noise_step_terrain = new Noise(&params->np_step_terrain, seed, csize.X, csize.Z); noise_hills = new Noise(&params->np_hills, seed, csize.X, csize.Z); noise_ridge_mnt = new Noise(&params->np_ridge_mnt, seed, csize.X, csize.Z); noise_step_mnt = new Noise(&params->np_step_mnt, seed, csize.X, csize.Z); //// 3D terrain noise // 1 up 1 down overgeneration noise_mnt_var = new Noise(&params->np_mnt_var, seed, csize.X, csize.Y + 2, csize.Z); //// Cave noise MapgenBasic::np_cave1 = params->np_cave1; MapgenBasic::np_cave2 = params->np_cave2; MapgenBasic::np_cavern = params->np_cavern; } MapgenCarpathian::~MapgenCarpathian() { delete noise_filler_depth; delete noise_height1; delete noise_height2; delete noise_height3; delete noise_height4; delete noise_hills_terrain; delete noise_ridge_terrain; delete noise_step_terrain; delete noise_hills; delete noise_ridge_mnt; delete noise_step_mnt; delete noise_mnt_var; } MapgenCarpathianParams::MapgenCarpathianParams(): np_filler_depth (0, 1, v3f(128, 128, 128), 261, 3, 0.7, 2.0), np_height1 (0, 5, v3f(251, 251, 251), 9613, 5, 0.5, 2.0), np_height2 (0, 5, v3f(383, 383, 383), 1949, 5, 0.5, 2.0), np_height3 (0, 5, v3f(509, 509, 509), 3211, 5, 0.5, 2.0), np_height4 (0, 5, v3f(631, 631, 631), 1583, 5, 0.5, 2.0), np_hills_terrain (1, 1, v3f(1301, 1301, 1301), 1692, 5, 0.5, 2.0), np_ridge_terrain (1, 1, v3f(1889, 1889, 1889), 3568, 5, 0.5, 2.0), np_step_terrain (1, 1, v3f(1889, 1889, 1889), 4157, 5, 0.5, 2.0), np_hills (0, 3, v3f(257, 257, 257), 6604, 6, 0.5, 2.0), np_ridge_mnt (0, 12, v3f(743, 743, 743), 5520, 6, 0.7, 2.0), np_step_mnt (0, 8, v3f(509, 509, 509), 2590, 6, 0.6, 2.0), np_mnt_var (0, 1, v3f(499, 499, 499), 2490, 5, 0.55, 2.0), np_cave1 (0, 12, v3f(61, 61, 61), 52534, 3, 0.5, 2.0), np_cave2 (0, 12, v3f(67, 67, 67), 10325, 3, 0.5, 2.0), np_cavern (0, 1, v3f(384, 128, 384), 723, 5, 0.63, 2.0) { } void MapgenCarpathianParams::readParams(const Settings *settings) { settings->getFlagStrNoEx("mgcarpathian_spflags", spflags, flagdesc_mapgen_carpathian); settings->getFloatNoEx("mgcarpathian_base_level", base_level); settings->getFloatNoEx("mgcarpathian_cave_width", cave_width); settings->getS16NoEx("mgcarpathian_large_cave_depth", large_cave_depth); settings->getS16NoEx("mgcarpathian_lava_depth", lava_depth); settings->getS16NoEx("mgcarpathian_cavern_limit", cavern_limit); settings->getS16NoEx("mgcarpathian_cavern_taper", cavern_taper); settings->getFloatNoEx("mgcarpathian_cavern_threshold", cavern_threshold); settings->getS16NoEx("mgcarpathian_dungeon_ymin", dungeon_ymin); settings->getS16NoEx("mgcarpathian_dungeon_ymax", dungeon_ymax); settings->getNoiseParams("mgcarpathian_np_filler_depth", np_filler_depth); settings->getNoiseParams("mgcarpathian_np_height1", np_height1); settings->getNoiseParams("mgcarpathian_np_height2", np_height2); settings->getNoiseParams("mgcarpathian_np_height3", np_height3); settings->getNoiseParams("mgcarpathian_np_height4", np_height4); settings->getNoiseParams("mgcarpathian_np_hills_terrain", np_hills_terrain); settings->getNoiseParams("mgcarpathian_np_ridge_terrain", np_ridge_terrain); settings->getNoiseParams("mgcarpathian_np_step_terrain", np_step_terrain); settings->getNoiseParams("mgcarpathian_np_hills", np_hills); settings->getNoiseParams("mgcarpathian_np_ridge_mnt", np_ridge_mnt); settings->getNoiseParams("mgcarpathian_np_step_mnt", np_step_mnt); settings->getNoiseParams("mgcarpathian_np_mnt_var", np_mnt_var); settings->getNoiseParams("mgcarpathian_np_cave1", np_cave1); settings->getNoiseParams("mgcarpathian_np_cave2", np_cave2); settings->getNoiseParams("mgcarpathian_np_cavern", np_cavern); } void MapgenCarpathianParams::writeParams(Settings *settings) const { settings->setFlagStr("mgcarpathian_spflags", spflags, flagdesc_mapgen_carpathian, U32_MAX); settings->setFloat("mgcarpathian_base_level", base_level); settings->setFloat("mgcarpathian_cave_width", cave_width); settings->setS16("mgcarpathian_large_cave_depth", large_cave_depth); settings->setS16("mgcarpathian_lava_depth", lava_depth); settings->setS16("mgcarpathian_cavern_limit", cavern_limit); settings->setS16("mgcarpathian_cavern_taper", cavern_taper); settings->setFloat("mgcarpathian_cavern_threshold", cavern_threshold); settings->setS16("mgcarpathian_dungeon_ymin", dungeon_ymin); settings->setS16("mgcarpathian_dungeon_ymax", dungeon_ymax); settings->setNoiseParams("mgcarpathian_np_filler_depth", np_filler_depth); settings->setNoiseParams("mgcarpathian_np_height1", np_height1); settings->setNoiseParams("mgcarpathian_np_height2", np_height2); settings->setNoiseParams("mgcarpathian_np_height3", np_height3); settings->setNoiseParams("mgcarpathian_np_height4", np_height4); settings->setNoiseParams("mgcarpathian_np_hills_terrain", np_hills_terrain); settings->setNoiseParams("mgcarpathian_np_ridge_terrain", np_ridge_terrain); settings->setNoiseParams("mgcarpathian_np_step_terrain", np_step_terrain); settings->setNoiseParams("mgcarpathian_np_hills", np_hills); settings->setNoiseParams("mgcarpathian_np_ridge_mnt", np_ridge_mnt); settings->setNoiseParams("mgcarpathian_np_step_mnt", np_step_mnt); settings->setNoiseParams("mgcarpathian_np_mnt_var", np_mnt_var); settings->setNoiseParams("mgcarpathian_np_cave1", np_cave1); settings->setNoiseParams("mgcarpathian_np_cave2", np_cave2); settings->setNoiseParams("mgcarpathian_np_cavern", np_cavern); } //////////////////////////////////////////////////////////////////////////////// // Lerp function inline float MapgenCarpathian::getLerp(float noise1, float noise2, float mod) { return noise1 + mod * (noise2 - noise1); } // Steps function float MapgenCarpathian::getSteps(float noise) { float w = 0.5f; float k = std::floor(noise / w); float f = (noise - k * w) / w; float s = std::fmin(2.f * f, 1.f); return (k + s) * w; } //////////////////////////////////////////////////////////////////////////////// void MapgenCarpathian::makeChunk(BlockMakeData *data) { // Pre-conditions assert(data->vmanip); assert(data->nodedef); assert(data->blockpos_requested.X >= data->blockpos_min.X && data->blockpos_requested.Y >= data->blockpos_min.Y && data->blockpos_requested.Z >= data->blockpos_min.Z); assert(data->blockpos_requested.X <= data->blockpos_max.X && data->blockpos_requested.Y <= data->blockpos_max.Y && data->blockpos_requested.Z <= data->blockpos_max.Z); this->generating = true; this->vm = data->vmanip; this->ndef = data->nodedef; v3s16 blockpos_min = data->blockpos_min; v3s16 blockpos_max = data->blockpos_max; node_min = blockpos_min * MAP_BLOCKSIZE; node_max = (blockpos_max + v3s16(1, 1, 1)) * MAP_BLOCKSIZE - v3s16(1, 1, 1); full_node_min = (blockpos_min - 1) * MAP_BLOCKSIZE; full_node_max = (blockpos_max + 2) * MAP_BLOCKSIZE - v3s16(1, 1, 1); // Create a block-specific seed blockseed = getBlockSeed2(full_node_min, seed); // Generate terrain s16 stone_surface_max_y = generateTerrain(); // Create heightmap updateHeightmap(node_min, node_max); // Init biome generator, place biome-specific nodes, and build biomemap if (flags & MG_BIOMES) { biomegen->calcBiomeNoise(node_min); generateBiomes(); } // Generate tunnels, caverns and large randomwalk caves if (flags & MG_CAVES) { // Generate tunnels first as caverns confuse them generateCavesNoiseIntersection(stone_surface_max_y); // Generate caverns bool near_cavern = false; if (spflags & MGCARPATHIAN_CAVERNS) near_cavern = generateCavernsNoise(stone_surface_max_y); // Generate large randomwalk caves if (near_cavern) // Disable large randomwalk caves in this mapchunk by setting // 'large cave depth' to world base. Avoids excessive liquid in // large caverns and floating blobs of overgenerated liquid. generateCavesRandomWalk(stone_surface_max_y, -MAX_MAP_GENERATION_LIMIT); else generateCavesRandomWalk(stone_surface_max_y, large_cave_depth); } // Generate the registered ores m_emerge->oremgr->placeAllOres(this, blockseed, node_min, node_max); // Generate dungeons if ((flags & MG_DUNGEONS) && full_node_min.Y >= dungeon_ymin && full_node_max.Y <= dungeon_ymax) generateDungeons(stone_surface_max_y); // Generate the registered decorations if (flags & MG_DECORATIONS) m_emerge->decomgr->placeAllDecos(this, blockseed, node_min, node_max); // Sprinkle some dust on top after everything else was generated if (flags & MG_BIOMES) dustTopNodes(); // Update liquids updateLiquid(&data->transforming_liquid, full_node_min, full_node_max); // Calculate lighting if (flags & MG_LIGHT) { calcLighting(node_min - v3s16(0, 1, 0), node_max + v3s16(0, 1, 0), full_node_min, full_node_max); } this->generating = false; } //////////////////////////////////////////////////////////////////////////////// int MapgenCarpathian::getSpawnLevelAtPoint(v2s16 p) { s16 level_at_point = terrainLevelAtPoint(p.X, p.Y); if (level_at_point <= water_level || level_at_point > water_level + 32) return MAX_MAP_GENERATION_LIMIT; // Unsuitable spawn point return level_at_point; } float MapgenCarpathian::terrainLevelAtPoint(s16 x, s16 z) { float height1 = NoisePerlin2D(&noise_height1->np, x, z, seed); float height2 = NoisePerlin2D(&noise_height2->np, x, z, seed); float height3 = NoisePerlin2D(&noise_height3->np, x, z, seed); float height4 = NoisePerlin2D(&noise_height4->np, x, z, seed); float hter = NoisePerlin2D(&noise_hills_terrain->np, x, z, seed); float rter = NoisePerlin2D(&noise_ridge_terrain->np, x, z, seed); float ster = NoisePerlin2D(&noise_step_terrain->np, x, z, seed); float n_hills = NoisePerlin2D(&noise_hills->np, x, z, seed); float n_ridge_mnt = NoisePerlin2D(&noise_ridge_mnt->np, x, z, seed); float n_step_mnt = NoisePerlin2D(&noise_step_mnt->np, x, z, seed); int height = -MAX_MAP_GENERATION_LIMIT; for (s16 y = 1; y <= 30; y++) { float mnt_var = NoisePerlin3D(&noise_mnt_var->np, x, y, z, seed); // Gradient & shallow seabed s32 grad = (y < water_level) ? grad_wl + (water_level - y) * 3 : 1 - y; // Hill/Mountain height (hilliness) float hill1 = getLerp(height1, height2, mnt_var); float hill2 = getLerp(height3, height4, mnt_var); float hill3 = getLerp(height3, height2, mnt_var); float hill4 = getLerp(height1, height4, mnt_var); float hilliness = std::fmax(std::fmin(hill1, hill2), std::fmin(hill3, hill4)); // Rolling hills float hill_mnt = hilliness * std::pow(n_hills, 2.f); float hills = std::pow(std::fabs(hter), 3.f) * hill_mnt; // Ridged mountains float ridge_mnt = hilliness * (1.f - std::fabs(n_ridge_mnt)); float ridged_mountains = std::pow(std::fabs(rter), 3.f) * ridge_mnt; // Step (terraced) mountains float step_mnt = hilliness * getSteps(n_step_mnt); float step_mountains = std::pow(std::fabs(ster), 3.f) * step_mnt; // Final terrain level float mountains = hills + ridged_mountains + step_mountains; float surface_level = base_level + mountains + grad; if (y > surface_level && height < 0) height = y; } return height; } //////////////////////////////////////////////////////////////////////////////// int MapgenCarpathian::generateTerrain() { MapNode mn_air(CONTENT_AIR); MapNode mn_stone(c_stone); MapNode mn_water(c_water_source); // Calculate noise for terrain generation noise_height1->perlinMap2D(node_min.X, node_min.Z); noise_height2->perlinMap2D(node_min.X, node_min.Z); noise_height3->perlinMap2D(node_min.X, node_min.Z); noise_height4->perlinMap2D(node_min.X, node_min.Z); noise_hills_terrain->perlinMap2D(node_min.X, node_min.Z); noise_ridge_terrain->perlinMap2D(node_min.X, node_min.Z); noise_step_terrain->perlinMap2D(node_min.X, node_min.Z); noise_hills->perlinMap2D(node_min.X, node_min.Z); noise_ridge_mnt->perlinMap2D(node_min.X, node_min.Z); noise_step_mnt->perlinMap2D(node_min.X, node_min.Z); noise_mnt_var->perlinMap3D(node_min.X, node_min.Y - 1, node_min.Z); //// Place nodes const v3s16 &em = vm->m_area.getExtent(); s16 stone_surface_max_y = -MAX_MAP_GENERATION_LIMIT; u32 index2d = 0; for (s16 z = node_min.Z; z <= node_max.Z; z++) for (s16 x = node_min.X; x <= node_max.X; x++, index2d++) { // Hill/Mountain height (hilliness) float height1 = noise_height1->result[index2d]; float height2 = noise_height2->result[index2d]; float height3 = noise_height3->result[index2d]; float height4 = noise_height4->result[index2d]; // Rolling hills float hterabs = std::fabs(noise_hills_terrain->result[index2d]); float n_hills = noise_hills->result[index2d]; float hill_mnt = hterabs * hterabs * hterabs * n_hills * n_hills; // Ridged mountains float rterabs = std::fabs(noise_ridge_terrain->result[index2d]); float n_ridge_mnt = noise_ridge_mnt->result[index2d]; float ridge_mnt = rterabs * rterabs * rterabs * (1.f - std::fabs(n_ridge_mnt)); // Step (terraced) mountains float sterabs = std::fabs(noise_step_terrain->result[index2d]); float n_step_mnt = noise_step_mnt->result[index2d]; float step_mnt = sterabs * sterabs * sterabs * getSteps(n_step_mnt); // Initialise 3D noise index and voxelmanip index to column base u32 index3d = (z - node_min.Z) * zstride_1u1d + (x - node_min.X); u32 vi = vm->m_area.index(x, node_min.Y - 1, z); for (s16 y = node_min.Y - 1; y <= node_max.Y + 1; y++, index3d += ystride, VoxelArea::add_y(em, vi, 1)) { if (vm->m_data[vi].getContent() != CONTENT_IGNORE) continue; // Combine height noises and apply 3D variation float mnt_var = noise_mnt_var->result[index3d]; float hill1 = getLerp(height1, height2, mnt_var); float hill2 = getLerp(height3, height4, mnt_var); float hill3 = getLerp(height3, height2, mnt_var); float hill4 = getLerp(height1, height4, mnt_var); // 'hilliness' determines whether hills/mountains are // small or large float hilliness = std::fmax(std::fmin(hill1, hill2), std::fmin(hill3, hill4)); float hills = hill_mnt * hilliness; float ridged_mountains = ridge_mnt * hilliness; float step_mountains = step_mnt * hilliness; // Gradient & shallow seabed s32 grad = (y < water_level) ? grad_wl + (water_level - y) * 3 : 1 - y; // Final terrain level float mountains = hills + ridged_mountains + step_mountains; float surface_level = base_level + mountains + grad; if (y < surface_level) { vm->m_data[vi] = mn_stone; // Stone if (y > stone_surface_max_y) stone_surface_max_y = y; } else if (y <= water_level) { vm->m_data[vi] = mn_water; // Sea water } else { vm->m_data[vi] = mn_air; // Air } } } return stone_surface_max_y; }
pgimeno/minetest
src/mapgen/mapgen_carpathian.cpp
C++
mit
17,855
/* Minetest Copyright (C) 2017-2018 vlapsley, Vaughan Lapsley <vlapsley@gmail.com> Copyright (C) 2010-2018 paramat Copyright (C) 2010-2018 kwolekr, Ryan Kwolek <kwolekr@minetest.net> 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. */ #pragma once #include "mapgen.h" ///////// Mapgen Carpathian flags #define MGCARPATHIAN_CAVERNS 0x01 class BiomeManager; extern FlagDesc flagdesc_mapgen_carpathian[]; struct MapgenCarpathianParams : public MapgenParams { float base_level = 12.0f; u32 spflags = MGCARPATHIAN_CAVERNS; float cave_width = 0.09f; s16 large_cave_depth = -33; s16 lava_depth = -256; s16 cavern_limit = -256; s16 cavern_taper = 256; float cavern_threshold = 0.7f; s16 dungeon_ymin = -31000; s16 dungeon_ymax = 31000; NoiseParams np_filler_depth; NoiseParams np_height1; NoiseParams np_height2; NoiseParams np_height3; NoiseParams np_height4; NoiseParams np_hills_terrain; NoiseParams np_ridge_terrain; NoiseParams np_step_terrain; NoiseParams np_hills; NoiseParams np_ridge_mnt; NoiseParams np_step_mnt; NoiseParams np_mnt_var; NoiseParams np_cave1; NoiseParams np_cave2; NoiseParams np_cavern; MapgenCarpathianParams(); ~MapgenCarpathianParams() = default; void readParams(const Settings *settings); void writeParams(Settings *settings) const; }; class MapgenCarpathian : public MapgenBasic { public: MapgenCarpathian(MapgenCarpathianParams *params, EmergeManager *emerge); ~MapgenCarpathian(); virtual MapgenType getType() const { return MAPGEN_CARPATHIAN; } float getSteps(float noise); inline float getLerp(float noise1, float noise2, float mod); virtual void makeChunk(BlockMakeData *data); int getSpawnLevelAtPoint(v2s16 p); private: float base_level; s32 grad_wl; s16 large_cave_depth; s16 dungeon_ymin; s16 dungeon_ymax; Noise *noise_height1; Noise *noise_height2; Noise *noise_height3; Noise *noise_height4; Noise *noise_hills_terrain; Noise *noise_ridge_terrain; Noise *noise_step_terrain; Noise *noise_hills; Noise *noise_ridge_mnt; Noise *noise_step_mnt; Noise *noise_mnt_var; float terrainLevelAtPoint(s16 x, s16 z); int generateTerrain(); };
pgimeno/minetest
src/mapgen/mapgen_carpathian.h
C++
mit
2,852
/* Minetest Copyright (C) 2015-2018 paramat Copyright (C) 2015-2018 kwolekr, Ryan Kwolek <kwolekr@minetest.net> 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 "mapgen.h" #include "voxel.h" #include "noise.h" #include "mapblock.h" #include "mapnode.h" #include "map.h" #include "content_sao.h" #include "nodedef.h" #include "voxelalgorithms.h" //#include "profiler.h" // For TimeTaker #include "settings.h" // For g_settings #include "emerge.h" #include "dungeongen.h" #include "cavegen.h" #include "mg_biome.h" #include "mg_ore.h" #include "mg_decoration.h" #include "mapgen_flat.h" FlagDesc flagdesc_mapgen_flat[] = { {"lakes", MGFLAT_LAKES}, {"hills", MGFLAT_HILLS}, {NULL, 0} }; /////////////////////////////////////////////////////////////////////////////////////// MapgenFlat::MapgenFlat(MapgenFlatParams *params, EmergeManager *emerge) : MapgenBasic(MAPGEN_FLAT, params, emerge) { spflags = params->spflags; ground_level = params->ground_level; large_cave_depth = params->large_cave_depth; lava_depth = params->lava_depth; cave_width = params->cave_width; lake_threshold = params->lake_threshold; lake_steepness = params->lake_steepness; hill_threshold = params->hill_threshold; hill_steepness = params->hill_steepness; dungeon_ymin = params->dungeon_ymin; dungeon_ymax = params->dungeon_ymax; // 2D noise noise_filler_depth = new Noise(&params->np_filler_depth, seed, csize.X, csize.Z); if ((spflags & MGFLAT_LAKES) || (spflags & MGFLAT_HILLS)) noise_terrain = new Noise(&params->np_terrain, seed, csize.X, csize.Z); // 3D noise MapgenBasic::np_cave1 = params->np_cave1; MapgenBasic::np_cave2 = params->np_cave2; } MapgenFlat::~MapgenFlat() { delete noise_filler_depth; if ((spflags & MGFLAT_LAKES) || (spflags & MGFLAT_HILLS)) delete noise_terrain; } MapgenFlatParams::MapgenFlatParams(): np_terrain (0, 1, v3f(600, 600, 600), 7244, 5, 0.6, 2.0), np_filler_depth (0, 1.2, v3f(150, 150, 150), 261, 3, 0.7, 2.0), np_cave1 (0, 12, v3f(61, 61, 61), 52534, 3, 0.5, 2.0), np_cave2 (0, 12, v3f(67, 67, 67), 10325, 3, 0.5, 2.0) { } void MapgenFlatParams::readParams(const Settings *settings) { settings->getFlagStrNoEx("mgflat_spflags", spflags, flagdesc_mapgen_flat); settings->getS16NoEx("mgflat_ground_level", ground_level); settings->getS16NoEx("mgflat_large_cave_depth", large_cave_depth); settings->getS16NoEx("mgflat_lava_depth", lava_depth); settings->getFloatNoEx("mgflat_cave_width", cave_width); settings->getFloatNoEx("mgflat_lake_threshold", lake_threshold); settings->getFloatNoEx("mgflat_lake_steepness", lake_steepness); settings->getFloatNoEx("mgflat_hill_threshold", hill_threshold); settings->getFloatNoEx("mgflat_hill_steepness", hill_steepness); settings->getS16NoEx("mgflat_dungeon_ymin", dungeon_ymin); settings->getS16NoEx("mgflat_dungeon_ymax", dungeon_ymax); settings->getNoiseParams("mgflat_np_terrain", np_terrain); settings->getNoiseParams("mgflat_np_filler_depth", np_filler_depth); settings->getNoiseParams("mgflat_np_cave1", np_cave1); settings->getNoiseParams("mgflat_np_cave2", np_cave2); } void MapgenFlatParams::writeParams(Settings *settings) const { settings->setFlagStr("mgflat_spflags", spflags, flagdesc_mapgen_flat, U32_MAX); settings->setS16("mgflat_ground_level", ground_level); settings->setS16("mgflat_large_cave_depth", large_cave_depth); settings->setS16("mgflat_lava_depth", lava_depth); settings->setFloat("mgflat_cave_width", cave_width); settings->setFloat("mgflat_lake_threshold", lake_threshold); settings->setFloat("mgflat_lake_steepness", lake_steepness); settings->setFloat("mgflat_hill_threshold", hill_threshold); settings->setFloat("mgflat_hill_steepness", hill_steepness); settings->setS16("mgflat_dungeon_ymin", dungeon_ymin); settings->setS16("mgflat_dungeon_ymax", dungeon_ymax); settings->setNoiseParams("mgflat_np_terrain", np_terrain); settings->setNoiseParams("mgflat_np_filler_depth", np_filler_depth); settings->setNoiseParams("mgflat_np_cave1", np_cave1); settings->setNoiseParams("mgflat_np_cave2", np_cave2); } ///////////////////////////////////////////////////////////////// int MapgenFlat::getSpawnLevelAtPoint(v2s16 p) { s16 level_at_point = ground_level; float n_terrain = 0.0f; if ((spflags & MGFLAT_LAKES) || (spflags & MGFLAT_HILLS)) n_terrain = NoisePerlin2D(&noise_terrain->np, p.X, p.Y, seed); if ((spflags & MGFLAT_LAKES) && n_terrain < lake_threshold) { level_at_point = ground_level - (lake_threshold - n_terrain) * lake_steepness; } else if ((spflags & MGFLAT_HILLS) && n_terrain > hill_threshold) { level_at_point = ground_level + (n_terrain - hill_threshold) * hill_steepness; } if (ground_level < water_level) // Ocean world, allow spawn in water return MYMAX(level_at_point, water_level); if (level_at_point > water_level) return level_at_point; // Spawn on land return MAX_MAP_GENERATION_LIMIT; // Unsuitable spawn point } void MapgenFlat::makeChunk(BlockMakeData *data) { // Pre-conditions assert(data->vmanip); assert(data->nodedef); assert(data->blockpos_requested.X >= data->blockpos_min.X && data->blockpos_requested.Y >= data->blockpos_min.Y && data->blockpos_requested.Z >= data->blockpos_min.Z); assert(data->blockpos_requested.X <= data->blockpos_max.X && data->blockpos_requested.Y <= data->blockpos_max.Y && data->blockpos_requested.Z <= data->blockpos_max.Z); this->generating = true; this->vm = data->vmanip; this->ndef = data->nodedef; //TimeTaker t("makeChunk"); v3s16 blockpos_min = data->blockpos_min; v3s16 blockpos_max = data->blockpos_max; node_min = blockpos_min * MAP_BLOCKSIZE; node_max = (blockpos_max + v3s16(1, 1, 1)) * MAP_BLOCKSIZE - v3s16(1, 1, 1); full_node_min = (blockpos_min - 1) * MAP_BLOCKSIZE; full_node_max = (blockpos_max + 2) * MAP_BLOCKSIZE - v3s16(1, 1, 1); blockseed = getBlockSeed2(full_node_min, seed); // Generate base terrain, mountains, and ridges with initial heightmaps s16 stone_surface_max_y = generateTerrain(); // Create heightmap updateHeightmap(node_min, node_max); // Init biome generator, place biome-specific nodes, and build biomemap if (flags & MG_BIOMES) { biomegen->calcBiomeNoise(node_min); generateBiomes(); } if (flags & MG_CAVES) { // Generate tunnels generateCavesNoiseIntersection(stone_surface_max_y); // Generate large randomwalk caves generateCavesRandomWalk(stone_surface_max_y, large_cave_depth); } // Generate the registered ores m_emerge->oremgr->placeAllOres(this, blockseed, node_min, node_max); if ((flags & MG_DUNGEONS) && full_node_min.Y >= dungeon_ymin && full_node_max.Y <= dungeon_ymax) generateDungeons(stone_surface_max_y); // Generate the registered decorations if (flags & MG_DECORATIONS) m_emerge->decomgr->placeAllDecos(this, blockseed, node_min, node_max); // Sprinkle some dust on top after everything else was generated if (flags & MG_BIOMES) dustTopNodes(); //printf("makeChunk: %dms\n", t.stop()); updateLiquid(&data->transforming_liquid, full_node_min, full_node_max); if (flags & MG_LIGHT) calcLighting(node_min - v3s16(0, 1, 0), node_max + v3s16(0, 1, 0), full_node_min, full_node_max); //setLighting(node_min - v3s16(1, 0, 1) * MAP_BLOCKSIZE, // node_max + v3s16(1, 0, 1) * MAP_BLOCKSIZE, 0xFF); this->generating = false; } s16 MapgenFlat::generateTerrain() { MapNode n_air(CONTENT_AIR); MapNode n_stone(c_stone); MapNode n_water(c_water_source); const v3s16 &em = vm->m_area.getExtent(); s16 stone_surface_max_y = -MAX_MAP_GENERATION_LIMIT; u32 ni2d = 0; bool use_noise = (spflags & MGFLAT_LAKES) || (spflags & MGFLAT_HILLS); if (use_noise) noise_terrain->perlinMap2D(node_min.X, node_min.Z); for (s16 z = node_min.Z; z <= node_max.Z; z++) for (s16 x = node_min.X; x <= node_max.X; x++, ni2d++) { s16 stone_level = ground_level; float n_terrain = use_noise ? noise_terrain->result[ni2d] : 0.0f; if ((spflags & MGFLAT_LAKES) && n_terrain < lake_threshold) { s16 depress = (lake_threshold - n_terrain) * lake_steepness; stone_level = ground_level - depress; } else if ((spflags & MGFLAT_HILLS) && n_terrain > hill_threshold) { s16 rise = (n_terrain - hill_threshold) * hill_steepness; stone_level = ground_level + rise; } u32 vi = vm->m_area.index(x, node_min.Y - 1, z); for (s16 y = node_min.Y - 1; y <= node_max.Y + 1; y++) { if (vm->m_data[vi].getContent() == CONTENT_IGNORE) { if (y <= stone_level) { vm->m_data[vi] = n_stone; if (y > stone_surface_max_y) stone_surface_max_y = y; } else if (y <= water_level) { vm->m_data[vi] = n_water; } else { vm->m_data[vi] = n_air; } } VoxelArea::add_y(em, vi, 1); } } return stone_surface_max_y; }
pgimeno/minetest
src/mapgen/mapgen_flat.cpp
C++
mit
9,582
/* Minetest Copyright (C) 2015-2018 paramat Copyright (C) 2015-2018 kwolekr, Ryan Kwolek <kwolekr@minetest.net> 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. */ #pragma once #include "mapgen.h" /////// Mapgen Flat flags #define MGFLAT_LAKES 0x01 #define MGFLAT_HILLS 0x02 class BiomeManager; extern FlagDesc flagdesc_mapgen_flat[]; struct MapgenFlatParams : public MapgenParams { u32 spflags = 0; s16 ground_level = 8; s16 large_cave_depth = -33; s16 lava_depth = -256; float cave_width = 0.09f; float lake_threshold = -0.45f; float lake_steepness = 48.0f; float hill_threshold = 0.45f; float hill_steepness = 64.0f; s16 dungeon_ymin = -31000; s16 dungeon_ymax = 31000; NoiseParams np_terrain; NoiseParams np_filler_depth; NoiseParams np_cave1; NoiseParams np_cave2; MapgenFlatParams(); ~MapgenFlatParams() = default; void readParams(const Settings *settings); void writeParams(Settings *settings) const; }; class MapgenFlat : public MapgenBasic { public: MapgenFlat(MapgenFlatParams *params, EmergeManager *emerge); ~MapgenFlat(); virtual MapgenType getType() const { return MAPGEN_FLAT; } virtual void makeChunk(BlockMakeData *data); int getSpawnLevelAtPoint(v2s16 p); s16 generateTerrain(); private: s16 ground_level; s16 large_cave_depth; float lake_threshold; float lake_steepness; float hill_threshold; float hill_steepness; s16 dungeon_ymin; s16 dungeon_ymax; Noise *noise_terrain; };
pgimeno/minetest
src/mapgen/mapgen_flat.h
C++
mit
2,098
/* Minetest Copyright (C) 2015-2018 paramat Copyright (C) 2015-2018 kwolekr, Ryan Kwolek <kwolekr@minetest.net> 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 "mapgen.h" #include <cmath> #include "voxel.h" #include "noise.h" #include "mapblock.h" #include "mapnode.h" #include "map.h" #include "content_sao.h" #include "nodedef.h" #include "voxelalgorithms.h" //#include "profiler.h" // For TimeTaker #include "settings.h" // For g_settings #include "emerge.h" #include "dungeongen.h" #include "cavegen.h" #include "mg_biome.h" #include "mg_ore.h" #include "mg_decoration.h" #include "mapgen_fractal.h" FlagDesc flagdesc_mapgen_fractal[] = { {NULL, 0} }; /////////////////////////////////////////////////////////////////////////////////////// MapgenFractal::MapgenFractal(MapgenFractalParams *params, EmergeManager *emerge) : MapgenBasic(MAPGEN_FRACTAL, params, emerge) { spflags = params->spflags; cave_width = params->cave_width; large_cave_depth = params->large_cave_depth; lava_depth = params->lava_depth; dungeon_ymin = params->dungeon_ymin; dungeon_ymax = params->dungeon_ymax; fractal = params->fractal; iterations = params->iterations; scale = params->scale; offset = params->offset; slice_w = params->slice_w; julia_x = params->julia_x; julia_y = params->julia_y; julia_z = params->julia_z; julia_w = params->julia_w; //// 2D terrain noise noise_seabed = new Noise(&params->np_seabed, seed, csize.X, csize.Z); noise_filler_depth = new Noise(&params->np_filler_depth, seed, csize.X, csize.Z); MapgenBasic::np_cave1 = params->np_cave1; MapgenBasic::np_cave2 = params->np_cave2; formula = fractal / 2 + fractal % 2; julia = fractal % 2 == 0; } MapgenFractal::~MapgenFractal() { delete noise_seabed; delete noise_filler_depth; } MapgenFractalParams::MapgenFractalParams(): np_seabed (-14, 9, v3f(600, 600, 600), 41900, 5, 0.6, 2.0), np_filler_depth (0, 1.2, v3f(150, 150, 150), 261, 3, 0.7, 2.0), np_cave1 (0, 12, v3f(61, 61, 61), 52534, 3, 0.5, 2.0), np_cave2 (0, 12, v3f(67, 67, 67), 10325, 3, 0.5, 2.0) { } void MapgenFractalParams::readParams(const Settings *settings) { settings->getFlagStrNoEx("mgfractal_spflags", spflags, flagdesc_mapgen_fractal); settings->getFloatNoEx("mgfractal_cave_width", cave_width); settings->getS16NoEx("mgfractal_large_cave_depth", large_cave_depth); settings->getS16NoEx("mgfractal_lava_depth", lava_depth); settings->getS16NoEx("mgfractal_dungeon_ymin", dungeon_ymin); settings->getS16NoEx("mgfractal_dungeon_ymax", dungeon_ymax); settings->getU16NoEx("mgfractal_fractal", fractal); settings->getU16NoEx("mgfractal_iterations", iterations); settings->getV3FNoEx("mgfractal_scale", scale); settings->getV3FNoEx("mgfractal_offset", offset); settings->getFloatNoEx("mgfractal_slice_w", slice_w); settings->getFloatNoEx("mgfractal_julia_x", julia_x); settings->getFloatNoEx("mgfractal_julia_y", julia_y); settings->getFloatNoEx("mgfractal_julia_z", julia_z); settings->getFloatNoEx("mgfractal_julia_w", julia_w); settings->getNoiseParams("mgfractal_np_seabed", np_seabed); settings->getNoiseParams("mgfractal_np_filler_depth", np_filler_depth); settings->getNoiseParams("mgfractal_np_cave1", np_cave1); settings->getNoiseParams("mgfractal_np_cave2", np_cave2); } void MapgenFractalParams::writeParams(Settings *settings) const { settings->setFlagStr("mgfractal_spflags", spflags, flagdesc_mapgen_fractal, U32_MAX); settings->setFloat("mgfractal_cave_width", cave_width); settings->setS16("mgfractal_large_cave_depth", large_cave_depth); settings->setS16("mgfractal_lava_depth", lava_depth); settings->setS16("mgfractal_dungeon_ymin", dungeon_ymin); settings->setS16("mgfractal_dungeon_ymax", dungeon_ymax); settings->setU16("mgfractal_fractal", fractal); settings->setU16("mgfractal_iterations", iterations); settings->setV3F("mgfractal_scale", scale); settings->setV3F("mgfractal_offset", offset); settings->setFloat("mgfractal_slice_w", slice_w); settings->setFloat("mgfractal_julia_x", julia_x); settings->setFloat("mgfractal_julia_y", julia_y); settings->setFloat("mgfractal_julia_z", julia_z); settings->setFloat("mgfractal_julia_w", julia_w); settings->setNoiseParams("mgfractal_np_seabed", np_seabed); settings->setNoiseParams("mgfractal_np_filler_depth", np_filler_depth); settings->setNoiseParams("mgfractal_np_cave1", np_cave1); settings->setNoiseParams("mgfractal_np_cave2", np_cave2); } ///////////////////////////////////////////////////////////////// int MapgenFractal::getSpawnLevelAtPoint(v2s16 p) { bool solid_below = false; // Dry solid node is present below to spawn on u8 air_count = 0; // Consecutive air nodes above the dry solid node s16 seabed_level = NoisePerlin2D(&noise_seabed->np, p.X, p.Y, seed); // Seabed can rise above water_level or might be raised to create dry land s16 search_start = MYMAX(seabed_level, water_level + 1); if (seabed_level > water_level) solid_below = true; for (s16 y = search_start; y <= search_start + 128; y++) { if (getFractalAtPoint(p.X, y, p.Y)) { // Fractal node solid_below = true; air_count = 0; } else if (solid_below) { // Air above solid node air_count++; // 3 to account for snowblock dust if (air_count == 3) return y - 2; } } return MAX_MAP_GENERATION_LIMIT; // Unsuitable spawn point } void MapgenFractal::makeChunk(BlockMakeData *data) { // Pre-conditions assert(data->vmanip); assert(data->nodedef); assert(data->blockpos_requested.X >= data->blockpos_min.X && data->blockpos_requested.Y >= data->blockpos_min.Y && data->blockpos_requested.Z >= data->blockpos_min.Z); assert(data->blockpos_requested.X <= data->blockpos_max.X && data->blockpos_requested.Y <= data->blockpos_max.Y && data->blockpos_requested.Z <= data->blockpos_max.Z); this->generating = true; this->vm = data->vmanip; this->ndef = data->nodedef; //TimeTaker t("makeChunk"); v3s16 blockpos_min = data->blockpos_min; v3s16 blockpos_max = data->blockpos_max; node_min = blockpos_min * MAP_BLOCKSIZE; node_max = (blockpos_max + v3s16(1, 1, 1)) * MAP_BLOCKSIZE - v3s16(1, 1, 1); full_node_min = (blockpos_min - 1) * MAP_BLOCKSIZE; full_node_max = (blockpos_max + 2) * MAP_BLOCKSIZE - v3s16(1, 1, 1); blockseed = getBlockSeed2(full_node_min, seed); // Generate base terrain, mountains, and ridges with initial heightmaps s16 stone_surface_max_y = generateTerrain(); // Create heightmap updateHeightmap(node_min, node_max); // Init biome generator, place biome-specific nodes, and build biomemap if (flags & MG_BIOMES) { biomegen->calcBiomeNoise(node_min); generateBiomes(); } if (flags & MG_CAVES) { // Generate tunnels generateCavesNoiseIntersection(stone_surface_max_y); // Generate large randomwalk caves generateCavesRandomWalk(stone_surface_max_y, large_cave_depth); } // Generate the registered ores m_emerge->oremgr->placeAllOres(this, blockseed, node_min, node_max); if ((flags & MG_DUNGEONS) && full_node_min.Y >= dungeon_ymin && full_node_max.Y <= dungeon_ymax) generateDungeons(stone_surface_max_y); // Generate the registered decorations if (flags & MG_DECORATIONS) m_emerge->decomgr->placeAllDecos(this, blockseed, node_min, node_max); // Sprinkle some dust on top after everything else was generated if (flags & MG_BIOMES) dustTopNodes(); //printf("makeChunk: %dms\n", t.stop()); updateLiquid(&data->transforming_liquid, full_node_min, full_node_max); if (flags & MG_LIGHT) calcLighting(node_min - v3s16(0, 1, 0), node_max + v3s16(0, 1, 0), full_node_min, full_node_max); //setLighting(node_min - v3s16(1, 0, 1) * MAP_BLOCKSIZE, // node_max + v3s16(1, 0, 1) * MAP_BLOCKSIZE, 0xFF); this->generating = false; } bool MapgenFractal::getFractalAtPoint(s16 x, s16 y, s16 z) { float cx, cy, cz, cw, ox, oy, oz, ow; if (julia) { // Julia set cx = julia_x; cy = julia_y; cz = julia_z; cw = julia_w; ox = (float)x / scale.X - offset.X; oy = (float)y / scale.Y - offset.Y; oz = (float)z / scale.Z - offset.Z; ow = slice_w; } else { // Mandelbrot set cx = (float)x / scale.X - offset.X; cy = (float)y / scale.Y - offset.Y; cz = (float)z / scale.Z - offset.Z; cw = slice_w; ox = 0.0f; oy = 0.0f; oz = 0.0f; ow = 0.0f; } float nx = 0.0f; float ny = 0.0f; float nz = 0.0f; float nw = 0.0f; for (u16 iter = 0; iter < iterations; iter++) { switch (formula) { default: case 1: // 4D "Roundy" nx = ox * ox - oy * oy - oz * oz - ow * ow + cx; ny = 2.0f * (ox * oy + oz * ow) + cy; nz = 2.0f * (ox * oz + oy * ow) + cz; nw = 2.0f * (ox * ow + oy * oz) + cw; break; case 2: // 4D "Squarry" nx = ox * ox - oy * oy - oz * oz - ow * ow + cx; ny = 2.0f * (ox * oy + oz * ow) + cy; nz = 2.0f * (ox * oz + oy * ow) + cz; nw = 2.0f * (ox * ow - oy * oz) + cw; break; case 3: // 4D "Mandy Cousin" nx = ox * ox - oy * oy - oz * oz + ow * ow + cx; ny = 2.0f * (ox * oy + oz * ow) + cy; nz = 2.0f * (ox * oz + oy * ow) + cz; nw = 2.0f * (ox * ow + oy * oz) + cw; break; case 4: // 4D "Variation" nx = ox * ox - oy * oy - oz * oz - ow * ow + cx; ny = 2.0f * (ox * oy + oz * ow) + cy; nz = 2.0f * (ox * oz - oy * ow) + cz; nw = 2.0f * (ox * ow + oy * oz) + cw; break; case 5: // 3D "Mandelbrot/Mandelbar" nx = ox * ox - oy * oy - oz * oz + cx; ny = 2.0f * ox * oy + cy; nz = -2.0f * ox * oz + cz; break; case 6: // 3D "Christmas Tree" // Altering the formula here is necessary to avoid division by zero if (std::fabs(oz) < 0.000000001f) { nx = ox * ox - oy * oy - oz * oz + cx; ny = 2.0f * oy * ox + cy; nz = 4.0f * oz * ox + cz; } else { float a = (2.0f * ox) / (std::sqrt(oy * oy + oz * oz)); nx = ox * ox - oy * oy - oz * oz + cx; ny = a * (oy * oy - oz * oz) + cy; nz = a * 2.0f * oy * oz + cz; } break; case 7: // 3D "Mandelbulb" if (std::fabs(oy) < 0.000000001f) { nx = ox * ox - oz * oz + cx; ny = cy; nz = -2.0f * oz * std::sqrt(ox * ox) + cz; } else { float a = 1.0f - (oz * oz) / (ox * ox + oy * oy); nx = (ox * ox - oy * oy) * a + cx; ny = 2.0f * ox * oy * a + cy; nz = -2.0f * oz * std::sqrt(ox * ox + oy * oy) + cz; } break; case 8: // 3D "Cosine Mandelbulb" if (std::fabs(oy) < 0.000000001f) { nx = 2.0f * ox * oz + cx; ny = 4.0f * oy * oz + cy; nz = oz * oz - ox * ox - oy * oy + cz; } else { float a = (2.0f * oz) / std::sqrt(ox * ox + oy * oy); nx = (ox * ox - oy * oy) * a + cx; ny = 2.0f * ox * oy * a + cy; nz = oz * oz - ox * ox - oy * oy + cz; } break; case 9: // 4D "Mandelbulb" float rxy = std::sqrt(ox * ox + oy * oy); float rxyz = std::sqrt(ox * ox + oy * oy + oz * oz); if (std::fabs(ow) < 0.000000001f && std::fabs(oz) < 0.000000001f) { nx = (ox * ox - oy * oy) + cx; ny = 2.0f * ox * oy + cy; nz = -2.0f * rxy * oz + cz; nw = 2.0f * rxyz * ow + cw; } else { float a = 1.0f - (ow * ow) / (rxyz * rxyz); float b = a * (1.0f - (oz * oz) / (rxy * rxy)); nx = (ox * ox - oy * oy) * b + cx; ny = 2.0f * ox * oy * b + cy; nz = -2.0f * rxy * oz * a + cz; nw = 2.0f * rxyz * ow + cw; } break; } if (nx * nx + ny * ny + nz * nz + nw * nw > 4.0f) return false; ox = nx; oy = ny; oz = nz; ow = nw; } return true; } s16 MapgenFractal::generateTerrain() { MapNode n_air(CONTENT_AIR); MapNode n_stone(c_stone); MapNode n_water(c_water_source); s16 stone_surface_max_y = -MAX_MAP_GENERATION_LIMIT; u32 index2d = 0; noise_seabed->perlinMap2D(node_min.X, node_min.Z); for (s16 z = node_min.Z; z <= node_max.Z; z++) { for (s16 y = node_min.Y - 1; y <= node_max.Y + 1; y++) { u32 vi = vm->m_area.index(node_min.X, y, z); for (s16 x = node_min.X; x <= node_max.X; x++, vi++, index2d++) { if (vm->m_data[vi].getContent() == CONTENT_IGNORE) { s16 seabed_height = noise_seabed->result[index2d]; if (y <= seabed_height || getFractalAtPoint(x, y, z)) { vm->m_data[vi] = n_stone; if (y > stone_surface_max_y) stone_surface_max_y = y; } else if (y <= water_level) { vm->m_data[vi] = n_water; } else { vm->m_data[vi] = n_air; } } } index2d -= ystride; } index2d += ystride; } return stone_surface_max_y; }
pgimeno/minetest
src/mapgen/mapgen_fractal.cpp
C++
mit
13,383
/* Minetest Copyright (C) 2015-2018 paramat Copyright (C) 2015-2018 kwolekr, Ryan Kwolek <kwolekr@minetest.net> Fractal formulas from http://www.bugman123.com/Hypercomplex/index.html by Paul Nylander, and from http://www.fractalforums.com, thank you. 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. */ #pragma once #include "mapgen.h" class BiomeManager; extern FlagDesc flagdesc_mapgen_fractal[]; struct MapgenFractalParams : public MapgenParams { u32 spflags = 0; float cave_width = 0.09f; s16 large_cave_depth = -33; s16 lava_depth = -256; s16 dungeon_ymin = -31000; s16 dungeon_ymax = 31000; u16 fractal = 1; u16 iterations = 11; v3f scale = v3f(4096.0, 1024.0, 4096.0); v3f offset = v3f(1.52, 0.0, 0.0); float slice_w = 0.0f; float julia_x = 0.267f; float julia_y = 0.2f; float julia_z = 0.133f; float julia_w = 0.067f; NoiseParams np_seabed; NoiseParams np_filler_depth; NoiseParams np_cave1; NoiseParams np_cave2; MapgenFractalParams(); ~MapgenFractalParams() = default; void readParams(const Settings *settings); void writeParams(Settings *settings) const; }; class MapgenFractal : public MapgenBasic { public: MapgenFractal(MapgenFractalParams *params, EmergeManager *emerge); ~MapgenFractal(); virtual MapgenType getType() const { return MAPGEN_FRACTAL; } virtual void makeChunk(BlockMakeData *data); int getSpawnLevelAtPoint(v2s16 p); bool getFractalAtPoint(s16 x, s16 y, s16 z); s16 generateTerrain(); private: u16 formula; bool julia; s16 large_cave_depth; s16 dungeon_ymin; s16 dungeon_ymax; u16 fractal; u16 iterations; v3f scale; v3f offset; float slice_w; float julia_x; float julia_y; float julia_z; float julia_w; Noise *noise_seabed; };
pgimeno/minetest
src/mapgen/mapgen_fractal.h
C++
mit
2,372
/* Minetest Copyright (C) 2013-2018 celeron55, Perttu Ahola <celeron55@gmail.com> Copyright (C) 2013-2018 kwolekr, Ryan Kwolek <kwolekr@minetest.net> Copyright (C) 2015-2018 paramat 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 "mapgen_singlenode.h" #include "voxel.h" #include "mapblock.h" #include "mapnode.h" #include "map.h" #include "nodedef.h" #include "voxelalgorithms.h" #include "emerge.h" MapgenSinglenode::MapgenSinglenode(MapgenParams *params, EmergeManager *emerge) : Mapgen(MAPGEN_SINGLENODE, params, emerge) { const NodeDefManager *ndef = emerge->ndef; c_node = ndef->getId("mapgen_singlenode"); if (c_node == CONTENT_IGNORE) c_node = CONTENT_AIR; MapNode n_node(c_node); set_light = (ndef->get(n_node).sunlight_propagates) ? LIGHT_SUN : 0x00; } //////////////////////// Map generator void MapgenSinglenode::makeChunk(BlockMakeData *data) { // Pre-conditions assert(data->vmanip); assert(data->nodedef); assert(data->blockpos_requested.X >= data->blockpos_min.X && data->blockpos_requested.Y >= data->blockpos_min.Y && data->blockpos_requested.Z >= data->blockpos_min.Z); assert(data->blockpos_requested.X <= data->blockpos_max.X && data->blockpos_requested.Y <= data->blockpos_max.Y && data->blockpos_requested.Z <= data->blockpos_max.Z); this->generating = true; this->vm = data->vmanip; this->ndef = data->nodedef; v3s16 blockpos_min = data->blockpos_min; v3s16 blockpos_max = data->blockpos_max; // Area of central chunk v3s16 node_min = blockpos_min * MAP_BLOCKSIZE; v3s16 node_max = (blockpos_max + v3s16(1, 1, 1)) * MAP_BLOCKSIZE - v3s16(1, 1, 1); blockseed = getBlockSeed2(node_min, data->seed); MapNode n_node(c_node); for (s16 z = node_min.Z; z <= node_max.Z; z++) for (s16 y = node_min.Y; y <= node_max.Y; y++) { u32 i = vm->m_area.index(node_min.X, y, z); for (s16 x = node_min.X; x <= node_max.X; x++) { if (vm->m_data[i].getContent() == CONTENT_IGNORE) vm->m_data[i] = n_node; i++; } } // Add top and bottom side of water to transforming_liquid queue updateLiquid(&data->transforming_liquid, node_min, node_max); // Set lighting if ((flags & MG_LIGHT) && set_light == LIGHT_SUN) setLighting(LIGHT_SUN, node_min, node_max); this->generating = false; } int MapgenSinglenode::getSpawnLevelAtPoint(v2s16 p) { return 0; }
pgimeno/minetest
src/mapgen/mapgen_singlenode.cpp
C++
mit
2,995
/* Minetest Copyright (C) 2013-2018 celeron55, Perttu Ahola <celeron55@gmail.com> Copyright (C) 2013-2018 kwolekr, Ryan Kwolek <kwolekr@minetest.net> Copyright (C) 2015-2018 paramat 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. */ #pragma once #include "mapgen.h" struct MapgenSinglenodeParams : public MapgenParams { MapgenSinglenodeParams() = default; ~MapgenSinglenodeParams() = default; void readParams(const Settings *settings) {} void writeParams(Settings *settings) const {} }; class MapgenSinglenode : public Mapgen { public: content_t c_node; u8 set_light; MapgenSinglenode(MapgenParams *params, EmergeManager *emerge); ~MapgenSinglenode() = default; virtual MapgenType getType() const { return MAPGEN_SINGLENODE; } void makeChunk(BlockMakeData *data); int getSpawnLevelAtPoint(v2s16 p); };
pgimeno/minetest
src/mapgen/mapgen_singlenode.h
C++
mit
1,477
/* Minetest Copyright (C) 2014-2018 paramat Copyright (C) 2014-2018 kwolekr, Ryan Kwolek <kwolekr@minetest.net> 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 "mapgen.h" #include "voxel.h" #include "noise.h" #include "mapblock.h" #include "mapnode.h" #include "map.h" #include "content_sao.h" #include "nodedef.h" #include "voxelalgorithms.h" //#include "profiler.h" // For TimeTaker #include "settings.h" // For g_settings #include "emerge.h" #include "dungeongen.h" #include "cavegen.h" #include "mg_biome.h" #include "mg_ore.h" #include "mg_decoration.h" #include "mapgen_v5.h" FlagDesc flagdesc_mapgen_v5[] = { {"caverns", MGV5_CAVERNS}, {NULL, 0} }; MapgenV5::MapgenV5(MapgenV5Params *params, EmergeManager *emerge) : MapgenBasic(MAPGEN_V5, params, emerge) { spflags = params->spflags; cave_width = params->cave_width; large_cave_depth = params->large_cave_depth; lava_depth = params->lava_depth; cavern_limit = params->cavern_limit; cavern_taper = params->cavern_taper; cavern_threshold = params->cavern_threshold; dungeon_ymin = params->dungeon_ymin; dungeon_ymax = params->dungeon_ymax; // Terrain noise noise_filler_depth = new Noise(&params->np_filler_depth, seed, csize.X, csize.Z); noise_factor = new Noise(&params->np_factor, seed, csize.X, csize.Z); noise_height = new Noise(&params->np_height, seed, csize.X, csize.Z); // 3D terrain noise // 1-up 1-down overgeneration noise_ground = new Noise(&params->np_ground, seed, csize.X, csize.Y + 2, csize.Z); // 1 down overgeneration MapgenBasic::np_cave1 = params->np_cave1; MapgenBasic::np_cave2 = params->np_cave2; MapgenBasic::np_cavern = params->np_cavern; } MapgenV5::~MapgenV5() { delete noise_filler_depth; delete noise_factor; delete noise_height; delete noise_ground; } MapgenV5Params::MapgenV5Params(): np_filler_depth (0, 1, v3f(150, 150, 150), 261, 4, 0.7, 2.0), np_factor (0, 1, v3f(250, 250, 250), 920381, 3, 0.45, 2.0), np_height (0, 10, v3f(250, 250, 250), 84174, 4, 0.5, 2.0), np_ground (0, 40, v3f(80, 80, 80), 983240, 4, 0.55, 2.0, NOISE_FLAG_EASED), np_cave1 (0, 12, v3f(61, 61, 61), 52534, 3, 0.5, 2.0), np_cave2 (0, 12, v3f(67, 67, 67), 10325, 3, 0.5, 2.0), np_cavern (0, 1, v3f(384, 128, 384), 723, 5, 0.63, 2.0) { } void MapgenV5Params::readParams(const Settings *settings) { settings->getFlagStrNoEx("mgv5_spflags", spflags, flagdesc_mapgen_v5); settings->getFloatNoEx("mgv5_cave_width", cave_width); settings->getS16NoEx("mgv5_large_cave_depth", large_cave_depth); settings->getS16NoEx("mgv5_lava_depth", lava_depth); settings->getS16NoEx("mgv5_cavern_limit", cavern_limit); settings->getS16NoEx("mgv5_cavern_taper", cavern_taper); settings->getFloatNoEx("mgv5_cavern_threshold", cavern_threshold); settings->getS16NoEx("mgv5_dungeon_ymin", dungeon_ymin); settings->getS16NoEx("mgv5_dungeon_ymax", dungeon_ymax); settings->getNoiseParams("mgv5_np_filler_depth", np_filler_depth); settings->getNoiseParams("mgv5_np_factor", np_factor); settings->getNoiseParams("mgv5_np_height", np_height); settings->getNoiseParams("mgv5_np_ground", np_ground); settings->getNoiseParams("mgv5_np_cave1", np_cave1); settings->getNoiseParams("mgv5_np_cave2", np_cave2); settings->getNoiseParams("mgv5_np_cavern", np_cavern); } void MapgenV5Params::writeParams(Settings *settings) const { settings->setFlagStr("mgv5_spflags", spflags, flagdesc_mapgen_v5, U32_MAX); settings->setFloat("mgv5_cave_width", cave_width); settings->setS16("mgv5_large_cave_depth", large_cave_depth); settings->setS16("mgv5_lava_depth", lava_depth); settings->setS16("mgv5_cavern_limit", cavern_limit); settings->setS16("mgv5_cavern_taper", cavern_taper); settings->setFloat("mgv5_cavern_threshold", cavern_threshold); settings->setS16("mgv5_dungeon_ymin", dungeon_ymin); settings->setS16("mgv5_dungeon_ymax", dungeon_ymax); settings->setNoiseParams("mgv5_np_filler_depth", np_filler_depth); settings->setNoiseParams("mgv5_np_factor", np_factor); settings->setNoiseParams("mgv5_np_height", np_height); settings->setNoiseParams("mgv5_np_ground", np_ground); settings->setNoiseParams("mgv5_np_cave1", np_cave1); settings->setNoiseParams("mgv5_np_cave2", np_cave2); settings->setNoiseParams("mgv5_np_cavern", np_cavern); } int MapgenV5::getSpawnLevelAtPoint(v2s16 p) { float f = 0.55 + NoisePerlin2D(&noise_factor->np, p.X, p.Y, seed); if (f < 0.01) f = 0.01; else if (f >= 1.0) f *= 1.6; float h = NoisePerlin2D(&noise_height->np, p.X, p.Y, seed); // noise_height 'offset' is the average level of terrain. At least 50% of // terrain will be below this. // Raising the maximum spawn level above 'water_level + 16' is necessary // for when noise_height 'offset' is set much higher than water_level. s16 max_spawn_y = MYMAX(noise_height->np.offset, water_level + 16); // Starting spawn search at max_spawn_y + 128 ensures 128 nodes of open // space above spawn position. Avoids spawning in possibly sealed voids. for (s16 y = max_spawn_y + 128; y >= water_level; y--) { float n_ground = NoisePerlin3D(&noise_ground->np, p.X, y, p.Y, seed); if (n_ground * f > y - h) { // If solid if (y < water_level || y > max_spawn_y) return MAX_MAP_GENERATION_LIMIT; // Unsuitable spawn point // y + 2 because y is surface and due to biome 'dust' nodes. return y + 2; } } // Unsuitable spawn position, no ground found return MAX_MAP_GENERATION_LIMIT; } void MapgenV5::makeChunk(BlockMakeData *data) { // Pre-conditions assert(data->vmanip); assert(data->nodedef); assert(data->blockpos_requested.X >= data->blockpos_min.X && data->blockpos_requested.Y >= data->blockpos_min.Y && data->blockpos_requested.Z >= data->blockpos_min.Z); assert(data->blockpos_requested.X <= data->blockpos_max.X && data->blockpos_requested.Y <= data->blockpos_max.Y && data->blockpos_requested.Z <= data->blockpos_max.Z); this->generating = true; this->vm = data->vmanip; this->ndef = data->nodedef; //TimeTaker t("makeChunk"); v3s16 blockpos_min = data->blockpos_min; v3s16 blockpos_max = data->blockpos_max; node_min = blockpos_min * MAP_BLOCKSIZE; node_max = (blockpos_max + v3s16(1, 1, 1)) * MAP_BLOCKSIZE - v3s16(1, 1, 1); full_node_min = (blockpos_min - 1) * MAP_BLOCKSIZE; full_node_max = (blockpos_max + 2) * MAP_BLOCKSIZE - v3s16(1, 1, 1); // Create a block-specific seed blockseed = getBlockSeed2(full_node_min, seed); // Generate base terrain s16 stone_surface_max_y = generateBaseTerrain(); // Create heightmap updateHeightmap(node_min, node_max); // Init biome generator, place biome-specific nodes, and build biomemap if (flags & MG_BIOMES) { biomegen->calcBiomeNoise(node_min); generateBiomes(); } // Generate tunnels, caverns and large randomwalk caves if (flags & MG_CAVES) { // Generate tunnels first as caverns confuse them generateCavesNoiseIntersection(stone_surface_max_y); // Generate caverns bool near_cavern = false; if (spflags & MGV5_CAVERNS) near_cavern = generateCavernsNoise(stone_surface_max_y); // Generate large randomwalk caves if (near_cavern) // Disable large randomwalk caves in this mapchunk by setting // 'large cave depth' to world base. Avoids excessive liquid in // large caverns and floating blobs of overgenerated liquid. generateCavesRandomWalk(stone_surface_max_y, -MAX_MAP_GENERATION_LIMIT); else generateCavesRandomWalk(stone_surface_max_y, large_cave_depth); } // Generate the registered ores m_emerge->oremgr->placeAllOres(this, blockseed, node_min, node_max); // Generate dungeons and desert temples if ((flags & MG_DUNGEONS) && full_node_min.Y >= dungeon_ymin && full_node_max.Y <= dungeon_ymax) generateDungeons(stone_surface_max_y); // Generate the registered decorations if (flags & MG_DECORATIONS) m_emerge->decomgr->placeAllDecos(this, blockseed, node_min, node_max); // Sprinkle some dust on top after everything else was generated if (flags & MG_BIOMES) dustTopNodes(); //printf("makeChunk: %dms\n", t.stop()); // Add top and bottom side of water to transforming_liquid queue updateLiquid(&data->transforming_liquid, full_node_min, full_node_max); // Calculate lighting if (flags & MG_LIGHT) { calcLighting(node_min - v3s16(0, 1, 0), node_max + v3s16(0, 1, 0), full_node_min, full_node_max); } this->generating = false; } int MapgenV5::generateBaseTerrain() { u32 index = 0; u32 index2d = 0; int stone_surface_max_y = -MAX_MAP_GENERATION_LIMIT; noise_factor->perlinMap2D(node_min.X, node_min.Z); noise_height->perlinMap2D(node_min.X, node_min.Z); noise_ground->perlinMap3D(node_min.X, node_min.Y - 1, node_min.Z); for (s16 z=node_min.Z; z<=node_max.Z; z++) { for (s16 y=node_min.Y - 1; y<=node_max.Y + 1; y++) { u32 vi = vm->m_area.index(node_min.X, y, z); for (s16 x=node_min.X; x<=node_max.X; x++, vi++, index++, index2d++) { if (vm->m_data[vi].getContent() != CONTENT_IGNORE) continue; float f = 0.55 + noise_factor->result[index2d]; if (f < 0.01) f = 0.01; else if (f >= 1.0) f *= 1.6; float h = noise_height->result[index2d]; if (noise_ground->result[index] * f < y - h) { if (y <= water_level) vm->m_data[vi] = MapNode(c_water_source); else vm->m_data[vi] = MapNode(CONTENT_AIR); } else { vm->m_data[vi] = MapNode(c_stone); if (y > stone_surface_max_y) stone_surface_max_y = y; } } index2d -= ystride; } index2d += ystride; } return stone_surface_max_y; }
pgimeno/minetest
src/mapgen/mapgen_v5.cpp
C++
mit
10,468
/* Minetest Copyright (C) 2014-2018 paramat Copyright (C) 2014-2018 kwolekr, Ryan Kwolek <kwolekr@minetest.net> 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. */ #pragma once #include "mapgen.h" ///////// Mapgen V5 flags #define MGV5_CAVERNS 0x01 class BiomeManager; extern FlagDesc flagdesc_mapgen_v5[]; struct MapgenV5Params : public MapgenParams { u32 spflags = MGV5_CAVERNS; float cave_width = 0.09f; s16 large_cave_depth = -256; s16 lava_depth = -256; s16 cavern_limit = -256; s16 cavern_taper = 256; float cavern_threshold = 0.7f; s16 dungeon_ymin = -31000; s16 dungeon_ymax = 31000; NoiseParams np_filler_depth; NoiseParams np_factor; NoiseParams np_height; NoiseParams np_ground; NoiseParams np_cave1; NoiseParams np_cave2; NoiseParams np_cavern; MapgenV5Params(); ~MapgenV5Params() = default; void readParams(const Settings *settings); void writeParams(Settings *settings) const; }; class MapgenV5 : public MapgenBasic { public: MapgenV5(MapgenV5Params *params, EmergeManager *emerge); ~MapgenV5(); virtual MapgenType getType() const { return MAPGEN_V5; } virtual void makeChunk(BlockMakeData *data); int getSpawnLevelAtPoint(v2s16 p); int generateBaseTerrain(); private: s16 large_cave_depth; s16 dungeon_ymin; s16 dungeon_ymax; Noise *noise_factor; Noise *noise_height; Noise *noise_ground; };
pgimeno/minetest
src/mapgen/mapgen_v5.h
C++
mit
2,008
/* Minetest Copyright (C) 2010-2018 celeron55, Perttu Ahola <celeron55@gmail.com> Copyright (C) 2013-2018 kwolekr, Ryan Kwolek <kwolekr@minetest.net> Copyright (C) 2014-2018 paramat 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 "mapgen.h" #include "voxel.h" #include "noise.h" #include "mapblock.h" #include "mapnode.h" #include "map.h" //#include "serverobject.h" #include "content_sao.h" #include "nodedef.h" #include "voxelalgorithms.h" //#include "profiler.h" // For TimeTaker #include "settings.h" // For g_settings #include "emerge.h" #include "dungeongen.h" #include "cavegen.h" #include "treegen.h" #include "mg_ore.h" #include "mg_decoration.h" #include "mapgen_v6.h" FlagDesc flagdesc_mapgen_v6[] = { {"jungles", MGV6_JUNGLES}, {"biomeblend", MGV6_BIOMEBLEND}, {"mudflow", MGV6_MUDFLOW}, {"snowbiomes", MGV6_SNOWBIOMES}, {"flat", MGV6_FLAT}, {"trees", MGV6_TREES}, {NULL, 0} }; ///////////////////////////////////////////////////////////////////////////// MapgenV6::MapgenV6(MapgenV6Params *params, EmergeManager *emerge) : Mapgen(MAPGEN_V6, params, emerge) { m_emerge = emerge; ystride = csize.X; //////fix this heightmap = new s16[csize.X * csize.Z]; spflags = params->spflags; freq_desert = params->freq_desert; freq_beach = params->freq_beach; dungeon_ymin = params->dungeon_ymin; dungeon_ymax = params->dungeon_ymax; np_cave = &params->np_cave; np_humidity = &params->np_humidity; np_trees = &params->np_trees; np_apple_trees = &params->np_apple_trees; //// Create noise objects noise_terrain_base = new Noise(&params->np_terrain_base, seed, csize.X, csize.Y); noise_terrain_higher = new Noise(&params->np_terrain_higher, seed, csize.X, csize.Y); noise_steepness = new Noise(&params->np_steepness, seed, csize.X, csize.Y); noise_height_select = new Noise(&params->np_height_select, seed, csize.X, csize.Y); noise_mud = new Noise(&params->np_mud, seed, csize.X, csize.Y); noise_beach = new Noise(&params->np_beach, seed, csize.X, csize.Y); noise_biome = new Noise(&params->np_biome, seed, csize.X + 2 * MAP_BLOCKSIZE, csize.Y + 2 * MAP_BLOCKSIZE); noise_humidity = new Noise(&params->np_humidity, seed, csize.X + 2 * MAP_BLOCKSIZE, csize.Y + 2 * MAP_BLOCKSIZE); //// Resolve nodes to be used const NodeDefManager *ndef = emerge->ndef; c_stone = ndef->getId("mapgen_stone"); c_dirt = ndef->getId("mapgen_dirt"); c_dirt_with_grass = ndef->getId("mapgen_dirt_with_grass"); c_sand = ndef->getId("mapgen_sand"); c_water_source = ndef->getId("mapgen_water_source"); c_lava_source = ndef->getId("mapgen_lava_source"); c_gravel = ndef->getId("mapgen_gravel"); c_desert_stone = ndef->getId("mapgen_desert_stone"); c_desert_sand = ndef->getId("mapgen_desert_sand"); c_dirt_with_snow = ndef->getId("mapgen_dirt_with_snow"); c_snow = ndef->getId("mapgen_snow"); c_snowblock = ndef->getId("mapgen_snowblock"); c_ice = ndef->getId("mapgen_ice"); if (c_gravel == CONTENT_IGNORE) c_gravel = c_stone; if (c_desert_stone == CONTENT_IGNORE) c_desert_stone = c_stone; if (c_desert_sand == CONTENT_IGNORE) c_desert_sand = c_sand; if (c_dirt_with_snow == CONTENT_IGNORE) c_dirt_with_snow = c_dirt_with_grass; if (c_snow == CONTENT_IGNORE) c_snow = CONTENT_AIR; if (c_snowblock == CONTENT_IGNORE) c_snowblock = c_dirt_with_grass; if (c_ice == CONTENT_IGNORE) c_ice = c_water_source; c_cobble = ndef->getId("mapgen_cobble"); c_mossycobble = ndef->getId("mapgen_mossycobble"); c_stair_cobble = ndef->getId("mapgen_stair_cobble"); c_stair_desert_stone = ndef->getId("mapgen_stair_desert_stone"); if (c_mossycobble == CONTENT_IGNORE) c_mossycobble = c_cobble; if (c_stair_cobble == CONTENT_IGNORE) c_stair_cobble = c_cobble; if (c_stair_desert_stone == CONTENT_IGNORE) c_stair_desert_stone = c_desert_stone; } MapgenV6::~MapgenV6() { delete noise_terrain_base; delete noise_terrain_higher; delete noise_steepness; delete noise_height_select; delete noise_mud; delete noise_beach; delete noise_biome; delete noise_humidity; delete[] heightmap; } MapgenV6Params::MapgenV6Params(): np_terrain_base (-4, 20.0, v3f(250.0, 250.0, 250.0), 82341, 5, 0.6, 2.0), np_terrain_higher (20, 16.0, v3f(500.0, 500.0, 500.0), 85039, 5, 0.6, 2.0), np_steepness (0.85, 0.5, v3f(125.0, 125.0, 125.0), -932, 5, 0.7, 2.0), np_height_select (0, 1.0, v3f(250.0, 250.0, 250.0), 4213, 5, 0.69, 2.0), np_mud (4, 2.0, v3f(200.0, 200.0, 200.0), 91013, 3, 0.55, 2.0), np_beach (0, 1.0, v3f(250.0, 250.0, 250.0), 59420, 3, 0.50, 2.0), np_biome (0, 1.0, v3f(500.0, 500.0, 500.0), 9130, 3, 0.50, 2.0), np_cave (6, 6.0, v3f(250.0, 250.0, 250.0), 34329, 3, 0.50, 2.0), np_humidity (0.5, 0.5, v3f(500.0, 500.0, 500.0), 72384, 3, 0.50, 2.0), np_trees (0, 1.0, v3f(125.0, 125.0, 125.0), 2, 4, 0.66, 2.0), np_apple_trees (0, 1.0, v3f(100.0, 100.0, 100.0), 342902, 3, 0.45, 2.0) { } void MapgenV6Params::readParams(const Settings *settings) { settings->getFlagStrNoEx("mgv6_spflags", spflags, flagdesc_mapgen_v6); settings->getFloatNoEx("mgv6_freq_desert", freq_desert); settings->getFloatNoEx("mgv6_freq_beach", freq_beach); settings->getS16NoEx("mgv6_dungeon_ymin", dungeon_ymin); settings->getS16NoEx("mgv6_dungeon_ymax", dungeon_ymax); settings->getNoiseParams("mgv6_np_terrain_base", np_terrain_base); settings->getNoiseParams("mgv6_np_terrain_higher", np_terrain_higher); settings->getNoiseParams("mgv6_np_steepness", np_steepness); settings->getNoiseParams("mgv6_np_height_select", np_height_select); settings->getNoiseParams("mgv6_np_mud", np_mud); settings->getNoiseParams("mgv6_np_beach", np_beach); settings->getNoiseParams("mgv6_np_biome", np_biome); settings->getNoiseParams("mgv6_np_cave", np_cave); settings->getNoiseParams("mgv6_np_humidity", np_humidity); settings->getNoiseParams("mgv6_np_trees", np_trees); settings->getNoiseParams("mgv6_np_apple_trees", np_apple_trees); } void MapgenV6Params::writeParams(Settings *settings) const { settings->setFlagStr("mgv6_spflags", spflags, flagdesc_mapgen_v6, U32_MAX); settings->setFloat("mgv6_freq_desert", freq_desert); settings->setFloat("mgv6_freq_beach", freq_beach); settings->setS16("mgv6_dungeon_ymin", dungeon_ymin); settings->setS16("mgv6_dungeon_ymax", dungeon_ymax); settings->setNoiseParams("mgv6_np_terrain_base", np_terrain_base); settings->setNoiseParams("mgv6_np_terrain_higher", np_terrain_higher); settings->setNoiseParams("mgv6_np_steepness", np_steepness); settings->setNoiseParams("mgv6_np_height_select", np_height_select); settings->setNoiseParams("mgv6_np_mud", np_mud); settings->setNoiseParams("mgv6_np_beach", np_beach); settings->setNoiseParams("mgv6_np_biome", np_biome); settings->setNoiseParams("mgv6_np_cave", np_cave); settings->setNoiseParams("mgv6_np_humidity", np_humidity); settings->setNoiseParams("mgv6_np_trees", np_trees); settings->setNoiseParams("mgv6_np_apple_trees", np_apple_trees); } //////////////////////// Some helper functions for the map generator // Returns Y one under area minimum if not found s16 MapgenV6::find_stone_level(v2s16 p2d) { const v3s16 &em = vm->m_area.getExtent(); s16 y_nodes_max = vm->m_area.MaxEdge.Y; s16 y_nodes_min = vm->m_area.MinEdge.Y; u32 i = vm->m_area.index(p2d.X, y_nodes_max, p2d.Y); s16 y; for (y = y_nodes_max; y >= y_nodes_min; y--) { content_t c = vm->m_data[i].getContent(); if (c != CONTENT_IGNORE && (c == c_stone || c == c_desert_stone)) break; VoxelArea::add_y(em, i, -1); } return (y >= y_nodes_min) ? y : y_nodes_min - 1; } // Required by mapgen.h bool MapgenV6::block_is_underground(u64 seed, v3s16 blockpos) { /*s16 minimum_groundlevel = (s16)get_sector_minimum_ground_level( seed, v2s16(blockpos.X, blockpos.Z));*/ // Nah, this is just a heuristic, just return something s16 minimum_groundlevel = water_level; if(blockpos.Y * MAP_BLOCKSIZE + MAP_BLOCKSIZE <= minimum_groundlevel) return true; return false; } //////////////////////// Base terrain height functions float MapgenV6::baseTerrainLevel(float terrain_base, float terrain_higher, float steepness, float height_select) { float base = 1 + terrain_base; float higher = 1 + terrain_higher; // Limit higher ground level to at least base if(higher < base) higher = base; // Steepness factor of cliffs float b = steepness; b = rangelim(b, 0.0, 1000.0); b = 5 * b * b * b * b * b * b * b; b = rangelim(b, 0.5, 1000.0); // Values 1.5...100 give quite horrible looking slopes if (b > 1.5 && b < 100.0) b = (b < 10.0) ? 1.5 : 100.0; float a_off = -0.20; // Offset to more low float a = 0.5 + b * (a_off + height_select); a = rangelim(a, 0.0, 1.0); // Limit return base * (1.0 - a) + higher * a; } float MapgenV6::baseTerrainLevelFromNoise(v2s16 p) { if (spflags & MGV6_FLAT) return water_level; float terrain_base = NoisePerlin2D_PO(&noise_terrain_base->np, p.X, 0.5, p.Y, 0.5, seed); float terrain_higher = NoisePerlin2D_PO(&noise_terrain_higher->np, p.X, 0.5, p.Y, 0.5, seed); float steepness = NoisePerlin2D_PO(&noise_steepness->np, p.X, 0.5, p.Y, 0.5, seed); float height_select = NoisePerlin2D_PO(&noise_height_select->np, p.X, 0.5, p.Y, 0.5, seed); return baseTerrainLevel(terrain_base, terrain_higher, steepness, height_select); } float MapgenV6::baseTerrainLevelFromMap(v2s16 p) { int index = (p.Y - node_min.Z) * ystride + (p.X - node_min.X); return baseTerrainLevelFromMap(index); } float MapgenV6::baseTerrainLevelFromMap(int index) { if (spflags & MGV6_FLAT) return water_level; float terrain_base = noise_terrain_base->result[index]; float terrain_higher = noise_terrain_higher->result[index]; float steepness = noise_steepness->result[index]; float height_select = noise_height_select->result[index]; return baseTerrainLevel(terrain_base, terrain_higher, steepness, height_select); } s16 MapgenV6::find_ground_level_from_noise(u64 seed, v2s16 p2d, s16 precision) { return baseTerrainLevelFromNoise(p2d) + MGV6_AVERAGE_MUD_AMOUNT; } int MapgenV6::getGroundLevelAtPoint(v2s16 p) { return baseTerrainLevelFromNoise(p) + MGV6_AVERAGE_MUD_AMOUNT; } int MapgenV6::getSpawnLevelAtPoint(v2s16 p) { s16 level_at_point = baseTerrainLevelFromNoise(p) + MGV6_AVERAGE_MUD_AMOUNT; if (level_at_point <= water_level || level_at_point > water_level + 16) return MAX_MAP_GENERATION_LIMIT; // Unsuitable spawn point return level_at_point; } //////////////////////// Noise functions float MapgenV6::getMudAmount(v2s16 p) { int index = (p.Y - node_min.Z) * ystride + (p.X - node_min.X); return getMudAmount(index); } bool MapgenV6::getHaveBeach(v2s16 p) { int index = (p.Y - node_min.Z) * ystride + (p.X - node_min.X); return getHaveBeach(index); } BiomeV6Type MapgenV6::getBiome(v2s16 p) { int index = (p.Y - full_node_min.Z) * (ystride + 2 * MAP_BLOCKSIZE) + (p.X - full_node_min.X); return getBiome(index, p); } float MapgenV6::getHumidity(v2s16 p) { /*double noise = noise2d_perlin( 0.5+(float)p.X/500, 0.5+(float)p.Y/500, seed+72384, 4, 0.66); noise = (noise + 1.0)/2.0;*/ int index = (p.Y - full_node_min.Z) * (ystride + 2 * MAP_BLOCKSIZE) + (p.X - full_node_min.X); float noise = noise_humidity->result[index]; if (noise < 0.0) noise = 0.0; if (noise > 1.0) noise = 1.0; return noise; } float MapgenV6::getTreeAmount(v2s16 p) { /*double noise = noise2d_perlin( 0.5+(float)p.X/125, 0.5+(float)p.Y/125, seed+2, 4, 0.66);*/ float noise = NoisePerlin2D(np_trees, p.X, p.Y, seed); float zeroval = -0.39; if (noise < zeroval) return 0; return 0.04 * (noise - zeroval) / (1.0 - zeroval); } bool MapgenV6::getHaveAppleTree(v2s16 p) { /*is_apple_tree = noise2d_perlin( 0.5+(float)p.X/100, 0.5+(float)p.Z/100, data->seed+342902, 3, 0.45) > 0.2;*/ float noise = NoisePerlin2D(np_apple_trees, p.X, p.Y, seed); return noise > 0.2; } float MapgenV6::getMudAmount(int index) { if (spflags & MGV6_FLAT) return MGV6_AVERAGE_MUD_AMOUNT; /*return ((float)AVERAGE_MUD_AMOUNT + 2.0 * noise2d_perlin( 0.5+(float)p.X/200, 0.5+(float)p.Y/200, seed+91013, 3, 0.55));*/ return noise_mud->result[index]; } bool MapgenV6::getHaveBeach(int index) { // Determine whether to have sand here /*double sandnoise = noise2d_perlin( 0.2+(float)p2d.X/250, 0.7+(float)p2d.Y/250, seed+59420, 3, 0.50);*/ float sandnoise = noise_beach->result[index]; return (sandnoise > freq_beach); } BiomeV6Type MapgenV6::getBiome(int index, v2s16 p) { // Just do something very simple as for now /*double d = noise2d_perlin( 0.6+(float)p2d.X/250, 0.2+(float)p2d.Y/250, seed+9130, 3, 0.50);*/ float d = noise_biome->result[index]; float h = noise_humidity->result[index]; if (spflags & MGV6_SNOWBIOMES) { float blend = (spflags & MGV6_BIOMEBLEND) ? noise2d(p.X, p.Y, seed) / 40 : 0; if (d > MGV6_FREQ_HOT + blend) { if (h > MGV6_FREQ_JUNGLE + blend) return BT_JUNGLE; return BT_DESERT; } if (d < MGV6_FREQ_SNOW + blend) { if (h > MGV6_FREQ_TAIGA + blend) return BT_TAIGA; return BT_TUNDRA; } return BT_NORMAL; } if (d > freq_desert) return BT_DESERT; if ((spflags & MGV6_BIOMEBLEND) && (d > freq_desert - 0.10) && ((noise2d(p.X, p.Y, seed) + 1.0) > (freq_desert - d) * 20.0)) return BT_DESERT; if ((spflags & MGV6_JUNGLES) && h > 0.75) return BT_JUNGLE; return BT_NORMAL; } u32 MapgenV6::get_blockseed(u64 seed, v3s16 p) { s32 x = p.X, y = p.Y, z = p.Z; return (u32)(seed % 0x100000000ULL) + z * 38134234 + y * 42123 + x * 23; } //////////////////////// Map generator void MapgenV6::makeChunk(BlockMakeData *data) { // Pre-conditions assert(data->vmanip); assert(data->nodedef); assert(data->blockpos_requested.X >= data->blockpos_min.X && data->blockpos_requested.Y >= data->blockpos_min.Y && data->blockpos_requested.Z >= data->blockpos_min.Z); assert(data->blockpos_requested.X <= data->blockpos_max.X && data->blockpos_requested.Y <= data->blockpos_max.Y && data->blockpos_requested.Z <= data->blockpos_max.Z); this->generating = true; this->vm = data->vmanip; this->ndef = data->nodedef; // Hack: use minimum block coords for old code that assumes a single block v3s16 blockpos_min = data->blockpos_min; v3s16 blockpos_max = data->blockpos_max; // Area of central chunk node_min = blockpos_min * MAP_BLOCKSIZE; node_max = (blockpos_max + v3s16(1, 1, 1)) * MAP_BLOCKSIZE - v3s16(1, 1, 1); // Full allocated area full_node_min = (blockpos_min - 1) * MAP_BLOCKSIZE; full_node_max = (blockpos_max + 2) * MAP_BLOCKSIZE - v3s16(1, 1, 1); central_area_size = node_max - node_min + v3s16(1, 1, 1); assert(central_area_size.X == central_area_size.Z); // Create a block-specific seed blockseed = get_blockseed(data->seed, full_node_min); // Make some noise calculateNoise(); // Maximum height of the stone surface and obstacles. // This is used to guide the cave generation s16 stone_surface_max_y; // Generate general ground level to full area stone_surface_max_y = generateGround(); // Create initial heightmap to limit caves updateHeightmap(node_min, node_max); const s16 max_spread_amount = MAP_BLOCKSIZE; // Limit dirt flow area by 1 because mud is flown into neighbors. s16 mudflow_minpos = -max_spread_amount + 1; s16 mudflow_maxpos = central_area_size.X + max_spread_amount - 2; // Loop this part, it will make stuff look older and newer nicely const u32 age_loops = 2; for (u32 i_age = 0; i_age < age_loops; i_age++) { // Aging loop // Make caves (this code is relatively horrible) if (flags & MG_CAVES) generateCaves(stone_surface_max_y); // Add mud to the central chunk addMud(); // Flow mud away from steep edges if (spflags & MGV6_MUDFLOW) flowMud(mudflow_minpos, mudflow_maxpos); } // Update heightmap after mudflow updateHeightmap(node_min, node_max); // Add dungeons if ((flags & MG_DUNGEONS) && stone_surface_max_y >= node_min.Y && full_node_min.Y >= dungeon_ymin && full_node_max.Y <= dungeon_ymax) { DungeonParams dp; dp.seed = seed; dp.only_in_ground = true; dp.corridor_len_min = 1; dp.corridor_len_max = 13; dp.rooms_min = 2; dp.rooms_max = 16; dp.np_density = NoiseParams(0.9, 0.5, v3f(500.0, 500.0, 500.0), 0, 2, 0.8, 2.0); dp.np_alt_wall = NoiseParams(-0.4, 1.0, v3f(40.0, 40.0, 40.0), 32474, 6, 1.1, 2.0); if (getBiome(0, v2s16(node_min.X, node_min.Z)) == BT_DESERT) { dp.c_wall = c_desert_stone; dp.c_alt_wall = CONTENT_IGNORE; dp.c_stair = c_stair_desert_stone; dp.diagonal_dirs = true; dp.holesize = v3s16(2, 3, 2); dp.room_size_min = v3s16(6, 9, 6); dp.room_size_max = v3s16(10, 11, 10); dp.room_size_large_min = v3s16(10, 13, 10); dp.room_size_large_max = v3s16(18, 21, 18); dp.notifytype = GENNOTIFY_TEMPLE; } else { dp.c_wall = c_cobble; dp.c_alt_wall = c_mossycobble; dp.c_stair = c_stair_cobble; dp.diagonal_dirs = false; dp.holesize = v3s16(1, 2, 1); dp.room_size_min = v3s16(4, 4, 4); dp.room_size_max = v3s16(8, 6, 8); dp.room_size_large_min = v3s16(8, 8, 8); dp.room_size_large_max = v3s16(16, 16, 16); dp.notifytype = GENNOTIFY_DUNGEON; } DungeonGen dgen(ndef, &gennotify, &dp); dgen.generate(vm, blockseed, full_node_min, full_node_max); } // Add top and bottom side of water to transforming_liquid queue updateLiquid(&data->transforming_liquid, full_node_min, full_node_max); // Add surface nodes growGrass(); // Generate some trees, and add grass, if a jungle if (spflags & MGV6_TREES) placeTreesAndJungleGrass(); // Generate the registered decorations if (flags & MG_DECORATIONS) m_emerge->decomgr->placeAllDecos(this, blockseed, node_min, node_max); // Generate the registered ores m_emerge->oremgr->placeAllOres(this, blockseed, node_min, node_max); // Calculate lighting if (flags & MG_LIGHT) calcLighting(node_min - v3s16(1, 1, 1) * MAP_BLOCKSIZE, node_max + v3s16(1, 0, 1) * MAP_BLOCKSIZE, full_node_min, full_node_max); this->generating = false; } void MapgenV6::calculateNoise() { int x = node_min.X; int z = node_min.Z; int fx = full_node_min.X; int fz = full_node_min.Z; if (!(spflags & MGV6_FLAT)) { noise_terrain_base->perlinMap2D_PO(x, 0.5, z, 0.5); noise_terrain_higher->perlinMap2D_PO(x, 0.5, z, 0.5); noise_steepness->perlinMap2D_PO(x, 0.5, z, 0.5); noise_height_select->perlinMap2D_PO(x, 0.5, z, 0.5); noise_mud->perlinMap2D_PO(x, 0.5, z, 0.5); } noise_beach->perlinMap2D_PO(x, 0.2, z, 0.7); noise_biome->perlinMap2D_PO(fx, 0.6, fz, 0.2); noise_humidity->perlinMap2D_PO(fx, 0.0, fz, 0.0); // Humidity map does not need range limiting 0 to 1, // only humidity at point does } int MapgenV6::generateGround() { //TimeTaker timer1("Generating ground level"); MapNode n_air(CONTENT_AIR), n_water_source(c_water_source); MapNode n_stone(c_stone), n_desert_stone(c_desert_stone); MapNode n_ice(c_ice); int stone_surface_max_y = -MAX_MAP_GENERATION_LIMIT; u32 index = 0; for (s16 z = node_min.Z; z <= node_max.Z; z++) for (s16 x = node_min.X; x <= node_max.X; x++, index++) { // Surface height s16 surface_y = (s16)baseTerrainLevelFromMap(index); // Log it if (surface_y > stone_surface_max_y) stone_surface_max_y = surface_y; BiomeV6Type bt = getBiome(v2s16(x, z)); // Fill ground with stone const v3s16 &em = vm->m_area.getExtent(); u32 i = vm->m_area.index(x, node_min.Y, z); for (s16 y = node_min.Y; y <= node_max.Y; y++) { if (vm->m_data[i].getContent() == CONTENT_IGNORE) { if (y <= surface_y) { vm->m_data[i] = (y >= MGV6_DESERT_STONE_BASE && bt == BT_DESERT) ? n_desert_stone : n_stone; } else if (y <= water_level) { vm->m_data[i] = (y >= MGV6_ICE_BASE && bt == BT_TUNDRA) ? n_ice : n_water_source; } else { vm->m_data[i] = n_air; } } VoxelArea::add_y(em, i, 1); } } return stone_surface_max_y; } void MapgenV6::addMud() { // 15ms @cs=8 //TimeTaker timer1("add mud"); MapNode n_dirt(c_dirt), n_gravel(c_gravel); MapNode n_sand(c_sand), n_desert_sand(c_desert_sand); MapNode addnode; u32 index = 0; for (s16 z = node_min.Z; z <= node_max.Z; z++) for (s16 x = node_min.X; x <= node_max.X; x++, index++) { // Randomize mud amount s16 mud_add_amount = getMudAmount(index) / 2.0 + 0.5; // Find ground level s16 surface_y = find_stone_level(v2s16(x, z)); /////////////////optimize this! // Handle area not found if (surface_y == vm->m_area.MinEdge.Y - 1) continue; BiomeV6Type bt = getBiome(v2s16(x, z)); addnode = (bt == BT_DESERT) ? n_desert_sand : n_dirt; if (bt == BT_DESERT && surface_y + mud_add_amount <= water_level + 1) { addnode = n_sand; } else if (mud_add_amount <= 0) { mud_add_amount = 1 - mud_add_amount; addnode = n_gravel; } else if (bt != BT_DESERT && getHaveBeach(index) && surface_y + mud_add_amount <= water_level + 2) { addnode = n_sand; } if ((bt == BT_DESERT || bt == BT_TUNDRA) && surface_y > 20) mud_add_amount = MYMAX(0, mud_add_amount - (surface_y - 20) / 5); /* If topmost node is grass, change it to mud. It might be if it was // flown to there from a neighboring chunk and then converted. u32 i = vm->m_area.index(x, surface_y, z); if (vm->m_data[i].getContent() == c_dirt_with_grass) vm->m_data[i] = n_dirt;*/ // Add mud on ground s16 mudcount = 0; const v3s16 &em = vm->m_area.getExtent(); s16 y_start = surface_y + 1; u32 i = vm->m_area.index(x, y_start, z); for (s16 y = y_start; y <= node_max.Y; y++) { if (mudcount >= mud_add_amount) break; vm->m_data[i] = addnode; mudcount++; VoxelArea::add_y(em, i, 1); } } } void MapgenV6::flowMud(s16 &mudflow_minpos, s16 &mudflow_maxpos) { // 340ms @cs=8 //TimeTaker timer1("flow mud"); // Iterate a few times for (s16 k = 0; k < 3; k++) { for (s16 z = mudflow_minpos; z <= mudflow_maxpos; z++) for (s16 x = mudflow_minpos; x <= mudflow_maxpos; x++) { // Invert coordinates every 2nd iteration if (k % 2 == 0) { x = mudflow_maxpos - (x - mudflow_minpos); z = mudflow_maxpos - (z - mudflow_minpos); } // Node position in 2d v2s16 p2d = v2s16(node_min.X, node_min.Z) + v2s16(x, z); const v3s16 &em = vm->m_area.getExtent(); u32 i = vm->m_area.index(p2d.X, node_max.Y, p2d.Y); s16 y = node_max.Y; while (y >= node_min.Y) { for (;; y--) { MapNode *n = NULL; // Find mud for (; y >= node_min.Y; y--) { n = &vm->m_data[i]; if (n->getContent() == c_dirt || n->getContent() == c_dirt_with_grass || n->getContent() == c_gravel) break; VoxelArea::add_y(em, i, -1); } // Stop if out of area //if(vmanip.m_area.contains(i) == false) if (y < node_min.Y) break; if (n->getContent() == c_dirt || n->getContent() == c_dirt_with_grass) { // Make it exactly mud n->setContent(c_dirt); // Don't flow it if the stuff under it is not mud { u32 i2 = i; VoxelArea::add_y(em, i2, -1); // Cancel if out of area if (!vm->m_area.contains(i2)) continue; MapNode *n2 = &vm->m_data[i2]; if (n2->getContent() != c_dirt && n2->getContent() != c_dirt_with_grass) continue; } } static const v3s16 dirs4[4] = { v3s16(0, 0, 1), // back v3s16(1, 0, 0), // right v3s16(0, 0, -1), // front v3s16(-1, 0, 0), // left }; // Check that upper is walkable. Cancel // dropping if upper keeps it in place. u32 i3 = i; VoxelArea::add_y(em, i3, 1); MapNode *n3 = NULL; if (vm->m_area.contains(i3)) { n3 = &vm->m_data[i3]; if (ndef->get(*n3).walkable) continue; } // Drop mud on side for (const v3s16 &dirp : dirs4) { u32 i2 = i; // Move to side VoxelArea::add_p(em, i2, dirp); // Fail if out of area if (!vm->m_area.contains(i2)) continue; // Check that side is air MapNode *n2 = &vm->m_data[i2]; if (ndef->get(*n2).walkable) continue; // Check that under side is air VoxelArea::add_y(em, i2, -1); if (!vm->m_area.contains(i2)) continue; n2 = &vm->m_data[i2]; if (ndef->get(*n2).walkable) continue; // Loop further down until not air bool dropped_to_unknown = false; do { VoxelArea::add_y(em, i2, -1); n2 = &vm->m_data[i2]; // if out of known area if (!vm->m_area.contains(i2) || n2->getContent() == CONTENT_IGNORE) { dropped_to_unknown = true; break; } } while (!ndef->get(*n2).walkable); // Loop one up so that we're in air VoxelArea::add_y(em, i2, 1); // Move mud to new place. Outside mapchunk remove // any decorations above removed or placed mud. if (!dropped_to_unknown) moveMud(i, i2, i3, p2d, em); // Done break; } } } } } } void MapgenV6::moveMud(u32 remove_index, u32 place_index, u32 above_remove_index, v2s16 pos, v3s16 em) { MapNode n_air(CONTENT_AIR); // Copy mud from old place to new place vm->m_data[place_index] = vm->m_data[remove_index]; // Set old place to be air vm->m_data[remove_index] = n_air; // Outside the mapchunk decorations may need to be removed if above removed // mud or if half-buried in placed mud. Placed mud is to the side of pos so // use 'pos.X >= node_max.X' etc. if (pos.X >= node_max.X || pos.X <= node_min.X || pos.Y >= node_max.Z || pos.Y <= node_min.Z) { // 'above remove' node is above removed mud. If it is not air, water or // 'ignore' it is a decoration that needs removing. Also search upwards // to remove a possible stacked decoration. // Check for 'ignore' because stacked decorations can penetrate into // 'ignore' nodes above the mapchunk. while (vm->m_area.contains(above_remove_index) && vm->m_data[above_remove_index].getContent() != CONTENT_AIR && vm->m_data[above_remove_index].getContent() != c_water_source && vm->m_data[above_remove_index].getContent() != CONTENT_IGNORE) { vm->m_data[above_remove_index] = n_air; VoxelArea::add_y(em, above_remove_index, 1); } // Mud placed may have partially-buried a stacked decoration, search // above and remove. VoxelArea::add_y(em, place_index, 1); while (vm->m_area.contains(place_index) && vm->m_data[place_index].getContent() != CONTENT_AIR && vm->m_data[place_index].getContent() != c_water_source && vm->m_data[place_index].getContent() != CONTENT_IGNORE) { vm->m_data[place_index] = n_air; VoxelArea::add_y(em, place_index, 1); } } } void MapgenV6::placeTreesAndJungleGrass() { //TimeTaker t("placeTrees"); if (node_max.Y < water_level) return; PseudoRandom grassrandom(blockseed + 53); content_t c_junglegrass = ndef->getId("mapgen_junglegrass"); // if we don't have junglegrass, don't place cignore... that's bad if (c_junglegrass == CONTENT_IGNORE) c_junglegrass = CONTENT_AIR; MapNode n_junglegrass(c_junglegrass); const v3s16 &em = vm->m_area.getExtent(); // Divide area into parts s16 div = 8; s16 sidelen = central_area_size.X / div; double area = sidelen * sidelen; // N.B. We must add jungle grass first, since tree leaves will // obstruct the ground, giving us a false ground level for (s16 z0 = 0; z0 < div; z0++) for (s16 x0 = 0; x0 < div; x0++) { // Center position of part of division v2s16 p2d_center( node_min.X + sidelen / 2 + sidelen * x0, node_min.Z + sidelen / 2 + sidelen * z0 ); // Minimum edge of part of division v2s16 p2d_min( node_min.X + sidelen * x0, node_min.Z + sidelen * z0 ); // Maximum edge of part of division v2s16 p2d_max( node_min.X + sidelen + sidelen * x0 - 1, node_min.Z + sidelen + sidelen * z0 - 1 ); // Get biome at center position of part of division BiomeV6Type bt = getBiome(p2d_center); // Amount of trees u32 tree_count; if (bt == BT_JUNGLE || bt == BT_TAIGA || bt == BT_NORMAL) { tree_count = area * getTreeAmount(p2d_center); if (bt == BT_JUNGLE) tree_count *= 4; } else { tree_count = 0; } // Add jungle grass if (bt == BT_JUNGLE) { float humidity = getHumidity(p2d_center); u32 grass_count = 5 * humidity * tree_count; for (u32 i = 0; i < grass_count; i++) { s16 x = grassrandom.range(p2d_min.X, p2d_max.X); s16 z = grassrandom.range(p2d_min.Y, p2d_max.Y); int mapindex = central_area_size.X * (z - node_min.Z) + (x - node_min.X); s16 y = heightmap[mapindex]; if (y < water_level) continue; u32 vi = vm->m_area.index(x, y, z); // place on dirt_with_grass, since we know it is exposed to sunlight if (vm->m_data[vi].getContent() == c_dirt_with_grass) { VoxelArea::add_y(em, vi, 1); vm->m_data[vi] = n_junglegrass; } } } // Put trees in random places on part of division for (u32 i = 0; i < tree_count; i++) { s16 x = myrand_range(p2d_min.X, p2d_max.X); s16 z = myrand_range(p2d_min.Y, p2d_max.Y); int mapindex = central_area_size.X * (z - node_min.Z) + (x - node_min.X); s16 y = heightmap[mapindex]; // Don't make a tree under water level // Don't make a tree so high that it doesn't fit if (y < water_level || y > node_max.Y - 6) continue; v3s16 p(x, y, z); // Trees grow only on mud and grass { u32 i = vm->m_area.index(p); content_t c = vm->m_data[i].getContent(); if (c != c_dirt && c != c_dirt_with_grass && c != c_dirt_with_snow) continue; } p.Y++; // Make a tree if (bt == BT_JUNGLE) { treegen::make_jungletree(*vm, p, ndef, myrand()); } else if (bt == BT_TAIGA) { treegen::make_pine_tree(*vm, p - v3s16(0, 1, 0), ndef, myrand()); } else if (bt == BT_NORMAL) { bool is_apple_tree = (myrand_range(0, 3) == 0) && getHaveAppleTree(v2s16(x, z)); treegen::make_tree(*vm, p, is_apple_tree, ndef, myrand()); } } } //printf("placeTreesAndJungleGrass: %dms\n", t.stop()); } void MapgenV6::growGrass() // Add surface nodes { MapNode n_dirt_with_grass(c_dirt_with_grass); MapNode n_dirt_with_snow(c_dirt_with_snow); MapNode n_snowblock(c_snowblock); MapNode n_snow(c_snow); const v3s16 &em = vm->m_area.getExtent(); u32 index = 0; for (s16 z = full_node_min.Z; z <= full_node_max.Z; z++) for (s16 x = full_node_min.X; x <= full_node_max.X; x++, index++) { // Find the lowest surface to which enough light ends up to make // grass grow. Basically just wait until not air and not leaves. s16 surface_y = 0; { u32 i = vm->m_area.index(x, node_max.Y, z); s16 y; // Go to ground level for (y = node_max.Y; y >= full_node_min.Y; y--) { MapNode &n = vm->m_data[i]; if (ndef->get(n).param_type != CPT_LIGHT || ndef->get(n).liquid_type != LIQUID_NONE || n.getContent() == c_ice) break; VoxelArea::add_y(em, i, -1); } surface_y = (y >= full_node_min.Y) ? y : full_node_min.Y; } BiomeV6Type bt = getBiome(index, v2s16(x, z)); u32 i = vm->m_area.index(x, surface_y, z); content_t c = vm->m_data[i].getContent(); if (surface_y >= water_level - 20) { if (bt == BT_TAIGA && c == c_dirt) { vm->m_data[i] = n_dirt_with_snow; } else if (bt == BT_TUNDRA) { if (c == c_dirt) { vm->m_data[i] = n_snowblock; VoxelArea::add_y(em, i, -1); vm->m_data[i] = n_dirt_with_snow; } else if (c == c_stone && surface_y < node_max.Y) { VoxelArea::add_y(em, i, 1); vm->m_data[i] = n_snowblock; } } else if (c == c_dirt) { vm->m_data[i] = n_dirt_with_grass; } } } } void MapgenV6::generateCaves(int max_stone_y) { float cave_amount = NoisePerlin2D(np_cave, node_min.X, node_min.Y, seed); int volume_nodes = (node_max.X - node_min.X + 1) * (node_max.Y - node_min.Y + 1) * MAP_BLOCKSIZE; cave_amount = MYMAX(0.0, cave_amount); u32 caves_count = cave_amount * volume_nodes / 50000; u32 bruises_count = 1; PseudoRandom ps(blockseed + 21343); PseudoRandom ps2(blockseed + 1032); if (ps.range(1, 6) == 1) bruises_count = ps.range(0, ps.range(0, 2)); if (getBiome(v2s16(node_min.X, node_min.Z)) == BT_DESERT) { caves_count /= 3; bruises_count /= 3; } for (u32 i = 0; i < caves_count + bruises_count; i++) { CavesV6 cave(ndef, &gennotify, water_level, c_water_source, c_lava_source); bool large_cave = (i >= caves_count); cave.makeCave(vm, node_min, node_max, &ps, &ps2, large_cave, max_stone_y, heightmap); } }
pgimeno/minetest
src/mapgen/mapgen_v6.cpp
C++
mit
33,793
/* Minetest Copyright (C) 2010-2018 celeron55, Perttu Ahola <celeron55@gmail.com> Copyright (C) 2013-2018 kwolekr, Ryan Kwolek <kwolekr@minetest.net> Copyright (C) 2014-2018 paramat 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. */ #pragma once #include "mapgen.h" #include "noise.h" #define MGV6_AVERAGE_MUD_AMOUNT 4 #define MGV6_DESERT_STONE_BASE -32 #define MGV6_ICE_BASE 0 #define MGV6_FREQ_HOT 0.4 #define MGV6_FREQ_SNOW -0.4 #define MGV6_FREQ_TAIGA 0.5 #define MGV6_FREQ_JUNGLE 0.5 //////////// Mapgen V6 flags #define MGV6_JUNGLES 0x01 #define MGV6_BIOMEBLEND 0x02 #define MGV6_MUDFLOW 0x04 #define MGV6_SNOWBIOMES 0x08 #define MGV6_FLAT 0x10 #define MGV6_TREES 0x20 extern FlagDesc flagdesc_mapgen_v6[]; enum BiomeV6Type { BT_NORMAL, BT_DESERT, BT_JUNGLE, BT_TUNDRA, BT_TAIGA, }; struct MapgenV6Params : public MapgenParams { u32 spflags = MGV6_JUNGLES | MGV6_SNOWBIOMES | MGV6_TREES | MGV6_BIOMEBLEND | MGV6_MUDFLOW; float freq_desert = 0.45f; float freq_beach = 0.15f; s16 dungeon_ymin = -31000; s16 dungeon_ymax = 31000; NoiseParams np_terrain_base; NoiseParams np_terrain_higher; NoiseParams np_steepness; NoiseParams np_height_select; NoiseParams np_mud; NoiseParams np_beach; NoiseParams np_biome; NoiseParams np_cave; NoiseParams np_humidity; NoiseParams np_trees; NoiseParams np_apple_trees; MapgenV6Params(); ~MapgenV6Params() = default; void readParams(const Settings *settings); void writeParams(Settings *settings) const; }; class MapgenV6 : public Mapgen { public: EmergeManager *m_emerge; int ystride; u32 spflags; v3s16 node_min; v3s16 node_max; v3s16 full_node_min; v3s16 full_node_max; v3s16 central_area_size; Noise *noise_terrain_base; Noise *noise_terrain_higher; Noise *noise_steepness; Noise *noise_height_select; Noise *noise_mud; Noise *noise_beach; Noise *noise_biome; Noise *noise_humidity; NoiseParams *np_cave; NoiseParams *np_humidity; NoiseParams *np_trees; NoiseParams *np_apple_trees; float freq_desert; float freq_beach; s16 dungeon_ymin; s16 dungeon_ymax; content_t c_stone; content_t c_dirt; content_t c_dirt_with_grass; content_t c_sand; content_t c_water_source; content_t c_lava_source; content_t c_gravel; content_t c_desert_stone; content_t c_desert_sand; content_t c_dirt_with_snow; content_t c_snow; content_t c_snowblock; content_t c_ice; content_t c_cobble; content_t c_mossycobble; content_t c_stair_cobble; content_t c_stair_desert_stone; MapgenV6(MapgenV6Params *params, EmergeManager *emerge); ~MapgenV6(); virtual MapgenType getType() const { return MAPGEN_V6; } void makeChunk(BlockMakeData *data); int getGroundLevelAtPoint(v2s16 p); int getSpawnLevelAtPoint(v2s16 p); float baseTerrainLevel(float terrain_base, float terrain_higher, float steepness, float height_select); virtual float baseTerrainLevelFromNoise(v2s16 p); virtual float baseTerrainLevelFromMap(v2s16 p); virtual float baseTerrainLevelFromMap(int index); s16 find_stone_level(v2s16 p2d); bool block_is_underground(u64 seed, v3s16 blockpos); s16 find_ground_level_from_noise(u64 seed, v2s16 p2d, s16 precision); float getHumidity(v2s16 p); float getTreeAmount(v2s16 p); bool getHaveAppleTree(v2s16 p); float getMudAmount(v2s16 p); virtual float getMudAmount(int index); bool getHaveBeach(v2s16 p); bool getHaveBeach(int index); BiomeV6Type getBiome(v2s16 p); BiomeV6Type getBiome(int index, v2s16 p); u32 get_blockseed(u64 seed, v3s16 p); virtual void calculateNoise(); int generateGround(); void addMud(); void flowMud(s16 &mudflow_minpos, s16 &mudflow_maxpos); void moveMud(u32 remove_index, u32 place_index, u32 above_remove_index, v2s16 pos, v3s16 em); void growGrass(); void placeTreesAndJungleGrass(); virtual void generateCaves(int max_stone_y); };
pgimeno/minetest
src/mapgen/mapgen_v6.h
C++
mit
4,486
/* Minetest Copyright (C) 2013-2018 kwolekr, Ryan Kwolek <kwolekr@minetest.net> Copyright (C) 2014-2018 paramat 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 "mapgen.h" #include <cmath> #include "voxel.h" #include "noise.h" #include "mapblock.h" #include "mapnode.h" #include "map.h" #include "content_sao.h" #include "nodedef.h" #include "voxelalgorithms.h" //#include "profiler.h" // For TimeTaker #include "settings.h" // For g_settings #include "emerge.h" #include "dungeongen.h" #include "cavegen.h" #include "mg_biome.h" #include "mg_ore.h" #include "mg_decoration.h" #include "mapgen_v7.h" FlagDesc flagdesc_mapgen_v7[] = { {"mountains", MGV7_MOUNTAINS}, {"ridges", MGV7_RIDGES}, {"floatlands", MGV7_FLOATLANDS}, {"caverns", MGV7_CAVERNS}, {NULL, 0} }; //////////////////////////////////////////////////////////////////////////////// MapgenV7::MapgenV7(MapgenV7Params *params, EmergeManager *emerge) : MapgenBasic(MAPGEN_V7, params, emerge) { spflags = params->spflags; mount_zero_level = params->mount_zero_level; float_mount_density = params->float_mount_density; float_mount_exponent = params->float_mount_exponent; floatland_level = params->floatland_level; shadow_limit = params->shadow_limit; cave_width = params->cave_width; large_cave_depth = params->large_cave_depth; lava_depth = params->lava_depth; cavern_limit = params->cavern_limit; cavern_taper = params->cavern_taper; cavern_threshold = params->cavern_threshold; dungeon_ymin = params->dungeon_ymin; dungeon_ymax = params->dungeon_ymax; // This is to avoid a divide-by-zero. // Parameter will be saved to map_meta.txt in limited form. params->float_mount_height = std::fmax(params->float_mount_height, 1.0f); float_mount_height = params->float_mount_height; // 2D noise noise_terrain_base = new Noise(&params->np_terrain_base, seed, csize.X, csize.Z); noise_terrain_alt = new Noise(&params->np_terrain_alt, seed, csize.X, csize.Z); noise_terrain_persist = new Noise(&params->np_terrain_persist, seed, csize.X, csize.Z); noise_height_select = new Noise(&params->np_height_select, seed, csize.X, csize.Z); noise_filler_depth = new Noise(&params->np_filler_depth, seed, csize.X, csize.Z); if (spflags & MGV7_MOUNTAINS) noise_mount_height = new Noise(&params->np_mount_height, seed, csize.X, csize.Z); if (spflags & MGV7_FLOATLANDS) { noise_floatland_base = new Noise(&params->np_floatland_base, seed, csize.X, csize.Z); noise_float_base_height = new Noise(&params->np_float_base_height, seed, csize.X, csize.Z); } if (spflags & MGV7_RIDGES) { noise_ridge_uwater = new Noise(&params->np_ridge_uwater, seed, csize.X, csize.Z); // 3D noise, 1 up, 1 down overgeneration noise_ridge = new Noise(&params->np_ridge, seed, csize.X, csize.Y + 2, csize.Z); } // 3D noise, 1 up, 1 down overgeneration if ((spflags & MGV7_MOUNTAINS) || (spflags & MGV7_FLOATLANDS)) noise_mountain = new Noise(&params->np_mountain, seed, csize.X, csize.Y + 2, csize.Z); // 3D noise, 1 down overgeneration MapgenBasic::np_cave1 = params->np_cave1; MapgenBasic::np_cave2 = params->np_cave2; MapgenBasic::np_cavern = params->np_cavern; } MapgenV7::~MapgenV7() { delete noise_terrain_base; delete noise_terrain_alt; delete noise_terrain_persist; delete noise_height_select; delete noise_filler_depth; if (spflags & MGV7_MOUNTAINS) delete noise_mount_height; if (spflags & MGV7_FLOATLANDS) { delete noise_floatland_base; delete noise_float_base_height; } if (spflags & MGV7_RIDGES) { delete noise_ridge_uwater; delete noise_ridge; } if ((spflags & MGV7_MOUNTAINS) || (spflags & MGV7_FLOATLANDS)) delete noise_mountain; } MapgenV7Params::MapgenV7Params(): np_terrain_base (4.0, 70.0, v3f(600, 600, 600), 82341, 5, 0.6, 2.0), np_terrain_alt (4.0, 25.0, v3f(600, 600, 600), 5934, 5, 0.6, 2.0), np_terrain_persist (0.6, 0.1, v3f(2000, 2000, 2000), 539, 3, 0.6, 2.0), np_height_select (-8.0, 16.0, v3f(500, 500, 500), 4213, 6, 0.7, 2.0), np_filler_depth (0.0, 1.2, v3f(150, 150, 150), 261, 3, 0.7, 2.0), np_mount_height (256.0, 112.0, v3f(1000, 1000, 1000), 72449, 3, 0.6, 2.0), np_ridge_uwater (0.0, 1.0, v3f(1000, 1000, 1000), 85039, 5, 0.6, 2.0), np_floatland_base (-0.6, 1.5, v3f(600, 600, 600), 114, 5, 0.6, 2.0), np_float_base_height (48.0, 24.0, v3f(300, 300, 300), 907, 4, 0.7, 2.0), np_mountain (-0.6, 1.0, v3f(250, 350, 250), 5333, 5, 0.63, 2.0), np_ridge (0.0, 1.0, v3f(100, 100, 100), 6467, 4, 0.75, 2.0), np_cavern (0.0, 1.0, v3f(384, 128, 384), 723, 5, 0.63, 2.0), np_cave1 (0.0, 12.0, v3f(61, 61, 61), 52534, 3, 0.5, 2.0), np_cave2 (0.0, 12.0, v3f(67, 67, 67), 10325, 3, 0.5, 2.0) { } void MapgenV7Params::readParams(const Settings *settings) { settings->getFlagStrNoEx("mgv7_spflags", spflags, flagdesc_mapgen_v7); settings->getS16NoEx("mgv7_mount_zero_level", mount_zero_level); settings->getFloatNoEx("mgv7_cave_width", cave_width); settings->getS16NoEx("mgv7_large_cave_depth", large_cave_depth); settings->getS16NoEx("mgv7_lava_depth", lava_depth); settings->getFloatNoEx("mgv7_float_mount_density", float_mount_density); settings->getFloatNoEx("mgv7_float_mount_height", float_mount_height); settings->getFloatNoEx("mgv7_float_mount_exponent", float_mount_exponent); settings->getS16NoEx("mgv7_floatland_level", floatland_level); settings->getS16NoEx("mgv7_shadow_limit", shadow_limit); settings->getS16NoEx("mgv7_cavern_limit", cavern_limit); settings->getS16NoEx("mgv7_cavern_taper", cavern_taper); settings->getFloatNoEx("mgv7_cavern_threshold", cavern_threshold); settings->getS16NoEx("mgv7_dungeon_ymin", dungeon_ymin); settings->getS16NoEx("mgv7_dungeon_ymax", dungeon_ymax); settings->getNoiseParams("mgv7_np_terrain_base", np_terrain_base); settings->getNoiseParams("mgv7_np_terrain_alt", np_terrain_alt); settings->getNoiseParams("mgv7_np_terrain_persist", np_terrain_persist); settings->getNoiseParams("mgv7_np_height_select", np_height_select); settings->getNoiseParams("mgv7_np_filler_depth", np_filler_depth); settings->getNoiseParams("mgv7_np_mount_height", np_mount_height); settings->getNoiseParams("mgv7_np_ridge_uwater", np_ridge_uwater); settings->getNoiseParams("mgv7_np_floatland_base", np_floatland_base); settings->getNoiseParams("mgv7_np_float_base_height", np_float_base_height); settings->getNoiseParams("mgv7_np_mountain", np_mountain); settings->getNoiseParams("mgv7_np_ridge", np_ridge); settings->getNoiseParams("mgv7_np_cavern", np_cavern); settings->getNoiseParams("mgv7_np_cave1", np_cave1); settings->getNoiseParams("mgv7_np_cave2", np_cave2); } void MapgenV7Params::writeParams(Settings *settings) const { settings->setFlagStr("mgv7_spflags", spflags, flagdesc_mapgen_v7, U32_MAX); settings->setS16("mgv7_mount_zero_level", mount_zero_level); settings->setFloat("mgv7_cave_width", cave_width); settings->setS16("mgv7_large_cave_depth", large_cave_depth); settings->setS16("mgv7_lava_depth", lava_depth); settings->setFloat("mgv7_float_mount_density", float_mount_density); settings->setFloat("mgv7_float_mount_height", float_mount_height); settings->setFloat("mgv7_float_mount_exponent", float_mount_exponent); settings->setS16("mgv7_floatland_level", floatland_level); settings->setS16("mgv7_shadow_limit", shadow_limit); settings->setS16("mgv7_cavern_limit", cavern_limit); settings->setS16("mgv7_cavern_taper", cavern_taper); settings->setFloat("mgv7_cavern_threshold", cavern_threshold); settings->setS16("mgv7_dungeon_ymin", dungeon_ymin); settings->setS16("mgv7_dungeon_ymax", dungeon_ymax); settings->setNoiseParams("mgv7_np_terrain_base", np_terrain_base); settings->setNoiseParams("mgv7_np_terrain_alt", np_terrain_alt); settings->setNoiseParams("mgv7_np_terrain_persist", np_terrain_persist); settings->setNoiseParams("mgv7_np_height_select", np_height_select); settings->setNoiseParams("mgv7_np_filler_depth", np_filler_depth); settings->setNoiseParams("mgv7_np_mount_height", np_mount_height); settings->setNoiseParams("mgv7_np_ridge_uwater", np_ridge_uwater); settings->setNoiseParams("mgv7_np_floatland_base", np_floatland_base); settings->setNoiseParams("mgv7_np_float_base_height", np_float_base_height); settings->setNoiseParams("mgv7_np_mountain", np_mountain); settings->setNoiseParams("mgv7_np_ridge", np_ridge); settings->setNoiseParams("mgv7_np_cavern", np_cavern); settings->setNoiseParams("mgv7_np_cave1", np_cave1); settings->setNoiseParams("mgv7_np_cave2", np_cave2); } //////////////////////////////////////////////////////////////////////////////// int MapgenV7::getSpawnLevelAtPoint(v2s16 p) { // If rivers are enabled, first check if in a river if (spflags & MGV7_RIDGES) { float width = 0.2f; float uwatern = NoisePerlin2D(&noise_ridge_uwater->np, p.X, p.Y, seed) * 2.0f; if (std::fabs(uwatern) <= width) return MAX_MAP_GENERATION_LIMIT; // Unsuitable spawn point } // Terrain noise 'offset' is the average level of that terrain. // At least 50% of terrain will be below the higher of base and alt terrain // 'offset's. // Raising the maximum spawn level above 'water_level + 16' is necessary // for when terrain 'offset's are set much higher than water_level. s16 max_spawn_y = std::fmax(std::fmax(noise_terrain_alt->np.offset, noise_terrain_base->np.offset), water_level + 16); // Base terrain calculation s16 y = baseTerrainLevelAtPoint(p.X, p.Y); // If mountains are disabled, terrain level is base terrain level. // Avoids mid-air spawn where mountain terrain would have been. if (!(spflags & MGV7_MOUNTAINS)) { if (y < water_level || y > max_spawn_y) return MAX_MAP_GENERATION_LIMIT; // Unsuitable spawn point // y + 2 because y is surface level and due to biome 'dust' return y + 2; } // Search upwards for first node without mountain terrain int iters = 256; while (iters > 0 && y <= max_spawn_y) { if (!getMountainTerrainAtPoint(p.X, y + 1, p.Y)) { if (y <= water_level || y > max_spawn_y) return MAX_MAP_GENERATION_LIMIT; // Unsuitable spawn point // y + 1 due to biome 'dust' return y + 1; } y++; iters--; } // Unsuitable spawn point return MAX_MAP_GENERATION_LIMIT; } void MapgenV7::makeChunk(BlockMakeData *data) { // Pre-conditions assert(data->vmanip); assert(data->nodedef); assert(data->blockpos_requested.X >= data->blockpos_min.X && data->blockpos_requested.Y >= data->blockpos_min.Y && data->blockpos_requested.Z >= data->blockpos_min.Z); assert(data->blockpos_requested.X <= data->blockpos_max.X && data->blockpos_requested.Y <= data->blockpos_max.Y && data->blockpos_requested.Z <= data->blockpos_max.Z); //TimeTaker t("makeChunk"); this->generating = true; this->vm = data->vmanip; this->ndef = data->nodedef; v3s16 blockpos_min = data->blockpos_min; v3s16 blockpos_max = data->blockpos_max; node_min = blockpos_min * MAP_BLOCKSIZE; node_max = (blockpos_max + v3s16(1, 1, 1)) * MAP_BLOCKSIZE - v3s16(1, 1, 1); full_node_min = (blockpos_min - 1) * MAP_BLOCKSIZE; full_node_max = (blockpos_max + 2) * MAP_BLOCKSIZE - v3s16(1, 1, 1); blockseed = getBlockSeed2(full_node_min, seed); // Generate base and mountain terrain s16 stone_surface_max_y = generateTerrain(); // Generate rivers if (spflags & MGV7_RIDGES) generateRidgeTerrain(); // Create heightmap updateHeightmap(node_min, node_max); // Init biome generator, place biome-specific nodes, and build biomemap if (flags & MG_BIOMES) { biomegen->calcBiomeNoise(node_min); generateBiomes(); } // Generate tunnels, caverns and large randomwalk caves if (flags & MG_CAVES) { // Generate tunnels first as caverns confuse them generateCavesNoiseIntersection(stone_surface_max_y); // Generate caverns bool near_cavern = false; if (spflags & MGV7_CAVERNS) near_cavern = generateCavernsNoise(stone_surface_max_y); // Generate large randomwalk caves if (near_cavern) // Disable large randomwalk caves in this mapchunk by setting // 'large cave depth' to world base. Avoids excessive liquid in // large caverns and floating blobs of overgenerated liquid. generateCavesRandomWalk(stone_surface_max_y, -MAX_MAP_GENERATION_LIMIT); else generateCavesRandomWalk(stone_surface_max_y, large_cave_depth); } // Generate the registered ores m_emerge->oremgr->placeAllOres(this, blockseed, node_min, node_max); // Generate dungeons if ((flags & MG_DUNGEONS) && full_node_min.Y >= dungeon_ymin && full_node_max.Y <= dungeon_ymax) generateDungeons(stone_surface_max_y); // Generate the registered decorations if (flags & MG_DECORATIONS) m_emerge->decomgr->placeAllDecos(this, blockseed, node_min, node_max); // Sprinkle some dust on top after everything else was generated if (flags & MG_BIOMES) dustTopNodes(); // Update liquids updateLiquid(&data->transforming_liquid, full_node_min, full_node_max); // Calculate lighting. // Limit floatland shadow. bool propagate_shadow = !((spflags & MGV7_FLOATLANDS) && node_min.Y <= shadow_limit && node_max.Y >= shadow_limit); if (flags & MG_LIGHT) calcLighting(node_min - v3s16(0, 1, 0), node_max + v3s16(0, 1, 0), full_node_min, full_node_max, propagate_shadow); this->generating = false; //printf("makeChunk: %lums\n", t.stop()); } //////////////////////////////////////////////////////////////////////////////// float MapgenV7::baseTerrainLevelAtPoint(s16 x, s16 z) { float hselect = NoisePerlin2D(&noise_height_select->np, x, z, seed); hselect = rangelim(hselect, 0.0f, 1.0f); float persist = NoisePerlin2D(&noise_terrain_persist->np, x, z, seed); noise_terrain_base->np.persist = persist; float height_base = NoisePerlin2D(&noise_terrain_base->np, x, z, seed); noise_terrain_alt->np.persist = persist; float height_alt = NoisePerlin2D(&noise_terrain_alt->np, x, z, seed); if (height_alt > height_base) return height_alt; return (height_base * hselect) + (height_alt * (1.0f - hselect)); } float MapgenV7::baseTerrainLevelFromMap(int index) { float hselect = rangelim(noise_height_select->result[index], 0.0f, 1.0f); float height_base = noise_terrain_base->result[index]; float height_alt = noise_terrain_alt->result[index]; if (height_alt > height_base) return height_alt; return (height_base * hselect) + (height_alt * (1.0f - hselect)); } bool MapgenV7::getMountainTerrainAtPoint(s16 x, s16 y, s16 z) { float mnt_h_n = std::fmax(NoisePerlin2D(&noise_mount_height->np, x, z, seed), 1.0f); float density_gradient = -((float)(y - mount_zero_level) / mnt_h_n); float mnt_n = NoisePerlin3D(&noise_mountain->np, x, y, z, seed); return mnt_n + density_gradient >= 0.0f; } bool MapgenV7::getMountainTerrainFromMap(int idx_xyz, int idx_xz, s16 y) { float mounthn = std::fmax(noise_mount_height->result[idx_xz], 1.0f); float density_gradient = -((float)(y - mount_zero_level) / mounthn); float mountn = noise_mountain->result[idx_xyz]; return mountn + density_gradient >= 0.0f; } bool MapgenV7::getFloatlandMountainFromMap(int idx_xyz, int idx_xz, s16 y) { // Make rim 2 nodes thick to match floatland base terrain float density_gradient = (y >= floatland_level) ? -std::pow((float)(y - floatland_level) / float_mount_height, float_mount_exponent) : -std::pow((float)(floatland_level - 1 - y) / float_mount_height, float_mount_exponent); float floatn = noise_mountain->result[idx_xyz] + float_mount_density; return floatn + density_gradient >= 0.0f; } void MapgenV7::floatBaseExtentFromMap(s16 *float_base_min, s16 *float_base_max, int idx_xz) { // '+1' to avoid a layer of stone at y = MAX_MAP_GENERATION_LIMIT s16 base_min = MAX_MAP_GENERATION_LIMIT + 1; s16 base_max = MAX_MAP_GENERATION_LIMIT; float n_base = noise_floatland_base->result[idx_xz]; if (n_base > 0.0f) { float n_base_height = std::fmax(noise_float_base_height->result[idx_xz], 1.0f); float amp = n_base * n_base_height; float ridge = n_base_height / 3.0f; base_min = floatland_level - amp / 1.5f; if (amp > ridge * 2.0f) { // Lake bed base_max = floatland_level - (amp - ridge * 2.0f) / 2.0f; } else { // Hills and ridges float diff = std::fabs(amp - ridge) / ridge; // Smooth ridges using the 'smoothstep function' float smooth_diff = diff * diff * (3.0f - 2.0f * diff); base_max = floatland_level + ridge - smooth_diff * ridge; } } *float_base_min = base_min; *float_base_max = base_max; } int MapgenV7::generateTerrain() { MapNode n_air(CONTENT_AIR); MapNode n_stone(c_stone); MapNode n_water(c_water_source); //// Calculate noise for terrain generation noise_terrain_persist->perlinMap2D(node_min.X, node_min.Z); float *persistmap = noise_terrain_persist->result; noise_terrain_base->perlinMap2D(node_min.X, node_min.Z, persistmap); noise_terrain_alt->perlinMap2D(node_min.X, node_min.Z, persistmap); noise_height_select->perlinMap2D(node_min.X, node_min.Z); if ((spflags & MGV7_MOUNTAINS) || (spflags & MGV7_FLOATLANDS)) { noise_mountain->perlinMap3D(node_min.X, node_min.Y - 1, node_min.Z); } if (spflags & MGV7_MOUNTAINS) { noise_mount_height->perlinMap2D(node_min.X, node_min.Z); } if (spflags & MGV7_FLOATLANDS) { noise_floatland_base->perlinMap2D(node_min.X, node_min.Z); noise_float_base_height->perlinMap2D(node_min.X, node_min.Z); } //// Place nodes const v3s16 &em = vm->m_area.getExtent(); s16 stone_surface_max_y = -MAX_MAP_GENERATION_LIMIT; u32 index2d = 0; for (s16 z = node_min.Z; z <= node_max.Z; z++) for (s16 x = node_min.X; x <= node_max.X; x++, index2d++) { s16 surface_y = baseTerrainLevelFromMap(index2d); if (surface_y > stone_surface_max_y) stone_surface_max_y = surface_y; // Get extent of floatland base terrain // '+1' to avoid a layer of stone at y = MAX_MAP_GENERATION_LIMIT s16 float_base_min = MAX_MAP_GENERATION_LIMIT + 1; s16 float_base_max = MAX_MAP_GENERATION_LIMIT; if (spflags & MGV7_FLOATLANDS) floatBaseExtentFromMap(&float_base_min, &float_base_max, index2d); u32 vi = vm->m_area.index(x, node_min.Y - 1, z); u32 index3d = (z - node_min.Z) * zstride_1u1d + (x - node_min.X); for (s16 y = node_min.Y - 1; y <= node_max.Y + 1; y++, index3d += ystride, VoxelArea::add_y(em, vi, 1)) { if (vm->m_data[vi].getContent() != CONTENT_IGNORE) continue; if (y <= surface_y) { vm->m_data[vi] = n_stone; // Base terrain } else if ((spflags & MGV7_MOUNTAINS) && getMountainTerrainFromMap(index3d, index2d, y)) { vm->m_data[vi] = n_stone; // Mountain terrain if (y > stone_surface_max_y) stone_surface_max_y = y; } else if ((spflags & MGV7_FLOATLANDS) && ((y >= float_base_min && y <= float_base_max) || getFloatlandMountainFromMap(index3d, index2d, y))) { vm->m_data[vi] = n_stone; // Floatland terrain stone_surface_max_y = node_max.Y; } else if (y <= water_level) { vm->m_data[vi] = n_water; // Ground level water } else if ((spflags & MGV7_FLOATLANDS) && (y >= float_base_max && y <= floatland_level)) { vm->m_data[vi] = n_water; // Floatland water } else { vm->m_data[vi] = n_air; } } } return stone_surface_max_y; } void MapgenV7::generateRidgeTerrain() { if (node_max.Y < water_level - 16 || ((spflags & MGV7_FLOATLANDS) && node_max.Y > shadow_limit)) return; noise_ridge->perlinMap3D(node_min.X, node_min.Y - 1, node_min.Z); noise_ridge_uwater->perlinMap2D(node_min.X, node_min.Z); MapNode n_water(c_water_source); MapNode n_air(CONTENT_AIR); u32 index3d = 0; float width = 0.2f; for (s16 z = node_min.Z; z <= node_max.Z; z++) for (s16 y = node_min.Y - 1; y <= node_max.Y + 1; y++) { u32 vi = vm->m_area.index(node_min.X, y, z); for (s16 x = node_min.X; x <= node_max.X; x++, index3d++, vi++) { u32 index2d = (z - node_min.Z) * csize.X + (x - node_min.X); float uwatern = noise_ridge_uwater->result[index2d] * 2.0f; if (std::fabs(uwatern) > width) continue; // Optimises, but also avoids removing nodes placed by mods in // 'on-generated', when generating outside mapchunk. content_t c = vm->m_data[vi].getContent(); if (c != c_stone) continue; float altitude = y - water_level; float height_mod = (altitude + 17.0f) / 2.5f; float width_mod = width - std::fabs(uwatern); float nridge = noise_ridge->result[index3d] * std::fmax(altitude, 0.0f) / 7.0f; if (nridge + width_mod * height_mod < 0.6f) continue; vm->m_data[vi] = (y > water_level) ? n_air : n_water; } } }
pgimeno/minetest
src/mapgen/mapgen_v7.cpp
C++
mit
21,853
/* Minetest Copyright (C) 2013-2018 kwolekr, Ryan Kwolek <kwolekr@minetest.net> Copyright (C) 2014-2018 paramat 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. */ #pragma once #include "mapgen.h" ///////////// Mapgen V7 flags #define MGV7_MOUNTAINS 0x01 #define MGV7_RIDGES 0x02 #define MGV7_FLOATLANDS 0x04 #define MGV7_CAVERNS 0x08 #define MGV7_BIOMEREPEAT 0x10 // Now unused class BiomeManager; extern FlagDesc flagdesc_mapgen_v7[]; struct MapgenV7Params : public MapgenParams { u32 spflags = MGV7_MOUNTAINS | MGV7_RIDGES | MGV7_CAVERNS; s16 mount_zero_level = 0; float float_mount_density = 0.6f; float float_mount_height = 128.0f; float float_mount_exponent = 0.75f; s16 floatland_level = 1280; s16 shadow_limit = 1024; float cave_width = 0.09f; s16 large_cave_depth = -33; s16 lava_depth = -256; s16 cavern_limit = -256; s16 cavern_taper = 256; float cavern_threshold = 0.7f; s16 dungeon_ymin = -31000; s16 dungeon_ymax = 31000; NoiseParams np_terrain_base; NoiseParams np_terrain_alt; NoiseParams np_terrain_persist; NoiseParams np_height_select; NoiseParams np_filler_depth; NoiseParams np_mount_height; NoiseParams np_ridge_uwater; NoiseParams np_floatland_base; NoiseParams np_float_base_height; NoiseParams np_mountain; NoiseParams np_ridge; NoiseParams np_cavern; NoiseParams np_cave1; NoiseParams np_cave2; MapgenV7Params(); ~MapgenV7Params() = default; void readParams(const Settings *settings); void writeParams(Settings *settings) const; }; class MapgenV7 : public MapgenBasic { public: MapgenV7(MapgenV7Params *params, EmergeManager *emerge); ~MapgenV7(); virtual MapgenType getType() const { return MAPGEN_V7; } virtual void makeChunk(BlockMakeData *data); int getSpawnLevelAtPoint(v2s16 p); float baseTerrainLevelAtPoint(s16 x, s16 z); float baseTerrainLevelFromMap(int index); bool getMountainTerrainAtPoint(s16 x, s16 y, s16 z); bool getMountainTerrainFromMap(int idx_xyz, int idx_xz, s16 y); bool getFloatlandMountainFromMap(int idx_xyz, int idx_xz, s16 y); void floatBaseExtentFromMap(s16 *float_base_min, s16 *float_base_max, int idx_xz); int generateTerrain(); void generateRidgeTerrain(); private: s16 mount_zero_level; float float_mount_density; float float_mount_height; float float_mount_exponent; s16 floatland_level; s16 shadow_limit; s16 large_cave_depth; s16 dungeon_ymin; s16 dungeon_ymax; Noise *noise_terrain_base; Noise *noise_terrain_alt; Noise *noise_terrain_persist; Noise *noise_height_select; Noise *noise_mount_height; Noise *noise_ridge_uwater; Noise *noise_floatland_base; Noise *noise_float_base_height; Noise *noise_mountain; Noise *noise_ridge; };
pgimeno/minetest
src/mapgen/mapgen_v7.h
C++
mit
3,349
/* Minetest Copyright (C) 2016-2019 Duane Robertson <duane@duanerobertson.com> Copyright (C) 2016-2019 paramat Based on Valleys Mapgen by Gael de Sailly (https://forum.minetest.net/viewtopic.php?f=9&t=11430) and mapgen_v7, mapgen_flat by kwolekr and paramat. Licensing changed by permission of Gael de Sailly. 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 "mapgen.h" #include "voxel.h" #include "noise.h" #include "mapblock.h" #include "mapnode.h" #include "map.h" #include "nodedef.h" #include "voxelalgorithms.h" //#include "profiler.h" // For TimeTaker #include "settings.h" // For g_settings #include "emerge.h" #include "dungeongen.h" #include "mg_biome.h" #include "mg_ore.h" #include "mg_decoration.h" #include "mapgen_valleys.h" #include "cavegen.h" #include <cmath> FlagDesc flagdesc_mapgen_valleys[] = { {"altitude_chill", MGVALLEYS_ALT_CHILL}, {"humid_rivers", MGVALLEYS_HUMID_RIVERS}, {"vary_river_depth", MGVALLEYS_VARY_RIVER_DEPTH}, {"altitude_dry", MGVALLEYS_ALT_DRY}, {NULL, 0} }; MapgenValleys::MapgenValleys(MapgenValleysParams *params, EmergeManager *emerge) : MapgenBasic(MAPGEN_VALLEYS, params, emerge) { // NOTE: MapgenValleys has a hard dependency on BiomeGenOriginal m_bgen = (BiomeGenOriginal *)biomegen; spflags = params->spflags; altitude_chill = params->altitude_chill; river_depth_bed = params->river_depth + 1.0f; river_size_factor = params->river_size / 100.0f; cave_width = params->cave_width; large_cave_depth = params->large_cave_depth; lava_depth = params->lava_depth; cavern_limit = params->cavern_limit; cavern_taper = params->cavern_taper; cavern_threshold = params->cavern_threshold; dungeon_ymin = params->dungeon_ymin; dungeon_ymax = params->dungeon_ymax; //// 2D Terrain noise noise_filler_depth = new Noise(&params->np_filler_depth, seed, csize.X, csize.Z); noise_inter_valley_slope = new Noise(&params->np_inter_valley_slope, seed, csize.X, csize.Z); noise_rivers = new Noise(&params->np_rivers, seed, csize.X, csize.Z); noise_terrain_height = new Noise(&params->np_terrain_height, seed, csize.X, csize.Z); noise_valley_depth = new Noise(&params->np_valley_depth, seed, csize.X, csize.Z); noise_valley_profile = new Noise(&params->np_valley_profile, seed, csize.X, csize.Z); //// 3D Terrain noise // 1-up 1-down overgeneration noise_inter_valley_fill = new Noise(&params->np_inter_valley_fill, seed, csize.X, csize.Y + 2, csize.Z); // 1-down overgeneraion MapgenBasic::np_cave1 = params->np_cave1; MapgenBasic::np_cave2 = params->np_cave2; MapgenBasic::np_cavern = params->np_cavern; } MapgenValleys::~MapgenValleys() { delete noise_filler_depth; delete noise_inter_valley_fill; delete noise_inter_valley_slope; delete noise_rivers; delete noise_terrain_height; delete noise_valley_depth; delete noise_valley_profile; } MapgenValleysParams::MapgenValleysParams(): np_filler_depth (0.0, 1.2, v3f(256, 256, 256), 1605, 3, 0.5, 2.0), np_inter_valley_fill (0.0, 1.0, v3f(256, 512, 256), 1993, 6, 0.8, 2.0), np_inter_valley_slope (0.5, 0.5, v3f(128, 128, 128), 746, 1, 1.0, 2.0), np_rivers (0.0, 1.0, v3f(256, 256, 256), -6050, 5, 0.6, 2.0), np_terrain_height (-10.0, 50.0, v3f(1024, 1024, 1024), 5202, 6, 0.4, 2.0), np_valley_depth (5.0, 4.0, v3f(512, 512, 512), -1914, 1, 1.0, 2.0), np_valley_profile (0.6, 0.50, v3f(512, 512, 512), 777, 1, 1.0, 2.0), np_cave1 (0.0, 12.0, v3f(61, 61, 61), 52534, 3, 0.5, 2.0), np_cave2 (0.0, 12.0, v3f(67, 67, 67), 10325, 3, 0.5, 2.0), np_cavern (0.0, 1.0, v3f(768, 256, 768), 59033, 6, 0.63, 2.0) { } void MapgenValleysParams::readParams(const Settings *settings) { settings->getFlagStrNoEx("mgvalleys_spflags", spflags, flagdesc_mapgen_valleys); settings->getU16NoEx("mgvalleys_altitude_chill", altitude_chill); settings->getS16NoEx("mgvalleys_large_cave_depth", large_cave_depth); settings->getS16NoEx("mgvalleys_lava_depth", lava_depth); settings->getU16NoEx("mgvalleys_river_depth", river_depth); settings->getU16NoEx("mgvalleys_river_size", river_size); settings->getFloatNoEx("mgvalleys_cave_width", cave_width); settings->getS16NoEx("mgvalleys_cavern_limit", cavern_limit); settings->getS16NoEx("mgvalleys_cavern_taper", cavern_taper); settings->getFloatNoEx("mgvalleys_cavern_threshold", cavern_threshold); settings->getS16NoEx("mgvalleys_dungeon_ymin", dungeon_ymin); settings->getS16NoEx("mgvalleys_dungeon_ymax", dungeon_ymax); settings->getNoiseParams("mgvalleys_np_filler_depth", np_filler_depth); settings->getNoiseParams("mgvalleys_np_inter_valley_fill", np_inter_valley_fill); settings->getNoiseParams("mgvalleys_np_inter_valley_slope", np_inter_valley_slope); settings->getNoiseParams("mgvalleys_np_rivers", np_rivers); settings->getNoiseParams("mgvalleys_np_terrain_height", np_terrain_height); settings->getNoiseParams("mgvalleys_np_valley_depth", np_valley_depth); settings->getNoiseParams("mgvalleys_np_valley_profile", np_valley_profile); settings->getNoiseParams("mgvalleys_np_cave1", np_cave1); settings->getNoiseParams("mgvalleys_np_cave2", np_cave2); settings->getNoiseParams("mgvalleys_np_cavern", np_cavern); } void MapgenValleysParams::writeParams(Settings *settings) const { settings->setFlagStr("mgvalleys_spflags", spflags, flagdesc_mapgen_valleys, U32_MAX); settings->setU16("mgvalleys_altitude_chill", altitude_chill); settings->setS16("mgvalleys_large_cave_depth", large_cave_depth); settings->setS16("mgvalleys_lava_depth", lava_depth); settings->setU16("mgvalleys_river_depth", river_depth); settings->setU16("mgvalleys_river_size", river_size); settings->setFloat("mgvalleys_cave_width", cave_width); settings->setS16("mgvalleys_cavern_limit", cavern_limit); settings->setS16("mgvalleys_cavern_taper", cavern_taper); settings->setFloat("mgvalleys_cavern_threshold", cavern_threshold); settings->setS16("mgvalleys_dungeon_ymin", dungeon_ymin); settings->setS16("mgvalleys_dungeon_ymax", dungeon_ymax); settings->setNoiseParams("mgvalleys_np_filler_depth", np_filler_depth); settings->setNoiseParams("mgvalleys_np_inter_valley_fill", np_inter_valley_fill); settings->setNoiseParams("mgvalleys_np_inter_valley_slope", np_inter_valley_slope); settings->setNoiseParams("mgvalleys_np_rivers", np_rivers); settings->setNoiseParams("mgvalleys_np_terrain_height", np_terrain_height); settings->setNoiseParams("mgvalleys_np_valley_depth", np_valley_depth); settings->setNoiseParams("mgvalleys_np_valley_profile", np_valley_profile); settings->setNoiseParams("mgvalleys_np_cave1", np_cave1); settings->setNoiseParams("mgvalleys_np_cave2", np_cave2); settings->setNoiseParams("mgvalleys_np_cavern", np_cavern); } void MapgenValleys::makeChunk(BlockMakeData *data) { // Pre-conditions assert(data->vmanip); assert(data->nodedef); assert(data->blockpos_requested.X >= data->blockpos_min.X && data->blockpos_requested.Y >= data->blockpos_min.Y && data->blockpos_requested.Z >= data->blockpos_min.Z); assert(data->blockpos_requested.X <= data->blockpos_max.X && data->blockpos_requested.Y <= data->blockpos_max.Y && data->blockpos_requested.Z <= data->blockpos_max.Z); //TimeTaker t("makeChunk"); this->generating = true; this->vm = data->vmanip; this->ndef = data->nodedef; v3s16 blockpos_min = data->blockpos_min; v3s16 blockpos_max = data->blockpos_max; node_min = blockpos_min * MAP_BLOCKSIZE; node_max = (blockpos_max + v3s16(1, 1, 1)) * MAP_BLOCKSIZE - v3s16(1, 1, 1); full_node_min = (blockpos_min - 1) * MAP_BLOCKSIZE; full_node_max = (blockpos_max + 2) * MAP_BLOCKSIZE - v3s16(1, 1, 1); blockseed = getBlockSeed2(full_node_min, seed); // Generate biome noises. Note this must be executed strictly before // generateTerrain, because generateTerrain depends on intermediate // biome-related noises. m_bgen->calcBiomeNoise(node_min); // Generate terrain s16 stone_surface_max_y = generateTerrain(); // Create heightmap updateHeightmap(node_min, node_max); // Place biome-specific nodes and build biomemap if (flags & MG_BIOMES) { generateBiomes(); } // Generate tunnels, caverns and large randomwalk caves if (flags & MG_CAVES) { // Generate tunnels first as caverns confuse them generateCavesNoiseIntersection(stone_surface_max_y); // Generate caverns bool near_cavern = generateCavernsNoise(stone_surface_max_y); // Generate large randomwalk caves if (near_cavern) // Disable large randomwalk caves in this mapchunk by setting // 'large cave depth' to world base. Avoids excessive liquid in // large caverns and floating blobs of overgenerated liquid. generateCavesRandomWalk(stone_surface_max_y, -MAX_MAP_GENERATION_LIMIT); else generateCavesRandomWalk(stone_surface_max_y, large_cave_depth); } // Generate the registered ores m_emerge->oremgr->placeAllOres(this, blockseed, node_min, node_max); // Dungeon creation if ((flags & MG_DUNGEONS) && full_node_min.Y >= dungeon_ymin && full_node_max.Y <= dungeon_ymax) generateDungeons(stone_surface_max_y); // Generate the registered decorations if (flags & MG_DECORATIONS) m_emerge->decomgr->placeAllDecos(this, blockseed, node_min, node_max); // Sprinkle some dust on top after everything else was generated if (flags & MG_BIOMES) dustTopNodes(); updateLiquid(&data->transforming_liquid, full_node_min, full_node_max); if (flags & MG_LIGHT) calcLighting(node_min - v3s16(0, 1, 0), node_max + v3s16(0, 1, 0), full_node_min, full_node_max); this->generating = false; //printf("makeChunk: %lums\n", t.stop()); } int MapgenValleys::getSpawnLevelAtPoint(v2s16 p) { // Check if in a river channel float n_rivers = NoisePerlin2D(&noise_rivers->np, p.X, p.Y, seed); if (std::fabs(n_rivers) <= river_size_factor) // Unsuitable spawn point return MAX_MAP_GENERATION_LIMIT; float n_slope = NoisePerlin2D(&noise_inter_valley_slope->np, p.X, p.Y, seed); float n_terrain_height = NoisePerlin2D(&noise_terrain_height->np, p.X, p.Y, seed); float n_valley = NoisePerlin2D(&noise_valley_depth->np, p.X, p.Y, seed); float n_valley_profile = NoisePerlin2D(&noise_valley_profile->np, p.X, p.Y, seed); float valley_d = n_valley * n_valley; float base = n_terrain_height + valley_d; float river = std::fabs(n_rivers) - river_size_factor; float tv = std::fmax(river / n_valley_profile, 0.0f); float valley_h = valley_d * (1.0f - std::exp(-tv * tv)); float surface_y = base + valley_h; float slope = n_slope * valley_h; float river_y = base - 1.0f; // Raising the maximum spawn level above 'water_level + 16' is necessary for custom // parameters that set average terrain level much higher than water_level. s16 max_spawn_y = std::fmax( noise_terrain_height->np.offset + noise_valley_depth->np.offset * noise_valley_depth->np.offset, water_level + 16); // Starting spawn search at max_spawn_y + 128 ensures 128 nodes of open // space above spawn position. Avoids spawning in possibly sealed voids. for (s16 y = max_spawn_y + 128; y >= water_level; y--) { float n_fill = NoisePerlin3D(&noise_inter_valley_fill->np, p.X, y, p.Y, seed); float surface_delta = (float)y - surface_y; float density = slope * n_fill - surface_delta; if (density > 0.0f) { // If solid // Sometimes surface level is below river water level in places that are not // river channels. if (y < water_level || y > max_spawn_y || y < (s16)river_y) // Unsuitable spawn point return MAX_MAP_GENERATION_LIMIT; // y + 2 because y is surface and due to biome 'dust' nodes. return y + 2; } } // Unsuitable spawn position, no ground found return MAX_MAP_GENERATION_LIMIT; } int MapgenValleys::generateTerrain() { MapNode n_air(CONTENT_AIR); MapNode n_river_water(c_river_water_source); MapNode n_stone(c_stone); MapNode n_water(c_water_source); noise_inter_valley_slope->perlinMap2D(node_min.X, node_min.Z); noise_rivers->perlinMap2D(node_min.X, node_min.Z); noise_terrain_height->perlinMap2D(node_min.X, node_min.Z); noise_valley_depth->perlinMap2D(node_min.X, node_min.Z); noise_valley_profile->perlinMap2D(node_min.X, node_min.Z); noise_inter_valley_fill->perlinMap3D(node_min.X, node_min.Y - 1, node_min.Z); const v3s16 &em = vm->m_area.getExtent(); s16 surface_max_y = -MAX_MAP_GENERATION_LIMIT; u32 index_2d = 0; for (s16 z = node_min.Z; z <= node_max.Z; z++) for (s16 x = node_min.X; x <= node_max.X; x++, index_2d++) { float n_slope = noise_inter_valley_slope->result[index_2d]; float n_rivers = noise_rivers->result[index_2d]; float n_terrain_height = noise_terrain_height->result[index_2d]; float n_valley = noise_valley_depth->result[index_2d]; float n_valley_profile = noise_valley_profile->result[index_2d]; float valley_d = n_valley * n_valley; // 'base' represents the level of the river banks float base = n_terrain_height + valley_d; // 'river' represents the distance from the river edge float river = std::fabs(n_rivers) - river_size_factor; // Use the curve of the function 1-exp(-(x/a)^2) to model valleys. // 'valley_h' represents the height of the terrain, from the rivers. float tv = std::fmax(river / n_valley_profile, 0.0f); float valley_h = valley_d * (1.0f - std::exp(-tv * tv)); // Approximate height of the terrain float surface_y = base + valley_h; float slope = n_slope * valley_h; // River water surface is 1 node below river banks float river_y = base - 1.0f; // Rivers are placed where 'river' is negative if (river < 0.0f) { // Use the the function -sqrt(1-x^2) which models a circle float tr = river / river_size_factor + 1.0f; float depth = (river_depth_bed * std::sqrt(std::fmax(0.0f, 1.0f - tr * tr))); // There is no logical equivalent to this using rangelim surface_y = std::fmin( std::fmax(base - depth, (float)(water_level - 3)), surface_y); slope = 0.0f; } // Optionally vary river depth according to heat and humidity if (spflags & MGVALLEYS_VARY_RIVER_DEPTH) { float t_heat = m_bgen->heatmap[index_2d]; float heat = (spflags & MGVALLEYS_ALT_CHILL) ? // Match heat value calculated below in // 'Optionally decrease heat with altitude'. // In rivers, 'ground height ignoring riverbeds' is 'base'. // As this only affects river water we can assume y > water_level. t_heat + 5.0f - (base - water_level) * 20.0f / altitude_chill : t_heat; float delta = m_bgen->humidmap[index_2d] - 50.0f; if (delta < 0.0f) { float t_evap = (heat - 32.0f) / 300.0f; river_y += delta * std::fmax(t_evap, 0.08f); } } // Highest solid node in column s16 column_max_y = surface_y; u32 index_3d = (z - node_min.Z) * zstride_1u1d + (x - node_min.X); u32 index_data = vm->m_area.index(x, node_min.Y - 1, z); for (s16 y = node_min.Y - 1; y <= node_max.Y + 1; y++) { if (vm->m_data[index_data].getContent() == CONTENT_IGNORE) { float n_fill = noise_inter_valley_fill->result[index_3d]; float surface_delta = (float)y - surface_y; // Density = density noise + density gradient float density = slope * n_fill - surface_delta; if (density > 0.0f) { vm->m_data[index_data] = n_stone; // Stone if (y > surface_max_y) surface_max_y = y; if (y > column_max_y) column_max_y = y; } else if (y <= water_level) { vm->m_data[index_data] = n_water; // Water } else if (y <= (s16)river_y) { vm->m_data[index_data] = n_river_water; // River water } else { vm->m_data[index_data] = n_air; // Air } } VoxelArea::add_y(em, index_data, 1); index_3d += ystride; } // Optionally increase humidity around rivers if (spflags & MGVALLEYS_HUMID_RIVERS) { // Compensate to avoid increasing average humidity m_bgen->humidmap[index_2d] *= 0.8f; // Ground height ignoring riverbeds float t_alt = std::fmax(base, (float)column_max_y); float water_depth = (t_alt - base) / 4.0f; m_bgen->humidmap[index_2d] *= 1.0f + std::pow(0.5f, std::fmax(water_depth, 1.0f)); } // Optionally decrease humidity with altitude if (spflags & MGVALLEYS_ALT_DRY) { // Ground height ignoring riverbeds float t_alt = std::fmax(base, (float)column_max_y); // Only decrease above water_level if (t_alt > water_level) m_bgen->humidmap[index_2d] -= (t_alt - water_level) * 10.0f / altitude_chill; } // Optionally decrease heat with altitude if (spflags & MGVALLEYS_ALT_CHILL) { // Compensate to avoid reducing the average heat m_bgen->heatmap[index_2d] += 5.0f; // Ground height ignoring riverbeds float t_alt = std::fmax(base, (float)column_max_y); // Only decrease above water_level if (t_alt > water_level) m_bgen->heatmap[index_2d] -= (t_alt - water_level) * 20.0f / altitude_chill; } } return surface_max_y; }
pgimeno/minetest
src/mapgen/mapgen_valleys.cpp
C++
mit
18,018
/* Minetest Copyright (C) 2016-2019 Duane Robertson <duane@duanerobertson.com> Copyright (C) 2016-2019 paramat Based on Valleys Mapgen by Gael de Sailly (https://forum.minetest.net/viewtopic.php?f=9&t=11430) and mapgen_v7, mapgen_flat by kwolekr and paramat. Licensing changed by permission of Gael de Sailly. 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. */ #pragma once #include "mapgen.h" #define MGVALLEYS_ALT_CHILL 0x01 #define MGVALLEYS_HUMID_RIVERS 0x02 #define MGVALLEYS_VARY_RIVER_DEPTH 0x04 #define MGVALLEYS_ALT_DRY 0x08 class BiomeManager; class BiomeGenOriginal; extern FlagDesc flagdesc_mapgen_valleys[]; struct MapgenValleysParams : public MapgenParams { u32 spflags = MGVALLEYS_ALT_CHILL | MGVALLEYS_HUMID_RIVERS | MGVALLEYS_VARY_RIVER_DEPTH | MGVALLEYS_ALT_DRY; u16 altitude_chill = 90; u16 river_depth = 4; u16 river_size = 5; float cave_width = 0.09f; s16 large_cave_depth = -33; s16 lava_depth = 1; s16 cavern_limit = -256; s16 cavern_taper = 192; float cavern_threshold = 0.6f; s16 dungeon_ymin = -31000; s16 dungeon_ymax = 63; NoiseParams np_filler_depth; NoiseParams np_inter_valley_fill; NoiseParams np_inter_valley_slope; NoiseParams np_rivers; NoiseParams np_terrain_height; NoiseParams np_valley_depth; NoiseParams np_valley_profile; NoiseParams np_cave1; NoiseParams np_cave2; NoiseParams np_cavern; MapgenValleysParams(); ~MapgenValleysParams() = default; void readParams(const Settings *settings); void writeParams(Settings *settings) const; }; class MapgenValleys : public MapgenBasic { public: MapgenValleys(MapgenValleysParams *params, EmergeManager *emerge); ~MapgenValleys(); virtual MapgenType getType() const { return MAPGEN_VALLEYS; } virtual void makeChunk(BlockMakeData *data); int getSpawnLevelAtPoint(v2s16 p); private: BiomeGenOriginal *m_bgen; float altitude_chill; float river_depth_bed; float river_size_factor; s16 large_cave_depth; s16 dungeon_ymin; s16 dungeon_ymax; Noise *noise_inter_valley_fill; Noise *noise_inter_valley_slope; Noise *noise_rivers; Noise *noise_terrain_height; Noise *noise_valley_depth; Noise *noise_valley_profile; virtual int generateTerrain(); };
pgimeno/minetest
src/mapgen/mapgen_valleys.h
C++
mit
2,873
/* Minetest Copyright (C) 2014-2018 kwolekr, Ryan Kwolek <kwolekr@minetest.net> Copyright (C) 2014-2018 paramat 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 "mg_biome.h" #include "mg_decoration.h" #include "emerge.h" #include "server.h" #include "nodedef.h" #include "map.h" //for MMVManip #include "util/numeric.h" #include "porting.h" #include "settings.h" /////////////////////////////////////////////////////////////////////////////// BiomeManager::BiomeManager(Server *server) : ObjDefManager(server, OBJDEF_BIOME) { m_server = server; // Create default biome to be used in case none exist Biome *b = new Biome; b->name = "default"; b->flags = 0; b->depth_top = 0; b->depth_filler = -MAX_MAP_GENERATION_LIMIT; b->depth_water_top = 0; b->depth_riverbed = 0; b->min_pos = v3s16(-MAX_MAP_GENERATION_LIMIT, -MAX_MAP_GENERATION_LIMIT, -MAX_MAP_GENERATION_LIMIT); b->max_pos = v3s16(MAX_MAP_GENERATION_LIMIT, MAX_MAP_GENERATION_LIMIT, MAX_MAP_GENERATION_LIMIT); b->heat_point = 0.0; b->humidity_point = 0.0; b->vertical_blend = 0; b->m_nodenames.emplace_back("mapgen_stone"); b->m_nodenames.emplace_back("mapgen_stone"); b->m_nodenames.emplace_back("mapgen_stone"); b->m_nodenames.emplace_back("mapgen_water_source"); b->m_nodenames.emplace_back("mapgen_water_source"); b->m_nodenames.emplace_back("mapgen_river_water_source"); b->m_nodenames.emplace_back("mapgen_stone"); b->m_nodenames.emplace_back("ignore"); b->m_nodenames.emplace_back("ignore"); b->m_nodenames.emplace_back("ignore"); b->m_nodenames.emplace_back("ignore"); b->m_nodenames.emplace_back("ignore"); m_ndef->pendNodeResolve(b); add(b); } void BiomeManager::clear() { EmergeManager *emerge = m_server->getEmergeManager(); // Remove all dangling references in Decorations DecorationManager *decomgr = emerge->decomgr; for (size_t i = 0; i != decomgr->getNumObjects(); i++) { Decoration *deco = (Decoration *)decomgr->getRaw(i); deco->biomes.clear(); } // Don't delete the first biome for (size_t i = 1; i < m_objects.size(); i++) delete (Biome *)m_objects[i]; m_objects.resize(1); } // For BiomeGen type 'BiomeGenOriginal' float BiomeManager::getHeatAtPosOriginal(v3s16 pos, NoiseParams &np_heat, NoiseParams &np_heat_blend, u64 seed) { return NoisePerlin2D(&np_heat, pos.X, pos.Z, seed) + NoisePerlin2D(&np_heat_blend, pos.X, pos.Z, seed); } // For BiomeGen type 'BiomeGenOriginal' float BiomeManager::getHumidityAtPosOriginal(v3s16 pos, NoiseParams &np_humidity, NoiseParams &np_humidity_blend, u64 seed) { return NoisePerlin2D(&np_humidity, pos.X, pos.Z, seed) + NoisePerlin2D(&np_humidity_blend, pos.X, pos.Z, seed); } // For BiomeGen type 'BiomeGenOriginal' Biome *BiomeManager::getBiomeFromNoiseOriginal(float heat, float humidity, v3s16 pos) { Biome *biome_closest = nullptr; Biome *biome_closest_blend = nullptr; float dist_min = FLT_MAX; float dist_min_blend = FLT_MAX; for (size_t i = 1; i < getNumObjects(); i++) { Biome *b = (Biome *)getRaw(i); if (!b || pos.Y < b->min_pos.Y || pos.Y > b->max_pos.Y + b->vertical_blend || pos.X < b->min_pos.X || pos.X > b->max_pos.X || pos.Z < b->min_pos.Z || pos.Z > b->max_pos.Z) continue; float d_heat = heat - b->heat_point; float d_humidity = humidity - b->humidity_point; float dist = (d_heat * d_heat) + (d_humidity * d_humidity); if (pos.Y <= b->max_pos.Y) { // Within y limits of biome b if (dist < dist_min) { dist_min = dist; biome_closest = b; } } else if (dist < dist_min_blend) { // Blend area above biome b dist_min_blend = dist; biome_closest_blend = b; } } mysrand(pos.Y + (heat + humidity) * 0.9f); if (biome_closest_blend && dist_min_blend <= dist_min && myrand_range(0, biome_closest_blend->vertical_blend) >= pos.Y - biome_closest_blend->max_pos.Y) return biome_closest_blend; return (biome_closest) ? biome_closest : (Biome *)getRaw(BIOME_NONE); } //////////////////////////////////////////////////////////////////////////////// void BiomeParamsOriginal::readParams(const Settings *settings) { settings->getNoiseParams("mg_biome_np_heat", np_heat); settings->getNoiseParams("mg_biome_np_heat_blend", np_heat_blend); settings->getNoiseParams("mg_biome_np_humidity", np_humidity); settings->getNoiseParams("mg_biome_np_humidity_blend", np_humidity_blend); } void BiomeParamsOriginal::writeParams(Settings *settings) const { settings->setNoiseParams("mg_biome_np_heat", np_heat); settings->setNoiseParams("mg_biome_np_heat_blend", np_heat_blend); settings->setNoiseParams("mg_biome_np_humidity", np_humidity); settings->setNoiseParams("mg_biome_np_humidity_blend", np_humidity_blend); } //////////////////////////////////////////////////////////////////////////////// BiomeGenOriginal::BiomeGenOriginal(BiomeManager *biomemgr, BiomeParamsOriginal *params, v3s16 chunksize) { m_bmgr = biomemgr; m_params = params; m_csize = chunksize; noise_heat = new Noise(&params->np_heat, params->seed, m_csize.X, m_csize.Z); noise_humidity = new Noise(&params->np_humidity, params->seed, m_csize.X, m_csize.Z); noise_heat_blend = new Noise(&params->np_heat_blend, params->seed, m_csize.X, m_csize.Z); noise_humidity_blend = new Noise(&params->np_humidity_blend, params->seed, m_csize.X, m_csize.Z); heatmap = noise_heat->result; humidmap = noise_humidity->result; biomemap = new biome_t[m_csize.X * m_csize.Z]; // Initialise with the ID of 'BIOME_NONE' so that cavegen can get the // fallback biome when biome generation (which calculates the biomemap IDs) // is disabled. memset(biomemap, 0, sizeof(biome_t) * m_csize.X * m_csize.Z); } BiomeGenOriginal::~BiomeGenOriginal() { delete []biomemap; delete noise_heat; delete noise_humidity; delete noise_heat_blend; delete noise_humidity_blend; } // Only usable in a mapgen thread Biome *BiomeGenOriginal::calcBiomeAtPoint(v3s16 pos) const { float heat = NoisePerlin2D(&m_params->np_heat, pos.X, pos.Z, m_params->seed) + NoisePerlin2D(&m_params->np_heat_blend, pos.X, pos.Z, m_params->seed); float humidity = NoisePerlin2D(&m_params->np_humidity, pos.X, pos.Z, m_params->seed) + NoisePerlin2D(&m_params->np_humidity_blend, pos.X, pos.Z, m_params->seed); return calcBiomeFromNoise(heat, humidity, pos); } void BiomeGenOriginal::calcBiomeNoise(v3s16 pmin) { m_pmin = pmin; noise_heat->perlinMap2D(pmin.X, pmin.Z); noise_humidity->perlinMap2D(pmin.X, pmin.Z); noise_heat_blend->perlinMap2D(pmin.X, pmin.Z); noise_humidity_blend->perlinMap2D(pmin.X, pmin.Z); for (s32 i = 0; i < m_csize.X * m_csize.Z; i++) { noise_heat->result[i] += noise_heat_blend->result[i]; noise_humidity->result[i] += noise_humidity_blend->result[i]; } } biome_t *BiomeGenOriginal::getBiomes(s16 *heightmap, v3s16 pmin) { for (s16 zr = 0; zr < m_csize.Z; zr++) for (s16 xr = 0; xr < m_csize.X; xr++) { s32 i = zr * m_csize.X + xr; Biome *biome = calcBiomeFromNoise( noise_heat->result[i], noise_humidity->result[i], v3s16(pmin.X + xr, heightmap[i], pmin.Z + zr)); biomemap[i] = biome->index; } return biomemap; } Biome *BiomeGenOriginal::getBiomeAtPoint(v3s16 pos) const { return getBiomeAtIndex( (pos.Z - m_pmin.Z) * m_csize.X + (pos.X - m_pmin.X), pos); } Biome *BiomeGenOriginal::getBiomeAtIndex(size_t index, v3s16 pos) const { return calcBiomeFromNoise( noise_heat->result[index], noise_humidity->result[index], pos); } Biome *BiomeGenOriginal::calcBiomeFromNoise(float heat, float humidity, v3s16 pos) const { Biome *biome_closest = nullptr; Biome *biome_closest_blend = nullptr; float dist_min = FLT_MAX; float dist_min_blend = FLT_MAX; for (size_t i = 1; i < m_bmgr->getNumObjects(); i++) { Biome *b = (Biome *)m_bmgr->getRaw(i); if (!b || pos.Y < b->min_pos.Y || pos.Y > b->max_pos.Y + b->vertical_blend || pos.X < b->min_pos.X || pos.X > b->max_pos.X || pos.Z < b->min_pos.Z || pos.Z > b->max_pos.Z) continue; float d_heat = heat - b->heat_point; float d_humidity = humidity - b->humidity_point; float dist = (d_heat * d_heat) + (d_humidity * d_humidity); if (pos.Y <= b->max_pos.Y) { // Within y limits of biome b if (dist < dist_min) { dist_min = dist; biome_closest = b; } } else if (dist < dist_min_blend) { // Blend area above biome b dist_min_blend = dist; biome_closest_blend = b; } } // Carefully tune pseudorandom seed variation to avoid single node dither // and create larger scale blending patterns similar to horizontal biome // blend. mysrand(pos.Y + (heat + humidity) * 0.9f); if (biome_closest_blend && dist_min_blend <= dist_min && myrand_range(0, biome_closest_blend->vertical_blend) >= pos.Y - biome_closest_blend->max_pos.Y) return biome_closest_blend; return (biome_closest) ? biome_closest : (Biome *)m_bmgr->getRaw(BIOME_NONE); } //////////////////////////////////////////////////////////////////////////////// void Biome::resolveNodeNames() { getIdFromNrBacklog(&c_top, "mapgen_stone", CONTENT_AIR, false); getIdFromNrBacklog(&c_filler, "mapgen_stone", CONTENT_AIR, false); getIdFromNrBacklog(&c_stone, "mapgen_stone", CONTENT_AIR, false); getIdFromNrBacklog(&c_water_top, "mapgen_water_source", CONTENT_AIR, false); getIdFromNrBacklog(&c_water, "mapgen_water_source", CONTENT_AIR, false); getIdFromNrBacklog(&c_river_water, "mapgen_river_water_source", CONTENT_AIR, false); getIdFromNrBacklog(&c_riverbed, "mapgen_stone", CONTENT_AIR, false); getIdFromNrBacklog(&c_dust, "ignore", CONTENT_IGNORE, false); getIdFromNrBacklog(&c_cave_liquid, "ignore", CONTENT_IGNORE, false); getIdFromNrBacklog(&c_dungeon, "ignore", CONTENT_IGNORE, false); getIdFromNrBacklog(&c_dungeon_alt, "ignore", CONTENT_IGNORE, false); getIdFromNrBacklog(&c_dungeon_stair, "ignore", CONTENT_IGNORE, false); }
pgimeno/minetest
src/mapgen/mg_biome.cpp
C++
mit
10,904
/* Minetest Copyright (C) 2014-2018 kwolekr, Ryan Kwolek <kwolekr@minetest.net> Copyright (C) 2014-2018 paramat 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. */ #pragma once #include "objdef.h" #include "nodedef.h" #include "noise.h" class Server; class Settings; class BiomeManager; //// //// Biome //// typedef u8 biome_t; #define BIOME_NONE ((biome_t)0) enum BiomeType { BIOMETYPE_NORMAL, }; class Biome : public ObjDef, public NodeResolver { public: u32 flags; content_t c_top; content_t c_filler; content_t c_stone; content_t c_water_top; content_t c_water; content_t c_river_water; content_t c_riverbed; content_t c_dust; content_t c_cave_liquid; content_t c_dungeon; content_t c_dungeon_alt; content_t c_dungeon_stair; s16 depth_top; s16 depth_filler; s16 depth_water_top; s16 depth_riverbed; v3s16 min_pos; v3s16 max_pos; float heat_point; float humidity_point; s16 vertical_blend; virtual void resolveNodeNames(); }; //// //// BiomeGen //// enum BiomeGenType { BIOMEGEN_ORIGINAL, }; struct BiomeParams { virtual void readParams(const Settings *settings) = 0; virtual void writeParams(Settings *settings) const = 0; virtual ~BiomeParams() = default; s32 seed; }; class BiomeGen { public: virtual ~BiomeGen() = default; virtual BiomeGenType getType() const = 0; // Calculates the biome at the exact position provided. This function can // be called at any time, but may be less efficient than the latter methods, // depending on implementation. virtual Biome *calcBiomeAtPoint(v3s16 pos) const = 0; // Computes any intermediate results needed for biome generation. Must be // called before using any of: getBiomes, getBiomeAtPoint, or getBiomeAtIndex. // Calling this invalidates the previous results stored in biomemap. virtual void calcBiomeNoise(v3s16 pmin) = 0; // Gets all biomes in current chunk using each corresponding element of // heightmap as the y position, then stores the results by biome index in // biomemap (also returned) virtual biome_t *getBiomes(s16 *heightmap, v3s16 pmin) = 0; // Gets a single biome at the specified position, which must be contained // in the region formed by m_pmin and (m_pmin + m_csize - 1). virtual Biome *getBiomeAtPoint(v3s16 pos) const = 0; // Same as above, but uses a raw numeric index correlating to the (x,z) position. virtual Biome *getBiomeAtIndex(size_t index, v3s16 pos) const = 0; // Result of calcBiomes bulk computation. biome_t *biomemap = nullptr; protected: BiomeManager *m_bmgr = nullptr; v3s16 m_pmin; v3s16 m_csize; }; //// //// BiomeGen implementations //// // // Original biome algorithm (Whittaker's classification + surface height) // struct BiomeParamsOriginal : public BiomeParams { BiomeParamsOriginal() : np_heat(50, 50, v3f(1000.0, 1000.0, 1000.0), 5349, 3, 0.5, 2.0), np_humidity(50, 50, v3f(1000.0, 1000.0, 1000.0), 842, 3, 0.5, 2.0), np_heat_blend(0, 1.5, v3f(8.0, 8.0, 8.0), 13, 2, 1.0, 2.0), np_humidity_blend(0, 1.5, v3f(8.0, 8.0, 8.0), 90003, 2, 1.0, 2.0) { } virtual void readParams(const Settings *settings); virtual void writeParams(Settings *settings) const; NoiseParams np_heat; NoiseParams np_humidity; NoiseParams np_heat_blend; NoiseParams np_humidity_blend; }; class BiomeGenOriginal : public BiomeGen { public: BiomeGenOriginal(BiomeManager *biomemgr, BiomeParamsOriginal *params, v3s16 chunksize); virtual ~BiomeGenOriginal(); BiomeGenType getType() const { return BIOMEGEN_ORIGINAL; } Biome *calcBiomeAtPoint(v3s16 pos) const; void calcBiomeNoise(v3s16 pmin); biome_t *getBiomes(s16 *heightmap, v3s16 pmin); Biome *getBiomeAtPoint(v3s16 pos) const; Biome *getBiomeAtIndex(size_t index, v3s16 pos) const; Biome *calcBiomeFromNoise(float heat, float humidity, v3s16 pos) const; float *heatmap; float *humidmap; private: BiomeParamsOriginal *m_params; Noise *noise_heat; Noise *noise_humidity; Noise *noise_heat_blend; Noise *noise_humidity_blend; }; //// //// BiomeManager //// class BiomeManager : public ObjDefManager { public: BiomeManager(Server *server); virtual ~BiomeManager() = default; const char *getObjectTitle() const { return "biome"; } static Biome *create(BiomeType type) { return new Biome; } BiomeGen *createBiomeGen(BiomeGenType type, BiomeParams *params, v3s16 chunksize) { switch (type) { case BIOMEGEN_ORIGINAL: return new BiomeGenOriginal(this, (BiomeParamsOriginal *)params, chunksize); default: return NULL; } } static BiomeParams *createBiomeParams(BiomeGenType type) { switch (type) { case BIOMEGEN_ORIGINAL: return new BiomeParamsOriginal; default: return NULL; } } virtual void clear(); // For BiomeGen type 'BiomeGenOriginal' float getHeatAtPosOriginal(v3s16 pos, NoiseParams &np_heat, NoiseParams &np_heat_blend, u64 seed); float getHumidityAtPosOriginal(v3s16 pos, NoiseParams &np_humidity, NoiseParams &np_humidity_blend, u64 seed); Biome *getBiomeFromNoiseOriginal(float heat, float humidity, v3s16 pos); private: Server *m_server; };
pgimeno/minetest
src/mapgen/mg_biome.h
C++
mit
5,725
/* Minetest Copyright (C) 2014-2018 kwolekr, Ryan Kwolek <kwolekr@minetest.net> Copyright (C) 2015-2018 paramat 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 "mg_decoration.h" #include "mg_schematic.h" #include "mapgen.h" #include "noise.h" #include "map.h" #include "log.h" #include "util/numeric.h" #include <algorithm> #include <vector> FlagDesc flagdesc_deco[] = { {"place_center_x", DECO_PLACE_CENTER_X}, {"place_center_y", DECO_PLACE_CENTER_Y}, {"place_center_z", DECO_PLACE_CENTER_Z}, {"force_placement", DECO_FORCE_PLACEMENT}, {"liquid_surface", DECO_LIQUID_SURFACE}, {"all_floors", DECO_ALL_FLOORS}, {"all_ceilings", DECO_ALL_CEILINGS}, {NULL, 0} }; /////////////////////////////////////////////////////////////////////////////// DecorationManager::DecorationManager(IGameDef *gamedef) : ObjDefManager(gamedef, OBJDEF_DECORATION) { } size_t DecorationManager::placeAllDecos(Mapgen *mg, u32 blockseed, v3s16 nmin, v3s16 nmax) { size_t nplaced = 0; for (size_t i = 0; i != m_objects.size(); i++) { Decoration *deco = (Decoration *)m_objects[i]; if (!deco) continue; nplaced += deco->placeDeco(mg, blockseed, nmin, nmax); blockseed++; } return nplaced; } /////////////////////////////////////////////////////////////////////////////// void Decoration::resolveNodeNames() { getIdsFromNrBacklog(&c_place_on); getIdsFromNrBacklog(&c_spawnby); } bool Decoration::canPlaceDecoration(MMVManip *vm, v3s16 p) { // Check if the decoration can be placed on this node u32 vi = vm->m_area.index(p); if (!CONTAINS(c_place_on, vm->m_data[vi].getContent())) return false; // Don't continue if there are no spawnby constraints if (nspawnby == -1) return true; int nneighs = 0; static const v3s16 dirs[16] = { v3s16( 0, 0, 1), v3s16( 0, 0, -1), v3s16( 1, 0, 0), v3s16(-1, 0, 0), v3s16( 1, 0, 1), v3s16(-1, 0, 1), v3s16(-1, 0, -1), v3s16( 1, 0, -1), v3s16( 0, 1, 1), v3s16( 0, 1, -1), v3s16( 1, 1, 0), v3s16(-1, 1, 0), v3s16( 1, 1, 1), v3s16(-1, 1, 1), v3s16(-1, 1, -1), v3s16( 1, 1, -1) }; // Check these 16 neighbouring nodes for enough spawnby nodes for (size_t i = 0; i != ARRLEN(dirs); i++) { u32 index = vm->m_area.index(p + dirs[i]); if (!vm->m_area.contains(index)) continue; if (CONTAINS(c_spawnby, vm->m_data[index].getContent())) nneighs++; } if (nneighs < nspawnby) return false; return true; } size_t Decoration::placeDeco(Mapgen *mg, u32 blockseed, v3s16 nmin, v3s16 nmax) { PcgRandom ps(blockseed + 53); int carea_size = nmax.X - nmin.X + 1; // Divide area into parts // If chunksize is changed it may no longer be divisable by sidelen if (carea_size % sidelen) sidelen = carea_size; s16 divlen = carea_size / sidelen; int area = sidelen * sidelen; for (s16 z0 = 0; z0 < divlen; z0++) for (s16 x0 = 0; x0 < divlen; x0++) { v2s16 p2d_center( // Center position of part of division nmin.X + sidelen / 2 + sidelen * x0, nmin.Z + sidelen / 2 + sidelen * z0 ); v2s16 p2d_min( // Minimum edge of part of division nmin.X + sidelen * x0, nmin.Z + sidelen * z0 ); v2s16 p2d_max( // Maximum edge of part of division nmin.X + sidelen + sidelen * x0 - 1, nmin.Z + sidelen + sidelen * z0 - 1 ); bool cover = false; // Amount of decorations float nval = (flags & DECO_USE_NOISE) ? NoisePerlin2D(&np, p2d_center.X, p2d_center.Y, mapseed) : fill_ratio; u32 deco_count = 0; if (nval >= 10.0f) { // Complete coverage. Disable random placement to avoid // redundant multiple placements at one position. cover = true; deco_count = area; } else { float deco_count_f = (float)area * nval; if (deco_count_f >= 1.0f) { deco_count = deco_count_f; } else if (deco_count_f > 0.0f) { // For very low density calculate a chance for 1 decoration if (ps.range(1000) <= deco_count_f * 1000.0f) deco_count = 1; } } s16 x = p2d_min.X - 1; s16 z = p2d_min.Y; for (u32 i = 0; i < deco_count; i++) { if (!cover) { x = ps.range(p2d_min.X, p2d_max.X); z = ps.range(p2d_min.Y, p2d_max.Y); } else { x++; if (x == p2d_max.X + 1) { z++; x = p2d_min.X; } } int mapindex = carea_size * (z - nmin.Z) + (x - nmin.X); if ((flags & DECO_ALL_FLOORS) || (flags & DECO_ALL_CEILINGS)) { // All-surfaces decorations // Check biome of column if (mg->biomemap && !biomes.empty()) { std::unordered_set<u8>::const_iterator iter = biomes.find(mg->biomemap[mapindex]); if (iter == biomes.end()) continue; } // Get all floors and ceilings in node column u16 size = (nmax.Y - nmin.Y + 1) / 2; std::vector<s16> floors; std::vector<s16> ceilings; floors.reserve(size); ceilings.reserve(size); mg->getSurfaces(v2s16(x, z), nmin.Y, nmax.Y, floors, ceilings); if (flags & DECO_ALL_FLOORS) { // Floor decorations for (const s16 y : floors) { if (y < y_min || y > y_max) continue; v3s16 pos(x, y, z); if (generate(mg->vm, &ps, pos, false)) mg->gennotify.addEvent( GENNOTIFY_DECORATION, pos, index); } } if (flags & DECO_ALL_CEILINGS) { // Ceiling decorations for (const s16 y : ceilings) { if (y < y_min || y > y_max) continue; v3s16 pos(x, y, z); if (generate(mg->vm, &ps, pos, true)) mg->gennotify.addEvent( GENNOTIFY_DECORATION, pos, index); } } } else { // Heightmap decorations s16 y = -MAX_MAP_GENERATION_LIMIT; if (flags & DECO_LIQUID_SURFACE) y = mg->findLiquidSurface(v2s16(x, z), nmin.Y, nmax.Y); else if (mg->heightmap) y = mg->heightmap[mapindex]; else y = mg->findGroundLevel(v2s16(x, z), nmin.Y, nmax.Y); if (y < y_min || y > y_max || y < nmin.Y || y > nmax.Y) continue; if (mg->biomemap && !biomes.empty()) { std::unordered_set<u8>::const_iterator iter = biomes.find(mg->biomemap[mapindex]); if (iter == biomes.end()) continue; } v3s16 pos(x, y, z); if (generate(mg->vm, &ps, pos, false)) mg->gennotify.addEvent(GENNOTIFY_DECORATION, pos, index); } } } return 0; } /////////////////////////////////////////////////////////////////////////////// void DecoSimple::resolveNodeNames() { Decoration::resolveNodeNames(); getIdsFromNrBacklog(&c_decos); } size_t DecoSimple::generate(MMVManip *vm, PcgRandom *pr, v3s16 p, bool ceiling) { // Don't bother if there aren't any decorations to place if (c_decos.empty()) return 0; if (!canPlaceDecoration(vm, p)) return 0; // Check for placement outside the voxelmanip volume if (ceiling) { // Ceiling decorations // 'place offset y' is inverted if (p.Y - place_offset_y - std::max(deco_height, deco_height_max) < vm->m_area.MinEdge.Y) return 0; if (p.Y - 1 - place_offset_y > vm->m_area.MaxEdge.Y) return 0; } else { // Heightmap and floor decorations if (p.Y + place_offset_y + std::max(deco_height, deco_height_max) > vm->m_area.MaxEdge.Y) return 0; if (p.Y + 1 + place_offset_y < vm->m_area.MinEdge.Y) return 0; } content_t c_place = c_decos[pr->range(0, c_decos.size() - 1)]; s16 height = (deco_height_max > 0) ? pr->range(deco_height, deco_height_max) : deco_height; u8 param2 = (deco_param2_max > 0) ? pr->range(deco_param2, deco_param2_max) : deco_param2; bool force_placement = (flags & DECO_FORCE_PLACEMENT); const v3s16 &em = vm->m_area.getExtent(); u32 vi = vm->m_area.index(p); if (ceiling) { // Ceiling decorations // 'place offset y' is inverted VoxelArea::add_y(em, vi, -place_offset_y); for (int i = 0; i < height; i++) { VoxelArea::add_y(em, vi, -1); content_t c = vm->m_data[vi].getContent(); if (c != CONTENT_AIR && c != CONTENT_IGNORE && !force_placement) break; vm->m_data[vi] = MapNode(c_place, 0, param2); } } else { // Heightmap and floor decorations VoxelArea::add_y(em, vi, place_offset_y); for (int i = 0; i < height; i++) { VoxelArea::add_y(em, vi, 1); content_t c = vm->m_data[vi].getContent(); if (c != CONTENT_AIR && c != CONTENT_IGNORE && !force_placement) break; vm->m_data[vi] = MapNode(c_place, 0, param2); } } return 1; } /////////////////////////////////////////////////////////////////////////////// size_t DecoSchematic::generate(MMVManip *vm, PcgRandom *pr, v3s16 p, bool ceiling) { // Schematic could have been unloaded but not the decoration // In this case generate() does nothing (but doesn't *fail*) if (schematic == NULL) return 0; if (!canPlaceDecoration(vm, p)) return 0; if (flags & DECO_PLACE_CENTER_Y) { p.Y -= (schematic->size.Y - 1) / 2; } else { // Only apply 'place offset y' if not 'deco place center y' if (ceiling) // Shift down so that schematic top layer is level with ceiling // 'place offset y' is inverted p.Y -= (place_offset_y + schematic->size.Y - 1); else p.Y += place_offset_y; } // Check schematic top and base are in voxelmanip if (p.Y + schematic->size.Y - 1 > vm->m_area.MaxEdge.Y) return 0; if (p.Y < vm->m_area.MinEdge.Y) return 0; Rotation rot = (rotation == ROTATE_RAND) ? (Rotation)pr->range(ROTATE_0, ROTATE_270) : rotation; if (flags & DECO_PLACE_CENTER_X) { if (rot == ROTATE_0 || rot == ROTATE_180) p.X -= (schematic->size.X - 1) / 2; else p.Z -= (schematic->size.X - 1) / 2; } if (flags & DECO_PLACE_CENTER_Z) { if (rot == ROTATE_0 || rot == ROTATE_180) p.Z -= (schematic->size.Z - 1) / 2; else p.X -= (schematic->size.Z - 1) / 2; } bool force_placement = (flags & DECO_FORCE_PLACEMENT); schematic->blitToVManip(vm, p, rot, force_placement); return 1; }
pgimeno/minetest
src/mapgen/mg_decoration.cpp
C++
mit
10,415
/* Minetest Copyright (C) 2014-2018 kwolekr, Ryan Kwolek <kwolekr@minetest.net> Copyright (C) 2015-2018 paramat 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. */ #pragma once #include <unordered_set> #include "objdef.h" #include "noise.h" #include "nodedef.h" class Mapgen; class MMVManip; class PcgRandom; class Schematic; enum DecorationType { DECO_SIMPLE, DECO_SCHEMATIC, DECO_LSYSTEM }; #define DECO_PLACE_CENTER_X 0x01 #define DECO_PLACE_CENTER_Y 0x02 #define DECO_PLACE_CENTER_Z 0x04 #define DECO_USE_NOISE 0x08 #define DECO_FORCE_PLACEMENT 0x10 #define DECO_LIQUID_SURFACE 0x20 #define DECO_ALL_FLOORS 0x40 #define DECO_ALL_CEILINGS 0x80 extern FlagDesc flagdesc_deco[]; class Decoration : public ObjDef, public NodeResolver { public: Decoration() = default; virtual ~Decoration() = default; virtual void resolveNodeNames(); bool canPlaceDecoration(MMVManip *vm, v3s16 p); size_t placeDeco(Mapgen *mg, u32 blockseed, v3s16 nmin, v3s16 nmax); virtual size_t generate(MMVManip *vm, PcgRandom *pr, v3s16 p, bool ceiling) = 0; u32 flags = 0; int mapseed = 0; std::vector<content_t> c_place_on; s16 sidelen = 1; s16 y_min; s16 y_max; float fill_ratio = 0.0f; NoiseParams np; std::vector<content_t> c_spawnby; s16 nspawnby; s16 place_offset_y = 0; std::unordered_set<u8> biomes; }; class DecoSimple : public Decoration { public: virtual void resolveNodeNames(); virtual size_t generate(MMVManip *vm, PcgRandom *pr, v3s16 p, bool ceiling); std::vector<content_t> c_decos; s16 deco_height; s16 deco_height_max; u8 deco_param2; u8 deco_param2_max; }; class DecoSchematic : public Decoration { public: DecoSchematic() = default; virtual size_t generate(MMVManip *vm, PcgRandom *pr, v3s16 p, bool ceiling); Rotation rotation; Schematic *schematic = nullptr; }; /* class DecoLSystem : public Decoration { public: virtual void generate(Mapgen *mg, u32 blockseed, v3s16 nmin, v3s16 nmax); }; */ class DecorationManager : public ObjDefManager { public: DecorationManager(IGameDef *gamedef); virtual ~DecorationManager() = default; const char *getObjectTitle() const { return "decoration"; } static Decoration *create(DecorationType type) { switch (type) { case DECO_SIMPLE: return new DecoSimple; case DECO_SCHEMATIC: return new DecoSchematic; //case DECO_LSYSTEM: // return new DecoLSystem; default: return NULL; } } size_t placeAllDecos(Mapgen *mg, u32 blockseed, v3s16 nmin, v3s16 nmax); };
pgimeno/minetest
src/mapgen/mg_decoration.h
C++
mit
3,155
/* Minetest Copyright (C) 2014-2018 kwolekr, Ryan Kwolek <kwolekr@minetest.net> Copyright (C) 2015-2018 paramat 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 "mg_ore.h" #include "mapgen.h" #include "noise.h" #include "map.h" #include "log.h" #include "util/numeric.h" #include <cmath> #include <algorithm> FlagDesc flagdesc_ore[] = { {"absheight", OREFLAG_ABSHEIGHT}, // Non-functional {"puff_cliffs", OREFLAG_PUFF_CLIFFS}, {"puff_additive_composition", OREFLAG_PUFF_ADDITIVE}, {NULL, 0} }; /////////////////////////////////////////////////////////////////////////////// OreManager::OreManager(IGameDef *gamedef) : ObjDefManager(gamedef, OBJDEF_ORE) { } size_t OreManager::placeAllOres(Mapgen *mg, u32 blockseed, v3s16 nmin, v3s16 nmax) { size_t nplaced = 0; for (size_t i = 0; i != m_objects.size(); i++) { Ore *ore = (Ore *)m_objects[i]; if (!ore) continue; nplaced += ore->placeOre(mg, blockseed, nmin, nmax); blockseed++; } return nplaced; } void OreManager::clear() { for (ObjDef *object : m_objects) { Ore *ore = (Ore *) object; delete ore; } m_objects.clear(); } /////////////////////////////////////////////////////////////////////////////// Ore::~Ore() { delete noise; } void Ore::resolveNodeNames() { getIdFromNrBacklog(&c_ore, "", CONTENT_AIR); getIdsFromNrBacklog(&c_wherein); } size_t Ore::placeOre(Mapgen *mg, u32 blockseed, v3s16 nmin, v3s16 nmax) { if (nmin.Y > y_max || nmax.Y < y_min) return 0; int actual_ymin = MYMAX(nmin.Y, y_min); int actual_ymax = MYMIN(nmax.Y, y_max); if (clust_size >= actual_ymax - actual_ymin + 1) return 0; nmin.Y = actual_ymin; nmax.Y = actual_ymax; generate(mg->vm, mg->seed, blockseed, nmin, nmax, mg->biomemap); return 1; } /////////////////////////////////////////////////////////////////////////////// void OreScatter::generate(MMVManip *vm, int mapseed, u32 blockseed, v3s16 nmin, v3s16 nmax, u8 *biomemap) { PcgRandom pr(blockseed); MapNode n_ore(c_ore, 0, ore_param2); u32 sizex = (nmax.X - nmin.X + 1); u32 volume = (nmax.X - nmin.X + 1) * (nmax.Y - nmin.Y + 1) * (nmax.Z - nmin.Z + 1); u32 csize = clust_size; u32 cvolume = csize * csize * csize; u32 nclusters = volume / clust_scarcity; for (u32 i = 0; i != nclusters; i++) { int x0 = pr.range(nmin.X, nmax.X - csize + 1); int y0 = pr.range(nmin.Y, nmax.Y - csize + 1); int z0 = pr.range(nmin.Z, nmax.Z - csize + 1); if ((flags & OREFLAG_USE_NOISE) && (NoisePerlin3D(&np, x0, y0, z0, mapseed) < nthresh)) continue; if (biomemap && !biomes.empty()) { u32 index = sizex * (z0 - nmin.Z) + (x0 - nmin.X); std::unordered_set<u8>::const_iterator it = biomes.find(biomemap[index]); if (it == biomes.end()) continue; } for (u32 z1 = 0; z1 != csize; z1++) for (u32 y1 = 0; y1 != csize; y1++) for (u32 x1 = 0; x1 != csize; x1++) { if (pr.range(1, cvolume) > clust_num_ores) continue; u32 i = vm->m_area.index(x0 + x1, y0 + y1, z0 + z1); if (!CONTAINS(c_wherein, vm->m_data[i].getContent())) continue; vm->m_data[i] = n_ore; } } } /////////////////////////////////////////////////////////////////////////////// void OreSheet::generate(MMVManip *vm, int mapseed, u32 blockseed, v3s16 nmin, v3s16 nmax, u8 *biomemap) { PcgRandom pr(blockseed + 4234); MapNode n_ore(c_ore, 0, ore_param2); u16 max_height = column_height_max; int y_start_min = nmin.Y + max_height; int y_start_max = nmax.Y - max_height; int y_start = y_start_min < y_start_max ? pr.range(y_start_min, y_start_max) : (y_start_min + y_start_max) / 2; if (!noise) { int sx = nmax.X - nmin.X + 1; int sz = nmax.Z - nmin.Z + 1; noise = new Noise(&np, 0, sx, sz); } noise->seed = mapseed + y_start; noise->perlinMap2D(nmin.X, nmin.Z); size_t index = 0; for (int z = nmin.Z; z <= nmax.Z; z++) for (int x = nmin.X; x <= nmax.X; x++, index++) { float noiseval = noise->result[index]; if (noiseval < nthresh) continue; if (biomemap && !biomes.empty()) { std::unordered_set<u8>::const_iterator it = biomes.find(biomemap[index]); if (it == biomes.end()) continue; } u16 height = pr.range(column_height_min, column_height_max); int ymidpoint = y_start + noiseval; int y0 = MYMAX(nmin.Y, ymidpoint - height * (1 - column_midpoint_factor)); int y1 = MYMIN(nmax.Y, y0 + height - 1); for (int y = y0; y <= y1; y++) { u32 i = vm->m_area.index(x, y, z); if (!vm->m_area.contains(i)) continue; if (!CONTAINS(c_wherein, vm->m_data[i].getContent())) continue; vm->m_data[i] = n_ore; } } } /////////////////////////////////////////////////////////////////////////////// OrePuff::~OrePuff() { delete noise_puff_top; delete noise_puff_bottom; } void OrePuff::generate(MMVManip *vm, int mapseed, u32 blockseed, v3s16 nmin, v3s16 nmax, u8 *biomemap) { PcgRandom pr(blockseed + 4234); MapNode n_ore(c_ore, 0, ore_param2); int y_start = pr.range(nmin.Y, nmax.Y); if (!noise) { int sx = nmax.X - nmin.X + 1; int sz = nmax.Z - nmin.Z + 1; noise = new Noise(&np, 0, sx, sz); noise_puff_top = new Noise(&np_puff_top, 0, sx, sz); noise_puff_bottom = new Noise(&np_puff_bottom, 0, sx, sz); } noise->seed = mapseed + y_start; noise->perlinMap2D(nmin.X, nmin.Z); bool noise_generated = false; size_t index = 0; for (int z = nmin.Z; z <= nmax.Z; z++) for (int x = nmin.X; x <= nmax.X; x++, index++) { float noiseval = noise->result[index]; if (noiseval < nthresh) continue; if (biomemap && !biomes.empty()) { std::unordered_set<u8>::const_iterator it = biomes.find(biomemap[index]); if (it == biomes.end()) continue; } if (!noise_generated) { noise_generated = true; noise_puff_top->perlinMap2D(nmin.X, nmin.Z); noise_puff_bottom->perlinMap2D(nmin.X, nmin.Z); } float ntop = noise_puff_top->result[index]; float nbottom = noise_puff_bottom->result[index]; if (!(flags & OREFLAG_PUFF_CLIFFS)) { float ndiff = noiseval - nthresh; if (ndiff < 1.0f) { ntop *= ndiff; nbottom *= ndiff; } } int ymid = y_start; int y0 = ymid - nbottom; int y1 = ymid + ntop; if ((flags & OREFLAG_PUFF_ADDITIVE) && (y0 > y1)) SWAP(int, y0, y1); for (int y = y0; y <= y1; y++) { u32 i = vm->m_area.index(x, y, z); if (!vm->m_area.contains(i)) continue; if (!CONTAINS(c_wherein, vm->m_data[i].getContent())) continue; vm->m_data[i] = n_ore; } } } /////////////////////////////////////////////////////////////////////////////// void OreBlob::generate(MMVManip *vm, int mapseed, u32 blockseed, v3s16 nmin, v3s16 nmax, u8 *biomemap) { PcgRandom pr(blockseed + 2404); MapNode n_ore(c_ore, 0, ore_param2); u32 sizex = (nmax.X - nmin.X + 1); u32 volume = (nmax.X - nmin.X + 1) * (nmax.Y - nmin.Y + 1) * (nmax.Z - nmin.Z + 1); u32 csize = clust_size; u32 nblobs = volume / clust_scarcity; if (!noise) noise = new Noise(&np, mapseed, csize, csize, csize); for (u32 i = 0; i != nblobs; i++) { int x0 = pr.range(nmin.X, nmax.X - csize + 1); int y0 = pr.range(nmin.Y, nmax.Y - csize + 1); int z0 = pr.range(nmin.Z, nmax.Z - csize + 1); if (biomemap && !biomes.empty()) { u32 bmapidx = sizex * (z0 - nmin.Z) + (x0 - nmin.X); std::unordered_set<u8>::const_iterator it = biomes.find(biomemap[bmapidx]); if (it == biomes.end()) continue; } bool noise_generated = false; noise->seed = blockseed + i; size_t index = 0; for (u32 z1 = 0; z1 != csize; z1++) for (u32 y1 = 0; y1 != csize; y1++) for (u32 x1 = 0; x1 != csize; x1++, index++) { u32 i = vm->m_area.index(x0 + x1, y0 + y1, z0 + z1); if (!CONTAINS(c_wherein, vm->m_data[i].getContent())) continue; // Lazily generate noise only if there's a chance of ore being placed // This simple optimization makes calls 6x faster on average if (!noise_generated) { noise_generated = true; noise->perlinMap3D(x0, y0, z0); } float noiseval = noise->result[index]; float xdist = (s32)x1 - (s32)csize / 2; float ydist = (s32)y1 - (s32)csize / 2; float zdist = (s32)z1 - (s32)csize / 2; noiseval -= std::sqrt(xdist * xdist + ydist * ydist + zdist * zdist) / csize; if (noiseval < nthresh) continue; vm->m_data[i] = n_ore; } } } /////////////////////////////////////////////////////////////////////////////// OreVein::~OreVein() { delete noise2; } void OreVein::generate(MMVManip *vm, int mapseed, u32 blockseed, v3s16 nmin, v3s16 nmax, u8 *biomemap) { PcgRandom pr(blockseed + 520); MapNode n_ore(c_ore, 0, ore_param2); int sizex = nmax.X - nmin.X + 1; int sizey = nmax.Y - nmin.Y + 1; // Because this ore uses 3D noise the perlinmap Y size can be different in // different mapchunks due to ore Y limits. So recreate the noise objects // if Y size has changed. // Because these noise objects are created multiple times for this ore type // it is necessary to 'delete' them here. if (!noise || sizey != sizey_prev) { delete noise; delete noise2; int sizez = nmax.Z - nmin.Z + 1; noise = new Noise(&np, mapseed, sizex, sizey, sizez); noise2 = new Noise(&np, mapseed + 436, sizex, sizey, sizez); sizey_prev = sizey; } bool noise_generated = false; size_t index = 0; for (int z = nmin.Z; z <= nmax.Z; z++) for (int y = nmin.Y; y <= nmax.Y; y++) for (int x = nmin.X; x <= nmax.X; x++, index++) { u32 i = vm->m_area.index(x, y, z); if (!vm->m_area.contains(i)) continue; if (!CONTAINS(c_wherein, vm->m_data[i].getContent())) continue; if (biomemap && !biomes.empty()) { u32 bmapidx = sizex * (z - nmin.Z) + (x - nmin.X); std::unordered_set<u8>::const_iterator it = biomes.find(biomemap[bmapidx]); if (it == biomes.end()) continue; } // Same lazy generation optimization as in OreBlob if (!noise_generated) { noise_generated = true; noise->perlinMap3D(nmin.X, nmin.Y, nmin.Z); noise2->perlinMap3D(nmin.X, nmin.Y, nmin.Z); } // randval ranges from -1..1 float randval = (float)pr.next() / (pr.RANDOM_RANGE / 2) - 1.f; float noiseval = contour(noise->result[index]); float noiseval2 = contour(noise2->result[index]); if (noiseval * noiseval2 + randval * random_factor < nthresh) continue; vm->m_data[i] = n_ore; } } /////////////////////////////////////////////////////////////////////////////// OreStratum::~OreStratum() { delete noise_stratum_thickness; } void OreStratum::generate(MMVManip *vm, int mapseed, u32 blockseed, v3s16 nmin, v3s16 nmax, u8 *biomemap) { PcgRandom pr(blockseed + 4234); MapNode n_ore(c_ore, 0, ore_param2); if (flags & OREFLAG_USE_NOISE) { if (!noise) { int sx = nmax.X - nmin.X + 1; int sz = nmax.Z - nmin.Z + 1; noise = new Noise(&np, 0, sx, sz); } noise->perlinMap2D(nmin.X, nmin.Z); } if (flags & OREFLAG_USE_NOISE2) { if (!noise_stratum_thickness) { int sx = nmax.X - nmin.X + 1; int sz = nmax.Z - nmin.Z + 1; noise_stratum_thickness = new Noise(&np_stratum_thickness, 0, sx, sz); } noise_stratum_thickness->perlinMap2D(nmin.X, nmin.Z); } size_t index = 0; for (int z = nmin.Z; z <= nmax.Z; z++) for (int x = nmin.X; x <= nmax.X; x++, index++) { if (biomemap && !biomes.empty()) { std::unordered_set<u8>::const_iterator it = biomes.find(biomemap[index]); if (it == biomes.end()) continue; } int y0; int y1; if (flags & OREFLAG_USE_NOISE) { float nhalfthick = ((flags & OREFLAG_USE_NOISE2) ? noise_stratum_thickness->result[index] : (float)stratum_thickness) / 2.0f; float nmid = noise->result[index]; y0 = MYMAX(nmin.Y, std::ceil(nmid - nhalfthick)); y1 = MYMIN(nmax.Y, nmid + nhalfthick); } else { // Simple horizontal stratum y0 = nmin.Y; y1 = nmax.Y; } for (int y = y0; y <= y1; y++) { if (pr.range(1, clust_scarcity) != 1) continue; u32 i = vm->m_area.index(x, y, z); if (!vm->m_area.contains(i)) continue; if (!CONTAINS(c_wherein, vm->m_data[i].getContent())) continue; vm->m_data[i] = n_ore; } } }
pgimeno/minetest
src/mapgen/mg_ore.cpp
C++
mit
12,740
/* Minetest Copyright (C) 2014-2018 kwolekr, Ryan Kwolek <kwolekr@minetest.net> Copyright (C) 2015-2018 paramat 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. */ #pragma once #include <unordered_set> #include "objdef.h" #include "noise.h" #include "nodedef.h" class Noise; class Mapgen; class MMVManip; /////////////////// Ore generation flags #define OREFLAG_ABSHEIGHT 0x01 // Non-functional but kept to not break flags #define OREFLAG_PUFF_CLIFFS 0x02 #define OREFLAG_PUFF_ADDITIVE 0x04 #define OREFLAG_USE_NOISE 0x08 #define OREFLAG_USE_NOISE2 0x10 enum OreType { ORE_SCATTER, ORE_SHEET, ORE_PUFF, ORE_BLOB, ORE_VEIN, ORE_STRATUM, }; extern FlagDesc flagdesc_ore[]; class Ore : public ObjDef, public NodeResolver { public: static const bool NEEDS_NOISE = false; content_t c_ore; // the node to place std::vector<content_t> c_wherein; // the nodes to be placed in u32 clust_scarcity; // ore cluster has a 1-in-clust_scarcity chance of appearing at a node s16 clust_num_ores; // how many ore nodes are in a chunk s16 clust_size; // how large (in nodes) a chunk of ore is s16 y_min; s16 y_max; u8 ore_param2; // to set node-specific attributes u32 flags = 0; // attributes for this ore float nthresh; // threshold for noise at which an ore is placed NoiseParams np; // noise for distribution of clusters (NULL for uniform scattering) Noise *noise = nullptr; std::unordered_set<u8> biomes; Ore() = default;; virtual ~Ore(); virtual void resolveNodeNames(); size_t placeOre(Mapgen *mg, u32 blockseed, v3s16 nmin, v3s16 nmax); virtual void generate(MMVManip *vm, int mapseed, u32 blockseed, v3s16 nmin, v3s16 nmax, u8 *biomemap) = 0; }; class OreScatter : public Ore { public: static const bool NEEDS_NOISE = false; virtual void generate(MMVManip *vm, int mapseed, u32 blockseed, v3s16 nmin, v3s16 nmax, u8 *biomemap); }; class OreSheet : public Ore { public: static const bool NEEDS_NOISE = true; u16 column_height_min; u16 column_height_max; float column_midpoint_factor; virtual void generate(MMVManip *vm, int mapseed, u32 blockseed, v3s16 nmin, v3s16 nmax, u8 *biomemap); }; class OrePuff : public Ore { public: static const bool NEEDS_NOISE = true; NoiseParams np_puff_top; NoiseParams np_puff_bottom; Noise *noise_puff_top = nullptr; Noise *noise_puff_bottom = nullptr; OrePuff() = default; virtual ~OrePuff(); virtual void generate(MMVManip *vm, int mapseed, u32 blockseed, v3s16 nmin, v3s16 nmax, u8 *biomemap); }; class OreBlob : public Ore { public: static const bool NEEDS_NOISE = true; virtual void generate(MMVManip *vm, int mapseed, u32 blockseed, v3s16 nmin, v3s16 nmax, u8 *biomemap); }; class OreVein : public Ore { public: static const bool NEEDS_NOISE = true; float random_factor; Noise *noise2 = nullptr; int sizey_prev = 0; OreVein() = default; virtual ~OreVein(); virtual void generate(MMVManip *vm, int mapseed, u32 blockseed, v3s16 nmin, v3s16 nmax, u8 *biomemap); }; class OreStratum : public Ore { public: static const bool NEEDS_NOISE = false; NoiseParams np_stratum_thickness; Noise *noise_stratum_thickness = nullptr; u16 stratum_thickness; OreStratum() = default; virtual ~OreStratum(); virtual void generate(MMVManip *vm, int mapseed, u32 blockseed, v3s16 nmin, v3s16 nmax, u8 *biomemap); }; class OreManager : public ObjDefManager { public: OreManager(IGameDef *gamedef); virtual ~OreManager() = default; const char *getObjectTitle() const { return "ore"; } static Ore *create(OreType type) { switch (type) { case ORE_SCATTER: return new OreScatter; case ORE_SHEET: return new OreSheet; case ORE_PUFF: return new OrePuff; case ORE_BLOB: return new OreBlob; case ORE_VEIN: return new OreVein; case ORE_STRATUM: return new OreStratum; default: return nullptr; } } void clear(); size_t placeAllOres(Mapgen *mg, u32 blockseed, v3s16 nmin, v3s16 nmax); };
pgimeno/minetest
src/mapgen/mg_ore.h
C++
mit
4,648
/* Minetest Copyright (C) 2014-2018 kwolekr, Ryan Kwolek <kwolekr@minetest.net> Copyright (C) 2015-2018 paramat 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 <fstream> #include <typeinfo> #include "mg_schematic.h" #include "server.h" #include "mapgen.h" #include "emerge.h" #include "map.h" #include "mapblock.h" #include "log.h" #include "util/numeric.h" #include "util/serialize.h" #include "serialization.h" #include "filesys.h" #include "voxelalgorithms.h" /////////////////////////////////////////////////////////////////////////////// SchematicManager::SchematicManager(Server *server) : ObjDefManager(server, OBJDEF_SCHEMATIC), m_server(server) { } void SchematicManager::clear() { EmergeManager *emerge = m_server->getEmergeManager(); // Remove all dangling references in Decorations DecorationManager *decomgr = emerge->decomgr; for (size_t i = 0; i != decomgr->getNumObjects(); i++) { Decoration *deco = (Decoration *)decomgr->getRaw(i); try { DecoSchematic *dschem = dynamic_cast<DecoSchematic *>(deco); if (dschem) dschem->schematic = NULL; } catch (const std::bad_cast &) { } } ObjDefManager::clear(); } /////////////////////////////////////////////////////////////////////////////// Schematic::Schematic() = default; Schematic::~Schematic() { delete []schemdata; delete []slice_probs; } void Schematic::resolveNodeNames() { getIdsFromNrBacklog(&c_nodes, true, CONTENT_AIR); size_t bufsize = size.X * size.Y * size.Z; for (size_t i = 0; i != bufsize; i++) { content_t c_original = schemdata[i].getContent(); content_t c_new = c_nodes[c_original]; schemdata[i].setContent(c_new); } } void Schematic::blitToVManip(MMVManip *vm, v3s16 p, Rotation rot, bool force_place) { sanity_check(m_ndef != NULL); int xstride = 1; int ystride = size.X; int zstride = size.X * size.Y; s16 sx = size.X; s16 sy = size.Y; s16 sz = size.Z; int i_start, i_step_x, i_step_z; switch (rot) { case ROTATE_90: i_start = sx - 1; i_step_x = zstride; i_step_z = -xstride; SWAP(s16, sx, sz); break; case ROTATE_180: i_start = zstride * (sz - 1) + sx - 1; i_step_x = -xstride; i_step_z = -zstride; break; case ROTATE_270: i_start = zstride * (sz - 1); i_step_x = -zstride; i_step_z = xstride; SWAP(s16, sx, sz); break; default: i_start = 0; i_step_x = xstride; i_step_z = zstride; } s16 y_map = p.Y; for (s16 y = 0; y != sy; y++) { if ((slice_probs[y] != MTSCHEM_PROB_ALWAYS) && (slice_probs[y] <= myrand_range(1, MTSCHEM_PROB_ALWAYS))) continue; for (s16 z = 0; z != sz; z++) { u32 i = z * i_step_z + y * ystride + i_start; for (s16 x = 0; x != sx; x++, i += i_step_x) { v3s16 pos(p.X + x, y_map, p.Z + z); if (!vm->m_area.contains(pos)) continue; if (schemdata[i].getContent() == CONTENT_IGNORE) continue; u8 placement_prob = schemdata[i].param1 & MTSCHEM_PROB_MASK; bool force_place_node = schemdata[i].param1 & MTSCHEM_FORCE_PLACE; if (placement_prob == MTSCHEM_PROB_NEVER) continue; u32 vi = vm->m_area.index(pos); if (!force_place && !force_place_node) { content_t c = vm->m_data[vi].getContent(); if (c != CONTENT_AIR && c != CONTENT_IGNORE) continue; } if ((placement_prob != MTSCHEM_PROB_ALWAYS) && (placement_prob <= myrand_range(1, MTSCHEM_PROB_ALWAYS))) continue; vm->m_data[vi] = schemdata[i]; vm->m_data[vi].param1 = 0; if (rot) vm->m_data[vi].rotateAlongYAxis(m_ndef, rot); } } y_map++; } } bool Schematic::placeOnVManip(MMVManip *vm, v3s16 p, u32 flags, Rotation rot, bool force_place) { assert(vm != NULL); assert(schemdata != NULL); sanity_check(m_ndef != NULL); //// Determine effective rotation and effective schematic dimensions if (rot == ROTATE_RAND) rot = (Rotation)myrand_range(ROTATE_0, ROTATE_270); v3s16 s = (rot == ROTATE_90 || rot == ROTATE_270) ? v3s16(size.Z, size.Y, size.X) : size; //// Adjust placement position if necessary if (flags & DECO_PLACE_CENTER_X) p.X -= (s.X - 1) / 2; if (flags & DECO_PLACE_CENTER_Y) p.Y -= (s.Y - 1) / 2; if (flags & DECO_PLACE_CENTER_Z) p.Z -= (s.Z - 1) / 2; blitToVManip(vm, p, rot, force_place); return vm->m_area.contains(VoxelArea(p, p + s - v3s16(1, 1, 1))); } void Schematic::placeOnMap(ServerMap *map, v3s16 p, u32 flags, Rotation rot, bool force_place) { std::map<v3s16, MapBlock *> lighting_modified_blocks; std::map<v3s16, MapBlock *> modified_blocks; std::map<v3s16, MapBlock *>::iterator it; assert(map != NULL); assert(schemdata != NULL); sanity_check(m_ndef != NULL); //// Determine effective rotation and effective schematic dimensions if (rot == ROTATE_RAND) rot = (Rotation)myrand_range(ROTATE_0, ROTATE_270); v3s16 s = (rot == ROTATE_90 || rot == ROTATE_270) ? v3s16(size.Z, size.Y, size.X) : size; //// Adjust placement position if necessary if (flags & DECO_PLACE_CENTER_X) p.X -= (s.X - 1) / 2; if (flags & DECO_PLACE_CENTER_Y) p.Y -= (s.Y - 1) / 2; if (flags & DECO_PLACE_CENTER_Z) p.Z -= (s.Z - 1) / 2; //// Create VManip for effected area, emerge our area, modify area //// inside VManip, then blit back. v3s16 bp1 = getNodeBlockPos(p); v3s16 bp2 = getNodeBlockPos(p + s - v3s16(1, 1, 1)); MMVManip vm(map); vm.initialEmerge(bp1, bp2); blitToVManip(&vm, p, rot, force_place); voxalgo::blit_back_with_light(map, &vm, &modified_blocks); //// Carry out post-map-modification actions //// Create & dispatch map modification events to observers MapEditEvent event; event.type = MEET_OTHER; for (it = modified_blocks.begin(); it != modified_blocks.end(); ++it) event.modified_blocks.insert(it->first); map->dispatchEvent(&event); } bool Schematic::deserializeFromMts(std::istream *is, std::vector<std::string> *names) { std::istream &ss = *is; content_t cignore = CONTENT_IGNORE; bool have_cignore = false; //// Read signature u32 signature = readU32(ss); if (signature != MTSCHEM_FILE_SIGNATURE) { errorstream << __FUNCTION__ << ": invalid schematic " "file" << std::endl; return false; } //// Read version u16 version = readU16(ss); if (version > MTSCHEM_FILE_VER_HIGHEST_READ) { errorstream << __FUNCTION__ << ": unsupported schematic " "file version" << std::endl; return false; } //// Read size size = readV3S16(ss); //// Read Y-slice probability values delete []slice_probs; slice_probs = new u8[size.Y]; for (int y = 0; y != size.Y; y++) slice_probs[y] = (version >= 3) ? readU8(ss) : MTSCHEM_PROB_ALWAYS_OLD; //// Read node names u16 nidmapcount = readU16(ss); for (int i = 0; i != nidmapcount; i++) { std::string name = deSerializeString(ss); // Instances of "ignore" from v1 are converted to air (and instances // are fixed to have MTSCHEM_PROB_NEVER later on). if (name == "ignore") { name = "air"; cignore = i; have_cignore = true; } names->push_back(name); } //// Read node data size_t nodecount = size.X * size.Y * size.Z; delete []schemdata; schemdata = new MapNode[nodecount]; MapNode::deSerializeBulk(ss, SER_FMT_VER_HIGHEST_READ, schemdata, nodecount, 2, 2, true); // Fix probability values for nodes that were ignore; removed in v2 if (version < 2) { for (size_t i = 0; i != nodecount; i++) { if (schemdata[i].param1 == 0) schemdata[i].param1 = MTSCHEM_PROB_ALWAYS_OLD; if (have_cignore && schemdata[i].getContent() == cignore) schemdata[i].param1 = MTSCHEM_PROB_NEVER; } } // Fix probability values for probability range truncation introduced in v4 if (version < 4) { for (s16 y = 0; y != size.Y; y++) slice_probs[y] >>= 1; for (size_t i = 0; i != nodecount; i++) schemdata[i].param1 >>= 1; } return true; } bool Schematic::serializeToMts(std::ostream *os, const std::vector<std::string> &names) { std::ostream &ss = *os; writeU32(ss, MTSCHEM_FILE_SIGNATURE); // signature writeU16(ss, MTSCHEM_FILE_VER_HIGHEST_WRITE); // version writeV3S16(ss, size); // schematic size for (int y = 0; y != size.Y; y++) // Y slice probabilities writeU8(ss, slice_probs[y]); writeU16(ss, names.size()); // name count for (size_t i = 0; i != names.size(); i++) ss << serializeString(names[i]); // node names // compressed bulk node data MapNode::serializeBulk(ss, SER_FMT_VER_HIGHEST_WRITE, schemdata, size.X * size.Y * size.Z, 2, 2, true); return true; } bool Schematic::serializeToLua(std::ostream *os, const std::vector<std::string> &names, bool use_comments, u32 indent_spaces) { std::ostream &ss = *os; std::string indent("\t"); if (indent_spaces > 0) indent.assign(indent_spaces, ' '); //// Write header { ss << "schematic = {" << std::endl; ss << indent << "size = " << "{x=" << size.X << ", y=" << size.Y << ", z=" << size.Z << "}," << std::endl; } //// Write y-slice probabilities { ss << indent << "yslice_prob = {" << std::endl; for (u16 y = 0; y != size.Y; y++) { u8 probability = slice_probs[y] & MTSCHEM_PROB_MASK; ss << indent << indent << "{" << "ypos=" << y << ", prob=" << (u16)probability * 2 << "}," << std::endl; } ss << indent << "}," << std::endl; } //// Write node data { ss << indent << "data = {" << std::endl; u32 i = 0; for (u16 z = 0; z != size.Z; z++) for (u16 y = 0; y != size.Y; y++) { if (use_comments) { ss << std::endl << indent << indent << "-- z=" << z << ", y=" << y << std::endl; } for (u16 x = 0; x != size.X; x++, i++) { u8 probability = schemdata[i].param1 & MTSCHEM_PROB_MASK; bool force_place = schemdata[i].param1 & MTSCHEM_FORCE_PLACE; ss << indent << indent << "{" << "name=\"" << names[schemdata[i].getContent()] << "\", prob=" << (u16)probability * 2 << ", param2=" << (u16)schemdata[i].param2; if (force_place) ss << ", force_place=true"; ss << "}," << std::endl; } } ss << indent << "}," << std::endl; } ss << "}" << std::endl; return true; } bool Schematic::loadSchematicFromFile(const std::string &filename, const NodeDefManager *ndef, StringMap *replace_names) { std::ifstream is(filename.c_str(), std::ios_base::binary); if (!is.good()) { errorstream << __FUNCTION__ << ": unable to open file '" << filename << "'" << std::endl; return false; } size_t origsize = m_nodenames.size(); if (!deserializeFromMts(&is, &m_nodenames)) return false; m_nnlistsizes.push_back(m_nodenames.size() - origsize); name = filename; if (replace_names) { for (size_t i = origsize; i < m_nodenames.size(); i++) { std::string &node_name = m_nodenames[i]; StringMap::iterator it = replace_names->find(node_name); if (it != replace_names->end()) node_name = it->second; } } if (ndef) ndef->pendNodeResolve(this); return true; } bool Schematic::saveSchematicToFile(const std::string &filename, const NodeDefManager *ndef) { MapNode *orig_schemdata = schemdata; std::vector<std::string> ndef_nodenames; std::vector<std::string> *names; if (m_resolve_done && ndef == NULL) ndef = m_ndef; if (ndef) { names = &ndef_nodenames; u32 volume = size.X * size.Y * size.Z; schemdata = new MapNode[volume]; for (u32 i = 0; i != volume; i++) schemdata[i] = orig_schemdata[i]; generate_nodelist_and_update_ids(schemdata, volume, names, ndef); } else { // otherwise, use the names we have on hand in the list names = &m_nodenames; } std::ostringstream os(std::ios_base::binary); bool status = serializeToMts(&os, *names); if (ndef) { delete []schemdata; schemdata = orig_schemdata; } if (!status) return false; return fs::safeWriteToFile(filename, os.str()); } bool Schematic::getSchematicFromMap(Map *map, v3s16 p1, v3s16 p2) { MMVManip *vm = new MMVManip(map); v3s16 bp1 = getNodeBlockPos(p1); v3s16 bp2 = getNodeBlockPos(p2); vm->initialEmerge(bp1, bp2); size = p2 - p1 + 1; slice_probs = new u8[size.Y]; for (s16 y = 0; y != size.Y; y++) slice_probs[y] = MTSCHEM_PROB_ALWAYS; schemdata = new MapNode[size.X * size.Y * size.Z]; u32 i = 0; for (s16 z = p1.Z; z <= p2.Z; z++) for (s16 y = p1.Y; y <= p2.Y; y++) { u32 vi = vm->m_area.index(p1.X, y, z); for (s16 x = p1.X; x <= p2.X; x++, i++, vi++) { schemdata[i] = vm->m_data[vi]; schemdata[i].param1 = MTSCHEM_PROB_ALWAYS; } } delete vm; return true; } void Schematic::applyProbabilities(v3s16 p0, std::vector<std::pair<v3s16, u8> > *plist, std::vector<std::pair<s16, u8> > *splist) { for (size_t i = 0; i != plist->size(); i++) { v3s16 p = (*plist)[i].first - p0; int index = p.Z * (size.Y * size.X) + p.Y * size.X + p.X; if (index < size.Z * size.Y * size.X) { u8 prob = (*plist)[i].second; schemdata[index].param1 = prob; // trim unnecessary node names from schematic if (prob == MTSCHEM_PROB_NEVER) schemdata[index].setContent(CONTENT_AIR); } } for (size_t i = 0; i != splist->size(); i++) { s16 y = (*splist)[i].first - p0.Y; slice_probs[y] = (*splist)[i].second; } } void generate_nodelist_and_update_ids(MapNode *nodes, size_t nodecount, std::vector<std::string> *usednodes, const NodeDefManager *ndef) { std::unordered_map<content_t, content_t> nodeidmap; content_t numids = 0; for (size_t i = 0; i != nodecount; i++) { content_t id; content_t c = nodes[i].getContent(); std::unordered_map<content_t, content_t>::const_iterator it = nodeidmap.find(c); if (it == nodeidmap.end()) { id = numids; numids++; usednodes->push_back(ndef->get(c).name); nodeidmap.insert(std::make_pair(c, id)); } else { id = it->second; } nodes[i].setContent(id); } }
pgimeno/minetest
src/mapgen/mg_schematic.cpp
C++
mit
14,363
/* Minetest Copyright (C) 2014-2018 kwolekr, Ryan Kwolek <kwolekr@minetest.net> Copyright (C) 2015-2018 paramat 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. */ #pragma once #include <map> #include "mg_decoration.h" #include "util/string.h" class Map; class ServerMap; class Mapgen; class MMVManip; class PseudoRandom; class NodeResolver; class Server; /* Minetest Schematic File Format All values are stored in big-endian byte order. [u32] signature: 'MTSM' [u16] version: 4 [u16] size X [u16] size Y [u16] size Z For each Y: [u8] slice probability value [Name-ID table] Name ID Mapping Table [u16] name-id count For each name-id mapping: [u16] name length [u8[]] name ZLib deflated { For each node in schematic: (for z, y, x) [u16] content For each node in schematic: [u8] param1 bit 0-6: probability bit 7: specific node force placement For each node in schematic: [u8] param2 } Version changes: 1 - Initial version 2 - Fixed messy never/always place; 0 probability is now never, 0xFF is always 3 - Added y-slice probabilities; this allows for variable height structures 4 - Compressed range of node occurence prob., added per-node force placement bit */ //// Schematic constants #define MTSCHEM_FILE_SIGNATURE 0x4d54534d // 'MTSM' #define MTSCHEM_FILE_VER_HIGHEST_READ 4 #define MTSCHEM_FILE_VER_HIGHEST_WRITE 4 #define MTSCHEM_PROB_MASK 0x7F #define MTSCHEM_PROB_NEVER 0x00 #define MTSCHEM_PROB_ALWAYS 0x7F #define MTSCHEM_PROB_ALWAYS_OLD 0xFF #define MTSCHEM_FORCE_PLACE 0x80 enum SchematicType { SCHEMATIC_NORMAL, }; enum SchematicFormatType { SCHEM_FMT_HANDLE, SCHEM_FMT_MTS, SCHEM_FMT_LUA, }; class Schematic : public ObjDef, public NodeResolver { public: Schematic(); virtual ~Schematic(); virtual void resolveNodeNames(); bool loadSchematicFromFile(const std::string &filename, const NodeDefManager *ndef, StringMap *replace_names = NULL); bool saveSchematicToFile(const std::string &filename, const NodeDefManager *ndef); bool getSchematicFromMap(Map *map, v3s16 p1, v3s16 p2); bool deserializeFromMts(std::istream *is, std::vector<std::string> *names); bool serializeToMts(std::ostream *os, const std::vector<std::string> &names); bool serializeToLua(std::ostream *os, const std::vector<std::string> &names, bool use_comments, u32 indent_spaces); void blitToVManip(MMVManip *vm, v3s16 p, Rotation rot, bool force_place); bool placeOnVManip(MMVManip *vm, v3s16 p, u32 flags, Rotation rot, bool force_place); void placeOnMap(ServerMap *map, v3s16 p, u32 flags, Rotation rot, bool force_place); void applyProbabilities(v3s16 p0, std::vector<std::pair<v3s16, u8> > *plist, std::vector<std::pair<s16, u8> > *splist); std::vector<content_t> c_nodes; u32 flags = 0; v3s16 size; MapNode *schemdata = nullptr; u8 *slice_probs = nullptr; }; class SchematicManager : public ObjDefManager { public: SchematicManager(Server *server); virtual ~SchematicManager() = default; virtual void clear(); const char *getObjectTitle() const { return "schematic"; } static Schematic *create(SchematicType type) { return new Schematic; } private: Server *m_server; }; void generate_nodelist_and_update_ids(MapNode *nodes, size_t nodecount, std::vector<std::string> *usednodes, const NodeDefManager *ndef);
pgimeno/minetest
src/mapgen/mg_schematic.h
C++
mit
3,991
/* Minetest Copyright (C) 2010-2018 celeron55, Perttu Ahola <celeron55@gmail.com>, Copyright (C) 2012-2018 RealBadAngel, Maciej Kasatkin Copyright (C) 2015-2018 paramat 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 "irr_v3d.h" #include <stack> #include "util/pointer.h" #include "util/numeric.h" #include "map.h" #include "mapblock.h" #include "serverenvironment.h" #include "nodedef.h" #include "treegen.h" #include "voxelalgorithms.h" namespace treegen { void make_tree(MMVManip &vmanip, v3s16 p0, bool is_apple_tree, const NodeDefManager *ndef, s32 seed) { /* NOTE: Tree-placing code is currently duplicated in the engine and in games that have saplings; both are deprecated but not replaced yet */ MapNode treenode(ndef->getId("mapgen_tree")); MapNode leavesnode(ndef->getId("mapgen_leaves")); MapNode applenode(ndef->getId("mapgen_apple")); PseudoRandom pr(seed); s16 trunk_h = pr.range(4, 5); v3s16 p1 = p0; for (s16 ii = 0; ii < trunk_h; ii++) { if (vmanip.m_area.contains(p1)) { u32 vi = vmanip.m_area.index(p1); vmanip.m_data[vi] = treenode; } p1.Y++; } // p1 is now the last piece of the trunk p1.Y -= 1; VoxelArea leaves_a(v3s16(-2, -1, -2), v3s16(2, 2, 2)); Buffer<u8> leaves_d(leaves_a.getVolume()); for (s32 i = 0; i < leaves_a.getVolume(); i++) leaves_d[i] = 0; // Force leaves at near the end of the trunk s16 d = 1; for (s16 z = -d; z <= d; z++) for (s16 y = -d; y <= d; y++) for (s16 x = -d; x <= d; x++) { leaves_d[leaves_a.index(v3s16(x, y, z))] = 1; } // Add leaves randomly for (u32 iii = 0; iii < 7; iii++) { v3s16 p( pr.range(leaves_a.MinEdge.X, leaves_a.MaxEdge.X - d), pr.range(leaves_a.MinEdge.Y, leaves_a.MaxEdge.Y - d), pr.range(leaves_a.MinEdge.Z, leaves_a.MaxEdge.Z - d) ); for (s16 z = 0; z <= d; z++) for (s16 y = 0; y <= d; y++) for (s16 x = 0; x <= d; x++) { leaves_d[leaves_a.index(p + v3s16(x, y, z))] = 1; } } // Blit leaves to vmanip for (s16 z = leaves_a.MinEdge.Z; z <= leaves_a.MaxEdge.Z; z++) for (s16 y = leaves_a.MinEdge.Y; y <= leaves_a.MaxEdge.Y; y++) { v3s16 pmin(leaves_a.MinEdge.X, y, z); u32 i = leaves_a.index(pmin); u32 vi = vmanip.m_area.index(pmin + p1); for (s16 x = leaves_a.MinEdge.X; x <= leaves_a.MaxEdge.X; x++) { v3s16 p(x, y, z); if (vmanip.m_area.contains(p + p1) && (vmanip.m_data[vi].getContent() == CONTENT_AIR || vmanip.m_data[vi].getContent() == CONTENT_IGNORE)) { if (leaves_d[i] == 1) { bool is_apple = pr.range(0, 99) < 10; if (is_apple_tree && is_apple) vmanip.m_data[vi] = applenode; else vmanip.m_data[vi] = leavesnode; } } vi++; i++; } } } // L-System tree LUA spawner treegen::error spawn_ltree(ServerEnvironment *env, v3s16 p0, const NodeDefManager *ndef, const TreeDef &tree_definition) { ServerMap *map = &env->getServerMap(); std::map<v3s16, MapBlock*> modified_blocks; MMVManip vmanip(map); v3s16 tree_blockp = getNodeBlockPos(p0); treegen::error e; vmanip.initialEmerge(tree_blockp - v3s16(1, 1, 1), tree_blockp + v3s16(1, 3, 1)); e = make_ltree(vmanip, p0, ndef, tree_definition); if (e != SUCCESS) return e; voxalgo::blit_back_with_light(map, &vmanip, &modified_blocks); // Send a MEET_OTHER event MapEditEvent event; event.type = MEET_OTHER; for (auto &modified_block : modified_blocks) event.modified_blocks.insert(modified_block.first); map->dispatchEvent(&event); return SUCCESS; } //L-System tree generator treegen::error make_ltree(MMVManip &vmanip, v3s16 p0, const NodeDefManager *ndef, TreeDef tree_definition) { MapNode dirtnode(ndef->getId("mapgen_dirt")); s32 seed; if (tree_definition.explicit_seed) seed = tree_definition.seed + 14002; else seed = p0.X * 2 + p0.Y * 4 + p0.Z; // use the tree position to seed PRNG PseudoRandom ps(seed); // chance of inserting abcd rules double prop_a = 9; double prop_b = 8; double prop_c = 7; double prop_d = 6; //randomize tree growth level, minimum=2 s16 iterations = tree_definition.iterations; if (tree_definition.iterations_random_level > 0) iterations -= ps.range(0, tree_definition.iterations_random_level); if (iterations < 2) iterations = 2; s16 MAX_ANGLE_OFFSET = 5; double angle_in_radians = (double)tree_definition.angle * M_PI / 180; double angleOffset_in_radians = (s16)(ps.range(0, 1) % MAX_ANGLE_OFFSET) * M_PI / 180; //initialize rotation matrix, position and stacks for branches core::matrix4 rotation; rotation = setRotationAxisRadians(rotation, M_PI / 2, v3f(0, 0, 1)); v3f position; position.X = p0.X; position.Y = p0.Y; position.Z = p0.Z; std::stack <core::matrix4> stack_orientation; std::stack <v3f> stack_position; //generate axiom std::string axiom = tree_definition.initial_axiom; for (s16 i = 0; i < iterations; i++) { std::string temp; for (s16 j = 0; j < (s16)axiom.size(); j++) { char axiom_char = axiom.at(j); switch (axiom_char) { case 'A': temp += tree_definition.rules_a; break; case 'B': temp += tree_definition.rules_b; break; case 'C': temp += tree_definition.rules_c; break; case 'D': temp += tree_definition.rules_d; break; case 'a': if (prop_a >= ps.range(1, 10)) temp += tree_definition.rules_a; break; case 'b': if (prop_b >= ps.range(1, 10)) temp += tree_definition.rules_b; break; case 'c': if (prop_c >= ps.range(1, 10)) temp += tree_definition.rules_c; break; case 'd': if (prop_d >= ps.range(1, 10)) temp += tree_definition.rules_d; break; default: temp += axiom_char; break; } } axiom = temp; } //make sure tree is not floating in the air if (tree_definition.trunk_type == "double") { tree_node_placement( vmanip, v3f(position.X + 1, position.Y - 1, position.Z), dirtnode ); tree_node_placement( vmanip, v3f(position.X, position.Y - 1, position.Z + 1), dirtnode ); tree_node_placement( vmanip, v3f(position.X + 1, position.Y - 1, position.Z + 1), dirtnode ); } else if (tree_definition.trunk_type == "crossed") { tree_node_placement( vmanip, v3f(position.X + 1, position.Y - 1, position.Z), dirtnode ); tree_node_placement( vmanip, v3f(position.X - 1, position.Y - 1, position.Z), dirtnode ); tree_node_placement( vmanip, v3f(position.X, position.Y - 1, position.Z + 1), dirtnode ); tree_node_placement( vmanip, v3f(position.X, position.Y - 1, position.Z - 1), dirtnode ); } /* build tree out of generated axiom Key for Special L-System Symbols used in Axioms G - move forward one unit with the pen up F - move forward one unit with the pen down drawing trunks and branches f - move forward one unit with the pen down drawing leaves (100% chance) T - move forward one unit with the pen down drawing trunks only R - move forward one unit with the pen down placing fruit A - replace with rules set A B - replace with rules set B C - replace with rules set C D - replace with rules set D a - replace with rules set A, chance 90% b - replace with rules set B, chance 80% c - replace with rules set C, chance 70% d - replace with rules set D, chance 60% + - yaw the turtle right by angle degrees - - yaw the turtle left by angle degrees & - pitch the turtle down by angle degrees ^ - pitch the turtle up by angle degrees / - roll the turtle to the right by angle degrees * - roll the turtle to the left by angle degrees [ - save in stack current state info ] - recover from stack state info */ s16 x,y,z; for (s16 i = 0; i < (s16)axiom.size(); i++) { char axiom_char = axiom.at(i); core::matrix4 temp_rotation; temp_rotation.makeIdentity(); v3f dir; switch (axiom_char) { case 'G': dir = v3f(1, 0, 0); dir = transposeMatrix(rotation, dir); position += dir; break; case 'T': tree_trunk_placement( vmanip, v3f(position.X, position.Y, position.Z), tree_definition ); if (tree_definition.trunk_type == "double" && !tree_definition.thin_branches) { tree_trunk_placement( vmanip, v3f(position.X + 1, position.Y, position.Z), tree_definition ); tree_trunk_placement( vmanip, v3f(position.X, position.Y, position.Z + 1), tree_definition ); tree_trunk_placement( vmanip, v3f(position.X + 1, position.Y, position.Z + 1), tree_definition ); } else if (tree_definition.trunk_type == "crossed" && !tree_definition.thin_branches) { tree_trunk_placement( vmanip, v3f(position.X + 1, position.Y, position.Z), tree_definition ); tree_trunk_placement( vmanip, v3f(position.X - 1, position.Y, position.Z), tree_definition ); tree_trunk_placement( vmanip, v3f(position.X, position.Y, position.Z + 1), tree_definition ); tree_trunk_placement( vmanip, v3f(position.X, position.Y, position.Z - 1), tree_definition ); } dir = v3f(1, 0, 0); dir = transposeMatrix(rotation, dir); position += dir; break; case 'F': tree_trunk_placement( vmanip, v3f(position.X, position.Y, position.Z), tree_definition ); if ((stack_orientation.empty() && tree_definition.trunk_type == "double") || (!stack_orientation.empty() && tree_definition.trunk_type == "double" && !tree_definition.thin_branches)) { tree_trunk_placement( vmanip, v3f(position.X +1 , position.Y, position.Z), tree_definition ); tree_trunk_placement( vmanip, v3f(position.X, position.Y, position.Z + 1), tree_definition ); tree_trunk_placement( vmanip, v3f(position.X + 1, position.Y, position.Z + 1), tree_definition ); } else if ((stack_orientation.empty() && tree_definition.trunk_type == "crossed") || (!stack_orientation.empty() && tree_definition.trunk_type == "crossed" && !tree_definition.thin_branches)) { tree_trunk_placement( vmanip, v3f(position.X + 1, position.Y, position.Z), tree_definition ); tree_trunk_placement( vmanip, v3f(position.X - 1, position.Y, position.Z), tree_definition ); tree_trunk_placement( vmanip, v3f(position.X, position.Y, position.Z + 1), tree_definition ); tree_trunk_placement( vmanip, v3f(position.X, position.Y, position.Z - 1), tree_definition ); } if (!stack_orientation.empty()) { s16 size = 1; for (x = -size; x <= size; x++) for (y = -size; y <= size; y++) for (z = -size; z <= size; z++) { if (abs(x) == size && abs(y) == size && abs(z) == size) { tree_leaves_placement( vmanip, v3f(position.X + x + 1, position.Y + y, position.Z + z), ps.next(), tree_definition ); tree_leaves_placement( vmanip, v3f(position.X + x - 1, position.Y + y, position.Z + z), ps.next(), tree_definition ); tree_leaves_placement( vmanip,v3f(position.X + x, position.Y + y, position.Z + z + 1), ps.next(), tree_definition ); tree_leaves_placement( vmanip,v3f(position.X + x, position.Y + y, position.Z + z - 1), ps.next(), tree_definition ); } } } dir = v3f(1, 0, 0); dir = transposeMatrix(rotation, dir); position += dir; break; case 'f': tree_single_leaves_placement( vmanip, v3f(position.X, position.Y, position.Z), ps.next(), tree_definition ); dir = v3f(1, 0, 0); dir = transposeMatrix(rotation, dir); position += dir; break; case 'R': tree_fruit_placement( vmanip, v3f(position.X, position.Y, position.Z), tree_definition ); dir = v3f(1, 0, 0); dir = transposeMatrix(rotation, dir); position += dir; break; // turtle orientation commands case '[': stack_orientation.push(rotation); stack_position.push(position); break; case ']': if (stack_orientation.empty()) return UNBALANCED_BRACKETS; rotation = stack_orientation.top(); stack_orientation.pop(); position = stack_position.top(); stack_position.pop(); break; case '+': temp_rotation.makeIdentity(); temp_rotation = setRotationAxisRadians(temp_rotation, angle_in_radians + angleOffset_in_radians, v3f(0, 0, 1)); rotation *= temp_rotation; break; case '-': temp_rotation.makeIdentity(); temp_rotation = setRotationAxisRadians(temp_rotation, angle_in_radians + angleOffset_in_radians, v3f(0, 0, -1)); rotation *= temp_rotation; break; case '&': temp_rotation.makeIdentity(); temp_rotation = setRotationAxisRadians(temp_rotation, angle_in_radians + angleOffset_in_radians, v3f(0, 1, 0)); rotation *= temp_rotation; break; case '^': temp_rotation.makeIdentity(); temp_rotation = setRotationAxisRadians(temp_rotation, angle_in_radians + angleOffset_in_radians, v3f(0, -1, 0)); rotation *= temp_rotation; break; case '*': temp_rotation.makeIdentity(); temp_rotation = setRotationAxisRadians(temp_rotation, angle_in_radians, v3f(1, 0, 0)); rotation *= temp_rotation; break; case '/': temp_rotation.makeIdentity(); temp_rotation = setRotationAxisRadians(temp_rotation, angle_in_radians, v3f(-1, 0, 0)); rotation *= temp_rotation; break; default: break; } } return SUCCESS; } void tree_node_placement(MMVManip &vmanip, v3f p0, MapNode node) { v3s16 p1 = v3s16(myround(p0.X), myround(p0.Y), myround(p0.Z)); if (!vmanip.m_area.contains(p1)) return; u32 vi = vmanip.m_area.index(p1); if (vmanip.m_data[vi].getContent() != CONTENT_AIR && vmanip.m_data[vi].getContent() != CONTENT_IGNORE) return; vmanip.m_data[vmanip.m_area.index(p1)] = node; } void tree_trunk_placement(MMVManip &vmanip, v3f p0, TreeDef &tree_definition) { v3s16 p1 = v3s16(myround(p0.X), myround(p0.Y), myround(p0.Z)); if (!vmanip.m_area.contains(p1)) return; u32 vi = vmanip.m_area.index(p1); content_t current_node = vmanip.m_data[vi].getContent(); if (current_node != CONTENT_AIR && current_node != CONTENT_IGNORE && current_node != tree_definition.leavesnode.getContent() && current_node != tree_definition.leaves2node.getContent() && current_node != tree_definition.fruitnode.getContent()) return; vmanip.m_data[vi] = tree_definition.trunknode; } void tree_leaves_placement(MMVManip &vmanip, v3f p0, PseudoRandom ps, TreeDef &tree_definition) { MapNode leavesnode = tree_definition.leavesnode; if (ps.range(1, 100) > 100 - tree_definition.leaves2_chance) leavesnode = tree_definition.leaves2node; v3s16 p1 = v3s16(myround(p0.X), myround(p0.Y), myround(p0.Z)); if (!vmanip.m_area.contains(p1)) return; u32 vi = vmanip.m_area.index(p1); if (vmanip.m_data[vi].getContent() != CONTENT_AIR && vmanip.m_data[vi].getContent() != CONTENT_IGNORE) return; if (tree_definition.fruit_chance > 0) { if (ps.range(1, 100) > 100 - tree_definition.fruit_chance) vmanip.m_data[vmanip.m_area.index(p1)] = tree_definition.fruitnode; else vmanip.m_data[vmanip.m_area.index(p1)] = leavesnode; } else if (ps.range(1, 100) > 20) { vmanip.m_data[vmanip.m_area.index(p1)] = leavesnode; } } void tree_single_leaves_placement(MMVManip &vmanip, v3f p0, PseudoRandom ps, TreeDef &tree_definition) { MapNode leavesnode = tree_definition.leavesnode; if (ps.range(1, 100) > 100 - tree_definition.leaves2_chance) leavesnode = tree_definition.leaves2node; v3s16 p1 = v3s16(myround(p0.X), myround(p0.Y), myround(p0.Z)); if (!vmanip.m_area.contains(p1)) return; u32 vi = vmanip.m_area.index(p1); if (vmanip.m_data[vi].getContent() != CONTENT_AIR && vmanip.m_data[vi].getContent() != CONTENT_IGNORE) return; vmanip.m_data[vmanip.m_area.index(p1)] = leavesnode; } void tree_fruit_placement(MMVManip &vmanip, v3f p0, TreeDef &tree_definition) { v3s16 p1 = v3s16(myround(p0.X), myround(p0.Y), myround(p0.Z)); if (!vmanip.m_area.contains(p1)) return; u32 vi = vmanip.m_area.index(p1); if (vmanip.m_data[vi].getContent() != CONTENT_AIR && vmanip.m_data[vi].getContent() != CONTENT_IGNORE) return; vmanip.m_data[vmanip.m_area.index(p1)] = tree_definition.fruitnode; } irr::core::matrix4 setRotationAxisRadians(irr::core::matrix4 M, double angle, v3f axis) { double c = cos(angle); double s = sin(angle); double t = 1.0 - c; double tx = t * axis.X; double ty = t * axis.Y; double tz = t * axis.Z; double sx = s * axis.X; double sy = s * axis.Y; double sz = s * axis.Z; M[0] = tx * axis.X + c; M[1] = tx * axis.Y + sz; M[2] = tx * axis.Z - sy; M[4] = ty * axis.X - sz; M[5] = ty * axis.Y + c; M[6] = ty * axis.Z + sx; M[8] = tz * axis.X + sy; M[9] = tz * axis.Y - sx; M[10] = tz * axis.Z + c; return M; } v3f transposeMatrix(irr::core::matrix4 M, v3f v) { v3f translated; double x = M[0] * v.X + M[4] * v.Y + M[8] * v.Z +M[12]; double y = M[1] * v.X + M[5] * v.Y + M[9] * v.Z +M[13]; double z = M[2] * v.X + M[6] * v.Y + M[10] * v.Z +M[14]; translated.X = x; translated.Y = y; translated.Z = z; return translated; } void make_jungletree(MMVManip &vmanip, v3s16 p0, const NodeDefManager *ndef, s32 seed) { /* NOTE: Tree-placing code is currently duplicated in the engine and in games that have saplings; both are deprecated but not replaced yet */ content_t c_tree = ndef->getId("mapgen_jungletree"); content_t c_leaves = ndef->getId("mapgen_jungleleaves"); if (c_tree == CONTENT_IGNORE) c_tree = ndef->getId("mapgen_tree"); if (c_leaves == CONTENT_IGNORE) c_leaves = ndef->getId("mapgen_leaves"); MapNode treenode(c_tree); MapNode leavesnode(c_leaves); PseudoRandom pr(seed); for (s16 x= -1; x <= 1; x++) for (s16 z= -1; z <= 1; z++) { if (pr.range(0, 2) == 0) continue; v3s16 p1 = p0 + v3s16(x, 0, z); v3s16 p2 = p0 + v3s16(x, -1, z); u32 vi1 = vmanip.m_area.index(p1); u32 vi2 = vmanip.m_area.index(p2); if (vmanip.m_area.contains(p2) && vmanip.m_data[vi2].getContent() == CONTENT_AIR) vmanip.m_data[vi2] = treenode; else if (vmanip.m_area.contains(p1) && vmanip.m_data[vi1].getContent() == CONTENT_AIR) vmanip.m_data[vi1] = treenode; } vmanip.m_data[vmanip.m_area.index(p0)] = treenode; s16 trunk_h = pr.range(8, 12); v3s16 p1 = p0; for (s16 ii = 0; ii < trunk_h; ii++) { if (vmanip.m_area.contains(p1)) { u32 vi = vmanip.m_area.index(p1); vmanip.m_data[vi] = treenode; } p1.Y++; } // p1 is now the last piece of the trunk p1.Y -= 1; VoxelArea leaves_a(v3s16(-3, -2, -3), v3s16(3, 2, 3)); //SharedPtr<u8> leaves_d(new u8[leaves_a.getVolume()]); Buffer<u8> leaves_d(leaves_a.getVolume()); for (s32 i = 0; i < leaves_a.getVolume(); i++) leaves_d[i] = 0; // Force leaves at near the end of the trunk s16 d = 1; for (s16 z = -d; z <= d; z++) for (s16 y = -d; y <= d; y++) for (s16 x = -d; x <= d; x++) { leaves_d[leaves_a.index(v3s16(x,y,z))] = 1; } // Add leaves randomly for (u32 iii = 0; iii < 30; iii++) { v3s16 p( pr.range(leaves_a.MinEdge.X, leaves_a.MaxEdge.X - d), pr.range(leaves_a.MinEdge.Y, leaves_a.MaxEdge.Y - d), pr.range(leaves_a.MinEdge.Z, leaves_a.MaxEdge.Z - d) ); for (s16 z = 0; z <= d; z++) for (s16 y = 0; y <= d; y++) for (s16 x = 0; x <= d; x++) { leaves_d[leaves_a.index(p + v3s16(x, y, z))] = 1; } } // Blit leaves to vmanip for (s16 z = leaves_a.MinEdge.Z; z <= leaves_a.MaxEdge.Z; z++) for (s16 y = leaves_a.MinEdge.Y; y <= leaves_a.MaxEdge.Y; y++) { v3s16 pmin(leaves_a.MinEdge.X, y, z); u32 i = leaves_a.index(pmin); u32 vi = vmanip.m_area.index(pmin + p1); for (s16 x = leaves_a.MinEdge.X; x <= leaves_a.MaxEdge.X; x++) { v3s16 p(x, y, z); if (vmanip.m_area.contains(p + p1) && (vmanip.m_data[vi].getContent() == CONTENT_AIR || vmanip.m_data[vi].getContent() == CONTENT_IGNORE)) { if (leaves_d[i] == 1) vmanip.m_data[vi] = leavesnode; } vi++; i++; } } } void make_pine_tree(MMVManip &vmanip, v3s16 p0, const NodeDefManager *ndef, s32 seed) { /* NOTE: Tree-placing code is currently duplicated in the engine and in games that have saplings; both are deprecated but not replaced yet */ content_t c_tree = ndef->getId("mapgen_pine_tree"); content_t c_leaves = ndef->getId("mapgen_pine_needles"); content_t c_snow = ndef->getId("mapgen_snow"); if (c_tree == CONTENT_IGNORE) c_tree = ndef->getId("mapgen_tree"); if (c_leaves == CONTENT_IGNORE) c_leaves = ndef->getId("mapgen_leaves"); if (c_snow == CONTENT_IGNORE) c_snow = CONTENT_AIR; MapNode treenode(c_tree); MapNode leavesnode(c_leaves); MapNode snownode(c_snow); PseudoRandom pr(seed); u16 trunk_h = pr.range(9, 13); v3s16 p1 = p0; for (u16 ii = 0; ii < trunk_h; ii++) { if (vmanip.m_area.contains(p1)) { u32 vi = vmanip.m_area.index(p1); vmanip.m_data[vi] = treenode; } p1.Y++; } // Make p1 the top node of the trunk p1.Y -= 1; VoxelArea leaves_a(v3s16(-3, -6, -3), v3s16(3, 3, 3)); Buffer<u8> leaves_d(leaves_a.getVolume()); for (s32 i = 0; i < leaves_a.getVolume(); i++) leaves_d[i] = 0; // Upper branches u16 dev = 3; for (s16 yy = -1; yy <= 1; yy++) { for (s16 zz = -dev; zz <= dev; zz++) { u32 i = leaves_a.index(v3s16(-dev, yy, zz)); u32 ia = leaves_a.index(v3s16(-dev, yy+1, zz)); for (s16 xx = -dev; xx <= dev; xx++) { if (pr.range(0, 20) <= 19 - dev) { leaves_d[i] = 1; leaves_d[ia] = 2; } i++; ia++; } } dev--; } // Centre top nodes leaves_d[leaves_a.index(v3s16(0, 1, 0))] = 1; leaves_d[leaves_a.index(v3s16(0, 2, 0))] = 1; leaves_d[leaves_a.index(v3s16(0, 3, 0))] = 2; // Lower branches s16 my = -6; for (u32 iii = 0; iii < 20; iii++) { s16 xi = pr.range(-3, 2); s16 yy = pr.range(-6, -5); s16 zi = pr.range(-3, 2); if (yy > my) my = yy; for (s16 zz = zi; zz <= zi + 1; zz++) { u32 i = leaves_a.index(v3s16(xi, yy, zz)); u32 ia = leaves_a.index(v3s16(xi, yy + 1, zz)); for (s32 xx = xi; xx <= xi + 1; xx++) { leaves_d[i] = 1; if (leaves_d[ia] == 0) leaves_d[ia] = 2; i++; ia++; } } } dev = 2; for (s16 yy = my + 1; yy <= my + 2; yy++) { for (s16 zz = -dev; zz <= dev; zz++) { u32 i = leaves_a.index(v3s16(-dev, yy, zz)); u32 ia = leaves_a.index(v3s16(-dev, yy + 1, zz)); for (s16 xx = -dev; xx <= dev; xx++) { if (pr.range(0, 20) <= 19 - dev) { leaves_d[i] = 1; leaves_d[ia] = 2; } i++; ia++; } } dev--; } // Blit leaves to vmanip for (s16 z = leaves_a.MinEdge.Z; z <= leaves_a.MaxEdge.Z; z++) for (s16 y = leaves_a.MinEdge.Y; y <= leaves_a.MaxEdge.Y; y++) { v3s16 pmin(leaves_a.MinEdge.X, y, z); u32 i = leaves_a.index(pmin); u32 vi = vmanip.m_area.index(pmin + p1); for (s16 x = leaves_a.MinEdge.X; x <= leaves_a.MaxEdge.X; x++) { v3s16 p(x, y, z); if (vmanip.m_area.contains(p + p1) && (vmanip.m_data[vi].getContent() == CONTENT_AIR || vmanip.m_data[vi].getContent() == CONTENT_IGNORE || vmanip.m_data[vi] == snownode)) { if (leaves_d[i] == 1) vmanip.m_data[vi] = leavesnode; else if (leaves_d[i] == 2) vmanip.m_data[vi] = snownode; } vi++; i++; } } } }; // namespace treegen
pgimeno/minetest
src/mapgen/treegen.cpp
C++
mit
24,059
/* Minetest Copyright (C) 2010-2018 celeron55, Perttu Ahola <celeron55@gmail.com>, Copyright (C) 2012-2018 RealBadAngel, Maciej Kasatkin Copyright (C) 2015-2018 paramat 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. */ #pragma once #include <matrix4.h> #include "noise.h" class MMVManip; class NodeDefManager; class ServerEnvironment; namespace treegen { enum error { SUCCESS, UNBALANCED_BRACKETS }; struct TreeDef { std::string initial_axiom; std::string rules_a; std::string rules_b; std::string rules_c; std::string rules_d; MapNode trunknode; MapNode leavesnode; MapNode leaves2node; int leaves2_chance; int angle; int iterations; int iterations_random_level; std::string trunk_type; bool thin_branches; MapNode fruitnode; int fruit_chance; s32 seed; bool explicit_seed; }; // Add default tree void make_tree(MMVManip &vmanip, v3s16 p0, bool is_apple_tree, const NodeDefManager *ndef, s32 seed); // Add jungle tree void make_jungletree(MMVManip &vmanip, v3s16 p0, const NodeDefManager *ndef, s32 seed); // Add pine tree void make_pine_tree(MMVManip &vmanip, v3s16 p0, const NodeDefManager *ndef, s32 seed); // Add L-Systems tree (used by engine) treegen::error make_ltree(MMVManip &vmanip, v3s16 p0, const NodeDefManager *ndef, TreeDef tree_definition); // Spawn L-systems tree from LUA treegen::error spawn_ltree (ServerEnvironment *env, v3s16 p0, const NodeDefManager *ndef, const TreeDef &tree_definition); // L-System tree gen helper functions void tree_node_placement(MMVManip &vmanip, v3f p0, MapNode node); void tree_trunk_placement(MMVManip &vmanip, v3f p0, TreeDef &tree_definition); void tree_leaves_placement(MMVManip &vmanip, v3f p0, PseudoRandom ps, TreeDef &tree_definition); void tree_single_leaves_placement(MMVManip &vmanip, v3f p0, PseudoRandom ps, TreeDef &tree_definition); void tree_fruit_placement(MMVManip &vmanip, v3f p0, TreeDef &tree_definition); irr::core::matrix4 setRotationAxisRadians(irr::core::matrix4 M, double angle, v3f axis); v3f transposeMatrix(irr::core::matrix4 M ,v3f v); }; // namespace treegen
pgimeno/minetest
src/mapgen/treegen.h
C++
mit
2,793
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> 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 "irrlichttypes_extrabloated.h" #include "mapnode.h" #include "porting.h" #include "nodedef.h" #include "map.h" #include "content_mapnode.h" // For mapnode_translate_*_internal #include "serialization.h" // For ser_ver_supported #include "util/serialize.h" #include "log.h" #include "util/directiontables.h" #include "util/numeric.h" #include <string> #include <sstream> static const Rotation wallmounted_to_rot[] = { ROTATE_0, ROTATE_180, ROTATE_90, ROTATE_270 }; static const u8 rot_to_wallmounted[] = { 2, 4, 3, 5 }; /* MapNode */ void MapNode::getColor(const ContentFeatures &f, video::SColor *color) const { if (f.palette) { *color = (*f.palette)[param2]; return; } *color = f.color; } void MapNode::setLight(LightBank bank, u8 a_light, const ContentFeatures &f) noexcept { // If node doesn't contain light data, ignore this if(f.param_type != CPT_LIGHT) return; if(bank == LIGHTBANK_DAY) { param1 &= 0xf0; param1 |= a_light & 0x0f; } else if(bank == LIGHTBANK_NIGHT) { param1 &= 0x0f; param1 |= (a_light & 0x0f)<<4; } else assert("Invalid light bank" == NULL); } void MapNode::setLight(LightBank bank, u8 a_light, const NodeDefManager *nodemgr) { setLight(bank, a_light, nodemgr->get(*this)); } bool MapNode::isLightDayNightEq(const NodeDefManager *nodemgr) const { const ContentFeatures &f = nodemgr->get(*this); bool isEqual; if (f.param_type == CPT_LIGHT) { u8 day = MYMAX(f.light_source, param1 & 0x0f); u8 night = MYMAX(f.light_source, (param1 >> 4) & 0x0f); isEqual = day == night; } else { isEqual = true; } return isEqual; } u8 MapNode::getLight(LightBank bank, const NodeDefManager *nodemgr) const { // Select the brightest of [light source, propagated light] const ContentFeatures &f = nodemgr->get(*this); u8 light; if(f.param_type == CPT_LIGHT) light = bank == LIGHTBANK_DAY ? param1 & 0x0f : (param1 >> 4) & 0x0f; else light = 0; return MYMAX(f.light_source, light); } u8 MapNode::getLightRaw(LightBank bank, const ContentFeatures &f) const noexcept { if(f.param_type == CPT_LIGHT) return bank == LIGHTBANK_DAY ? param1 & 0x0f : (param1 >> 4) & 0x0f; return 0; } u8 MapNode::getLightNoChecks(LightBank bank, const ContentFeatures *f) const noexcept { return MYMAX(f->light_source, bank == LIGHTBANK_DAY ? param1 & 0x0f : (param1 >> 4) & 0x0f); } bool MapNode::getLightBanks(u8 &lightday, u8 &lightnight, const NodeDefManager *nodemgr) const { // Select the brightest of [light source, propagated light] const ContentFeatures &f = nodemgr->get(*this); if(f.param_type == CPT_LIGHT) { lightday = param1 & 0x0f; lightnight = (param1>>4)&0x0f; } else { lightday = 0; lightnight = 0; } if(f.light_source > lightday) lightday = f.light_source; if(f.light_source > lightnight) lightnight = f.light_source; return f.param_type == CPT_LIGHT || f.light_source != 0; } u8 MapNode::getFaceDir(const NodeDefManager *nodemgr, bool allow_wallmounted) const { const ContentFeatures &f = nodemgr->get(*this); if (f.param_type_2 == CPT2_FACEDIR || f.param_type_2 == CPT2_COLORED_FACEDIR) return (getParam2() & 0x1F) % 24; if (allow_wallmounted && (f.param_type_2 == CPT2_WALLMOUNTED || f.param_type_2 == CPT2_COLORED_WALLMOUNTED)) return wallmounted_to_facedir[getParam2() & 0x07]; return 0; } u8 MapNode::getWallMounted(const NodeDefManager *nodemgr) const { const ContentFeatures &f = nodemgr->get(*this); if (f.param_type_2 == CPT2_WALLMOUNTED || f.param_type_2 == CPT2_COLORED_WALLMOUNTED) return getParam2() & 0x07; return 0; } v3s16 MapNode::getWallMountedDir(const NodeDefManager *nodemgr) const { switch(getWallMounted(nodemgr)) { case 0: default: return v3s16(0,1,0); case 1: return v3s16(0,-1,0); case 2: return v3s16(1,0,0); case 3: return v3s16(-1,0,0); case 4: return v3s16(0,0,1); case 5: return v3s16(0,0,-1); } } void MapNode::rotateAlongYAxis(const NodeDefManager *nodemgr, Rotation rot) { ContentParamType2 cpt2 = nodemgr->get(*this).param_type_2; if (cpt2 == CPT2_FACEDIR || cpt2 == CPT2_COLORED_FACEDIR) { static const u8 rotate_facedir[24 * 4] = { // Table value = rotated facedir // Columns: 0, 90, 180, 270 degrees rotation around vertical axis // Rotation is anticlockwise as seen from above (+Y) 0, 1, 2, 3, // Initial facedir 0 to 3 1, 2, 3, 0, 2, 3, 0, 1, 3, 0, 1, 2, 4, 13, 10, 19, // 4 to 7 5, 14, 11, 16, 6, 15, 8, 17, 7, 12, 9, 18, 8, 17, 6, 15, // 8 to 11 9, 18, 7, 12, 10, 19, 4, 13, 11, 16, 5, 14, 12, 9, 18, 7, // 12 to 15 13, 10, 19, 4, 14, 11, 16, 5, 15, 8, 17, 6, 16, 5, 14, 11, // 16 to 19 17, 6, 15, 8, 18, 7, 12, 9, 19, 4, 13, 10, 20, 23, 22, 21, // 20 to 23 21, 20, 23, 22, 22, 21, 20, 23, 23, 22, 21, 20 }; u8 facedir = (param2 & 31) % 24; u8 index = facedir * 4 + rot; param2 &= ~31; param2 |= rotate_facedir[index]; } else if (cpt2 == CPT2_WALLMOUNTED || cpt2 == CPT2_COLORED_WALLMOUNTED) { u8 wmountface = (param2 & 7); if (wmountface <= 1) return; Rotation oldrot = wallmounted_to_rot[wmountface - 2]; param2 &= ~7; param2 |= rot_to_wallmounted[(oldrot - rot) & 3]; } } void transformNodeBox(const MapNode &n, const NodeBox &nodebox, const NodeDefManager *nodemgr, std::vector<aabb3f> *p_boxes, u8 neighbors = 0) { std::vector<aabb3f> &boxes = *p_boxes; if (nodebox.type == NODEBOX_FIXED || nodebox.type == NODEBOX_LEVELED) { const std::vector<aabb3f> &fixed = nodebox.fixed; int facedir = n.getFaceDir(nodemgr, true); u8 axisdir = facedir>>2; facedir&=0x03; for (aabb3f box : fixed) { if (nodebox.type == NODEBOX_LEVELED) box.MaxEdge.Y = (-0.5f + n.getLevel(nodemgr) / 64.0f) * BS; switch (axisdir) { case 0: if(facedir == 1) { box.MinEdge.rotateXZBy(-90); box.MaxEdge.rotateXZBy(-90); } else if(facedir == 2) { box.MinEdge.rotateXZBy(180); box.MaxEdge.rotateXZBy(180); } else if(facedir == 3) { box.MinEdge.rotateXZBy(90); box.MaxEdge.rotateXZBy(90); } break; case 1: // z+ box.MinEdge.rotateYZBy(90); box.MaxEdge.rotateYZBy(90); if(facedir == 1) { box.MinEdge.rotateXYBy(90); box.MaxEdge.rotateXYBy(90); } else if(facedir == 2) { box.MinEdge.rotateXYBy(180); box.MaxEdge.rotateXYBy(180); } else if(facedir == 3) { box.MinEdge.rotateXYBy(-90); box.MaxEdge.rotateXYBy(-90); } break; case 2: //z- box.MinEdge.rotateYZBy(-90); box.MaxEdge.rotateYZBy(-90); if(facedir == 1) { box.MinEdge.rotateXYBy(-90); box.MaxEdge.rotateXYBy(-90); } else if(facedir == 2) { box.MinEdge.rotateXYBy(180); box.MaxEdge.rotateXYBy(180); } else if(facedir == 3) { box.MinEdge.rotateXYBy(90); box.MaxEdge.rotateXYBy(90); } break; case 3: //x+ box.MinEdge.rotateXYBy(-90); box.MaxEdge.rotateXYBy(-90); if(facedir == 1) { box.MinEdge.rotateYZBy(90); box.MaxEdge.rotateYZBy(90); } else if(facedir == 2) { box.MinEdge.rotateYZBy(180); box.MaxEdge.rotateYZBy(180); } else if(facedir == 3) { box.MinEdge.rotateYZBy(-90); box.MaxEdge.rotateYZBy(-90); } break; case 4: //x- box.MinEdge.rotateXYBy(90); box.MaxEdge.rotateXYBy(90); if(facedir == 1) { box.MinEdge.rotateYZBy(-90); box.MaxEdge.rotateYZBy(-90); } else if(facedir == 2) { box.MinEdge.rotateYZBy(180); box.MaxEdge.rotateYZBy(180); } else if(facedir == 3) { box.MinEdge.rotateYZBy(90); box.MaxEdge.rotateYZBy(90); } break; case 5: box.MinEdge.rotateXYBy(-180); box.MaxEdge.rotateXYBy(-180); if(facedir == 1) { box.MinEdge.rotateXZBy(90); box.MaxEdge.rotateXZBy(90); } else if(facedir == 2) { box.MinEdge.rotateXZBy(180); box.MaxEdge.rotateXZBy(180); } else if(facedir == 3) { box.MinEdge.rotateXZBy(-90); box.MaxEdge.rotateXZBy(-90); } break; default: break; } box.repair(); boxes.push_back(box); } } else if(nodebox.type == NODEBOX_WALLMOUNTED) { v3s16 dir = n.getWallMountedDir(nodemgr); // top if(dir == v3s16(0,1,0)) { boxes.push_back(nodebox.wall_top); } // bottom else if(dir == v3s16(0,-1,0)) { boxes.push_back(nodebox.wall_bottom); } // side else { v3f vertices[2] = { nodebox.wall_side.MinEdge, nodebox.wall_side.MaxEdge }; for (v3f &vertex : vertices) { if(dir == v3s16(-1,0,0)) vertex.rotateXZBy(0); if(dir == v3s16(1,0,0)) vertex.rotateXZBy(180); if(dir == v3s16(0,0,-1)) vertex.rotateXZBy(90); if(dir == v3s16(0,0,1)) vertex.rotateXZBy(-90); } aabb3f box = aabb3f(vertices[0]); box.addInternalPoint(vertices[1]); boxes.push_back(box); } } else if (nodebox.type == NODEBOX_CONNECTED) { size_t boxes_size = boxes.size(); boxes_size += nodebox.fixed.size(); if (neighbors & 1) boxes_size += nodebox.connect_top.size(); else boxes_size += nodebox.disconnected_top.size(); if (neighbors & 2) boxes_size += nodebox.connect_bottom.size(); else boxes_size += nodebox.disconnected_bottom.size(); if (neighbors & 4) boxes_size += nodebox.connect_front.size(); else boxes_size += nodebox.disconnected_front.size(); if (neighbors & 8) boxes_size += nodebox.connect_left.size(); else boxes_size += nodebox.disconnected_left.size(); if (neighbors & 16) boxes_size += nodebox.connect_back.size(); else boxes_size += nodebox.disconnected_back.size(); if (neighbors & 32) boxes_size += nodebox.connect_right.size(); else boxes_size += nodebox.disconnected_right.size(); if (neighbors == 0) boxes_size += nodebox.disconnected.size(); if (neighbors < 4) boxes_size += nodebox.disconnected_sides.size(); boxes.reserve(boxes_size); #define BOXESPUSHBACK(c) \ for (std::vector<aabb3f>::const_iterator \ it = (c).begin(); \ it != (c).end(); ++it) \ (boxes).push_back(*it); BOXESPUSHBACK(nodebox.fixed); if (neighbors & 1) { BOXESPUSHBACK(nodebox.connect_top); } else { BOXESPUSHBACK(nodebox.disconnected_top); } if (neighbors & 2) { BOXESPUSHBACK(nodebox.connect_bottom); } else { BOXESPUSHBACK(nodebox.disconnected_bottom); } if (neighbors & 4) { BOXESPUSHBACK(nodebox.connect_front); } else { BOXESPUSHBACK(nodebox.disconnected_front); } if (neighbors & 8) { BOXESPUSHBACK(nodebox.connect_left); } else { BOXESPUSHBACK(nodebox.disconnected_left); } if (neighbors & 16) { BOXESPUSHBACK(nodebox.connect_back); } else { BOXESPUSHBACK(nodebox.disconnected_back); } if (neighbors & 32) { BOXESPUSHBACK(nodebox.connect_right); } else { BOXESPUSHBACK(nodebox.disconnected_right); } if (neighbors == 0) { BOXESPUSHBACK(nodebox.disconnected); } if (neighbors < 4) { BOXESPUSHBACK(nodebox.disconnected_sides); } } else // NODEBOX_REGULAR { boxes.emplace_back(-BS/2,-BS/2,-BS/2,BS/2,BS/2,BS/2); } } static inline void getNeighborConnectingFace( const v3s16 &p, const NodeDefManager *nodedef, Map *map, MapNode n, u8 bitmask, u8 *neighbors) { MapNode n2 = map->getNodeNoEx(p); if (nodedef->nodeboxConnects(n, n2, bitmask)) *neighbors |= bitmask; } u8 MapNode::getNeighbors(v3s16 p, Map *map) const { const NodeDefManager *nodedef = map->getNodeDefManager(); u8 neighbors = 0; const ContentFeatures &f = nodedef->get(*this); // locate possible neighboring nodes to connect to if (f.drawtype == NDT_NODEBOX && f.node_box.type == NODEBOX_CONNECTED) { v3s16 p2 = p; p2.Y++; getNeighborConnectingFace(p2, nodedef, map, *this, 1, &neighbors); p2 = p; p2.Y--; getNeighborConnectingFace(p2, nodedef, map, *this, 2, &neighbors); p2 = p; p2.Z--; getNeighborConnectingFace(p2, nodedef, map, *this, 4, &neighbors); p2 = p; p2.X--; getNeighborConnectingFace(p2, nodedef, map, *this, 8, &neighbors); p2 = p; p2.Z++; getNeighborConnectingFace(p2, nodedef, map, *this, 16, &neighbors); p2 = p; p2.X++; getNeighborConnectingFace(p2, nodedef, map, *this, 32, &neighbors); } return neighbors; } void MapNode::getNodeBoxes(const NodeDefManager *nodemgr, std::vector<aabb3f> *boxes, u8 neighbors) const { const ContentFeatures &f = nodemgr->get(*this); transformNodeBox(*this, f.node_box, nodemgr, boxes, neighbors); } void MapNode::getCollisionBoxes(const NodeDefManager *nodemgr, std::vector<aabb3f> *boxes, u8 neighbors) const { const ContentFeatures &f = nodemgr->get(*this); if (f.collision_box.fixed.empty()) transformNodeBox(*this, f.node_box, nodemgr, boxes, neighbors); else transformNodeBox(*this, f.collision_box, nodemgr, boxes, neighbors); } void MapNode::getSelectionBoxes(const NodeDefManager *nodemgr, std::vector<aabb3f> *boxes, u8 neighbors) const { const ContentFeatures &f = nodemgr->get(*this); transformNodeBox(*this, f.selection_box, nodemgr, boxes, neighbors); } u8 MapNode::getMaxLevel(const NodeDefManager *nodemgr) const { const ContentFeatures &f = nodemgr->get(*this); // todo: after update in all games leave only if (f.param_type_2 == if( f.liquid_type == LIQUID_FLOWING || f.param_type_2 == CPT2_FLOWINGLIQUID) return LIQUID_LEVEL_MAX; if(f.leveled || f.param_type_2 == CPT2_LEVELED) return LEVELED_MAX; return 0; } u8 MapNode::getLevel(const NodeDefManager *nodemgr) const { const ContentFeatures &f = nodemgr->get(*this); // todo: after update in all games leave only if (f.param_type_2 == if(f.liquid_type == LIQUID_SOURCE) return LIQUID_LEVEL_SOURCE; if (f.param_type_2 == CPT2_FLOWINGLIQUID) return getParam2() & LIQUID_LEVEL_MASK; if(f.liquid_type == LIQUID_FLOWING) // can remove if all param_type_2 setted return getParam2() & LIQUID_LEVEL_MASK; if (f.param_type_2 == CPT2_LEVELED) { u8 level = getParam2() & LEVELED_MASK; if (level) return level; } if (f.leveled > LEVELED_MAX) return LEVELED_MAX; return f.leveled; } u8 MapNode::setLevel(const NodeDefManager *nodemgr, s8 level) { u8 rest = 0; const ContentFeatures &f = nodemgr->get(*this); if (f.param_type_2 == CPT2_FLOWINGLIQUID || f.liquid_type == LIQUID_FLOWING || f.liquid_type == LIQUID_SOURCE) { if (level <= 0) { // liquid can’t exist with zero level setContent(CONTENT_AIR); return 0; } if (level >= LIQUID_LEVEL_SOURCE) { rest = level - LIQUID_LEVEL_SOURCE; setContent(nodemgr->getId(f.liquid_alternative_source)); setParam2(0); } else { setContent(nodemgr->getId(f.liquid_alternative_flowing)); setParam2((level & LIQUID_LEVEL_MASK) | (getParam2() & ~LIQUID_LEVEL_MASK)); } } else if (f.param_type_2 == CPT2_LEVELED) { if (level < 0) { // zero means default for a leveled nodebox rest = level; level = 0; } else if (level > LEVELED_MAX) { rest = level - LEVELED_MAX; level = LEVELED_MAX; } setParam2((level & LEVELED_MASK) | (getParam2() & ~LEVELED_MASK)); } return rest; } u8 MapNode::addLevel(const NodeDefManager *nodemgr, s8 add) { s8 level = getLevel(nodemgr); level += add; return setLevel(nodemgr, level); } u32 MapNode::serializedLength(u8 version) { if(!ser_ver_supported(version)) throw VersionMismatchException("ERROR: MapNode format not supported"); if (version == 0) return 1; if (version <= 9) return 2; if (version <= 23) return 3; return 4; } void MapNode::serialize(u8 *dest, u8 version) const { if(!ser_ver_supported(version)) throw VersionMismatchException("ERROR: MapNode format not supported"); // Can't do this anymore; we have 16-bit dynamically allocated node IDs // in memory; conversion just won't work in this direction. if(version < 24) throw SerializationError("MapNode::serialize: serialization to " "version < 24 not possible"); writeU16(dest+0, param0); writeU8(dest+2, param1); writeU8(dest+3, param2); } void MapNode::deSerialize(u8 *source, u8 version) { if(!ser_ver_supported(version)) throw VersionMismatchException("ERROR: MapNode format not supported"); if(version <= 21) { deSerialize_pre22(source, version); return; } if(version >= 24){ param0 = readU16(source+0); param1 = readU8(source+2); param2 = readU8(source+3); }else{ param0 = readU8(source+0); param1 = readU8(source+1); param2 = readU8(source+2); if(param0 > 0x7F){ param0 |= ((param2&0xF0)<<4); param2 &= 0x0F; } } } void MapNode::serializeBulk(std::ostream &os, int version, const MapNode *nodes, u32 nodecount, u8 content_width, u8 params_width, bool compressed) { if (!ser_ver_supported(version)) throw VersionMismatchException("ERROR: MapNode format not supported"); sanity_check(content_width == 2); sanity_check(params_width == 2); // Can't do this anymore; we have 16-bit dynamically allocated node IDs // in memory; conversion just won't work in this direction. if (version < 24) throw SerializationError("MapNode::serializeBulk: serialization to " "version < 24 not possible"); size_t databuf_size = nodecount * (content_width + params_width); u8 *databuf = new u8[databuf_size]; u32 start1 = content_width * nodecount; u32 start2 = (content_width + 1) * nodecount; // Serialize content for (u32 i = 0; i < nodecount; i++) { writeU16(&databuf[i * 2], nodes[i].param0); writeU8(&databuf[start1 + i], nodes[i].param1); writeU8(&databuf[start2 + i], nodes[i].param2); } /* Compress data to output stream */ if (compressed) compressZlib(databuf, databuf_size, os); else os.write((const char*) &databuf[0], databuf_size); delete [] databuf; } // Deserialize bulk node data void MapNode::deSerializeBulk(std::istream &is, int version, MapNode *nodes, u32 nodecount, u8 content_width, u8 params_width, bool compressed) { if(!ser_ver_supported(version)) throw VersionMismatchException("ERROR: MapNode format not supported"); if (version < 22 || (content_width != 1 && content_width != 2) || params_width != 2) FATAL_ERROR("Deserialize bulk node data error"); // Uncompress or read data u32 len = nodecount * (content_width + params_width); SharedBuffer<u8> databuf(len); if(compressed) { std::ostringstream os(std::ios_base::binary); decompressZlib(is, os); std::string s = os.str(); if(s.size() != len) throw SerializationError("deSerializeBulkNodes: " "decompress resulted in invalid size"); memcpy(&databuf[0], s.c_str(), len); } else { is.read((char*) &databuf[0], len); if(is.eof() || is.fail()) throw SerializationError("deSerializeBulkNodes: " "failed to read bulk node data"); } // Deserialize content if(content_width == 1) { for(u32 i=0; i<nodecount; i++) nodes[i].param0 = readU8(&databuf[i]); } else if(content_width == 2) { for(u32 i=0; i<nodecount; i++) nodes[i].param0 = readU16(&databuf[i*2]); } // Deserialize param1 u32 start1 = content_width * nodecount; for(u32 i=0; i<nodecount; i++) nodes[i].param1 = readU8(&databuf[start1 + i]); // Deserialize param2 u32 start2 = (content_width + 1) * nodecount; if(content_width == 1) { for(u32 i=0; i<nodecount; i++) { nodes[i].param2 = readU8(&databuf[start2 + i]); if(nodes[i].param0 > 0x7F){ nodes[i].param0 <<= 4; nodes[i].param0 |= (nodes[i].param2&0xF0)>>4; nodes[i].param2 &= 0x0F; } } } else if(content_width == 2) { for(u32 i=0; i<nodecount; i++) nodes[i].param2 = readU8(&databuf[start2 + i]); } } /* Legacy serialization */ void MapNode::deSerialize_pre22(const u8 *source, u8 version) { if(version <= 1) { param0 = source[0]; } else if(version <= 9) { param0 = source[0]; param1 = source[1]; } else { param0 = source[0]; param1 = source[1]; param2 = source[2]; if(param0 > 0x7f){ param0 <<= 4; param0 |= (param2&0xf0)>>4; param2 &= 0x0f; } } // Convert special values from old version to new if(version <= 19) { // In these versions, CONTENT_IGNORE and CONTENT_AIR // are 255 and 254 // Version 19 is fucked up with sometimes the old values and sometimes not if(param0 == 255) param0 = CONTENT_IGNORE; else if(param0 == 254) param0 = CONTENT_AIR; } // Translate to our known version *this = mapnode_translate_to_internal(*this, version); }
pgimeno/minetest
src/mapnode.cpp
C++
mit
21,147
/* Minetest Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com> 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. */ #pragma once #include "irrlichttypes_bloated.h" #include "light.h" #include <string> #include <vector> class NodeDefManager; class Map; /* Naming scheme: - Material = irrlicht's Material class - Content = (content_t) content of a node - Tile = TileSpec at some side of a node of some content type */ typedef u16 content_t; /* The maximum node ID that can be registered by mods. This must be significantly lower than the maximum content_t value, so that there is enough room for dummy node IDs, which are created when a MapBlock containing unknown node names is loaded from disk. */ #define MAX_REGISTERED_CONTENT 0x7fffU /* A solid walkable node with the texture unknown_node.png. For example, used on the client to display unregistered node IDs (instead of expanding the vector of node definitions each time such a node is received). */ #define CONTENT_UNKNOWN 125 /* The common material through which the player can walk and which is transparent to light */ #define CONTENT_AIR 126 /* Ignored node. Unloaded chunks are considered to consist of this. Several other methods return this when an error occurs. Also, during map generation this means the node has not been set yet. Doesn't create faces with anything and is considered being out-of-map in the game map. */ #define CONTENT_IGNORE 127 enum LightBank { LIGHTBANK_DAY, LIGHTBANK_NIGHT }; /* Simple rotation enum. */ enum Rotation { ROTATE_0, ROTATE_90, ROTATE_180, ROTATE_270, ROTATE_RAND, }; /* Masks for MapNode.param2 of flowing liquids */ #define LIQUID_LEVEL_MASK 0x07 #define LIQUID_FLOW_DOWN_MASK 0x08 //#define LIQUID_LEVEL_MASK 0x3f // better finite water //#define LIQUID_FLOW_DOWN_MASK 0x40 // not used when finite water /* maximum amount of liquid in a block */ #define LIQUID_LEVEL_MAX LIQUID_LEVEL_MASK #define LIQUID_LEVEL_SOURCE (LIQUID_LEVEL_MAX+1) #define LIQUID_INFINITY_MASK 0x80 //0b10000000 // mask for leveled nodebox param2 #define LEVELED_MASK 0x7F #define LEVELED_MAX LEVELED_MASK struct ContentFeatures; /* This is the stuff what the whole world consists of. */ struct MapNode { /* Main content */ u16 param0; /* Misc parameter. Initialized to 0. - For light_propagates() blocks, this is light intensity, stored logarithmically from 0 to LIGHT_MAX. Sunlight is LIGHT_SUN, which is LIGHT_MAX+1. - Contains 2 values, day- and night lighting. Each takes 4 bits. - Uhh... well, most blocks have light or nothing in here. */ u8 param1; /* The second parameter. Initialized to 0. E.g. direction for torches and flowing water. */ u8 param2; MapNode() = default; MapNode(content_t content, u8 a_param1=0, u8 a_param2=0) noexcept : param0(content), param1(a_param1), param2(a_param2) { } bool operator==(const MapNode &other) const noexcept { return (param0 == other.param0 && param1 == other.param1 && param2 == other.param2); } // To be used everywhere content_t getContent() const noexcept { return param0; } void setContent(content_t c) noexcept { param0 = c; } u8 getParam1() const noexcept { return param1; } void setParam1(u8 p) noexcept { param1 = p; } u8 getParam2() const noexcept { return param2; } void setParam2(u8 p) noexcept { param2 = p; } /*! * Returns the color of the node. * * \param f content features of this node * \param color output, contains the node's color. */ void getColor(const ContentFeatures &f, video::SColor *color) const; void setLight(LightBank bank, u8 a_light, const ContentFeatures &f) noexcept; void setLight(LightBank bank, u8 a_light, const NodeDefManager *nodemgr); /** * Check if the light value for night differs from the light value for day. * * @return If the light values are equal, returns true; otherwise false */ bool isLightDayNightEq(const NodeDefManager *nodemgr) const; u8 getLight(LightBank bank, const NodeDefManager *nodemgr) const; /*! * Returns the node's light level from param1. * If the node emits light, it is ignored. * \param f the ContentFeatures of this node. */ u8 getLightRaw(LightBank bank, const ContentFeatures &f) const noexcept; /** * This function differs from getLight(LightBank bank, NodeDefManager *nodemgr) * in that the ContentFeatures of the node in question are not retrieved by * the function itself. Thus, if you have already called nodemgr->get() to * get the ContentFeatures you pass it to this function instead of the * function getting ContentFeatures itself. Since NodeDefManager::get() * is relatively expensive this can lead to significant performance * improvements in some situations. Call this function if (and only if) * you have already retrieved the ContentFeatures by calling * NodeDefManager::get() for the node you're working with and the * pre-conditions listed are true. * * @pre f != NULL * @pre f->param_type == CPT_LIGHT */ u8 getLightNoChecks(LightBank bank, const ContentFeatures *f) const noexcept; bool getLightBanks(u8 &lightday, u8 &lightnight, const NodeDefManager *nodemgr) const; // 0 <= daylight_factor <= 1000 // 0 <= return value <= LIGHT_SUN u8 getLightBlend(u32 daylight_factor, const NodeDefManager *nodemgr) const { u8 lightday = 0; u8 lightnight = 0; getLightBanks(lightday, lightnight, nodemgr); return blend_light(daylight_factor, lightday, lightnight); } u8 getFaceDir(const NodeDefManager *nodemgr, bool allow_wallmounted = false) const; u8 getWallMounted(const NodeDefManager *nodemgr) const; v3s16 getWallMountedDir(const NodeDefManager *nodemgr) const; void rotateAlongYAxis(const NodeDefManager *nodemgr, Rotation rot); /*! * Checks which neighbors does this node connect to. * * \param p coordinates of the node */ u8 getNeighbors(v3s16 p, Map *map) const; /* Gets list of node boxes (used for rendering (NDT_NODEBOX)) */ void getNodeBoxes(const NodeDefManager *nodemgr, std::vector<aabb3f> *boxes, u8 neighbors = 0) const; /* Gets list of selection boxes */ void getSelectionBoxes(const NodeDefManager *nodemg, std::vector<aabb3f> *boxes, u8 neighbors = 0) const; /* Gets list of collision boxes */ void getCollisionBoxes(const NodeDefManager *nodemgr, std::vector<aabb3f> *boxes, u8 neighbors = 0) const; /* Liquid helpers */ u8 getMaxLevel(const NodeDefManager *nodemgr) const; u8 getLevel(const NodeDefManager *nodemgr) const; u8 setLevel(const NodeDefManager *nodemgr, s8 level = 1); u8 addLevel(const NodeDefManager *nodemgr, s8 add = 1); /* Serialization functions */ static u32 serializedLength(u8 version); void serialize(u8 *dest, u8 version) const; void deSerialize(u8 *source, u8 version); // Serializes or deserializes a list of nodes in bulk format (first the // content of all nodes, then the param1 of all nodes, then the param2 // of all nodes). // version = serialization version. Must be >= 22 // content_width = the number of bytes of content per node // params_width = the number of bytes of params per node // compressed = true to zlib-compress output static void serializeBulk(std::ostream &os, int version, const MapNode *nodes, u32 nodecount, u8 content_width, u8 params_width, bool compressed); static void deSerializeBulk(std::istream &is, int version, MapNode *nodes, u32 nodecount, u8 content_width, u8 params_width, bool compressed); private: // Deprecated serialization methods void deSerialize_pre22(const u8 *source, u8 version); };
pgimeno/minetest
src/mapnode.h
C++
mit
8,299
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> 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 "mapsector.h" #include "exceptions.h" #include "mapblock.h" #include "serialization.h" MapSector::MapSector(Map *parent, v2s16 pos, IGameDef *gamedef): m_parent(parent), m_pos(pos), m_gamedef(gamedef) { } MapSector::~MapSector() { deleteBlocks(); } void MapSector::deleteBlocks() { // Clear cache m_block_cache = nullptr; // Delete all for (auto &block : m_blocks) { delete block.second; } // Clear container m_blocks.clear(); } MapBlock * MapSector::getBlockBuffered(s16 y) { MapBlock *block; if (m_block_cache && y == m_block_cache_y) { return m_block_cache; } // If block doesn't exist, return NULL std::unordered_map<s16, MapBlock*>::const_iterator n = m_blocks.find(y); block = (n != m_blocks.end() ? n->second : nullptr); // Cache the last result m_block_cache_y = y; m_block_cache = block; return block; } MapBlock * MapSector::getBlockNoCreateNoEx(s16 y) { return getBlockBuffered(y); } MapBlock * MapSector::createBlankBlockNoInsert(s16 y) { assert(getBlockBuffered(y) == NULL); // Pre-condition v3s16 blockpos_map(m_pos.X, y, m_pos.Y); MapBlock *block = new MapBlock(m_parent, blockpos_map, m_gamedef); return block; } MapBlock * MapSector::createBlankBlock(s16 y) { MapBlock *block = createBlankBlockNoInsert(y); m_blocks[y] = block; return block; } void MapSector::insertBlock(MapBlock *block) { s16 block_y = block->getPos().Y; MapBlock *block2 = getBlockBuffered(block_y); if (block2) { throw AlreadyExistsException("Block already exists"); } v2s16 p2d(block->getPos().X, block->getPos().Z); assert(p2d == m_pos); // Insert into container m_blocks[block_y] = block; } void MapSector::deleteBlock(MapBlock *block) { s16 block_y = block->getPos().Y; // Clear from cache m_block_cache = nullptr; // Remove from container m_blocks.erase(block_y); // Delete delete block; } void MapSector::getBlocks(MapBlockVect &dest) { for (auto &block : m_blocks) { dest.push_back(block.second); } }
pgimeno/minetest
src/mapsector.cpp
C++
mit
2,774
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> 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. */ #pragma once #include "irrlichttypes.h" #include "irr_v2d.h" #include "mapblock.h" #include <ostream> #include <map> #include <vector> class Map; class IGameDef; /* This is an Y-wise stack of MapBlocks. */ #define MAPSECTOR_SERVER 0 #define MAPSECTOR_CLIENT 1 class MapSector { public: MapSector(Map *parent, v2s16 pos, IGameDef *gamedef); virtual ~MapSector(); void deleteBlocks(); v2s16 getPos() { return m_pos; } MapBlock * getBlockNoCreateNoEx(s16 y); MapBlock * createBlankBlockNoInsert(s16 y); MapBlock * createBlankBlock(s16 y); void insertBlock(MapBlock *block); void deleteBlock(MapBlock *block); void getBlocks(MapBlockVect &dest); bool empty() const { return m_blocks.empty(); } protected: // The pile of MapBlocks std::unordered_map<s16, MapBlock*> m_blocks; Map *m_parent; // Position on parent (in MapBlock widths) v2s16 m_pos; IGameDef *m_gamedef; // Last-used block is cached here for quicker access. // Be sure to set this to nullptr when the cached block is deleted MapBlock *m_block_cache = nullptr; s16 m_block_cache_y; /* Private methods */ MapBlock *getBlockBuffered(s16 y); };
pgimeno/minetest
src/mapsector.h
C++
mit
1,936
/* Minetest Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com> 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 "metadata.h" #include "log.h" /* Metadata */ void Metadata::clear() { m_stringvars.clear(); m_modified = true; } bool Metadata::empty() const { return m_stringvars.empty(); } size_t Metadata::size() const { return m_stringvars.size(); } bool Metadata::contains(const std::string &name) const { return m_stringvars.find(name) != m_stringvars.end(); } bool Metadata::operator==(const Metadata &other) const { if (size() != other.size()) return false; for (const auto &sv : m_stringvars) { if (!other.contains(sv.first) || other.getString(sv.first) != sv.second) return false; } return true; } const std::string &Metadata::getString(const std::string &name, u16 recursion) const { StringMap::const_iterator it = m_stringvars.find(name); if (it == m_stringvars.end()) { static const std::string empty_string = std::string(""); return empty_string; } return resolveString(it->second, recursion); } bool Metadata::getStringToRef( const std::string &name, std::string &str, u16 recursion) const { StringMap::const_iterator it = m_stringvars.find(name); if (it == m_stringvars.end()) { return false; } str = resolveString(it->second, recursion); return true; } /** * Sets var to name key in the metadata storage * * @param name * @param var * @return true if key-value pair is created or changed */ bool Metadata::setString(const std::string &name, const std::string &var) { if (var.empty()) { m_stringvars.erase(name); return true; } StringMap::iterator it = m_stringvars.find(name); if (it != m_stringvars.end() && it->second == var) { return false; } m_stringvars[name] = var; m_modified = true; return true; } const std::string &Metadata::resolveString(const std::string &str, u16 recursion) const { if (recursion <= 1 && str.substr(0, 2) == "${" && str[str.length() - 1] == '}') { return getString(str.substr(2, str.length() - 3), recursion + 1); } return str; }
pgimeno/minetest
src/metadata.cpp
C++
mit
2,735
/* Minetest Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com> 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. */ #pragma once #include "irr_v3d.h" #include <iostream> #include <vector> #include "util/string.h" class Metadata { bool m_modified = false; public: virtual ~Metadata() = default; virtual void clear(); virtual bool empty() const; bool operator==(const Metadata &other) const; inline bool operator!=(const Metadata &other) const { return !(*this == other); } // // Key-value related // size_t size() const; bool contains(const std::string &name) const; const std::string &getString(const std::string &name, u16 recursion = 0) const; bool getStringToRef(const std::string &name, std::string &str, u16 recursion = 0) const; virtual bool setString(const std::string &name, const std::string &var); inline bool removeString(const std::string &name) { return setString(name, ""); } const StringMap &getStrings() const { return m_stringvars; } // Add support for variable names in values const std::string &resolveString(const std::string &str, u16 recursion = 0) const; inline bool isModified() const { return m_modified; } inline void setModified(bool v) { m_modified = v; } protected: StringMap m_stringvars; };
pgimeno/minetest
src/metadata.h
C++
mit
1,933
/* Minetest Copyright (C) 2017 nerzhul, Loic Blot <loic.blot@unix-experience.fr> 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 "modchannels.h" #include <algorithm> #include <cassert> #include "util/basic_macros.h" bool ModChannel::registerConsumer(session_t peer_id) { // ignore if peer_id already joined if (CONTAINS(m_client_consumers, peer_id)) return false; m_client_consumers.push_back(peer_id); return true; } bool ModChannel::removeConsumer(session_t peer_id) { bool found = false; auto peer_removal_fct = [peer_id, &found](u16 p) { if (p == peer_id) found = true; return p == peer_id; }; m_client_consumers.erase( std::remove_if(m_client_consumers.begin(), m_client_consumers.end(), peer_removal_fct), m_client_consumers.end()); return found; } bool ModChannel::canWrite() const { return m_state == MODCHANNEL_STATE_READ_WRITE; } void ModChannel::setState(ModChannelState state) { assert(state != MODCHANNEL_STATE_INIT); m_state = state; } bool ModChannelMgr::channelRegistered(const std::string &channel) const { return m_registered_channels.find(channel) != m_registered_channels.end(); } ModChannel *ModChannelMgr::getModChannel(const std::string &channel) { if (!channelRegistered(channel)) return nullptr; return m_registered_channels[channel].get(); } bool ModChannelMgr::canWriteOnChannel(const std::string &channel) const { const auto channel_it = m_registered_channels.find(channel); if (channel_it == m_registered_channels.end()) { return false; } return channel_it->second->canWrite(); } void ModChannelMgr::registerChannel(const std::string &channel) { m_registered_channels[channel] = std::unique_ptr<ModChannel>(new ModChannel(channel)); } bool ModChannelMgr::setChannelState(const std::string &channel, ModChannelState state) { if (!channelRegistered(channel)) return false; auto channel_it = m_registered_channels.find(channel); channel_it->second->setState(state); return true; } bool ModChannelMgr::removeChannel(const std::string &channel) { if (!channelRegistered(channel)) return false; m_registered_channels.erase(channel); return true; } bool ModChannelMgr::joinChannel(const std::string &channel, session_t peer_id) { if (!channelRegistered(channel)) registerChannel(channel); return m_registered_channels[channel]->registerConsumer(peer_id); } bool ModChannelMgr::leaveChannel(const std::string &channel, session_t peer_id) { if (!channelRegistered(channel)) return false; // Remove consumer from channel bool consumerRemoved = m_registered_channels[channel]->removeConsumer(peer_id); // If channel is empty, remove it if (m_registered_channels[channel]->getChannelPeers().empty()) { removeChannel(channel); } return consumerRemoved; } void ModChannelMgr::leaveAllChannels(session_t peer_id) { for (auto &channel_it : m_registered_channels) channel_it.second->removeConsumer(peer_id); } static std::vector<u16> empty_channel_list; const std::vector<u16> &ModChannelMgr::getChannelPeers(const std::string &channel) const { const auto &channel_it = m_registered_channels.find(channel); if (channel_it == m_registered_channels.end()) return empty_channel_list; return channel_it->second->getChannelPeers(); }
pgimeno/minetest
src/modchannels.cpp
C++
mit
3,920
/* Minetest Copyright (C) 2017 nerzhul, Loic Blot <loic.blot@unix-experience.fr> 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. */ #pragma once #include <unordered_map> #include <string> #include <vector> #include <memory> #include "network/networkprotocol.h" #include "irrlichttypes.h" enum ModChannelState : u8 { MODCHANNEL_STATE_INIT, MODCHANNEL_STATE_READ_WRITE, MODCHANNEL_STATE_READ_ONLY, MODCHANNEL_STATE_MAX, }; class ModChannel { public: ModChannel(const std::string &name) : m_name(name) {} ~ModChannel() = default; const std::string &getName() const { return m_name; } bool registerConsumer(session_t peer_id); bool removeConsumer(session_t peer_id); const std::vector<u16> &getChannelPeers() const { return m_client_consumers; } bool canWrite() const; void setState(ModChannelState state); private: std::string m_name; ModChannelState m_state = MODCHANNEL_STATE_INIT; std::vector<u16> m_client_consumers; }; enum ModChannelSignal : u8 { MODCHANNEL_SIGNAL_JOIN_OK, MODCHANNEL_SIGNAL_JOIN_FAILURE, MODCHANNEL_SIGNAL_LEAVE_OK, MODCHANNEL_SIGNAL_LEAVE_FAILURE, MODCHANNEL_SIGNAL_CHANNEL_NOT_REGISTERED, MODCHANNEL_SIGNAL_SET_STATE, }; class ModChannelMgr { public: ModChannelMgr() = default; ~ModChannelMgr() = default; void registerChannel(const std::string &channel); bool setChannelState(const std::string &channel, ModChannelState state); bool joinChannel(const std::string &channel, session_t peer_id); bool leaveChannel(const std::string &channel, session_t peer_id); bool channelRegistered(const std::string &channel) const; ModChannel *getModChannel(const std::string &channel); /** * This function check if a local mod can write on the channel * * @param channel * @return true if write is allowed */ bool canWriteOnChannel(const std::string &channel) const; void leaveAllChannels(session_t peer_id); const std::vector<u16> &getChannelPeers(const std::string &channel) const; private: bool removeChannel(const std::string &channel); std::unordered_map<std::string, std::unique_ptr<ModChannel>> m_registered_channels; };
pgimeno/minetest
src/modchannels.h
C++
mit
2,753