summaryrefslogtreecommitdiff
path: root/src/reflowscan.cpp
blob: fd169f1a833964b8e856959932adc686c8b52e6a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
/*
Minetest
Copyright (C) 2016 MillersMan <millersman@users.noreply.github.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 "reflowscan.h"
#include "map.h"
#include "mapblock.h"
#include "nodedef.h"
#include "util/timetaker.h"


ReflowScan::ReflowScan(Map *map, INodeDefManager *ndef) :
	m_map(map),
	m_ndef(ndef)
{
}

void ReflowScan::scan(MapBlock *block, UniqueQueue<v3s16> *liquid_queue)
{
	m_block_pos = block->getPos();
	m_rel_block_pos = block->getPosRelative();
	m_liquid_queue = liquid_queue;

	// Prepare the lookup which is a 3x3x3 array of the blocks surrounding the
	// scanned block. Blocks are only added to the lookup if they are really
	// needed. The lookup is indexed manually to use the same index in a
	// bit-array (of uint32 type) which stores for unloaded blocks that they
	// were already fetched from Map but were actually nullptr.
	memset(m_lookup, 0, sizeof(m_lookup));
	int block_idx = 1 + (1 * 9) + (1 * 3);
	m_lookup[block_idx] = block;
	m_lookup_state_bitset = 1 << block_idx;

	// Scan the columns in the block
	for (s16 z = 0; z < MAP_BLOCKSIZE; z++)
	for (s16 x = 0; x < MAP_BLOCKSIZE; x++) {
		scanColumn(x, z);
	}

	// Scan neighbouring columns from the nearby blocks as they might contain
	// liquid nodes that weren't allowed to flow to prevent gaps.
	for (s16 i = 0; i < MAP_BLOCKSIZE; i++) {
		scanColumn(i, -1);
		scanColumn(i, MAP_BLOCKSIZE);
		scanColumn(-1, i);
		scanColumn(MAP_BLOCKSIZE, i);
	}
}

inline MapBlock *ReflowScan::lookupBlock(int x, int y, int z)
{
	// Gets the block that contains (x,y,z) relativ to the scanned block.
	// This uses a lookup as there might be many lookups into the same
	// neighbouring block which makes fetches from Map costly.
	int bx = (MAP_BLOCKSIZE + x) / MAP_BLOCKSIZE;
	int by = (MAP_BLOCKSIZE + y) / MAP_BLOCKSIZE;
	int bz = (MAP_BLOCKSIZE + z) / MAP_BLOCKSIZE;
	int idx = (bx + (by * 9) + (bz * 3));
	MapBlock *result = m_lookup[idx];
	if (!result && (m_lookup_state_bitset & (1 << idx)) == 0) {
		// The block wasn't requested yet so fetch it from Map and store it
		// in the lookup
		v3s16 pos = m_block_pos + v3s16(bx - 1, by - 1, bz - 1);
		m_lookup[idx] = result = m_map->getBlockNoCreateNoEx(pos);
		m_lookup_state_bitset |= (1 << idx);
	}
	return result;
}

inline bool ReflowScan::isLiquidFlowableTo(int x, int y, int z)
{
	// Tests whether (x,y,z) is a node to which liquid might flow.
	bool valid_position;
	MapBlock *block = lookupBlock(x, y, z);
	if (block) {
		int dx = (MAP_BLOCKSIZE + x) % MAP_BLOCKSIZE;
		int dy = (MAP_BLOCKSIZE + y) % MAP_BLOCKSIZE;
		int dz = (MAP_BLOCKSIZE + z) % MAP_BLOCKSIZE;
		MapNode node = block->getNodeNoCheck(dx, dy, dz, &valid_position);
		if (node.getContent() != CONTENT_IGNORE) {
			const ContentFeatures &f = m_ndef->get(node);
			// NOTE: No need to check for flowing nodes with lower liquid level
			// as they should only occur on top of other columns where they
			// will be added to the queue themselves.
			return f.floodable;
		}
	}
	return false;
}

inline bool ReflowScan::isLiquidHorizontallyFlowable(int x, int y, int z)
{
	// Check if the (x,y,z) might spread to one of the horizontally
	// neighbouring nodes
	return isLiquidFlowableTo(x - 1, y, z) ||
		isLiquidFlowableTo(x + 1, y, z) ||
		isLiquidFlowableTo(x, y, z - 1) ||
		isLiquidFlowableTo(x, y, z + 1);
}

void ReflowScan::scanColumn(int x, int z)
{
	bool valid_position;

	// Is the column inside a loaded block?
	MapBlock *block = lookupBlock(x, 0, z);
	if (!block)
		return;

	MapBlock *above = lookupBlock(x, MAP_BLOCKSIZE, z);
	int dx = (MAP_BLOCKSIZE + x) % MAP_BLOCKSIZE;
	int dz = (MAP_BLOCKSIZE + z) % MAP_BLOCKSIZE;

	// Get the state from the node above the scanned block
	bool was_ignore, was_liquid;
	if (above) {
		MapNode node = above->getNodeNoCheck(dx, 0, dz, &valid_position);
		was_ignore = node.getContent() == CONTENT_IGNORE;
		was_liquid = m_ndef->get(node).isLiquid();
	} else {
		was_ignore = true;
		was_liquid = false;
	}
	bool was_checked = false;
	bool was_pushed = false;

	// Scan through the whole block
	for (s16 y = MAP_BLOCKSIZE - 1; y >= 0; y--) {
		MapNode node = block->getNodeNoCheck(dx, y, dz, &valid_position);
		const ContentFeatures &f = m_ndef->get(node);
		bool is_ignore = node.getContent() == CONTENT_IGNORE;
		bool is_liquid = f.isLiquid();

		if (is_ignore || was_ignore || is_liquid == was_liquid) {
			// Neither topmost node of liquid column nor topmost node below column
			was_checked = false;
			was_pushed = false;
		} else if (is_liquid) {
			// This is the topmost node in the column
			bool is_pushed = false;
			if (f.liquid_type == LIQUID_FLOWING ||
					isLiquidHorizontallyFlowable(x, y, z)) {
				m_liquid_queue->push_back(m_rel_block_pos + v3s16(x, y, z));
				is_pushed = true;
			}
			// Remember waschecked and waspushed to avoid repeated
			// checks/pushes in case the column consists of only this node
			was_checked = true;
			was_pushed = is_pushed;
		} else {
			// This is the topmost node below a liquid column
			if (!was_pushed && (f.floodable ||
					(!was_checked && isLiquidHorizontallyFlowable(x, y + 1, z)))) {
				// Activate the lowest node in the column which is one
				// node above this one
				m_liquid_queue->push_back(m_rel_block_pos + v3s16(x, y + 1, z));
			}
		}

		was_liquid = is_liquid;
		was_ignore = is_ignore;
	}

	// Check the node below the current block
	MapBlock *below = lookupBlock(x, -1, z);
	if (below) {
		MapNode node = below->getNodeNoCheck(dx, MAP_BLOCKSIZE - 1, dz, &valid_position);
		const ContentFeatures &f = m_ndef->get(node);
		bool is_ignore = node.getContent() == CONTENT_IGNORE;
		bool is_liquid = f.isLiquid();

		if (is_ignore || was_ignore || is_liquid == was_liquid) {
			// Neither topmost node of liquid column nor topmost node below column
		} else if (is_liquid) {
			// This is the topmost node in the column and might want to flow away
			if (f.liquid_type == LIQUID_FLOWING ||
					isLiquidHorizontallyFlowable(x, -1, z)) {
				m_liquid_queue->push_back(m_rel_block_pos + v3s16(x, -1, z));
			}
		} else {
			// This is the topmost node below a liquid column
			if (!was_pushed && (f.floodable ||
					(!was_checked && isLiquidHorizontallyFlowable(x, 0, z)))) {
				// Activate the lowest node in the column which is one
				// node above this one
				m_liquid_queue->push_back(m_rel_block_pos + v3s16(x, 0, z));
			}
		}
	}
}
> FlagDesc *flagdesc, u32 flagmask); size_t mystrlcpy(char *dst, const char *src, size_t size); char *mystrtok_r(char *s, const char *sep, char **lasts); u64 read_seed(const char *str); bool parseColorString(const std::string &value, video::SColor &color, bool quiet, unsigned char default_alpha = 0xff); /** * Returns a copy of \p str with spaces inserted at the right hand side to ensure * that the string is \p len characters in length. If \p str is <= \p len then the * returned string will be identical to str. */ inline std::string padStringRight(std::string str, size_t len) { if (len > str.size()) str.insert(str.end(), len - str.size(), ' '); return str; } /** * Returns a version of \p str with the first occurrence of a string * contained within ends[] removed from the end of the string. * * @param str * @param ends A NULL- or ""- terminated array of strings to remove from s in * the copy produced. Note that once one of these strings is removed * that no further postfixes contained within this array are removed. * * @return If no end could be removed then "" is returned. */ inline std::string removeStringEnd(const std::string &str, const char *ends[]) { const char **p = ends; for (; *p && (*p)[0] != '\0'; p++) { std::string end = *p; if (str.size() < end.size()) continue; if (str.compare(str.size() - end.size(), end.size(), end) == 0) return str.substr(0, str.size() - end.size()); } return ""; } /** * Check two strings for equivalence. If \p case_insensitive is true * then the case of the strings is ignored (default is false). * * @param s1 * @param s2 * @param case_insensitive * @return true if the strings match */ template <typename T> inline bool str_equal(const std::basic_string<T> &s1, const std::basic_string<T> &s2, bool case_insensitive = false) { if (!case_insensitive) return s1 == s2; if (s1.size() != s2.size()) return false; for (size_t i = 0; i < s1.size(); ++i) if(tolower(s1[i]) != tolower(s2[i])) return false; return true; } /** * Check whether \p str begins with the string prefix. If \p case_insensitive * is true then the check is case insensitve (default is false; i.e. case is * significant). * * @param str * @param prefix * @param case_insensitive * @return true if the str begins with prefix */ template <typename T> inline bool str_starts_with(const std::basic_string<T> &str, const std::basic_string<T> &prefix, bool case_insensitive = false) { if (str.size() < prefix.size()) return false; if (!case_insensitive) return str.compare(0, prefix.size(), prefix) == 0; for (size_t i = 0; i < prefix.size(); ++i) if (tolower(str[i]) != tolower(prefix[i])) return false; return true; } /** * Check whether \p str begins with the string prefix. If \p case_insensitive * is true then the check is case insensitve (default is false; i.e. case is * significant). * * @param str * @param prefix * @param case_insensitive * @return true if the str begins with prefix */ template <typename T> inline bool str_starts_with(const std::basic_string<T> &str, const T *prefix, bool case_insensitive = false) { return str_starts_with(str, std::basic_string<T>(prefix), case_insensitive); } /** * Check whether \p str ends with the string suffix. If \p case_insensitive * is true then the check is case insensitve (default is false; i.e. case is * significant). * * @param str * @param suffix * @param case_insensitive * @return true if the str begins with suffix */ template <typename T> inline bool str_ends_with(const std::basic_string<T> &str, const std::basic_string<T> &suffix, bool case_insensitive = false) { if (str.size() < suffix.size()) return false; size_t start = str.size() - suffix.size(); if (!case_insensitive) return str.compare(start, suffix.size(), suffix) == 0; for (size_t i = 0; i < suffix.size(); ++i) if (tolower(str[start + i]) != tolower(suffix[i])) return false; return true; } /** * Check whether \p str ends with the string suffix. If \p case_insensitive * is true then the check is case insensitve (default is false; i.e. case is * significant). * * @param str * @param suffix * @param case_insensitive * @return true if the str begins with suffix */ template <typename T> inline bool str_ends_with(const std::basic_string<T> &str, const T *suffix, bool case_insensitive = false) { return str_ends_with(str, std::basic_string<T>(suffix), case_insensitive); } /** * Splits a string into its component parts separated by the character * \p delimiter. * * @return An std::vector<std::basic_string<T> > of the component parts */ template <typename T> inline std::vector<std::basic_string<T> > str_split( const std::basic_string<T> &str, T delimiter) { std::vector<std::basic_string<T> > parts; std::basic_stringstream<T> sstr(str); std::basic_string<T> part; while (std::getline(sstr, part, delimiter)) parts.push_back(part); return parts; } /** * @param str * @return A copy of \p str converted to all lowercase characters. */ inline std::string lowercase(const std::string &str) { std::string s2; s2.reserve(str.size()); for (char i : str) s2 += tolower(i); return s2; } /** * @param str * @return A copy of \p str with leading and trailing whitespace removed. */ inline std::string trim(const std::string &str) { size_t front = 0; while (std::isspace(str[front])) ++front; size_t back = str.size(); while (back > front && std::isspace(str[back - 1])) --back; return str.substr(front, back - front); } /** * Returns whether \p str should be regarded as (bool) true. Case and leading * and trailing whitespace are ignored. Values that will return * true are "y", "yes", "true" and any number that is not 0. * @param str */ inline bool is_yes(const std::string &str) { std::string s2 = lowercase(trim(str)); return s2 == "y" || s2 == "yes" || s2 == "true" || atoi(s2.c_str()) != 0; } /** * Converts the string \p str to a signed 32-bit integer. The converted value * is constrained so that min <= value <= max. * * @see atoi(3) for limitations * * @param str * @param min Range minimum * @param max Range maximum * @return The value converted to a signed 32-bit integer and constrained * within the range defined by min and max (inclusive) */ inline s32 mystoi(const std::string &str, s32 min, s32 max) { s32 i = atoi(str.c_str()); if (i < min) i = min; if (i > max) i = max; return i; } // MSVC2010 includes it's own versions of these //#if !defined(_MSC_VER) || _MSC_VER < 1600 /** * Returns a 32-bit value reprensented by the string \p str (decimal). * @see atoi(3) for further limitations */ inline s32 mystoi(const std::string &str) { return atoi(str.c_str()); } /** * Returns s 32-bit value represented by the wide string \p str (decimal). * @see atoi(3) for further limitations */ inline s32 mystoi(const std::wstring &str) { return mystoi(wide_to_narrow(str)); } /** * Returns a float reprensented by the string \p str (decimal). * @see atof(3) */ inline float mystof(const std::string &str) { return atof(str.c_str()); } //#endif #define stoi mystoi #define stof mystof /// Returns a value represented by the string \p val. template <typename T> inline T from_string(const std::string &str) { std::stringstream tmp(str); T t; tmp >> t; return t; } /// Returns a 64-bit signed value represented by the string \p str (decimal). inline s64 stoi64(const std::string &str) { return from_string<s64>(str); } #if __cplusplus < 201103L namespace std { /// Returns a string representing the value \p val. template <typename T> inline string to_string(T val) { ostringstream oss; oss << val; return oss.str(); } #define DEFINE_STD_TOSTRING_FLOATINGPOINT(T) \ template <> \ inline string to_string<T>(T val) \ { \ ostringstream oss; \ oss << std::fixed \ << std::setprecision(6) \ << val; \ return oss.str(); \ } DEFINE_STD_TOSTRING_FLOATINGPOINT(float) DEFINE_STD_TOSTRING_FLOATINGPOINT(double) DEFINE_STD_TOSTRING_FLOATINGPOINT(long double) #undef DEFINE_STD_TOSTRING_FLOATINGPOINT /// Returns a wide string representing the value \p val template <typename T> inline wstring to_wstring(T val) { return utf8_to_wide(to_string(val)); } } #endif /// Returns a string representing the decimal value of the 32-bit value \p i. inline std::string itos(s32 i) { return std::to_string(i); } /// Returns a string representing the decimal value of the 64-bit value \p i. inline std::string i64tos(s64 i) { return std::to_string(i); } // std::to_string uses the '%.6f' conversion, which is inconsistent with // std::ostream::operator<<() and impractical too. ftos() uses the // more generic and std::ostream::operator<<()-compatible '%G' format. /// Returns a string representing the decimal value of the float value \p f. inline std::string ftos(float f) { std::ostringstream oss; oss << f; return oss.str(); } /** * Replace all occurrences of \p pattern in \p str with \p replacement. * * @param str String to replace pattern with replacement within. * @param pattern The pattern to replace. * @param replacement What to replace the pattern with. */ inline void str_replace(std::string &str, const std::string &pattern, const std::string &replacement) { std::string::size_type start = str.find(pattern, 0); while (start != str.npos) { str.replace(start, pattern.size(), replacement); start = str.find(pattern, start + replacement.size()); } } /** * Escapes characters [ ] \ , ; that can not be used in formspecs */ inline void str_formspec_escape(std::string &str) { str_replace(str, "\\", "\\\\"); str_replace(str, "]", "\\]"); str_replace(str, "[", "\\["); str_replace(str, ";", "\\;"); str_replace(str, ",", "\\,"); } /** * Replace all occurrences of the character \p from in \p str with \p to. * * @param str The string to (potentially) modify. * @param from The character in str to replace. * @param to The replacement character. */ void str_replace(std::string &str, char from, char to); /** * Check that a string only contains whitelisted characters. This is the * opposite of string_allowed_blacklist(). * * @param str The string to be checked. * @param allowed_chars A string containing permitted characters. * @return true if the string is allowed, otherwise false. * * @see string_allowed_blacklist() */ inline bool string_allowed(const std::string &str, const std::string &allowed_chars) { return str.find_first_not_of(allowed_chars) == str.npos; } /** * Check that a string contains no blacklisted characters. This is the * opposite of string_allowed(). * * @param str The string to be checked. * @param blacklisted_chars A string containing prohibited characters. * @return true if the string is allowed, otherwise false. * @see string_allowed() */ inline bool string_allowed_blacklist(const std::string &str, const std::string &blacklisted_chars) { return str.find_first_of(blacklisted_chars) == str.npos; } /** * Create a string based on \p from where a newline is forcefully inserted * every \p row_len characters. * * @note This function does not honour word wraps and blindy inserts a newline * every \p row_len characters whether it breaks a word or not. It is * intended to be used for, for example, showing paths in the GUI. * * @note This function doesn't wrap inside utf-8 multibyte sequences and also * counts multibyte sequences correcly as single characters. * * @param from The (utf-8) string to be wrapped into rows. * @param row_len The row length (in characters). * @return A new string with the wrapping applied. */ inline std::string wrap_rows(const std::string &from, unsigned row_len) { std::string to; size_t character_idx = 0; for (size_t i = 0; i < from.size(); i++) { if (!IS_UTF8_MULTB_INNER(from[i])) { // Wrap string after last inner byte of char if (character_idx > 0 && character_idx % row_len == 0) to += '\n'; character_idx++; } to += from[i]; } return to; } /** * Removes backslashes from an escaped string (FormSpec strings) */ template <typename T> inline std::basic_string<T> unescape_string(const std::basic_string<T> &s) { std::basic_string<T> res; for (size_t i = 0; i < s.length(); i++) { if (s[i] == '\\') { i++; if (i >= s.length()) break; } res += s[i]; } return res; } /** * Remove all escape sequences in \p s. * * @param s The string in which to remove escape sequences. * @return \p s, with escape sequences removed. */ template <typename T> std::basic_string<T> unescape_enriched(const std::basic_string<T> &s) { std::basic_string<T> output; size_t i = 0; while (i < s.length()) { if (s[i] == '\x1b') { ++i; if (i == s.length()) continue; if (s[i] == '(') { ++i; while (i < s.length() && s[i] != ')') { if (s[i] == '\\') { ++i; } ++i; } ++i; } else { ++i; } continue; } output += s[i]; ++i; } return output; } template <typename T> std::vector<std::basic_string<T> > split(const std::basic_string<T> &s, T delim) { std::vector<std::basic_string<T> > tokens; std::basic_string<T> current; bool last_was_escape = false; for (size_t i = 0; i < s.length(); i++) { T si = s[i]; if (last_was_escape) { current += '\\'; current += si; last_was_escape = false; } else { if (si == delim) { tokens.push_back(current); current = std::basic_string<T>(); last_was_escape = false; } else if (si == '\\') { last_was_escape = true; } else { current += si; last_was_escape = false; } } } //push last element tokens.push_back(current); return tokens; } std::wstring translate_string(const std::wstring &s, Translations *translations); std::wstring translate_string(const std::wstring &s); inline std::wstring unescape_translate(const std::wstring &s) { return unescape_enriched(translate_string(s)); } /** * Checks that all characters in \p to_check are a decimal digits. * * @param to_check * @return true if to_check is not empty and all characters in to_check are * decimal digits, otherwise false */ inline bool is_number(const std::string &to_check) { for (char i : to_check) if (!std::isdigit(i)) return false; return !to_check.empty(); } /** * Returns a C-string, either "true" or "false", corresponding to \p val. * * @return If \p val is true, then "true" is returned, otherwise "false". */ inline const char *bool_to_cstr(bool val) { return val ? "true" : "false"; } inline const std::string duration_to_string(int sec) { int min = sec / 60; sec %= 60; int hour = min / 60; min %= 60; std::stringstream ss; if (hour > 0) { ss << hour << "h "; } if (min > 0) { ss << min << "m "; } if (sec > 0) { ss << sec << "s "; } return ss.str(); } /** * Joins a vector of strings by the string \p delimiter. * * @return A std::string */ inline std::string str_join(const std::vector<std::string> &list, const std::string &delimiter) { std::ostringstream oss; bool first = true; for (const auto &part : list) { if (!first) oss << delimiter; oss << part; first = false; } return oss.str(); } /** * Create a UTF8 std::string from a irr::core::stringw. */ inline std::string stringw_to_utf8(const irr::core::stringw &input) { std::wstring str(input.c_str()); return wide_to_utf8(str); } /** * Create a irr::core:stringw from a UTF8 std::string. */ inline irr::core::stringw utf8_to_stringw(const std::string &input) { std::wstring str = utf8_to_wide(input); return irr::core::stringw(str.c_str()); } /** * Sanitize the name of a new directory. This consists of two stages: * 1. Check for 'reserved filenames' that can't be used on some filesystems * and prefix them * 2. Remove 'unsafe' characters from the name by replacing them with '_' */ std::string sanitizeDirName(const std::string &str, const std::string &optional_prefix);