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