Remove unused and clean up missused variable-value assignments.
[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 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 = item:get_count()
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 ipairs(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 ipairs(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)
252         local name = 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 nodeupdate for everything within 1.5x blast radius
336         for z = -radius * 1.5, radius * 1.5 do
337         for x = -radius * 1.5, radius * 1.5 do
338         for y = -radius * 1.5, radius * 1.5 do
339                 local s = vector.add(pos, {x = x, y = y, z = z})
340                 local r = vector.distance(pos, s)
341                 if r / radius < 1.4 then
342                         nodeupdate(s)
343                 end
344         end
345         end
346         end
347
348         for _, data in ipairs(on_blast_queue) do
349                 local dist = math.max(1, vector.distance(data.pos, pos))
350                 local intensity = (radius * radius) / (dist * dist)
351                 local node_drops = data.on_blast(data.pos, intensity)
352                 if node_drops then
353                         for _, item in ipairs(node_drops) do
354                                 add_drop(drops, item)
355                         end
356                 end
357         end
358
359         return drops, radius
360 end
361
362 function tnt.boom(pos, def)
363         minetest.sound_play("tnt_explode", {pos = pos, gain = 1.5, max_hear_distance = 2*64})
364         minetest.set_node(pos, {name = "tnt:boom"})
365         local drops, radius = tnt_explode(pos, def.radius, def.ignore_protection,
366                         def.ignore_on_blast)
367         -- append entity drops
368         local damage_radius = (radius / def.radius) * def.damage_radius
369         entity_physics(pos, damage_radius, drops)
370         if not def.disable_drops then
371                 eject_drops(drops, pos, radius)
372         end
373         add_effects(pos, radius, drops)
374 end
375
376 minetest.register_node("tnt:boom", {
377         drawtype = "airlike",
378         light_source = default.LIGHT_MAX,
379         walkable = false,
380         drop = "",
381         groups = {dig_immediate = 3},
382         on_construct = function(pos)
383                 minetest.get_node_timer(pos):start(0.4)
384         end,
385         on_timer = function(pos, elapsed)
386                 minetest.remove_node(pos)
387         end,
388         -- unaffected by explosions
389         on_blast = function() end,
390 })
391
392 minetest.register_node("tnt:gunpowder", {
393         description = "Gun Powder",
394         drawtype = "raillike",
395         paramtype = "light",
396         is_ground_content = false,
397         sunlight_propagates = true,
398         walkable = false,
399         tiles = {"tnt_gunpowder_straight.png", "tnt_gunpowder_curved.png", "tnt_gunpowder_t_junction.png", "tnt_gunpowder_crossing.png"},
400         inventory_image = "tnt_gunpowder_inventory.png",
401         wield_image = "tnt_gunpowder_inventory.png",
402         selection_box = {
403                 type = "fixed",
404                 fixed = {-1/2, -1/2, -1/2, 1/2, -1/2+1/16, 1/2},
405         },
406         groups = {dig_immediate = 2, attached_node = 1, connect_to_raillike = minetest.raillike_group("gunpowder")},
407         sounds = default.node_sound_leaves_defaults(),
408
409         on_punch = function(pos, node, puncher)
410                 if puncher:get_wielded_item():get_name() == "default:torch" then
411                         tnt.burn(pos)
412                 end
413         end,
414         on_blast = function(pos, intensity)
415                 tnt.burn(pos)
416         end,
417 })
418
419 minetest.register_node("tnt:gunpowder_burning", {
420         drawtype = "raillike",
421         paramtype = "light",
422         sunlight_propagates = true,
423         walkable = false,
424         light_source = 5,
425         tiles = {{
426                 name = "tnt_gunpowder_burning_straight_animated.png",
427                 animation = {
428                         type = "vertical_frames",
429                         aspect_w = 16,
430                         aspect_h = 16,
431                         length = 1,
432                 }
433         },
434         {
435                 name = "tnt_gunpowder_burning_curved_animated.png",
436                 animation = {
437                         type = "vertical_frames",
438                         aspect_w = 16,
439                         aspect_h = 16,
440                         length = 1,
441                 }
442         },
443         {
444                 name = "tnt_gunpowder_burning_t_junction_animated.png",
445                 animation = {
446                         type = "vertical_frames",
447                         aspect_w = 16,
448                         aspect_h = 16,
449                         length = 1,
450                 }
451         },
452         {
453                 name = "tnt_gunpowder_burning_crossing_animated.png",
454                 animation = {
455                         type = "vertical_frames",
456                         aspect_w = 16,
457                         aspect_h = 16,
458                         length = 1,
459                 }
460         }},
461         selection_box = {
462                 type = "fixed",
463                 fixed = {-1/2, -1/2, -1/2, 1/2, -1/2+1/16, 1/2},
464         },
465         drop = "",
466         groups = {dig_immediate = 2, attached_node = 1, connect_to_raillike = minetest.raillike_group("gunpowder")},
467         sounds = default.node_sound_leaves_defaults(),
468         on_timer = function(pos, elapsed)
469                 for dx = -1, 1 do
470                 for dz = -1, 1 do
471                 for dy = -1, 1 do
472                         if not (dx == 0 and dz == 0) then
473                                 tnt.burn({
474                                         x = pos.x + dx,
475                                         y = pos.y + dy,
476                                         z = pos.z + dz,
477                                 })
478                         end
479                 end
480                 end
481                 end
482                 minetest.remove_node(pos)
483         end,
484         -- unaffected by explosions
485         on_blast = function() end,
486         on_construct = function(pos)
487                 minetest.sound_play("tnt_gunpowder_burning", {pos = pos, gain = 2})
488                 minetest.get_node_timer(pos):start(1)
489         end,
490 })
491
492 minetest.register_craft({
493         output = "tnt:gunpowder",
494         type = "shapeless",
495         recipe = {"default:coal_lump", "default:gravel"}
496 })
497
498 if enable_tnt then
499         minetest.register_craft({
500                 output = "tnt:tnt",
501                 recipe = {
502                         {"",           "group:wood",    ""},
503                         {"group:wood", "tnt:gunpowder", "group:wood"},
504                         {"",           "group:wood",    ""}
505                 }
506         })
507
508         minetest.register_abm({
509                 nodenames = {"group:tnt", "tnt:gunpowder"},
510                 neighbors = {"fire:basic_flame", "default:lava_source", "default:lava_flowing"},
511                 interval = 4,
512                 chance = 1,
513                 action = tnt.burn,
514         })
515 end
516
517 function tnt.register_tnt(def)
518         local name
519         if not def.name:find(':') then
520                 name = "tnt:" .. def.name
521         else
522                 name = def.name
523                 def.name = def.name:match(":([%w_]+)")
524         end
525         if not def.tiles then def.tiles = {} end
526         local tnt_top = def.tiles.top or def.name .. "_top.png"
527         local tnt_bottom = def.tiles.bottom or def.name .. "_bottom.png"
528         local tnt_side = def.tiles.side or def.name .. "_side.png"
529         local tnt_burning = def.tiles.burning or def.name .. "_top_burning_animated.png"
530         if not def.damage_radius then def.damage_radius = def.radius * 2 end
531
532         if enable_tnt then
533                 minetest.register_node(":" .. name, {
534                         description = def.description,
535                         tiles = {tnt_top, tnt_bottom, tnt_side},
536                         is_ground_content = false,
537                         groups = {dig_immediate = 2, mesecon = 2, tnt = 1},
538                         sounds = default.node_sound_wood_defaults(),
539                         on_punch = function(pos, node, puncher)
540                                 if puncher:get_wielded_item():get_name() == "default:torch" then
541                                         minetest.set_node(pos, {name = name .. "_burning"})
542                                 end
543                         end,
544                         on_blast = function(pos, intensity)
545                                 minetest.after(0.1, function()
546                                         tnt.boom(pos, def)
547                                 end)
548                         end,
549                         mesecons = {effector =
550                                 {action_on =
551                                         function(pos)
552                                                 tnt.boom(pos, def)
553                                         end
554                                 }
555                         },
556                 })
557         end
558
559         minetest.register_node(":" .. name .. "_burning", {
560                 tiles = {
561                         {
562                                 name = tnt_burning,
563                                 animation = {
564                                         type = "vertical_frames",
565                                         aspect_w = 16,
566                                         aspect_h = 16,
567                                         length = 1,
568                                 }
569                         },
570                         tnt_bottom, tnt_side
571                         },
572                 light_source = 5,
573                 drop = "",
574                 sounds = default.node_sound_wood_defaults(),
575                 groups = {falling_node = 1},
576                 on_timer = function(pos, elapsed)
577                         tnt.boom(pos, def)
578                 end,
579                 -- unaffected by explosions
580                 on_blast = function() end,
581                 on_construct = function(pos)
582                         minetest.sound_play("tnt_ignite", {pos = pos})
583                         minetest.get_node_timer(pos):start(4)
584                         nodeupdate(pos)
585                 end,
586         })
587 end
588
589 tnt.register_tnt({
590         name = "tnt:tnt",
591         description = "TNT",
592         radius = radius,
593 })