Fix potential crash when few loot items are registered
[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:set_acceleration({x = 0, y = -10, z = 0})
62                                 obj:set_velocity({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:get_pos()
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:set_pos(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:get_velocity()
183                                 obj:set_velocity(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         local sound = def.sound or "tnt_explode"
399         minetest.sound_play(sound, {pos = pos, gain = 1.5,
400                         max_hear_distance = math.min(def.radius * 20, 128)})
401         local drops, radius = tnt_explode(pos, def.radius, def.ignore_protection,
402                         def.ignore_on_blast, owner, def.explode_center)
403         -- append entity drops
404         local damage_radius = (radius / math.max(1, def.radius)) * def.damage_radius
405         entity_physics(pos, damage_radius, drops)
406         if not def.disable_drops then
407                 eject_drops(drops, pos, radius)
408         end
409         add_effects(pos, radius, drops)
410         minetest.log("action", "A TNT explosion occurred at " .. minetest.pos_to_string(pos) ..
411                 " with radius " .. radius)
412 end
413
414 minetest.register_node("tnt:boom", {
415         drawtype = "airlike",
416         light_source = default.LIGHT_MAX,
417         walkable = false,
418         drop = "",
419         groups = {dig_immediate = 3},
420         -- unaffected by explosions
421         on_blast = function() end,
422 })
423
424 minetest.register_node("tnt:gunpowder", {
425         description = "Gun Powder",
426         drawtype = "raillike",
427         paramtype = "light",
428         is_ground_content = false,
429         sunlight_propagates = true,
430         walkable = false,
431         tiles = {
432                 "tnt_gunpowder_straight.png",
433                 "tnt_gunpowder_curved.png",
434                 "tnt_gunpowder_t_junction.png",
435                 "tnt_gunpowder_crossing.png"
436         },
437         inventory_image = "tnt_gunpowder_inventory.png",
438         wield_image = "tnt_gunpowder_inventory.png",
439         selection_box = {
440                 type = "fixed",
441                 fixed = {-1/2, -1/2, -1/2, 1/2, -1/2+1/16, 1/2},
442         },
443         groups = {dig_immediate = 2, attached_node = 1, flammable = 5,
444                 connect_to_raillike = minetest.raillike_group("gunpowder")},
445         sounds = default.node_sound_leaves_defaults(),
446
447         on_punch = function(pos, node, puncher)
448                 if puncher:get_wielded_item():get_name() == "default:torch" then
449                         minetest.set_node(pos, {name = "tnt:gunpowder_burning"})
450                         minetest.log("action", puncher:get_player_name() ..
451                                 " ignites tnt:gunpowder at " ..
452                                 minetest.pos_to_string(pos))
453                 end
454         end,
455         on_blast = function(pos, intensity)
456                 minetest.set_node(pos, {name = "tnt:gunpowder_burning"})
457         end,
458         on_burn = function(pos)
459                 minetest.set_node(pos, {name = "tnt:gunpowder_burning"})
460         end,
461         on_ignite = function(pos, igniter)
462                 minetest.set_node(pos, {name = "tnt:gunpowder_burning"})
463         end,
464 })
465
466 minetest.register_node("tnt:gunpowder_burning", {
467         drawtype = "raillike",
468         paramtype = "light",
469         sunlight_propagates = true,
470         walkable = false,
471         light_source = 5,
472         tiles = {{
473                 name = "tnt_gunpowder_burning_straight_animated.png",
474                 animation = {
475                         type = "vertical_frames",
476                         aspect_w = 16,
477                         aspect_h = 16,
478                         length = 1,
479                 }
480         },
481         {
482                 name = "tnt_gunpowder_burning_curved_animated.png",
483                 animation = {
484                         type = "vertical_frames",
485                         aspect_w = 16,
486                         aspect_h = 16,
487                         length = 1,
488                 }
489         },
490         {
491                 name = "tnt_gunpowder_burning_t_junction_animated.png",
492                 animation = {
493                         type = "vertical_frames",
494                         aspect_w = 16,
495                         aspect_h = 16,
496                         length = 1,
497                 }
498         },
499         {
500                 name = "tnt_gunpowder_burning_crossing_animated.png",
501                 animation = {
502                         type = "vertical_frames",
503                         aspect_w = 16,
504                         aspect_h = 16,
505                         length = 1,
506                 }
507         }},
508         selection_box = {
509                 type = "fixed",
510                 fixed = {-1/2, -1/2, -1/2, 1/2, -1/2+1/16, 1/2},
511         },
512         drop = "",
513         groups = {
514                 dig_immediate = 2,
515                 attached_node = 1,
516                 connect_to_raillike = minetest.raillike_group("gunpowder")
517         },
518         sounds = default.node_sound_leaves_defaults(),
519         on_timer = function(pos, elapsed)
520                 for dx = -1, 1 do
521                 for dz = -1, 1 do
522                         if math.abs(dx) + math.abs(dz) == 1 then
523                                 for dy = -1, 1 do
524                                         tnt.burn({
525                                                 x = pos.x + dx,
526                                                 y = pos.y + dy,
527                                                 z = pos.z + dz,
528                                         })
529                                 end
530                         end
531                 end
532                 end
533                 minetest.remove_node(pos)
534         end,
535         -- unaffected by explosions
536         on_blast = function() end,
537         on_construct = function(pos)
538                 minetest.sound_play("tnt_gunpowder_burning", {pos = pos, gain = 2})
539                 minetest.get_node_timer(pos):start(1)
540         end,
541 })
542
543 minetest.register_craft({
544         output = "tnt:gunpowder 5",
545         type = "shapeless",
546         recipe = {"default:coal_lump", "default:gravel"}
547 })
548
549 minetest.register_craftitem("tnt:tnt_stick", {
550         description = "TNT Stick",
551         inventory_image = "tnt_tnt_stick.png",
552         groups = {flammable = 5},
553 })
554
555 if enable_tnt then
556         minetest.register_craft({
557                 output = "tnt:tnt_stick 2",
558                 recipe = {
559                         {"tnt:gunpowder", "", "tnt:gunpowder"},
560                         {"tnt:gunpowder", "default:paper", "tnt:gunpowder"},
561                         {"tnt:gunpowder", "", "tnt:gunpowder"},
562                 }
563         })
564
565         minetest.register_craft({
566                 output = "tnt:tnt",
567                 recipe = {
568                         {"tnt:tnt_stick", "tnt:tnt_stick", "tnt:tnt_stick"},
569                         {"tnt:tnt_stick", "tnt:tnt_stick", "tnt:tnt_stick"},
570                         {"tnt:tnt_stick", "tnt:tnt_stick", "tnt:tnt_stick"}
571                 }
572         })
573
574         minetest.register_abm({
575                 label = "TNT ignition",
576                 nodenames = {"group:tnt", "tnt:gunpowder"},
577                 neighbors = {"fire:basic_flame", "default:lava_source", "default:lava_flowing"},
578                 interval = 4,
579                 chance = 1,
580                 action = function(pos, node)
581                         tnt.burn(pos, node.name)
582                 end,
583         })
584 end
585
586 function tnt.register_tnt(def)
587         local name
588         if not def.name:find(':') then
589                 name = "tnt:" .. def.name
590         else
591                 name = def.name
592                 def.name = def.name:match(":([%w_]+)")
593         end
594         if not def.tiles then def.tiles = {} end
595         local tnt_top = def.tiles.top or def.name .. "_top.png"
596         local tnt_bottom = def.tiles.bottom or def.name .. "_bottom.png"
597         local tnt_side = def.tiles.side or def.name .. "_side.png"
598         local tnt_burning = def.tiles.burning or def.name .. "_top_burning_animated.png"
599         if not def.damage_radius then def.damage_radius = def.radius * 2 end
600
601         if enable_tnt then
602                 minetest.register_node(":" .. name, {
603                         description = def.description,
604                         tiles = {tnt_top, tnt_bottom, tnt_side},
605                         is_ground_content = false,
606                         groups = {dig_immediate = 2, mesecon = 2, tnt = 1, flammable = 5},
607                         sounds = default.node_sound_wood_defaults(),
608                         after_place_node = function(pos, placer)
609                                 if placer:is_player() then
610                                         local meta = minetest.get_meta(pos)
611                                         meta:set_string("owner", placer:get_player_name())
612                                 end
613                         end,
614                         on_punch = function(pos, node, puncher)
615                                 if puncher:get_wielded_item():get_name() == "default:torch" then
616                                         minetest.swap_node(pos, {name = name .. "_burning"})
617                                         minetest.registered_nodes[name .. "_burning"].on_construct(pos)
618                                         minetest.log("action", puncher:get_player_name() ..
619                                                 " ignites " .. node.name .. " at " ..
620                                                 minetest.pos_to_string(pos))
621                                 end
622                         end,
623                         on_blast = function(pos, intensity)
624                                 minetest.after(0.1, function()
625                                         tnt.boom(pos, def)
626                                 end)
627                         end,
628                         mesecons = {effector =
629                                 {action_on =
630                                         function(pos)
631                                                 tnt.boom(pos, def)
632                                         end
633                                 }
634                         },
635                         on_burn = function(pos)
636                                 minetest.swap_node(pos, {name = name .. "_burning"})
637                                 minetest.registered_nodes[name .. "_burning"].on_construct(pos)
638                         end,
639                         on_ignite = function(pos, igniter)
640                                 minetest.swap_node(pos, {name = name .. "_burning"})
641                                 minetest.registered_nodes[name .. "_burning"].on_construct(pos)
642                         end,
643                 })
644         end
645
646         minetest.register_node(":" .. name .. "_burning", {
647                 tiles = {
648                         {
649                                 name = tnt_burning,
650                                 animation = {
651                                         type = "vertical_frames",
652                                         aspect_w = 16,
653                                         aspect_h = 16,
654                                         length = 1,
655                                 }
656                         },
657                         tnt_bottom, tnt_side
658                         },
659                 light_source = 5,
660                 drop = "",
661                 sounds = default.node_sound_wood_defaults(),
662                 groups = {falling_node = 1},
663                 on_timer = function(pos, elapsed)
664                         tnt.boom(pos, def)
665                 end,
666                 -- unaffected by explosions
667                 on_blast = function() end,
668                 on_construct = function(pos)
669                         minetest.sound_play("tnt_ignite", {pos = pos})
670                         minetest.get_node_timer(pos):start(4)
671                         minetest.check_for_falling(pos)
672                 end,
673         })
674 end
675
676 tnt.register_tnt({
677         name = "tnt:tnt",
678         description = "TNT",
679         radius = tnt_radius,
680 })