1-- Minetest: builtin/item_entity.lua
2
3function core.spawn_item(pos, item)
4	-- Take item in any format
5	local stack = ItemStack(item)
6	local obj = core.add_entity(pos, "__builtin:item")
7	-- Don't use obj if it couldn't be added to the map.
8	if obj then
9		obj:get_luaentity():set_item(stack:to_string())
10	end
11	return obj
12end
13
14-- If item_entity_ttl is not set, enity will have default life time
15-- Setting it to -1 disables the feature
16
17local time_to_live = tonumber(core.settings:get("item_entity_ttl")) or 900
18local gravity = tonumber(core.settings:get("movement_gravity")) or 9.81
19
20
21core.register_entity(":__builtin:item", {
22	initial_properties = {
23		hp_max = 1,
24		physical = true,
25		collide_with_objects = false,
26		collisionbox = {-0.3, -0.3, -0.3, 0.3, 0.3, 0.3},
27		visual = "wielditem",
28		visual_size = {x = 0.4, y = 0.4},
29		textures = {""},
30		is_visible = false,
31	},
32
33	itemstring = "",
34	moving_state = true,
35	physical_state = true,
36	-- Item expiry
37	age = 0,
38	-- Pushing item out of solid nodes
39	force_out = nil,
40	force_out_start = nil,
41
42	set_item = function(self, item)
43		local stack = ItemStack(item or self.itemstring)
44		self.itemstring = stack:to_string()
45		if self.itemstring == "" then
46			-- item not yet known
47			return
48		end
49
50		-- Backwards compatibility: old clients use the texture
51		-- to get the type of the item
52		local itemname = stack:is_known() and stack:get_name() or "unknown"
53
54		local max_count = stack:get_stack_max()
55		local count = math.min(stack:get_count(), max_count)
56		local size = 0.2 + 0.1 * (count / max_count) ^ (1 / 3)
57		local def = core.registered_items[itemname]
58		local glow = def and def.light_source and
59			math.floor(def.light_source / 2 + 0.5)
60
61		self.object:set_properties({
62			is_visible = true,
63			visual = "wielditem",
64			textures = {itemname},
65			visual_size = {x = size, y = size},
66			collisionbox = {-size, -size, -size, size, size, size},
67			automatic_rotate = math.pi * 0.5 * 0.2 / size,
68			wield_item = self.itemstring,
69			glow = glow,
70		})
71
72	end,
73
74	get_staticdata = function(self)
75		return core.serialize({
76			itemstring = self.itemstring,
77			age = self.age,
78			dropped_by = self.dropped_by
79		})
80	end,
81
82	on_activate = function(self, staticdata, dtime_s)
83		if string.sub(staticdata, 1, string.len("return")) == "return" then
84			local data = core.deserialize(staticdata)
85			if data and type(data) == "table" then
86				self.itemstring = data.itemstring
87				self.age = (data.age or 0) + dtime_s
88				self.dropped_by = data.dropped_by
89			end
90		else
91			self.itemstring = staticdata
92		end
93		self.object:set_armor_groups({immortal = 1})
94		self.object:set_velocity({x = 0, y = 2, z = 0})
95		self.object:set_acceleration({x = 0, y = -gravity, z = 0})
96		self:set_item()
97	end,
98
99	try_merge_with = function(self, own_stack, object, entity)
100		if self.age == entity.age then
101			-- Can not merge with itself
102			return false
103		end
104
105		local stack = ItemStack(entity.itemstring)
106		local name = stack:get_name()
107		if own_stack:get_name() ~= name or
108				own_stack:get_meta() ~= stack:get_meta() or
109				own_stack:get_wear() ~= stack:get_wear() or
110				own_stack:get_free_space() == 0 then
111			-- Can not merge different or full stack
112			return false
113		end
114
115		local count = own_stack:get_count()
116		local total_count = stack:get_count() + count
117		local max_count = stack:get_stack_max()
118
119		if total_count > max_count then
120			return false
121		end
122		-- Merge the remote stack into this one
123
124		local pos = object:get_pos()
125		pos.y = pos.y + ((total_count - count) / max_count) * 0.15
126		self.object:move_to(pos)
127
128		self.age = 0 -- Handle as new entity
129		own_stack:set_count(total_count)
130		self:set_item(own_stack)
131
132		entity.itemstring = ""
133		object:remove()
134		return true
135	end,
136
137	enable_physics = function(self)
138		if not self.physical_state then
139			self.physical_state = true
140			self.object:set_properties({physical = true})
141			self.object:set_velocity({x=0, y=0, z=0})
142			self.object:set_acceleration({x=0, y=-gravity, z=0})
143		end
144	end,
145
146	disable_physics = function(self)
147		if self.physical_state then
148			self.physical_state = false
149			self.object:set_properties({physical = false})
150			self.object:set_velocity({x=0, y=0, z=0})
151			self.object:set_acceleration({x=0, y=0, z=0})
152		end
153	end,
154
155	on_step = function(self, dtime, moveresult)
156		self.age = self.age + dtime
157		if time_to_live > 0 and self.age > time_to_live then
158			self.itemstring = ""
159			self.object:remove()
160			return
161		end
162
163		local pos = self.object:get_pos()
164		local node = core.get_node_or_nil({
165			x = pos.x,
166			y = pos.y + self.object:get_properties().collisionbox[2] - 0.05,
167			z = pos.z
168		})
169		-- Delete in 'ignore' nodes
170		if node and node.name == "ignore" then
171			self.itemstring = ""
172			self.object:remove()
173			return
174		end
175
176		if self.force_out then
177			-- This code runs after the entity got a push from the is_stuck code.
178			-- It makes sure the entity is entirely outside the solid node
179			local c = self.object:get_properties().collisionbox
180			local s = self.force_out_start
181			local f = self.force_out
182			local ok = (f.x > 0 and pos.x + c[1] > s.x + 0.5) or
183				(f.y > 0 and pos.y + c[2] > s.y + 0.5) or
184				(f.z > 0 and pos.z + c[3] > s.z + 0.5) or
185				(f.x < 0 and pos.x + c[4] < s.x - 0.5) or
186				(f.z < 0 and pos.z + c[6] < s.z - 0.5)
187			if ok then
188				-- Item was successfully forced out
189				self.force_out = nil
190				self:enable_physics()
191				return
192			end
193		end
194
195		if not self.physical_state then
196			return -- Don't do anything
197		end
198
199		assert(moveresult,
200			"Collision info missing, this is caused by an out-of-date/buggy mod or game")
201
202		if not moveresult.collides then
203			-- future TODO: items should probably decelerate in air
204			return
205		end
206
207		-- Push item out when stuck inside solid node
208		local is_stuck = false
209		local snode = core.get_node_or_nil(pos)
210		if snode then
211			local sdef = core.registered_nodes[snode.name] or {}
212			is_stuck = (sdef.walkable == nil or sdef.walkable == true)
213				and (sdef.collision_box == nil or sdef.collision_box.type == "regular")
214				and (sdef.node_box == nil or sdef.node_box.type == "regular")
215		end
216
217		if is_stuck then
218			local shootdir
219			local order = {
220				{x=1, y=0, z=0}, {x=-1, y=0, z= 0},
221				{x=0, y=0, z=1}, {x= 0, y=0, z=-1},
222			}
223
224			-- Check which one of the 4 sides is free
225			for o = 1, #order do
226				local cnode = core.get_node(vector.add(pos, order[o])).name
227				local cdef = core.registered_nodes[cnode] or {}
228				if cnode ~= "ignore" and cdef.walkable == false then
229					shootdir = order[o]
230					break
231				end
232			end
233			-- If none of the 4 sides is free, check upwards
234			if not shootdir then
235				shootdir = {x=0, y=1, z=0}
236				local cnode = core.get_node(vector.add(pos, shootdir)).name
237				if cnode == "ignore" then
238					shootdir = nil -- Do not push into ignore
239				end
240			end
241
242			if shootdir then
243				-- Set new item moving speed accordingly
244				local newv = vector.multiply(shootdir, 3)
245				self:disable_physics()
246				self.object:set_velocity(newv)
247
248				self.force_out = newv
249				self.force_out_start = vector.round(pos)
250				return
251			end
252		end
253
254		node = nil -- ground node we're colliding with
255		if moveresult.touching_ground then
256			for _, info in ipairs(moveresult.collisions) do
257				if info.axis == "y" then
258					node = core.get_node(info.node_pos)
259					break
260				end
261			end
262		end
263
264		-- Slide on slippery nodes
265		local def = node and core.registered_nodes[node.name]
266		local keep_movement = false
267
268		if def then
269			local slippery = core.get_item_group(node.name, "slippery")
270			local vel = self.object:get_velocity()
271			if slippery ~= 0 and (math.abs(vel.x) > 0.1 or math.abs(vel.z) > 0.1) then
272				-- Horizontal deceleration
273				local factor = math.min(4 / (slippery + 4) * dtime, 1)
274				self.object:set_velocity({
275					x = vel.x * (1 - factor),
276					y = 0,
277					z = vel.z * (1 - factor)
278				})
279				keep_movement = true
280			end
281		end
282
283		if not keep_movement then
284			self.object:set_velocity({x=0, y=0, z=0})
285		end
286
287		if self.moving_state == keep_movement then
288			-- Do not update anything until the moving state changes
289			return
290		end
291		self.moving_state = keep_movement
292
293		-- Only collect items if not moving
294		if self.moving_state then
295			return
296		end
297		-- Collect the items around to merge with
298		local own_stack = ItemStack(self.itemstring)
299		if own_stack:get_free_space() == 0 then
300			return
301		end
302		local objects = core.get_objects_inside_radius(pos, 1.0)
303		for k, obj in pairs(objects) do
304			local entity = obj:get_luaentity()
305			if entity and entity.name == "__builtin:item" then
306				if self:try_merge_with(own_stack, obj, entity) then
307					own_stack = ItemStack(self.itemstring)
308					if own_stack:get_free_space() == 0 then
309						return
310					end
311				end
312			end
313		end
314	end,
315
316	on_punch = function(self, hitter)
317		local inv = hitter:get_inventory()
318		if inv and self.itemstring ~= "" then
319			local left = inv:add_item("main", self.itemstring)
320			if left and not left:is_empty() then
321				self:set_item(left)
322				return
323			end
324		end
325		self.itemstring = ""
326		self.object:remove()
327	end,
328})
329