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