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