local NAME = minetest.get_current_modname()
local sap_id = minetest.get_decoration_id(NAME .. ":sapling")

local True = 1
local False = 0
local treedef = { -- Yes, i will use L-trees, when i can send meshes over the network for proper trees.
	{ x= 0, y= 0, z= 0, leaf= False },
	{ x= 0, y= 1, z= 0, leaf= False },
	{ x= 0, y= 2, z= 0, leaf= False },
	{ x= 0, y= 3, z= 0, leaf= False },
		{ x= 1,  y= 3, z= 0,  leaf= True },
		{ x= -1, y= 3, z= 0,  leaf= True },
		{ x= 0,  y= 3, z= 1,  leaf= True },
		{ x= 0,  y= 3, z= -1, leaf= True },
		{ x= 1,  y= 3, z= 1,  leaf= True },
		{ x= 1,  y= 3, z= -1, leaf= True },
		{ x= -1, y= 3, z= 1,  leaf= True },
		{ x= -1, y= 3, z= -1, leaf= True },
	{ x= 0, y= 4,  z= 0, leaf= False },
		{ x= 1,  y= 4, z= 0,  leaf= True },
		{ x= -1, y= 4, z= 0,  leaf= True },
		{ x= 0,  y= 4, z= 1,  leaf= True },
		{ x= 0,  y= 4, z= -1, leaf= True },
		{ x= 1,  y= 4, z= 1,  leaf= True },
		{ x= 1,  y= 4, z= -1, leaf= True },
		{ x= -1, y= 4, z= 1,  leaf= True },
		{ x= -1, y= 4, z= -1, leaf= True },
	{ x= 0, y= 5,  z= 0, leaf= False },
		{ x= 1,  y= 5, z= 0,  leaf= True },
		{ x= -1, y= 5, z= 0,  leaf= True },
		{ x= 0,  y= 5, z= 1,  leaf= True },
		{ x= 0,  y= 5, z= -1, leaf= True },
		{ x= 1,  y= 5, z= 1,  leaf= True },
		{ x= 1,  y= 5, z= -1, leaf= True },
		{ x= -1, y= 5, z= 1,  leaf= True },
		{ x= -1, y= 5, z= -1, leaf= True },
	{ x= 0, y= 6,  z= 0, leaf= False },
		{ x= 1,  y= 6, z= 0,  leaf= True },
		{ x= -1, y= 6, z= 0,  leaf= True },
		{ x= 0,  y= 6, z= 1,  leaf= True },
		{ x= 0,  y= 6, z= -1, leaf= True },
		{ x= 1,  y= 6, z= 1,  leaf= True },
		{ x= 1,  y= 6, z= -1, leaf= True },
		{ x= -1, y= 6, z= 1,  leaf= True },
		{ x= -1, y= 6, z= -1, leaf= True }
}


orion.make_tree = function(x, y, z, variant)
	for i = 1, #treedef do
		local node
		if treedef[i]["leaf"] == 1 then
			node = NAME .. ":leaf"
		else
			node = NAME .. ":trunk_" .. variant
		end
		minetest.set_node({ x=x + treedef[i]["x"], y =y + treedef[i]["y"], z = z + treedef[i]["z"]}, { name = node})
	end
end

local make_trees = function(min_pos, max_pos, _)
	local random = PcgRandom(min_pos.x + min_pos.y * 2^16 + min_pos.z * 2^17 )
	local notification = minetest.get_mapgen_object("gennotify")
	local saplings = notification["decoration#" .. sap_id]
	if saplings == nil then return end
	for i = 1, #saplings do
		orion.make_tree(saplings[i]["x"], saplings[i]["y"], saplings[i]["z"], "c0" .. random:next(1,6))
	end
end

minetest.set_gen_notify({decoration = true}, {sap_id})
minetest.register_on_generated(make_trees)
