aboutsummaryrefslogtreecommitdiff
path: root/builtin/game/falling.lua
blob: b1beb1ab0c47bd5f20ff03d67862f76f1a2c7c8f (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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
-- Minetest: builtin/item.lua

local builtin_shared = ...

--
-- Falling stuff
--

core.register_entity(":__builtin:falling_node", {
	initial_properties = {
		visual = "wielditem",
		visual_size = {x = 0.667, y = 0.667},
		textures = {},
		physical = true,
		is_visible = false,
		collide_with_objects = false,
		collisionbox = {-0.5, -0.5, -0.5, 0.5, 0.5, 0.5},
	},

	node = {},
	meta = {},

	set_node = function(self, node, meta)
		self.node = node
		self.meta = meta or {}
		self.object:set_properties({
			is_visible = true,
			textures = {node.name},
		})
	end,

	get_staticdata = function(self)
		local ds = {
			node = self.node,
			meta = self.meta,
		}
		return core.serialize(ds)
	end,

	on_activate = function(self, staticdata)
		self.object:set_armor_groups({immortal = 1})
		
		local ds = core.deserialize(staticdata)
		if ds and ds.node then
			self:set_node(ds.node, ds.meta)
		elseif ds then
			self:set_node(ds)
		elseif staticdata ~= "" then
			self:set_node({name = staticdata})
		end
	end,

	on_step = function(self, dtime)
		-- Set gravity
		local acceleration = self.object:getacceleration()
		if not vector.equals(acceleration, {x = 0, y = -10, z = 0}) then
			self.object:setacceleration({x = 0, y = -10, z = 0})
		end
		-- Turn to actual node when colliding with ground, or continue to move
		local pos = self.object:getpos()
		-- Position of bottom center point
		local bcp = {x = pos.x, y = pos.y - 0.7, z = pos.z}
		-- Avoid bugs caused by an unloaded node below
		local bcn = core.get_node_or_nil(bcp)
		local bcd = bcn and core.registered_nodes[bcn.name]
		if bcn and
				(not bcd or bcd.walkable or
				(core.get_item_group(self.node.name, "float") ~= 0 and
				bcd.liquidtype ~= "none")) then
			if bcd and bcd.leveled and
					bcn.name == self.node.name then
				local addlevel = self.node.level
				if not addlevel or addlevel <= 0 then
					addlevel = bcd.leveled
				end
				if core.add_node_level(bcp, addlevel) == 0 then
					self.object:remove()
					return
				end
			elseif bcd and bcd.buildable_to and
					(core.get_item_group(self.node.name, "float") == 0 or
					bcd.liquidtype == "none") then
				core.remove_node(bcp)
				return
			end
			local np = {x = bcp.x, y = bcp.y + 1, z = bcp.z}
			-- Check what's here
			local n2 = core.get_node(np)
			local nd = core.registered_nodes[n2.name]
			-- If it's not air or liquid, remove node and replace it with
			-- it's drops
			if n2.name ~= "air" and (not nd or nd.liquidtype == "none") then
				core.remove_node(np)
				if nd and nd.buildable_to == false then
					-- Add dropped items
					local drops = core.get_node_drops(n2.name, "")
					for _, dropped_item in pairs(drops) do
						core.add_item(np, dropped_item)
					end
				end
				-- Run script hook
				for _, callback in pairs(core.registered_on_dignodes) do
					callback(np, n2)
				end
			end
			-- Create node and remove entity
			if core.registered_nodes[self.node.name] then
				core.add_node(np, self.node)
				if self.meta then
					local meta = core.get_meta(np)
					meta:from_table(self.meta)
				end
			end
			self.object:remove()
			core.check_for_falling(np)
			return
		end
		local vel = self.object:getvelocity()
		if vector.equals(vel, {x = 0, y = 0, z = 0}) then
			local npos = self.object:getpos()
			self.object:setpos(vector.round(npos))
		end
	end
})

local function spawn_falling_node(p, node, meta)
	local obj = core.add_entity(p, "__builtin:falling_node")
	if obj then
		obj:get_luaentity():set_node(node, meta)
	end
end

function core.spawn_falling_node(pos)
	local node = core.get_node(pos)
	if node.name == "air" or node.name == "ignore" then
		return false
	end
	local obj = core.add_entity(pos, "__builtin:falling_node")
	if obj then
		obj:get_luaentity():set_node(node)
		core.remove_node(pos)
		return true
	end
	return false
end

local function drop_attached_node(p)
	local nn = core.get_node(p).name
	core.remove_node(p)
	for _, item in pairs(core.get_node_drops(nn, "")) do
		local pos = {
			x = p.x + math.random()/2 - 0.25,
			y = p.y + math.random()/2 - 0.25,
			z = p.z + math.random()/2 - 0.25,
		}
		core.add_item(pos, item)
	end
end

function builtin_shared.check_attached_node(p, n)
	local def = core.registered_nodes[n.name]
	local d = {x = 0, y = 0, z = 0}
	if def.paramtype2 == "wallmounted" or
			def.paramtype2 == "colorwallmounted" then
		-- The fallback vector here is in case 'wallmounted to dir' is nil due
		-- to voxelmanip placing a wallmounted node without resetting a
		-- pre-existing param2 value that is out-of-range for wallmounted.
		-- The fallback vector corresponds to param2 = 0.
		d = core.wallmounted_to_dir(n.param2) or {x = 0, y = 1, z = 0}
	else
		d.y = -1
	end
	local p2 = vector.add(p, d)
	local nn = core.get_node(p2).name
	local def2 = core.registered_nodes[nn]
	if def2 and not def2.walkable then
		return false
	end
	return true
end

--
-- Some common functions
--

function core.check_single_for_falling(p)
	local n = core.get_node(p)
	if core.get_item_group(n.name, "falling_node") ~= 0 then
		local p_bottom = {x = p.x, y = p.y - 1, z = p.z}
		-- Only spawn falling node if node below is loaded
		local n_bottom = core.get_node_or_nil(p_bottom)
		local d_bottom = n_bottom and core.registered_nodes[n_bottom.name]
		if d_bottom and

				(core.get_item_group(n.name, "float") == 0 or
				d_bottom.liquidtype == "none") and

				(n.name ~= n_bottom.name or (d_bottom.leveled and
				core.get_node_level(p_bottom) <
				core.get_node_max_level(p_bottom))) and

				(not d_bottom.walkable or d_bottom.buildable_to) then
			n.level = core.get_node_level(p)
			local meta = core.get_meta(p)
			local metatable = {}
			if meta ~= nil then
				metatable = meta:to_table()
			end
			core.remove_node(p)
			spawn_falling_node(p, n, metatable)
			return true
		end
	end

	if core.get_item_group(n.name, "attached_node") ~= 0 then
		if not builtin_shared.check_attached_node(p, n) then
			drop_attached_node(p)
			return true
		end
	end

	return false
end

-- This table is specifically ordered.
-- We don't walk diagonals, only our direct neighbors, and self.
-- Down first as likely case, but always before self. The same with sides.
-- Up must come last, so that things above self will also fall all at once.
local check_for_falling_neighbors = {
	{x = -1, y = -1, z = 0},
	{x = 1, y = -1, z = 0},
	{x = 0, y = -1, z = -1},
	{x = 0, y = -1, z = 1},
	{x = 0, y = -1, z = 0},
	{x = -1, y = 0, z = 0},
	{x = 1, y = 0, z = 0},
	{x = 0, y = 0, z = 1},
	{x = 0, y = 0, z = -1},
	{x = 0, y = 0, z = 0},
	{x = 0, y = 1, z = 0},
}

function core.check_for_falling(p)
	-- Round p to prevent falling entities to get stuck.
	p = vector.round(p)

	-- We make a stack, and manually maintain size for performance.
	-- Stored in the stack, we will maintain tables with pos, and
	-- last neighbor visited. This way, when we get back to each
	-- node, we know which directions we have already walked, and
	-- which direction is the next to walk.
	local s = {}
	local n = 0
	-- The neighbor order we will visit from our table.
	local v = 1

	while true do
		-- Push current pos onto the stack.
		n = n + 1
		s[n] = {p = p, v = v}
		-- Select next node from neighbor list.
		p = vector.add(p, check_for_falling_neighbors[v])
		-- Now we check out the node. If it is in need of an update,
		-- it will let us know in the return value (true = updated).
		if not core.check_single_for_falling(p) then
			-- If we don't need to "recurse" (walk) to it then pop
			-- our previous pos off the stack and continue from there,
			-- with the v value we were at when we last were at that
			-- node
			repeat
				local pop = s[n]
				p = pop.p
				v = pop.v
				s[n] = nil
				n = n - 1
				-- If there's nothing left on the stack, and no
				-- more sides to walk to, we're done and can exit
				if n == 0 and v == 11 then
					return
				end
			until v < 11
			-- The next round walk the next neighbor in list.
			v = v + 1
		else
			-- If we did need to walk the neighbor, then
			-- start walking it from the walk order start (1),
			-- and not the order we just pushed up the stack.
			v = 1
		end
	end
end

--
-- Global callbacks
--

local function on_placenode(p, node)
	core.check_for_falling(p)
end
core.register_on_placenode(on_placenode)

local function on_dignode(p, node)
	core.check_for_falling(p)
end
core.register_on_dignode(on_dignode)

local function on_punchnode(p, node)
	core.check_for_falling(p)
end
core.register_on_punchnode(on_punchnode)

--
-- Globally exported functions
--

-- TODO remove this function after the 0.4.15 release
function nodeupdate(p)
	core.log("deprecated", "nodeupdate: deprecated, please use core.check_for_falling instead")
	core.check_for_falling(p)
end

-- TODO remove this function after the 0.4.15 release
function nodeupdate_single(p)
	core.log("deprecated", "nodeupdate_single: deprecated, please use core.check_single_for_falling instead")
	core.check_single_for_falling(p)
end
span>("="); name = trim(name); if(name == "") { dst.push_back(line+line_end); return true; } std::string value = sf.next("\n"); value = trim(value); if(m_settings.find(name) != m_settings.end()) { std::string newvalue = m_settings[name]; if(newvalue != value) { infostream<<"Changing value of \""<<name<<"\" = \"" <<value<<"\" -> \""<<newvalue<<"\"" <<std::endl; value_changed = true; } dst.push_back(name + " = " + newvalue + line_end); updated.insert(name); } else //file contains a setting which is not in m_settings value_changed=true; return true; } /* Updates configuration file Returns true on success */ bool updateConfigFile(const char *filename) { infostream<<"Updating configuration file: \"" <<filename<<"\""<<std::endl; std::list<std::string> objects; std::set<std::string> updated; bool something_actually_changed = false; // Read and modify stuff { std::ifstream is(filename); if(is.good() == false) { infostream<<"updateConfigFile():" " Error opening configuration file" " for reading: \"" <<filename<<"\""<<std::endl; } else { while(getUpdatedConfigObject(is, objects, updated, something_actually_changed)); } } JMutexAutoLock lock(m_mutex); // If something not yet determined to have been changed, check if // any new stuff was added if(!something_actually_changed){ for(std::map<std::string, std::string>::iterator i = m_settings.begin(); i != m_settings.end(); ++i) { if(updated.find(i->first) != updated.end()) continue; something_actually_changed = true; break; } } // If nothing was actually changed, skip writing the file if(!something_actually_changed){ infostream<<"Skipping writing of "<<filename <<" because content wouldn't be modified"<<std::endl; return true; } // Write stuff back { std::ostringstream ss(std::ios_base::binary); /* Write updated stuff */ for(std::list<std::string>::iterator i = objects.begin(); i != objects.end(); ++i) { ss<<(*i); } /* Write stuff that was not already in the file */ for(std::map<std::string, std::string>::iterator i = m_settings.begin(); i != m_settings.end(); ++i) { if(updated.find(i->first) != updated.end()) continue; std::string name = i->first; std::string value = i->second; infostream<<"Adding \""<<name<<"\" = \""<<value<<"\"" <<std::endl; ss<<name<<" = "<<value<<"\n"; } if(!fs::safeWriteToFile(filename, ss.str())) { errorstream<<"Error writing configuration file: \"" <<filename<<"\""<<std::endl; return false; } } return true; } /* NOTE: Types of allowed_options are ignored returns true on success */ bool parseCommandLine(int argc, char *argv[], std::map<std::string, ValueSpec> &allowed_options) { int nonopt_index = 0; int i=1; for(;;) { if(i >= argc) break; std::string argname = argv[i]; if(argname.substr(0, 2) != "--") { // If option doesn't start with -, read it in as nonoptX if(argname[0] != '-'){ std::string name = "nonopt"; name += itos(nonopt_index); set(name, argname); nonopt_index++; i++; continue; } errorstream<<"Invalid command-line parameter \"" <<argname<<"\": --<option> expected."<<std::endl; return false; } i++; std::string name = argname.substr(2); std::map<std::string, ValueSpec>::iterator n; n = allowed_options.find(name); if(n == allowed_options.end()) { errorstream<<"Unknown command-line parameter \"" <<argname<<"\""<<std::endl; return false; } ValueType type = n->second.type; std::string value = ""; if(type == VALUETYPE_FLAG) { value = "true"; } else { if(i >= argc) { errorstream<<"Invalid command-line parameter \"" <<name<<"\": missing value"<<std::endl; return false; } value = argv[i]; i++; } infostream<<"Valid command-line parameter: \"" <<name<<"\" = \""<<value<<"\"" <<std::endl; set(name, value); } return true; } void set(std::string name, std::string value) { JMutexAutoLock lock(m_mutex); m_settings[name] = value; } void set(std::string name, const char *value) { JMutexAutoLock lock(m_mutex); m_settings[name] = value; } void setDefault(std::string name, std::string value) { JMutexAutoLock lock(m_mutex); m_defaults[name] = value; } bool exists(std::string name) { JMutexAutoLock lock(m_mutex); return (m_settings.find(name) != m_settings.end() || m_defaults.find(name) != m_defaults.end()); } std::string get(std::string name) { JMutexAutoLock lock(m_mutex); std::map<std::string, std::string>::iterator n; n = m_settings.find(name); if(n == m_settings.end()) { n = m_defaults.find(name); if(n == m_defaults.end()) { throw SettingNotFoundException(("Setting [" + name + "] not found ").c_str()); } } return n->second; } bool getBool(std::string name) { return is_yes(get(name)); } bool getFlag(std::string name) { try { return getBool(name); } catch(SettingNotFoundException &e) { return false; } } // Asks if empty bool getBoolAsk(std::string name, std::string question, bool def) { // If it is in settings if(exists(name)) return getBool(name); std::string s; char templine[10]; std::cout<<question<<" [y/N]: "; std::cin.getline(templine, 10); s = templine; if(s == "") return def; return is_yes(s); } float getFloat(std::string name) { return stof(get(name)); } u16 getU16(std::string name) { return stoi(get(name), 0, 65535); } u16 getU16Ask(std::string name, std::string question, u16 def) { // If it is in settings if(exists(name)) return getU16(name); std::string s; char templine[10]; std::cout<<question<<" ["<<def<<"]: "; std::cin.getline(templine, 10); s = templine; if(s == "") return def; return stoi(s, 0, 65535); } s16 getS16(std::string name) { return stoi(get(name), -32768, 32767); } s32 getS32(std::string name) { return stoi(get(name)); } v3f getV3F(std::string name) { v3f value; Strfnd f(get(name)); f.next("("); value.X = stof(f.next(",")); value.Y = stof(f.next(",")); value.Z = stof(f.next(")")); return value; } v2f getV2F(std::string name) { v2f value; Strfnd f(get(name)); f.next("("); value.X = stof(f.next(",")); value.Y = stof(f.next(")")); return value; } u64 getU64(std::string name) { u64 value = 0; std::string s = get(name); std::istringstream ss(s); ss>>value; return value; } u32 getFlagStr(std::string name, FlagDesc *flagdesc) { std::string val = get(name); return (isdigit(val[0])) ? stoi(val) : readFlagString(val, flagdesc); } bool getStruct(std::string name, std::string format, void *out, size_t olen) { size_t len = olen; std::vector<std::string *> strs_alloced; std::string *str; std::string valstr = get(name); char *s = &valstr[0]; char *buf = new char[len]; char *bufpos = buf; char *f, *snext; size_t pos; char *fmtpos, *fmt = &format[0]; while ((f = strtok_r(fmt, ",", &fmtpos)) && s) { fmt = NULL; bool is_unsigned = false; int width = 0; char valtype = *f; width = (int)strtol(f + 1, &f, 10); if (width && valtype == 's') valtype = 'i'; switch (valtype) { case 'u': is_unsigned = true; /* FALLTHROUGH */ case 'i': if (width == 16) { bufpos += PADDING(bufpos, u16); if ((bufpos - buf) + sizeof(u16) <= len) { if (is_unsigned) *(u16 *)bufpos = (u16)strtoul(s, &s, 10); else *(s16 *)bufpos = (s16)strtol(s, &s, 10); } bufpos += sizeof(u16); } else if (width == 32) { bufpos += PADDING(bufpos, u32); if ((bufpos - buf) + sizeof(u32) <= len) { if (is_unsigned) *(u32 *)bufpos = (u32)strtoul(s, &s, 10); else *(s32 *)bufpos = (s32)strtol(s, &s, 10); } bufpos += sizeof(u32); } else if (width == 64) { bufpos += PADDING(bufpos, u64); if ((bufpos - buf) + sizeof(u64) <= len) { if (is_unsigned) *(u64 *)bufpos = (u64)strtoull(s, &s, 10); else *(s64 *)bufpos = (s64)strtoll(s, &s, 10); } bufpos += sizeof(u64); } s = strchr(s, ','); break; case 'b': snext = strchr(s, ','); if (snext) *snext++ = 0; bufpos += PADDING(bufpos, bool); if ((bufpos - buf) + sizeof(bool) <= len) *(bool *)bufpos = is_yes(std::string(s)); bufpos += sizeof(bool); s = snext; break; case 'f': bufpos += PADDING(bufpos, float); if ((bufpos - buf) + sizeof(float) <= len) *(float *)bufpos = strtof(s, &s); bufpos += sizeof(float); s = strchr(s, ','); break; case 's': while (*s == ' ' || *s == '\t') s++; if (*s++ != '"') //error, expected string goto fail; snext = s; while (snext[0] && !(snext[-1] != '\\' && snext[0] == '"')) snext++; *snext++ = 0; bufpos += PADDING(bufpos, std::string *); str = new std::string(s); pos = 0; while ((pos = str->find("\\\"", pos)) != std::string::npos) str->erase(pos, 1); if ((bufpos - buf) + sizeof(std::string *) <= len) *(std::string **)bufpos = str; bufpos += sizeof(std::string *); strs_alloced.push_back(str); s = *snext ? snext + 1 : NULL; break; case 'v': while (*s == ' ' || *s == '\t') s++; if (*s++ != '(') //error, expected vector goto fail; if (width == 2) { bufpos += PADDING(bufpos, v2f); if ((bufpos - buf) + sizeof(v2f) <= len) { v2f *v = (v2f *)bufpos; v->X = strtof(s, &s); s++; v->Y = strtof(s, &s); } bufpos += sizeof(v2f); } else if (width == 3) { bufpos += PADDING(bufpos, v3f); if ((bufpos - buf) + sizeof(v3f) <= len) { v3f *v = (v3f *)bufpos; v->X = strtof(s, &s); s++; v->Y = strtof(s, &s); s++; v->Z = strtof(s, &s); } bufpos += sizeof(v3f); } s = strchr(s, ','); break; default: //error, invalid format specifier goto fail; } if (s && *s == ',') s++; if ((size_t)(bufpos - buf) > len) //error, buffer too small goto fail; } if (f && *f) { //error, mismatched number of fields and values fail: for (size_t i = 0; i != strs_alloced.size(); i++) delete strs_alloced[i]; delete[] buf; return false; } memcpy(out, buf, olen); delete[] buf; return true; } bool setStruct(std::string name, std::string format, void *value) { char sbuf[2048]; int sbuflen = sizeof(sbuf) - 1; sbuf[sbuflen] = 0; std::string str; int pos = 0; size_t fpos; char *f; char *bufpos = (char *)value; char *fmtpos, *fmt = &format[0]; while ((f = strtok_r(fmt, ",", &fmtpos))) { fmt = NULL; bool is_unsigned = false; int width = 0, nprinted = 0; char valtype = *f; width = (int)strtol(f + 1, &f, 10); if (width && valtype == 's') valtype = 'i'; switch (valtype) { case 'u': is_unsigned = true; /* FALLTHROUGH */ case 'i': if (width == 16) { bufpos += PADDING(bufpos, u16); nprinted = snprintf(sbuf + pos, sbuflen, is_unsigned ? "%u, " : "%d, ", *((u16 *)bufpos)); bufpos += sizeof(u16); } else if (width == 32) { bufpos += PADDING(bufpos, u32); nprinted = snprintf(sbuf + pos, sbuflen, is_unsigned ? "%u, " : "%d, ", *((u32 *)bufpos)); bufpos += sizeof(u32); } else if (width == 64) { bufpos += PADDING(bufpos, u64); nprinted = snprintf(sbuf + pos, sbuflen, is_unsigned ? "%llu, " : "%lli, ", (unsigned long long)*((u64 *)bufpos)); bufpos += sizeof(u64); } break; case 'b': bufpos += PADDING(bufpos, bool); nprinted = snprintf(sbuf + pos, sbuflen, "%s, ", *((bool *)bufpos) ? "true" : "false"); bufpos += sizeof(bool); break; case 'f': bufpos += PADDING(bufpos, float); nprinted = snprintf(sbuf + pos, sbuflen, "%f, ", *((float *)bufpos)); bufpos += sizeof(float);