---------------------------------------------------------------------------------------------------------------------------------------------------
--------- TUNNEL
---------------------------------------------------------------------------------------------------------------------------------------------------

local Tunnel = module("vrp","lib/Tunnel")
local Proxy = module("vrp","lib/Proxy")
vRP = Proxy.getInterface("vRP")

src = {}
Tunnel.bindInterface(GetCurrentResourceName(), src)
vSERVER = Tunnel.getInterface(GetCurrentResourceName())

---------------------------------------------------------------------------------------------------------------------------------------------------
--------- VARIABLES
---------------------------------------------------------------------------------------------------------------------------------------------------
 
local farmando = false
local pos = 1
local blips = nil
local typefarm = 'none'
local nivel = 0
local rotas = {}
local inPed = nil
local pedSpawn = true
local pedFire = true
local ameaca = 30
local armadura = 50
local arma = "WEAPON_PISTOL"
local inPed = nil
local inPed2 = nil
local inPed3 = nil
local inPed4 = nil
local methpedtruck = nil
local methpedtruckdriver = nil
local methpedtruck2 = nil
local methpedtruckdriver2 = nil
local movimento = 0
local reforco = false
local meuXp = 0
local meuXpLoja = 0
local fac = nil
local facId = nil

-----------------------------------------------------------------------------------------------------------------------------------------
-- PEDHASHS
-----------------------------------------------------------------------------------------------------------------------------------------
local pedHashs = {
	"ig_abigail",
	"u_m_y_abner",
	"a_m_o_acult_02",
	"a_m_m_afriamer_01",
	"csb_mp_agent14",
	"csb_agent",
	"u_m_m_aldinapoli",
	"ig_amandatownley",
	"ig_andreas",
	"u_m_y_antonb",
	"csb_anita",
	"cs_andreas",
	"ig_ashley",
	"s_m_m_autoshop_01",
	"ig_money",
	"g_m_y_ballaeast_01",
	"g_m_y_ballaorig_01",
	"g_f_y_ballas_01",
	"u_m_y_babyd",
	"ig_barry",
	"s_m_y_barman_01",
	"u_m_y_baygor",
	"a_f_y_beach_01",
	"a_f_y_bevhills_02",
	"a_f_y_bevhills_01",
	"u_m_y_burgerdrug_01",
	"a_m_m_business_01",
	"a_f_m_business_02",
	"a_m_y_business_02",
	"ig_car3guy1",
	"ig_chef2",
	"g_m_m_chigoon_02",
	"g_m_m_chigoon_01",
	"ig_claypain",
	"ig_clay",
	"a_f_m_eastsa_01"
}



---------------------------------------------------------------------------------------------------------------------------------------------------
--------- THREADS
---------------------------------------------------------------------------------------------------------------------------------------------------

-- print(GetWeaponDamageModifier(GetHashKey("WEAPON_PISTOL_MK2")))
-- print(GetCurrentPedWeaponEntityIndex(ped2))
-- print(GetHashKey("WEAPON_PISTOL_MK2"))
--N_0x4757f00bc6323cfe(teste2,1.0)
-- print(GetWeaponDamageModifier(GetHashKey("WEAPON_PISTOL_MK2")))

-- ARMAZEM
Citizen.CreateThread(function()

    while true do
        local idle = 1000 
        for k,v in pairs(cfg.geral) do
            local ped = PlayerPedId()
            local coords = GetEntityCoords(ped)
            local distance = #(vector3(coords.x,coords.y,coords.z) - vector3(v.armazem[1],v.armazem[2],v.armazem[3]))
            
                
            if distance <= 5.0 then
                idle = 1
                if distance <= 3.0 then
                    idle = 1
                    DrawText3D(v.armazem[1],v.armazem[2],v.armazem[3], "[~b~ARMAZEM~w~] Aperte ~g~ G ~w~ para guardar.")
                    if distance <= 2.0 and IsControlJustPressed(0, 47) and vSERVER.checkPerm(v.permissao) then
                        
                        vSERVER.guardarItensArmazem(k)
                    end
                end
            end
        end
    Citizen.Wait(idle)
    end
end)

-- ROTAS
Citizen.CreateThread(function()

    while true do
        local idle = 1000 
        for k,v in pairs(cfg.geral) do
        local ped = PlayerPedId()
        local coords = GetEntityCoords(ped)
        local distance = #(vector3(coords.x,coords.y,coords.z) - vector3(v.inicio[1],v.inicio[2],v.inicio[3]))

            if not farmando then
                if distance <= 5.0 then
                    idle = 1
                    typefarm = k
                    DrawMarker(27,v.inicio[1],v.inicio[2],v.inicio[3]-0.97,0,0,0,0,0,0,0.7,0.7,0.3,0,255,249,249,0,0,0,1)
                    if distance <= 3.0 then
                        idle = 1
                        DrawText3D(v.inicio[1],v.inicio[2],v.inicio[3], "~w~[~r~"..k.."~w~]<br>"..cfg.lang['bliptxt'].."")
                        if distance <= 2.0 and IsControlJustPressed(0, 38) and vSERVER.checkPerm(v.permissao) then
                            fac = v.permissao
                            facId = v.idFac
                            meuXp = vSERVER.getXp()
                            
                            SendNUIMessage({
                                tipo="farm",
                                show = true,
                                rotaNome = k,
                                xp = meuXp        
                            })    
                            SetNuiFocus(true,true)                                                
                            --farmando = true
                            --criandoblip(cfg.geral[typefarm].rotas[1][1],cfg.geral[typefarm].rotas[1][2],cfg.geral[typefarm].rotas[1][3])                                                   
                        end
                    end
                end
            end
        end
    Citizen.Wait(idle)
    end
end)

Citizen.CreateThread(function()

    while true do
            local idle = 1000
            local ped = PlayerPedId()
            local coords = GetEntityCoords(ped)
            if GetEntityHealth(ped) <= 101 then
                encerrar()
            end

                if farmando then
                    local distance = #(vector3(coords.x,coords.y,coords.z) - vector3(rotas[pos].x,rotas[pos].y,rotas[pos].z))
                    if nivel >= 2 and pedSpawn then
                        local mHash = GetHashKey(pedHashs[math.random(#pedHashs)])
                        local mHash2 = GetHashKey(pedHashs[math.random(#pedHashs)])
                     
                        RequestModel(mHash)
                        while not HasModelLoaded(mHash) do
                            RequestModel(mHash)
                            Citizen.Wait(10)
                        end
                       
                        retval = false
                        
                        while not retval do
                             x = rotas[pos].x + math.random(-3, 3)
                             y = rotas[pos].y + math.random(-3, 3)
                             retval, z  = GetGroundZFor_3dCoord(x,y,rotas[pos].z,false)
                            
                             Citizen.Wait(500)
                        end
                        
                        
                        inPed = CreatePed(4,mHash,x,y,z,240.91,true,false)
                        SetEntityInvincible(inPed,false)
                        -- FreezeEntityPosition(inPed,false)
                        
                        SetModelAsNoLongerNeeded(mHash) 
                        GiveWeaponToPed(inPed,GetHashKey(arma),200,true,true)

                        inPed4 = CreatePed(4,mHash2,x,y,z,240.91,true,false)
                        SetEntityInvincible(inPed4,false)
                        -- FreezeEntityPosition(inPed,false)
                        
                        SetModelAsNoLongerNeeded(mHash) 
                        GiveWeaponToPed(inPed,GetHashKey(arma),200,true,true)

                        SetModelAsNoLongerNeeded(mHash2) 
                        GiveWeaponToPed(inPed4,GetHashKey(arma),200,true,true)
          
                        
                        pedSpawn = false
                    end
                    if nivel >= 2 and distance <= 100.0 and pedFire then
                        -- TaskSetBlockingOfNonTemporaryEvents(inPed, true)
                        SetPedCanRagdoll(inPed)
                        SetPedCombatAttributes(inPed, 46, true)
                        SetEntityInvincible(inPed,false)
                        SetPedFleeAttributes(inPed, 0, true)
                        FreezeEntityPosition(inPed,false)
                        SetPedSuffersCriticalHits(inPed,false)
                        SetPedArmour(inPed, armadura)
                        SetPedAsEnemy(inPed, true)
                        SetPedRelationshipGroupHash(inPed, 'Methhouse')
                        -- SetPedRelationshipGroupHash(inPed, GetHashKey("HATES_PLAYER"))
                        -- SetRelationshipBetweenGroups(5, GetHashKey("Methhouse"), GetHashKey("PLAYER"))
                        SetPedCombatRange(inPed,2)
                        TaskCombatPed(inPed, GetPlayerPed(-1))
                        --SetRelationshipBetweenGroups(5, Grupo de hash1, Grupo de hash2)
                        SetPedAccuracy(inPed, ameaca)
                        SetPedDropsWeaponsWhenDead(inPed, false)
                        SetPedCombatMovement(inPed,movimento)

                        SetPedCanRagdoll(inPed4)
                        SetPedCombatAttributes(inPed4, 46, true)
                        SetEntityInvincible(inPed4,false)
                        SetPedFleeAttributes(inPed4, 0, true)
                        FreezeEntityPosition(inPed4,false)
                        SetPedSuffersCriticalHits(inPed4,false)
                        SetPedArmour(inPed4, armadura)
                        SetPedAsEnemy(inPed4, true)
                        SetPedRelationshipGroupHash(inPed4, 'Methhouse')
                        -- SetPedRelationshipGroupHash(inPed, GetHashKey("HATES_PLAYER"))
                        -- SetRelationshipBetweenGroups(5, GetHashKey("Methhouse"), GetHashKey("PLAYER"))
                        SetPedCombatRange(inPed4,2)
                        TaskCombatPed(inPed4, GetPlayerPed(-1))
                        --SetRelationshipBetweenGroups(5, Grupo de hash1, Grupo de hash2)
                        SetPedAccuracy(inPed4, ameaca)
                        SetPedDropsWeaponsWhenDead(inPed4, false)
                        SetPedCombatMovement(inPed4,movimento)
                        
                        --TaskWanderInArea(inPed, rotas[pos].x,rotas[pos].y,rotas[pos].z, 1 , 150,150)
                        -- SetBlockingOfNonTemporaryEvents(inPed,false)
                        --TaskShootAtEntity(inPed,ped,5000,GetHashKey("FIRING_PATTERN_FULL_AUTO")) -- forte
                        --TaskShootAtEntity(inPed,ped,5000,GetHashKey("FIRING_PATTERN_BURST_FIRE_DRIVEBY")) --medio
                        --TaskShootAtEntity(inPed,ped,5000,GetHashKey(ameaca)) -- parece facil
                        --TaskShootAtEntity(inPed,ped,5000,GetHashKey("FIRING_PATTERN_BURST_FIRE_PISTOL"))
                        pedFire = false
                    end
                    

                    if inPed then
                        
                    end

                    if distance <= 20.0 then
                        idle = 1
                        DrawMarker(21,rotas[pos].x,rotas[pos].y,rotas[pos].z-0.1,0,0,0,0,0,0,0.7,0.7,0.3,0,255,249,249,0,0,0,1)
                        if distance <= 3.0 then
                            idle = 1
                            DrawText3D(rotas[pos].x,rotas[pos].y,rotas[pos].z, cfg.lang['farmtxt'])
                            if distance <= 2.0 and IsControlJustPressed(0, 38) then
                                
                                if checkOnVehicle() then
                                            
                                            if cfg.animation == true then 
                                                vRP._playAnim(false,{"amb@medic@standing@tendtodead@idle_a","idle_a"},true)
                                            end

                                                SetTimeout(500,function()
                                                    TriggerEvent('cancelando',false)
                                                    ClearPedTasks(PlayerPedId())
                                                end)
                                                
                                                DeleteEntity(methpedtruck)
                                                DeleteEntity(methpedtruckdriver)
                                                DeleteEntity(methpedtruck2)
                                                DeleteEntity(methpedtruckdriver2)

                                                if blips then
                                                    RemoveBlip(blips)
                                                end
                                                DeleteEntity(inPed)
                                                DeleteEntity(inPed4)
                                                inPed = nil
                                                DeleteEntity(inPed2)
                                                DeleteEntity(inPed3)
                                                pedSpawn = true
                                                pedFire = true
                                                reforco = false
                                                checkFarm()
                                                cacado()
                                                
                                                
                                                

                                                if nivel == 3 then
                                                    pos = math.random(1,#rotas)
                                                else
                                                    if pos == #rotas then
                                                        pos = 1
                                                    else
                                                        pos = pos + 1                                
                                                    end
                                                end
                                                
                                                criandoblip(rotas[pos].x,rotas[pos].y,rotas[pos].z)
                                                --teste
                                               
                                                vSERVER.setXp(nivel,fac,facId)

                                                
                                                    --print("Aqui")
                                                    --RequestModel(GetHashKey(yosemite3))
                                                

                                               

                                end
                            end
                        end
                    end
                end
    Citizen.Wait(idle)
    end
end)

Citizen.CreateThread(function()
    while true do
    local idle = 1000
    if farmando then
        idle = 1
        drawTxt("~y~PRESSIONE ~r~F7 ~w~SE DESEJA FINALIZAR A ROTA ",4,0.270,0.905,0.45,255,255,255,200)
		drawTxt("VA ATÉ O DESTINO PARA COLETAR OS ~g~ITENS",4,0.270,0.93,0.45,255,255,255,200)
        if IsControlJustPressed(0, 168) then
            TriggerEvent('Notify','importante','Você cancelou a rota!',5000)
            encerrar()
        end
    end
        Citizen.Wait(idle)
    end
end)
-- Verifica se o ped foi morto por arma branca no nivel 2

Citizen.CreateThread(function()
    while true do
    local idle = 5000
        

        if farmando and nivel == 2 and inPed and not reforco then
            idle = 1000
            if GetEntityHealth(inPed) == 0 then 
                arm1, arm2 = GetCurrentPedWeapon(PlayerPedId()) 
                if arm2 ~= GetHashKey("WEAPON_KNIFE") or arm2 ~= GetHashKey("WEAPON_GOLFCLUB") or arm2 ~= GetHashKey("WEAPON_POOLCUE") or arm2 ~= GetHashKey("WEAPON_BAT") or  arm2 ~= GetHashKey("WEAPON_DAGGER")then
                    TriggerEvent('Notify','alerta','Você usou uma arma de fogo! em uma briga de facas!<BR> Reforços foram chamados!',5000)
                    reforco = true 
                    callReforco()
                end
            end
        end
        Citizen.Wait(idle)
    end
end)




function cacado()
        
        local ped = PlayerPedId()
        local idle = 5000
        loc = GetEntityCoords(PlayerPedId())
        local spawnRadius = 200                                                    
        local found, spawnPos, spawnHeading = GetClosestVehicleNodeWithHeading(loc.x + math.random(-spawnRadius, spawnRadius), loc.y + math.random(-spawnRadius, spawnRadius), loc.z, 0, 3, 0)
    
        Citizen.Wait(idle)
        if farmando and nivel == 3 then
            TriggerEvent('Notify','importante','Você esta sendo caçado',5000)
            RequestModel(0x3BAD4184) --a_m_m_rurmeth_01
            RequestModel(0x3D0A5EB1) --ig_russiandrunk
            RequestModel(0x3F789426) --a_f_y_rurmeth_01
            local ModelHash = 'LECTRO' -- Use Compile-time hashes to get the hash of this model
            if not IsModelInCdimage(ModelHash) then 
                return 
            end
            RequestModel(ModelHash) -- Request the model
            while not HasModelLoaded(ModelHash) do -- Waits for the model to load
                Wait(2)
            end
            
            --local Vehicle = CreateVehicle(ModelHash, -1496.04,1477.33,117.37,339.3 , true, false) -- Spawns a networked vehicle on your current coords
        
            methpedtruck = CreateVehicle(ModelHash, spawnPos, spawnHeading  , true, false)
            SetVehicleColours(methpedtruck, 2, 2)
            oke, Group = AddRelationshipGroup("Methhouse")
            methpedtruckdriver = CreatePedInsideVehicle(methpedtruck, 12, GetHashKey("a_m_m_rurmeth_01"), -1, true, false)
            
            --TaskVehicleGotoNavmesh(methpedtruckdriver, methpedtruck, 2474.4, 4950.79, 45.16, 200, 156, 5.0)
            SetPedRelationshipGroupHash(methpedtruckdriver, Group)
            SetEntityCanBeDamagedByRelationshipGroup(methpedtruckdriver, false, Group)
        
            GiveWeaponToPed(methpedtruckdriver, "WEAPON_PISTOL", 400, false, true) 
            SetPedCombatAttributes(methpedtruckdriver, 1, true)
            SetPedCombatAttributes(methpedtruckdriver, 2, true)
            SetPedCombatAttributes(methpedtruckdriver, 5, true)
        
            SetPedCombatAttributes(methpedtruckdriver, 16, true)
            SetPedFleeAttributes(methpedtruckdriver, 0, 0)
            SetPedPathAvoidFire(methpedtruckdriver, 1)
            SetPedAlertness(methpedtruckdriver,3)
            SetPedAccuracy(methpedtruckdriver, 15) 
            SetPedArmour(methpedtruckdriver, 90)
            SetPedCanRagdoll(methpedtruckdriver)
            TaskCombatPed(methpedtruckdriver, GetPlayerPed(-1), 0, 16)
            SetDriverAbility(methpedtruckdriver, 1.0)
            SetPedDropsWeaponsWhenDead(methpedtruckdriver, false)


            found, spawnPos, spawnHeading = GetClosestVehicleNodeWithHeading(loc.x + math.random(-spawnRadius, spawnRadius), loc.y + math.random(-spawnRadius, spawnRadius), loc.z, 0, 3, 0)
            methpedtruck2 = CreateVehicle(ModelHash, spawnPos, spawnHeading  , true, false)
            SetVehicleColours(methpedtruck2, 2, 2)
            oke, Group = AddRelationshipGroup("Methhouse")
            methpedtruckdriver2 = CreatePedInsideVehicle(methpedtruck2, 12, GetHashKey("a_m_m_rurmeth_01"), -1, true, false)
            
            --TaskVehicleGotoNavmesh(methpedtruckdriver, methpedtruck, 2474.4, 4950.79, 45.16, 200, 156, 5.0)
            SetPedRelationshipGroupHash(methpedtruckdriver2, Group)
            SetEntityCanBeDamagedByRelationshipGroup(methpedtruckdriver2, false, Group)
        
            GiveWeaponToPed(methpedtruckdriver2, "WEAPON_PISTOL", 400, false, true) 
            SetPedCombatAttributes(methpedtruckdriver2, 1, true)
            SetPedCombatAttributes(methpedtruckdriver2, 2, true)
            SetPedCombatAttributes(methpedtruckdriver2, 5, true)
        
            SetPedCombatAttributes(methpedtruckdriver2, 16, true)
            SetPedFleeAttributes(methpedtruckdriver2, 0, 0)
            SetPedPathAvoidFire(methpedtruckdriver2, 1)
            SetPedAlertness(methpedtruckdriver2,3)
            SetPedAccuracy(methpedtruckdriver2, 15) 
            SetPedArmour(methpedtruckdriver2, 90)
            SetPedCanRagdoll(methpedtruckdriver2)
            TaskCombatPed(methpedtruckdriver2, GetPlayerPed(-1), 0, 16)
            SetDriverAbility(methpedtruckdriver2, 1.0)
            SetPedDropsWeaponsWhenDead(methpedtruckdriver2, false)
        end
        
    end

function callReforco()
  
        local mHash2 = GetHashKey(pedHashs[math.random(#pedHashs)])
        local mHash3 = GetHashKey(pedHashs[math.random(#pedHashs)])

        RequestModel(mHash2)
        while not HasModelLoaded(mHash2) do
            RequestModel(mHash2)
            Citizen.Wait(10)
        end
        RequestModel(mHash3)
        while not HasModelLoaded(mHash3) do
            RequestModel(mHash3)
            Citizen.Wait(10)
        end
        retval = false
                        
        while not retval do
             x = rotas[pos].x + math.random(-15, 15)
             y = rotas[pos].y + math.random(-15, 15)
             retval, z  = GetGroundZFor_3dCoord(x,y,rotas[pos].z + 1000,false)
            
             Citizen.Wait(500)
        end

        
        inPed2 = CreatePed(4,mHash2,x , y ,z,240.91,true,false)
        SetModelAsNoLongerNeeded(mHash2) 
        GiveWeaponToPed(inPed2,GetHashKey("WEAPON_PISTOL"),200,true,true)
        TaskSetBlockingOfNonTemporaryEvents(inPed, true)
        SetPedCanRagdoll(inPed2)
        SetPedCombatAttributes(inPed2, 46, true)
        SetEntityInvincible(inPed2,false)
        SetPedFleeAttributes(inPed2, 0, true)
        FreezeEntityPosition(inPed,false)
        SetPedSuffersCriticalHits(inPed,false)
        SetPedArmour(inPed2, 50)
        SetPedAsEnemy(inPed2, true)
        SetPedRelationshipGroupHash(inPed2, 'Methhouse')
        SetPedCombatRange(inPed2,2)
        TaskCombatPed(inPed2, GetPlayerPed(-1))
        SetPedAccuracy(inPed2, 10)
        SetPedDropsWeaponsWhenDead(inPed2, false)
        SetPedCombatMovement(inPed2,movimento)

        Wait(2000)
        retval = false
                        
        while not retval do
             x = rotas[pos].x + math.random(-15, 15)
             y = rotas[pos].y + math.random(-15, 15)
             retval, z  = GetGroundZFor_3dCoord(x,y,rotas[pos].z + 1000,false)
            
             Citizen.Wait(500)
        end

        inPed3 = CreatePed(4,mHash3,x , y ,z,240.91,true,false)
        SetModelAsNoLongerNeeded(mHash3) 
        GiveWeaponToPed(inPed3,GetHashKey("WEAPON_PISTOL"),200,true,true)
        TaskSetBlockingOfNonTemporaryEvents(inPed, true)
        SetPedCanRagdoll(inPed3)
        SetPedCombatAttributes(inPed3, 46, true)
        SetEntityInvincible(inPed3,false)
        SetPedFleeAttributes(inPed3, 0, true)
        FreezeEntityPosition(inPed3,false)
        SetPedSuffersCriticalHits(inPed3,false)
        SetPedArmour(inPed3, 50)
        SetPedAsEnemy(inPed3, true)
        SetPedRelationshipGroupHash(inPed3, 'Methhouse')
        SetPedCombatRange(inPed3,2)
        TaskCombatPed(inPed3, GetPlayerPed(-1))
        SetPedAccuracy(inPed3, 10)
        SetPedDropsWeaponsWhenDead(inPed3, false)
        SetPedCombatMovement(inPed3,movimento)

end


---------------------------------------------------------------------------------------------------------------------------------------------------
--------- FUNCTIONS
---------------------------------------------------------------------------------------------------------------------------------------------------

function checkFarm()
    local msg = ""

    if cfg.geral[typefarm].nome == "Rota Munição" then
        local posi = math.random(1,#cfg.geral[typefarm].itens)
        local amount = math.random(cfg.geral[typefarm].itens[posi].min,cfg.geral[typefarm].itens[posi].max)
        vSERVER.giveFarm(cfg.geral[typefarm].itens[posi].item,amount)
        Wait(1000)
        posi = math.random(1,#cfg.geral[typefarm].itens)
        local posi = math.random(1,#cfg.geral[typefarm].itens)
        local amount = math.random(cfg.geral[typefarm].itens[posi].min,cfg.geral[typefarm].itens[posi].max)
        vSERVER.giveFarm(cfg.geral[typefarm].itens[posi].item,amount)
    else
        for k,v in pairs(cfg.geral[typefarm].itens) do

            local itens = v.item
            local amount = math.random(v.min,v.max)
            Wait(1000)
            if vSERVER.giveFarm(itens,amount) then
                msg = msg.. "Item <b>"..itens.."</b> quantidade <b>"..amount.."x</b><br>"
            else
                msg = msg.. "<b>Inventário CHEIO</b><br>"
            end
        end
    end

    TriggerEvent('Notify','importante',msg,5000)
    if nivel == 2 then
        local sorte = math.random(0, 100)
        for k,v in pairs(cfg.geral[typefarm].itens2) do
            if sorte <= v.chance then
                local itens = v.item
                local amount = math.random(v.min,v.max)
                Wait(800)
                vSERVER.giveFarm(itens,amount) 
            end
        end

    end

end

function checkOnVehicle()

    local ped = PlayerPedId()
    if cfg.invehicle then
        return true
    else
        if IsPedInAnyVehicle(ped) then
            TriggerEvent('Notify','importante','Saia do veículo para coletar!',5000)
            return false
        else
            return true
        end
    end
end

function drawTxt(text,font,x,y,scale,r,g,b,a)
	SetTextFont(font)
	SetTextScale(scale,scale)
	SetTextColour(r,g,b,a)
	SetTextOutline()
	SetTextCentre(1)
	SetTextEntry("STRING")
	AddTextComponentString(text)
	DrawText(x,y)
end

function DrawText3D(x, y, z, text)
	local onScreen,_x,_y = World3dToScreen2d(x,y,z)
	SetTextFont(4)
	SetTextScale(0.50,0.50)
	SetTextColour(255,255,255,150)
	SetTextEntry("STRING")
	SetTextCentre(1)
	AddTextComponentString(text)
	DrawText(_x,_y)
end

function criandoblip(x,y,z)
	blips = AddBlipForCoord(x,y,z)
	SetBlipSprite(blips,1)
	SetBlipColour(blips,5)
	SetBlipScale(blips,0.4)
	SetBlipAsShortRange(blips,false)
	SetBlipRoute(blips,true)
	BeginTextCommandSetBlipName("STRING")
	AddTextComponentString("Destino")
	EndTextCommandSetBlipName(blips)
end

function encerrar()
    RemoveBlip(blips)
    DeleteEntity(inPed)
    DeleteEntity(inPed4)
    pos = 1
    farmando = false
    pedSpawn = true
    pedFire = true
    reforco = false
    Wait(5000)
    
    DeleteEntity(inPed2)
    DeleteEntity(inPed3)
    DeleteEntity(methpedtruck)
    DeleteEntity(methpedtruckdriver)
    DeleteEntity(methpedtruck2)
    DeleteEntity(methpedtruckdriver2)
    inPed = nil
    methpedtruck = nil
    methpedtruckdriver = nil
end



------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- CALLBACKS
------------------------------------------------------------------------------
RegisterNUICallback("sair", function(data)
        SetNuiFocus(false,false)
end)

RegisterNUICallback("setarRota", function(data)
    nivel = data.nivel
    if nivel == 2 then
       ameaca = 10
       arma = "WEAPON_KNIFE"
       armadura = 50
       movimento = 3
    elseif nivel == 3 then
        ameaca =  15
        arma = "WEAPON_ASSAULTRIFLE_MK2"
        armadura = 80
        movimento = 3
    elseif nivel == 4 then
        ameaca =  30
        arma = "WEAPON_ASSAULTRIFLE_MK2"
        movimento = 3
    else
        ameaca =  10
        arma = "WEAPON_PISTOL"
    end
    AddRelationshipGroup('Methhouse')
end)

RegisterNUICallback("iniciarRotaNorte", function(data)
    rotas = vSERVER.getRota("norte")
    farmando = true
    
    if nivel == 3 then
        pos = math.random(1,#rotas)
        
    else
        pos = 1
    end
    criandoblip(rotas[pos].x,rotas[pos].y,rotas[pos].z) 

end)

RegisterNUICallback("iniciarRotaSul", function(data)
    rotas =  vSERVER.getRota("sul")
    farmando = true
    criandoblip(rotas[1].x,rotas[1].y,rotas[1].z) 
end)

RegisterNUICallback("comprar", function(data)
    meuXpLoja = vSERVER.getXpLoja()
    if meuXpLoja >= data.total then
        if data.tipo == "item" then
            if vSERVER.giveFarm(data.item,data.qtd) then
                meuXpLoja = meuXpLoja - data.total
                vSERVER.setXpLoja(data.total)
            else
                TriggerEvent('Notify','negado','Mochila cheia!',5000)
            end
        else
            vSERVER.giveCar(data)
            vSERVER.setXpLoja(data.total)
            TriggerEvent('Notify','negado','Carro adiconado na garagem!',5000)
        end
    --SetNuiFocus(false,false)
    end
end)



-- ALEX DA HORA CAMERAS DE SEGURANÇA
local inCamera = false
local camSelect = nil
local coords = nil
local configCam = {
    ["Armas1"] = {
        cameras = {
        	["1"] = { -1920.43,2056.89,142.83,243.17 },
            ["2"] = {-1911.86,2013.84,153.81,336.97}
        }
    },
    ["Armas2"] = {
        cameras = {
        	["1"] = { -1920.43,2056.89,142.83,130.1 },
        }
    },
    ["Police"] = {
        cameras = {
        	["1"] = { 128.28,-1025.44,43.4,200.39},
            ["2"] = { 260.26,-830.06,52.56,266.81},
            ["3"] = { 454.29,-1003.41,37.52,312.56},
            ["4"] = { 419.47,-960.94,34.69,268.76},
            ["5"] = { 489.07,-965.59,36.85,346.1},
            ["6"] = { -824.91,-1191.38,10.56,211.39},
        }
    }

}


local inCamera = false
local coordsC = nil
RegisterCommand('cameraSeg',function(source,args,rawCommand)
	local ped = PlayerPedId()
  
    local camSelect = nil
  
    local source = source
    local org = nil

    for k,v in pairs(configCam) do
       
        if vSERVER.checkPerm2(k) then
            org = k
        end
    end
    if not args[1] then
        TriggerEvent('Notify','importante','Informe o número da camera <br> Exemplo: /cameraSeg 1',6000)
    end
	if not IsPedInAnyVehicle(ped) then
		if inCamera then
			ClearTimecycleModifier()
			DestroyCam(camSelect,false)
			SetEntityInvincible(ped,false)
			--SetEntityVisible(ped,true,false)
			--SetEntityCoords(ped,coordsC,1,0,0,0)
			FreezeEntityPosition(ped,false)
			TriggerEvent("hudActived",true)
			RenderScriptCams(false,false,0,1,0)
			PlaySoundFrontend(-1,"HACKING_SUCCESS",false)

			inCamera = false
			camSelect = nil
		else
			if configCam[org].cameras[args[1]] then
				inCamera = true
				coordsC = GetEntityCoords(ped)
				--SetEntityInvincible(ped,true)
				--SetEntityVisible(ped,false,false)
				--SetEntityCoords(ped,configCam[org].cameras[args[1]][1],configCam[org].cameras[args[1]][2],configCam[org].cameras[args[1]][3],1,0,0,0)
				--FreezeEntityPosition(ped,true)
				TriggerEvent("hudActived",false)
				SetTimecycleModifier("heliGunCam")
				PlaySoundFrontend(-1,"HACKING_SUCCESS",false)
				camSelect = CreateCam("DEFAULT_SCRIPTED_CAMERA",true)
				SetCamCoord(camSelect,configCam[org].cameras[args[1]][1],configCam[org].cameras[args[1]][2],configCam[org].cameras[args[1]][3])
				SetCamRot(camSelect,-20.0,0.0,configCam[org].cameras[args[1]][4])
				RenderScriptCams(true,false,0,1,0)
			end
		end
	end
end)

------------------------------------------------------------------------------
-- CARREGAR NO OMBRO
--------------------------------------------------------------------------------
local carryingBackInProgress = false

RegisterCommand("carregar",function(source, args)
	if vSERVER.checkpermcarregar() then
		if not carryingBackInProgress then
			carryingBackInProgress = true
			local player = PlayerPedId()	
			lib = 'missfinale_c2mcs_1'
			anim1 = 'fin_c2_mcs_1_camman'
			lib2 = 'nm'
			anim2 = 'firemans_carry'
			distans = 0.15
			distans2 = 0.27
			height = 0.63
			spin = 0.0		
			length = 100000
			controlFlagMe = 49
			controlFlagTarget = 33
			animFlagTarget = 1
			local closestPlayer = GetClosestPlayer(3)
			target = GetPlayerServerId(closestPlayer)
			if closestPlayer ~= nil then
			--	print("triggering cmg2_animations:sync")
				TriggerServerEvent('cmg2_animations:sync', closestPlayer, lib,lib2, anim1, anim2, distans, distans2, height,target,length,spin,controlFlagMe,controlFlagTarget,animFlagTarget)
			else
			--	print("[Aviso] Nenhum jogador por perto")
			end
		else
			carryingBackInProgress = false
			ClearPedSecondaryTask(GetPlayerPed(-1))
			DetachEntity(GetPlayerPed(-1), true, false)
			local closestPlayer = GetClosestPlayer(3)
			target = GetPlayerServerId(closestPlayer)
			TriggerServerEvent("cmg2_animations:stop",target)
		end
	end
end,false)

RegisterNetEvent('cmg2_animations:syncTarget')
AddEventHandler('cmg2_animations:syncTarget', function(target, animationLib, animation2, distans, distans2, height, length,spin,controlFlag)
	local playerPed = GetPlayerPed(-1)
	local targetPed = GetPlayerPed(GetPlayerFromServerId(target))
	carryingBackInProgress = true
	print("triggered cmg2_animations:syncTarget")
	RequestAnimDict(animationLib)

	while not HasAnimDictLoaded(animationLib) do
		Citizen.Wait(10)
	end
	if spin == nil then spin = 180.0 end
	AttachEntityToEntity(GetPlayerPed(-1), targetPed, 0, distans2, distans, height, 0.5, 0.5, spin, false, false, false, false, 2, false)
	if controlFlag == nil then controlFlag = 0 end
	TaskPlayAnim(playerPed, animationLib, animation2, 8.0, -8.0, length, controlFlag, 0, false, false, false)
end)

RegisterNetEvent('cmg2_animations:syncMe')
AddEventHandler('cmg2_animations:syncMe', function(animationLib, animation,length,controlFlag,animFlag)
	local playerPed = GetPlayerPed(-1)
	print("triggered cmg2_animations:syncMe")
	RequestAnimDict(animationLib)

	while not HasAnimDictLoaded(animationLib) do
		Citizen.Wait(10)
	end
	Wait(500)
	if controlFlag == nil then controlFlag = 0 end
	TaskPlayAnim(playerPed, animationLib, animation, 8.0, -8.0, length, controlFlag, 0, false, false, false)

	Citizen.Wait(length)
end)

RegisterNetEvent('cmg2_animations:cl_stop')
AddEventHandler('cmg2_animations:cl_stop', function()
	carryingBackInProgress = false
	ClearPedSecondaryTask(GetPlayerPed(-1))
	DetachEntity(GetPlayerPed(-1), true, false)
end)

function GetPlayers()
    local players = {}

    for i = 0, 255 do
        if NetworkIsPlayerActive(i) then
            table.insert(players, i)
        end
    end

    return players
end

function GetClosestPlayer(radius)
    local players = GetPlayers()
    local closestDistance = -1
    local closestPlayer = -1
    local ply = GetPlayerPed(-1)
    local plyCoords = GetEntityCoords(ply, 0)

    for index,value in ipairs(players) do
        local target = GetPlayerPed(value)
        if(target ~= ply) then
            local targetCoords = GetEntityCoords(GetPlayerPed(value), 0)
            local distance = GetDistanceBetweenCoords(targetCoords['x'], targetCoords['y'], targetCoords['z'], plyCoords['x'], plyCoords['y'], plyCoords['z'], true)
            if(closestDistance == -1 or closestDistance > distance) then
                closestPlayer = value
                closestDistance = distance
            end
        end
    end
--	print("jogador mais próximo é dist: " .. tostring(closestDistance))
	if closestDistance <= radius then
		return closestPlayer
	else
		return nil
	end
end

------------------------------------------------------------------------------
-- CAVALINHO
--------------------------------------------------------------------------------
local piggyBackInProgress = false

RegisterCommand("cavalinho",function(source, args)
if src.checkpermcarregar() then
	if not piggyBackInProgress then
		piggyBackInProgress = true
		local player = PlayerPedId()	
		lib = 'anim@arena@celeb@flat@paired@no_props@'
		anim1 = 'piggyback_c_player_a'
		anim2 = 'piggyback_c_player_b'
		distans = -0.07 
		distans2 = 0.0
		height = 0.45
		spin = 0.0		
		length = 100000
		controlFlagMe = 49
		controlFlagTarget = 33
		animFlagTarget = 1
		local closestPlayer = GetClosestPlayer(3)
		target = GetPlayerServerId(closestPlayer)
		if closestPlayer ~= nil then
			-----print("triggering cmg2_animations:sync")
			TriggerServerEvent('cmg2_animations:sync', closestPlayer, lib, anim1, anim2, distans, distans2, height,target,length,spin,controlFlagMe,controlFlagTarget,animFlagTarget)
		else
			-----print("[CMG Anim] No player nearby")
		end
	else
		piggyBackInProgress = false
		ClearPedSecondaryTask(GetPlayerPed(-1))
		DetachEntity(GetPlayerPed(-1), true, false)
		local closestPlayer = GetClosestPlayer(3)
		target = GetPlayerServerId(closestPlayer)
		TriggerServerEvent("cmg2_animations:stop",target)
	end
end
end,false)

RegisterNetEvent('cmg2_animations:syncTarget')
AddEventHandler('cmg2_animations:syncTarget', function(target, animationLib, animation2, distans, distans2, height, length,spin,controlFlag)
	local playerPed = GetPlayerPed(-1)
	local targetPed = GetPlayerPed(GetPlayerFromServerId(target))
	piggyBackInProgress = true
	-----print("triggered cmg2_animations:syncTarget")
	RequestAnimDict(animationLib)

	while not HasAnimDictLoaded(animationLib) do
		Citizen.Wait(10)
	end
	if spin == nil then spin = 180.0 end
	AttachEntityToEntity(GetPlayerPed(-1), targetPed, 0, distans2, distans, height, 0.5, 0.5, spin, false, false, false, false, 2, false)
	if controlFlag == nil then controlFlag = 0 end
	TaskPlayAnim(playerPed, animationLib, animation2, 8.0, -8.0, length, controlFlag, 0, false, false, false)
end)

RegisterNetEvent('cmg2_animations:syncMe')
AddEventHandler('cmg2_animations:syncMe', function(animationLib, animation,length,controlFlag,animFlag)
	local playerPed = GetPlayerPed(-1)
	-----print("triggered cmg2_animations:syncMe")
	RequestAnimDict(animationLib)

	while not HasAnimDictLoaded(animationLib) do
		Citizen.Wait(10)
	end
	Wait(500)
	if controlFlag == nil then controlFlag = 0 end
	TaskPlayAnim(playerPed, animationLib, animation, 8.0, -8.0, length, controlFlag, 0, false, false, false)

	Citizen.Wait(length)
end)

RegisterNetEvent('cmg2_animations:cl_stop')
AddEventHandler('cmg2_animations:cl_stop', function()
	piggyBackInProgress = false
	ClearPedSecondaryTask(GetPlayerPed(-1))
	DetachEntity(GetPlayerPed(-1), true, false)
end)

function GetPlayers()
    local players = {}

    for i = 0, 255 do
        if NetworkIsPlayerActive(i) then
            table.insert(players, i)
        end
    end

    return players
end

function GetClosestPlayer(radius)
    local players = GetPlayers()
    local closestDistance = -1
    local closestPlayer = -1
    local ply = GetPlayerPed(-1)
    local plyCoords = GetEntityCoords(ply, 0)

    for index,value in ipairs(players) do
        local target = GetPlayerPed(value)
        if(target ~= ply) then
            local targetCoords = GetEntityCoords(GetPlayerPed(value), 0)
            local distance = GetDistanceBetweenCoords(targetCoords['x'], targetCoords['y'], targetCoords['z'], plyCoords['x'], plyCoords['y'], plyCoords['z'], true)
            if(closestDistance == -1 or closestDistance > distance) then
                closestPlayer = value
                closestDistance = distance
            end
        end
    end
	-----print("closest player is dist: " .. tostring(closestDistance))
	if closestDistance <= radius then
		return closestPlayer
	else
		return nil
	end
end

function src.getNearestPlayer()
	local player = nil
	local players = GetNearestPlayers()
	local min = 5.0001
	for id,distance in pairs(players) do
		if distance < min then
			min = distance
			player = id
		end
	end
	return player
end

function GetNearestPlayers()
	local players = {}
	local pid = PlayerId()
	local coords = GetEntityCoords(PlayerPedId())

	for _,player in pairs(GetActivePlayers()) do
		if player ~= pid and NetworkIsPlayerConnected(player) then
			local distance = #(GetEntityCoords(GetPlayerPed(player)) - coords)
			if distance <= 2.0 then
				players[GetPlayerServerId(player)] = distance
			end
		end
	end
	return players
end


--------------------------------------------------------------------------------------
--
-- FUNCOES LOJA XP
---------------------------------------------------------------------------------------

RegisterCommand("lojaxp",function(source)
    meuXpLoja = vSERVER.getXpLoja()
    SendNUIMessage({
        tipo = "loja",
        show = true,
        rotaNome = k,
        xp = meuXpLoja,
        itens = cfg.itensLoja        
    }) 
    SetNuiFocus(true,true) 


end)



--------------------------------------------------------------------------------------
--
-- FUNÇÕES DE TESTE
---------------------------------------------------------------------------------------
RegisterCommand('voar',function(source,args,rawCommand)
    local ped = PlayerPedId()
    --SetPedGravity(ped,true)
    SetGravityLevel(PlayerPedId(), 1.0)
    SetGravityLevel(0.0)
end) 

Lua online compiler

Write, Run & Share Lua code online using OneCompiler's Lua online compiler for free. It's one of the robust, feature-rich online compilers for Lua language, running the latest Lua version 5.4. Getting started with the OneCompiler's Lua editor is easy and fast. The editor shows sample boilerplate code when you choose language as Lua and start coding.

Taking inputs (stdin)

OneCompiler's Lua online editor supports stdin and users can give inputs to programs using the STDIN textbox under the I/O tab. Following is a sample Lua program which takes name as input and prints hello message with your name.

name = io.read("*a")
print ("Hello ", name)

About Lua

Lua is a light weight embeddable scripting language which is built on top of C. It is used in almost all kind of applications like games, web applications, mobile applications, image processing etc. It's a very powerful, fast, easy to learn, open-source scripting language.

Syntax help

Variables

  • By default all the variables declared are global variables
  • If the variables are explicitly mentioned as local then they are local variables.
  • Lua is a dynamically typed language and hence only the values will have types not the variables.

Examples

-- global variables
a = 10

-- local variables

local x = 30
Value TypeDescription
numberRepresents numbers
stringRepresents text
nilDifferentiates values whether it has data or not
booleanValue can be either true or false
functionRepresents a sub-routine
userdataRepresents arbitary C data
threadRepresents independent threads of execution.
tableCan hold any value except nil

Loops

1. While:

While is also used to iterate a set of statements based on a condition. Usually while is preferred when number of iterations are not known in advance.

while(condition)
do
--code
end

2. Repeat-Until:

Repeat-Until is also used to iterate a set of statements based on a condition. It is very similar to Do-While, it is mostly used when you need to execute the statements atleast once.

repeat
   --code
until( condition )

3. For:

For loop is used to iterate a set of statements based on a condition.

for init,max/min value, increment
do
   --code
end

Functions

Function is a sub-routine which contains set of statements. Usually functions are written when multiple calls are required to same set of statements which increase re-usuability and modularity.

optional_function_scope function function_name( argument1, argument2, argument3........, argumentn)
--code
return params with comma seperated
end