TNT: Fix multiple explosions erasing drops
[oweals/minetest_game.git] / mods / tnt / init.lua
1 tnt = {}
2 -- Default to enabled in singleplayer and disabled in multiplayer
3 local singleplayer = minetest.is_singleplayer()
4 local setting = minetest.setting_getbool("enable_tnt")
5 if (not singleplayer and setting ~= true) or
6                 (singleplayer and setting == false) then
7         return
8 end
9
10 -- loss probabilities array (one in X will be lost)
11 local loss_prob = {}
12
13 loss_prob["default:cobble"] = 3
14 loss_prob["default:dirt"] = 4
15
16 local radius = tonumber(minetest.setting_get("tnt_radius") or 3)
17
18 -- Fill a list with data for content IDs, after all nodes are registered
19 local cid_data = {}
20 minetest.after(0, function()
21         for name, def in pairs(minetest.registered_nodes) do
22                 cid_data[minetest.get_content_id(name)] = {
23                         name = name,
24                         drops = def.drops,
25                         flammable = def.groups.flammable,
26                         on_blast = def.on_blast,
27                 }
28         end
29 end)
30
31 local function rand_pos(center, pos, radius)
32         local def
33         local reg_nodes = minetest.registered_nodes
34         local i = 0
35         repeat
36                 -- Give up and use the center if this takes too long
37                 if i > 4 then
38                         pos.x, pos.z = center.x, center.z
39                         break
40                 end
41                 pos.x = center.x + math.random(-radius, radius)
42                 pos.z = center.z + math.random(-radius, radius)
43                 def = reg_nodes[minetest.get_node(pos).name]
44                 i = i + 1
45         until def and not def.walkable
46 end
47
48 local function eject_drops(drops, pos, radius)
49         local drop_pos = vector.new(pos)
50         for _, item in pairs(drops) do
51                 local count = item:get_count()
52                 local take_est = math.log(count * count) + math.random(0,4) - 2
53                 while count > 0 do
54                         local take = math.max(1,math.min(take_est,
55                                         item:get_count(),
56                                         item:get_stack_max()))
57                         rand_pos(pos, drop_pos, radius)
58                         local dropitem = ItemStack(item)
59                         dropitem:set_count(take)
60                         local obj = minetest.add_item(drop_pos, dropitem)
61                         if obj then
62                                 obj:get_luaentity().collect = true
63                                 obj:setacceleration({x = 0, y = -10, z = 0})
64                                 obj:setvelocity({x = math.random(-3, 3),
65                                                 y = math.random(0, 10),
66                                                 z = math.random(-3, 3)})
67                         end
68                         count = count - take
69                 end
70         end
71 end
72
73 local function add_drop(drops, item)
74         item = ItemStack(item)
75         local name = item:get_name()
76         if loss_prob[name] ~= nil and math.random(1, loss_prob[name]) == 1 then
77                 return
78         end
79
80         local drop = drops[name]
81         if drop == nil then
82                 drops[name] = item
83         else
84                 drop:set_count(drop:get_count() + item:get_count())
85         end
86 end
87
88
89 local function destroy(drops, npos, cid, c_air, c_fire, on_blast_queue, ignore_protection, ignore_on_blast)
90         if not ignore_protection and minetest.is_protected(npos, "") then
91                 return cid
92         end
93
94         local def = cid_data[cid]
95
96         if not def then
97                 return c_air
98         elseif not ignore_on_blast and def.on_blast then
99                 on_blast_queue[#on_blast_queue + 1] = {pos = vector.new(npos), on_blast = def.on_blast}
100                 return cid
101         elseif def.flammable then
102                 return c_fire
103         else
104                 local node_drops = minetest.get_node_drops(def.name, "")
105                 for _, item in ipairs(node_drops) do
106                         add_drop(drops, item)
107                 end
108                 return c_air
109         end
110 end
111
112
113 local function calc_velocity(pos1, pos2, old_vel, power)
114         local vel = vector.direction(pos1, pos2)
115         vel = vector.normalize(vel)
116         vel = vector.multiply(vel, power)
117
118         -- Divide by distance
119         local dist = vector.distance(pos1, pos2)
120         dist = math.max(dist, 1)
121         vel = vector.divide(vel, dist)
122
123         -- Add old velocity
124         vel = vector.add(vel, old_vel)
125
126         -- randomize it a bit
127         vel = vector.add(vel, {
128                 x = math.random() - 0.5,
129                 y = math.random() - 0.5,
130                 z = math.random() - 0.5,
131         })
132
133         -- Limit to terminal velocity
134         dist = vector.length(vel)
135         if dist > 250 then
136                 vel = vector.divide(vel, dist / 250)
137         end
138         return vel
139 end
140
141 local function entity_physics(pos, radius)
142         local objs = minetest.get_objects_inside_radius(pos, radius)
143         for _, obj in pairs(objs) do
144                 local obj_pos = obj:getpos()
145                 local dist = math.max(1, vector.distance(pos, obj_pos))
146
147                 local damage = (4 / dist) * radius
148                 if obj:is_player() then
149                         -- currently the engine has no method to set
150                         -- player velocity. See #2960
151                         -- instead, we knock the player back 1.0 node, and slightly upwards
152                         local dir = vector.normalize(vector.subtract(obj_pos, pos))
153                         local moveoff = vector.multiply(dir, dist + 1.0)
154                         local newpos = vector.add(pos, moveoff)
155                         local newpos = vector.add(newpos, {x = 0, y = 0.2, z = 0})
156                         obj:setpos(newpos)
157
158                         obj:set_hp(obj:get_hp() - damage)
159                 else
160                         local obj_vel = obj:getvelocity()
161                         obj:setvelocity(calc_velocity(pos, obj_pos,
162                                         obj_vel, radius * 10))
163                         if not obj:get_armor_groups().immortal then
164                                 obj:punch(obj, 1.0, {
165                                         full_punch_interval = 1.0,
166                                         damage_groups = {fleshy = damage},
167                                 }, nil)
168                         end
169                 end
170         end
171 end
172
173 local function add_effects(pos, radius, drops)
174         minetest.add_particlespawner({
175                 amount = 64,
176                 time = 0.5,
177                 minpos = vector.subtract(pos, radius / 2),
178                 maxpos = vector.add(pos, radius / 2),
179                 minvel = {x = -10, y = -10, z = -10},
180                 maxvel = {x = 10, y = 10, z = 10},
181                 minacc = vector.new(),
182                 maxacc = vector.new(),
183                 minexptime = 1,
184                 maxexptime = 2.5,
185                 minsize = 8,
186                 maxsize = 16,
187                 texture = "tnt_smoke.png",
188         })
189
190         -- we just dropped some items. Look at the items entities and pick
191         -- one of them to use as texture
192         local texture = "tnt_blast.png" --fallback texture
193         local most = 0
194         for name, stack in pairs(drops) do
195                 local count = stack:get_count()
196                 if count > most then
197                         most = count
198                         local def = minetest.registered_nodes[name]
199                         if def and def.tiles and def.tiles[1] then
200                                 texture = def.tiles[1]
201                         end
202                 end
203         end
204
205         minetest.add_particlespawner({
206                 amount = 64,
207                 time = 0.1,
208                 minpos = vector.subtract(pos, radius / 2),
209                 maxpos = vector.add(pos, radius / 2),
210                 minvel = {x = -3, y = 0, z = -3},
211                 maxvel = {x = 3, y = 5,  z = 3},
212                 minacc = {x = 0, y = -10, z = 0},
213                 maxacc = {x = 0, y = -10, z = 0},
214                 minexptime = 0.8,
215                 maxexptime = 2.0,
216                 minsize = 2,
217                 maxsize = 6,
218                 texture = texture,
219                 collisiondetection = true,
220         })
221 end
222
223 function tnt.burn(pos)
224         local name = minetest.get_node(pos).name
225         local group = minetest.get_item_group(name, "tnt")
226         if group > 0 then
227                 minetest.sound_play("tnt_ignite", {pos = pos})
228                 minetest.set_node(pos, {name = name .. "_burning"})
229                 minetest.get_node_timer(pos):start(1)
230         elseif name == "tnt:gunpowder" then
231                 minetest.set_node(pos, {name = "tnt:gunpowder_burning"})
232         end
233 end
234
235 local function tnt_explode(pos, radius, ignore_protection, ignore_on_blast)
236         local pos = vector.round(pos)
237         local vm = VoxelManip()
238         local pr = PseudoRandom(os.time())
239         local p1 = vector.subtract(pos, radius)
240         local p2 = vector.add(pos, radius)
241         local minp, maxp = vm:read_from_map(p1, p2)
242         local a = VoxelArea:new({MinEdge = minp, MaxEdge = maxp})
243         local data = vm:get_data()
244
245         local drops = {}
246         local on_blast_queue = {}
247
248         local c_air = minetest.get_content_id("air")
249         local c_fire = minetest.get_content_id("fire:basic_flame")
250         for z = -radius, radius do
251         for y = -radius, radius do
252         local vi = a:index(pos.x + (-radius), pos.y + y, pos.z + z)
253         for x = -radius, radius do
254                 local r = vector.length(vector.new(x, y, z))
255                 if (radius * radius) / (r * r) >= (pr:next(80, 125) / 100) then
256                         local cid = data[vi]
257                         local p = {x = pos.x + x, y = pos.y + y, z = pos.z + z}
258                         if cid ~= c_air then
259                                 data[vi] = destroy(drops, p, cid, c_air, c_fire,
260                                         on_blast_queue, ignore_protection,
261                                         ignore_on_blast)
262                         end
263                 end
264                 vi = vi + 1
265         end
266         end
267         end
268
269         vm:set_data(data)
270         vm:write_to_map()
271         vm:update_map()
272         vm:update_liquids()
273
274         -- call nodeupdate for everything within 1.5x blast radius
275         for z = -radius * 1.5, radius * 1.5 do
276         for x = -radius * 1.5, radius * 1.5 do
277         for y = -radius * 1.5, radius * 1.5 do
278                 local s = vector.add(pos, {x = x, y = y, z = z})
279                 local r = vector.distance(pos, s)
280                 if r / radius < 1.4 then
281                         nodeupdate(s)
282                 end
283         end
284         end
285         end
286
287         for _, data in ipairs(on_blast_queue) do
288                 local dist = math.max(1, vector.distance(data.pos, pos))
289                 local intensity = (radius * radius) / (dist * dist)
290                 local node_drops = data.on_blast(data.pos, intensity)
291                 if node_drops then
292                         for _, item in ipairs(node_drops) do
293                                 add_drop(drops, item)
294                         end
295                 end
296         end
297
298         return drops
299 end
300
301 function tnt.boom(pos, def)
302         minetest.sound_play("tnt_explode", {pos = pos, gain = 1.5, max_hear_distance = 2*64})
303         minetest.set_node(pos, {name = "tnt:boom"})
304         local drops = tnt_explode(pos, def.radius, def.ignore_protection,
305                         def.ignore_on_blast)
306         entity_physics(pos, def.damage_radius)
307         if not def.disable_drops then
308                 eject_drops(drops, pos, def.radius)
309         end
310         add_effects(pos, def.radius, drops)
311 end
312
313 minetest.register_node("tnt:boom", {
314         drawtype = "airlike",
315         light_source = default.LIGHT_MAX,
316         walkable = false,
317         drop = "",
318         groups = {dig_immediate = 3},
319         on_construct = function(pos)
320                 minetest.add_particle({
321                         pos = pos,
322                         velocity = vector.new(),
323                         acceleration = vector.new(),
324                         expirationtime = 0.4,
325                         size = 30,
326                         collisiondetection = false,
327                         vertical = false,
328                         texture = "tnt_boom.png",
329                         playername = nil,
330                 })
331                 minetest.get_node_timer(pos):start(0.4)
332         end,
333         on_timer = function(pos, elapsed)
334                 minetest.remove_node(pos)
335         end,
336         -- unaffected by explosions
337         on_blast = function() end,
338 })
339
340 minetest.register_node("tnt:gunpowder", {
341         description = "Gun Powder",
342         drawtype = "raillike",
343         paramtype = "light",
344         is_ground_content = false,
345         sunlight_propagates = true,
346         walkable = false,
347         tiles = {"tnt_gunpowder_straight.png", "tnt_gunpowder_curved.png", "tnt_gunpowder_t_junction.png", "tnt_gunpowder_crossing.png"},
348         inventory_image = "tnt_gunpowder_inventory.png",
349         wield_image = "tnt_gunpowder_inventory.png",
350         selection_box = {
351                 type = "fixed",
352                 fixed = {-1/2, -1/2, -1/2, 1/2, -1/2+1/16, 1/2},
353         },
354         groups = {dig_immediate = 2, attached_node = 1, connect_to_raillike = minetest.raillike_group("gunpowder")},
355         sounds = default.node_sound_leaves_defaults(),
356
357         on_punch = function(pos, node, puncher)
358                 if puncher:get_wielded_item():get_name() == "default:torch" then
359                         tnt.burn(pos)
360                 end
361         end,
362         on_blast = function(pos, intensity)
363                 tnt.burn(pos)
364         end,
365 })
366
367 minetest.register_node("tnt:gunpowder_burning", {
368         drawtype = "raillike",
369         paramtype = "light",
370         sunlight_propagates = true,
371         walkable = false,
372         light_source = 5,
373         tiles = {{
374                 name = "tnt_gunpowder_burning_straight_animated.png",
375                 animation = {
376                         type = "vertical_frames",
377                         aspect_w = 16,
378                         aspect_h = 16,
379                         length = 1,
380                 }
381         },
382         {
383                 name = "tnt_gunpowder_burning_curved_animated.png",
384                 animation = {
385                         type = "vertical_frames",
386                         aspect_w = 16,
387                         aspect_h = 16,
388                         length = 1,
389                 }
390         },
391         {
392                 name = "tnt_gunpowder_burning_t_junction_animated.png",
393                 animation = {
394                         type = "vertical_frames",
395                         aspect_w = 16,
396                         aspect_h = 16,
397                         length = 1,
398                 }
399         },
400         {
401                 name = "tnt_gunpowder_burning_crossing_animated.png",
402                 animation = {
403                         type = "vertical_frames",
404                         aspect_w = 16,
405                         aspect_h = 16,
406                         length = 1,
407                 }
408         }},
409         selection_box = {
410                 type = "fixed",
411                 fixed = {-1/2, -1/2, -1/2, 1/2, -1/2+1/16, 1/2},
412         },
413         drop = "",
414         groups = {dig_immediate = 2, attached_node = 1, connect_to_raillike = minetest.raillike_group("gunpowder")},
415         sounds = default.node_sound_leaves_defaults(),
416         on_timer = function(pos, elapsed)
417                 for dx = -1, 1 do
418                 for dz = -1, 1 do
419                 for dy = -1, 1 do
420                         if not (dx == 0 and dz == 0) then
421                                 tnt.burn({
422                                         x = pos.x + dx,
423                                         y = pos.y + dy,
424                                         z = pos.z + dz,
425                                 })
426                         end
427                 end
428                 end
429                 end
430                 minetest.remove_node(pos)
431         end,
432         -- unaffected by explosions
433         on_blast = function() end,
434         on_construct = function(pos)
435                 minetest.sound_play("tnt_gunpowder_burning", {pos = pos, gain = 2})
436                 minetest.get_node_timer(pos):start(1)
437         end,
438 })
439
440 minetest.register_abm({
441         nodenames = {"group:tnt", "tnt:gunpowder"},
442         neighbors = {"fire:basic_flame", "default:lava_source", "default:lava_flowing"},
443         interval = 4,
444         chance = 1,
445         action = tnt.burn,
446 })
447
448 minetest.register_craft({
449         output = "tnt:gunpowder",
450         type = "shapeless",
451         recipe = {"default:coal_lump", "default:gravel"}
452 })
453
454 minetest.register_craft({
455         output = "tnt:tnt",
456         recipe = {
457                 {"",           "group:wood",    ""},
458                 {"group:wood", "tnt:gunpowder", "group:wood"},
459                 {"",           "group:wood",    ""}
460         }
461 })
462
463 function tnt.register_tnt(def)
464         local name = ""
465         if not def.name:find(':') then
466                 name = "tnt:" .. def.name
467         else
468                 name = def.name
469                 def.name = def.name:match(":([%w_]+)")
470         end
471         if not def.tiles then def.tiles = {} end
472         local tnt_top = def.tiles.top or def.name .. "_top.png"
473         local tnt_bottom = def.tiles.bottom or def.name .. "_bottom.png"
474         local tnt_side = def.tiles.side or def.name .. "_side.png"
475         local tnt_burning = def.tiles.burning or def.name .. "_top_burning_animated.png"
476         if not def.damage_radius then def.damage_radius = def.radius * 2 end
477
478         minetest.register_node(":" .. name, {
479                 description = def.description,
480                 tiles = {tnt_top, tnt_bottom, tnt_side},
481                 is_ground_content = false,
482                 groups = {dig_immediate = 2, mesecon = 2, tnt = 1},
483                 sounds = default.node_sound_wood_defaults(),
484                 on_punch = function(pos, node, puncher)
485                         if puncher:get_wielded_item():get_name() == "default:torch" then
486                                 minetest.set_node(pos, {name = name .. "_burning"})
487                         end
488                 end,
489                 on_blast = function(pos, intensity)
490                         minetest.after(0.1, function()
491                                 tnt.boom(pos, def)
492                         end)
493                 end,
494                 mesecons = {effector =
495                         {action_on =
496                                 function(pos)
497                                         tnt.boom(pos, def)
498                                 end
499                         }
500                 },
501         })
502
503         minetest.register_node(":" .. name .. "_burning", {
504                 tiles = {
505                         {
506                                 name = tnt_burning,
507                                 animation = {
508                                         type = "vertical_frames",
509                                         aspect_w = 16,
510                                         aspect_h = 16,
511                                         length = 1,
512                                 }
513                         },
514                         tnt_bottom, tnt_side
515                         },
516                 light_source = 5,
517                 drop = "",
518                 sounds = default.node_sound_wood_defaults(),
519                 groups = {falling_node = 1},
520                 on_timer = function(pos, elapsed)
521                         tnt.boom(pos, def)
522                 end,
523                 -- unaffected by explosions
524                 on_blast = function() end,
525                 on_construct = function(pos)
526                         minetest.sound_play("tnt_ignite", {pos = pos})
527                         minetest.get_node_timer(pos):start(4)
528                         nodeupdate(pos)
529                 end,
530         })
531 end
532
533 tnt.register_tnt({
534         name = "tnt:tnt",
535         description = "TNT",
536         radius = radius,
537 })
538