-- Game State ----------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------
dofile("script\\sound.lua");

thread_load_act = 0;
not_hint=false
after_saving = false;

g_attachedID = -1;

cur_lev = "";
cur_lev_numb = "";
cur_sub_lev_numb = "";
-- Init values
username = GetCurrentUser();                     -- Get current player name. String
savepath = GetSavePath() .. username .. ".sav"; -- Get save path. String
text_sheet = "re";                                 -- Text sheet const
sheet = "gr";                                     -- Tool sheet const
gamedata = {};                                    -- Table of logical game data
gamedata.id_index = 50000;                        -- Starting value of objects id index

gamedata.current_level = "comics";                            -- Starting level
gamedata.cur_lev_number = 0;
gamedata.cur_sub_lev_number = 50;
TargetID2=87651

obj = {};                                        -- Unique objects id dictionary
flags = {};                                        -- Dictionary of logical game flags
PlayList()

do
-- declare local variables
--// exportstring( string )
--// returns a "Lua" portable version of the string
local function exportstring( s )
    s = string.format( "%q",s )
    -- to replace
    s = string.gsub( s,"\\\n","\\n" )
    s = string.gsub( s,"\r","\\r" )
    s = string.gsub( s,string.char(26),"\"..string.char(26)..\"" )
    return s
end
--// The Save Function
function table.save(  tbl,filename )
    local charS,charE = "   ","\n"
    local file,err
    -- create a pseudo file that writes to a string and return the string
    if not filename then
        file =  { write = function( self,newstr ) self.str = self.str..newstr end, str = "" }
        charS,charE = "",""
    -- write table to tmpfile
    elseif filename == true or filename == 1 then
        charS,charE,file = "","",io.tmpfile()
    -- write table to file
    -- use io.open here rather than io.output, since in windows when clicking on a file opened with io.output will create an error
    else
        file,err = io.open( filename, "w" )
        if err then return _,err end
    end
    -- initiate variables for save procedure
    local tables,lookup = { tbl },{ [tbl] = 1 }
    file:write( "return {"..charE )
    for idx,t in ipairs( tables ) do
        if filename and filename ~= true and filename ~= 1 then
            file:write( "-- Table: {"..idx.."}"..charE )
        end
        file:write( "{"..charE )
        local thandled = {}
        for i,v in ipairs( t ) do
            thandled[i] = true
            -- escape functions and userdata
            if type( v ) ~= "userdata" then
                -- only handle value
                if type( v ) == "table" then
                    if not lookup[v] then
                        table.insert( tables, v )
                        lookup[v] = #tables
                    end
                    file:write( charS.."{"..lookup[v].."},"..charE )
                elseif type( v ) == "function" then
                    file:write( charS.."loadstring("..exportstring(string.dump( v )).."),"..charE )
                else
                    local value =  ( type( v ) == "string" and exportstring( v ) ) or tostring( v )
                    file:write(  charS..value..","..charE )
                end
            end
        end
        for i,v in pairs( t ) do
            -- escape functions and userdata
            if (not thandled[i]) and type( v ) ~= "userdata" then
                -- handle index
                if type( i ) == "table" then
                    if not lookup[i] then
                        table.insert( tables,i )
                        lookup[i] = #tables
                    end
                    file:write( charS.."[{"..lookup[i].."}]=" )
                else
                    local index = ( type( i ) == "string" and "["..exportstring( i ).."]" ) or string.format( "[%d]",i )
                    file:write( charS..index.."=" )
                end
                -- handle value
                if type( v ) == "table" then
                    if not lookup[v] then
                        table.insert( tables,v )
                        lookup[v] = #tables
                    end
                    file:write( "{"..lookup[v].."},"..charE )
                elseif type( v ) == "function" then
                    file:write( "loadstring("..exportstring(string.dump( v )).."),"..charE )
                else
                    local value =  ( type( v ) == "string" and exportstring( v ) ) or tostring( v )
                    file:write( value..","..charE )
                end
            end
        end
        file:write( "},"..charE )
    end
    file:write( "}" )
    -- Return Values
    -- return stringtable from string
    if not filename then
        -- set marker for stringtable
        return file.str.."--|"
    -- return stringttable from file
    elseif filename == true or filename == 1 then
        file:seek ( "set" )
        -- no need to close file, it gets closed and removed automatically
        -- set marker for stringtable
        return file:read( "*a" ).."--|"
    -- close file and return 1
    else
        file:close()
        return 1
    end
end

--// The Load Function
function table.load( sfile )
    -- catch marker for stringtable
    if string.sub( sfile,-3,-1 ) == "--|" then
        tables,err = loadstring( sfile )
    else
        tables,err = loadfile( sfile )
    end
    if err then return _,err
    end
    tables = tables()
    for idx = 1,#tables do
        local tolinkv,tolinki = {},{}
        for i,v in pairs( tables[idx] ) do
            if type( v ) == "table" and tables[v[1]] then
                table.insert( tolinkv,{ i,tables[v[1]] } )
            end
            if type( i ) == "table" and tables[i[1]] then
                table.insert( tolinki,{ i,tables[i[1]] } )
            end
        end
        -- link values, first due to possible changes of indices
        for _,v in ipairs( tolinkv ) do
            tables[idx][v[1]] = v[2]
        end
        -- link indices
        for _,v in ipairs( tolinki ) do
            tables[idx][v[2]],tables[idx][v[1]] =  tables[idx][v[1]],nil
        end
    end
    return tables[1]
end
end; -- close do
-- End table.save/table.load ------------------------------------------------------------------------

before_load = 0;
not_exit = false;


function wait_dropping(thread_id) --функция, выполняемая после завершения удаления локаций

    if neighbors[neighbors[thread_id]].threadId~=0 then
        messagebox("progress loading loc_name.."..neighbors[thread_id]);
    end;
      if type(neighbors[neighbors[thread_id]])=="table" and neighbors[neighbors[thread_id]].del_threadId==thread_id then
       
        neighbors[neighbors[thread_id]].del_threadId=0;
        neighbors[neighbors[thread_id]].loaded=false;
        WriteToConsole("Location = "..neighbors[neighbors[thread_id]].name.." deleted\n");
    end
end;

function DropLocation(loc1, loc2) --функция удаления соседних локаций, относительно покидаемой локации, вызывается из jump
      if type(neighbors[loc1]) == "table" then
        for i=1,neighbors[loc1].neighbors_count,1 do
            if type(neighbors[neighbors[loc1][i]])=="table" and neighbors[neighbors[loc1][i]].loaded and neighbors[neighbors[loc1][i]].name ~= loc2 and neighbors[neighbors[loc1][i]].threadId==0 and neighbors[neighbors[loc1][i]].del_threadId==0 then                
                if neighbors[neighbors[loc1][i]].threadId~=0 then
                    messagebox("progress loading loc_name.."..neighbors[neighbors[loc1][i]]);
                end;                
                local thread_id=DeleteResources("./data/0/global_res.lua",neighbors[loc1][i],"wait_dropping");
                neighbors[neighbors[loc1][i]].del_threadId = thread_id; 
                neighbors[thread_id] = neighbors[loc1][i];
                delete_tree_leaf("Root",neighbors[loc1][i]);
                neighbors[neighbors[loc1][i]].obj_created=false;
                WriteToConsole("Start Dropping Location "..neighbors[neighbors[loc1][i]].name.."is not loaded ThreadId = "..neighbors[neighbors[loc1][i]].threadId.." DelThread = "..neighbors[neighbors[loc1][i]].del_threadId.." \n")                            
            end
        end;
    end;
end;

function finish_load ()

    --ShowCursor(true)    
    --ShowMenu(true)
    SaveGame()
    whole_darkness=false;
    
end;



function PlayMusic()
    --if not flags.is_comics then
        k=table.getn(play)
        m=math.random(1,k);
        if play[m]~=-1 then        
            if playfile(play[m],false,true) then
            WriteToConsole("play[m] = "..play[m].."\n")
            timer_time=dlinap[m]+zader[m]
            StartTimer(12542,timer_time,"PlayMusic",true)          
            play[m]=-1;
			else
			StartTimer(12542,1,"PlayMusic",true)	
			end	
        else
            is_list_emty=true
            for i,v in pairs(play) do
                if play[i]~=-1 then
                    is_list_emty=false
                end;
            end;
            if not is_list_emty then
                PlayMusic()
            else
               PlayList()   
               PlayMusic()
            end;
        end;
    --end;
end;

Emitters={
"fakel2","fakel1","fakel3","fakel4","fakel_dop","svecha","svecha_loc","fakel_perehod","fire_krysy","fire_krysy2","fire_krysy_loc","FlyList","FlyList1","FlyList3","FlyList4","FlyList5",
"tiger_eye1","tiger_eye2","duh","strujka","kislota","benzopila","kislota1","kap","kap1","smoke","iskri","iskri1","el_chair","electro","el_chair1","sm_comics2","sm_comics3","from_duh","to_duh","pism",
"dver_exit","one2","one1","stol","veshalka","ugol","shkaf","book","laborator","polka","molot","gorza","molnii1","molnii","nog","stol_lab","bulavka","dverka_lab","chulan","reshetka",
"veshalka","saray","bcol","taburet","derevo","case","statuj","vaza","shkaf_police","stol_police","kanistra","postbox","mostik","pogarbox","jama","veshalka","prichal_box","lebedka",
"secret_book","portret","kucha","na_fakel","mayor_wind","vaza_mayor","garderob","secret_nog","kamin","volf","vepr","tiger","kamin_stat","kartina_house","seyf_mayor","rubka","comodo",
"luk_john","conteiner","lebedkatwo","ugon_auto","zamok_turmy","derevo2","trava","kyst","kusty","rama","stenka","zamok_kamera","cep_krugka","taburetochka","water_kкugka","krysaki",
"kirpich","perehod","zavareno","racha","stulja","ventil_turma","shitok","posilka","napilnik","ruk_johnes","fomka","fonar","bagor","zarosli_hidd","kipit","waterH","main2","EyeG","EyeG1",
"Mouth","EyeS1","EyeS2","EyeS3","EyeS4","EyeS5","EyeS6","EyeS7","EyeS8","listva","pil2","water1","water2","water3",
"water4","SvetMig2","SvetMig3"
}

function StopAllEmitters()
    for i,v in pairs(Emitters) do
        StopEmiter(v);   
    end
end;

function alfa_out()
check_jmp()
   -- GetRenderTarget(TargetID2,"rendertar2");
   -- leafobj={TargetID2,9090}    
end;

function check_jmp()

    WriteToConsole("check_jmp start to = "..g_location.."\n")
    if (g_location~=nil or g_location~="") and neighbors[g_location].loaded  then
    WriteToConsole("check_jmp neighbors[g_location].loaded \n")
        neighbors[g_location].ready=true
            jump1();
            if not flags.is_comics then
            --    PlayMusic()    
            end;
            
    else 
        if neighbors[g_location].threadId == 0 then
        WriteToConsole("Load Locaion In CheckJump \n")
        LoadLocation(neighbors[g_location].name)
        end;
        WriteToConsole("Start Timer second time \n")
        StartTimer(7890,g_jumptime,"check_jmp")
    end
end;

function jump_effect()
   WriteToConsole("In Jump Effect \n")
   SetAlfa(9090,0,1,g_jumptime,"alfa_out");

end;


function jump1()
    if neighbors[g_location].ready then
    if not neighbors[g_location].loaded then
        WriteToConsole("Location "..neighbors[g_location].name.."is not loaded ThreadId = "..neighbors[g_location].threadId.." DelThread = "..neighbors[g_location].del_threadId.." \n")    
        return false;
    else
        if neighbors[g_location].obj_created then --переход на локацию, если ее объекты и лист созданы
            cur_lev = g_location;
            cur_lev_numb = g_curl;
            cur_sub_lev_numb = g_subl;                
            setcurentleaf(g_location,g_curl,g_subl);
            if flags.is_final_loc then
                WriteToConsole("IS_JUMPING")
            end;
            flags.is_jumping = true;
        elseif not neighbors[g_location].obj_created then --переход на локацию, если ее лист и объекты не созданы
            add_tree_leaf("Root",g_location,g_curl,g_subl);
            cur_lev = g_location;
            cur_lev_numb = g_curl;
            cur_sub_lev_numb = g_subl;
            dofile("./data/"..g_curl.."/"..g_subl.."/res.lua");
            flags.is_jumping = true;
            neighbors[g_location].obj_created = true;
            dofile("./data/"..g_curl.."/"..g_subl.."/level.lua");
        
            if flags.is_comics then
                ShowMenu(false)
            else
                if flags.is_final_loc then

                ShowMenu(false)
                else
                ShowMenu(true)
                end;    
                
                if not flags.is_hidden_loc then --рисование вкладок на новой локации
                    SwitchToSheet("gr");
                    SetDrawSheet("gr",true);
                end;
                if flags.is_hidden_loc then
                    SwitchToSheet("re");
                    SetDrawSheet("gr",false);
                end;
            end;
        end
        neighbors_func(g_location);
        DropLocation(g_loc0, g_location);
    StopAllEffects()        
        WaitRender()
        BlockCursor(false)
        SetAlfa(9090,1,0,g_jumptime,"finish_load");
        neighbors[g_location].ready=false    
        cur_location=g_location
        cur_curl=g_curl
        g_loc0="";
        g_location="";
        g_curl=0
        g_subl=0
    end    
    else
    check_jmp()
    end    


    -- DeleteRenderTarget(TargetID2)    
    -- ReturnHiddenObjects()        
    -- leafobj={}    

end;

function rendertar2(tex_name,tex_id)
 FlipVertical(TargetID);
 SetObjectPosition(TargetID,0,-256);
 LeaveObjectsOnReder("leafobj"); 
 SetAlfa(TargetID,0,1,0)
 check_jmp()
end;

function jump(loc0,location,curl,subl)
    WriteToConsole("In Jump \n")
    ClearCursor()
    ClearCursor1()
    ClearCurTables()    
    ActionsJump()
    g_loc0=loc0;
    g_location=location;
    g_curl=curl
    g_subl=subl       
    BlockCursor(true)
    if is_plashechka then
        HidePlashechka()
    end;
    neighbors[g_location].ready=false
--    ShowCursor(false)    
    jump_effect()
end;

function ending_thread(thread_id) --конец загрузки соседей начальной локации
    if neighbors[neighbors[thread_id]].del_threadId~=0 then
        messagebox("progress Delete loc_name.."..neighbors[thread_id]);
    end;
    if type(neighbors[neighbors[thread_id]])=="table" and neighbors[neighbors[thread_id]].threadId==thread_id then
        neighbors[neighbors[thread_id]].threadId=0;
        neighbors[neighbors[thread_id]].loaded=true;
        WriteToConsole("Location = "..neighbors[neighbors[thread_id]].name.." loaded\n");
        neighbors[thread_id]=nil;
    end
end;

function neighbors_func(param) --загрузка ресурсов соседей начальной локации
    if type(neighbors[param]) == "table" then
        for i=1,neighbors[param].neighbors_count,1 do
            if type(neighbors[neighbors[param][i]])=="table" and not neighbors[neighbors[param][i]].loaded and not neighbors[neighbors[param][i]].lock and neighbors[neighbors[param][i]].del_threadId==0 and neighbors[neighbors[param][i]].threadId==0 then
                local thread_id=PreLoadResource("./data/0/global_res.lua",neighbors[param][i],"ending_thread");
                neighbors[neighbors[param][i]].threadId =thread_id; 
                neighbors[thread_id]=neighbors[param][i];
                WriteToConsole("Start Preload Location "..neighbors[neighbors[param][i]].name.."is not loaded ThreadId = "..neighbors[neighbors[param][i]].threadId.." DelThread = "..neighbors[neighbors[param][i]].del_threadId.." \n")
                
            end
        end;
    end;
end;

function LoadLocation(loc_name)
   if not neighbors[loc_name].loaded and neighbors[loc_name].threadId==0 and neighbors[loc_name].del_threadId==0  then
    local thread_id=PreLoadResource("./data/0/global_res.lua",loc_name,"ending_thread");
    neighbors[loc_name].threadId =thread_id; 
    neighbors[thread_id]=loc_name;
    end;
end


function finish_preload_comics(id_comics)
  if id_comics == thread_comics4 then
    thread_comics4 = 0;
    flags.load_comics4 = true;
  return; end;
  if id_comics == thread_comics5 then
    thread_comics5 = 0;
    flags.load_comics5 = true;
  return; end;
  if id_comics == thread_comics6 then
    thread_comics6 = 0;
    flags.load_comics6 = true;
  return; end;
  if id_comics == thread_comics7 then
    thread_comics7 = 0;
    flags.load_comics7 = true;
  return; end;
  if id_comics == thread_comics11 then
    thread_comics11 = 0;
    flags.load_comics11 = true;
  return; end;
  if id_comics == thread_comics12 then
    thread_comics12 = 0;
    flags.load_comics12 = true;
  return; end;
end;

function finish_func1(id_thread)
    add_tree_leaf("Root",cur_lev,cur_lev_numb,cur_sub_lev_numb);
    dofile("./data/"..gamedata.cur_lev_number.."/"..gamedata.cur_sub_lev_number.."/res.lua");
    dofile("./data/"..gamedata.cur_lev_number.."/"..gamedata.cur_sub_lev_number.."/level.lua");
end;

function finish_func(id_thread) --ресурсы начальной локации загружены!
  if flags.is_final_loc then
          WriteToConsole("IS_JUMPING")
        flags.is_jumping=true
  end;        
    if id_thread == thread_load_act then
        thread_load_act = 0;
        cur_lev = gamedata.current_level;
        cur_lev_numb = gamedata.cur_lev_number;
        cur_sub_lev_numb = gamedata.cur_sub_lev_number;
        ShowMenu(true);
        neighbors[cur_lev].threadId=0;
        neighbors[cur_lev].loaded=true;
        neighbors[cur_lev].obj_created=true;
        WriteToConsole(neighbors[neighbors[id_thread]].name.." loaded\n");
    end;    

    add_tree_leaf("Root",cur_lev,cur_lev_numb,cur_sub_lev_numb);
    dofile("./data/"..gamedata.cur_lev_number.."/"..gamedata.cur_sub_lev_number.."/res.lua");
    dofile("./data/"..gamedata.cur_lev_number.."/"..gamedata.cur_sub_lev_number.."/level.lua");
    after_saving = false;
    
    neighbors_func(cur_lev); --запускаем загрузку ресурсов для соседей
    for i,v in pairs( obj ) do --восстанавливаем объекты инвентаря
        if type( obj[i] ) == "table" then
            if obj[i].is_stored then
                WriteToConsole("obj_id ="..obj[i].id.."notice = "..obj[i].notice.."resname= "..tostring(invent_source[obj[i].resname]).."textname= "..tostring(invent_texture[obj[i].resname]).."\n")
                loadresource(invent_source[obj[i].resname], invent_texture[obj[i].resname], obj[i].id);
                addactivobjecttogame(obj[i].id, invent_texture[obj[i].resname], 0+2048, 0+2048, "", obj[i].notice);
                if obj[i].metkaId~=nil and obj[i].metkaId~=0 then
                    addglobalobjecttogame(obj[i].metkaId,"magnifier",2000,2000,"",0,0,64,64);
                end;
                AddElement("gr", obj[i].id,obj[i].metkaId);
                MoveObjectToTree(obj[i].id);
            end;
        end;
    end;
    Block_Show_Cur(false);
    if flags.is_comics then
        ShowMenu(false)
    else
        ShowMenu(true)
        if not flags.is_hidden_loc then --рисование вкладок на новой локации
            SwitchToSheet("gr");
            SetDrawSheet("gr",true);
        end;
        if flags.is_hidden_loc then
            SwitchToSheet("re");
            SetDrawSheet("gr",false);
        end;
    end;
    WriteToConsole("flags.ShowWindow = "..tostring(flags.ShowWindow ).."\n")
    if flags.ShowWindow then
    LevelComplete()
        -- StoreObj(flags.obj_id_gl,nil,flags.text,335,350,flags.img,291,239,flags.metka_gl)
     flags.ShowWindow=false
    end;
  if flags.ShowTutorial then
    nexttutorial=true
    is_tutorial=false
  else
    nexttutorial=false  
  end;
    WaitRender()
end;

function SaveGame()
  -- gamedata.flags = flags
  -- gamedata.neighbors = neighbors
  -- gamedata.obj = obj
  -- table.save( gamedata, savepath );
  gamedata.flags = flags;
  gamedata.neighbors = neighbors
  gamedata.obj = obj;    
  gamedata.current_level = cur_lev;
  gamedata.cur_lev_number = cur_lev_numb;
  gamedata.cur_sub_lev_number = cur_sub_lev_numb;
  table.save( gamedata, savepath );
end;

function InitMenuAnim()
    --set_visible_object(12347,true);
    -- flyM={"InstantiationOfCircleR", 3, 40, 95, 60, 110,0,360, 5, false}
    -- StartTravel(12347,1,nil,nil,flyM)
    g_curr_anim=12347
    --speciale_action(2,g_curr_anim,true,0.1)
    --SetAlfa(12347,1,0,0)
     StartTimer(78321,0.1,"ChangeAnim",true)
     StartPosX=52
     StartPosY=552+92
     StartMoving=0
end;

function LoadGame()
  -- WriteToConsole("for i, v in pairs(neighbors) \n")
  for i, v in pairs(neighbors) do --сброс флагов, определяющих загрузку локаций
      if type(v) == "table" then
        v.loaded = false;
        v.obj_created=false;
        v.threadId = 0;
        v.del_threadId = 0;
        v.ready = false;
      end;
  end;
  objectid = 0;
  WriteToConsole("bef load \n")
 hFile=io.open( savepath, "r" );
 if hFile then --загрузка после сохранения

    gamedata = table.load( savepath );
    io.close(hFile);
    hFile=nil;
    WriteToConsole("table.load( savepath ) \n")
    flags = gamedata.flags;
    if not flags.GAMEOVER then
        flags.Obj_In_Cur=false
        neighbors = gamedata.neighbors
        obj = gamedata.obj;
        -- for i, v in pairs(obj) do --сброс флагов, определяющих загрузку локаций
          -- if type(v) == "table" and v.is_stored then
		   -- messagebox(tostring(v.resname))
          -- end;
        -- end; 		
        after_saving = true;    
        flags.Is_Satellite=false;
        flags.GlobalHint=false;
		flags.IngameMenu=false
        from_menu=false
        is_plashechka=false
        pl_process=false       
		not_hint=false	
		vilezmessage=false
		satelliteopen=false		
        WriteToConsole("all flags \n")
        local cur_lev=gamedata.current_level;
        for i, v in pairs(neighbors) do --сброс флагов, определяющих загрузку локаций
          if type(v) == "table" then
            v.loaded = false;
            v.obj_created=false;
            v.threadId = 0;
            v.del_threadId = 0;
            v.ready = false;
          end;
        end;    
        WriteToConsole("all tables \n")
        WriteToConsole("Start Preload\n")
        thread_load_act = PreLoadResource("./data/0/global_res.lua",gamedata.current_level,"finish_func");
        neighbors[gamedata.current_level].threadId = thread_load_act; 
        neighbors[thread_load_act]=gamedata.current_level;
        PlayList()   
        PlayMusic()
    else
        flags={}
        after_saving = false;    
        flags.Is_Satellite=false;
        flags.GlobalHint=false;
        thread_load_act = PreLoadResource("./data/0/global_res.lua",gamedata.current_level,"finish_func"); 
        neighbors[gamedata.current_level].threadId = thread_load_act; 
        neighbors[thread_load_act]=gamedata.current_level;        
    end;
-- InitMenuAnim()
--playfile(".\\sound\\mus01.ogg",false,true);
  return; end;    
  --новый профиль
  after_saving = false;
  
  thread_load_act = PreLoadResource("./data/0/global_res.lua",gamedata.current_level,"finish_func"); 
  neighbors[gamedata.current_level].threadId = thread_load_act; 
  neighbors[thread_load_act]=gamedata.current_level;
        
--InitMenuAnim()
    

end;

function NextLevel( nextlevel, next_sublevel )
    setnextlavel( nextlevel );
    loadlavel();
    gamedata.current_level = nextlevel;
end;

-- Auto unique id -----------------------------------------------------------------------------------
function NewId(name) -- name must be string
    if type(name) ~= "string" then 
        messagebox("Wrong type(" .. type(name) ..") of name param");
    return; end;
    
    if obj[name] == nil then
        obj[name] = {};
    end;
    
    if not obj[name].id then
        gamedata.id_index = gamedata.id_index + 1;
        obj[name].id = gamedata.id_index;
    --else
        --messagebox("There was a try to duplicate id of " .. tostring(name) .. " object");
    end;
    return obj[name].id;
end;
-- End of Auto id -----------------------------------------------------------------------------------

function NewObj(name, resname, x, y, notice,t_x,t_y,t_w,t_h,notice_ext) --создание активных объектов -- name не больше 6 символов (маленькие английскаие)
    if not flags.is_final_loc then
  if obj[name] ~= nil then --если объект уже был создан...

    if not obj[name].is_collapsed then --если объект не коллапсился...

      if t_x~=nil and t_y~=nil and t_w~=nil and t_h~=nil then
         addactivobjecttogame(obj[name].id, obj[name].resname, x, y, "", obj[name].notice,0,0,t_x,t_y,t_w,t_h); 
      else
      addactivobjecttogame(obj[name].id, obj[name].resname, x, y, "", obj[name].notice); -- unpack(arg));    
      end;
      if obj[name].is_removed then
         RemoveActivObject(obj[name].id)
      end;
    return; end;
    if obj[name].is_collapsed and not obj[name].is_stored and not obj[name].is_unstored then --если объект коллапсился
      if t_x~=nil and t_y~=nil and t_w~=nil and t_h~=nil then
         addactivobjecttogame(obj[name].id, obj[name].resname, x+2048, y+2048, "", obj[name].notice,0,0,t_x,t_y,t_w,t_h); 
      end;    
      if t_x==nil and t_y==nil and t_w==nil and t_h==nil then
      addactivobjecttogame(obj[name].id, obj[name].resname, x+2048, y+2048, "", obj[name].notice); -- unpack(arg));
      end;    
      speciale_action(2,obj[name].id)        
      RemoveActivObject(obj[name].id)
      if flags.is_hidden_loc then
        setcolor(obj[name].id,0.5,0.5,0.5,1,1)
      end;
      if flags.is_hidden_loc then --если мы на хиддене, включаем счетчик отработанных объектов...
        dropped_obj = dropped_obj + 1;
      end;
    return; end;
  end;  

  if obj[name] == nil then --объект не был создан ранее...
      obj[name] = {};
      obj[name].name = name;
      obj[name].id = StringToInt(obj[name]["name"]);
      obj[name].resname = resname;
      obj[name].notice = notice;
    if notice_ext~=nil then
        obj[name].notice_ext = notice_ext
    else
        obj[name].notice_ext = "";
    end;
      obj[name].is_collapsed = false;
    obj[name].is_collapsing = false;
      obj[name].is_stored = false;
    obj[name].is_removed = false;
    obj[name].is_unstored = false;
    obj[name].metkaId = 0;
      if t_x~=nil and t_y~=nil and t_w~=nil and t_h~=nil then
         addactivobjecttogame(obj[name].id, obj[name].resname, x, y, "", obj[name].notice,0,0,t_x,t_y,t_w,t_h); 
      end;    
      if t_x==nil and t_y==nil and t_w==nil and t_h==nil then
        addactivobjecttogame(obj[name].id, obj[name].resname, x, y, "", obj[name].notice); -- unpack(arg));
       end;    
  end;
    else
          obj[name] = {};
      obj[name].name = name;
      obj[name].id = StringToInt(obj[name]["name"]);
      obj[name].resname = resname;
      obj[name].notice = notice;
    if notice_ext~=nil then
        obj[name].notice_ext = notice_ext
    else
        obj[name].notice_ext = "";
    end;
      obj[name].is_collapsed = false;
    obj[name].is_collapsing = false;
      obj[name].is_stored = false;
    obj[name].is_removed = false;
    obj[name].is_unstored = false;
    obj[name].metkaId = 0;
      if t_x~=nil and t_y~=nil and t_w~=nil and t_h~=nil then
         addactivobjecttogame(obj[name].id, obj[name].resname, x, y, "", obj[name].notice,0,0,t_x,t_y,t_w,t_h); 
      end;    
      if t_x==nil and t_y==nil and t_w==nil and t_h==nil then
        addactivobjecttogame(obj[name].id, obj[name].resname, x, y, "", obj[name].notice); -- unpack(arg));
       end;    
  end;
end;

function CollapseObj(obj_id, coll_speed, coll_time)
  for i,v in pairs(obj) do
      if obj[i].id == obj_id then
        if not coll_speed then
            coll_speed = 6;
        end;
        if not coll_time then
            coll_time = 0.5;
        end;
 --collaps_obj(obj_id, 0, 0, coll_speed, coll_time);
     
      --Fadeaway(obj_id,nil,nil,"collaps","farShootStyle",7,{0.9,0.1,5,3,3,0.05,0.1})
      --em_name="Tunnel1"
      wdth,hgth=GetObjectSize(obj_id)

      if wdth<=64 and hgth<=64 then
        em_name="collapsing4"    
      end;
      if (wdth>64 or hgth>64) and  (wdth<=128 or hgth<=128) then
        em_name="collapsing3"    
      end;      
      if wdth>128 or hgth>128 then
        em_name="collapsing"    
      end;            
        Fadeaway(obj_id,nil,nil,--[["collaps"--]]"collapsing","farShootStyle",7,{0.8,0.3,2,700,1,0.2,0.1})    --"Tunnel1" 
        obj[i].is_collapsed = true;
      return; end;
  end;
end;


function CollapseObj1(obj_id, coll_speed, coll_time)


function InputCollapse (sender,id,at_id)
    if sender==33 then
       for i,v in pairs(obj) do
        if obj[i].id == id then
          obj[i].is_collapsed = true;
          obj[i].is_collapsing = false;
         end;
       end;     
       set_inpun_fun("gameinput");
       gameinput(12,id,at_id)                   
    end;
 
end;

  for i,v in pairs(obj) do
      if obj[i].id == obj_id then
      wo,ho=GetObjectSize(obj_id,true)    
      SetHotPoint(obj_id,math.floor(wo/2),math.floor(ho/2))
      set_inpun_fun("InputCollapse"); 
      ScaleObject(obj_id,1,1.4,2);
      SetAlfa(obj_id,1,0,2);    
      obj[i].is_collapsing=true;
      setcolor(obj[i].id,0.5,0.5,0.5,0.5,1);
      return; end;
  end;  
  
end;
function StoreInput(sender,id)
    if sender==26 then
         DeleteResource(res_name)
         StoreObj1(flags.obj_id_gl,flags.metka_gl)
    return;end;
end;

function StoreObj(obj_id,obj_loc,text_id,textx,texty,img,imgx,imgy,metka)
    flags.obj_id_gl=obj_id
    flags.metka_gl=metka
    flags.text=text_id
    flags.img=img
    obj_loc_gl=obj_loc
    speciale_action(2,obj_loc_gl);
          for i,v in pairs(obj) do
            if obj[i].id == flags.obj_id_gl then
              notice_ext=obj[i].notice_ext;
            end;
          end;        
    set_inpun_fun("StoreInput");
    res_str="data\\window_items\\"..tostring(img)..".png"
    res_name=img.."w"
    loadresource(res_str,res_name)
    CreateWindow1(100,100,text_id,nil,"okno",textx,texty,res_name,281,220,notice_ext,"StoreInput");
end;

function StoreObj1(obj_id,metka) 
    WriteToConsole("StoreObj1 \n")
   flags.obj_id_gl =0
   flags.metka_gl =0
    if obj_loc_gl~=nil then
        
        Set_Anim_Cur(obj_loc_gl,3)
          for i,v in pairs(obj) do
            if obj[i].id == obj_loc_gl then
              obj[i].is_collapsed = true;
            end;
          end;        
    end;   
  for i,v in pairs(obj) do
      if obj[i].id == obj_id then
      if metka~=0 and metka~=nil then
         flags["label_id"]=flags["label_id"]+1;
         addglobalobjecttogame(flags["label_id"],"magnifier",2000,2000,"",0,0,64,64);--particl star         
         obj[i].metkaId=flags["label_id"]
      else
        obj[i].metkaId=0
      end;
      AddElement("gr",obj_id,obj[i].metkaId);
        MoveObjectToTree(obj_id);
      obj[i].is_collapsed = true;
        obj[i].is_stored = true;
      set_inpun_fun("gameinput");
      SwitchToSheet("gr");
      ShowSheet("gr","move",2000,true);
      gameinput(50,obj_id);
      return; end;
  end;
 
end;

function UnStoreObj(obj_id)
  for i,v in pairs(obj) do
      if obj[i].id == obj_id then
      if obj[i].metkaId~=0 then
        del_object_from_game(obj[i].metkaId)
      end;
        DeleteElement(sheet,obj_id);
        obj[i].is_stored = false;
        obj[i].is_collapsed = true;
      obj[i].is_unstored = true;
      return; end;
  end;
end;

function CreateSatelite(parent,name)
    level = neighbors[name].level;
    sublevel = neighbors[name].sublevel;
    add_free_leaf("Root",name,level,sublevel);
    dofile("./data/"..level.."/"..sublevel.."/res.lua");
    set_satelite_leaf(parent);
    dofile("./data/"..level.."/"..sublevel.."/level.lua");
end;

local count =0;
local i=500000;
local coord = {};
local j=1;
local line=0;
local n=1;
local startX=0;
local startY=0;

function PolyCoord(dest)

           
        
        if count ==0 then
        x,y = GetCursorPos()
        coord[j] =x;         j=j+1;
        coord[j]=y;            j=j+1;

        count =1;
        startX=x;
        startY=y;
        return;end;
        
        if count ==1 then            
        x1,y1=GetCursorPos()    
        if n==6 then n=1; end
        i=i+1;
        AddLine(i,"tochka"..n,x,y,x1,y1,5);            
        speciale_action(4,i);        
        
        
        x=x1; y=y1;        
        coord[j]=x1;        j=j+1;
        coord[j]=y1;        j=j+1;
        line=line+1;    
        
        if x1 > startX -10 and x1 < startX+10 and y1 >startY-10 and y1<startY+10 then        
        io.output(io.open("data\\"..dest.."\\polygons.lua","a"))    
        io.write("CreatePolygon( "..(i-4)..", "..line..", ".." { ");
        for i,v in pairs(coord) do                
        if i==table.maxn (coord) or i==(table.maxn (coord)-1) or i==(table.maxn (coord)-2) then    
        if i==(table.maxn (coord)-2) then
        io.write(coord[i]);
        end
        else
        io.write(coord[i]);
        io.write(", "); 
        end    
        end        
        
        io.write(" } ".." )".."\n");
        io.close();
        count=0;coord = {};    line=0;    j=1; points_count = 0;
        
        n=n+1;         
        
        
        end;
        
        end;
        
        
end
-----------------------------------------------------------------------------------------------------
-- End Game State -----------------------------------------------------------------------------------
