Call nodeupdate on the entire blast zone
[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 obj = minetest.add_item(drop_pos, item:get_name() .. " " .. take)
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
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         
92         local def = cid_data[cid]
93
94         if not def then
95                 return c_air
96         elseif not ignore_on_blast and def.on_blast then
97                 on_blast_queue[#on_blast_queue + 1] = {pos = vector.new(npos), on_blast = def.on_blast}
98                 return cid
99         elseif def.flammable then
100                 return c_fire
101         else
102                 local node_drops = minetest.get_node_drops(def.name, "")
103                 for _, item in ipairs(node_drops) do
104                         add_drop(drops, item)
105                 end
106                 return c_air
107         end
108 end
109
110
111 local function calc_velocity(pos1, pos2, old_vel, power)
112         local vel = vector.direction(pos1, pos2)
113         vel = vector.normalize(vel)
114         vel = vector.multiply(vel, power)
115
116         -- Divide by distance
117         local dist = vector.distance(pos1, pos2)
118         dist = math.max(dist, 1)
119         vel = vector.divide(vel, dist)
120
121         -- Add old velocity
122         vel = vector.add(vel, old_vel)
123
124         -- Limit to terminal velocity
125         dist = vector.length(vel)
126         if dist > 250 then
127                 vel = vector.divide(vel, dist / 250)
128         end
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, drops)
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 most = 0
170         for name, stack in pairs(drops) do
171                 local count = stack:get_count()
172                 if count > most then
173                         most = count
174                         local def = minetest.registered_nodes[name]
175                         if def and def.tiles and def.tiles[1] then
176                                 texture = def.tiles[1]
177                         end
178                 end
179         end
180
181         minetest.add_particlespawner({
182                 amount = 64,
183                 time = 0.1,
184                 minpos = vector.subtract(pos, radius / 2),
185                 maxpos = vector.add(pos, radius / 2),
186                 minvel = {x = -3, y = 0, z = -3},
187                 maxvel = {x = 3, y = 5,  z = 3},
188                 minacc = {x = 0, y = -10, z = 0},
189                 maxacc = {x = 0, y = -10, z = 0},
190                 minexptime = 0.8,
191                 maxexptime = 2.0,
192                 minsize = 2,
193                 maxsize = 6,
194                 texture = texture,
195                 collisiondetection = true,
196         })
197 end
198
199 function tnt.burn(pos)
200         local name = minetest.get_node(pos).name
201         local group = minetest.get_item_group(name, "tnt")
202         if group > 0 then
203                 minetest.sound_play("tnt_ignite", {pos = pos})
204                 minetest.set_node(pos, {name = name .. "_burning"})
205                 minetest.get_node_timer(pos):start(1)
206         elseif name == "tnt:gunpowder" then
207                 minetest.set_node(pos, {name = "tnt:gunpowder_burning"})
208         end
209 end
210
211 local function tnt_explode(pos, radius, ignore_protection, ignore_on_blast)
212         local pos = vector.round(pos)
213         local vm = VoxelManip()
214         local pr = PseudoRandom(os.time())
215         local p1 = vector.subtract(pos, radius)
216         local p2 = vector.add(pos, radius)
217         local minp, maxp = vm:read_from_map(p1, p2)
218         local a = VoxelArea:new({MinEdge = minp, MaxEdge = maxp})
219         local data = vm:get_data()
220
221         local drops = {}
222         local on_blast_queue = {}
223
224         local c_air = minetest.get_content_id("air")
225         local c_fire = minetest.get_content_id("fire:basic_flame")
226         for z = -radius, radius do
227         for y = -radius, radius do
228         local vi = a:index(pos.x + (-radius), pos.y + y, pos.z + z)
229         for x = -radius, radius do
230                 local r = vector.length(vector.new(x, y, z))
231                 if (radius * radius) / (r * r) >= (pr:next(80, 125) / 100) then
232                         local cid = data[vi]
233                         local p = {x = pos.x + x, y = pos.y + y, z = pos.z + z}
234                         if cid ~= c_air then
235                                 data[vi] = destroy(drops, p, cid, c_air, c_fire,
236                                         on_blast_queue, ignore_protection,
237                                         ignore_on_blast)
238                         end
239                 end
240                 vi = vi + 1
241         end
242         end
243         end
244
245         vm:set_data(data)
246         vm:write_to_map()
247         vm:update_map()
248         vm:update_liquids()
249
250         -- call nodeupdate for everything within 1.5x blast radius
251         for z = -radius * 1.5, radius * 1.5 do
252         for x = -radius * 1.5, radius * 1.5 do
253         for y = -radius * 1.5, radius * 1.5 do
254                 local s = vector.add(pos, {x = x, y = y, z = z})
255                 local r = vector.distance(pos, s)
256                 if r / radius < 1.4 then
257                         nodeupdate(s)
258                 end
259         end
260         end
261         end
262
263         for _, data in ipairs(on_blast_queue) do
264                 local dist = math.max(1, vector.distance(data.pos, pos))
265                 local intensity = (radius * radius) / (dist * dist)
266                 local node_drops = data.on_blast(data.pos, intensity)
267                 if node_drops then
268                         for _, item in ipairs(node_drops) do
269                                 add_drop(drops, item)
270                         end
271                 end
272         end
273
274         return drops
275 end
276
277 function tnt.boom(pos, def)
278         minetest.sound_play("tnt_explode", {pos = pos, gain = 1.5, max_hear_distance = 2*64})
279         minetest.set_node(pos, {name = "tnt:boom"})
280         minetest.get_node_timer(pos):start(0.5)
281         local drops = tnt_explode(pos, def.radius, def.ignore_protection,
282                         def.ignore_on_blast)
283         entity_physics(pos, def.damage_radius)
284         if not def.disable_drops then
285                 eject_drops(drops, pos, def.radius)
286         end
287         add_effects(pos, def.radius, drops)
288 end
289
290 minetest.register_node("tnt:boom", {
291         drawtype = "plantlike",
292         tiles = {"tnt_boom.png"},
293         light_source = default.LIGHT_MAX,
294         walkable = false,
295         drop = "",
296         groups = {dig_immediate = 3},
297         on_timer = function(pos, elapsed)
298                 minetest.remove_node(pos)
299         end,
300         -- unaffected by explosions
301         on_blast = function() end,
302 })
303
304 minetest.register_node("tnt:gunpowder", {
305         description = "Gun Powder",
306         drawtype = "raillike",
307         paramtype = "light",
308         is_ground_content = false,
309         sunlight_propagates = true,
310         walkable = false,
311         tiles = {"tnt_gunpowder_straight.png", "tnt_gunpowder_curved.png", "tnt_gunpowder_t_junction.png", "tnt_gunpowder_crossing.png"},
312         inventory_image = "tnt_gunpowder_inventory.png",
313         wield_image = "tnt_gunpowder_inventory.png",
314         selection_box = {
315                 type = "fixed",
316                 fixed = {-1/2, -1/2, -1/2, 1/2, -1/2+1/16, 1/2},
317         },
318         groups = {dig_immediate = 2, attached_node = 1, connect_to_raillike = minetest.raillike_group("gunpowder")},
319         sounds = default.node_sound_leaves_defaults(),
320         
321         on_punch = function(pos, node, puncher)
322                 if puncher:get_wielded_item():get_name() == "default:torch" then
323                         tnt.burn(pos)
324                 end
325         end,
326         on_blast = function(pos, intensity)
327                 tnt.burn(pos)
328         end,
329 })
330
331 minetest.register_node("tnt:gunpowder_burning", {
332         drawtype = "raillike",
333         paramtype = "light",
334         sunlight_propagates = true,
335         walkable = false,
336         light_source = 5,
337         tiles = {{
338                 name = "tnt_gunpowder_burning_straight_animated.png",
339                 animation = {
340                         type = "vertical_frames",
341                         aspect_w = 16,
342                         aspect_h = 16,
343                         length = 1,
344                 }
345         },
346         {
347                 name = "tnt_gunpowder_burning_curved_animated.png",
348                 animation = {
349                         type = "vertical_frames",
350                         aspect_w = 16,
351                         aspect_h = 16,
352                         length = 1,
353                 }
354         },
355         {
356                 name = "tnt_gunpowder_burning_t_junction_animated.png",
357                 animation = {
358                         type = "vertical_frames",
359                         aspect_w = 16,
360                         aspect_h = 16,
361                         length = 1,
362                 }
363         },
364         {
365                 name = "tnt_gunpowder_burning_crossing_animated.png",
366                 animation = {
367                         type = "vertical_frames",
368                         aspect_w = 16,
369                         aspect_h = 16,
370                         length = 1,
371                 }
372         }},
373         selection_box = {
374                 type = "fixed",
375                 fixed = {-1/2, -1/2, -1/2, 1/2, -1/2+1/16, 1/2},
376         },
377         drop = "",
378         groups = {dig_immediate = 2, attached_node = 1, connect_to_raillike = minetest.raillike_group("gunpowder")},
379         sounds = default.node_sound_leaves_defaults(),
380         on_timer = function(pos, elapsed)
381                 for dx = -1, 1 do
382                 for dz = -1, 1 do
383                 for dy = -1, 1 do
384                         if not (dx == 0 and dz == 0) then
385                                 tnt.burn({
386                                         x = pos.x + dx,
387                                         y = pos.y + dy,
388                                         z = pos.z + dz,
389                                 })
390                         end
391                 end
392                 end
393                 end
394                 minetest.remove_node(pos)
395         end,
396         -- unaffected by explosions
397         on_blast = function() end,
398         on_construct = function(pos)
399                 minetest.sound_play("tnt_gunpowder_burning", {pos = pos, gain = 2})
400                 minetest.get_node_timer(pos):start(1)
401         end,
402 })
403
404 minetest.register_abm({
405         nodenames = {"group:tnt", "tnt:gunpowder"},
406         neighbors = {"fire:basic_flame", "default:lava_source", "default:lava_flowing"},
407         interval = 4,
408         chance = 1,
409         action = tnt.burn,
410 })
411
412 minetest.register_craft({
413         output = "tnt:gunpowder",
414         type = "shapeless",
415         recipe = {"default:coal_lump", "default:gravel"}
416 })
417
418 minetest.register_craft({
419         output = "tnt:tnt",
420         recipe = {
421                 {"",           "group:wood",    ""},
422                 {"group:wood", "tnt:gunpowder", "group:wood"},
423                 {"",           "group:wood",    ""}
424         }
425 })
426
427 function tnt.register_tnt(def)
428         local name = ""
429         if not def.name:find(':') then
430                 name = "tnt:" .. def.name
431         else
432                 name = def.name
433                 def.name = def.name:match(":([%w_]+)")
434         end
435         if not def.tiles then def.tiles = {} end
436         local tnt_top = def.tiles.top or def.name .. "_top.png"
437         local tnt_bottom = def.tiles.bottom or def.name .. "_bottom.png"
438         local tnt_side = def.tiles.side or def.name .. "_side.png"
439         local tnt_burning = def.tiles.burning or def.name .. "_top_burning_animated.png"
440         if not def.damage_radius then def.damage_radius = def.radius * 2 end
441         
442         minetest.register_node(":" .. name, {
443                 description = def.description,
444                 tiles = {tnt_top, tnt_bottom, tnt_side},
445                 is_ground_content = false,
446                 groups = {dig_immediate = 2, mesecon = 2, tnt = 1},
447                 sounds = default.node_sound_wood_defaults(),
448                 on_punch = function(pos, node, puncher)
449                         if puncher:get_wielded_item():get_name() == "default:torch" then
450                                 minetest.set_node(pos, {name = name .. "_burning"})
451                         end
452                 end,
453                 on_blast = function(pos, intensity)
454                         minetest.after(0.1, function()
455                                 tnt.boom(pos, def)
456                         end)
457                 end,
458                 mesecons = {effector = 
459                         {action_on = 
460                                 function(pos)
461                                         tnt.boom(pos, def)
462                                 end
463                         }
464                 },
465         })
466         
467         minetest.register_node(":" .. name .. "_burning", {
468                 tiles = {
469                         {
470                                 name = tnt_burning,
471                                 animation = {
472                                         type = "vertical_frames",
473                                         aspect_w = 16,
474                                         aspect_h = 16,
475                                         length = 1,
476                                 }
477                         },
478                         tnt_bottom, tnt_side
479                         },
480                 light_source = 5,
481                 drop = "",
482                 sounds = default.node_sound_wood_defaults(),
483                 on_timer = function(pos, elapsed)
484                         tnt.boom(pos, def)
485                 end,
486                 -- unaffected by explosions
487                 on_blast = function() end,
488                 on_construct = function(pos)
489                         minetest.sound_play("tnt_ignite", {pos = pos})
490                         minetest.get_node_timer(pos):start(4)
491                 end,
492         })
493 end
494
495 tnt.register_tnt({
496         name = "tnt:tnt",
497         description = "TNT",
498         radius = radius,
499 })
500