dofile("Scripts/Objects/Materials/tree.lua");
dofile("Scripts/Objects/Types/tree.lua");

wave_touch = "Effects/trees/green_tree_touch.dsc";
leaves_splash = "Effects/trees/green_tree_splash.dsc";
destr_splash = "Effects/trees/green_tree_break.dsc";

-- INIT
crown = -1;
trunk = -1;
damage = -1;
dam_tree = 100;
state = 0;


function Initialize()
  crown = object.GetFrameGroupId("Crown");
  if not crown then ScreenError("TREE Object \"" .. object.GetName() .. "\" hasn't a CROWN!"); end
  trunk = object.GetFrameGroupId("Trunk");
  if not trunk then ScreenError("TREE Object \"" .. object.GetName() .. "\" hasn't a TRUNK!"); end
end



function CheckDamageAP(Caliber, Point, Random)
	dam_tree = CalculateDirectDamage(Caliber, Random, dam_tree);

	if object.IsVisibleByCamera() then	-- place visuals
		if state == 0 and dam_tree < 24 then	CreateObject(wave_touch, Point);
		elseif state == 0 then	CreateObject(leaves_splash, Point);
		else	CreateObject(destr_splash, Point);
		end
	end

	if dam_tree <=48 then
		object.SetGroupVisible(false, crown);
		crown = -1;
		state = 1;
	end

	if dam_tree <= 0 then
		object.SetGroupVisible(false, trunk);
		trunk = -1;
  		object.Die();
	end
end



function CheckDamageHE(Caliber, Point, DistanceFactor, Random)
	dam_tree = CalculateSplashDamage(Caliber, Random, dam_tree, DistanceFactor);

	if object.IsVisibleByCamera() then	-- place visuals
		if state == 0 and dam_tree < 24 then	CreateObject(wave_touch, Point);
		elseif state == 0 then	CreateObject(leaves_splash, Point);
		else	CreateObject(destr_splash, Point);
		end
	end

	if dam_tree <=48 then
		object.SetGroupVisible(false, crown);
		crown = -1;
		state = 1;
	end

	if dam_tree <= 0 then
		object.SetGroupVisible(false, trunk);
		trunk = -1;
		object.Die();
	end
end



function CalculateDirectDamage(cal, rnd, frame_dam)
	local dam = (ap_cal_max - ap_cal_min) / 100 * (cal - ap_cal_min);
	return frame_dam - dam
end


function CalculateSplashDamage(cal, rnd, frame_dam, distfactor)
	local dam = (he_cal_max - he_cal_min) / 100 * (cal - he_cal_min);
	if dam < 0 then dam =0; end
	if distfactor < he_distance_cut then
		dam = 0;
	else
		dam = dam * distfactor;
	end
	return frame_dam - dam - 20
end


function CheckCollision(Object)
	object.SetGroupVisible(false, trunk);
	object.SetGroupVisible(false, crown);
	CreateObject(destr_splash, object.GetPosition());
--	PlaySound("derevo_slomali",object.GetPosition());
	object.Die();
end
