------------------- Библиотека служебных скриптов для OGSM 2.x ----------------

---------------------- Copyright 2007-2008 xStream & DEXXX --------------------

wthr = level.get_weather()
local wfx1 = "p_surge_day_"..tostring(level.get_time_hours())
local wfx2 = "surge_day_"..tostring(level.get_time_hours())

function do_timer_action(select_string,params_string)

if select_string=="eco_group" then
dialogs_predbannik.ecolog_group()
end

-- Начало алгоритма выброса --

-- 1. Настало время выброса.
	if select_string=="bl1" then
		if ogsm_surge then
			if (level.name() ~= "l03u_agr_underground") and (level.name() ~= "l08u_brainlab") and (level.name() ~= "l10u_bunker") and (level.name() ~= "l04u_labx18") and (level.name() ~= "l12u_sarcofag") and (level.name() ~= "l12u_control_monolith") and (level.name() ~= "l12_stancia") and (level.name() ~= "l12_stancia_2") and (level.name() ~= "av_peshera") and (level.name() ~= "warlab") and (level.name() ~= "jupiter_underground") and (level.name() ~= "labx8") and (level.name() ~= "peshera") and (level.name() ~= "predbannik") then
				if sleep_manager and sleep_manager.is_sleep_active() then sleep_manager.stopper() end
				amk.start_timer("bl2",1)
			else
				amk.g_start_timer("bl1",0,1,0)
			end
		else
			amk.g_start_timer("bl1",0,10,0)
		end
	end

-- 2. Сирена, первые визуальные признаки выброса
	if select_string=="bl2" then
        news_manager.send_tip(db.actor, "%c[255,255,128,128]Внимание%c[default] Приближается выброс. Сейчас тряхнет не по-детски, ищите норы ребята", nil, nil, 30000)
        ogsm_anomaly.blow_flags()
		snd_obj = xr_sound.get_safe_sound_object( [[ambient\siren1]] )
		snd_obj:play_no_feedback(db.actor, sound_object.s2d, 0, vector(), 1.0)
		db.Flag2 = 1
		amk.save_variable("blt", 1)
		level.set_weather("stancia")
		wfx1 = "p_surge_day_"..tostring(level.get_time_hours())
		level.set_weather_fx(wfx1)
		level.add_pp_effector("vibros_p.ppe", 1974, false)	
		local snd_obj = xr_sound.get_safe_sound_object([[anomaly\dezodor]])
		snd_obj:play_at_pos(db.actor, vector():set(0,0,0), 0, sound_object.s2d)
		amk.g_start_timer("bl3",0,0,6)
	end

-- 3. Проигрываем промежуточные эффекты
	if select_string=="bl3" then
		level.set_weather("stancia")
		level.set_weather_fx(wfx1)
		amk.g_start_timer("bl4",0,0,1)
	end

-- 4. Спустя 5 минут затишья начинаем выброс
	if select_string=="bl4" then
		xr_sound.set_actor_sound("")
		level.set_weather("stancia")
		local snd_obj = xr_sound.get_safe_sound_object([[ambient\earthquake]])
		snd_obj:play_at_pos(db.actor, vector():set(0,0,0), 0, sound_object.s2d)
		level.add_cam_effector("camera_effects\\earthquake.anm", 1974, true, "")
		wfx2 = "surge_day_"..tostring(level.get_time_hours())
		level.set_weather_fx(wfx2)
		level.add_pp_effector ("vibros.ppe", 1974, false)
		local snd_obj = xr_sound.get_safe_sound_object([[anomaly\blowout]])
		snd_obj:play_at_pos(db.actor, vector():set(0,0,0), 0, sound_object.s2d)
		ogsm_surge.play_sounds()
		amk.g_start_timer("bl5",0,0,3)
	end

-- 5. Начинаем расколбас
	if select_string=="bl5" then
		amk.save_variable("blt", 2)
		level.remove_cam_effector(1974)
		db.Dead2 = 1
		if db.FlagEsc == 0 then
			local snd_obj = xr_sound.get_safe_sound_object([[actor\pain_3]])
			snd_obj:play_at_pos(db.actor, vector():set(0,0,0), 0, sound_object.s2d)
			level.add_cam_effector("camera_effects\\head_shot.anm", 1975, false, "")
			ogsm_surge.g_R_Vibros:Run()
		end
		kill_crow()
		deaht_blowout()
		amk.g_start_timer("bl6",0,0,6)
	end


-- 6. Выброс близится к концу
	if select_string=="bl6" then
		level.set_weather_fx(wfx1)
		amk.g_start_timer("bl7",0,0,5)
	end

-- 7. Завершаем выброс, устанавливаем время следующего
	if select_string=="bl7" then
	    ogsm_surge.g_R_Vibros:Stop()
		if db.FlagEsc == 0 then
			level.add_cam_effector("camera_effects\\shell_shock.anm", 1974, false, "")
			local snd_obj = xr_sound.get_safe_sound_object([[actor\breath_1]])
			snd_obj:play_at_pos(db.actor, vector():set(0,0,0), 0, sound_object.s2d)
		end
		level.add_pp_effector ("teleport.ppe", 2009, false)
		local snd_obj2 = xr_sound.get_safe_sound_object([[ambient\earthquake]])
		snd_obj2:play_at_pos(db.actor, vector():set(0,0,0), 0, sound_object.s2d)
		level.set_weather(wthr)
		amk.del_variable("blt")
		amk.g_start_timer("bl1",0, lwc.t_surge+math.random(-6,6), 0)
		if ogsm_anomaly then
		    ogsm_anomaly.add_anom(level.name())
		end
	    	spawn_crow()
		db.Dead2 = 0
		db.Flag2 = 0
	end
end


-- Конец алгоритма выброса --

-- Загружаем все переменные, которые нужно, вызывается загрузке игры автоматически
function on_game_load()
	if amk.load_variable("frn",true) then
		amk.g_start_timer("bl1", 0, lwc.t_start, 0)
		ogsm_hideout.first_run()
		amk.save_variable("frn",false)
	end

	ogsm_hideout.get_level_hides()

	wthr = level.get_weather()
	level.set_weather("ogsm",true)
	game.start_tutorial("restore_sun")

end

function set_sun()
	if amk.load_variable("blt",0) == 1 then
		level.set_weather("stancia")
		db.Flag2 = 1
	elseif amk.load_variable("blt",0) == 2 then
		level.set_weather("stancia")
		db.Flag2 = 1
		db.Dead2 = 1
	else
		level.set_weather(wthr)
	end
end

--------------------------------------------------
--' Эта функция парсит строку из конфига артов
--' аномалии и выбирает какой арт спавнить
--------------------------------------------------
function parse_string_arts(obj_sect)
-- arts_table
local arts_table = {}
if not system_ini():section_exist(obj_sect) then 
	-- amk.logf("ARTF_D SUCH ANOMALY DONT EXIST "..tostring(obj_sect)) 
return nil end
local line = system_ini():r_string(obj_sect,"artefacts")

	if line then
		for key, value, dec in string.gfind( line, "%s*([%w_%-.\\]+)%s*,%s*(%d).(%d)%s*" ) do
			local artefact = {art = key, val = tonumber(tostring(value).."."..tostring(dec)) }
			table.insert(arts_table, artefact)
		end
	end
	
	local spawn_choose = amk.real_rand()
	-- -- amk.logf(tostring(spawn_choose))
	local low_level = 0.0
	local art_to_spawn = nil
	
	table.sort(arts_table,function(a,b) return a.val < b.val end)
	
	-- for debug only
		-- for key, value in pairs(arts_table) do
			-- -- amk.logf(tostring(value.art).."="..tostring(value.val))
		-- end	
	-- for debug only	
	
	for key, value in pairs(arts_table) do
		if spawn_choose < value.val and spawn_choose >= low_level then
			art_to_spawn = value.art
		end
		low_level = value.val
	end		
	
	-- -- amk.logf("ARTF_D we will spawn "..tostring(art_to_spawn).." rnd "..tostring(spawn_choose))
	return art_to_spawn
end

--added_stalbar_2009
--Рандом координат и спавн на уровнях  
function quest_spawn(obj_name, total, posit, y_offset, lv, gv)
	local zombie_index
	local new_pos
	local x_offset = 0
	local z_offset = 0
	local spawn_item
	local spawn_obj
	local obj
	local obj2
	for zombie_index=1, total do
		x_offset = math.random(40)-20
		z_offset = math.random(40)-20
		if( x_offset < 2 and x_offset > -2 ) then
			x_offset = -2
		end
		if( z_offset < 2 and z_offset > -2 ) then
			z_offset = -2
		end
		new_pos = posit
		new_pos.x = new_pos.x + x_offset
		new_pos.y = new_pos.y + y_offset
		new_pos.z = new_pos.z + z_offset
		spawn_item = alife():create("bolt", new_pos, lv, gv) 
		obj = alife():object(spawn_item.id)
--		logf("bolt_spawned-----------------------")
		if obj then
			local lvid, gvid = obj.m_level_vertex_id, obj.m_game_vertex_id
			if lvid then 
				local pos = obj.position
				local spawn_pos = level.vertex_position(lvid)
--				logf("obj_bolt_".."_obj_id_"..obj.id.."_lvid_"..lvid.."_gvid_"..gvid)
--				logf("pos_x_"..pos.x.."_pos_y_"..pos.y.."_pos_z_"..pos.z)
				alife():release(obj, true)
				spawn_obj = alife():create(obj_name, spawn_pos, lvid, gvid)
--				obj2 = alife():object(spawn_obj.id)
--				local lvid2, gvid2 = obj2.m_level_vertex_id, obj2.m_game_vertex_id
--				local pos2 = obj2.position
--				logf("obj2_"..obj_name.."_obj_id_"..obj2.id.."_lvid2_"..lvid2.."_gvid2_"..gvid2)
--				logf("pos2_x_"..pos2.x.."_pos2_y_"..pos2.y.."_pos2_z_"..pos2.z)
			end
		end	
	end
end

---вороны----
function kill_crow()
	for k=1,65355 do
		local crow = level.object_by_id(k)
		if crow and string.find(crow:name(), "m_crow") then
			local hit = hit()
			hit.direction = vector():set(0,0,0)
			hit.impulse = 10
			hit.draftsman = crow
			hit.power = 10
			hit.type = hit.strike
			if crow then 
				crow:hit(hit)
			end	
		end
	end
end

function spawn_crow()
local lv = db.actor:level_vertex_id()
local gv = db.actor:game_vertex_id()
local x_offset = 0
local z_offset = 0
local y_offset = 100
	for k=1,20 do
	x_offset = math.random(-100,100)
	z_offset = math.random(-100,100)
		local pos = db.actor:position()
		pos.x = pos.x + x_offset
		pos.y = pos.y + y_offset
		pos.z = pos.z + z_offset
		alife():create("m_crow", pos, lv, gv)
	end
end

function deaht_blowout()
    
    local level_name = level.name()
    local blow = hit()
	blow.direction = vector():set(0,0,0)
	blow.impulse = 0
	blow.draftsman = db.actor
	blow.power = 0.0
	blow.type = hit.explosion
	db.actor:hit(blow)
		
	level.add_cam_effector("camera_effects\\fusker.anm",959,false,"")
		
    local active_item = db.actor:active_item()
	if active_item and active_item:section()~= "bolt" and active_item:section()~= "wpn_knife" then
		db.actor:drop_item(active_item)
	end

    if db.Dead2 == 1 and db.FlagEsc == 0 then
         local h = math.random(1,100)
         local h_b = math.random(-0.8,-0.3)	
         local actor=db.actor
         actor.health = h_b
         actor.power  = -1.0
         actor.radiation = 0.0
         actor.psy_health = -0.6
         actor.morale = -0.6
         local a_sleep = math.random(1,3)
           if a_sleep > 30 then
                 sleep_manager.main (h)
           end
    end

    if db.FlagEsc == 1 then
         local h_s = math.random(-0.2,-0.05)
         local actor=db.actor
         actor.health = h_s
         actor.power  = -0.3
         actor.radiation = 0.0
         actor.psy_health = -0.2
         actor.morale = -0.2
    end
end

------------------- Библиотека служебных скриптов для OGSM 2.x ----------------

---------------------- Copyright 2007-2008 xStream & DEXXX --------------------

--[[

If you're going to use the whole of this script or its parts in your own creative 
developments for the S.T.A.L.K.E.R. game, please don't become such a goddamn 
motherfucker like the notorious author of the ABC Mod - Carbrobro. Leave the 
copyrights, note the real author(s) and don't claim others' ideas and their 
realization to be your own ones. It's just simple Modmakers' Ethics. Thank you!

Если вы собираетесь использовать данный скрипт целиком или частично в своих 
разработках по игре S.T.A.L.K.E.R., пожалуйста не опускайтесь до уровня печально 
известного автора ABC мода - Carbrobro. Не удаляйте копирайты, указывайте настоящего 
автора(ов) и не выдавайте чужие идеи и их реализацию за свои. Ведь это элементарная 
этика модостроителей! Спасибо за понимание.

]]--