f9bc307c50b1f72600f629d5b99cc4a4cd829997
[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 end
376
377 minetest.register_node("tnt:boom", {
378         drawtype = "airlike",
379         light_source = default.LIGHT_MAX,
380         walkable = false,
381         drop = "",
382         groups = {dig_immediate = 3},
383         on_construct = function(pos)
384                 minetest.get_node_timer(pos):start(0.4)
385         end,
386         on_timer = function(pos, elapsed)
387                 minetest.remove_node(pos)
388         end,
389         -- unaffected by explosions
390         on_blast = function() end,
391 })
392
393 minetest.register_node("tnt:gunpowder", {
394         description = "Gun Powder",
395         drawtype = "raillike",
396         paramtype = "light",
397         is_ground_content = false,
398         sunlight_propagates = true,
399         walkable = false,
400         tiles = {"tnt_gunpowder_straight.png", "tnt_gunpowder_curved.png", "tnt_gunpowder_t_junction.png", "tnt_gunpowder_crossing.png"},
401         inventory_image = "tnt_gunpowder_inventory.png",
402         wield_image = "tnt_gunpowder_inventory.png",
403         selection_box = {
404                 type = "fixed",
405                 fixed = {-1/2, -1/2, -1/2, 1/2, -1/2+1/16, 1/2},
406         },
407         groups = {dig_immediate = 2, attached_node = 1, flammable = 5,
408                 connect_to_raillike = minetest.raillike_group("gunpowder")},
409         sounds = default.node_sound_leaves_defaults(),
410
411         on_punch = function(pos, node, puncher)
412                 if puncher:get_wielded_item():get_name() == "default:torch" then
413                         minetest.set_node(pos, {name = "tnt:gunpowder_burning"})
414                 end
415         end,
416         on_blast = function(pos, intensity)
417                 minetest.set_node(pos, {name = "tnt:gunpowder_burning"})
418         end,
419         on_burn = function(pos)
420                 minetest.set_node(pos, {name = "tnt:gunpowder_burning"})
421         end,
422         on_ignite = function(pos, igniter)
423                 minetest.set_node(pos, {name = "tnt:gunpowder_burning"})
424         end,
425 })
426
427 minetest.register_node("tnt:gunpowder_burning", {
428         drawtype = "raillike",
429         paramtype = "light",
430         sunlight_propagates = true,
431         walkable = false,
432         light_source = 5,
433         tiles = {{
434                 name = "tnt_gunpowder_burning_straight_animated.png",
435                 animation = {
436                         type = "vertical_frames",
437                         aspect_w = 16,
438                         aspect_h = 16,
439                         length = 1,
440                 }
441         },
442         {
443                 name = "tnt_gunpowder_burning_curved_animated.png",
444                 animation = {
445                         type = "vertical_frames",
446                         aspect_w = 16,
447                         aspect_h = 16,
448                         length = 1,
449                 }
450         },
451         {
452                 name = "tnt_gunpowder_burning_t_junction_animated.png",
453                 animation = {
454                         type = "vertical_frames",
455                         aspect_w = 16,
456                         aspect_h = 16,
457                         length = 1,
458                 }
459         },
460         {
461                 name = "tnt_gunpowder_burning_crossing_animated.png",
462                 animation = {
463                         type = "vertical_frames",
464                         aspect_w = 16,
465                         aspect_h = 16,
466                         length = 1,
467                 }
468         }},
469         selection_box = {
470                 type = "fixed",
471                 fixed = {-1/2, -1/2, -1/2, 1/2, -1/2+1/16, 1/2},
472         },
473         drop = "",
474         groups = {dig_immediate = 2, attached_node = 1, connect_to_raillike = minetest.raillike_group("gunpowder")},
475         sounds = default.node_sound_leaves_defaults(),
476         on_timer = function(pos, elapsed)
477                 for dx = -1, 1 do
478                 for dz = -1, 1 do
479                 for dy = -1, 1 do
480                         if not (dx == 0 and dz == 0) then
481                                 tnt.burn({
482                                         x = pos.x + dx,
483                                         y = pos.y + dy,
484                                         z = pos.z + dz,
485                                 })
486                         end
487                 end
488                 end
489                 end
490                 minetest.remove_node(pos)
491         end,
492         -- unaffected by explosions
493         on_blast = function() end,
494         on_construct = function(pos)
495                 minetest.sound_play("tnt_gunpowder_burning", {pos = pos, gain = 2})
496                 minetest.get_node_timer(pos):start(1)
497         end,
498 })
499
500 minetest.register_craft({
501         output = "tnt:gunpowder",
502         type = "shapeless",
503         recipe = {"default:coal_lump", "default:gravel"}
504 })
505
506 if enable_tnt then
507         minetest.register_craft({
508                 output = "tnt:tnt",
509                 recipe = {
510                         {"",           "group:wood",    ""},
511                         {"group:wood", "tnt:gunpowder", "group:wood"},
512                         {"",           "group:wood",    ""}
513                 }
514         })
515
516         minetest.register_abm({
517                 label = "TNT ignition",
518                 nodenames = {"group:tnt", "tnt:gunpowder"},
519                 neighbors = {"fire:basic_flame", "default:lava_source", "default:lava_flowing"},
520                 interval = 4,
521                 chance = 1,
522                 action = function(pos, node)
523                         tnt.burn(pos, node.name)
524                 end,
525         })
526 end
527
528 function tnt.register_tnt(def)
529         local name
530         if not def.name:find(':') then
531                 name = "tnt:" .. def.name
532         else
533                 name = def.name
534                 def.name = def.name:match(":([%w_]+)")
535         end
536         if not def.tiles then def.tiles = {} end
537         local tnt_top = def.tiles.top or def.name .. "_top.png"
538         local tnt_bottom = def.tiles.bottom or def.name .. "_bottom.png"
539         local tnt_side = def.tiles.side or def.name .. "_side.png"
540         local tnt_burning = def.tiles.burning or def.name .. "_top_burning_animated.png"
541         if not def.damage_radius then def.damage_radius = def.radius * 2 end
542
543         if enable_tnt then
544                 minetest.register_node(":" .. name, {
545                         description = def.description,
546                         tiles = {tnt_top, tnt_bottom, tnt_side},
547                         is_ground_content = false,
548                         groups = {dig_immediate = 2, mesecon = 2, tnt = 1, flammable = 5},
549                         sounds = default.node_sound_wood_defaults(),
550                         on_punch = function(pos, node, puncher)
551                                 if puncher:get_wielded_item():get_name() == "default:torch" then
552                                         minetest.set_node(pos, {name = name .. "_burning"})
553                                 end
554                         end,
555                         on_blast = function(pos, intensity)
556                                 minetest.after(0.1, function()
557                                         tnt.boom(pos, def)
558                                 end)
559                         end,
560                         mesecons = {effector =
561                                 {action_on =
562                                         function(pos)
563                                                 tnt.boom(pos, def)
564                                         end
565                                 }
566                         },
567                         on_burn = function(pos)
568                                 minetest.set_node(pos, {name = name .. "_burning"})
569                         end,
570                         on_ignite = function(pos, igniter)
571                                 minetest.set_node(pos, {name = name .. "_burning"})
572                         end,
573                 })
574         end
575
576         minetest.register_node(":" .. name .. "_burning", {
577                 tiles = {
578                         {
579                                 name = tnt_burning,
580                                 animation = {
581                                         type = "vertical_frames",
582                                         aspect_w = 16,
583                                         aspect_h = 16,
584                                         length = 1,
585                                 }
586                         },
587                         tnt_bottom, tnt_side
588                         },
589                 light_source = 5,
590                 drop = "",
591                 sounds = default.node_sound_wood_defaults(),
592                 groups = {falling_node = 1},
593                 on_timer = function(pos, elapsed)
594                         tnt.boom(pos, def)
595                 end,
596                 -- unaffected by explosions
597                 on_blast = function() end,
598                 on_construct = function(pos)
599                         minetest.sound_play("tnt_ignite", {pos = pos})
600                         minetest.get_node_timer(pos):start(4)
601                         minetest.check_for_falling(pos)
602                 end,
603         })
604 end
605
606 tnt.register_tnt({
607         name = "tnt:tnt",
608         description = "TNT",
609         radius = tnt_radius,
610 })