code:
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007

Copyright © 2007 Free Software Foundation, Inc. <https://fsf.org/>

Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.

Preamble
The GNU General Public License is a free, copyleft license for software and other kinds of works.

The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too.

When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.

To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others.

For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.

Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it.

For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions.

Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users.

Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free.

The precise terms and conditions for copying, distribution and modification follow.

TERMS AND CONDITIONS
0. Definitions.
“This License” refers to version 3 of the GNU General Public License.

“Copyright” also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.

“The Program” refers to any copyrightable work licensed under this License. Each licensee is addressed as “you”. “Licensees” and “recipients” may be individuals or organizations.

To “modify” a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a “modified version” of the earlier work or a work “based on” the earlier work.

A “covered work” means either the unmodified Program or a work based on the Program.

To “propagate” a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.

To “convey” a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.

An interactive user interface displays “Appropriate Legal Notices” to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.

1. Source Code.
The “source code” for a work means the preferred form of the work for making modifications to it. “Object code” means any non-source form of a work.

A “Standard Interface” means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.

The “System Libraries” of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A “Major Component”, in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.

The “Corresponding Source” for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work.

The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.

The Corresponding Source for a work in source code form is that same work.

2. Basic Permissions.
All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.

You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.

Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.

3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.

When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.

4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.

You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.

5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:

a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to “keep intact all notices”.
c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an “aggregate” if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.

6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:

a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.

A “User Product” is either (1) a “consumer product”, which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, “normally used” refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.

“Installation Information” for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.

If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).

The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.

Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.

7. Additional Terms.
“Additional permissions” are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.

When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.

Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:

a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
All other non-permissive additional terms are considered “further restrictions” within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.

If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.

Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.

8. Termination.
You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).

However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.

Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.

Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.

9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.

10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.

An “entity transaction” is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.

You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.

11. Patents.
A “contributor” is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's “contributor version”.

A contributor's “essential patent claims” are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, “control” includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.

Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.

In the following three paragraphs, a “patent license” is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To “grant” such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.

If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. “Knowingly relying” means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.

If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.

A patent license is “discriminatory” if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.

Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.

12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.

13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such.

14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.

Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation.

If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program.

Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.

15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.

16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.

17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.

END OF TERMS AND CONDITIONS


code:
local special_leaves = dofile(minetest.get_modpath("leaves_in_the_wind").."/special_leaves.lua")

local pi_over2 = (math.pi/2)
local _3pi_over2 = 3*pi_over2

local ppos, pyaw, dx, dz, yaw, isBehind -- Allocate

minetest.register_abm({
	interval = 30,
	chance = 5,
	catch_up = false,
	nodenames = {"group:leaves"},
	action = function(npos, node, ...)
		if not minetest.registered_nodes[node.name] then return end
		npos.y = npos.y - 1
		local in_node = minetest.registered_nodes[minetest.get_node(npos).name]
		if in_node then
			if in_node.walkable then return end
		else
			return
		end
		--print(minetest.pos_to_string(npos))
		local particle = { --Default leaf particle
			pos = {x=npos.x+0.1,y=npos.y+0.25,z=npos.z+0.1},
			 -- If these aren't floats, for some reason, particles will end up in the corners of nodes.
			texture = "(single_leaf_texture_mask"..math.random(1,2)..".png^[mask:"..
				-- Take this leaf's texture and mask it with the shape of a single leaf
				(minetest.registered_nodes[node.name].tiles[1] or "default_leaves.png")..
				")^[transform"..math.random(0,7), --Flip it around for some randomness
			velocity = {
				x=math.sin((os.clock()%2000)/80)*0.25,
				y = -0.6,
				z=math.sin((os.clock()%2000)/80)*0.33,
			},
			size=2,
			expirationtime = 24,
			collisiondetection = true,
			collision_removal = true,
			vertical = false,
			leaf_spawn_chance = 70,
			spawn_radius = 44
		}
		local override = special_leaves[node.name]
		if type(override) == "table" then
			for k,v in pairs(override) do
				particle[k] = v
			end
		end

		for k,v in pairs(particle) do
			if type(v) == "function" then
				 -- since values in tables are static,
				 -- and we often want things to be a bit more random,
				 -- let particles implement a function call.
				particle[k] = v(particle, npos, node, ...)
			end
		end

		if math.abs(particle.velocity.x) < 0.01 or math.abs(particle.velocity.z) < 0.01 then
			particle.collision_removal = false
			-- Collision seems to get confused if particles are moving very slowly.
			-- I'm not sure why, but frankly, I'm sick of working with engine code,
			-- so here's me chickening out instead.
		end

		if particle.leaf_spawn_chance >= 1 and math.random() < (1/particle.leaf_spawn_chance) then
			for _,player in pairs(minetest.get_connected_players()) do
				ppos = player:get_pos()
				pyaw = player:get_look_horizontal()
				dx = (ppos.x-npos.x)
				dz = (ppos.z-npos.z)
				isBehind = true
				yaw = nil

				if dz<0 then
					yaw = -math.atan(dx/dz)
				elseif dz>0 then
					yaw = math.pi-math.atan(dx/dz)
				elseif dx<0 then
					yaw = 0
				else
					yaw = math.pi
				end
				if yaw then
					local yaw_diff = ((yaw - pyaw)%(2*math.pi))
					isBehind = (yaw_diff > pi_over2) and (yaw_diff < _3pi_over2)
				end
				if math.sqrt(
					math.sqrt(dx^2 + dz^2)^2 -- Horizontal hypotenuse
					+
					(ppos.y-npos.y)^2
				) <= (isBehind and (particle.spawn_radius/4) or particle.spawn_radius) then -- Reduce spawn radius significantly behind the player
					particle.playername = player:get_player_name()
					minetest.add_particle(table.copy(particle))
				end
			end
		end
	end,
})

repo_name: korkut/MeseCraft

license: mit


code:
name = leaves_in_the_wind
title = Leaves in the Wind
description = Adds falling leaves from trees effects.
author = Piezo
depends =
optional_depends = sakuragi


code:
local special_leaves = {}

if minetest.get_modpath("sakuragi") then
special_leaves["sakuragi:sleaves"] = {
	texture = function() return "single_cherry_blossom"..math.random(1,4)..".png^[transform"..math.random(0,7) end,
	velocity = function()
		return {
			x=math.sin((os.clock()%2000)/40)*0.04,
			y = -0.05, -- If you know this, you're a weeb.
			z=math.cos((os.clock()%2000)/80)*0.04,
		}
	end,
	size=0.75,
	expirationtime = 56,
	leaf_spawn_chance = 15,
	collision_removal = false,
	spawn_radius = 28,
}
end

if minetest.get_modpath("dfcaverns") then --Don't drop leaves from mushrooms, they don't have any!
	special_leaves["dfcaverns:fungiwood_shelf"] = {texture = "default_wood.png^[colorize:#0000:255",size=0,expirationtime = 0}
	special_leaves["dfcaverns:goblin_cap_gills"] = {texture = "default_wood.png^[colorize:#0000:255",size=0,expirationtime = 0}
	special_leaves["dfcaverns:nether_cap_gills"] = {texture = "default_wood.png^[colorize:#0000:255",size=0,expirationtime = 0}
	special_leaves["dfcaverns:tower_cap_gills"] = {texture = "default_wood.png^[colorize:#0000:255",size=0,expirationtime = 0}
	special_leaves["dfcaverns:spore_tree_hyphae"] = {texture = "default_wood.png^[colorize:#0000:255",size=0,expirationtime = 0}
	special_leaves["dfcaverns:spore_tree_fruiting_body"] = {texture = "default_wood.png^[colorize:#0000:255",size=0,expirationtime = 0}
end

if minetest.get_modpath("glowtest") then -- Glowing leaves shine in darkness
	special_leaves["glowtest:redleaf"] = {glow=10}
	special_leaves["glowtest:yellowleaf"] = {glow=10}
	special_leaves["glowtest:blueleaf"] = {glow=10}
	special_leaves["glowtest:greenleaf"] = {glow=10}
	special_leaves["glowtest:pinkleaf"] = {glow=10}
	special_leaves["glowtest:blackleaf"] = {glow=10}
	special_leaves["glowtest:whiteleaf"] = {glow=10}

end

minetest.after(0, function()
	for name,def in pairs(minetest.registered_nodes) do
		if def.groups and def.groups["leaves"] and def.groups["mushroom"] then
			special_leaves[name] {texture = "default_wood.png^[colorize:#0000:255",size=0}
		end
	end

end)

return special_leaves


code:
name = ENVIRONMENT
description = Meta-modpack containing environment and nature-related mods for Mesecraft.


code:
name: luacheck

on: [push, pull_request]

jobs:
  build:

    runs-on: ubuntu-latest

    steps:
    - uses: actions/checkout@v1
    - name: apt
      run: sudo apt-get install -y luarocks
    - name: luacheck install
      run: luarocks install --local luacheck
    - name: luacheck run
      run: $HOME/.luarocks/bin/luacheck ./


code:
unused_args = false
allow_defined_top = true

globals = {
	"radioactive_gas"
}

read_globals = {
	-- Stdlib
	string = {fields = {"split"}},
	table = {fields = {"copy", "getn"}},

	-- Minetest
	"minetest",
	"vector", "ItemStack",
	"dump", "VoxelArea",

	-- Deps
	"unified_inventory", "default",
	"vacuum",

	-- optional mods
	"planetoidgen"
}


code:
-- radioactive outgasing of ores in vacuum

-- gas definition, drowns and is slightly radioactive
minetest.register_node("radioactive_gas:gas", {
	description = "Moon gas",
	walkable = false,
	pointable = false,
	diggable = false,
	buildable_to = true,
	drawtype = "glasslike",
	drowning = 1,
	post_effect_color = {a = 20, r = 20, g = 250, b = 20},
	tiles = {"radioactive_gas.png"},
	use_texture_alpha = "blend",
	paramtype = "light",
	groups = {
    not_in_creative_inventory = 1,
    not_blocking_trains = 1,
    cools_lava = 1,
    radioactive = 4,
  },
	drop = {},
	sunlight_propagates = true
})

-- ores gas out in vacuum
minetest.register_abm({
  label = "moon ore outgasing",
	nodenames = {"vacuum:vacuum"},
	neighbors = {
    "default:stone_with_mese",
    "default:mineral_uranium"
  },
	interval = 20,
	chance = 2000,
	action = function(pos)
    minetest.set_node(pos, {name = "radioactive_gas:gas"})
  end
})

-- radioactive gas removal if near air
minetest.register_abm({
  label = "radioactive gas removal",
	nodenames = {"radioactive_gas:gas"},
	neighbors = {"air"},
	interval = 5,
	chance = 5,
	action = function(pos)
    minetest.set_node(pos, {name = "air"})
  end
})


code:
local MP = minetest.get_modpath("radioactive_gas")
dofile(MP.."/gas.lua")

print("[OK] Radioactive gas")


code:
name = radioactive_gas
optional_depends = vacuum, default


code:
# Radioactive gas mod for minetest

Spawns radioactive gas around ore and vacuum nodes
The gas disappears again if in contact with air

## Dependencies

* default?
* vacuum?


code:
-- unlit torch
minetest.register_node("real_torch:torch", {

	description = "Unlit Torch",
	drawtype = "torchlike",
	tiles = {
		{name = "real_torch_on_floor.png"},
		{name = "real_torch_ceiling.png"},
		{name = "real_torch_wall.png"},
	},
	inventory_image = "real_torch_on_floor.png",
	wield_image = "real_torch_on_floor.png",
	paramtype = "light",
	paramtype2 = "wallmounted",
	light_source = 3,
	sunlight_propagates = true,
	is_ground_content = false,
	walkable = false,
	selection_box = {
		type = "wallmounted",
		wall_top = {-0.1, 0.5 - 0.6, -0.1, 0.1, 0.5, 0.1},
		wall_bottom = {-0.1, -0.5, -0.1, 0.1, -0.5 + 0.6, 0.1},
		wall_side = {-0.5, -0.3, -0.1, -0.5 + 0.3, 0.3, 0.1},
	},
	groups = {choppy = 2, dig_immediate = 3, attached_node = 1},
	legacy_wallmounted = true,
	sounds = default.node_sound_defaults(),
})

-- override default torches to burn out after 8-10 minutes
minetest.override_item("default:torch", {

	on_timer = function(pos, elapsed)
		local p2 = minetest.get_node(pos).param2
		minetest.set_node(pos, {name = "real_torch:torch", param2 = p2})
		minetest.sound_play({name="real_torch_burnout", gain = 0.1},
			{pos = pos, max_hear_distance = 10})
	end,

	on_construct = function(pos)
		minetest.get_node_timer(pos):start(
			math.random(real_torch.min_duration, real_torch.max_duration))
	end,
})


code:
-- unlit floor torch
minetest.register_node("real_torch:torch", {
	description = "Torch",
	drawtype = "mesh",
	mesh = "torch_floor.obj",
	inventory_image = "real_torch_on_floor.png",
	wield_image = "real_torch_on_floor.png",
	tiles = {{
		    name = "real_torch_on_floor.png",
		    animation = {type = "vertical_frames", aspect_w = 16, aspect_h = 16, length = 3.3}
	}},
	paramtype = "light",
	paramtype2 = "wallmounted",
	light_source = 0,
	sunlight_propagates = true,
	walkable = false,
	liquids_pointable = false,
	groups = {choppy=2, dig_immediate=3, flammable=1, attached_node=1},
	drop = "real_torch:torch",
	selection_box = {
		type = "wallmounted",
		wall_bottom = {-1/8, -1/2, -1/8, 1/8, 2/16, 1/8},
	},
	sounds = default.node_sound_wood_defaults(),
	on_place = function(itemstack, placer, pointed_thing)
		local under = pointed_thing.under
		local node = minetest.get_node(under)
		local def = minetest.registered_nodes[node.name]
		if def and def.on_rightclick and
			((not placer) or (placer and not placer:get_player_control().sneak)) then
			return def.on_rightclick(under, node, placer, itemstack,
				pointed_thing) or itemstack
		end

		local above = pointed_thing.above
		local wdir = minetest.dir_to_wallmounted(vector.subtract(under, above))
		local fakestack = itemstack
		if wdir == 0 then
			fakestack:set_name("real_torch:torch_ceiling")
		elseif wdir == 1 then
			fakestack:set_name("real_torch:torch")
		else
			fakestack:set_name("real_torch:torch_wall")
		end

		itemstack = minetest.item_place(fakestack, placer, pointed_thing, wdir)
		itemstack:set_name("real_torch:torch")

		return itemstack
	end,
	on_ignite = function(pos, igniter)
		local nod = minetest.get_node(pos)
		minetest.set_node(pos, {name = "default:torch", param2 = nod.param2})
	end,
})

-- unlit wall torch
minetest.register_node("real_torch:torch_wall", {
	drawtype = "mesh",
	mesh = "torch_wall.obj",
	tiles = {{
		    name = "real_torch_on_floor.png",
		    animation = {type = "vertical_frames", aspect_w = 16, aspect_h = 16, length = 3.3}
	}},
	paramtype = "light",
	paramtype2 = "wallmounted",
	light_source = 0,
	sunlight_propagates = true,
	walkable = false,
	groups = {choppy=2, dig_immediate=3, flammable=1, not_in_creative_inventory=1, attached_node=1},
	drop = "real_torch:torch",
	selection_box = {
		type = "wallmounted",
		wall_side = {-1/2, -1/2, -1/8, -1/8, 1/8, 1/8},
	},
	sounds = default.node_sound_wood_defaults(),
	on_ignite = function(pos, igniter)
		local nod = minetest.get_node(pos)
		minetest.set_node(pos, {name = "default:torch_wall", param2 = nod.param2})
	end,
})

-- unlit ceiling torch
minetest.register_node("real_torch:torch_ceiling", {
	drawtype = "mesh",
	mesh = "torch_ceiling.obj",
	tiles = {{
		    name = "real_torch_on_floor.png",
		    animation = {type = "vertical_frames", aspect_w = 16, aspect_h = 16, length = 3.3}
	}},
	paramtype = "light",
	paramtype2 = "wallmounted",
	light_source = 0,
	sunlight_propagates = true,
	walkable = false,
	groups = {choppy=2, dig_immediate=3, flammable=1, not_in_creative_inventory=1, attached_node=1},
	drop = "real_torch:torch",
	selection_box = {
		type = "wallmounted",
		wall_top = {-1/8, -1/16, -5/16, 1/8, 1/2, 1/8},
	},
	sounds = default.node_sound_wood_defaults(),
	on_ignite = function(pos, igniter)
		local nod = minetest.get_node(pos)
		minetest.set_node(pos, {name = "default:torch_ceiling", param2 = nod.param2})
	end,
})

-- override default torches to burn out after 8-10 minutes
minetest.override_item("default:torch", {

	on_timer = function(pos, elapsed)
		local p2 = minetest.get_node(pos).param2
		minetest.set_node(pos, {name = "real_torch:torch", param2 = p2})
		minetest.sound_play({name="real_torch_burnout", gain = 0.1},
			{pos = pos, max_hear_distance = 10})
	end,

	on_construct = function(pos)
		minetest.get_node_timer(pos):start(
			math.random(real_torch.min_duration, real_torch.max_duration))
	end,
})

minetest.override_item("default:torch_wall", {

	on_timer = function(pos, elapsed)
		local p2 = minetest.get_node(pos).param2
		minetest.set_node(pos, {name = "real_torch:torch_wall", param2 = p2})
		minetest.sound_play({name="real_torch_burnout", gain = 0.1},
			{pos = pos, max_hear_distance = 10})
	end,

	on_construct = function(pos)
		minetest.get_node_timer(pos):start(
			math.random(real_torch.min_duration, real_torch.max_duration))
	end,
})

minetest.override_item("default:torch_ceiling", {

	on_timer = function(pos, elapsed)
		local p2 = minetest.get_node(pos).param2
		minetest.set_node(pos, {name = "real_torch:torch_ceiling", param2 = p2})
		minetest.sound_play({name="real_torch_burnout", gain = 0.1},
			{pos = pos, max_hear_distance = 10})
	end,

	on_construct = function(pos)
		minetest.get_node_timer(pos):start(
			math.random(real_torch.min_duration, real_torch.max_duration))
	end,
})


code:
-- Realistic Torch mod by TenPlus1

real_torch = {}

-- check for timer settings or use defaults
real_torch.min_duration = tonumber(minetest.settings:get("torch_min_duration")) or 1200
real_torch.max_duration = tonumber(minetest.settings:get("torch_min_duration")) or 1800

-- check which torch(es) are available in minetest version
if minetest.registered_nodes["default:torch_ceiling"] then

	dofile(minetest.get_modpath("real_torch") .. "/3d.lua")
else
	dofile(minetest.get_modpath("real_torch") .. "/2d.lua")
end

-- start timer on any already placed torches
minetest.register_lbm({
	name = "real_torch:convert_torch_to_node_timer",
	nodenames = {"default:torch", "default:torch_wall", "default:torch_ceiling"},
	action = function(pos)
		if not minetest.get_node_timer(pos):is_started() then
			minetest.get_node_timer(pos):start(
				math.random(real_torch.min_duration, real_torch.max_duration))
		end
	end
})

-- creative check
local creative_mode_cache = minetest.settings:get_bool("creative_mode")
function is_creative(name)
	return creative_mode_cache or minetest.check_player_privs(name, {creative = true})
end

-- coal powder
minetest.register_craftitem("real_torch:coal_powder", {
	description = "Coal Powder",
	inventory_image = "real_torch_coal_powder.png",

	-- punching unlit torch with coal powder relights
	on_use = function(itemstack, user, pointed_thing)

		if not pointed_thing or pointed_thing.type ~= "node" then
			return
		end

		local pos = pointed_thing.under
		local nod = minetest.get_node(pos)
		local rep = false

		if nod.name == "real_torch:torch" then
			nod.name = "default:torch"
			rep = true

		elseif nod.name == "real_torch:torch_wall" then
			nod.name = "default:torch_wall"
			rep = true

		elseif nod.name == "real_torch:torch_ceiling" then
			nod.name = "default:torch_ceiling"
			rep = true
		end

		if rep then
			minetest.set_node(pos, {name = nod.name, param2 = nod.param2})

			if not is_creative(user:get_player_name()) then
				itemstack:take_item()
			end
		end

		return itemstack
	end,
})

-- use coal powder as furnace fuel
minetest.register_craft({
	type = "fuel",
	recipe = "real_torch:coal_powder",
	burntime = 8,
})

-- 2x coal lumps = 12x coal powder
minetest.register_craft({
	type = "shapeless",
	output = "real_torch:coal_powder 12",
	recipe = {"default:coal_lump", "default:coal_lump"},
})

-- coal powder can make black dye
minetest.register_craft({
	type = "shapeless",
	output = "dye:black",
	recipe = {"real_torch:coal_powder"},
})

-- add coal powder to burnt out torch to relight
minetest.register_craft({
	type = "shapeless",
	output = "default:torch",
	recipe = {"real_torch:torch", "real_torch:coal_powder"},
})

-- 4x burnt out torches = 1x stick
minetest.register_craft({
	type = "shapeless",
	output = "default:stick",
	recipe = {"real_torch:torch", "real_torch:torch", "real_torch:torch", "real_torch:torch"},
})

-- Make sure Ethereal mod isn't running as this Abm already exists there
if not minetest.get_modpath("ethereal") then

-- if torch touches water then drop as unlit torch
minetest.register_abm({
	label = "Real Torch water check",
	nodenames = {
		"default:torch", "default:torch_wall", "default:torch:ceiling",
		"real_torch:torch", "real_torch:torch_wall", "real_torch:torch_ceiling"
	},
	neighbors = {"group:water"},
	interval = 5,
	chance = 1,
	catch_up = false,

	action = function(pos, node)

		local num = #minetest.find_nodes_in_area(
			{x = pos.x - 1, y = pos.y, z = pos.z},
			{x = pos.x + 1, y = pos.y, z = pos.z},
			{"group:water"})

		if num == 0 then
			num = num + #minetest.find_nodes_in_area(
				{x = pos.x, y = pos.y, z = pos.z - 1},
				{x = pos.x, y = pos.y, z = pos.z + 1},
				{"group:water"})
		end

		if num == 0 then
			num = num + #minetest.find_nodes_in_area(
				{x = pos.x, y = pos.y + 1, z = pos.z},
				{x = pos.x, y = pos.y + 1, z = pos.z},
				{"group:water"})
		end

		if num > 0 then
			minetest.set_node(pos, {name = "air"})

			minetest.sound_play({name="real_torch_extinguish", gain = 0.2},
				{pos = pos, max_hear_distance = 10})

			minetest.add_item(pos, {name = "real_torch:torch"})
		end
	end,
})

end

-- particle effects
local function add_effects(pos, radius)

	minetest.add_particle({
		pos = pos,
		velocity = vector.new(),
		acceleration = vector.new(),
		expirationtime = 0.4,
		size = radius * 10,
		collisiondetection = false,
		vertical = false,
		texture = "tnt_boom.png",
		glow = 15,
	})

	minetest.add_particlespawner({
		amount = 16,
		time = 0.5,
		minpos = vector.subtract(pos, radius / 2),
		maxpos = vector.add(pos, radius / 2),
		minvel = {x = -2, y = -2, z = -2},
		maxvel = {x = 2, y = 2, z = 2},
		minacc = vector.new(),
		maxacc = vector.new(),
		minexptime = 1,
		maxexptime = 2.5,
		minsize = radius * 3,
		maxsize = radius * 5,
		texture = "tnt_smoke.png",
	})

	minetest.sound_play("tnt_explode", {pos = pos, gain = 0.1, max_hear_distance = 5})
end

-- override tnt:gunpowder to explode when used on torch,
-- will also re-light torches and cause player damage when used on lit torch.
if minetest.get_modpath("tnt") then

minetest.override_item("tnt:gunpowder", {

	on_use = function(itemstack, user, pointed_thing)

		if not pointed_thing or pointed_thing.type ~= "node" then
			return
		end

		local pos = pointed_thing.under
		local nod = minetest.get_node(pos)

		local rep = false

		if nod.name == "real_torch:torch" then
			nod.name = "default:torch"
			rep = true

		elseif nod.name == "real_torch:torch_wall" then
			nod.name = "default:torch_wall"
			rep = true

		elseif nod.name == "real_torch:torch_ceiling" then
			nod.name = "default:torch_ceiling"
			rep = true
		end

		if rep then

			minetest.set_node(pos, {name = nod.name, param2 = nod.param2})

			add_effects(pos, 1)

			if not is_creative(user:get_player_name()) then
				itemstack:take_item()
			end

			return itemstack
		end

		if nod.name == "default:torch"
		or nod.name == "default:torch_wall"
		or nod.name == "default:torch_ceiling" then

			user:set_hp(user:get_hp() - 2)

			add_effects(pos, 1)

			if not is_creative(user:get_player_name()) then
				itemstack:take_item()
			end
		end

		return itemstack
	end,
})
end


code:
name = real_torch
description = Have torches go out after a while and drop when in water.
depends = default
optional_depends = tnt
author = TenPlus1
title = Real Torch


code:
Real Torch by TenPlus1

This mod changes minetest torches so that they have a life of 20-30 minutes which
is configurable using the torch_min_duration and torch_max_duration settings.

- 2x coal lumps can be crafted into 12x coal powder
- coal powder and an unlit torch can be crafted into a lit torch again
- punching an unlit torch with coal powder relights it
- punching an unlit torch with flint & steel relights it
- punching an unlit torch with gunpowder explodes and relights it
- never punch a lit torch with gunpowder, ow!
- water near torches make them drop as unlit torches
- coal powder can also be used for fuel or crafted into black dye

https://forum.minetest.net/viewtopic.php?f=11&t=15721

Changelog:

- 0.1 - Initial upload
- 0.2 - Punching unlit torch with coal powder relights torch
- 0.3 - Torches are 2D and override any that are 3D
- 0.4 - Changed my mind, now detects old 2D or new 3D torches and works accordingly
- 0.5 - 2x coal lumps give 10x coal dust, also fixed check for ethereal mod
- 0.6 - Burnout and extinguish sounds added by tacotexmex :)
- 0.7 - Torches can be re-lit using flint & steel and gunpowder, settings added
- 0.8 - Updated to newer functions, requires Minetest 0.4.16 to run


code:
#    Minimum torch duration before it goes out
torch_min_duration (Torch duration min) int 480

#    Maximum torch duration before it goes out
torch_max_duration (Torch duration max) int 600


code:
-- Author: Astrobe
-- Animated smoke texture courtesy of Texmex.
-- Version: 0.6
-- License for code: LGPL 2.1
-- License for textures: CC--BY-SA 4.0
--
-- Dokimi's self-organizing systems with its ever-expanding poison gas inspired this less deadly smoke mod.

smoke= {}

-- Library parameters
local ITVL=1 -- how fast smoke moves, in seconds. Smoke is generate at twice this period (so half slower than the smoke moves).
local PERSIST=0.91 -- the chance smokes has *not* to dissipate.
-- This is a very sensitive parameter: in terms of average smoke column average half-height, 0.95 -> 14, 0.93 -> 10 but 0.80 -> 5
local PERSIST_S=0.96 -- same parameter for smog
local TRANSPARENCY= "opaque" -- enable/disable transparency ("blend" or "opaque"). Transparency causes visual glitches when smoke is in contact with liquids
local WIND=0.05 -- Chance for a smoke node to move horizontally instead of going up

local SMOKE_DPS=nil -- use it to define the amount of damage per second of smoke nodes.
local SMOKE_OPACITY= 200 -- opacity when inside of smoke nodes

local SMOG_DPS=nil -- use it to define the amount of damage per second of smoke nodes.
local SMOG_OPACITY= 200 -- opacity when inside of smoke nodes

local locations = {
	1, 0,  -1, 0,  0, 1,  0, -1,
	1, 0,  -1, 0,  0, 1,  0, -1,
}

local sb={name="smoke:block", param2=0} -- avoid building that table each time our wannabe fast function is executed.
local sh={name="smoke:smog"}
local ab={name="air"}

-- This function does everything it can to be as fast as possible, all while randomzing the movement of the nodes.
-- The "locations" aboves are pairs of x,z coordinates for the four horizontal neighbors (no diagonals),
-- repeated two times.
-- spread_smoke picks at random a starting pair in this array. It adds the offsets to the coordinates,
-- check if the node there is air, and if not subtracts the current offsets and adds the next ones in one go.
-- This gives 4 different check orders out of the 4! = 24 possible in theory. Of course one could write down all 24 orders in an array...

local random=math.random

local function spread_smoke(pos)
	local p={x=pos.x, y=pos.y+1, z=pos.z}
	local gn=minetest.get_node
	local r=random(0, 3)*2+1
	local rr=random()
	local loc=locations

	repeat
		if gn(p).name=="air" and rr>WIND then break end
		if gn(p).name=="ignore" then minetest.swap_node(pos, ab) return false end -- we don't want wandering smoke nodes at the mapblock limit in the sky.
		p.y=p.y-1
		p.x=p.x+loc[r]
		p.z=p.z+loc[r+1]
		if gn(p).name=="air" then break end
		p.x=p.x-loc[r]+loc[r+2]
		p.z=p.z-loc[r+1]+loc[r+3]
		if gn(p).name=="air" then break end
		p.x=p.x-loc[r+2]+loc[r+4]
		p.z=p.z-loc[r+3]+loc[r+5]
		if gn(p).name=="air" then break end
		p.x=p.x-loc[r+4]+loc[r+6]
		p.z=p.z-loc[r+5]+loc[r+7]
		if gn(p).name=="air" then break end
		p.x=p.x-loc[r+6]
		p.z=p.z-loc[r+7]
		p.y=p.y-1
		if gn(p).name=="air" then break end
		-- trapped; retry later
		minetest.get_node_timer(pos):start(ITVL*2)
		return false
	until true -- never loop; all we wanted is a freaking Goto.

	--if rr<(PERSIST-p.y/1000) then
	if rr<PERSIST then
		sb.param2=random(0,5)
		minetest.set_node(p, sb)
	end
	minetest.swap_node(pos, ab)
	return false
end

minetest.register_node('smoke:block', {
	description = 'Smoke',
	drawtype = "glasslike",
	waving = 1,
	tiles = {{
		name = "smoke.png",
		--backface_culling=false, -- it seems to mitigate a bit visual glitches when transparency is enabled.
		animation = {
			type = "vertical_frames",
			aspect_w = 16,
			aspect_h = 16,
			length = 6,
		},
	}},
	inventory_image = "smoke.png^[verticalframe:16:1",
	wield_image =  "smoke.png^[verticalframe:16:1",
	paramtype = "light",
	paramtype2 = "facedir",
	use_texture_alpha=TRANSPARENCY,
	sunlight_propagates = true,
	walkable = false,
	pointable = false,
	diggable = false,
	buildable_to = true,
	floodable=true,
	damage_per_second = SMOKE_DPS,
	drowning=1,
	post_effect_color = {a = SMOKE_OPACITY, r = 177, g = 177, b = 177},
	drop="",

	on_timer=spread_smoke,
	on_construct=function(pos)
		minetest.get_node_timer(pos):start(ITVL+random())
	end
	})

function smoke.add(pos)
	minetest.set_node(pos, sb)
end

-- "Smog" is a second type of smoke that prefers to float or go down.

local function spread_smog(pos)
	local p={x=pos.x, y=pos.y, z=pos.z}
	local gn=minetest.get_node
	local r=random(0, 3)*2+1
	local loc=locations

	repeat
		p.x=p.x+loc[r]
		p.z=p.z+loc[r+1]
		if gn(p).name=="air" then break end
		p.x=p.x-loc[r]+loc[r+2]
		p.z=p.z-loc[r+1]+loc[r+3]
		if gn(p).name=="air" then break end
		p.x=p.x-loc[r+2]+loc[r+4]
		p.z=p.z-loc[r+3]+loc[r+5]
		if gn(p).name=="air" then break end
		p.x=p.x-loc[r+4]+loc[r+6]
		p.z=p.z-loc[r+5]+loc[r+7]
		if gn(p).name=="air" then break end
		p.x=p.x-loc[r+6]
		p.z=p.z-loc[r+7]
		-- down
		p.y=p.y-1
		if gn(p).name=="air" then break end
		p.y=p.y+2
		-- up
		if gn(p).name=="air" then break end
		p.y=p.y-1
		-- trapped; retry later
		minetest.get_node_timer(pos):start(ITVL*2)
		return false
	until true -- never loop; all we wanted is a freaking Goto.

	if random()<PERSIST_S then
		minetest.set_node(p, sh)
	end
	minetest.swap_node(pos, ab)
	return false
end

minetest.register_node('smoke:smog', {
	description = 'Smog',
	tiles = {{
		name = "smoke.png^gui_hb_bg.png",
		--backface_culling=false,
		animation = {
			type = "vertical_frames",
			aspect_w = 16,
			aspect_h = 16,
			length = 6,
		},
	}},
	inventory_image = "smoke.png^[verticalframe:16:1^gui_hb_bg.png",
	wield_image =  "smoke.png^[verticalframe:16:1^gui_hb_bg.png",
	drawtype = "glasslike",
	paramtype = "light",
	use_texture_alpha=TRANSPARENCY,
	sunlight_propagates = true,
	walkable = false,
	pointable = false,
	diggable = false,
	buildable_to = true,
	floodable=true,
	damage_per_second = SMOG_DPS ,
	drowning=1,
	post_effect_color = {a = SMOG_OPACITY, r = 177, g = 177, b = 177},
	drop="",

	on_timer=spread_smog,
	on_construct=function(pos)
		minetest.get_node_timer(pos):start(ITVL)
	end
	})

function smoke.add_smog(pos, jitters)
	minetest.set_node(pos, {name="smoke:smog"})
	jitters=jitters or random()
	minetest.get_node_timer(pos):start(ITVL+jitters)
end

-- API DOC
-- =======
--
-- smoke.add(pos)
-- smoke.add_smog(pos, jitters)
--
-- These functions add smoke or smog at a given position.
-- normal smoke, "light" smoke will go up whenever it can
-- while smog, tends to wander horizontally or go down. It only goes up when there's nowhere else to go.
--
-- The "jitters" parameter is optional; it introduces a delay on the first node update.
-- If not given, the functions will apply a random delay up to one second. This is intended
-- to smooth out performance in case the smoke is generated by a periodic process such as an ABM.
-- In this case, because the smoke nodes are updated at a fix time interval (using timers), you may
-- end up with CPU consumption "spikes" because all smoke nodes change position at the same time.
--
-- The functions do not check that the node at pos is air, nor do they care about protections.
--
-- APPLICATION
-- ===========
--
-- * creates an ABM that adds smoke on top of nodes belonging to the "smokey" group
-- * smoke generation rate is 1/g, where g is the value for the smokey group
-- * adds active furnaces, fire and lava flows to this group

if true then -- change to "false" if you want to do your own thing
	minetest.register_abm{
		label="Smoke",
		nodenames= {"group:smokey"},
		neighbors={"air"},
		interval=4,
		chance=1,
		action=function(pos)
			local p=minetest.find_node_near(pos, 1, "air") -- note that it happens that this function will try the node above first, but no statement about that in the docs.
			if p and random(1, minetest.get_item_group(minetest.get_node(pos).name, "smokey"))==1 then
				smoke.add(p)
			end
		end
	}

	function smoke.add_source(name, rate)
		local g=table.copy(minetest.registered_nodes[name].groups)
		g.smokey=rate
		minetest.override_item(name, { groups=g })
	end

	smoke.add_source("default:furnace_active", 1)
	smoke.add_source("fire:basic_flame", 2)
--	smoke.add_source("default:lava_flowing", 32)
	smoke.add_source("default:lava_source", 32)
	smoke.add_source("fire:permanent_flame", 2)
	smoke.add_source("default:torch", 4)
	smoke.add_source("default:torch_wall", 4)
	smoke.add_source("default:torch_ceiling", 4)
end


code:
name = smoke
description = Simulates smoke as air-like nodes that move around.
depends = default
optional_depends = fire


code:
unused_args = false
allow_defined_top = true

globals = {
	"vacuum",
}

read_globals = {
	-- Stdlib
	string = {fields = {"split"}},
	table = {fields = {"copy", "getn"}},
	"call",

	-- Minetest
	"minetest",
	"vector", "ItemStack",
	"dump", "VoxelArea",

	-- Deps
	"unified_inventory", "default", "monitoring"
}


code:
minetest.register_craftitem("vacuum:air_bottle", {
	description = "Air Bottle",
	inventory_image = vacuum.air_bottle_image
})


code:
local has_pipeworks = minetest.get_modpath("pipeworks")

local tube_entry = ""

if has_pipeworks then
	tube_entry = "^pipeworks_tube_connection_wooden.png"
end

local has_full_air_bottle = function(inv)
	return inv:contains_item("main", {name="vacuum:air_bottle", count=1})
end

local has_empty_air_bottle = function(inv)
	return inv:contains_item("main", {name="vessels:steel_bottle", count=1})
end

local do_empty_bottle = function(inv)
	if not has_full_air_bottle(inv) then
		return false
	end

	local new_stack = ItemStack("vessels:steel_bottle")
	inv:remove_item("main", {name="vacuum:air_bottle", count=1})

	if inv:room_for_item("main", new_stack) then
		inv:add_item("main", new_stack)
		return true
	end

	return false
end

local do_fill_bottle = function(inv)
	if not has_empty_air_bottle(inv) then
		return false
	end

	local new_stack = ItemStack("vacuum:air_bottle")
	inv:remove_item("main", {name="vessels:steel_bottle", count=1})

	if inv:room_for_item("main", new_stack) then
		inv:add_item("main", new_stack)
		return true
	end

	return false
end

-- just enabled
vacuum.airpump_enabled = function(meta)
	return meta:get_int("enabled") == 1
end

-- enabled and actively pumping
vacuum.airpump_active = function(meta)
	local inv = meta:get_inventory()
	return vacuum.airpump_enabled(meta) and has_full_air_bottle(inv)
end

local update_infotext = function(meta)
	local str = "Airpump: "

	if vacuum.airpump_enabled(meta) then
		str = str .. " (Enabled)"
	else
		str = str .. " (Disabled)"
	end

	meta:set_string("infotext", str)
end

-- update airpump formspec
local update_formspec = function(meta)
	local btnName = "State: "

	if meta:get_int("enabled") == 1 then
		btnName = btnName .. "<Enabled>"
	else
		btnName = btnName .. "<Disabled>"
	end

	meta:set_string("formspec", "size[8,7.2;]" ..
		"image[3,0;1,1;" .. vacuum.air_bottle_image .. "]" ..
		"image[4,0;1,1;vessels_steel_bottle.png]" ..
		"button[0,1;8,1;toggle;" .. btnName .. "]" ..
		"list[context;main;0,2;8,1;]" ..
		"list[current_player;main;0,3.2;8,4;]" ..
		"listring[]" ..
		"")

	update_infotext(meta)

end

minetest.register_node("vacuum:airpump", {
	description = "Air pump",--tube_entry
	tiles = { -- top, bottom
		"vacuum_airpump_top.png",
		"vacuum_airpump_side.png" .. tube_entry,
		"vacuum_airpump_side.png" .. tube_entry,
		"vacuum_airpump_side.png" .. tube_entry,
		"vacuum_airpump_side.png" .. tube_entry,
		"vacuum_airpump_front.png"
	},
	paramtype = "light",
	paramtype2 = "facedir",
	legacy_facedir_simple = true,
	groups = {cracky=3, oddly_breakable_by_hand=3, tubedevice=1, tubedevice_receiver=1},
	sounds = default.node_sound_glass_defaults(),

	mesecons = {effector = {
		action_on = function (pos, node)
			local meta = minetest.get_meta(pos)
			meta:set_int("enabled", 1)
			update_infotext(meta)
		end,
		action_off = function (pos, node)
			local meta = minetest.get_meta(pos)
			meta:set_int("enabled", 0)
			update_infotext(meta)
		end
	}},

	after_place_node = function(pos, placer)
		local meta = minetest.get_meta(pos)
		meta:set_string("owner", placer:get_player_name() or "")
	end,

	on_construct = function(pos)
		local meta = minetest.get_meta(pos)
		meta:set_int("enabled", 0)

		local inv = meta:get_inventory()
		inv:set_size("main", 8)

		update_formspec(meta)
	end,

	can_dig = function(pos,player)
		if player and player:is_player() and minetest.is_protected(pos, player:get_player_name()) then
			-- protected
			return false
		end

		local meta = minetest.get_meta(pos);
		local inv = meta:get_inventory()
		return inv:is_empty("main")
	end,

	allow_metadata_inventory_take = function(pos, listname, index, stack, player)
		if player and player:is_player() and minetest.is_protected(pos, player:get_player_name()) then
			-- protected
			return 0
		end

		return stack:get_count()
	end,

	allow_metadata_inventory_put = function(pos, listname, index, stack, player)
		if player and player:is_player() and minetest.is_protected(pos, player:get_player_name()) then
			-- protected
			return 0
		end

		return stack:get_count()
	end,

	on_receive_fields = function(pos, formname, fields, sender)
		local meta = minetest.get_meta(pos);

                if minetest.is_protected(pos, sender:get_player_name()) then
                        -- not allowed
                        return
                end

		if fields.toggle then
			if meta:get_int("enabled") == 1 then
				meta:set_int("enabled", 0)
			else
				meta:set_int("enabled", 1)
			end
		end

		update_formspec(meta)
	end,

	tube = {
		insert_object = function(pos, node, stack, direction)
			local meta = minetest.get_meta(pos)
			local inv = meta:get_inventory()
			return inv:add_item("main", stack)
		end,
		can_insert = function(pos, node, stack, direction)
			local meta = minetest.get_meta(pos)
			local inv = meta:get_inventory()
			stack = stack:peek_item(1)
			return inv:room_for_item("main", stack)
		end,
		input_inventory = "main",
		connect_sides = {left = 1, right = 1, back = 1, bottom = 1, top = 1}
	}

})

minetest.register_abm({
        label = "airpump",
	nodenames = {"vacuum:airpump"},
	interval = 5,
	chance = 1,
	action = function(pos)
		local meta = minetest.get_meta(pos)
		if vacuum.airpump_enabled(meta) then

			local used
			if vacuum.is_pos_in_space(pos) then
				used = do_empty_bottle(meta:get_inventory())
			else
				used = do_fill_bottle(meta:get_inventory())
			end

			if used then
				minetest.sound_play("vacuum_hiss", {pos = pos, gain = 0.5})

				minetest.add_particlespawner(
	                                12, --amount
	                                4, --time
	                                {x=pos.x-0.95, y=pos.y-0.95, z=pos.z-0.95},
	                                {x=pos.x+0.95, y=pos.y+0.95, z=pos.z+0.95},
	                                {x=-1.2, y=-1.2, z=-1.2},
	                                {x=1.2, y=1.2, z=1.2},
	                                {x=0,y=0,z=0},
	                                {x=0,y=0,z=0},
	                                0.5,
	                                1,
	                                1,
	                                2,
	                                false,
	                                "bubble.png"
	                        )

			end

			update_infotext(meta)
		end
	end
})

-- initial airpump step
minetest.register_abm({
        label = "airpump seed",
	nodenames = {"vacuum:airpump"},
	neighbors = {"vacuum:vacuum"},
	interval = 1,
	chance = 1,
	action = function(pos)
		local meta = minetest.get_meta(pos)
		if vacuum.airpump_active(meta) then
			-- seed initial air
			local node = minetest.find_node_near(pos, 1, {"vacuum:vacuum"})

			if node ~= nil then
				minetest.set_node(node, {name = "air"})
			end
		end
	end
})

minetest.register_craft({
	output = "vacuum:airpump",
	recipe = {
		{"default:steel_ingot", "default:mese_block", "default:steel_ingot"},
		{"default:diamond", "default:glass", "default:steel_ingot"},
		{"default:steel_ingot", "default:steelblock", "default:steel_ingot"},
	},
})


code:
vacuum.air_bottle_image = "vessels_steel_bottle.png^[colorize:#0000FFAA"

-- space pos checker
vacuum.is_pos_in_space = function(pos)
	return pos.y > vacuum.space_height
end

-- (cheaper) space check, gets called more often than `is_pos_in_space`
vacuum.no_vacuum_abm = function(pos)
	return pos.y > vacuum.space_height - 40 and pos.y < vacuum.space_height + 40
end


code:
minetest.register_on_dignode(function(pos, oldnode, digger)
	if oldnode.name and string.sub(oldnode.name, 0, 7) == "digtron" then
		-- skip digtron moved nodes
		return;
	end

	local np = minetest.find_node_near(pos, 1,{"vacuum:vacuum"})
	if np ~= nil then
		minetest.set_node(pos, {name = "vacuum:vacuum"})
		return
	end
end)


code:
vacuum = {
	space_height = tonumber(minetest.settings:get("vacuum.space_height")) or 1000,
	air_pump_range = tonumber(minetest.settings:get("vacuum.air_pump_range")) or 5,
	profile_mapgen = minetest.settings:get("vacuum.profile_mapgen"),
	debug = minetest.settings:get("vacuum.debug")
}

local MP = minetest.get_modpath("vacuum")

dofile(MP.."/common.lua")
dofile(MP.."/vacuum.lua")
dofile(MP.."/compat.lua")
dofile(MP.."/airbottle.lua")
dofile(MP.."/airpump.lua")
dofile(MP.."/mapgen.lua")
dofile(MP.."/physics.lua")
dofile(MP.."/dignode.lua")

print("[OK] Vacuum")


code:
local c_vacuum = minetest.get_content_id("vacuum:vacuum")
local c_ignore = minetest.get_content_id("ignore")
local c_air = minetest.get_content_id("air")

local get_corners = function(minp, maxp)
	return {
		minp,
		maxp,
		{ x=maxp.x, y=minp.y, z=minp.z },
		{ x=minp.x, y=maxp.y, z=minp.z },
		{ x=minp.x, y=minp.y, z=maxp.z },
		{ x=maxp.x, y=maxp.y, z=minp.z },
		{ x=minp.x, y=maxp.y, z=maxp.z },
		{ x=maxp.x, y=minp.y, z=maxp.z },
	}
end

local check_corners_in_space = function(minp, maxp)
	for _, pos in ipairs(get_corners(minp, maxp)) do
		if vacuum.is_pos_in_space(pos) then
			return true
		end
	end

	return false
end

minetest.register_on_generated(function(minp, maxp, seed)
	local t0 = minetest.get_us_time()

	if not check_corners_in_space(minp, maxp) then
		return
	end

	local vm, emin, emax = minetest.get_mapgen_object("voxelmanip")
	local data = vm:get_data()
	local area = VoxelArea:new({MinEdge=emin, MaxEdge=emax})

	for i in area:iter(
		minp.x, minp.y, minp.z,
		maxp.x, maxp.y, maxp.z
	) do
		if data[i] == c_air or data[i] == c_ignore then
			data[i] = c_vacuum
		end
	end

	vm:set_data(data)
	vm:set_lighting({day=15, night=0})
	vm:write_to_map()

	local t1 = minetest.get_us_time()
	local micros = t1 -t0

	if vacuum.profile_mapgen then
		print("[vacuum] mapgen for " .. minetest.pos_to_string(minp) .. " took " .. micros .. " us")
	end
end)


code:
name = vacuum
description = Vacuum implementation and blocks for pumping and detection of vacuum and air.
author = thomasrudin
depends = default, vessels
optional_depends = doors, wool, mesecons, pipeworks, monitoring, mesecons_random, technic


code:
local has_monitoring = minetest.get_modpath("monitoring")
local has_technic = minetest.get_modpath("technic")
local has_mesecons_random = minetest.get_modpath("mesecons_random")

local MP = minetest.get_modpath("vacuum")
local throttle = dofile(MP .. "/util/throttle.lua")

local metric_space_vacuum_abm
local metric_space_vacuum_leak_abm

if has_monitoring then
  metric_space_vacuum_abm = monitoring.counter("vacuum_abm_count", "number of space vacuum abm calls")
  metric_space_vacuum_leak_abm = monitoring.counter("vacuum_abm_leak_count", "number of space vacuum leak abm calls")
end

-- air leaking nodes
local leaky_nodes = {
	"group:door",
	"group:soil",
	"group:pipe", "group:tube"
}

if has_mesecons_random then
  table.insert(leaky_nodes, "mesecons_random:ghoststone_active")
end

if has_technic then
  table.insert(leaky_nodes, "technic:lv_cable")
  table.insert(leaky_nodes, "technic:mv_cable")
  table.insert(leaky_nodes, "technic:hv_cable")
end

local near_powered_airpump = function(pos)
	local pos1 = vector.subtract(pos, {x=vacuum.air_pump_range, y=vacuum.air_pump_range, z=vacuum.air_pump_range})
	local pos2 = vector.add(pos, {x=vacuum.air_pump_range, y=vacuum.air_pump_range, z=vacuum.air_pump_range})

	local nodes = minetest.find_nodes_in_area(pos1, pos2, {"vacuum:airpump"})
	for _,node in ipairs(nodes) do
		local meta = minetest.get_meta(node)
		if vacuum.airpump_active(meta) then
			return true
		end
	end

	return false
end

-- vacuum/air propagation
minetest.register_abm({
  label = "space vacuum",
	nodenames = {"air"},
	neighbors = {"vacuum:vacuum"},
	interval = 1,
	chance = 1,
	action = throttle(1000, function(pos)

		if metric_space_vacuum_abm ~= nil then metric_space_vacuum_abm.inc() end

		if vacuum.no_vacuum_abm(pos) then
			return
		end

		if not vacuum.is_pos_in_space(pos) or near_powered_airpump(pos) then
			-- on earth or near a powered airpump
			local node = minetest.find_node_near(pos, 1, {"vacuum:vacuum"})

			if node ~= nil then
				minetest.set_node(node, {name = "air"})
			end
		else
			-- in space, evacuate air
			minetest.set_node(pos, {name = "vacuum:vacuum"})
		end
	end)
})

-- weird behaving nodes in vacuum
local drop_nodes = {
	"default:torch",
	"default:torch_wall",
	"default:torch_ceiling",
	"default:ladder_wood",
	"default:ladder_steel",
	"default:dry_shrub",
	"default:papyrus",
	"default:cactus",
	"group:wool",
	"group:wood",
	"group:tree",
	-- "group:mesecon", TODO: add hardcore setting for that one
	-- TODO: maybe: group:dig_immediate
}

-- special drop cases
local get_drop_name = function(name)
	if name == "default:torch_wall" or name == "default:torch_ceiling" then
		return "default:torch"
	else
		return name
	end
end

-- weird nodes in vacuum
minetest.register_abm({
        label = "space drop nodes",
	nodenames = drop_nodes,
	neighbors = {"vacuum:vacuum"},
	interval = 1,
	chance = 1,
	action = throttle(100, function(pos)

		if not vacuum.is_pos_in_space(pos) or near_powered_airpump(pos) then
			return
		end

		local node = minetest.get_node(pos)
		minetest.set_node(pos, {name = "vacuum:vacuum"})

		local dropname = get_drop_name(node.name)
		if dropname then
			minetest.add_item(pos, {name = dropname})
		end
	end)
})

-- various dirts in vacuum
minetest.register_abm({
        label = "space vacuum soil dry",
	nodenames = {
		"default:dirt",
		"default:dirt_with_grass",
		"default:dirt_with_snow",
		"default:dirt_with_dry_grass",
		"default:dirt_with_grass_footsteps",
		"default:dirt_with_rainforest_litter",
		"default:dirt_with_coniferous_litter"
	},
	neighbors = {"vacuum:vacuum"},
	interval = 1,
	chance = 1,
	action = throttle(100, function(pos)
		minetest.set_node(pos, {name = "default:gravel"})
	end)
})

-- plants in vacuum
minetest.register_abm({
        label = "space vacuum plants",
	nodenames = {
		"group:sapling",
		"group:plant",
		"group:flora",
		"group:flower",
		"group:leafdecay",
		"ethereal:banana", -- ethereal compat
		"ethereal:orange",
		"ethereal:strawberry"
	},
	neighbors = {"vacuum:vacuum"},
	interval = 1,
	chance = 1,
	action = throttle(100, function(pos)
		minetest.set_node(pos, {name = "default:dry_shrub"})
	end)
})

-- sublimate nodes in vacuum
minetest.register_abm({
        label = "space vacuum sublimate",
	nodenames = {"group:snowy", "group:leaves", "group:water"},
	neighbors = {"vacuum:vacuum"},
	interval = 1,
	chance = 1,
	action = throttle(100, function(pos)
		if not vacuum.is_pos_in_space(pos) or near_powered_airpump(pos) then
			return
		end

		minetest.set_node(pos, {name = "vacuum:vacuum"})
	end)
})

-- depressurize through leaky nodes
minetest.register_abm({
        label = "space vacuum depressurize",
	nodenames = leaky_nodes,
	neighbors = {"vacuum:vacuum"},
	interval = 2,
	chance = 2,
	action = throttle(250, function(pos)
		if metric_space_vacuum_leak_abm ~= nil then metric_space_vacuum_leak_abm.inc() end

		if not vacuum.is_pos_in_space(pos) or near_powered_airpump(pos) then
			-- on earth: TODO: replace vacuum with air
			return
		else
			local node = minetest.get_node(pos)

			if node.name == "pipeworks:entry_panel_empty" or node.name == "pipeworks:entry_panel_loaded" then
				-- air thight pipes
				return
			end

			if node.name == "vacuum:airpump" then
				-- pump is airthight
				return
			end

			-- TODO check n nodes down (multiple simple door airlock hack)
			-- in space: replace air with vacuum
			local surrounding_node = minetest.find_node_near(pos, 1, {"air"})

			if surrounding_node ~= nil then
			        if vacuum.debug then
					-- debug mode, set
					minetest.set_node(surrounding_node, {name = "default:cobble"})
				else
					-- normal case
					minetest.set_node(surrounding_node, {name = "vacuum:vacuum"})
				end
			end
		end
	end)
})


code:
Minetest vacuum
======

Vacuum implementation and blocks for pumping and detection of vacuum and air

* Github: [https://github.com/thomasrudin-mt/vacuum](https://github.com/thomasrudin-mt/vacuum)
* Forum topic: [https://forum.minetest.net/viewtopic.php?f=9&t=20195](https://forum.minetest.net/viewtopic.php?f=9&t=20195)

# Operation

The space/vacuum starts at 1000 blocks in the y axis (hardcoded in init.lua)

The mod defines an airlike **vacuum:vacuum** block which suffocates the player (with drowning=1).
An [spacesuit](https://git.rudin.io/minetest/spacesuit) or similar would help to survive in space.

Air can be pumped in to any closed structure with an airpump (vacuum:airpump).
the airpump needs air-bottles to work in vaccum. Air-bottles can be filled with an airpump on the ground.
Just place empty steel bottles in an airpump on the ground, enable it and it produces an airbottle every few seconds.

## Vacuum propagation

The vacuum sucks air out of every structure if there are leaky nodes (doors, wool, wood, etc; defined in abm.lua)

A vacuum node in a pressurized area can suck out the whole structure.

## Other nodes in space

Vacuum exposure on nodes:
* Dirt converts to gravel
* All plants convert to dry shrubs
* Leaves disappear
* Water evaporates
* Torches and ladders drop (to prevent air bubbles/cheating)

# Compatibility

Optional dependencies:
* Mesecon interaction (enable/disable airpump)
* Pipeworks

Tested mods:
* digtron
* technic (quarry, solar)

# Crafting

TODO

# Screenshots

Air pump:

![](screenshots/screenshot_20180524_204035.png?raw=true)

Hole in the structure (leaking air):

![](screenshots/screenshot_20180524_204042.png?raw=true)

Hole from outside:

![](screenshots/screenshot_20180524_204132.png?raw=true)

# Attributions
* textures/vacuum_airpump* by ManElevation MIT (https://github.com/ManElevation/oxygenerators5.2)

# History

## Version 0.1
* Initial release


code:
local function throttle(callspersecond, fn)
	local time = 0
	local count = 0

	return function(...)
		local now = minetest.get_us_time()
		if (now - time) > 1000000 then
			-- reset time
			time = now
			count = 0
		else
			-- check max calls
			count = count + 1
			if count > callspersecond then
				return
			end
		end

		return pcall(fn, ...)
	end

end

return throttle


code:
minetest.register_node("vacuum:vacuum", {
	description = "Vacuum",
	walkable = false,
	pointable = false,
	diggable = false,
	buildable_to = true,
	drawtype = "glasslike",
	drowning = 1,
	tiles = {"transparent_pixel.png"},
	use_texture_alpha = "blend",
	groups = {not_in_creative_inventory=1, not_blocking_trains=1, cools_lava=1},
	paramtype = "light",
	drop = {},
	sunlight_propagates = true
})


code:
-- Candy Cane Armor
minetest.register_tool("christmas_holiday_pack:helmet_cane", {
		description = "Candy Cane Helmet",
		inventory_image = "christmas_holiday_pack_inv_helmet_cane.png",
		groups = {armor_head=12, armor_heal=12, armor_use=200},
		wear = 0,
	})
	minetest.register_tool("christmas_holiday_pack:chestplate_cane", {
		description = "Candy Cane Chestplate",
		inventory_image = "christmas_holiday_pack_inv_chestplate_cane.png",
		groups = {armor_torso=16, armor_heal=12, armor_use=200},
		wear = 0,
	})
	minetest.register_tool("christmas_holiday_pack:leggings_cane", {
		description = "Candy Cane Leggings",
		inventory_image = "christmas_holiday_pack_inv_leggings_cane.png",
		groups = {armor_legs=16, armor_heal=12, armor_use=200},
		wear = 0,
	})
	minetest.register_tool("christmas_holiday_pack:boots_cane", {
		description = "Candy Cane Boots",
		inventory_image = "christmas_holiday_pack_inv_boots_cane.png",
		groups = {armor_feet=12, armor_heal=12, armor_use=200},
		wear = 0,
        })
        minetest.register_tool("christmas_holiday_pack:shield_cane", {
		description = "Candy Cane Shield",
		inventory_image = "christmas_holiday_pack_inv_shield_cane.png",
		groups = {armor_shield=12, armor_heal=12, armor_use=200},
		wear = 0,
	})


code:
########	TEXTURES	########
christmas_holiday_pack_candy_cane_block.png -- GreenXenith
christmas_holiday_pack_green_candy_cane_block.png -- FreeGamers.org
christmas_holiday_pack_gingerbread_block.png -- C_is_CREATIVE
christmas_holiday_pack_frosting_block.png -- GreenXenith
christmas_holiday_pack_candy_cane.png -- GreenXenith
christmas_holiday_pack_green_candy_cane.png -- FreeGamers.org
christmas_holiday_pack_gingerbread_cookie.png -- GreenXenith
christmas_holiday_pack_christmas_chest_red_bottom.png -- C_is_CREATIVE
christmas_holiday_pack_christmas_chest_red_front.png -- C_is_CREATIVE
christmas_holiday_pack_christmas_chest_red_side.png -- C_is_CREATIVE
christmas_holiday_pack_christmas_chest_red_top.png -- C_is_CREATIVE
christmas_holiday_pack_christmas_chest_blue_bottom.png -- FreeGamers.org
christmas_holiday_pack_christmas_chest_blue_front.png -- FreeGamers.org
christmas_holiday_pack_christmas_chest_blue_side.png -- FreeGamers.org
christmas_holiday_pack_christmas_chest_blue_top.png -- FreeGamers.org
christmas_holiday_pack_christmas_chest_green_bottom.png -- FreeGamers.org
christmas_holiday_pack_christmas_chest_green_front.png -- FreeGamers.org
christmas_holiday_pack_christmas_chest_green_side.png -- FreeGamers.org
christmas_holiday_pack_christmas_chest_green_top.png -- FreeGamers.org
christmas_holiday_pack_christmas_chest_yellow_bottom.png -- FreeGamers.org
christmas_holiday_pack_christmas_chest_yellow_front.png -- FreeGamers.org
christmas_holiday_pack_christmas_chest_yellow_side.png -- FreeGamers.org
christmas_holiday_pack_christmas_chest_yellow_top.png -- FreeGamers.org
christmas_hoilday_pack_green_peppermint_candies.png -- FreeGamers.org
christmas_holiday_pack_peppermint_candies.png -- IAmJoshuaStone
christmas_holiday_pack_sugar_cookie.png -- IAmJoshuaStone
christmas_holiday_pack_sugar_cookie_bell.png -- IAmJoshuaStone
christmas_holiday_pack_sugar_cookie_tree.png -- IAmJoshuaStone
christmas_holiday_pack_sugar_cookie_star.png -- IAmJoshuaStone
christmas_holiday_pack_mistletoe.png -- IAmJoshuaStone
christmas_holiday_pack_gingerbread.png -- IAmJoshuaStone
christmas_holiday_pack_stocking.png -- IAmJoshuaStone
christmas_holiday_pack_green_stocking.png -- IAmJoshuaStone
christmas_holiday_pack_stocking_background.png -- GreenXenith
christmas_holiday_pack_stocking_exit_button.png -- GreenXenith
christmas_holiday_pack_present_01.png -- FreeGamers.org
christmas_holiday_pack_present_02.png -- FreeGamers.org
christmas_holiday_pack_present_03.png -- FreeGamers.org
christmas_holiday_pack_present_04.png -- FreeGamers.org
christmas_holiday_pack_present_05.png -- FreeGamers.org
christmas_holiday_pack_present_06.png -- FreeGamers.org
christmas_holiday_pack_present_07.png -- FreeGamers.org
christmas_holiday_pack_christmas_bell.png -- IAmJoshuaStone
inv_mask_santa_hat.png -- IAmJoshuaStone
inv_mask_green_santa_hat.png -- IAmJoshuaStone
inv_mask_red_poof_ball_hat.png -- FreeGamers.org
inv_shirt_ugly_sweater.png -- FreeGamers.org
inv_suit_elf.png -- FreeGamers.org
inv_suit_orange_parka.png -- FreeGamers.org
inv_suit_santa.png -- FreeGamers.org
inv_suit_tree.png -- FreeGamers.org
christmas_holiday_pack_mask_green_santa_hat.png -- IAmJoshuaStone
christmas_holiday_pack_mask_santa_hat.png -- IAmJoshuaStone
christmas_holiday_pack_mask_red_poof_ball_hat.png -- antisocial_Ash
christmas_holiday_pack_shirt_ugly_sweater.png -- Zomblah
christmas_holiday_pack_suit_tree.png -- John Buck
christmas_holiday_pack_suit_elf.png -- TacoKing
christmas_holiday_pack_suit_orange_parka.png -- USE1ESS
christmas_holiday_pack_suit_santa.png -- TjingTjongWah
christmas_holiday_pack_hot_chocolate_glass -- FreeGamers.org
christmas_holiday_pack_eggnog_glass -- FreeGamers.org
peppermint -- IAmJoshuaStone
ginger -- IAmJoshuaStone


code:
-- Christmas Bell that rings every hour.
-- Most of this code is from the "bell" mod.

christmas_holiday_pack.bell_ring_interval = 3600; --60*60; -- ring each hour

christmas_holiday_pack.bell_save_file = minetest.get_worldpath().."/christmas_bell_positions.data";

local bell_positions = {};

christmas_holiday_pack.save_bell_positions = function( player )

   str = minetest.serialize( ({ bell_data = bell_positions}) );

   local file, err = io.open( christmas_holiday_pack.bell_save_file, "wb");
   if (err ~= nil) then
      return
   end
   file:write( str );
   file:flush();
   file:close();
end

christmas_holiday_pack.restore_bell_data = function()

   local bell_position_table;

   local file, err = io.open(christmas_holiday_pack.bell_save_file, "rb");
   if (err ~= nil) then
      print("Error: Could not open bell data savefile (ignore this message on first start)");
      return
   end
   local str = file:read();
   file:close();

   local bell_positions_table = minetest.deserialize( str );
   if( bell_positions_table and bell_positions_table.bell_data ) then
     bell_positions = bell_positions_table.bell_data;
   end
end

-- actually ring the bell
christmas_holiday_pack.ring_bell_once = function()

   for i,v in ipairs( bell_positions ) do
      minetest.sound_play( "bell_small",
        { pos = v, gain = 1.5, max_hear_distance = 300,});
   end
end

christmas_holiday_pack.ring_bell = function()

   -- figure out if this is the right time to ring
   local sekunde = tonumber( os.date( "%S"));
   local minute  = tonumber( os.date( "%M"));
   local stunde  = tonumber( os.date( "%I")); -- in 12h-format (a bell that rings 24x at once would not survive long...)
   local delay   = christmas_holiday_pack.bell_ring_interval;

   delay = christmas_holiday_pack.bell_ring_interval - sekunde - (minute*60);

   -- make sure the bell rings the next hour
   minetest.after( delay, christmas_holiday_pack.ring_bell );

   -- if no bells are around then don't ring
   if( bell_positions == nil or #bell_positions < 1 ) then
      return;
   end

   -- ring the bell for each hour once
   for i=1,stunde do
     minetest.after( (i-1)*5,  christmas_holiday_pack.ring_bell_once );
   end

end

-- first call (after the server has been started)
minetest.after( 10, christmas_holiday_pack.ring_bell );
-- read data about bell positions
christmas_holiday_pack.restore_bell_data();

minetest.register_node("christmas_holiday_pack:christmas_bell", {
    description = "Bell",
    node_placement_prediction = "",
	tiles = {"christmas_holiday_pack_christmas_bell.png"},
	paramtype = "light",
	is_ground_content = true,
    inventory_image = 'christmas_holiday_pack_christmas_bell.png',
    wield_image = 'christmas_holiday_pack_christmas_bell.png',
    stack_max = 1,
	drawtype = "plantlike",
    on_punch = function (pos,node,puncher)
        minetest.sound_play( "bell_small",
           { pos = pos, gain = 1.5, max_hear_distance = 300,});
	end,

    after_place_node = function(pos, placer)
       -- remember that there is a bell at that position
       table.insert( bell_positions, pos );
       christmas_holiday_pack.save_bell_positions( placer );
    end,

    after_dig_node = function(pos, oldnode, oldmetadata, digger)
       local found = 0;
       -- actually remove the bell from the list
       for i,v in ipairs( bell_positions ) do
          if( v ~= nil and v.x == pos.x and v.y == pos.y and v.z == pos.z ) then
             found = i;
          end
       end
       -- actually remove the bell
       if( found > 0 ) then
          table.remove( bell_positions, found );
          christmas_holiday_pack.save_bell_positions( digger );
       end
    end,
    groups = {cracky=2},
})


code:
-- Add Christmas Costumes.(Requires 3d Armor Mod by Stu)
-- Mostly based on the costumes submodule in the mod "halloween" by GreenDiamond.

-- Function for registering suits
function christmas_holiday_pack.register(costume, nodename, def)
	if not def then
		def = {}
	end

	local gen_prev = "((([combine:16x32:-16,-12=christmas_holiday_pack_suit_" .. nodename .. ".png^[mask:mask_chest.png)^([combine:16x32:-36,-8=christmas_holiday_pack_suit_" .. nodename .. ".png^[mask:mask_head.png)^([combine:16x32:-44,-12=christmas_holiday_pack_suit_" .. nodename .. ".png^[mask:mask_arm.png^[transformFX)^([combine:16x32:-44,-12=christmas_holiday_pack_suit_" .. nodename .. ".png^[mask:mask_arm.png)^([combine:16x32:4,0=christmas_holiday_pack_suit_" .. nodename .. ".png^[mask:mask_leg.png^[transformFX)^([combine:16x32:4,0=christmas_holiday_pack_suit_" .. nodename .. ".png^[mask:mask_leg.png))^[resize:32x64)^[mask:mask_preview.png"

	local grouptypes = {
		["suit"] = {armor_head=1, armor_torso=1, armor_legs=1, armor_feet=1, armor_use=1000},
		["mask"] = {armor_head=1, armor_use=1000},
		["shirt"] = {armor_torso=1, armor_use=1000},
	}

	local function is_type(key)
		return grouptypes[key] ~= nil
	end

	local grouptype = "suit"

	if def.type then
		if is_type(def.type) then
			grouptype = def.type
		end
	end

	local armor_groups = grouptypes[grouptype]
	local node_str = grouptype.."_"..nodename

	if def.name then
		node_str = def.name
	end

	armor:register_armor("christmas_holiday_pack:"..node_str, {
		description = costume,
		inventory_image = "inv_"..grouptype.."_"..nodename..".png",
		groups = armor_groups,
		on_equip = def.on_equip or nil,
		on_unequip = def.on_unequip or nil,
		on_destroy = def.on_destroy or nil,
		on_damage = def.on_damage or nil,
		on_punched = def.on_punched or nil,
	})

	local override_prev = gen_prev

	if def.preview then
		override_prev = def.preview
	end

	minetest.override_item("christmas_holiday_pack:"..node_str, {
		preview = override_prev
	})
end

-- Register Costumes
christmas_holiday_pack.register("Orange Parka", "orange_parka")
christmas_holiday_pack.register("Christmas Elf Costume", "elf")
christmas_holiday_pack.register("Christmas Tree Costume", "tree")
christmas_holiday_pack.register("Santa Claus Costume", "santa")

-- Register Ugly Sweater
christmas_holiday_pack.register("Ugly Christmas Sweater", "ugly_sweater", {
	type = "shirt",
	preview = "((([combine:16x32:-28,-12=christmas_holiday_pack_shirt_ugly_sweater.png^[mask:mask_chest.png)^([combine:16x32:-36,-8=christmas_holiday_pack_shirt_ugly_sweater.png^[mask:mask_head.png)^([combine:16x32:-52,-12=christmas_holiday_pack_shirt_ugly_sweater.png^[mask:mask_arm.png^[transformFX)^([combine:16x32:-52,-12=christmas_holiday_pack_shirt_ugly_sweater.png^[mask:mask_arm.png)^([combine:16x32:4,0=christmas_holiday_pack_shirt_ugly_sweater.png^[mask:mask_leg.png^[transformFX)^([combine:16x32:4,0=christmas_holiday_pack_shirt_ugly_sweater.png^[mask:mask_leg.png))^[resize:32x64)^[mask:mask_preview.png"
})
-- Register Santa Hat
christmas_holiday_pack.register("Santa Hat", "santa_hat", {
	type = "mask",
	preview = "((([combine:16x32:-16,-12=christmas_holiday_pack_mask_santa_hat.png^[mask:mask_chest.png)^([combine:16x32:-36,-8=christmas_holiday_pack_mask_santa_hat.png^[mask:mask_head.png)^([combine:16x32:-44,-12=christmas_holiday_pack_mask_santa_hat.png^[mask:mask_arm.png^[transformFX)^([combine:16x32:-44,-12=christmas_holiday_pack_mask_santa_hat.png^[mask:mask_arm.png)^([combine:16x32:4,0=christmas_holiday_pack_mask_santa_hat.png^[mask:mask_leg.png^[transformFX)^([combine:16x32:4,0=christmas_holiday_pack_mask_santa_hat.png^[mask:mask_leg.png))^[resize:32x64)^[mask:mask_preview.png"
})
-- Register Green Santa Hat
christmas_holiday_pack.register("Green Chritmas Hat", "green_santa_hat", {
	type = "mask",
	preview = "((([combine:16x32:-16,-12=christmas_holiday_pack_mask_green_santa_hat.png^[mask:mask_chest.png)^([combine:16x32:-36,-8=christmas_holiday_pack_mask_green_santa_hat.png^[mask:mask_head.png)^([combine:16x32:-44,-12=christmas_holiday_pack_mask_green_santa_hat.png^[mask:mask_arm.png^[transformFX)^([combine:16x32:-44,-12=christmas_holiday_pack_mask_green_santa_hat.png^[mask:mask_arm.png)^([combine:16x32:4,0=christmas_holiday_pack_mask_green_santa_hat.png^[mask:mask_leg.png^[transformFX)^([combine:16x32:4,0=christmas_holiday_pack_mask_green_santa_hat.png^[mask:mask_leg.png))^[resize:32x64)^[mask:mask_preview.png"
})
-- Register Red Poof Ball Hat
christmas_holiday_pack.register("Red Poofball Hat", "red_poof_ball_hat", {
	type = "mask",
	preview = "((([combine:16x32:-16,-12=christmas_holiday_pack_mask_red_poof_ball_hat.png^[mask:mask_chest.png)^([combine:16x32:-36,-8=christmas_holiday_pack_mask_red_poof_ball_hat.png^[mask:mask_head.png)^([combine:16x32:-44,-12=christmas_holiday_pack_mask_red_poof_ball_hat.png^[mask:mask_arm.png^[transformFX)^([combine:16x32:-44,-12=christmas_holiday_pack_mask_red_poof_ball_hat.png^[mask:mask_arm.png)^([combine:16x32:4,0=christmas_holiday_pack_mask_red_poof_ball_hat.png^[mask:mask_leg.png^[transformFX)^([combine:16x32:4,0=christmas_holiday_pack_mask_red_poof_ball_hat.png^[mask:mask_leg.png))^[resize:32x64)^[mask:mask_preview.png"
})


code:
-- Craft items and edibles for Christmas
-- these items can be made into blocks: candycanes, gingerbread man.

-- Candy Cane
minetest.register_craftitem("christmas_holiday_pack:candy_cane", {
	description = "Candy Cane",
	inventory_image = "christmas_holiday_pack_candy_cane.png",
	on_use = minetest.item_eat(3),
})

-- Green Candy Cane
minetest.register_craftitem("christmas_holiday_pack:green_candy_cane", {
	description = "Green Candy Cane",
	inventory_image = "christmas_holiday_pack_green_candy_cane.png",
	on_use = minetest.item_eat(3),
})

-- Gingerbread Dough
minetest.register_craftitem("christmas_holiday_pack:gingerbread_dough", {
        description = "Gingerbread Dough",
        inventory_image = "christmas_holiday_pack_gingerbread_dough.png",
        on_use = minetest.item_eat(2),
})

-- Gingerbread
minetest.register_craftitem("christmas_holiday_pack:gingerbread", {
        description = "Gingerbread",
        inventory_image = "christmas_holiday_pack_gingerbread.png",
        on_use = minetest.item_eat(6),
})

-- Peppermint Candies
minetest.register_craftitem("christmas_holiday_pack:peppermint_candies", {
        description = "Peppermint Candies",
        inventory_image = "christmas_holiday_pack_peppermint_candies.png",
        on_use = minetest.item_eat(2),
})

-- Green Peppermint Candies
minetest.register_craftitem("christmas_holiday_pack:green_peppermint_candies", {
        description = "Green Peppermint Candies",
        inventory_image = "christmas_holiday_pack_green_peppermint_candies.png",
        on_use = minetest.item_eat(2),
})

-- Gingerbread Cookie
minetest.register_craftitem("christmas_holiday_pack:gingerbread_cookie", {
	description = "Gingerbread Cookie",
	inventory_image = "christmas_holiday_pack_gingerbread_cookie.png",
	on_use = minetest.item_eat(4),
})

-- Sugar Cookie
minetest.register_craftitem("christmas_holiday_pack:sugar_cookie", {
        description = "Sugar Cookie",
        inventory_image = "christmas_holiday_pack_sugar_cookie.png",
        on_use = minetest.item_eat(6),
})

-- Bell Sugar Cookie
minetest.register_craftitem("christmas_holiday_pack:sugar_cookie_bell", {
        description = "Bell Sugar Cookie",
        inventory_image = "christmas_holiday_pack_sugar_cookie_bell.png",
        on_use = minetest.item_eat(6),
})

-- Star Sugar Cookie
minetest.register_craftitem("christmas_holiday_pack:sugar_cookie_star", {
        description = "Star Sugar Cookie",
        inventory_image = "christmas_holiday_pack_sugar_cookie_star.png",
        on_use = minetest.item_eat(6),
})

-- Tree Sugar Cookie
minetest.register_craftitem("christmas_holiday_pack:sugar_cookie_tree", {
        description = "Tree Sugar Cookie",
        inventory_image = "christmas_holiday_pack_sugar_cookie_tree.png",
        on_use = minetest.item_eat(6),
})

-- Glass of Eggnog
minetest.register_craftitem("christmas_holiday_pack:eggnog_glass", {
        description = "Glass of Eggnog",
        inventory_image = "christmas_holiday_pack_eggnog_glass.png",
	on_use = minetest.item_eat(3, 'vessels:drinking_glass'),
})
-- Glass of Hot Chocolate
minetest.register_craftitem("christmas_holiday_pack:hot_chocolate_glass", {
        description = "Glass of Hot Chocolate",
        inventory_image = "christmas_holiday_pack_hot_chocolate_glass.png",
	on_use = minetest.item_eat(2, 'vessels:drinking_glass'),
})