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