TNT: make tnt:boom visual a particle, and larger
[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 = "airlike",
313         light_source = default.LIGHT_MAX,
314         walkable = false,
315         drop = "",
316         groups = {dig_immediate = 3},
317         on_construct = function(pos)
318                 minetest.add_particle({
319                         pos = pos,
320                         velocity = vector.new(),
321                         acceleration = vector.new(),
322                         expirationtime = 0.4,
323                         size = 30,
324                         collisiondetection = false,
325                         vertical = false,
326                         texture = "tnt_boom.png",
327                         playername = nil,
328                 })
329                 minetest.get_node_timer(pos):start(0.4)
330         end,
331         on_timer = function(pos, elapsed)
332                 minetest.remove_node(pos)
333         end,
334         -- unaffected by explosions
335         on_blast = function() end,
336 })
337
338 minetest.register_node("tnt:gunpowder", {
339         description = "Gun Powder",
340         drawtype = "raillike",
341         paramtype = "light",
342         is_ground_content = false,
343         sunlight_propagates = true,
344         walkable = false,
345         tiles = {"tnt_gunpowder_straight.png", "tnt_gunpowder_curved.png", "tnt_gunpowder_t_junction.png", "tnt_gunpowder_crossing.png"},
346         inventory_image = "tnt_gunpowder_inventory.png",
347         wield_image = "tnt_gunpowder_inventory.png",
348         selection_box = {
349                 type = "fixed",
350                 fixed = {-1/2, -1/2, -1/2, 1/2, -1/2+1/16, 1/2},
351         },
352         groups = {dig_immediate = 2, attached_node = 1, connect_to_raillike = minetest.raillike_group("gunpowder")},
353         sounds = default.node_sound_leaves_defaults(),
354
355         on_punch = function(pos, node, puncher)
356                 if puncher:get_wielded_item():get_name() == "default:torch" then
357                         tnt.burn(pos)
358                 end
359         end,
360         on_blast = function(pos, intensity)
361                 tnt.burn(pos)
362         end,
363 })
364
365 minetest.register_node("tnt:gunpowder_burning", {
366         drawtype = "raillike",
367         paramtype = "light",
368         sunlight_propagates = true,
369         walkable = false,
370         light_source = 5,
371         tiles = {{
372                 name = "tnt_gunpowder_burning_straight_animated.png",
373                 animation = {
374                         type = "vertical_frames",
375                         aspect_w = 16,
376                         aspect_h = 16,
377                         length = 1,
378                 }
379         },
380         {
381                 name = "tnt_gunpowder_burning_curved_animated.png",
382                 animation = {
383                         type = "vertical_frames",
384                         aspect_w = 16,
385                         aspect_h = 16,
386                         length = 1,
387                 }
388         },
389         {
390                 name = "tnt_gunpowder_burning_t_junction_animated.png",
391                 animation = {
392                         type = "vertical_frames",
393                         aspect_w = 16,
394                         aspect_h = 16,
395                         length = 1,
396                 }
397         },
398         {
399                 name = "tnt_gunpowder_burning_crossing_animated.png",
400                 animation = {
401                         type = "vertical_frames",
402                         aspect_w = 16,
403                         aspect_h = 16,
404                         length = 1,
405                 }
406         }},
407         selection_box = {
408                 type = "fixed",
409                 fixed = {-1/2, -1/2, -1/2, 1/2, -1/2+1/16, 1/2},
410         },
411         drop = "",
412         groups = {dig_immediate = 2, attached_node = 1, connect_to_raillike = minetest.raillike_group("gunpowder")},
413         sounds = default.node_sound_leaves_defaults(),
414         on_timer = function(pos, elapsed)
415                 for dx = -1, 1 do
416                 for dz = -1, 1 do
417                 for dy = -1, 1 do
418                         if not (dx == 0 and dz == 0) then
419                                 tnt.burn({
420                                         x = pos.x + dx,
421                                         y = pos.y + dy,
422                                         z = pos.z + dz,
423                                 })
424                         end
425                 end
426                 end
427                 end
428                 minetest.remove_node(pos)
429         end,
430         -- unaffected by explosions
431         on_blast = function() end,
432         on_construct = function(pos)
433                 minetest.sound_play("tnt_gunpowder_burning", {pos = pos, gain = 2})
434                 minetest.get_node_timer(pos):start(1)
435         end,
436 })
437
438 minetest.register_abm({
439         nodenames = {"group:tnt", "tnt:gunpowder"},
440         neighbors = {"fire:basic_flame", "default:lava_source", "default:lava_flowing"},
441         interval = 4,
442         chance = 1,
443         action = tnt.burn,
444 })
445
446 minetest.register_craft({
447         output = "tnt:gunpowder",
448         type = "shapeless",
449         recipe = {"default:coal_lump", "default:gravel"}
450 })
451
452 minetest.register_craft({
453         output = "tnt:tnt",
454         recipe = {
455                 {"",           "group:wood",    ""},
456                 {"group:wood", "tnt:gunpowder", "group:wood"},
457                 {"",           "group:wood",    ""}
458         }
459 })
460
461 function tnt.register_tnt(def)
462         local name = ""
463         if not def.name:find(':') then
464                 name = "tnt:" .. def.name
465         else
466                 name = def.name
467                 def.name = def.name:match(":([%w_]+)")
468         end
469         if not def.tiles then def.tiles = {} end
470         local tnt_top = def.tiles.top or def.name .. "_top.png"
471         local tnt_bottom = def.tiles.bottom or def.name .. "_bottom.png"
472         local tnt_side = def.tiles.side or def.name .. "_side.png"
473         local tnt_burning = def.tiles.burning or def.name .. "_top_burning_animated.png"
474         if not def.damage_radius then def.damage_radius = def.radius * 2 end
475
476         minetest.register_node(":" .. name, {
477                 description = def.description,
478                 tiles = {tnt_top, tnt_bottom, tnt_side},
479                 is_ground_content = false,
480                 groups = {dig_immediate = 2, mesecon = 2, tnt = 1},
481                 sounds = default.node_sound_wood_defaults(),
482                 on_punch = function(pos, node, puncher)
483                         if puncher:get_wielded_item():get_name() == "default:torch" then
484                                 minetest.set_node(pos, {name = name .. "_burning"})
485                         end
486                 end,
487                 on_blast = function(pos, intensity)
488                         minetest.after(0.1, function()
489                                 tnt.boom(pos, def)
490                         end)
491                 end,
492                 mesecons = {effector =
493                         {action_on =
494                                 function(pos)
495                                         tnt.boom(pos, def)
496                                 end
497                         }
498                 },
499         })
500
501         minetest.register_node(":" .. name .. "_burning", {
502                 tiles = {
503                         {
504                                 name = tnt_burning,
505                                 animation = {
506                                         type = "vertical_frames",
507                                         aspect_w = 16,
508                                         aspect_h = 16,
509                                         length = 1,
510                                 }
511                         },
512                         tnt_bottom, tnt_side
513                         },
514                 light_source = 5,
515                 drop = "",
516                 sounds = default.node_sound_wood_defaults(),
517                 groups = {falling_node = 1},
518                 on_timer = function(pos, elapsed)
519                         tnt.boom(pos, def)
520                 end,
521                 -- unaffected by explosions
522                 on_blast = function() end,
523                 on_construct = function(pos)
524                         minetest.sound_play("tnt_ignite", {pos = pos})
525                         minetest.get_node_timer(pos):start(4)
526                         nodeupdate(pos)
527                 end,
528         })
529 end
530
531 tnt.register_tnt({
532         name = "tnt:tnt",
533         description = "TNT",
534         radius = radius,
535 })
536