3ef8a844ef011658ed2b00aa4508981d0a4750cd
[oweals/minetest_game.git] / mods / tnt / init.lua
1 tnt = {}
2 -- Default to enabled in singleplayer and disabled in multiplayer
3 local singleplayer = minetest.is_singleplayer()
4 local setting = minetest.setting_getbool("enable_tnt")
5 if (not singleplayer and setting ~= true) or
6                 (singleplayer and setting == false) then
7         return
8 end
9
10 -- loss probabilities array (one in X will be lost)
11 local loss_prob = {}
12
13 loss_prob["default:cobble"] = 3
14 loss_prob["default:dirt"] = 4
15
16 local radius = tonumber(minetest.setting_get("tnt_radius") or 3)
17
18 -- Fill a list with data for content IDs, after all nodes are registered
19 local cid_data = {}
20 minetest.after(0, function()
21         for name, def in pairs(minetest.registered_nodes) do
22                 cid_data[minetest.get_content_id(name)] = {
23                         name = name,
24                         drops = def.drops,
25                         flammable = def.groups.flammable,
26                         on_blast = def.on_blast,
27                 }
28         end
29 end)
30
31 local function rand_pos(center, pos, radius)
32         local def
33         local reg_nodes = minetest.registered_nodes
34         local i = 0
35         repeat
36                 -- Give up and use the center if this takes too long
37                 if i > 4 then
38                         pos.x, pos.z = center.x, center.z
39                         break
40                 end
41                 pos.x = center.x + math.random(-radius, radius)
42                 pos.z = center.z + math.random(-radius, radius)
43                 def = reg_nodes[minetest.get_node(pos).name]
44                 i = i + 1
45         until def and not def.walkable
46 end
47
48 local function eject_drops(drops, pos, radius)
49         local drop_pos = vector.new(pos)
50         for _, item in pairs(drops) do
51                 local count = item:get_count()
52                 local take_est = math.log(count * count) + math.random(0,4) - 2
53                 while count > 0 do
54                         local take = math.max(1,math.min(take_est,
55                                         item:get_count(),
56                                         item:get_stack_max()))
57                         rand_pos(pos, drop_pos, radius)
58                         local dropitem = ItemStack(item)
59                         dropitem:set_count(take)
60                         local obj = minetest.add_item(drop_pos, dropitem)
61                         if obj then
62                                 obj:get_luaentity().collect = true
63                                 obj:setacceleration({x = 0, y = -10, z = 0})
64                                 obj:setvelocity({x = math.random(-3, 3),
65                                                 y = math.random(0, 10),
66                                                 z = math.random(-3, 3)})
67                         end
68                         count = count - take
69                 end
70         end
71 end
72
73 local function add_drop(drops, item)
74         item = ItemStack(item)
75         local name = item:get_name()
76         if loss_prob[name] ~= nil and math.random(1, loss_prob[name]) == 1 then
77                 return
78         end
79
80         local drop = drops[name]
81         if drop == nil then
82                 drops[name] = item
83         else
84                 drop:set_count(drop:get_count() + item:get_count())
85         end
86 end
87
88
89 local function destroy(drops, npos, cid, c_air, c_fire, on_blast_queue, ignore_protection, ignore_on_blast)
90         if not ignore_protection and minetest.is_protected(npos, "") then
91                 return cid
92         end
93
94         local def = cid_data[cid]
95
96         if not def then
97                 return c_air
98         elseif not ignore_on_blast and def.on_blast then
99                 on_blast_queue[#on_blast_queue + 1] = {pos = vector.new(npos), on_blast = def.on_blast}
100                 return cid
101         elseif def.flammable then
102                 return c_fire
103         else
104                 local node_drops = minetest.get_node_drops(def.name, "")
105                 for _, item in ipairs(node_drops) do
106                         add_drop(drops, item)
107                 end
108                 return c_air
109         end
110 end
111
112
113 local function calc_velocity(pos1, pos2, old_vel, power)
114         local vel = vector.direction(pos1, pos2)
115         vel = vector.normalize(vel)
116         vel = vector.multiply(vel, power)
117
118         -- Divide by distance
119         local dist = vector.distance(pos1, pos2)
120         dist = math.max(dist, 1)
121         vel = vector.divide(vel, dist)
122
123         -- Add old velocity
124         vel = vector.add(vel, old_vel)
125
126         -- randomize it a bit
127         vel = vector.add(vel, {
128                 x = math.random() - 0.5,
129                 y = math.random() - 0.5,
130                 z = math.random() - 0.5,
131         })
132
133         -- Limit to terminal velocity
134         dist = vector.length(vel)
135         if dist > 250 then
136                 vel = vector.divide(vel, dist / 250)
137         end
138         return vel
139 end
140
141 local function entity_physics(pos, radius)
142         local objs = minetest.get_objects_inside_radius(pos, radius)
143         for _, obj in pairs(objs) do
144                 local obj_pos = obj:getpos()
145                 local dist = math.max(1, vector.distance(pos, obj_pos))
146
147                 local damage = (4 / dist) * radius
148                 if obj:is_player() then
149                         -- currently the engine has no method to set
150                         -- player velocity. See #2960
151                         -- instead, we knock the player back 1.0 node, and slightly upwards
152                         local dir = vector.normalize(vector.subtract(obj_pos, pos))
153                         local moveoff = vector.multiply(dir, dist + 1.0)
154                         local newpos = vector.add(pos, moveoff)
155                         local newpos = vector.add(newpos, {x = 0, y = 0.2, z = 0})
156                         obj:setpos(newpos)
157
158                         obj:set_hp(obj:get_hp() - damage)
159                 else
160                         local obj_vel = obj:getvelocity()
161                         obj:setvelocity(calc_velocity(pos, obj_pos,
162                                         obj_vel, radius * 10))
163                         obj:punch(obj, 1.0, {
164                                 full_punch_interval = 1.0,
165                                 damage_groups = {fleshy = damage},
166                         }, nil)
167                 end
168         end
169 end
170
171 local function add_effects(pos, radius, drops)
172         minetest.add_particlespawner({
173                 amount = 64,
174                 time = 0.5,
175                 minpos = vector.subtract(pos, radius / 2),
176                 maxpos = vector.add(pos, radius / 2),
177                 minvel = {x = -10, y = -10, z = -10},
178                 maxvel = {x = 10, y = 10, z = 10},
179                 minacc = vector.new(),
180                 maxacc = vector.new(),
181                 minexptime = 1,
182                 maxexptime = 2.5,
183                 minsize = 8,
184                 maxsize = 16,
185                 texture = "tnt_smoke.png",
186         })
187
188         -- we just dropped some items. Look at the items entities and pick
189         -- one of them to use as texture
190         local texture = "tnt_blast.png" --fallback texture
191         local most = 0
192         for name, stack in pairs(drops) do
193                 local count = stack:get_count()
194                 if count > most then
195                         most = count
196                         local def = minetest.registered_nodes[name]
197                         if def and def.tiles and def.tiles[1] then
198                                 texture = def.tiles[1]
199                         end
200                 end
201         end
202
203         minetest.add_particlespawner({
204                 amount = 64,
205                 time = 0.1,
206                 minpos = vector.subtract(pos, radius / 2),
207                 maxpos = vector.add(pos, radius / 2),
208                 minvel = {x = -3, y = 0, z = -3},
209                 maxvel = {x = 3, y = 5,  z = 3},
210                 minacc = {x = 0, y = -10, z = 0},
211                 maxacc = {x = 0, y = -10, z = 0},
212                 minexptime = 0.8,
213                 maxexptime = 2.0,
214                 minsize = 2,
215                 maxsize = 6,
216                 texture = texture,
217                 collisiondetection = true,
218         })
219 end
220
221 function tnt.burn(pos)
222         local name = minetest.get_node(pos).name
223         local group = minetest.get_item_group(name, "tnt")
224         if group > 0 then
225                 minetest.sound_play("tnt_ignite", {pos = pos})
226                 minetest.set_node(pos, {name = name .. "_burning"})
227                 minetest.get_node_timer(pos):start(1)
228         elseif name == "tnt:gunpowder" then
229                 minetest.set_node(pos, {name = "tnt:gunpowder_burning"})
230         end
231 end
232
233 local function tnt_explode(pos, radius, ignore_protection, ignore_on_blast)
234         local pos = vector.round(pos)
235         local vm = VoxelManip()
236         local pr = PseudoRandom(os.time())
237         local p1 = vector.subtract(pos, radius)
238         local p2 = vector.add(pos, radius)
239         local minp, maxp = vm:read_from_map(p1, p2)
240         local a = VoxelArea:new({MinEdge = minp, MaxEdge = maxp})
241         local data = vm:get_data()
242
243         local drops = {}
244         local on_blast_queue = {}
245
246         local c_air = minetest.get_content_id("air")
247         local c_fire = minetest.get_content_id("fire:basic_flame")
248         for z = -radius, radius do
249         for y = -radius, radius do
250         local vi = a:index(pos.x + (-radius), pos.y + y, pos.z + z)
251         for x = -radius, radius do
252                 local r = vector.length(vector.new(x, y, z))
253                 if (radius * radius) / (r * r) >= (pr:next(80, 125) / 100) then
254                         local cid = data[vi]
255                         local p = {x = pos.x + x, y = pos.y + y, z = pos.z + z}
256                         if cid ~= c_air then
257                                 data[vi] = destroy(drops, p, cid, c_air, c_fire,
258                                         on_blast_queue, ignore_protection,
259                                         ignore_on_blast)
260                         end
261                 end
262                 vi = vi + 1
263         end
264         end
265         end
266
267         vm:set_data(data)
268         vm:write_to_map()
269         vm:update_map()
270         vm:update_liquids()
271
272         -- call nodeupdate for everything within 1.5x blast radius
273         for z = -radius * 1.5, radius * 1.5 do
274         for x = -radius * 1.5, radius * 1.5 do
275         for y = -radius * 1.5, radius * 1.5 do
276                 local s = vector.add(pos, {x = x, y = y, z = z})
277                 local r = vector.distance(pos, s)
278                 if r / radius < 1.4 then
279                         nodeupdate(s)
280                 end
281         end
282         end
283         end
284
285         for _, data in ipairs(on_blast_queue) do
286                 local dist = math.max(1, vector.distance(data.pos, pos))
287                 local intensity = (radius * radius) / (dist * dist)
288                 local node_drops = data.on_blast(data.pos, intensity)
289                 if node_drops then
290                         for _, item in ipairs(node_drops) do
291                                 add_drop(drops, item)
292                         end
293                 end
294         end
295
296         return drops
297 end
298
299 function tnt.boom(pos, def)
300         minetest.sound_play("tnt_explode", {pos = pos, gain = 1.5, max_hear_distance = 2*64})
301         minetest.set_node(pos, {name = "tnt:boom"})
302         local drops = tnt_explode(pos, def.radius, def.ignore_protection,
303                         def.ignore_on_blast)
304         entity_physics(pos, def.damage_radius)
305         if not def.disable_drops then
306                 eject_drops(drops, pos, def.radius)
307         end
308         add_effects(pos, def.radius, drops)
309 end
310
311 minetest.register_node("tnt:boom", {
312         drawtype = "plantlike",
313         tiles = {"tnt_boom.png"},
314         light_source = default.LIGHT_MAX,
315         walkable = false,
316         drop = "",
317         groups = {dig_immediate = 3},
318         on_construct = function(pos)
319                 minetest.get_node_timer(pos):start(0.5)
320         end,
321         on_timer = function(pos, elapsed)
322                 minetest.remove_node(pos)
323         end,
324         -- unaffected by explosions
325         on_blast = function() end,
326 })
327
328 minetest.register_node("tnt:gunpowder", {
329         description = "Gun Powder",
330         drawtype = "raillike",
331         paramtype = "light",
332         is_ground_content = false,
333         sunlight_propagates = true,
334         walkable = false,
335         tiles = {"tnt_gunpowder_straight.png", "tnt_gunpowder_curved.png", "tnt_gunpowder_t_junction.png", "tnt_gunpowder_crossing.png"},
336         inventory_image = "tnt_gunpowder_inventory.png",
337         wield_image = "tnt_gunpowder_inventory.png",
338         selection_box = {
339                 type = "fixed",
340                 fixed = {-1/2, -1/2, -1/2, 1/2, -1/2+1/16, 1/2},
341         },
342         groups = {dig_immediate = 2, attached_node = 1, connect_to_raillike = minetest.raillike_group("gunpowder")},
343         sounds = default.node_sound_leaves_defaults(),
344
345         on_punch = function(pos, node, puncher)
346                 if puncher:get_wielded_item():get_name() == "default:torch" then
347                         tnt.burn(pos)
348                 end
349         end,
350         on_blast = function(pos, intensity)
351                 tnt.burn(pos)
352         end,
353 })
354
355 minetest.register_node("tnt:gunpowder_burning", {
356         drawtype = "raillike",
357         paramtype = "light",
358         sunlight_propagates = true,
359         walkable = false,
360         light_source = 5,
361         tiles = {{
362                 name = "tnt_gunpowder_burning_straight_animated.png",
363                 animation = {
364                         type = "vertical_frames",
365                         aspect_w = 16,
366                         aspect_h = 16,
367                         length = 1,
368                 }
369         },
370         {
371                 name = "tnt_gunpowder_burning_curved_animated.png",
372                 animation = {
373                         type = "vertical_frames",
374                         aspect_w = 16,
375                         aspect_h = 16,
376                         length = 1,
377                 }
378         },
379         {
380                 name = "tnt_gunpowder_burning_t_junction_animated.png",
381                 animation = {
382                         type = "vertical_frames",
383                         aspect_w = 16,
384                         aspect_h = 16,
385                         length = 1,
386                 }
387         },
388         {
389                 name = "tnt_gunpowder_burning_crossing_animated.png",
390                 animation = {
391                         type = "vertical_frames",
392                         aspect_w = 16,
393                         aspect_h = 16,
394                         length = 1,
395                 }
396         }},
397         selection_box = {
398                 type = "fixed",
399                 fixed = {-1/2, -1/2, -1/2, 1/2, -1/2+1/16, 1/2},
400         },
401         drop = "",
402         groups = {dig_immediate = 2, attached_node = 1, connect_to_raillike = minetest.raillike_group("gunpowder")},
403         sounds = default.node_sound_leaves_defaults(),
404         on_timer = function(pos, elapsed)
405                 for dx = -1, 1 do
406                 for dz = -1, 1 do
407                 for dy = -1, 1 do
408                         if not (dx == 0 and dz == 0) then
409                                 tnt.burn({
410                                         x = pos.x + dx,
411                                         y = pos.y + dy,
412                                         z = pos.z + dz,
413                                 })
414                         end
415                 end
416                 end
417                 end
418                 minetest.remove_node(pos)
419         end,
420         -- unaffected by explosions
421         on_blast = function() end,
422         on_construct = function(pos)
423                 minetest.sound_play("tnt_gunpowder_burning", {pos = pos, gain = 2})
424                 minetest.get_node_timer(pos):start(1)
425         end,
426 })
427
428 minetest.register_abm({
429         nodenames = {"group:tnt", "tnt:gunpowder"},
430         neighbors = {"fire:basic_flame", "default:lava_source", "default:lava_flowing"},
431         interval = 4,
432         chance = 1,
433         action = tnt.burn,
434 })
435
436 minetest.register_craft({
437         output = "tnt:gunpowder",
438         type = "shapeless",
439         recipe = {"default:coal_lump", "default:gravel"}
440 })
441
442 minetest.register_craft({
443         output = "tnt:tnt",
444         recipe = {
445                 {"",           "group:wood",    ""},
446                 {"group:wood", "tnt:gunpowder", "group:wood"},
447                 {"",           "group:wood",    ""}
448         }
449 })
450
451 function tnt.register_tnt(def)
452         local name = ""
453         if not def.name:find(':') then
454                 name = "tnt:" .. def.name
455         else
456                 name = def.name
457                 def.name = def.name:match(":([%w_]+)")
458         end
459         if not def.tiles then def.tiles = {} end
460         local tnt_top = def.tiles.top or def.name .. "_top.png"
461         local tnt_bottom = def.tiles.bottom or def.name .. "_bottom.png"
462         local tnt_side = def.tiles.side or def.name .. "_side.png"
463         local tnt_burning = def.tiles.burning or def.name .. "_top_burning_animated.png"
464         if not def.damage_radius then def.damage_radius = def.radius * 2 end
465
466         minetest.register_node(":" .. name, {
467                 description = def.description,
468                 tiles = {tnt_top, tnt_bottom, tnt_side},
469                 is_ground_content = false,
470                 groups = {dig_immediate = 2, mesecon = 2, tnt = 1},
471                 sounds = default.node_sound_wood_defaults(),
472                 on_punch = function(pos, node, puncher)
473                         if puncher:get_wielded_item():get_name() == "default:torch" then
474                                 minetest.set_node(pos, {name = name .. "_burning"})
475                         end
476                 end,
477                 on_blast = function(pos, intensity)
478                         minetest.after(0.1, function()
479                                 tnt.boom(pos, def)
480                         end)
481                 end,
482                 mesecons = {effector =
483                         {action_on =
484                                 function(pos)
485                                         tnt.boom(pos, def)
486                                 end
487                         }
488                 },
489         })
490
491         minetest.register_node(":" .. name .. "_burning", {
492                 tiles = {
493                         {
494                                 name = tnt_burning,
495                                 animation = {
496                                         type = "vertical_frames",
497                                         aspect_w = 16,
498                                         aspect_h = 16,
499                                         length = 1,
500                                 }
501                         },
502                         tnt_bottom, tnt_side
503                         },
504                 light_source = 5,
505                 drop = "",
506                 sounds = default.node_sound_wood_defaults(),
507                 groups = {falling_node = 1},
508                 on_timer = function(pos, elapsed)
509                         tnt.boom(pos, def)
510                 end,
511                 -- unaffected by explosions
512                 on_blast = function() end,
513                 on_construct = function(pos)
514                         minetest.sound_play("tnt_ignite", {pos = pos})
515                         minetest.get_node_timer(pos):start(4)
516                         nodeupdate(pos)
517                 end,
518         })
519 end
520
521 tnt.register_tnt({
522         name = "tnt:tnt",
523         description = "TNT",
524         radius = radius,
525 })
526