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