Fix TNT mod calculate blast intensity.
[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                 while count > 0 do
53                         local take = math.min(math.random(2,5),
54                                         item:get_count(),
55                                         item:get_stack_max())
56                         rand_pos(pos, drop_pos, radius)
57                         local obj = minetest.add_item(drop_pos, item:get_name() .. " " .. take)
58                         if obj then
59                                 obj:get_luaentity().collect = true
60                                 obj:setacceleration({x=0, y=-10, z=0})
61                                 obj:setvelocity({x=math.random(-3, 3),
62                                                 y=math.random(0, 10),
63                                                 z=math.random(-3, 3)})
64                         end
65                         count = count - take
66                 end
67         end
68 end
69
70 local function add_drop(drops, item)
71         item = ItemStack(item)
72         local name = item:get_name()
73         if loss_prob[name] ~= nil and math.random(1, loss_prob[name]) == 1 then
74                 return
75         end
76
77         local drop = drops[name]
78         if drop == nil then
79                 drops[name] = item
80         else
81                 drop:set_count(drop:get_count() + item:get_count())
82         end
83 end
84
85 local fire_node = {name="fire:basic_flame"}
86
87 local function destroy(drops, npos, cid, c_air, c_fire, on_blast_queue, ignore_protection, ignore_on_blast)
88         if not ignore_protection and minetest.is_protected(npos, "") then
89                 return cid
90         end
91         local def = cid_data[cid]
92         if not ignore_on_blast and def and def.on_blast then
93                 local dist = vector.distance(bpos, npos)
94                 local intensity = 1 / (dist * dist)
95                 local node_drops = def.on_blast(vector.new(npos), intensity)
96                 if node_drops then
97                         for _, item in ipairs(node_drops) do
98                                 add_drop(drops, item)
99                         end
100                 end
101                 return
102         end
103         if def and def.flammable then
104                 minetest.set_node(npos, fire_node)
105         else
106                 minetest.remove_node(npos)
107                 if def then
108                         local node_drops = minetest.get_node_drops(def.name, "")
109                         for _, item in ipairs(node_drops) do
110                                 add_drop(drops, item)
111                         end
112                 end
113         end
114 end
115
116
117 local function calc_velocity(pos1, pos2, old_vel, power)
118         local vel = vector.direction(pos1, pos2)
119         vel = vector.normalize(vel)
120         vel = vector.multiply(vel, power)
121
122         -- Divide by distance
123         local dist = vector.distance(pos1, pos2)
124         dist = math.max(dist, 1)
125         vel = vector.divide(vel, dist)
126
127         -- Add old velocity
128         vel = vector.add(vel, old_vel)
129         return vel
130 end
131
132 local function entity_physics(pos, radius)
133         local objs = minetest.get_objects_inside_radius(pos, radius)
134         for _, obj in pairs(objs) do
135                 local obj_pos = obj:getpos()
136                 local obj_vel = obj:getvelocity()
137                 local dist = math.max(1, vector.distance(pos, obj_pos))
138
139                 if obj_vel ~= nil then
140                         obj:setvelocity(calc_velocity(pos, obj_pos,
141                                         obj_vel, radius * 10))
142                 end
143
144                 local damage = (4 / dist) * radius
145                 obj:set_hp(obj:get_hp() - damage)
146         end
147 end
148
149 local function add_effects(pos, radius)
150         minetest.add_particlespawner({
151                 amount = 128,
152                 time = 1,
153                 minpos = vector.subtract(pos, radius / 2),
154                 maxpos = vector.add(pos, radius / 2),
155                 minvel = {x=-20, y=-20, z=-20},
156                 maxvel = {x=20,  y=20,  z=20},
157                 minacc = vector.new(),
158                 maxacc = vector.new(),
159                 minexptime = 1,
160                 maxexptime = 3,
161                 minsize = 8,
162                 maxsize = 16,
163                 texture = "tnt_smoke.png",
164         })
165
166         -- we just dropped some items. Look at the items entities and pick
167         -- one of them to use as texture
168         local texture = "tnt_blast.png" --fallback texture
169         local objs = minetest.get_objects_inside_radius(pos, 2)
170         for _, obj in pairs(objs) do
171                 if obj and obj:get_luaentity() then
172                         local def = ItemStack(obj:get_luaentity().itemstring):get_definition()
173                         if def.tiles then
174                                 texture = def.tiles[1]
175                                 break
176                         end
177                 end
178         end
179
180         minetest.add_particlespawner({
181                 amount = 64,
182                 time = 0.1,
183                 minpos = vector.subtract(pos, radius / 2),
184                 maxpos = vector.add(pos, radius / 2),
185                 minvel = {x=-3, y=0, z=-3},
186                 maxvel = {x=3,  y=5,  z=3},
187                 minacc = {x=0, y=-10, z=0},
188                 maxacc = {x=0, y=-10, z=0},
189                 minexptime = 0.8,
190                 maxexptime = 2.0,
191                 minsize = 2,
192                 maxsize = 6,
193                 texture = texture,
194                 collisiondetection = true,
195         })
196 end
197
198 function tnt.burn(pos)
199         local name = minetest.get_node(pos).name
200         local group = minetest.get_item_group(name, "tnt")
201         if group > 0 then
202                 minetest.sound_play("tnt_ignite", {pos=pos})
203                 minetest.set_node(pos, {name=name.."_burning"})
204                 minetest.get_node_timer(pos):start(1)
205         elseif name == "tnt:gunpowder" then
206                 minetest.sound_play("tnt_gunpowder_burning", {pos=pos, gain=2})
207                 minetest.set_node(pos, {name="tnt:gunpowder_burning"})
208                 minetest.get_node_timer(pos):start(1)
209         end
210 end
211
212 local function tnt_explode(pos, radius, ignore_protection, ignore_on_blast)
213         local pos = vector.round(pos)
214         local vm = VoxelManip()
215         local pr = PseudoRandom(os.time())
216         local p1 = vector.subtract(pos, radius)
217         local p2 = vector.add(pos, radius)
218         local minp, maxp = vm:read_from_map(p1, p2)
219         local a = VoxelArea:new({MinEdge = minp, MaxEdge = maxp})
220         local data = vm:get_data()
221
222         local drops = {}
223         local p = {}
224
225         local c_air = minetest.get_content_id("air")
226
227         for z = -radius, radius do
228         for y = -radius, radius do
229         local vi = a:index(pos.x + (-radius), pos.y + y, pos.z + z)
230         for x = -radius, radius do
231                 if (x * x) + (y * y) + (z * z) <=
232                                 (radius * radius) + pr:next(-radius, radius) then
233                         local cid = data[vi]
234                         p.x = pos.x + x
235                         p.y = pos.y + y
236                         p.z = pos.z + z
237                         if cid ~= c_air then
238                                 destroy(drops, p, cid, pos, ignore_protection, ignore_on_blast)
239                         end
240                 end
241                 vi = vi + 1
242         end
243         end
244         end
245
246         return drops
247 end
248
249 function tnt.boom(pos, def)
250         minetest.sound_play("tnt_explode", {pos=pos, gain=1.5, max_hear_distance=2*64})
251         minetest.set_node(pos, {name="tnt:boom"})
252         minetest.get_node_timer(pos):start(0.5)
253         local drops = tnt_explode(pos, def.radius, def.ignore_protection,
254                         def.ignore_on_blast)
255         entity_physics(pos, def.damage_radius)
256         if not def.disable_drops then
257                 eject_drops(drops, pos, def.radius)
258         end
259         add_effects(pos, def.radius)
260 end
261
262 minetest.register_node("tnt:boom", {
263         drawtype = "plantlike",
264         tiles = {"tnt_boom.png"},
265         light_source = default.LIGHT_MAX,
266         walkable = false,
267         drop = "",
268         groups = {dig_immediate=3},
269         on_timer = function(pos, elapsed)
270                 minetest.remove_node(pos)
271         end,
272         -- unaffected by explosions
273         on_blast = function() end,
274 })
275
276 minetest.register_node("tnt:gunpowder", {
277         description = "Gun Powder",
278         drawtype = "raillike",
279         paramtype = "light",
280         is_ground_content = false,
281         sunlight_propagates = true,
282         walkable = false,
283         tiles = {"tnt_gunpowder_straight.png", "tnt_gunpowder_curved.png", "tnt_gunpowder_t_junction.png", "tnt_gunpowder_crossing.png"},
284         inventory_image = "tnt_gunpowder_inventory.png",
285         wield_image = "tnt_gunpowder_inventory.png",
286         selection_box = {
287                 type = "fixed",
288                 fixed = {-1/2, -1/2, -1/2, 1/2, -1/2+1/16, 1/2},
289         },
290         groups = {dig_immediate=2,attached_node=1,connect_to_raillike=minetest.raillike_group("gunpowder")},
291         sounds = default.node_sound_leaves_defaults(),
292         
293         on_punch = function(pos, node, puncher)
294                 if puncher:get_wielded_item():get_name() == "default:torch" then
295                         tnt.burn(pos)
296                 end
297         end,
298         on_blast = function(pos, intensity)
299                 tnt.burn(pos)
300         end,
301 })
302
303 minetest.register_node("tnt:gunpowder_burning", {
304         drawtype = "raillike",
305         paramtype = "light",
306         sunlight_propagates = true,
307         walkable = false,
308         light_source = 5,
309         tiles = {{
310                 name = "tnt_gunpowder_burning_straight_animated.png",
311                 animation = {
312                         type = "vertical_frames",
313                         aspect_w = 16,
314                         aspect_h = 16,
315                         length = 1,
316                 }
317         },
318         {
319                 name = "tnt_gunpowder_burning_curved_animated.png",
320                 animation = {
321                         type = "vertical_frames",
322                         aspect_w = 16,
323                         aspect_h = 16,
324                         length = 1,
325                 }
326         },
327         {
328                 name = "tnt_gunpowder_burning_t_junction_animated.png",
329                 animation = {
330                         type = "vertical_frames",
331                         aspect_w = 16,
332                         aspect_h = 16,
333                         length = 1,
334                 }
335         },
336         {
337                 name = "tnt_gunpowder_burning_crossing_animated.png",
338                 animation = {
339                         type = "vertical_frames",
340                         aspect_w = 16,
341                         aspect_h = 16,
342                         length = 1,
343                 }
344         }},
345         selection_box = {
346                 type = "fixed",
347                 fixed = {-1/2, -1/2, -1/2, 1/2, -1/2+1/16, 1/2},
348         },
349         drop = "",
350         groups = {dig_immediate=2,attached_node=1,connect_to_raillike=minetest.raillike_group("gunpowder")},
351         sounds = default.node_sound_leaves_defaults(),
352         on_timer = function(pos, elapsed)
353                 for dx = -1, 1 do
354                 for dz = -1, 1 do
355                 for dy = -1, 1 do
356                         if not (dx == 0 and dz == 0) then
357                                 tnt.burn({
358                                         x = pos.x + dx,
359                                         y = pos.y + dy,
360                                         z = pos.z + dz,
361                                 })
362                         end
363                 end
364                 end
365                 end
366                 minetest.remove_node(pos)
367         end,
368         -- unaffected by explosions
369         on_blast = function() end,
370 })
371
372 minetest.register_abm({
373         nodenames = {"group:tnt", "tnt:gunpowder"},
374         neighbors = {"fire:basic_flame", "default:lava_source", "default:lava_flowing"},
375         interval = 4,
376         chance = 1,
377         action = tnt.burn,
378 })
379
380 minetest.register_craft({
381         output = "tnt:gunpowder",
382         type = "shapeless",
383         recipe = {"default:coal_lump", "default:gravel"}
384 })
385
386 minetest.register_craft({
387         output = "tnt:tnt",
388         recipe = {
389                 {"",           "group:wood",    ""},
390                 {"group:wood", "tnt:gunpowder", "group:wood"},
391                 {"",           "group:wood",    ""}
392         }
393 })
394
395 function tnt.register_tnt(def)
396         local name = ""
397         if not def.name:find(':') then
398                 name = "tnt:"..def.name
399         else
400                 name = def.name
401                 def.name = def.name:match(":([%w_]+)")
402         end
403         if not def.tiles then def.tiles = {} end
404         local tnt_top = def.tiles.top or def.name.."_top.png"
405         local tnt_bottom = def.tiles.bottom or def.name.."_bottom.png"
406         local tnt_side = def.tiles.side or def.name.."_side.png"
407         local tnt_burning = def.tiles.burning or def.name.."_top_burning_animated.png"
408         if not def.damage_radius then def.damage_radius = def.radius * 2 end
409         
410         minetest.register_node(":"..name, {
411                 description = def.description,
412                 tiles = {tnt_top, tnt_bottom, tnt_side},
413                 is_ground_content = false,
414                 groups = {dig_immediate=2, mesecon=2, tnt=1},
415                 sounds = default.node_sound_wood_defaults(),
416                 on_punch = function(pos, node, puncher)
417                         if puncher:get_wielded_item():get_name() == "default:torch" then
418                                 minetest.sound_play("tnt_ignite", {pos=pos})
419                                 minetest.set_node(pos, {name=name.."_burning"})
420                                 minetest.get_node_timer(pos):start(4)
421                         end
422                 end,
423                 on_blast = function(pos, intensity)
424                         tnt.burn(pos)
425                 end,
426                 mesecons = {effector = 
427                         {action_on = 
428                                 function(pos)
429                                         tnt.boom(pos, def)
430                                 end
431                         }
432                 },
433         })
434         
435         minetest.register_node(":"..name.."_burning", {
436                 tiles = {
437                         {
438                                 name = tnt_burning,
439                                 animation = {
440                                         type = "vertical_frames",
441                                         aspect_w = 16,
442                                         aspect_h = 16,
443                                         length = 1,
444                                 }
445                         },
446                         tnt_bottom, tnt_side
447                         },
448                 light_source = 5,
449                 drop = "",
450                 sounds = default.node_sound_wood_defaults(),
451                 on_timer = function(pos, elapsed)
452                         tnt.boom(pos, def)
453                 end,
454                 -- unaffected by explosions
455                 on_blast = function() end,
456         })
457 end
458
459 tnt.register_tnt({
460         name = "tnt:tnt",
461         description = "TNT",
462         radius = radius,
463 })
464