content
stringlengths
5
1.05M
ESX = nil PlayerXP = {} local isTime = false local playingSound = false Citizen.CreateThread(function() while ESX == nil do TriggerEvent('esx:getSharedObject', function(obj) ESX = obj end) Wait(0) end Wait(500) TriggerServerEvent('cm-xpsystem:server:playerJoined') end) RegisterNetEvent('esx:playerLoaded') AddEventHandler('esx:playerLoaded', function() TriggerServerEvent('cm-xpsystem:server:playerJoined') logger.info('Player XP initialized') end) Citizen.CreateThread(function() while true do Wait(Config.RewardTime * 60 * 60 * 1000) isTime = true TriggerServerEvent('cm-xpsystem:server:addXP', isTime) local reward = Config.GlobalXP * Config.RewardXP ESX.ShowNotification('ฮ ฮฎฯฮตฯ‚ '..reward..'XP ฮดฯŽฯฮฟ ฮตฯ€ฮตฮนฮดฮฎ ฮตฮฏฯƒฮฑฮน 1 ฯŽฯฮฑ ฯƒฯ…ฮฝฮตฯ‡ฯŒฮผฮตฮฝฮท ฮผฮญฯƒฮฑ!'); isTime = false end end) RegisterNetEvent('cm-xpsystem:client:updatePlayer') AddEventHandler('cm-xpsystem:client:updatePlayer', function(playerXP) PlayerXP = playerXP SendNUIMessage({ action = 'updatePlayer', level = playerXP.level, xp = playerXP.xp }) end) RegisterNetEvent('cm-xpsystem:client:openShopMenu') AddEventHandler('cm-xpsystem:client:openShopMenu', function(items) SendNUIMessage({ action = 'setShop', items = items, level = PlayerXP.level, xp = PlayerXP.xp, }) SetNuiFocus(true, true) end) RegisterNetEvent('cm-xpsystem:client:updateGlobalXP') AddEventHandler('cm-xpsystem:client:updateGlobalXP', function(globalXP) Config.GlobalXP = globalXP logger.info('Global XP changed to '..globalXP) end) RegisterNetEvent('cm-xpsystem:client:openPromoMenu') AddEventHandler('cm-xpsystem:client:openPromoMenu', function(promos) SendNUIMessage({ action = 'setPromos', promos = promos }) SetNuiFocus(true, true) end) RegisterNUICallback('closeNUI', function() SetNuiFocus(false, false) end) RegisterNUICallback('buyItem', function(data) local name = data.name ESX.TriggerServerCallback('cm-xpsystem:server:buyItem', function(success) if (success) then print('works') else print('doesnt work') end end, name) end) Citizen.CreateThread(function() while true do Wait(5) drawTxt(0.32, 1.06, 0.3, 0.3, 0.402, "~y~GLOBAL XP:~s~ ~r~" .. Config.GlobalXP .. "%~s~", 255, 255, 255, 255, true) end end) function drawTxt(x,y ,width,height,scale, text, r,g,b,a, outline) SetTextFont(6) SetTextProportional(0) SetTextScale(scale, scale) SetTextColour(r, g, b, a) SetTextDropShadow(0, 0, 0, 0,255) SetTextEdge(1, 0, 0, 0, 255) SetTextDropShadow() if(outline)then SetTextOutline() end SetTextEntry("STRING") AddTextComponentString(text) DrawText(x - width/2, y - height/2 + 0.005) end
--์ตœ์ดˆ 1ํšŒ๋งŒ ๋ถˆ๋ฆฌ๋Š” ์ฝ”๋“œ๋Š” ์—ฌ๊ธฐ๋‹ค ์ ์–ด์ฃผ์„ธ์š”. function LNX_MATH_RAD(vm,stck) local value = vm:ARGU("๋ผ๋””์•ˆ","์ˆ˜",0) vm:returnValue(math.rad(value)) end function LNX_MATH_DEG(vm,stck) local value = vm:ARGU("๊ฐ๋„","์ˆ˜",0) vm:returnValue(math.deg(value)) end function LNX_MATH_SIN(vm,stck) local value = vm:ARGU("์‚ฌ์ธ","์ˆ˜",0) value = math.rad(value) vm:returnValue(math.sin(value)) end function LNX_MATH_COS(vm,stck) local value = vm:ARGU("์ฝ”์‚ฌ์ธ","์ˆ˜",0) value = math.rad(value) vm:returnValue(math.cos(value)) end function LNX_MATH_ASIN(vm,stck) local value = vm:ARGU("์•„ํฌ์‚ฌ์ธ","์ˆ˜",0) vm:returnValue(math.deg(math.asin(value))) end function LNX_MATH_ACOS(vm,stck) local value = vm:ARGU("์•„ํฌ์ฝ”์‚ฌ์ธ","์ˆ˜",0) vm:returnValue(math.deg(math.acos(value))) end function LNX_MATH_TAN(vm,stck) local value = vm:ARGU("ํƒ„์  ํŠธ","์ˆ˜",0) value = math.rad(value) vm:returnValue(math.tan(value)) end function LNX_MATH_ATAN(vm,stck) local value1 = vm:ARGU("์•„ํฌํƒ„์  ํŠธ","์ˆ˜1",0) local value2 = vm:ARGU("์•„ํฌํƒ„์  ํŠธ","์ˆ˜2",nil) if value2 then vm:returnValue(math.deg(math.atan2(value1,value2))) else vm:returnValue(math.deg(math.atan(value1))) end end function LNX_MATH_ABS(vm,stck) local value = vm:ARGU("์ ˆ๋Œ€๊ฐ’","์ˆ˜",0) vm:returnValue(math.abs(value)) end function LNX_MATH_LOG(vm,stck) local value = vm:ARGU("์ž์—ฐ๋กœ๊ทธ","์ˆ˜",0) vm:returnValue(math.log(value)) end function LNX_MATH_LOG10(vm,stck) local value = vm:ARGU("์ƒ์šฉ๋กœ๊ทธ","์ˆ˜",0) vm:returnValue(math.log10(value)) end function LNX_MATH_EXP(vm,stck) local value = vm:ARGU("์ดˆ์›”ํ•จ์ˆ˜","์ˆ˜",0) vm:returnValue(math.exp(value)) end function LNX_MATH_POW(vm,stck) local base = vm:ARGU("์ œ๊ณฑ์Šน","๋ฐ‘",0) local power = vm:ARGU("์ œ๊ณฑ์Šน","์Šน์ˆ˜",0) vm:returnValue(math.pow(base,power)) end function LNX_MATH_MAX(vm,stck) local value1 = vm:ARGU("์ตœ๋Œ€๊ฐ’","์ˆ˜1",0) local value2 = vm:ARGU("์ตœ๋Œ€๊ฐ’","์ˆ˜2",0) vm:returnValue(math.max(value1,value2)) end function LNX_MATH_MIN(vm,stck) local value1 = vm:ARGU("์ตœ์†Œ๊ฐ’","์ˆ˜1",0) local value2 = vm:ARGU("์ตœ์†Œ๊ฐ’","์ˆ˜2",0) vm:returnValue(math.min(value1,value2)) end function LNX_MATH_SQRT(vm,stck) local value = vm:ARGU("์ œ๊ณฑ๊ทผ","์ˆ˜",0) vm:returnValue(math.sqrt(value)) end function LNX_MATH_PI(vm,stck) -- [์›์ฃผ์œจ] ๋งคํฌ๋กœ๋Š” ์ธ์ž๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค. vm:returnValue(math.pi) end function LNX_MATH_E(vm,stck) -- [์ž์—ฐ์ƒ์ˆ˜] ๋งคํฌ๋กœ๋Š” ์ธ์ž๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค. vm:returnValue(math.exp(1)) end local function m(XVM) -- ํ•จ์ˆ˜ ์ •์˜์šฉ ๋ฃจ์•„ ํŒŒ์ผ์ด๋ฏ€๋กœ, -- ์•„๋ฌด ๊ฒƒ๋„ ํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค. end return m
rawset(_G,"include",require) local string_gsub=string.gsub local function split(str,sep) local rt= {} local size=1 string_gsub(str, '[^'..sep..']+', function(w) rt[size]=w size=size+1 end ) return rt end local using_namespace local function namespace(nsName) nsName=nsName or "" local names=split(nsName,".") local index=1 local lastNs=_G while(names[index]~=nil) do local name=names[index] if rawget(lastNs,name)==nil then local ns={} rawset(lastNs,name,ns) lastNs=ns else lastNs=rawget(lastNs,name) end index=index+1 end local newNs={} local old=_G local meta={__ns=lastNs,_G=old,__usingtable={}} meta.__index=function (self,key ) --ไผ˜ๅ…ˆไฟ่ฏๆœฌๅœฐๅ‘ฝๅ็ฉบ้—ดๅ˜้‡ๅ…ˆ่Žทๅ– local res=rawget(meta.__ns,key) if res then return res end --็„ถๅŽไฟ่ฏusing่ฟ‡็š„ๅ‘ฝๅ็ฉบ้—ด่Žทๅ– for _,using_table in old.pairs(meta.__usingtable) do --้˜ฒๆญขๆ— ้™้€’ๅฝ’่ฎฟ้—ฎ local res=rawget(using_table,key) if res then return res end end --็„ถๅŽๅ†ๆŸฅๆ‰พๅ…จๅฑ€ๅ˜้‡ return rawget(meta._G,key) end meta.__newindex=function(self,k,v) rawset(meta.__ns,k,v) end old.setmetatable(newNs,meta) newNs.using_namespace=function (nsName) using_namespace(newNs,nsName) end if lastNs.__nsName==nil then --ไธป่ฆ็”จไบŽๅบๅˆ—ๅŒ– lastNs.__nsName=nsName end if _VERSION =="Lua 5.1" then setfenv(2,newNs) else _G.__currentENV=newNs end return newNs end rawset(_G,"namespace",namespace) rawset(_G,"__nsName","_G") using_namespace=function(nsTable,nsName) local names=split(nsName,".") local index=1 local __lastNs=_G while(names[index]~=nil) do local name=names[index] if rawget(__lastNs,name)==nil then local ns={} rawset(__lastNs,name,ns) __lastNs=ns else __lastNs=rawget(__lastNs,name) end index=index+1 end local meta=getmetatable(nsTable) local using_table=meta.__usingtable using_table[nsName]=__lastNs end
local z=redis.call('zcount','bitcoin_address_balances_chainstate', 0, 99999999999999999999999) return z
local args = { ... } local target = table.remove(args, 1) target = shell.resolve(target) fs.mount(target, table.unpack(args))
function modifier_item_heart_cyclone_regen_on_take_damage(keys) local attacker = keys.attacker local ability = keys.ability local caster = keys.caster if attacker then if keys.Damage > 0 and ((attacker.IsControllableByAnyPlayer and attacker:IsControllableByAnyPlayer()) or attacker:IsBoss()) then if caster:IsRangedAttacker() then ability:ApplyDataDrivenModifier(caster, caster, "modifier_item_heart_cyclone_regen_cooldown", {duration=keys.CooldownRanged}) else ability:ApplyDataDrivenModifier(caster, caster, "modifier_item_heart_cyclone_regen_cooldown", {duration=keys.CooldownMelee}) end end end end function item_heart_cyclone_on_spell_start(keys) local caster = keys.caster local target = keys.target local ability = keys.ability if target then if target:GetTeamNumber() == caster:GetTeamNumber() then target:Purge(false, true, false, true, false) ability:ApplyDataDrivenModifier(caster, target, "modifier_item_heart_cyclone_active_regen", {}) else target:Purge(true, false, false, true, false) ability:ApplyDataDrivenModifier(caster, target, "modifier_item_heart_cyclone_active_damage", {}) end end end function modifier_item_heart_cyclone_active_damage_on_interval_think(keys) local caster = keys.caster local target = keys.target local ability = keys.ability ApplyDamage({ victim = target, attacker = caster, damage = target:GetMaxHealth()*keys.damage*0.001, damage_type = DAMAGE_TYPE_PURE, ability = ability, damage_flags = DOTA_DAMAGE_FLAG_BYPASSES_INVULNERABILITY + DOTA_DAMAGE_FLAG_NO_SPELL_AMPLIFICATION }) end
local headerfont = "Trebuchet24" local namefont = "Trebuchet24" local textfont = "Trebuchet18" local configpaneltall = 60 nzu.AddSpawnmenuTab("Save/Load", "DPanel", function(panel) --panel:SetSkin("nZombies Unlimited") --panel:SetBackgroundColor(Color(150,150,150)) local editedconfig local configpanel = panel:Add("DPanel") configpanel:SetWidth(400) --configpanel:SetBackgroundColor(Color(40,30,30)) configpanel:Dock(LEFT) local infopanel = panel:Add("DPanel") infopanel:Dock(FILL) infopanel:DockPadding(30,30,30,30) -- Top of the config scroll list, we find info about currently loaded configs or new configs local curpanel = configpanel:Add("DPanel") curpanel:Dock(TOP) curpanel:SetTall(70 + configpaneltall) curpanel.m_bDrawCorners = true curpanel:DockMargin(5,5,0,25) local curtop = curpanel:Add("Panel") curtop:Dock(TOP) curtop:SetTall(35) local curloaded = curtop:Add("DLabel") curloaded:SetText("Current Config:") curloaded:SetFont(headerfont) curloaded:DockMargin(5,5,5,5) curloaded:Dock(FILL) local unload = curtop:Add("DButton") unload:SetText("Unload") unload:SetVisible(false) unload:Dock(RIGHT) unload:SetWide(100) unload:DockMargin(5,5,10,5) local loadedpnl = curpanel:Add("DPanel") loadedpnl:Dock(TOP) loadedpnl:SetTall(configpaneltall) loadedpnl.Paint = function(s,w,h) surface.SetDrawColor(50,50,50,230) surface.DrawRect(0,0,w,h) end local loadedcfg = loadedpnl:Add("nzu_ConfigPanel") loadedcfg:Dock(FILL) loadedcfg:SetVisible(false) loadedcfg.m_bDrawCorners = false local noloaded = loadedpnl:Add("DLabel") noloaded:SetText("No Config currently loaded.") noloaded:Dock(FILL) noloaded:SetContentAlignment(5) noloaded:SetFont(textfont) local createbutton = curpanel:Add("DButton") createbutton:Dock(FILL) createbutton:SetText("Create new Config ...") createbutton:DockMargin(10,7,10,7) local function updateloadedconfig(s,config) editedconfig = config if config then loadedcfg:SetConfig(config) loadedcfg:SetVisible(true) noloaded:SetVisible(false) createbutton:SetText("Create new editable copy ...") unload:SetVisible(true) else loadedcfg:SetVisible(false) noloaded:SetVisible(true) createbutton:SetText("Create new Config ...") unload:SetVisible(false) end end if nzu.CurrentConfig then updateloadedconfig(nil, nzu.CurrentConfig) end hook.Add("nzu_ConfigLoaded", curpanel, updateloadedconfig) local installed = configpanel:Add("DLabel") installed:SetText("Installed Configs:") installed:SetFont(headerfont) installed:DockMargin(10,5,5,5) installed:Dock(TOP) local configlist = configpanel:Add("nzu_ConfigList") configlist:Dock(FILL) configlist:DockMargin(5,0,0,5) configlist:SetPaintBackground(true) configlist:SetSelectable(true) configlist:LoadConfigs() local img = infopanel:Add("DImage") img:SetImage("vgui/black.png") img:Dock(TOP) img:DockMargin(0,0,0,15) function img:PerformLayout() local w = self:GetWide() self:SetTall(w/16 * 9) end local img_but = img:Add("DButton") img_but:Dock(FILL) img_but:SetText("") img_but:SetVisible(false) local editpanel = infopanel:Add("Panel") editpanel:Dock(FILL) local addonarea = editpanel:Add("Panel") addonarea:DockMargin(15,0,0,0) addonarea:Dock(RIGHT) addonarea:SetWide(200) wid = addonarea:Add("Panel") wid:DockMargin(0,0,0,0) wid:Dock(TOP) local widheader = wid:Add("DLabel") widheader:SetText("Config Workshop ID") widheader:SetFont(headerfont) widheader:Dock(FILL) local widinfo = wid:Add("DImage") widinfo:SetImage("icon16/information.png") widinfo:Dock(RIGHT) widinfo:DockMargin(0,5,5,5) function widinfo:PerformLayout() local t = self:GetTall() self:SetWide(t) end widinfo:SetTooltip("Fill this field with the numeric ID of this Config's Workshop addon after it has been uploaded.\nThis will allow users to view your Config's Workshop page from in-game.") widinfo:SetMouseInputEnabled(true) local widentry = addonarea:Add("DTextEntry") widentry:SetPlaceholderText("123456789") widentry:SetPlaceholderColor(Color(75,75,75)) widentry:SetFont(namefont) widentry:SetTall(35) widentry:Dock(TOP) widentry:SetNumeric(true) local addoncontrol = addonarea:Add("Panel") addoncontrol:Dock(TOP) addoncontrol:DockMargin(0,15,0,0) local addonscroll = addonarea:Add("DScrollPanel") addonscroll:Dock(FILL) addonscroll:SetPaintBackground(true) --addonscroll:SetBackgroundColor(Color(50,50,50)) local addonlist = addonscroll:Add("DListLayout") addonlist:Dock(FILL) function addonlist:Refresh() self.Addons = {} for k,v in pairs(engine.GetAddons()) do if v.downloaded and v.wsid then local p = vgui.Create("Panel") p:DockPadding(2,2,2,2) local c = p:Add("DCheckBox") c:Dock(LEFT) c:DockMargin(0,0,5,0) c:SetChecked(selected and selected.RequiredAddons[v.wsid] or false) function c:PerformLayout() self:SetWide(self:GetTall()) end local l = p:Add("DLabel") l:SetText(v.title) l:SetTextColor(Color(200,200,200)) l:Dock(FILL) l:SetContentAlignment(4) addonlist:Add(p) p:Dock(TOP) p.CheckBox = c self.Addons[v.wsid] = {v.title, c} end end end addonlist:Refresh() local addons = addoncontrol:Add("DLabel") addons:SetText("Required Addons") addons:SetFont(headerfont) addons:Dock(FILL) --local namearea = editpanel:Add("Panel") --namearea:SetBackgroundColor(Color(50,255,100)) --namearea:Dock(TOP) local nameheader = editpanel:Add("Panel") nameheader:Dock(TOP) local nhh = nameheader:Add("DLabel") nhh:SetFont(headerfont) nhh:SetText("Config name") nhh:SizeToContents() nhh:Dock(LEFT) nhh:DockMargin(3,0,0,0) local mapname = nameheader:Add("DLabel") mapname:SetText("File: || Map: ") mapname:SetFont(textfont) mapname:Dock(FILL) mapname:DockMargin(10,0,0,0) mapname:SizeToContents() mapname:SetContentAlignment(1) local configname = editpanel:Add("DTextEntry") configname:Dock(TOP) configname:SetEnabled(true) configname:SetFont(namefont) configname:SetPlaceholderText("Config name...") configname:SetPlaceholderColor(Color(75,75,75)) configname:SetTall(35) local ap = editpanel:Add("Panel") ap:DockMargin(0,15,0,0) ap:Dock(TOP) local ab = ap:Add("DButton") ab:SetText("Set to current players") ab:Dock(RIGHT) ab:SizeToContents() local authorheader = ap:Add("DLabel") authorheader:DockMargin(3,0,0,0) authorheader:SetText("Author(s)") authorheader:SetFont(headerfont) authorheader:Dock(FILL) local authors = editpanel:Add("DTextEntry") authors:SetPlaceholderText("Author(s)...") authors:SetPlaceholderColor(Color(75,75,75)) authors:SetFont(namefont) authors:Dock(TOP) authors:SetTall(30) function ab:DoClick() local str = "" for k,v in pairs(player.GetHumans()) do str = str .. v:Nick()..", " end str = string.sub(str, 0, #str - 2) authors:SetText(str) end local descheader = editpanel:Add("DLabel") descheader:DockMargin(3,15,0,0) descheader:SetText("Description") descheader:SetFont(headerfont) descheader:Dock(TOP) local desc = editpanel:Add("DTextEntry") desc:SetMultiline(true) desc:SetFont(textfont) desc:SetPlaceholderText("Config Description...") desc:SetPlaceholderColor(Color(75,75,75)) desc:Dock(FILL) local playbutton = infopanel:Add("DButton") playbutton:Dock(BOTTOM) playbutton:SetText("Save and Play") playbutton:DockMargin(100,10,100,-20) playbutton:SetTall(40) playbutton:SetFont("Trebuchet24") playbutton:SetEnabled(nzu.IsAdmin(LocalPlayer())) local saveload = infopanel:Add("Panel") saveload:DockMargin(0,5,0,0) saveload:SetTall(30) saveload:Dock(BOTTOM) local saveload2 = infopanel:Add("Panel") saveload2:DockMargin(0,30,0,0) saveload2:SetTall(20) saveload2:Dock(BOTTOM) local reload = saveload:Add("DButton") reload:SetText("Reload last saved version") local save = saveload:Add("DButton") save:SetText("Save Config") playbutton.DoClick = function(s) local selectedconfig = loadedcfg:IsSelected() and loadedcfg:GetConfig() or configlist:GetSelectedConfig() if selectedconfig then if selectedconfig == editedconfig then save:DoClick() end Derma_Query("Do you wish to change gamemode to NZOMBIES UNLIMITED?", "Mode change confirmation", "Change gamemode", function() nzu.RequestPlayConfig(selectedconfig) end, "Cancel"):SetSkin("nZombies Unlimited") end end function saveload:PerformLayout() local w = self:GetWide()/2 + 15 reload:StretchToParent(0,0,w,0) save:StretchToParent(w,0,0,0) end local delete = saveload2:Add("DButton") delete:Dock(LEFT) delete:SetText("Delete Config") delete:SetWide(150) local savemeta = saveload2:Add("DButton") savemeta:Dock(RIGHT) savemeta:SetText("Save Info") savemeta:SetWide(150) infopanel:SetZPos(2) infopanel:SetVisible(false) local noshow = panel:Add("DLabel") noshow:Dock(FILL) noshow:SetContentAlignment(5) noshow:SetFont(headerfont) noshow:SetText("<-- Click a Config to display.") local addonlist2_Scroll = addonarea:Add("DScrollPanel") addonlist2_Scroll:Dock(FILL) local addonlist2 = addonlist2_Scroll:Add("DListLayout") addonlist2:Dock(FILL) -- Control selecting configs local function doconfigclick(pnl) if not IsValid(pnl) or not pnl.Config then infopanel:SetVisible(false) infopanel.Config = nil return end infopanel:SetVisible(true) local cfg = pnl.Config infopanel.Config = cfg configname:SetText(cfg.Name) authors:SetText(cfg.Authors) desc:SetText(cfg.Description) mapname:SetText("File: " .. cfg.Codename .. " || Map: "..cfg.Map) widentry:SetText(cfg.WorkshopID or "") img:SetImage(nzu.GetConfigThumbnail(cfg) or "vgui/black.png") -- Edits and stuff if nzu.IsAdmin(LocalPlayer()) and cfg == editedconfig and (cfg.Type == "Local" or cfg.Type == "Unsaved") then addonscroll:SetVisible(true) addonlist2_Scroll:SetVisible(false) save:SetEnabled(true) reload:SetText("Reload last saved version") reload:SetEnabled(true) savemeta:SetEnabled(true) delete:SetEnabled(true) configname:SetEnabled(true) authors:SetEnabled(true) desc:SetEnabled(true) widentry:SetEnabled(true) ab:SetEnabled(true) playbutton:SetText("Save and Play") else addonscroll:SetVisible(false) addonlist2_Scroll:SetVisible(true) save:SetEnabled(false) reload:SetText(cfg == nzu.CurrentConfig and "Reload Config" or "Load Config") reload:SetEnabled(nzu.IsAdmin(LocalPlayer())) savemeta:SetEnabled(false) delete:SetEnabled(cfg.Type == "Local" and nzu.IsAdmin(LocalPlayer())) addonlist2:Clear() for k,v in pairs(cfg.RequiredAddons) do local lbl = addonlist2:Add("DLabelURL") lbl:SetText(v) lbl:SetURL("https://steamcommunity.com/sharedfiles/filedetails/?id="..k) lbl:SetTextColor(steamworks.ShouldMountAddon(k) and Color(0,255,0) or Color(255,0,0)) end configname:SetEnabled(false) authors:SetEnabled(false) desc:SetEnabled(false) widentry:SetEnabled(false) ab:SetEnabled(false) playbutton:SetText("Load and Play") end end configlist.OnConfigClicked = function(s,cfg,pnl) loadedcfg:SetSelected(loadedcfg:GetConfig() == cfg) doconfigclick(pnl) end -- Update through hook if the config updated is the currently viewed one hook.Add("nzu_ConfigInfoSaved", infopanel, function(self, config) if self.Config == config then doconfigclick(self) -- Kinda a fun way to make it update itself, since self.Config is the same end end) -- Create new config button createbutton:SetEnabled(nzu.IsAdmin(LocalPlayer())) function createbutton:DoClick() local frame = vgui.Create("DFrame", panel) --frame:SetSkin("nZombies Unlimited") frame:SetTitle("Enter Config Codename") frame:SetSize(400,130) frame:SetDeleteOnClose(true) frame:ShowCloseButton(false) frame:SetBackgroundBlur(true) frame:SetDrawOnTop(true) local t1 = frame:Add("DLabel") t1:Dock(TOP) t1:SetText("Enter Config Codename. Must be a valid folder name.") t1:SetContentAlignment(5) local errorval local function errorlight(s,w,h) if errorval then surface.SetDrawColor(255,0,0,errorval) local x2,y2 = s:GetSize() surface.DrawRect(-50, -50, x2+50, y2+50) errorval= errorval - FrameTime() * 100 if errorval <= 0 then errorval = nil end end end local entry = frame:Add("DTextEntry") entry:Dock(TOP) entry:SetPlaceholderText("Codename (Config folder name)...") entry.PaintOver = errorlight local t2 = frame:Add("DLabel") t2:Dock(TOP) t2:SetText("") t2:SetTextColor(Color(255,100,100)) t2:SetContentAlignment(5) t2.PaintOver = errorlight local buts = frame:Add("Panel") buts:Dock(BOTTOM) buts:SetTall(20) local save = buts:Add("DButton") save:Dock(LEFT) save:SetText("Confirm") save:SetWide(frame:GetWide()/2 - 10) local function doconfirm() local val = entry:GetValue() if not val or val == "" or string.match(val, "[^%w_%-]") then errorval = 255 t2:SetText("Invalid Codename") return end local result = nzu.ConfigExists(val, "Local") if result then errorval = 255 t2:SetText("Local Config by that Codename already exists.") return elseif result == false then t2:SetText("Getting Configs from Server - Try again in a moment ...") end editedconfig = nzu.CurrentConfig and table.Copy(nzu.CurrentConfig) or {} editedconfig.Codename = val editedconfig.Type = "Unsaved" editedconfig.Name = editedconfig.Name or val editedconfig.Map = game.GetMap() editedconfig.Authors = editedconfig.Authors or "" editedconfig.Description = editedconfig.Description or "" editedconfig.RequiredAddons = editedconfig.RequiredAddons or {} updateloadedconfig(nil, editedconfig) loadedcfg:DoClick() frame:Close() end save.DoClick = doconfirm entry.OnEnter = doconfirm local cancel = buts:Add("DButton") cancel:Dock(RIGHT) cancel:SetText("Cancel") cancel:SetWide(frame:GetWide()/2 - 10) cancel.DoClick = function() frame:Close() end frame:SetPos(panel:ScreenToLocal(ScrW()/2 - 200, ScrH()/2 + 65)) frame:MakePopup() frame:DoModal() entry:RequestFocus() end loadedcfg.DoClick = function(s) configlist:SelectConfig(s:GetConfig()) -- Update the selected list s:SetSelected(true) doconfigclick(s) end local function applyinfo() if editedconfig then editedconfig.Name = configname:GetValue() editedconfig.Description = desc:GetValue() editedconfig.Authors = authors:GetValue() editedconfig.WorkshopID = widentry:GetValue() editedconfig.RequiredAddons = {} for k,v in pairs(addonlist.Addons) do if v[2]:GetChecked() then editedconfig.RequiredAddons[k] = v[1] end end end end save.DoClick = function() if editedconfig and (editedconfig.Type == "Local" or editedconfig.Type == "Unsaved") then applyinfo() nzu.RequestSaveConfig(editedconfig) end end reload.DoClick = function() local selectedconfig = configlist:GetSelectedConfig() if selectedconfig then local txt = "Are you sure you want to load?" if nzu.CurrentConfig then txt = txt .. " This will reload the server." end Derma_Query(txt, "Config load confirmation", "Load the Config", function() nzu.RequestLoadConfig(selectedconfig) end, "Cancel" ):SetSkin("nZombies Unlimited") end end delete.DoClick = function() local selectedconfig = configlist:GetSelectedConfig() if selectedconfig then local txt = "Are you sure you want to delete this Config?" if selectedconfig == nzu.CurrentConfig then txt = txt .. " This will reload the server." end Derma_Query(txt, "Config deletion confirmation", "Delete the Config", function() nzu.RequestDeleteConfig(selectedconfig) end, "Cancel" ):SetSkin("nZombies Unlimited") end end savemeta.DoClick = function() if editedconfig and editedconfig.Type == "Local" then applyinfo() nzu.RequestSaveConfigInfo(editedconfig) end end unload.DoClick = function() Derma_Query("Are you sure you want to unload?\nThis will reload the server.", "Config load confirmation", "Unload", function() if editedconfig and editedconfig.Type == "Unsaved" then if editedconfig == configlist:GetSelectedConfig() then doconfigclick() end -- Reset info if it is the one shown updateloadedconfig() -- Reset return end nzu.RequestUnloadConfig() end, "Cancel" ):SetSkin("nZombies Unlimited") end end, "icon16/disk.png", "Save your Config or load another")
local rustboro_center = DoorSlot("rustboro", "center") local rustboro_center_hub = DoorSlotHub("rustboro", "center", rustboro_center) rustboro_center:setHubIcon(rustboro_center_hub) local rustboro_mart = DoorSlot("rustboro", "mart") local rustboro_mart_hub = DoorSlotHub("rustboro", "mart", rustboro_mart) rustboro_mart:setHubIcon(rustboro_mart_hub) local rustboro_gym = DoorSlot("rustboro", "gym") local rustboro_gym_hub = DoorSlotHub("rustboro", "gym", rustboro_gym) rustboro_gym:setHubIcon(rustboro_gym_hub) local rustboro_school = DoorSlot("rustboro", "school") local rustboro_school_hub = DoorSlotHub("rustboro", "school", rustboro_school) rustboro_school:setHubIcon(rustboro_school_hub) local rustboro_devon = DoorSlot("rustboro", "devon") local rustboro_devon_hub = DoorSlotHub("rustboro", "devon", rustboro_devon) rustboro_devon:setHubIcon(rustboro_devon_hub) local rustboro_house_nw = DoorSlot("rustboro", "house_nw") local rustboro_house_nw_hub = DoorSlotHub("rustboro", "house_nw", rustboro_house_nw) rustboro_house_nw:setHubIcon(rustboro_house_nw_hub) local rustboro_house_w = DoorSlot("rustboro", "house_w") local rustboro_house_w_hub = DoorSlotHub("rustboro", "house_w", rustboro_house_w) rustboro_house_w:setHubIcon(rustboro_house_w_hub) local rustboro_house_sw = DoorSlot("rustboro", "house_sw") local rustboro_house_sw_hub = DoorSlotHub("rustboro", "house_sw", rustboro_house_sw) rustboro_house_sw:setHubIcon(rustboro_house_sw_hub) local rustboro_house_ne = DoorSlot("rustboro", "house_ne") local rustboro_house_ne_hub = DoorSlotHub("rustboro", "house_ne", rustboro_house_ne) rustboro_house_ne:setHubIcon(rustboro_house_ne_hub) local rustboro_house_e = DoorSlot("rustboro", "house_e") local rustboro_house_e_hub = DoorSlotHub("rustboro", "house_e", rustboro_house_e) rustboro_house_e:setHubIcon(rustboro_house_e_hub) local rustboro_house_se = DoorSlot("rustboro", "house_se") local rustboro_house_se_hub = DoorSlotHub("rustboro", "house_se", rustboro_house_se) rustboro_house_se:setHubIcon(rustboro_house_se_hub)
--formspecs local function get_formspec_y(add, out) local dest = "Y destination: " .. add local cur = "Current Y postion: " .. out return "size[10,10]".. "image_button[0,6;4,4;handel_1.png;up; ;false;false;handel_2.png]".. "image_button[6,6;4,4;handel_1.png;down; ;false;false;handel_2.png]".. "label[1,1;"..minetest.formspec_escape(dest).."]".. "label[1,2.5;"..minetest.formspec_escape(cur).."]".. "tooltip[up;Increase]".. "tooltip[down;Decrease]" end local function get_formspec_z(add, out) local dest = "Z destination: " .. add local cur = "Current Z postion: " .. out return "size[10,10]".. "image_button[0,6;4,4;handel_1.png;right; ;false;false;handel_2.png]".. "image_button[6,6;4,4;handel_1.png;left; ;false;false;handel_2.png]".. "label[1,1;"..minetest.formspec_escape(dest).."]".. "label[1,2.5;"..minetest.formspec_escape(cur).."]".. "tooltip[right;Increase]".. "tooltip[left;Decrease]" end local function get_formspec_x(add, out) local dest = "X destination: " .. add local cur = "Current X postion: " .. out return "size[10,10]".. "image_button[0,6;4,4;handel_1.png;foward; ;false;false;handel_2.png]".. "image_button[6,6;4,4;handel_1.png;back; ;false;false;handel_2.png]".. "label[1,1;"..minetest.formspec_escape(dest).."]".. "label[1,2.5;"..minetest.formspec_escape(cur).."]".. "tooltip[foward;Increase]".. "tooltip[back;Decrease]" end local function get_formspec_w() return "size[10,10]".. --"button[1,3;5,1;go;Go]" "image_button_exit[3,3;4,4;lever_1.png;go; ;false;false;lever_2.png]" end local function get_formspec_r(set) local power = "Power Left: " .. set .. " out of 10" return "size[10,10]".. "label[1,1;"..minetest.formspec_escape(power).."]" end local function get_formspec_f(set) local factor = "Travel Factor: " .. set return "size[10,10]".. "label[1,1;"..minetest.formspec_escape(factor).."]".. "image_button[1,5;2,2;switch_1.png;one; ;false;false;switch_2.png]".. "image_button[2.5,5;2,2;switch_1.png;ten; ;false;false;switch_2.png]".. "image_button[4,5;2,2;switch_1.png;hundren; ;false;false;switch_2.png]".. "image_button[5.5,5;2,2;switch_1.png;thosand; ;false;false;switch_2.png]".. "tooltip[one;1]".. "tooltip[ten;10]".. "tooltip[hundren;100]".. "tooltip[thosand;1000]" end local function get_formspec_s() return "size[10,10]".. "field[1,9;8,1;locate;;type name here... ]".. "image_button[1,1;2,2;switch_1.png;pick; ;false;false;switch_2.png]".. "image_button[2.5,1;2,2;switch_1.png;heal; ;false;false;switch_2.png]".. "image_button[4,1;2,2;switch_1.png;axe; ;false;false;switch_2.png]".. "image_button[1,3;2,2;switch_1.png;antigrav; ;false;false;switch_2.png]".. "image_button[2.5,3;2,2;switch_1.png;food; ;false;false;switch_2.png]".. "image_button[4,3;2,2;switch_1.png;attack; ;false;false;switch_2.png]".. "image_button[6,1;4,4;handel_1.png;sonic; ;false;false;handel_2.png]".. "image_button_exit[0.5,5.5;3,3;dial_1.png;submit; ;false;false;dial_2.png]".. "image_button[3.5,5.5;3,3;dial_1.png;scan; ;false;false;dial_2.png]".. "tooltip[sonic;Create Sonic Screwdriver]".. "tooltip[heal;Heal Me]".. "tooltip[axe;Create a Axe]".. "tooltip[scan;Scan Named Player]".. "tooltip[submit;Locate Named Player]".. "tooltip[food;Create a Biscut]".. "tooltip[antigrav;Toggle Antigrav]".. "tooltip[attack;Activate Weapons]".. "tooltip[pick;Create a Pickaxe]" end local function get_formspec_c(set) local cur = set return "size[10,10]".. "label[1,1;Change Exterior Shell: ]".. "item_image[6,0.5;3,3;"..minetest.formspec_escape(cur).."]".. "button[1,3;3,3;old;Default]".. "button[1,4;3,3;pink;Pink]".. "button[1,5;3,3;blue;Blue]".. "button[1,6;3,3;yellow;Yellow]".. "button[1,7;3,3;stone;Stone]".. "button[5,3;3,3;empty;Invisible]".. "button[5,4;3,3;cool;Classic]".. "button[5,5;3,3;leave;Leaves]".. "button[5,6;3,3;soda;Soda]".. "button[5,7;3,3;funky;Funky]" end local function get_formspec_o() return "size[10,10]".. "image_button[1,1;2,2;dial_1.png;set_one; ;false;false;dial_2.png]".. "image_button[1,4;2,2;dial_1.png;set_two; ;false;false;dial_2.png]".. "image_button[1,7;2,2;dial_1.png;set_three; ;false;false;dial_2.png]".. "image_button_exit[4.5,2;2,2;switch_1.png;use_one; ;false;false;switch_2.png]".. "image_button_exit[6,2;2,2;switch_1.png;use_two; ;false;false;switch_2.png]".. "image_button_exit[7.5,2;2,2;switch_1.png;use_three; ;false;false;switch_2.png]".. "tooltip[set_one;Set Waypoint 1]".. "tooltip[use_one;Use Waypoint 1]".. "tooltip[set_two;Set Waypoint 2]".. "tooltip[use_two;Use Waypoint 2]".. "tooltip[set_three;Set Waypoint 3]".. "tooltip[use_three;Use Waypoint 3]" end local general_functions = function(pos, formname, fields, sender) local meta = minetest.get_meta(pos) local id = meta:get_string("id") local name = sender:get_player_name() local out_pos = minetest.deserialize(data:get_string(id.."out_pos")) local factor = data:get_int(id.."factor") local inv = sender:get_inventory() if fields.up then meta:set_string("formspec", get_formspec_y(data:get_int(id.."y_dest")+factor, out_pos.y)) data:set_int(id.."y_dest", data:get_int(id.."y_dest")+factor) end if fields.down then meta:set_string("formspec", get_formspec_y(data:get_int(id.."y_dest")-factor, out_pos.y)) data:set_int(id.."y_dest", data:get_int(id.."y_dest")-factor) end if fields.right then meta:set_string("formspec", get_formspec_z(data:get_int(id.."z_dest")+factor, out_pos.z)) data:set_int(id.."z_dest", data:get_int(id.."z_dest")+factor) end if fields.left then meta:set_string("formspec", get_formspec_z(data:get_int(id.."z_dest")-factor, out_pos.z)) data:set_int(id.."z_dest", data:get_int(id.."z_dest")-factor) end if fields.foward then meta:set_string("formspec", get_formspec_x(data:get_int(id.."x_dest")+factor, out_pos.x)) data:set_int(id.."x_dest", data:get_int(id.."x_dest")+factor) end if fields.back then meta:set_string("formspec", get_formspec_x(data:get_int(id.."x_dest")-factor, out_pos.x)) data:set_int(id.."x_dest", data:get_int(id.."x_dest")-factor) end if fields.one then meta:set_string("formspec", get_formspec_f(1)) data:set_int(id.."factor", 1) end if fields.ten then meta:set_string("formspec", get_formspec_f(10)) data:set_int(id.."factor", 10) end if fields.hundren then meta:set_string("formspec", get_formspec_f(100)) data:set_int(id.."factor", 100) end if fields.thosand then meta:set_string("formspec", get_formspec_f(1000)) data:set_int(id.."factor", 1000) end --extra functions if fields.submit then if data:get_int(id.."power") < 2 then minetest.chat_send_player(name, "You Need 2 Power") else local victim = minetest.get_player_by_name(fields.locate) if not victim then minetest.chat_send_player(name, fields.locate .. " not found") else local vpos = victim:get_pos() data:set_int(id.."x_dest", vpos.x) data:set_int(id.."y_dest", vpos.y+1) data:set_int(id.."z_dest", vpos.z) minetest.chat_send_player(name, "Player Located") data:set_int(id.."power", data:get_string(id.."power")-2) end end end if fields.sonic then if data:get_int(id.."power") < 5 then minetest.chat_send_player(name, "You Need 5 Power") else pos.y = pos.y+1 minetest.add_item(pos, "tardis_new:sonic") data:set_int(id.."power", data:get_string(id.."power")-5) end end if fields.heal then if data:get_int(id.."power") < 3 then minetest.chat_send_player(name, "You Need 3 Power") else sender:set_hp(40) data:set_int(id.."power", data:get_string(id.."power")-3) end end if fields.scan then if data:get_int(id.."power") < 1 then minetest.chat_send_player(name, "You Need 1 Power") else local victim = minetest.get_player_by_name(fields.locate) if not victim then minetest.chat_send_player(name, fields.locate .. " not found") else local item = victim:get_wielded_item() local item_name = item:get_name() if item:get_name() == "" then item_name = "nothing" end minetest.chat_send_player(name, fields.locate .. " is holding " .. item_name .. " and has " .. victim:get_hp()/2 .. " hearts") data:set_int(id.."power", data:get_string(id.."power")-1) end end end if fields.pick then if data:get_int(id.."power") < 5 then minetest.chat_send_player(name, "You Need 5 Power") else pos.y = pos.y+1 minetest.add_item(pos, "default:pick_diamond") data:set_int(id.."power", data:get_string(id.."power")-5) end end if fields.axe then if data:get_int(id.."power") < 5 then minetest.chat_send_player(name, "You Need 5 Power") else pos.y = pos.y+1 minetest.add_item(pos, "default:axe_diamond") data:set_int(id.."power", data:get_string(id.."power")-5) end end if fields.antigrav then if data:get_string(id.."grav") == "yes" then data:set_string(id.."grav", "no") minetest.chat_send_player(name, "Antigravs Disabled") else data:set_string(id.."grav", "yes") minetest.chat_send_player(name, "Antigravs Enabled") end end if fields.food then if data:get_int(id.."power") < 1 then minetest.chat_send_player(name, "You Need 1 Power") else pos.y = pos.y+1 minetest.add_item(pos, "tardis_new:biscut") data:set_int(id.."power", data:get_string(id.."power")-1) end end if fields.attack then if data:get_int(id.."power") < 1 then minetest.chat_send_player(name, "You Need 1 Power") else local objs = minetest.get_objects_inside_radius(out_pos, 20) if objs[1] == nil then minetest.chat_send_player(name, "No players in range of Tardis") else if objs[1]:get_player_name() ~= "" then objs[1]:set_hp(1) minetest.chat_send_player(name, objs[1]:get_player_name().." was attacked" ) data:set_int(id.."power", data:get_string(id.."power")-1) end end end end end local travel_to_location = function(pos, formname, fields, sender) local meta = minetest.get_meta(pos) local id = meta:get_string("id") local out_pos = minetest.deserialize(data:get_string(id.."out_pos")) local look = data:get_string(id.."look") local r_pos = minetest.deserialize(data:get_string(id.."r_pos")) local rmeta = minetest.get_meta(r_pos) local style = rmeta:get_string("style") local go_pos = { x = data:get_int(id.."x_dest"), y = data:get_int(id.."y_dest"), z = data:get_int(id.."z_dest") } local pmeta = sender:get_meta() local name = sender:get_player_name() if fields.go then if data:get_int(id.."power") == 0 then minetest.chat_send_player(name, "No Power Left!") else --power? if minetest.get_node(go_pos).name == "air" then if data:get_string(id.."grav") == "no" then local vpos = go_pos vpos.y = vpos.y-1 while minetest.get_node(vpos).name == "air" and minetest.get_node(go_pos).name ~= "ignore" do vpos.y = vpos.y-1 end go_pos.y = vpos.y+1 end else while minetest.get_node(go_pos).name ~= "air" and minetest.get_node(go_pos).name ~= "ignore" do go_pos.y = go_pos.y+1 end end if minetest.is_protected(go_pos, name) then minetest.chat_send_player(name, "You don't have access to this area!") else --protected? if r_pos.x+100 > go_pos.x and r_pos.x-100 < go_pos.x and r_pos.z+100 > go_pos.z and r_pos.z-100 < go_pos.z and r_pos.y+100 > go_pos.y and r_pos.y-100 < go_pos.y then minetest.chat_send_player(name, "Your Tardis does not want to land at this location") else --stay away from consle room! if 30900 > go_pos.x and -30900 < go_pos.x and 30900 > go_pos.z and -30900 < go_pos.z and 30900 > go_pos.z and -30900 < go_pos.z then --world limits minetest.swap_node(r_pos, {name = "tardis_new:rotor_active"..style }) pmeta:set_string("vortex", "yes") local effect = minetest.sound_play("tardis_sound", {pos = pos, max_hear_distance = 10}) minetest.after(8, function(effect) minetest.sound_stop(effect) minetest.swap_node(r_pos, {name = "tardis_new:rotor"..style }) --local ometa = minetest.get_meta(r_pos) --ometa:set_string("id", id) --ometa:set_string("formspec", get_formspec_r(data:get_int(id.."power"))) local otimer = minetest.get_node_timer(r_pos) otimer:start(15) pmeta:set_string("vortex", "no") end, effect) minetest.set_node(out_pos, {name = "air"}) out_pos = go_pos minetest.set_node(out_pos, {name=look}) out_pos.y = out_pos.y+1 minetest.set_node(out_pos, {name = "air"}) out_pos.y = out_pos.y-1 local ometa = minetest.get_meta(out_pos) ometa:set_string("id", id) data:set_string(id.."out_pos", minetest.serialize(out_pos)) data:set_int(id.."power", data:get_string(id.."power")-1) local timer = minetest.get_node_timer(out_pos) timer:start(0.2) else minetest.chat_send_player(name, "Your Tardis can not travel outside the world!") end end end end end end local change_look = function(pos, formname, fields, sender) local meta = minetest.get_meta(pos) local id = meta:get_string("id") local out_pos = minetest.deserialize(data:get_string(id.."out_pos")) if fields.blue then meta:set_string("formspec", get_formspec_c("tardis_new:tardis")) data:set_string(id.."look", "tardis_new:tardis") end if fields.yellow then meta:set_string("formspec", get_formspec_c("tardis_new:tardis_yellow")) data:set_string(id.."look", "tardis_new:tardis_yellow") end if fields.pink then meta:set_string("formspec", get_formspec_c("tardis_new:tardis_pink")) data:set_string(id.."look", "tardis_new:tardis_pink") end if fields.old then meta:set_string("formspec", get_formspec_c("tardis_new:tardis_old")) data:set_string(id.."look", "tardis_new:tardis_old") end if fields.stone then meta:set_string("formspec", get_formspec_c("tardis_new:tardis_stone")) data:set_string(id.."look", "tardis_new:tardis_stone") end if fields.empty then meta:set_string("formspec", get_formspec_c("tardis_new:tardis_empty")) data:set_string(id.."look", "tardis_new:tardis_empty") end if fields.cool then meta:set_string("formspec", get_formspec_c("tardis_new:tardis_cool")) data:set_string(id.."look", "tardis_new:tardis_cool") end if fields.leave then meta:set_string("formspec", get_formspec_c("tardis_new:tardis_leave")) data:set_string(id.."look", "tardis_new:tardis_leave") end if fields.soda then meta:set_string("formspec", get_formspec_c("tardis_new:tardis_soda")) data:set_string(id.."look", "tardis_new:tardis_soda") end if fields.funky then meta:set_string("formspec", get_formspec_c("tardis_new:tardis_funky")) data:set_string(id.."look", "tardis_new:tardis_funky") end end local waypoint = function(pos, formname, fields, sender) local meta = minetest.get_meta(pos) local id = meta:get_string("id") local out_pos = minetest.deserialize(data:get_string(id.."out_pos")) local way1 = minetest.deserialize(data:get_string(id.."way1")) local way2 = minetest.deserialize(data:get_string(id.."way2")) local way3 = minetest.deserialize(data:get_string(id.."way3")) if fields.set_one then data:set_string(id.."way1", minetest.serialize(out_pos)) local way1 = minetest.deserialize(data:get_string(id.."way1")) end if fields.use_one then data:set_int(id.."x_dest", way1.x) data:set_int(id.."y_dest", way1.y) data:set_int(id.."z_dest", way1.z) end if fields.set_two then data:set_string(id.."way2", minetest.serialize(out_pos)) local way2 = minetest.deserialize(data:get_string(id.."way2")) end if fields.use_two then data:set_int(id.."x_dest", way2.x) data:set_int(id.."y_dest", way2.y) data:set_int(id.."z_dest", way2.z) end if fields.set_three then data:set_string(id.."way3", minetest.serialize(out_pos)) local way3 = minetest.deserialize(data:get_string(id.."way3")) end if fields.use_three then data:set_int(id.."x_dest", way3.x) data:set_int(id.."y_dest", way3.y) data:set_int(id.."z_dest", way3.z) end end -------------------- --NODE DEFINITIONS-- -------------------- local function register_console_set(set, craftitem, side, ytexture, xtexture, ztexture, ftexture, stexture, wtexture, ctexture, otexture, rotortexture, altrotortexture, ltexture) minetest.register_node("tardis_new:consle_y"..set, { description = "Y-Axis Console Unit", tiles = {ytexture, ytexture, side, side, side, side}, groups = {cracky = 3}, after_place_node = function(pos, placer, itemstack, pointed_thing) local pmeta = placer:get_meta() local id = pmeta:get_string("id") local r_pos = minetest.deserialize(data:get_string(id.."r_pos")) if not r_pos then r_pos = placer:get_pos() end if r_pos.x+50 > pos.x and r_pos.x-50 < pos.x and r_pos.z+50 > pos.z and r_pos.z-50 < pos.z and r_pos.y+50 > pos.y and r_pos.y-50 < pos.y then local meta = minetest.get_meta(pos) local out_pos = minetest.deserialize(data:get_string(id.."out_pos")) meta:set_string("id", id) meta:set_string("formspec", get_formspec_y(0, out_pos.y)) else minetest.dig_node(pos) end end, on_rightclick = function(pos, node, clicker, itemstack) local meta = minetest.get_meta(pos) local id = meta:get_string("id") local out_pos = minetest.deserialize(data:get_string(id.."out_pos")) meta:set_string("id", id) meta:set_string("formspec", get_formspec_y(data:get_int(id.."y_dest"), out_pos.y)) end, on_receive_fields = general_functions }) minetest.register_node("tardis_new:consle_x"..set, { description = "X-Axis Console Unit", tiles = {xtexture, xtexture, side, side, side, side}, groups = {cracky = 3}, after_place_node = function(pos, placer, itemstack, pointed_thing) local pmeta = placer:get_meta() local id = pmeta:get_string("id") local r_pos = minetest.deserialize(data:get_string(id.."r_pos")) if not r_pos then r_pos = placer:get_pos() end if r_pos.x+50 > pos.x and r_pos.x-50 < pos.x and r_pos.z+50 > pos.z and r_pos.z-50 < pos.z and r_pos.y+50 > pos.y and r_pos.y-50 < pos.y then local meta = minetest.get_meta(pos) local out_pos = minetest.deserialize(data:get_string(id.."out_pos")) meta:set_string("id", id) meta:set_string("formspec", get_formspec_x(0, out_pos.x)) else minetest.dig_node(pos) end end, on_rightclick = function(pos, node, clicker, itemstack) local meta = minetest.get_meta(pos) local id = meta:get_string("id") local out_pos = minetest.deserialize(data:get_string(id.."out_pos")) meta:set_string("id", id) meta:set_string("formspec", get_formspec_x(data:get_int(id.."x_dest"), out_pos.x)) end, on_receive_fields = general_functions }) minetest.register_node("tardis_new:consle_z"..set, { description = "Z-Axis Console Unit", tiles = {ztexture, ztexture, side, side, side, side}, groups = {cracky = 3}, after_place_node = function(pos, placer, itemstack, pointed_thing) local pmeta = placer:get_meta() local id = pmeta:get_string("id") local r_pos = minetest.deserialize(data:get_string(id.."r_pos")) if not r_pos then r_pos = placer:get_pos() end if r_pos.x+50 > pos.x and r_pos.x-50 < pos.x and r_pos.z+50 > pos.z and r_pos.z-50 < pos.z and r_pos.y+50 > pos.y and r_pos.y-50 < pos.y then local meta = minetest.get_meta(pos) local out_pos = minetest.deserialize(data:get_string(id.."out_pos")) meta:set_string("id", id) meta:set_string("formspec", get_formspec_z(0, out_pos.z)) else minetest.dig_node(pos) end end, on_rightclick = function(pos, node, clicker, itemstack) local meta = minetest.get_meta(pos) local id = meta:get_string("id") local out_pos = minetest.deserialize(data:get_string(id.."out_pos")) meta:set_string("id", id) meta:set_string("formspec", get_formspec_z(data:get_int(id.."z_dest"), out_pos.z)) end, on_receive_fields = general_functions }) minetest.register_node("tardis_new:consle_f"..set, { description = "Travel Factor Console Unit", tiles = {ftexture, ftexture, side, side, side, side}, groups = {cracky = 3}, after_place_node = function(pos, placer, itemstack, pointed_thing) local pmeta = placer:get_meta() local id = pmeta:get_string("id") local r_pos = minetest.deserialize(data:get_string(id.."r_pos")) if not r_pos then r_pos = placer:get_pos() end if r_pos.x+50 > pos.x and r_pos.x-50 < pos.x and r_pos.z+50 > pos.z and r_pos.z-50 < pos.z and r_pos.y+50 > pos.y and r_pos.y-50 < pos.y then local meta = minetest.get_meta(pos) meta:set_string("id", id) meta:set_string("formspec", get_formspec_f(1)) else minetest.dig_node(pos) end end, on_rightclick = function(pos, node, clicker, itemstack) local meta = minetest.get_meta(pos) local id = meta:get_string("id") meta:set_string("id", id) meta:set_string("formspec", get_formspec_f(data:get_int(id.."factor"))) end, on_receive_fields = general_functions }) minetest.register_node("tardis_new:consle_s"..set, { description = "Functions Console Unit", tiles = {stexture, stexture, side, side, side, side}, groups = {cracky = 3}, after_place_node = function(pos, placer, itemstack, pointed_thing) local pmeta = placer:get_meta() local id = pmeta:get_string("id") local r_pos = minetest.deserialize(data:get_string(id.."r_pos")) if not r_pos then r_pos = placer:get_pos() end if r_pos.x+50 > pos.x and r_pos.x-50 < pos.x and r_pos.z+50 > pos.z and r_pos.z-50 < pos.z and r_pos.y+50 > pos.y and r_pos.y-50 < pos.y then local meta = minetest.get_meta(pos) local id = pmeta:get_string("id") meta:set_string("id", id) meta:set_string("formspec", get_formspec_s()) else minetest.dig_node(pos) end end, on_receive_fields = general_functions }) minetest.register_node("tardis_new:consle_go"..set, { description = "Warp Lever Console Unit", tiles = {wtexture, wtexture, side, side, side, side}, groups = {cracky = 3}, after_place_node = function(pos, placer, itemstack, pointed_thing) local pmeta = placer:get_meta() local id = pmeta:get_string("id") local r_pos = minetest.deserialize(data:get_string(id.."r_pos")) if not r_pos then r_pos = placer:get_pos() end if r_pos.x+50 > pos.x and r_pos.x-50 < pos.x and r_pos.z+50 > pos.z and r_pos.z-50 < pos.z and r_pos.y+50 > pos.y and r_pos.y-50 < pos.y then local meta = minetest.get_meta(pos) meta:set_string("id", id) meta:set_string("formspec", get_formspec_w()) else minetest.dig_node(pos) end end, on_receive_fields = travel_to_location }) minetest.register_node("tardis_new:consle_c"..set, { description = "Exterior Console Unit", tiles = {ctexture, ctexture, side, side, side, side}, groups = {cracky = 3}, after_place_node = function(pos, placer, itemstack, pointed_thing) local pmeta = placer:get_meta() local id = pmeta:get_string("id") local r_pos = minetest.deserialize(data:get_string(id.."r_pos")) if not r_pos then r_pos = placer:get_pos() end if r_pos.x+50 > pos.x and r_pos.x-50 < pos.x and r_pos.z+50 > pos.z and r_pos.z-50 < pos.z and r_pos.y+50 > pos.y and r_pos.y-50 < pos.y then local meta = minetest.get_meta(pos) meta:set_string("id", id) meta:set_string("formspec", get_formspec_c("tardis_new:tardis_old")) else minetest.dig_node(pos) end end, on_receive_fields = change_look }) minetest.register_node("tardis_new:consle_o"..set, { description = "Waypoint Console Unit", tiles = {otexture, otexture, side, side, side, side}, groups = {cracky = 3}, after_place_node = function(pos, placer, itemstack, pointed_thing) local pmeta = placer:get_meta() local id = pmeta:get_string("id") local r_pos = minetest.deserialize(data:get_string(id.."r_pos")) if not r_pos then r_pos = placer:get_pos() end if r_pos.x+50 > pos.x and r_pos.x-50 < pos.x and r_pos.z+50 > pos.z and r_pos.z-50 < pos.z and r_pos.y+50 > pos.y and r_pos.y-50 < pos.y then local meta = minetest.get_meta(pos) meta:set_string("id", id) meta:set_string("formspec", get_formspec_o()) else minetest.dig_node(pos) end end, on_receive_fields = waypoint }) minetest.register_node("tardis_new:rotor"..set, { description = "Time Rotor", tiles = {rotortexture}, drawtype = "mesh", mesh = "tardis_2.obj", selection_box = {type = "fixed", fixed = { { -0.5, -0.5, -0.5, 0.5, 1.5, 0.5 } }}, collision_box = {type = "fixed", fixed = { { -0.5, -0.5, -0.5, 0.5, 1.5, 0.5 } }}, light_source = 10, groups = {cracky = 1}, after_place_node = function(pos, placer, itemstack, pointed_thing) local pmeta = placer:get_meta() local id = pmeta:get_string("id") local r_pos = minetest.deserialize(data:get_string(id.."r_pos")) if not r_pos then r_pos = placer:get_pos() end if r_pos.x+50 > pos.x and r_pos.x-50 < pos.x and r_pos.z+50 > pos.z and r_pos.z-50 < pos.z and r_pos.y+50 > pos.y and r_pos.y-50 < pos.y then local meta = minetest.get_meta(pos) meta:set_string("id", id) meta:set_string("formspec", get_formspec_r(data:get_int(id.."power"))) meta:set_string("style", set) data:set_string(id.."r_pos", minetest.serialize(pos)) local timer = minetest.get_node_timer(pos) timer:start(15) else minetest.dig_node(pos) end end, on_rightclick = function(pos, node, clicker, itemstack) local meta = minetest.get_meta(pos) local id = meta:get_string("id") meta:set_string("formspec", get_formspec_r(data:get_int(id.."power"))) end, on_timer = function(pos) local meta = minetest.get_meta(pos) local id = meta:get_string("id") if data:get_int(id.."power") < 10 then data:set_int(id.."power", data:get_int(id.."power")+1) end meta:set_string("formspec", get_formspec_r(data:get_int(id.."power"))) if data:get_string(id.."r_pos") == minetest.serialize(pos) then return true else return false end end }) minetest.register_node("tardis_new:rotor_active"..set, { description = "Time Rotor (active)", tiles = { {name = altrotortexture, animation = {type = "vertical_frames", aspect_w = 64, aspect_h = 64, length = 1.5}} }, drawtype = "mesh", mesh = "tardis_2.obj", selection_box = {type = "fixed", fixed = { { -0.5, -0.5, -0.5, 0.5, 1.5, 0.5 } }}, collision_box = {type = "fixed", fixed = { { -0.5, -0.5, -0.5, 0.5, 1.5, 0.5 } }}, light_source = 12, groups = {not_in_creative_inventory = 1}, }) minetest.register_node("tardis_new:light"..set, { description = "Tardis Light", inventory_image = ltexture, drawtype = "signlike", paramtype = "light", sunlight_propagates = true, light_source = minetest.LIGHT_MAX, paramtype2 = "wallmounted", selection_box = { type = "wallmounted" }, tiles = {ltexture}, groups = {oddly_breakable_by_hand = 1} }) if craftitem == "" then return else minetest.register_craft({ output = "tardis_new:consle_y"..set, recipe = { {craftitem}, {"tardis_new:consle_y"} } }) minetest.register_craft({ output = "tardis_new:consle_x"..set, recipe = { {craftitem}, {"tardis_new:consle_x"} } }) minetest.register_craft({ output = "tardis_new:consle_z"..set, recipe = { {craftitem}, {"tardis_new:consle_z"} } }) minetest.register_craft({ output = "tardis_new:consle_c"..set, recipe = { {craftitem}, {"tardis_new:consle_c"} } }) minetest.register_craft({ output = "tardis_new:consle_go"..set, recipe = { {craftitem}, {"tardis_new:consle_go"} } }) minetest.register_craft({ output = "tardis_new:consle_f"..set, recipe = { {craftitem}, {"tardis_new:consle_f"} } }) minetest.register_craft({ output = "tardis_new:consle_o"..set, recipe = { {craftitem}, {"tardis_new:consle_o"} } }) minetest.register_craft({ output = "tardis_new:consle_s"..set, recipe = { {craftitem}, {"tardis_new:consle_s"} } }) minetest.register_craft({ output = "tardis_new:light"..set, recipe = { {craftitem}, {"tardis_new:light"} } }) minetest.register_craft({ output = "tardis_new:rotor"..set, recipe = { {craftitem}, {"tardis_new:rotor"} } }) end end register_console_set("", "", "tardis_side_1.png", "y_console_1.png", "x_console_1.png", "z_console_1.png", "f_console_1.png", "s_console_1.png", "w_console_1.png", "c_console_1.png", "o_console_1.png", "rotor_1.png", "alt_rotor_1.png", "tardis_light_1.png") register_console_set("_2", "group:wood", "tardis_side_2.png", "y_console_2.png", "x_console_2.png", "z_console_2.png", "f_console_2.png", "s_console_2.png", "w_console_2.png", "c_console_2.png", "o_console_2.png", "rotor_2.png", "alt_rotor_2.png", "tardis_light_2.png") register_console_set("_3", "default:silver_sand", "tardis_side_3.png", "y_console_3.png", "x_console_3.png", "z_console_3.png", "f_console_3.png", "s_console_3.png", "w_console_3.png", "c_console_3.png", "o_console_3.png", "rotor_3.png", "alt_rotor_3.png", "tardis_light_3.png")
-- disable header folding vim.g.vim_markdown_folding_disabled = 1 -- do not use conceal feature, provided by vim-pandoc-syntax vim.g.vim_markdown_conceal = 0 -- disable math tex conceal feature vim.g.tex_conceal = "" vim.g.vim_markdown_math = 1 -- support front matter vim.g.vim_markdown_frontmatter = 1 -- for YAML format
local access = ngx.shared.access local host = ngx.var.host or "unknow" local status = ngx.var.status local body_bytes_sent = ngx.var.body_bytes_sent local request_time = ngx.var.request_time local upstream_response_time = ngx.var.upstream_response_time or 0 local request_uri = ngx.var.request_uri or "/unknow" local timestamp = ngx.time() local expire_time = 70 local status_key = table.concat({host,"-",status,"-",timestamp}) local flow_key = table.concat({host,"-flow-",timestamp}) local req_time_key = table.concat({host,"-reqt-",timestamp}) local up_time_key = table.concat({host,"-upt-",timestamp}) local total_key = table.concat({host,"-total-",timestamp}) -- ๅŸŸๅๆ€ป่ฏทๆฑ‚ๆ•ฐ local n,e = access:incr(total_key,1) if not n then access:set(total_key, 1, expire_time) end -- ๅŸŸๅ็Šถๆ€็ ่ฏทๆฑ‚ๆ•ฐ local n,e = access:incr(status_key,1) if not n then access:set(status_key, 1, expire_time) end -- ๅŸŸๅๆต้‡ local n,e = access:incr(flow_key,body_bytes_sent) if not n then access:set(flow_key, body_bytes_sent, expire_time) end -- ๅŸŸๅ่ฏทๆฑ‚่€—ๆ—ถ local n,e = access:incr(req_time_key,request_time) if not n then access:set(req_time_key, request_time, expire_time) end -- ๅŸŸๅupstream่€—ๆ—ถ local n,e = access:incr(up_time_key,upstream_response_time) if not n then access:set(up_time_key, upstream_response_time, expire_time) end -- ่Žทๅ–ไธๅธฆๅ‚ๆ•ฐ็š„uri local m, err = ngx.re.match(request_uri, "(.*?)\\?") local request_without_args = m and m[1] or request_uri -- ๅญ˜ๅ‚จ็Šถๆ€็ ๅคงไบŽ400็š„url if tonumber(status) >= 400 then -- ๆ‹ผๆŽฅurl,็Šถๆ€็ ,ๅญ—่Š‚ๆ•ฐ็ญ‰ๅญ—ๆฎต local request_log_t = {} table.insert(request_log_t,host) table.insert(request_log_t,request_without_args) table.insert(request_log_t,status) local request_log = table.concat(request_log_t," ") -- ๆŠŠๆ‹ผๆŽฅ็š„ๅญ—ๆฎตๅ‚จๅญ˜ๅœจๅญ—ๅ…ธไธญ local log_key = table.concat({"status-",timestamp}) local request_log_dict = access:get(log_key) or "" if request_log_dict == "" then request_log_dict = request_log else request_log_dict = table.concat({request_log_dict,"\n",request_log}) end access:set(log_key, request_log_dict, expire_time) end -- ๅญ˜ๅ‚จupstream timeๅคงไบŽ0.5็š„url if tonumber(upstream_response_time) > 0.5 then -- ๆ‹ผๆŽฅurl,็Šถๆ€็ ,ๅญ—่Š‚ๆ•ฐ็ญ‰ๅญ—ๆฎต local request_log_t = {} table.insert(request_log_t,host) table.insert(request_log_t,request_without_args) table.insert(request_log_t,upstream_response_time) local request_log = table.concat(request_log_t," ") -- ๆŠŠๆ‹ผๆŽฅ็š„ๅญ—ๆฎตๅ‚จๅญ˜ๅœจๅญ—ๅ…ธไธญ local log_key = table.concat({"upt-",timestamp}) local request_log_dict = access:get(log_key) or "" if request_log_dict == "" then request_log_dict = request_log else request_log_dict = table.concat({request_log_dict,"\n",request_log}) end access:set(log_key, request_log_dict, expire_time) end
RDX = nil local Status, isPaused = {}, false Citizen.CreateThread(function() while RDX == nil do TriggerEvent('rdx:getSharedObject', function(obj) RDX = obj end) Citizen.Wait(0) end end) function GetStatusData(minimal) local status = {} for i=1, #Status, 1 do if minimal then table.insert(status, { name = Status[i].name, val = Status[i].val, percent = (Status[i].val / Config.StatusMax) * 100 }) else table.insert(status, { name = Status[i].name, val = Status[i].val, color = Status[i].color, visible = Status[i].visible(Status[i]), max = Status[i].max, percent = (Status[i].val / Config.StatusMax) * 100 }) end end return status end AddEventHandler('rdx_status:registerStatus', function(name, default, color, visible, tickCallback) local status = CreateStatus(name, default, color, visible, tickCallback) table.insert(Status, status) end) AddEventHandler('rdx_status:unregisterStatus', function(name) for k,v in ipairs(Status) do if v.name == name then table.remove(Status, k) break end end end) RegisterNetEvent('rdx_status:load') AddEventHandler('rdx_status:load', function(status) for i=1, #Status, 1 do for j=1, #status, 1 do if Status[i].name == status[j].name then Status[i].set(status[j].val) end end end Citizen.CreateThread(function() while true do for i=1, #Status, 1 do Status[i].onTick() end SendNUIMessage({ update = true, status = GetStatusData() }) TriggerEvent('rdx_status:onTick', GetStatusData(true)) Citizen.Wait(Config.TickTime) end end) end) RegisterNetEvent('rdx_status:set') AddEventHandler('rdx_status:set', function(name, val) for i=1, #Status, 1 do if Status[i].name == name then Status[i].set(val) break end end SendNUIMessage({ update = true, status = GetStatusData() }) TriggerServerEvent('rdx_status:update', GetStatusData(true)) end) RegisterNetEvent('rdx_status:add') AddEventHandler('rdx_status:add', function(name, val) for i=1, #Status, 1 do if Status[i].name == name then Status[i].add(val) break end end SendNUIMessage({ update = true, status = GetStatusData() }) TriggerServerEvent('rdx_status:update', GetStatusData(true)) end) RegisterNetEvent('rdx_status:remove') AddEventHandler('rdx_status:remove', function(name, val) for i=1, #Status, 1 do if Status[i].name == name then Status[i].remove(val) break end end SendNUIMessage({ update = true, status = GetStatusData() }) TriggerServerEvent('rdx_status:update', GetStatusData(true)) end) AddEventHandler('rdx_status:getStatus', function(name, cb) for i=1, #Status, 1 do if Status[i].name == name then cb(Status[i]) return end end end) AddEventHandler('rdx_status:setDisplay', function(val) SendNUIMessage({ setDisplay = true, display = val }) end) -- Pause menu disable hud display Citizen.CreateThread(function() while true do Citizen.Wait(300) if IsPauseMenuActive() and not isPaused then isPaused = true TriggerEvent('rdx_status:setDisplay', 0.0) elseif not IsPauseMenuActive() and isPaused then isPaused = false TriggerEvent('rdx_status:setDisplay', 0.5) end end end) -- Loaded event Citizen.CreateThread(function() TriggerEvent('rdx_status:loaded') end) -- Update server Citizen.CreateThread(function() while true do Citizen.Wait(Config.UpdateInterval) TriggerServerEvent('rdx_status:update', GetStatusData(true)) end end)
EvolutionChamber.kUpgradeButtons ={ [kTechId.SkulkMenu] = { kTechId.Leap, kTechId.Xenocide, kTechId.None, kTechId.None, kTechId.None, kTechId.None, kTechId.None, kTechId.None }, [kTechId.GorgeMenu] = { kTechId.BileBomb, kTechId.WebTech, kTechId.None, kTechId.None, kTechId.None, kTechId.None, kTechId.None, kTechId.None }, [kTechId.LerkMenu] = { kTechId.Umbra, kTechId.Spores, kTechId.None, kTechId.None, kTechId.None, kTechId.None, kTechId.None, kTechId.None }, [kTechId.FadeMenu] = { kTechId.MetabolizeEnergy, kTechId.MetabolizeHealth, kTechId.AdvancedSwipe, kTechId.None, kTechId.None, kTechId.None, kTechId.None, kTechId.None }, [kTechId.OnosMenu] = { kTechId.Charge, kTechId.BoneShield, kTechId.Stomp, kTechId.None, kTechId.None, kTechId.None, kTechId.None, kTechId.None } }
-- Start Point Guessing functions used by initial_spawn local claimRadius = 250*2.3 -- the radius about your own startpoint which the startpoint guesser regards as containing mexes that you've claimed for yourself (dgun range=250) local claimRadius2 = 250*1.5 -- as above, but for continuous metal dist instead of spots local claimHeight = 300 -- the height difference relative your own startpoint in which, within the claimRadius, the startpoint guesser regards you as claiming mexes (coms can build up a cliff ~200 high but not much more). local walkRadius = 250*3 -- the radius outside of the startbox that we regard as being able to walk to a mex on -- format of startPointTable passed in should be startPointTable(teamID) = {x,z}, where x,z<=-500 if team does not yet have a startpoint function IsSteep(x,z) --check if the position (x,z) is too step to start a commander on or not local mtta = math.acos(1.0 - 0.41221) - 0.02 --http://springrts.com/wiki/Movedefs.lua#How_slope_is_determined & the -0.02 is for safety local a1,a2,a3,a4 = 0,0,0,0 local d = 5 local y = Spring.GetGroundHeight(x,z) local y1 = Spring.GetGroundHeight(x+d,z) if math.abs(y1 - y) > 0.1 then a1 = math.atan((y1-y)/d) end local y2 = Spring.GetGroundHeight(x,z+d) if math.abs(y2 - y) > 0.1 then a2 = math.atan((y2-y)/d) end local y3 = Spring.GetGroundHeight(x-d,z) if math.abs(y3 - y) > 0.1 then a3 = math.atan((y3-y)/d) end local y4 = Spring.GetGroundHeight(x,z+d) if math.abs(y4 - y) > 0.1 then a4 = math.atan((y4-y)/d) end if math.abs(a1) > mtta or math.abs(a2) > mtta or math.abs(a3) > mtta or math.abs(a4) > mtta then return true --too steep else return false --ok end end function GuessOne(teamID, allyID, xmin, zmin, xmax, zmax, startPointTable) -- guess based on metal spots within startbox -- -- check if mex list generation worked and retrieve if so if not GG.metalSpots then return -1,-1 end local metalSpots = GG.metalSpots if metalSpots == false then return -1,-1 end -- find free metal spots local freeMetalSpots = {} -- will contain all metalspots that are within teamIDs startbox and are not within one of the cylinders given by (claimradius,claimheight) about an already existing startpoint local walkableMetalSpots = {} -- will contain all metalspots that are NOT within teamIDs startbox and are not within one of the cylinders given by (claimradius,claimheight) about an already existing startpoint, but are within walkradius of the startbox local k,j = 1,1 for i=1,#metalSpots do local spot = metalSpots[i] local mx,mz = spot.x,spot.z local my = Spring.GetGroundHeight(mx,mz) local isWithinStartBox = (xmin < mx) and (mx < xmax) and (zmin < mz) and (mz < zmax) local isWithinWalkRadius = (mx >= xmin - walkRadius) and (mx <= xmax + walkRadius) and (mz >= zmin - walkRadius) and (mz <= zmax + walkRadius) local isFree = true for _,startpoint in pairs(startPointTable) do -- we avoid enemy startpoints too, to prevent unnecessary explosions and to deal with the case of having no startboxes local sx,sz = startpoint[1],startpoint[2] local sy = Spring.GetGroundHeight(sx,sz) local isWithinClaimRadius = ((sx-mx)*(sx-mx)+(sz-mz)*(sz-mz) <= (claimRadius)*(claimRadius)) local isWithinClaimHeight = (math.abs(my-sy) <= claimHeight) if isWithinClaimRadius and isWithinClaimHeight then isFree = false break end end if isFree then if isWithinStartBox then freeMetalSpots[k] = {mx,mz} k = k + 1 elseif isWithinWalkRadius then walkableMetalSpots[j] = {mx,mz} j = j + 1 end end end if k==1 then --found no free metal spots within startbox if j==1 then --found no walkable spots either -> give up return -1,-1 end -- find nearest walkable metal spot to startbox local bx,bz = -1,-1 -- will contain nearest point in startbox to nearest walkable mex local bestDist = 2*walkRadius for i=1,#walkableMetalSpots do local mx,mz = walkableMetalSpots[i][1], walkableMetalSpots[i][2] local nx = math.max(math.min(mx,xmax),xmin) local nz = math.max(math.min(mz,zmax),zmin) local dist = math.sqrt((mx-nx)^2 + (mz-nz)^2) if not IsSteep(nx,nz) and dist < bestDist then bx = nx bz = nz end end return bx,bz end -- score each free metal spot local freeMetalSpotScores = {} for i=1,#freeMetalSpots do freeMetalSpotScores[i]=0 end for i=1,#freeMetalSpots do local ix,iz = freeMetalSpots[i][1], freeMetalSpots[i][2] for j=1,#freeMetalSpots do local jx,jz = freeMetalSpots[j][1],freeMetalSpots[j][2] if ix ~= jx or iz ~= jz then local r = math.sqrt((ix-jx)^2+(iz-jz)^2) local iy = Spring.GetGroundHeight(ix,iz) local jy = Spring.GetGroundHeight(jx,jz) local isWithinClaimRadius = (r <= claimRadius) local isWithinClaimHeight = (math.abs(iy-jy) <= claimHeight) local score -- Magic formula. Assumes all metal spots are of equal production value, TODO... if isWithinClaimRadius and isWithinClaimHeight then score = 10 else score = r^(-1/2) end freeMetalSpotScores[i] = freeMetalSpotScores[i] + score end end end -- find free metal spot with highest score local bestIndex = 1 for i=2,#freeMetalSpotScores do if freeMetalSpotScores[i] >= freeMetalSpotScores[bestIndex] then bestIndex = i end end -- find nearest free spot closest to best local bx,bz = freeMetalSpots[bestIndex][1],freeMetalSpots[bestIndex][2] local nx,nz local bestDistance = (xmax)*(xmax)+(zmax)*(zmax) -- meh, just need to be big for i=1,#freeMetalSpots do if i ~= bestIndex then local mx,mz = freeMetalSpots[i][1],freeMetalSpots[i][2] local thisDistance = (bx-mx)*(bx-mx)+(bz-mz)*(bz-mz) --no need to squareroot, we care only about the order if thisDistance < bestDistance then bestDistance = thisDistance nx = mx nz = mz end end end -- if it wasn't possible to find a nearest free spot if nx==nil or nx==bx or nz==nil or nz==bz then nx=bx+1 nz=bx+1 end -- move slightly towards nearest from best local norm = math.sqrt((bx-nx)*(bx-nx)+(bz-nz)*(bz-nz)) local dispx = (nx-bx)/norm local dispz = (nz-bz)/norm local disp = 120 x = bx + disp * (dispx) z = bz + disp * (dispz) -- if the terrain nearby was too steep, just start on the mex (-> assume mex is passable) if IsSteep(x,z) then x = bx z = bz end return x,z end function GuessTwo(teamID, allyID, xmin, zmin, xmax, zmax, startPointTable) --TODO: make this more efficient, atm it akes 1-2 sec to run -- search over metal map and find a point with a reasonable amount of non-claimed metal near to it local mmapx,mmapz = Spring.GetMetalMapSize() -- metal map cords * 16 = world coords local xres = math.max(1,math.floor(mmapx/16)) local zres = math.max(1,math.floor(mmapz/16)) local points = {} --possible startpoints point[id] = {x,z,metal}, grid over metalmap of sidelength res local x = xres local z = zres while true do --i hate lua local y = Spring.GetGroundHeight(x*16,z*16) local isWithinStartBox = (xmin < 16*x) and (16*x < xmax) and (zmin < 16*z) and (16*z < zmax) if isWithinStartBox then points[#points+1] = {x=x, y=y, z=z, m=0} end x = x + xres if x > mmapx then x = 1 z = z + zres end if z > mmapz then break end end -- count metal for each point (sample metalmap at points in square grid of sidelength res2) local xres2 = math.max(1,math.floor(xres/4)) local zres2 = math.max(1,math.floor(zres/4)) for x=1,mmapx,xres2 do for z=1,mmapz,zres2 do -- is this metal aready claimed? local isFree = true for _,startpoint in pairs(startPointTable) do -- we avoid enemy startpoints too, to prevent unnecessary explosions and to deal with the case of having no startboxes local sx,sz = startpoint[1],startpoint[2] local sy = Spring.GetGroundHeight(sx,sz) local y = Spring.GetGroundHeight(x*16,z*16) local isWithinClaimRadius = ((sx-x*16)*(sx-x*16)+(sz-z*16)*(sz-z*16) <= (claimRadius2)*(claimRadius2)) local isWithinClaimHeight = (math.abs(sy-y) <= claimHeight) if isWithinClaimRadius and isWithinClaimHeight then isFree = false break end end -- if it is, add this metal into points local m = Spring.GetMetalAmount(x,z) if isFree and m > 0.1 then local y = Spring.GetGroundHeight(x*16,z*16) for _,p in ipairs(points) do if m and (p.x-x)*(p.x-x)+(p.z-z)*(p.z-z) <= (claimRadius2/16)*(claimRadius2/16) and math.abs(p.y-y) <= claimHeight then p.m = p.m + m end end end end end -- find which point within the startbox that has the most metal local best local bestM = 0 for id,p in ipairs(points) do if bestM < p.m then best = id bestM = p.m end end -- return best if best then return (points[best].x)*16, (points[best].z)*16 end -- give up return -1,-1 end function GuessStartSpot(teamID, allyID, xmin, zmin, xmax, zmax, startPointTable) --Sanity check if (xmin >= xmax) or (zmin>=zmax) then return 0,0 end -- Try our guesses local x,z = GuessOne(teamID, allyID, xmin, zmin, xmax, zmax, startPointTable) if x>=0 and z>=0 then startPointTable[teamID]={x,z} return x,z end x,z = GuessTwo(teamID, allyID, xmin, zmin, xmax, zmax, startPointTable) if x>=0 and z>=0 then startPointTable[teamID]={x,z} return x,z end -- GIVE UP, fuuuuuuuuuuuuu -- x = (xmin + xmax) / 2 z = (zmin + zmax) / 2 startPointTable[teamID]={x,z} return x,z end
require "helpers" local tables = {} tables.natural_point = osm2pgsql.define_table({ name = 'natural_point', schema = schema_name, ids = { type = 'node', id_column = 'osm_id' }, columns = { { column = 'osm_type', type = 'text', not_null = true }, { column = 'name', type = 'text' }, { column = 'ele', type = 'int' }, { column = 'geom', type = 'point' , projection = srid}, } }) tables.natural_line = osm2pgsql.define_table({ name = 'natural_line', schema = schema_name, ids = { type = 'way', id_column = 'osm_id' }, columns = { { column = 'osm_type', type = 'text', not_null = true }, { column = 'name', type = 'text' }, { column = 'ele', type = 'int' }, { column = 'geom', type = 'linestring' , projection = srid}, } }) tables.natural_polygon = osm2pgsql.define_table({ name = 'natural_polygon', schema = schema_name, ids = { type = 'way', id_column = 'osm_id' }, columns = { { column = 'osm_type', type = 'text', not_null = true }, { column = 'name', type = 'text' }, { column = 'ele', type = 'int' }, { column = 'geom', type = 'multipolygon' , projection = srid}, } }) function natural_process_node(object) -- We are only interested in natural details if not object.tags.natural then return end -- Not interetested in tags caught in water.lua if object.tags.natural == 'water' or object.tags.natural == 'lake' or object.tags.natural == 'hot_spring' or object.tags.natural == 'waterfall' or object.tags.natural == 'wetland' or object.tags.natural == 'swamp' or object.tags.natural == 'water_meadow' or object.tags.natural == 'waterway' or object.tags.natural == 'spring' then return end -- Using grab_tag() removes from remaining key/value saved to Pg local osm_type = object:grab_tag('natural') local name = get_name(object.tags) local ele = parse_to_meters(object.tags.ele) tables.natural_point:add_row({ osm_type = osm_type, name = name, ele = ele, geom = { create = 'point' } }) end function natural_process_way(object) if not object.tags.natural then return end -- Not interetested in tags caught in water.lua if object.tags.natural == 'water' or object.tags.natural == 'lake' or object.tags.natural == 'hot_spring' or object.tags.natural == 'waterfall' or object.tags.natural == 'wetland' or object.tags.natural == 'swamp' or object.tags.natural == 'water_meadow' or object.tags.natural == 'waterway' or object.tags.natural == 'spring' then return end local osm_type = object:grab_tag('natural') local name = get_name(object.tags) local ele = parse_to_meters(object.tags.ele) if object.is_closed then tables.natural_polygon:add_row({ osm_type = osm_type, name = name, ele = ele, geom = { create = 'area' } }) else tables.natural_line:add_row({ osm_type = osm_type, name = name, ele = ele, geom = { create = 'line' } }) end end if osm2pgsql.process_node == nil then -- Change function name here osm2pgsql.process_node = natural_process_node else local nested = osm2pgsql.process_node osm2pgsql.process_node = function(object) local object_copy = deep_copy(object) nested(object) -- Change function name here natural_process_node(object_copy) end end if osm2pgsql.process_way == nil then -- Change function name here osm2pgsql.process_way = natural_process_way else local nested = osm2pgsql.process_way osm2pgsql.process_way = function(object) local object_copy = deep_copy(object) nested(object) -- Change function name here natural_process_way(object_copy) end end
local Dictionary = script.Parent local Llama = Dictionary.Parent local t = require(LLama.Parent.t) local validate = t.tuple(t.table, t.callback) local function map(dictionary, mapper) assert(validate(dictionary, mapper)) local new = {} for key, value in pairs(dictionary) do local newValue, newKey = mapper(value, key) new[newKey or key] = newValue end return new end return map
---Creates new vector. Itโ€™s usually faster to create a new item with `vec3(x, y, z)` directly, but the way LuaJIT works, ---that call only works with three numbers. If you only provide a single number, rest will be set to 0. This call, however, supports ---various calls (which also makes it slightly slower). ---@overload fun(value: vec3): vec3 ---@overload fun(tableOfThree: number[]): vec3 ---@overload fun(value: number): vec3 ---@param x number ---@param y number ---@param z number ---@return vec3 function vec3.new(x, y, z) end ---Checks if value is vec3 or not. ---@param p any ---@return boolean function vec3.isvec3(p) end ---Temporary vector. For most cases though, it might be better to define those locally and use those. Less chance of collision. ---@return vec3 function vec3.tmp() end ---Three-dimensional vector. All operators are overloaded. ---Note: creating a lot of new vectors can create extra work for garbage collector reducing overall effectiveness. ---Where possible, instead of using mathematical operators consider using methods altering state of already existing vectors. So, instead of: ---``` ---someVec = vec3() ---โ€ฆ ---someVec = math.normalize(vec1 + vec2) * 10 ---``` ---Consider rewriting it like: ---``` ---someVec = vec3() ---โ€ฆ ---someVec:set(vec1):add(vec2):normalize():scale(10) ---``` ---@class vec3 ---@field x number ---@field y number ---@field z number ---@constructor fun(x: number, y: number, z: number): vec3 ---Makes a copy of a vector. ---@return vec3 function vec3:clone() end ---Unpacks vec3 into rgb and number. ---@return rgb, number function vec3:unpack() end ---Turns vec3 into a table with three values. ---@return number[] function vec3:table() end ---Returns reference to vec3 class. function vec3:type() end ---@param x vec3|number ---@param y number? ---@param z number? ---@return vec3 @Returns itself. function vec3:set(x, y, z) end ---@param vec vec3 ---@param scale number ---@return vec3 @Returns itself. function vec3:setScaled(vec, scale) end ---@param value1 vec3 ---@param value2 vec3 ---@param mix number ---@return vec3 @Returns itself. function vec3:setLerp(value1, value2, mix) end ---Sets itself to a normalized result of cross product of value1 and value2. ---@param value1 vec3 ---@param value2 vec3 ---@return vec3 @Returns itself. function vec3:setCrossNormalized(value1, value2) end ---Copies its values to a different vector. ---@param out vec3 ---@return vec3 @Returns itself. function vec3:copyTo(out) end ---@param valueToAdd vec3|number ---@param out vec3|nil @Optional destination argument. ---@return vec3 @Returns itself or out value. function vec3:add(valueToAdd, out) end ---@param valueToAdd vec3 ---@param scale number ---@param out vec3|nil @Optional destination argument. ---@return vec3 @Returns itself or out value. function vec3:addScaled(valueToAdd, scale, out) end ---@param valueToSubtract vec3|number ---@param out vec3|nil @Optional destination argument. ---@return vec3 @Returns itself or out value. function vec3:sub(valueToSubtract, out) end ---@param valueToMultiplyBy vec3 ---@param out vec3|nil @Optional destination argument. ---@return vec3 @Returns itself or out value. function vec3:mul(valueToMultiplyBy, out) end ---@param valueToDivideBy vec3 ---@param out vec3|nil @Optional destination argument. ---@return vec3 @Returns itself or out value. function vec3:div(valueToDivideBy, out) end ---@param exponent vec3|number ---@param out vec3|nil @Optional destination argument. ---@return vec3 @Returns itself or out value. function vec3:pow(exponent, out) end ---@param multiplier number ---@param out vec3|nil @Optional destination argument. ---@return vec3 @Returns itself or out value. function vec3:scale(multiplier, out) end ---@param otherValue vec3|number ---@param out vec3|nil @Optional destination argument. ---@return vec3 @Returns itself or out value. function vec3:min(otherValue, out) end ---@param otherValue vec3|number ---@param out vec3|nil @Optional destination argument. ---@return vec3 @Returns itself or out value. function vec3:max(otherValue, out) end ---@param out vec3|nil @Optional destination argument. ---@return vec3 @Returns itself or out value. function vec3:saturate(out) end ---@param min vec3 ---@param max vec3 ---@param out vec3|nil @Optional destination argument. ---@return vec3 @Returns itself or out value. function vec3:clamp(min, max, out) end ---@return number function vec3:length() end ---@return number function vec3:lengthSquared() end ---@param otherVector vec3 ---@return number function vec3:distance(otherVector) end ---@param otherVector vec3 ---@return number function vec3:distanceSquared(otherVector) end ---@param otherVector vec3 ---@param distanceThreshold number ---@return boolean function vec3:closerToThan(otherVector, distanceThreshold) end ---@param otherVector vec3 ---@return number function vec3:angle(otherVector) end ---@param otherVector vec3 ---@return number function vec3:dot(otherVector) end ---Normalizes itself (unless different `out` is provided). ---@param out vec3|nil @Optional destination argument. ---@return vec3 @Returns itself or out value. function vec3:normalize(out) end ---Rewrites own values with values of cross product of itself and other vector (unless different `out` is provided). ---@param otherVector vec3 ---@param out vec3|nil @Optional destination argument. ---@return vec3 @Returns itself or out value. function vec3:cross(otherVector, out) end ---Rewrites own values with values of lerp of itself and other vector (unless different `out` is provided). ---@param otherVector vec3 ---@param mix number ---@param out vec3|nil @Optional destination argument. ---@return vec3 @Returns itself or out value. function vec3:lerp(otherVector, mix, out) end ---Rewrites own values with values of projection of itself onto another vector (unless different `out` is provided). ---@param otherVector vec3 ---@param out vec3|nil @Optional destination argument. ---@return vec3 @Returns itself or out value. function vec3:project(otherVector, out) end ---Rewrites own values with values of itself rotated with quaternion (unless different `out` is provided). ---@param quaternion quat ---@param out vec3|nil @Optional destination argument. ---@return vec3 @Returns itself or out value. function vec3:rotate(quaternion, out) end
require 'plugins' local opt = vim.opt local cmd = vim.cmd local g = vim.g local o = vim.o local wo = vim.wo local bo = vim.bo g.mapleader = ',' o.clipboard = 'unnamedplus' opt.termguicolors = true g.syntax = true require 'hemisu' opt.completeopt = 'menuone,noselect' -- Temporarily source the vim part cmd('source ~/.config/nvim/vimconfig.vim') opt.autoindent = true opt.autoread = true opt.encoding = 'utf-8' opt.expandtab = true opt.ignorecase = true opt.incsearch = true opt.inccommand = 'split' opt.laststatus = 2 opt.list = true opt.ruler = true opt.scrolloff = 3 opt.shiftwidth = 2 opt.showcmd = true opt.smartcase = true opt.softtabstop = 2 opt.tabstop = 2 opt.wildmenu = true opt.wildmode = 'longest,list,full' opt.mouse = 'a' wo.number = true wo.relativenumber = true opt.listchars = { tab = "โ–ธ ", trail = "โ–ซ" } -- Import on save vim.cmd([[ autocmd BufWritePre *.go :silent! lua require('go.format').goimport() ]], false) -- Format on save vim.cmd([[ autocmd BufWritePre *.go :silent! lua require('go.format').gofmt() ]], false) require'config/treesitter' require'config/telescope' require'config/lsp' require'config/lualine'
AddEventHandler('mythic_base:shared:ComponentsReady', function() exports['mythic_base']:FetchComponent('Chat'):RegisterCommand('phone', function(source) TriggerClientEvent('mythic_phone:client:TogglePhone', source) end, { help = "Toggle Phone Display" }, 0) exports['mythic_base']:FetchComponent('Chat'):RegisterCommand('testchip', function(source) print('testchip') TriggerClientEvent('mythic_phone:client:TestChip', source) end, { help = "Test Tuner Chip Function" }, 0) end)
require "helpers" require "functions" script.on_init(timg.events.init) script.on_configuration_changed(timg.events.on_config_change) script.on_event(defines.events.on_pre_build, timg.events.put_item) script.on_event( defines.events.on_built_entity, timg.events.build_entity, { {filter="ghost", invert=true, mode="and"}, {filter="rail", invert=true, mode="and"}, {filter="rolling-stock", invert=true, mode="and"}, {filter="vehicle", invert=true, mode="and"}, {filter="robot-with-logistics-interface", invert=true, mode="and"}, {filter="type", type="tile", invert=true, mode="and"}, {filter="type", type="land-mine", invert=true, mode="and"}, {filter="type", type="unit", invert=true, mode="and"}, {filter="type", type="unit-spawner", invert=true, mode="and"}, {filter="type", type="corpse", invert=true, mode="and"}, {filter="name", name="logistic-train-stop", invert=true, mode="and"}, }) --script.on_event(defines.events.on_player_cursor_stack_changed, timg.events.stack_change) script.on_event(timg.events.on_toggle, timg.events.toggle) script.on_event(timg.events.on_toggle_bp, timg.events.toggle_blueprint) script.on_event(defines.events.on_lua_shortcut, timg.events.shortcut) script.on_init(timg.events.init) script.on_event(defines.events.on_player_toggled_map_editor, timg.events.map_editor_toggle) commands.add_command("timg_debug", "Toggle There is my Ghosts debug mode. This will print a load of messages when on", timg.events.toggle_debug)
RegisterCommand('noty', function(source, args, raw) TriggerClientEvent('NotyFive:SendNotification', source, ({text = "(ERROR) Testing Notification<br>This is the second line<br>third line here", type = "error", timeout = math.random(1000, 10000)})) TriggerClientEvent('NotyFive:SendNotification', source, ({text = "(INFO) Testing Notification<br>This is the second line<br>third line here", type = "info", timeout = math.random(1000, 10000)})) TriggerClientEvent('NotyFive:SendNotification', source, ({text = "(SUCCESS) Testing Notification<br>This is the second line<br>third line here", type = "success", timeout = math.random(1000, 10000)})) TriggerClientEvent('NotyFive:SendNotification', source, ({text = "(ALERT) Testing Notification<br>This is the second line<br>third line here", type = "alert", timeout = math.random(1000, 10000)})) TriggerClientEvent('NotyFive:SendNotification', source, ({text = "(WARNING) Testing Notification<br>This is the second line<br>third line here", type = "warning", timeout = math.random(1000, 10000)})) Citizen.Wait(500) TriggerClientEvent('NotyFive:SendNotification', source, ({text = "This was a forced notification", type = "success", timeout = math.random(1000, 10000), force = true})) Citizen.Wait(1000) TriggerClientEvent('NotyFive:SendNotification', source, ({text = "This is a killer notification", type = "warning", timeout = math.random(1000, 10000), killer = true})) end)
-------------------------------------------------------------------------- -- Permutation avec repetion -- -------------------------------------------------------------------------- require("ui/wscreen") ArrangementAvecRep = Combinatoire(ARRANGEMENT_AVEC_REP_TITLE_ID,ARRANGEMENT_AVEC_REP_HEADER_ID) function ArrangementAvecRep:performnp(n,p) local calculate = "("..tostring(n)..")^("..tostring(p)..")" print(tostring(calculate)) local result,err1 = math.evalStr(tostring(calculate)) local resultA,err2 = math.evalStr("approx("..tostring(calculate)..")") local res = ASTxt(SOLVE_ID).." n="..tostring(n).." "..ASTxt(AND_ID).." p="..tostring(p).."\n=> \\0el {"..tostring(calculate).."}=\\0el {"..tostring(result).."}=\\0el {"..tostring(resultA).."}\n" if err1 then res = res.."ERROR:"..tostring(err1) end if err2 then res = res.."ERROR:"..tostring(err2) end return res end function ArrangementAvecRep:perform() print("ArrangementAvecRepCls:perform") self.font ={"sansserif", "r", 10} self.operation="" local n,p=self:extractTxt() if (tostring(n)=="nil") or tostring(n)=="" then return end if (tostring(p)=="nil") or tostring(p)=="" then p=0 while p<=tonumber(n) do self.operation=self.operation..self:performnp(n,p) p=p+1 end else self.operation=self.operation..self:performnp(n,p) end self:invalidate() end
local _, ns = ... local oUF = ns.oUF local Private = oUF.Private local unitExists = Private.unitExists local function updateArenaPreparationElements(self, event, elementName, specID) local element = self[elementName] if element and self:IsElementEnabled(elementName) then if element.OverrideArenaPreparation then --[[ Override: Health.OverrideArenaPreparation(self, event, specID) Used to completely override the internal update function for arena preparation. * self - the parent object * event - the event triggering the update (string) * specID - the specialization ID for the opponent (number) --]] --[[ Override: Power.OverrideArenaPreparation(self, event, specID) Used to completely override the internal update function for arena preparation. * self - the parent object * event - the event triggering the update (string) * specID - the specialization ID for the opponent (number) --]] element.OverrideArenaPreparation(self, event, specID) return end element:SetMinMaxValues(0, 1) element:SetValue(1) if element.UpdateColorArenaPreparation then --[[ Override: Health:UpdateColor(specID) Used to completely override the internal function for updating the widget's colors during arena preparation. * self - the Health element * specID - the specialization ID for the opponent (number) --]] --[[ Override: Power:UpdateColor(specID) Used to completely override the internal function for updating the widget's colors during arena preparation. * self - the Power element * specID - the specialization ID for the opponent (number) --]] element:UpdateColorArenaPreparation(specID) else -- this section just replicates the color options available to the Health and Power elements local r, g, b, color, _ -- if(element.colorPower and elementName == 'Power') then -- FIXME: no idea if we can get power type here without the unit if element.colorClass then local _, _, _, _, _, class = GetSpecializationInfoByID(specID) color = self.colors.class[class] elseif element.colorReaction then color = self.colors.reaction[2] elseif element.colorSmooth then _, _, _, _, _, _, r, g, b = unpack(element.smoothGradient or self.colors.smooth) elseif element.colorHealth and elementName == "Health" then color = self.colors.health end if color then r, g, b = color[1], color[2], color[3] end if r or g or b then element:SetStatusBarColor(r, g, b) local bg = element.bg if bg then local mu = bg.multiplier or 1 bg:SetVertexColor(r * mu, g * mu, b * mu) end end end if element.PostUpdateArenaPreparation then --[[ Callback: Health:PostUpdateArenaPreparation(event, specID) Called after the element has been updated during arena preparation. * self - the Health element * event - the event triggering the update (string) * specID - the specialization ID for the opponent (number) --]] --[[ Callback: Power:PostUpdateArenaPreparation(event, specID) Called after the element has been updated during arena preparation. * self - the Power element * event - the event triggering the update (string) * specID - the specialization ID for the opponent (number) --]] element:PostUpdateArenaPreparation(event, specID) end end end local function updateArenaPreparation(self, event) if not self:GetAttribute("oUF-enableArenaPrep") then return end if event == "ARENA_OPPONENT_UPDATE" and not self:IsEnabled() then self:Enable() self:UpdateAllElements("ArenaPreparation") self:UnregisterEvent(event, updateArenaPreparation) -- show elements that don't handle their own visibility if self:IsElementEnabled("Auras") then if self.Auras then self.Auras:Show() end if self.Buffs then self.Buffs:Show() end if self.Debuffs then self.Debuffs:Show() end end if self.Portrait and self:IsElementEnabled("Portrait") then self.Portrait:Show() end elseif event == "PLAYER_ENTERING_WORLD" and not UnitExists(self.unit) then -- semi-recursive call for when the player zones into an arena updateArenaPreparation(self, "ARENA_PREP_OPPONENT_SPECIALIZATIONS") elseif event == "ARENA_PREP_OPPONENT_SPECIALIZATIONS" then if InCombatLockdown() then -- prevent calling protected functions if entering arena while in combat self:RegisterEvent("PLAYER_REGEN_ENABLED", updateArenaPreparation, true) return end if self.PreUpdate then self:PreUpdate(event) end local id = tonumber(self.id) if not self:IsEnabled() and GetNumArenaOpponentSpecs() < id then -- hide the object if the opponent leaves self:Hide() end local specID = GetArenaOpponentSpec(id) if specID then if self:IsEnabled() then -- disable the unit watch so we can forcefully show the object ourselves self:Disable() self:RegisterEvent("ARENA_OPPONENT_UPDATE", updateArenaPreparation) end -- update Health and Power (if available) with "fake" data updateArenaPreparationElements(self, event, "Health", specID) updateArenaPreparationElements(self, event, "Power", specID) -- hide all other (relevant) elements (they have no effect during arena prep) if self.Auras then self.Auras:Hide() end if self.Buffs then self.Buffs:Hide() end if self.Debuffs then self.Debuffs:Hide() end if self.Castbar then self.Castbar:Hide() end if self.CombatIndicator then self.CombatIndicator:Hide() end if self.GroupRoleIndicator then self.GroupRoleIndicator:Hide() end if self.Portrait then self.Portrait:Hide() end if self.PvPIndicator then self.PvPIndicator:Hide() end if self.RaidTargetIndicator then self.RaidTargetIndicator:Hide() end self:Show() self:UpdateTags() end if self.PostUpdate then self:PostUpdate(event) end elseif event == "PLAYER_REGEN_ENABLED" then self:UnregisterEvent(event, updateArenaPreparation) updateArenaPreparation(self, "ARENA_PREP_OPPONENT_SPECIALIZATIONS") end end -- Handles unit specific actions. function oUF:HandleUnit(object, unit) unit = object.unit or unit if unit == "target" then object:RegisterEvent("PLAYER_TARGET_CHANGED", object.UpdateAllElements, true) elseif unit == "mouseover" then object:RegisterEvent("UPDATE_MOUSEOVER_UNIT", object.UpdateAllElements, true) elseif unit == "focus" then object:RegisterEvent("PLAYER_FOCUS_CHANGED", object.UpdateAllElements, true) elseif unit:match("boss%d?$") then object:RegisterEvent("INSTANCE_ENCOUNTER_ENGAGE_UNIT", object.UpdateAllElements, true) object:RegisterEvent("UNIT_TARGETABLE_CHANGED", object.UpdateAllElements) elseif unit:match("arena%d?$") then object:RegisterEvent("ARENA_OPPONENT_UPDATE", object.UpdateAllElements, true) object:RegisterEvent("ARENA_PREP_OPPONENT_SPECIALIZATIONS", updateArenaPreparation, true) object:SetAttribute("oUF-enableArenaPrep", true) -- the event handler only fires for visible frames, so we have to hook it for arena prep object:HookScript("OnEvent", updateArenaPreparation) end end local eventlessObjects = {} local onUpdates = {} local function createOnUpdate(timer) if not onUpdates[timer] then local frame = CreateFrame("Frame") local objects = eventlessObjects[timer] frame:SetScript("OnUpdate", function(self, elapsed) self.elapsed = (self.elapsed or 0) + elapsed if self.elapsed > timer then for _, object in next, objects do if object.unit and unitExists(object.unit) then object:UpdateAllElements("OnUpdate") end end self.elapsed = 0 end end) onUpdates[timer] = frame end end function oUF:HandleEventlessUnit(object) object.__eventless = true -- It's impossible to set onUpdateFrequency before the frame is created, so -- by default all eventless frames are created with the 0.5s timer. -- To change it you'll need to call oUF:HandleEventlessUnit(frame) one more -- time from the layout code after oUF:Spawn(unit) returns the frame. local timer = object.onUpdateFrequency or 0.5 -- Remove it, in case it's registered with another timer previously for t, objects in next, eventlessObjects do if t ~= timer then for i, obj in next, objects do if obj == object then table.remove(objects, i) break end end end end if not eventlessObjects[timer] then eventlessObjects[timer] = {} end table.insert(eventlessObjects[timer], object) createOnUpdate(timer) end
--- -- @module event_loop -- -- This module processes only the state transitions by executing queries returned by the Event Handler -- local M = { string_to_boolean = { ["True"]=true, ["False"]=false } } local exa_error = require("exaerror") _G.global_env = { pquery = pquery, error = error } --- -- Executes the given set of queries. -- -- @param queries lua table including queries -- @param from_index the index where the queries in the lua table start -- -- @return the result of the latest query -- function M._run_queries(queries, from_index) for i=from_index, #queries do if queries[i][1] ~= nil then success, result = _G.global_env.pquery(queries[i][1]) if not success then local error_obj = exa_error.create( "E-AAF-3", "Error occurred in executing the query: " .. queries[i][1] .. " error message: " .. result.error_message) _G.global_env.error(tostring(error_obj)) end end end return result end --- -- Initiates the Event Loop that handles state transition -- -- @param query string that calls the event handler -- function M.init(query_to_event_handler) local is_finished = false local final_result = nil local query_to_create_view = nil repeat -- call EventHandlerUDF return queries local return_queries = {{query_to_create_view}, {query_to_event_handler}} local result = M._run_queries(return_queries, 1) -- handle EventHandlerUDF return query_to_create_view = result[1][1] query_to_event_handler = result[2][1] is_finished = M.string_to_boolean[result[3][1]] final_result = result[4][1] M._run_queries(result, 5) until (is_finished) return final_result end return M;
local old_BMPD_init = SkillTreeTweakData.init function SkillTreeTweakData:init() old_BMPD_init(self, tweak_data) -- Lines: 9 to 10 local function digest(value) return Application:digest_value(value, true) end self.tier_unlocks = { digest(0), digest(0), digest(0), digest(0) } self.costs = { unlock_tree = digest(0), default = digest(1), pro = digest(3), hightier = digest(4), hightierpro = digest(8) } self.unlock_tree_cost = { digest(0), digest(0), digest(0), digest(0), digest(0) } self.skill_pages_order = { "mastermind", "enforcer", "technician", "ghost", "hoxton" } self.tier_cost = { { 1, 3 }, { 2, 4 }, { 3, 6 }, { 4, 8 } } self.num_tiers = #self.tier_cost self.HIDE_TIER_BONUS = true self.specialization_convertion_rate = { 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000 } local deck2 = { cost = 300, desc_id = "menu_deckall_2_desc", name_id = "menu_deckall_2", upgrades = {"weapon_passive_headshot_damage_multiplier"}, icon_xy = { 1, 0 } } local deck4 = { cost = 600, desc_id = "menu_deckall_4_desc", name_id = "menu_deckall_4", upgrades = { "passive_player_xp_multiplier", "player_passive_suspicion_bonus", "player_passive_armor_movement_penalty_multiplier" }, icon_xy = { 3, 0 } } local deck6 = { cost = 1600, desc_id = "menu_deckall_6_desc", name_id = "menu_deckall_6", upgrades = { "armor_kit", "player_pick_up_ammo_multiplier" }, icon_xy = { 5, 0 } } local deck8 = { cost = 3200, desc_id = "menu_deckall_8_desc", name_id = "menu_deckall_8", upgrades = { "weapon_passive_damage_multiplier", "passive_doctor_bag_interaction_speed_multiplier" }, icon_xy = { 7, 0 } } self.specializations = { { { cost = 200, desc_id = "menu_deck1_1_desc", name_id = "menu_deck1_1", upgrades = { "team_damage_reduction_1", "player_passive_damage_reduction_1" }, icon_xy = { 0, 0 } }, deck2, { cost = 400, desc_id = "menu_deck1_3_desc", name_id = "menu_deck1_3", upgrades = { "team_passive_stamina_multiplier_1", "player_passive_intimidate_range_mul", "player_damage_dampener_close_contact_1" }, icon_xy = { 2, 0 } }, deck4, { cost = 1000, desc_id = "menu_deck1_5_desc", name_id = "menu_deck1_5", upgrades = { "team_passive_health_multiplier", "player_passive_health_multiplier_1" }, icon_xy = { 4, 0 } }, deck6, { cost = 2400, desc_id = "menu_deck1_7_desc", name_id = "menu_deck1_7", upgrades = { "player_tier_armor_multiplier_1", "team_passive_armor_multiplier" }, icon_xy = { 6, 0 } }, deck8, { cost = 4000, desc_id = "menu_deck1_9_desc", name_id = "menu_deck1_9", upgrades = { "player_passive_loot_drop_multiplier", "team_hostage_health_multiplier", "team_hostage_stamina_multiplier", "team_hostage_damage_dampener_multiplier" }, icon_xy = { 0, 1 } }, desc_id = "menu_st_spec_1_desc", name_id = "menu_st_spec_1" }, { { cost = 200, desc_id = "menu_deck2_1_desc", name_id = "menu_deck2_1", upgrades = {"player_passive_health_multiplier_1"}, icon_xy = { 0, 0 } }, deck2, { cost = 400, desc_id = "menu_deck2_3_desc", name_id = "menu_deck2_3", upgrades = { "player_passive_health_multiplier_2", "player_uncover_multiplier" }, icon_xy = { 1, 1 } }, deck4, { cost = 1000, desc_id = "menu_deck2_5_desc", name_id = "menu_deck2_5", upgrades = {"player_passive_health_multiplier_3"}, icon_xy = { 2, 1 } }, deck6, { cost = 2400, desc_id = "menu_deck2_7_desc", name_id = "menu_deck2_7", upgrades = {"player_panic_suppression"}, icon_xy = { 3, 1 } }, deck8, { cost = 4000, desc_id = "menu_deck2_9_desc", name_id = "menu_deck2_9", upgrades = { "player_passive_loot_drop_multiplier", "player_passive_health_multiplier_4", "player_passive_health_regen", "PBC_AssaultRifleBuff1", "PBC_AssaultRifleBuff2" }, icon_xy = { 4, 1 } }, desc_id = "menu_st_spec_2_desc", name_id = "menu_st_spec_2" }, { { cost = 200, desc_id = "menu_deck3_1_desc", name_id = "menu_deck3_1", upgrades = { "player_tier_armor_multiplier_1", "player_tier_armor_multiplier_2" }, icon_xy = { 6, 0 } }, deck2, { cost = 400, desc_id = "menu_deck3_3_desc", name_id = "menu_deck3_3", upgrades = {"player_tier_armor_multiplier_3"}, icon_xy = { 5, 1 } }, deck4, { cost = 1000, desc_id = "menu_deck3_5_desc", name_id = "menu_deck3_5", upgrades = {"player_tier_armor_multiplier_4"}, icon_xy = { 7, 1 } }, deck6, { cost = 2400, desc_id = "menu_deck3_7_desc", name_id = "menu_deck3_7", upgrades = { "player_armor_regen_timer_multiplier_passive", "temporary_armor_break_invulnerable_1" }, icon_xy = { 6, 1 } }, deck8, { cost = 4000, desc_id = "menu_deck3_9_desc", name_id = "menu_deck3_9", upgrades = { "player_passive_loot_drop_multiplier", "player_tier_armor_multiplier_5", "player_tier_armor_multiplier_6", "team_passive_armor_regen_time_multiplier" }, icon_xy = { 0, 2 } }, desc_id = "menu_st_spec_3_desc", name_id = "menu_st_spec_3" }, { { cost = 200, desc_id = "menu_deck4_1_desc", name_id = "menu_deck4_1", upgrades = {"player_passive_dodge_chance_1"}, icon_xy = { 1, 2 } }, deck2, { cost = 400, desc_id = "menu_deck4_3_desc", name_id = "menu_deck4_3", upgrades = {"player_camouflage_multiplier"}, icon_xy = { 4, 2 } }, deck4, { cost = 1000, desc_id = "menu_deck4_5_desc", name_id = "menu_deck4_5", upgrades = {"player_passive_dodge_chance_2"}, icon_xy = { 2, 2 } }, deck6, { cost = 2400, desc_id = "menu_deck4_7_desc", name_id = "menu_deck4_7", upgrades = {"player_passive_dodge_chance_3"}, icon_xy = { 3, 2 } }, deck8, { cost = 4000, desc_id = "menu_deck4_9_desc", name_id = "menu_deck4_9", upgrades = { "player_passive_loot_drop_multiplier", "weapon_passive_armor_piercing_chance", "weapon_passive_swap_speed_multiplier_1" }, icon_xy = { 5, 2 } }, desc_id = "menu_st_spec_4_desc", name_id = "menu_st_spec_4" }, { { cost = 200, desc_id = "menu_deck5_1_desc", name_id = "menu_deck5_1", upgrades = {"player_perk_armor_regen_timer_multiplier_1"}, icon_xy = { 6, 2 } }, deck2, { cost = 400, desc_id = "menu_deck5_3_desc", name_id = "menu_deck5_3", upgrades = { "player_perk_armor_regen_timer_multiplier_2", "akimbo_recoil_index_addend_4", "akimbo_extra_ammo_multiplier_2" }, icon_xy = { 7, 2 } }, deck4, { cost = 1000, desc_id = "menu_deck5_5_desc", name_id = "menu_deck5_5", upgrades = {"player_perk_armor_regen_timer_multiplier_3"}, icon_xy = { 0, 3 } }, deck6, { cost = 2400, desc_id = "menu_deck5_7_desc", name_id = "menu_deck5_7", upgrades = {"player_perk_armor_regen_timer_multiplier_4"}, icon_xy = { 1, 3 } }, deck8, { cost = 4000, desc_id = "menu_deck5_9_desc", name_id = "menu_deck5_9", upgrades = { "player_passive_loot_drop_multiplier", "player_perk_armor_regen_timer_multiplier_5", "player_passive_always_regen_armor_1" }, icon_xy = { 3, 3 } }, desc_id = "menu_st_spec_5_desc", name_id = "menu_st_spec_5" }, { { cost = 200, desc_id = "menu_deck6_1_desc", name_id = "menu_deck6_1", upgrades = {"player_passive_dodge_chance_1"}, icon_xy = { 1, 2 } }, deck2, { cost = 400, desc_id = "menu_deck6_3_desc", name_id = "menu_deck6_3", upgrades = { "player_level_2_dodge_addend_1", "player_level_3_dodge_addend_1", "player_level_4_dodge_addend_1", "player_level_2_armor_multiplier_1", "player_level_3_armor_multiplier_1", "player_level_4_armor_multiplier_1" }, icon_xy = { 4, 3 } }, deck4, { cost = 1000, desc_id = "menu_deck6_5_desc", name_id = "menu_deck6_5", upgrades = { "player_level_2_dodge_addend_2", "player_level_3_dodge_addend_2", "player_level_4_dodge_addend_2", "player_level_2_armor_multiplier_2", "player_level_3_armor_multiplier_2", "player_level_4_armor_multiplier_2" }, icon_xy = { 5, 3 } }, deck6, { cost = 2400, desc_id = "menu_deck6_7_desc", name_id = "menu_deck6_7", upgrades = { "player_level_2_dodge_addend_3", "player_level_3_dodge_addend_3", "player_level_4_dodge_addend_3", "player_level_2_armor_multiplier_3", "player_level_3_armor_multiplier_3", "player_level_4_armor_multiplier_3" }, icon_xy = { 6, 3 } }, deck8, { cost = 4000, desc_id = "menu_deck6_9_desc", name_id = "menu_deck6_9", upgrades = { "player_passive_loot_drop_multiplier", "player_armor_regen_timer_multiplier_tier" }, icon_xy = { 6, 2 } }, desc_id = "menu_st_spec_6_desc", name_id = "menu_st_spec_6" }, { { cost = 200, desc_id = "menu_deck7_1_desc", name_id = "menu_deck7_1", upgrades = {"player_tier_dodge_chance_1"}, icon_xy = { 1, 2 } }, deck2, { cost = 400, desc_id = "menu_deck7_3_desc", name_id = "menu_deck7_3", upgrades = { "player_stand_still_crouch_camouflage_bonus_1", "player_corpse_dispose_speed_multiplier" }, icon_xy = { 0, 4 } }, deck4, { cost = 1000, desc_id = "menu_deck7_5_desc", name_id = "menu_deck7_5", upgrades = { "player_tier_dodge_chance_2", "player_stand_still_crouch_camouflage_bonus_2", "player_pick_lock_speed_multiplier" }, icon_xy = { 7, 3 } }, deck6, { cost = 2400, desc_id = "menu_deck7_7_desc", name_id = "menu_deck7_7", upgrades = { "player_tier_dodge_chance_3", "player_stand_still_crouch_camouflage_bonus_3", "player_alarm_pager_speed_multiplier" }, icon_xy = { 1, 4 } }, deck8, { cost = 4000, desc_id = "menu_deck7_9_desc", name_id = "menu_deck7_9", upgrades = { "player_passive_loot_drop_multiplier", "player_armor_regen_timer_stand_still_multiplier", "player_crouch_speed_multiplier_2" }, icon_xy = { 2, 4 } }, name_id = "menu_st_spec_7", dlc = "character_pack_clover", desc_id = "menu_st_spec_7_desc" }, { { cost = 200, desc_id = "menu_deck8_7_desc", name_id = "menu_deck8_7", upgrades = { "player_damage_dampener_outnumbered_strong", "melee_stacking_hit_damage_multiplier_1" }, icon_xy = { 6, 4 } }, deck2, { cost = 400, desc_id = "menu_deck8_1_desc", name_id = "menu_deck8_1", upgrades = {"player_damage_dampener_close_contact_1"}, icon_xy = { 3, 4 } }, deck4, { cost = 1000, desc_id = "menu_deck8_3_desc", name_id = "menu_deck8_3", upgrades = { "player_damage_dampener_close_contact_2", "melee_stacking_hit_expire_t", "melee_stacking_hit_damage_multiplier_1" }, icon_xy = { 4, 4 } }, deck6, { cost = 2400, desc_id = "menu_deck8_3_desc", name_id = "menu_deck8_5", upgrades = {"player_damage_dampener_close_contact_3"}, icon_xy = { 5, 4 } }, deck8, { cost = 4000, desc_id = "menu_deck8_9_desc", name_id = "menu_deck8_9", upgrades = { "player_passive_loot_drop_multiplier", "player_melee_life_leech" }, icon_xy = { 7, 4 } }, name_id = "menu_st_spec_8", dlc = "character_pack_dragan", desc_id = "menu_st_spec_8_desc" }, { { cost = 200, desc_id = "menu_deck9_1_desc", name_id = "menu_deck9_1", upgrades = { "player_damage_dampener_outnumbered_strong", "melee_stacking_hit_damage_multiplier_1" }, icon_xy = { 6, 4 } }, deck2, { cost = 400, desc_id = "menu_deck9_3_desc", name_id = "menu_deck9_3", upgrades = { "player_killshot_regen_armor_bonus", "player_tier_armor_multiplier_1", "player_tier_armor_multiplier_2" }, icon_xy = { 0, 5 } }, deck4, { cost = 1000, desc_id = "menu_deck9_5_desc", name_id = "menu_deck9_5", upgrades = { "player_melee_kill_life_leech", "player_damage_dampener_close_contact_1" }, icon_xy = { 1, 5 } }, deck6, { cost = 2400, desc_id = "menu_deck9_7_desc", name_id = "menu_deck9_7", upgrades = { "player_killshot_close_regen_armor_bonus", "player_tier_armor_multiplier_3" }, icon_xy = { 2, 5 } }, deck8, { cost = 4000, desc_id = "menu_deck9_9_desc", name_id = "menu_deck9_9", upgrades = { "player_passive_loot_drop_multiplier", "player_killshot_close_panic_chance" }, icon_xy = { 3, 5 } }, name_id = "menu_st_spec_9", dlc = "hlm2_deluxe", desc_id = "menu_st_spec_9_desc" }, { { cost = 200, desc_id = "menu_deck10_1_desc", name_id = "menu_deck10_1", upgrades = { "temporary_loose_ammo_restore_health_1", "player_gain_life_per_players" }, icon_xy = { 4, 5 } }, deck2, { cost = 400, desc_id = "menu_deck10_3_desc", name_id = "menu_deck10_3", upgrades = { "temporary_loose_ammo_give_team", "player_passive_health_multiplier_1", "player_passive_health_multiplier_2" }, icon_xy = { 5, 5 } }, deck4, { cost = 1000, desc_id = "menu_deck10_5_desc", name_id = "menu_deck10_5", upgrades = { "player_loose_ammo_restore_health_give_team", "player_passive_health_multiplier_3" }, icon_xy = { 6, 5 } }, deck6, { cost = 2400, desc_id = "menu_deck10_7_desc", name_id = "menu_deck10_7", upgrades = {"temporary_loose_ammo_restore_health_2"}, icon_xy = { 7, 5 } }, deck8, { cost = 4000, desc_id = "menu_deck10_9_desc", name_id = "menu_deck10_9", upgrades = { "player_passive_loot_drop_multiplier", "temporary_loose_ammo_restore_health_3" }, icon_xy = { 0, 6 } }, desc_id = "menu_st_spec_10_desc", name_id = "menu_st_spec_10" }, { { cost = 200, desc_id = "menu_deck11_1_desc", name_id = "menu_deck11_1", upgrades = {"player_damage_to_hot_1"}, icon_xy = { 1, 6 } }, deck2, { cost = 400, desc_id = "menu_deck11_3_desc", name_id = "menu_deck11_3", upgrades = { "player_damage_to_hot_2", "player_passive_health_multiplier_1", "player_passive_health_multiplier_2" }, icon_xy = { 2, 6 } }, deck4, { cost = 1000, desc_id = "menu_deck11_5_desc", name_id = "menu_deck11_5", upgrades = { "player_damage_to_hot_3", "player_armor_piercing_chance_1" }, icon_xy = { 3, 6 } }, deck6, { cost = 2400, desc_id = "menu_deck11_7_desc", name_id = "menu_deck11_7", upgrades = { "player_damage_to_hot_4", "player_passive_health_multiplier_3" }, icon_xy = { 4, 6 } }, deck8, { cost = 4000, desc_id = "menu_deck11_9_desc", name_id = "menu_deck11_9", upgrades = { "player_passive_loot_drop_multiplier", "player_damage_to_hot_extra_ticks", "player_armor_piercing_chance_2" }, icon_xy = { 5, 6 } }, name_id = "menu_st_spec_11", dlc = "character_pack_sokol", desc_id = "menu_st_spec_11_desc" }, { { cost = 200, desc_id = "menu_deck12_1_desc", name_id = "menu_deck12_1", upgrades = {"player_armor_regen_damage_health_ratio_multiplier_1"}, icon_xy = { 6, 6 } }, deck2, { cost = 400, desc_id = "menu_deck12_3_desc", name_id = "menu_deck12_3", upgrades = {"player_movement_speed_damage_health_ratio_multiplier"}, icon_xy = { 7, 6 } }, deck4, { cost = 1000, desc_id = "menu_deck12_5_desc", name_id = "menu_deck12_5", upgrades = {"player_armor_regen_damage_health_ratio_multiplier_2"}, icon_xy = { 0, 7 } }, deck6, { cost = 2400, desc_id = "menu_deck12_7_desc", name_id = "menu_deck12_7", upgrades = {"player_armor_regen_damage_health_ratio_multiplier_3"}, icon_xy = { 1, 7 } }, deck8, { cost = 4000, desc_id = "menu_deck12_9_desc", name_id = "menu_deck12_9", upgrades = { "player_passive_loot_drop_multiplier", "player_armor_regen_damage_health_ratio_threshold_multiplier", "player_movement_speed_damage_health_ratio_threshold_multiplier" }, icon_xy = { 2, 7 } }, name_id = "menu_st_spec_12", dlc = "dragon", desc_id = "menu_st_spec_12_desc" }, { { cost = 200, desc_id = "menu_deck13_1_desc", name_id = "menu_deck13_1", upgrades = {"player_armor_health_store_amount_1"}, icon_xy = { 3, 7 } }, deck2, { cost = 400, desc_id = "menu_deck13_3_desc", name_id = "menu_deck13_3", upgrades = { "player_armor_health_store_amount_2", "player_passive_health_multiplier_1" }, icon_xy = { 4, 7 } }, deck4, { cost = 1000, desc_id = "menu_deck13_5_desc", name_id = "menu_deck13_5", upgrades = { "player_armor_max_health_store_multiplier", "player_passive_health_multiplier_2", "player_passive_dodge_chance_1" }, icon_xy = { 5, 7 } }, deck6, { cost = 2400, desc_id = "menu_deck13_7_desc", name_id = "menu_deck13_7", upgrades = { "player_armor_health_store_amount_3", "player_passive_health_multiplier_3" }, icon_xy = { 6, 7 } }, deck8, { cost = 4000, desc_id = "menu_deck13_9_desc", name_id = "menu_deck13_9", upgrades = { "player_passive_loot_drop_multiplier", "player_kill_change_regenerate_speed" }, icon_xy = { 7, 7 } }, desc_id = "menu_st_spec_13_desc", name_id = "menu_st_spec_13" }, { { cost = 200, texture_bundle_folder = "coco", desc_id = "menu_deck14_1_desc", name_id = "menu_deck14_1", upgrades = {"player_cocaine_stacking_1"}, icon_xy = { 0, 0 } }, deck2, { cost = 400, texture_bundle_folder = "coco", desc_id = "menu_deck14_3_desc", name_id = "menu_deck14_3", upgrades = {"player_sync_cocaine_stacks"}, icon_xy = { 1, 0 } }, deck4, { cost = 1000, texture_bundle_folder = "coco", desc_id = "menu_deck14_5_desc", name_id = "menu_deck14_5", upgrades = {"player_cocaine_stacks_decay_multiplier_1"}, icon_xy = { 2, 0 } }, deck6, { cost = 2400, texture_bundle_folder = "coco", desc_id = "menu_deck14_7_desc", name_id = "menu_deck14_7", upgrades = {"player_sync_cocaine_upgrade_level_1"}, icon_xy = { 3, 0 } }, deck8, { cost = 4000, texture_bundle_folder = "coco", desc_id = "menu_deck14_9_desc", name_id = "menu_deck14_9", upgrades = { "player_passive_loot_drop_multiplier", "player_cocaine_stack_absorption_multiplier_1" }, icon_xy = { 0, 1 } }, desc_id = "menu_st_spec_14_desc", name_id = "menu_st_spec_14" }, { { cost = 200, texture_bundle_folder = "opera", desc_id = "menu_deck15_1_desc", name_id = "menu_deck15_1", upgrades = { "player_armor_grinding_1", "temporary_armor_break_invulnerable_1" }, icon_xy = { 0, 0 } }, deck2, { cost = 400, texture_bundle_folder = "opera", desc_id = "menu_deck15_3_desc", name_id = "menu_deck15_3", upgrades = { "player_health_decrease_1", "player_armor_increase_1" }, icon_xy = { 1, 0 } }, deck4, { cost = 1000, texture_bundle_folder = "opera", desc_id = "menu_deck15_5_desc", name_id = "menu_deck15_5", upgrades = {"player_armor_increase_2"}, icon_xy = { 2, 0 } }, deck6, { cost = 2400, texture_bundle_folder = "opera", desc_id = "menu_deck15_7_desc", name_id = "menu_deck15_7", upgrades = {"player_armor_increase_3"}, icon_xy = { 3, 0 } }, deck8, { cost = 4000, texture_bundle_folder = "opera", desc_id = "menu_deck15_9_desc", name_id = "menu_deck15_9", upgrades = { "player_passive_loot_drop_multiplier", "player_damage_to_armor_1" }, icon_xy = { 0, 1 } }, name_id = "menu_st_spec_15", dlc = "opera", desc_id = "menu_st_spec_15_desc" }, { { cost = 200, texture_bundle_folder = "wild", desc_id = "menu_deck16_1_desc", name_id = "menu_deck16_1", upgrades = { "player_wild_health_amount_1", "player_wild_armor_amount_1" }, icon_xy = { 0, 0 } }, deck2, { cost = 400, texture_bundle_folder = "wild", desc_id = "menu_deck16_3_desc", name_id = "menu_deck16_3", upgrades = {"player_less_health_wild_armor_1"}, icon_xy = { 1, 0 } }, deck4, { cost = 1000, texture_bundle_folder = "wild", desc_id = "menu_deck16_5_desc", name_id = "menu_deck16_5", upgrades = {"player_less_health_wild_cooldown_1"}, icon_xy = { 2, 0 } }, deck6, { cost = 2400, texture_bundle_folder = "wild", desc_id = "menu_deck16_7_desc", name_id = "menu_deck16_7", upgrades = {"player_less_armor_wild_health_1"}, icon_xy = { 3, 0 } }, deck8, { cost = 4000, texture_bundle_folder = "wild", desc_id = "menu_deck16_9_desc", name_id = "menu_deck16_9", upgrades = { "player_passive_loot_drop_multiplier", "player_less_armor_wild_cooldown_1" }, icon_xy = { 0, 1 } }, name_id = "menu_st_spec_16", dlc = "wild", desc_id = "menu_st_spec_16_desc" }, { { cost = 200, texture_bundle_folder = "chico", desc_id = "menu_deck17_1_desc", name_id = "menu_deck17_1", upgrades = { "temporary_chico_injector_1", "chico_injector" }, icon_xy = { 0, 0 } }, deck2, { cost = 400, texture_bundle_folder = "chico", desc_id = "menu_deck17_3_desc", name_id = "menu_deck17_3", upgrades = {"player_passive_health_multiplier_1"}, icon_xy = { 1, 0 } }, deck4, { cost = 1000, texture_bundle_folder = "chico", desc_id = "menu_deck17_5_desc", name_id = "menu_deck17_5", upgrades = { "player_chico_preferred_target", "player_passive_health_multiplier_2" }, icon_xy = { 2, 0 } }, deck6, { cost = 2400, texture_bundle_folder = "chico", desc_id = "menu_deck17_7_desc", name_id = "menu_deck17_7", upgrades = { "player_passive_health_multiplier_3", "player_chico_injector_low_health_multiplier" }, icon_xy = { 3, 0 } }, deck8, { cost = 4000, texture_bundle_folder = "chico", desc_id = "menu_deck17_9_desc", name_id = "menu_deck17_9", upgrades = { "player_passive_loot_drop_multiplier", "player_passive_health_multiplier_4", "player_chico_injector_health_to_speed" }, icon_xy = { 0, 1 } }, name_id = "menu_st_spec_17", dlc = "chico", desc_id = "menu_st_spec_17_desc" }, { { cost = 200, texture_bundle_folder = "max", desc_id = "menu_deck18_1_desc", name_id = "menu_deck18_1", upgrades = {"smoke_screen_grenade"}, icon_xy = { 0, 0 } }, deck2, { cost = 400, texture_bundle_folder = "max", desc_id = "menu_deck18_3_desc", name_id = "menu_deck18_3", upgrades = {"player_dodge_shot_gain"}, icon_xy = { 1, 0 } }, deck4, { cost = 1000, texture_bundle_folder = "max", desc_id = "menu_deck18_5_desc", name_id = "menu_deck18_5", upgrades = {"player_passive_dodge_chance_1"}, icon_xy = { 2, 0 } }, deck6, { cost = 2400, texture_bundle_folder = "max", desc_id = "menu_deck18_7_desc", name_id = "menu_deck18_7", upgrades = {"player_dodge_replenish_armor"}, icon_xy = { 3, 0 } }, deck8, { cost = 4000, texture_bundle_folder = "max", desc_id = "menu_deck18_9_desc", name_id = "menu_deck18_9", upgrades = { "player_passive_loot_drop_multiplier", "player_smoke_screen_ally_dodge_bonus", "player_sicario_multiplier" }, icon_xy = { 0, 1 } }, desc_id = "menu_st_spec_18_desc", name_id = "menu_st_spec_18" }, { { cost = 200, texture_bundle_folder = "myh", desc_id = "menu_deck19_1_desc", name_id = "menu_deck19_1", upgrades = { "damage_control", "player_damage_control_passive", "player_damage_control_cooldown_drain_1" }, icon_xy = { 0, 0 } }, deck2, { cost = 400, texture_bundle_folder = "myh", desc_id = "menu_deck19_3_desc", name_id = "menu_deck19_3", upgrades = {"player_armor_to_health_conversion"}, icon_xy = { 1, 0 } }, deck4, { cost = 1000, texture_bundle_folder = "myh", desc_id = "menu_deck19_5_desc", name_id = "menu_deck19_5", upgrades = {"player_damage_control_auto_shrug"}, icon_xy = { 2, 0 } }, deck6, { cost = 2400, texture_bundle_folder = "myh", desc_id = "menu_deck19_7_desc", name_id = "menu_deck19_7", upgrades = {"player_damage_control_cooldown_drain_2"}, icon_xy = { 3, 0 } }, deck8, { cost = 4000, texture_bundle_folder = "myh", desc_id = "menu_deck19_9_desc", name_id = "menu_deck19_9", upgrades = { "player_passive_loot_drop_multiplier", "player_damage_control_healing" }, icon_xy = { 0, 1 } }, desc_id = "menu_st_spec_19_desc", name_id = "menu_st_spec_19" }, { { cost = 200, texture_bundle_folder = "ecp", desc_id = "menu_deck20_1_desc", name_id = "menu_deck20_1", upgrades = { "tag_team", "player_tag_team_base", "player_tag_team_cooldown_drain_1" }, icon_xy = { 0, 0 } }, deck2, { cost = 400, texture_bundle_folder = "ecp", desc_id = "menu_deck20_3_desc", name_id = "menu_deck20_3", upgrades = { "player_passive_health_multiplier_1", "player_passive_health_multiplier_2" }, icon_xy = { 1, 0 } }, deck4, { cost = 1000, texture_bundle_folder = "ecp", desc_id = "menu_deck20_5_desc", name_id = "menu_deck20_5", upgrades = {"player_tag_team_damage_absorption"}, icon_xy = { 2, 0 } }, deck6, { cost = 2400, texture_bundle_folder = "ecp", desc_id = "menu_deck20_7_desc", name_id = "menu_deck20_7", upgrades = {"player_passive_health_multiplier_3"}, icon_xy = { 3, 0 } }, deck8, { cost = 4000, texture_bundle_folder = "ecp", desc_id = "menu_deck20_9_desc", name_id = "menu_deck20_9", upgrades = { "player_passive_loot_drop_multiplier", "player_tag_team_cooldown_drain_2" }, icon_xy = { 0, 1 } }, name_id = "menu_st_spec_20", dlc = "ecp", desc_id = "menu_st_spec_20_desc" }, { { cost = 200, texture_bundle_folder = "joy", desc_id = "menu_deck21_1_desc", name_id = "menu_deck21_1", upgrades = { "pocket_ecm_jammer", "player_pocket_ecm_jammer_base" }, icon_xy = { 0, 0 } }, deck2, { cost = 400, texture_bundle_folder = "joy", desc_id = "menu_deck21_3_desc", name_id = "menu_deck21_3", upgrades = { "player_passive_health_multiplier_1", "player_passive_health_multiplier_2" }, icon_xy = { 1, 0 } }, deck4, { cost = 1000, texture_bundle_folder = "joy", desc_id = "menu_deck21_5_desc", name_id = "menu_deck21_5", upgrades = { "player_pocket_ecm_heal_on_kill_1", "player_passive_dodge_chance_1" }, icon_xy = { 2, 0 } }, deck6, { cost = 2400, texture_bundle_folder = "joy", desc_id = "menu_deck21_7_desc", name_id = "menu_deck21_7", upgrades = { "player_pocket_ecm_kill_dodge_1" }, icon_xy = { 3, 0 } }, deck8, { cost = 4000, texture_bundle_folder = "joy", desc_id = "menu_deck21_9_desc", name_id = "menu_deck21_9", upgrades = { "player_passive_loot_drop_multiplier", "team_pocket_ecm_heal_on_kill_1", "player_passive_dodge_chance_2" }, icon_xy = { 0, 1 } }, desc_id = "menu_st_spec_21_desc", name_id = "menu_st_spec_21" } } end -- Lines: 1685 to 1700 function SkillTreeTweakData:get_tier_position_from_skill_name(skill_name) for tree_idx in pairs(self.trees) do local count = 0 local tree = self.trees[tree_idx] for tier_idx in pairs(tree.tiers) do count = count + 1 local tier = tree.tiers[tier_idx] for skill_idx in pairs(tier) do if skill_name == tier[skill_idx] then return count end end end end return -1 end -- Lines: 1703 to 1711 function SkillTreeTweakData:get_tree(tree_name) local list = {} for i, tree in ipairs(self.trees) do if tree.skill == tree_name then table.insert(list, tree) end end return list end -- Lines: 1714 to 1716 function SkillTreeTweakData:get_tiers(tree_idx) local tiers = deep_clone(self.trees[tree_idx].tiers) return tiers end -- Lines: 1719 to 1726 function SkillTreeTweakData:get_tier_unlocks() -- Lines: 1719 to 1720 local function digest(value) return Application:digest_value(value, false) end local tier_unlocks = self.tier_unlocks local unlock_values = {} for i = 1, #tier_unlocks, 1 do table.insert(unlock_values, digest(tier_unlocks[i])) end return unlock_values end -- Lines: 1729 to 1751 function SkillTreeTweakData:get_specialization_icon_data(spec, no_fallback) spec = spec or managers.skilltree:get_specialization_value("current_specialization") print(spec, type(spec)) local data = tweak_data.skilltree.specializations[spec] local max_tier = managers.skilltree:get_specialization_value(spec, "tiers", "max_tier") local tier_data = data and data[max_tier] if not tier_data then if no_fallback then return else print("fallback") return tweak_data.hud_icons:get_icon_data("fallback") end end local guis_catalog = "guis/" .. (tier_data.texture_bundle_folder and "dlcs/" .. tostring(tier_data.texture_bundle_folder) .. "/" or "") local x = tier_data.icon_xy and tier_data.icon_xy[1] or 0 local y = tier_data.icon_xy and tier_data.icon_xy[2] or 0 return guis_catalog .. "textures/pd2/specialization/icons_atlas", { x * 64, y * 64, 64, 64 } end
local PistolIdle = class("PistolIdle", PlayerActState) function PistolIdle:OnEnter() PlayerActState.OnEnter(self) localPlayer:MoveTowards(Vector2.Zero) end function PistolIdle:OnUpdate(dt) PlayerActState.OnUpdate(self, dt) localPlayer:MoveTowards(Vector2.Zero) FsmMgr.playerActFsm:TriggerMonitor({"Idle", "PistolIdle", "SwimIdle", "PistolHit", "Vertigo"}) end function PistolIdle:OnLeave() PlayerActState.OnLeave(self) end return PistolIdle
local Settings = { LOGGER = { -- Logger Settings ACTIVATED = true, -- Toggles if logger is activated WRITE_FILE = true, -- Toggles if logger can write the login a file FILE_PATH = "./" -- The log file path } } return Settings
local AddOnName, Engine = ... local _G = _G local math_max = _G.math.max local math_min = _G.math.min local string_format = _G.string.format local string_lower = _G.string.lower local string_match = _G.string.match local table_insert = _G.table.insert local tonumber = _G.tonumber local unpack = _G.unpack local CUSTOM_CLASS_COLORS = _G.CUSTOM_CLASS_COLORS local CombatLogGetCurrentEventInfo = _G.CombatLogGetCurrentEventInfo local CreateFrame = _G.CreateFrame local GetAddOnEnableState = _G.GetAddOnEnableState local GetAddOnInfo = _G.GetAddOnInfo local GetAddOnMetadata = _G.GetAddOnMetadata local GetBuildInfo = _G.GetBuildInfo local GetCVar = _G.GetCVar local GetCurrentResolution = _G.GetCurrentResolution local GetLocale = _G.GetLocale local GetNumAddOns = _G.GetNumAddOns local GetRealmName = _G.GetRealmName local GetScreenResolutions = _G.GetScreenResolutions local LOCALIZED_CLASS_NAMES_MALE = _G.LOCALIZED_CLASS_NAMES_MALE local LibStub = _G.LibStub local RAID_CLASS_COLORS = _G.RAID_CLASS_COLORS local UnitClass = _G.UnitClass local UnitFactionGroup = _G.UnitFactionGroup local UnitLevel = _G.UnitLevel local UnitName = _G.UnitName local UnitRace = _G.UnitRace -- Engine Engine[1] = {} -- K, Main Engine[2] = {} -- C, Config Engine[3] = {} -- L, Locales local K = unpack(Engine) K.LibClassicDurations = LibStub("LibClassicDurations") K.LibClassicDurations:RegisterFrame("KkthnxUI") K.Title = GetAddOnMetadata(AddOnName, "Title") K.Version = GetAddOnMetadata(AddOnName, "Version") K.Credits = GetAddOnMetadata(AddOnName, "X-Credits") K.Noop = function() return end K.Name = UnitName("player") K.LocalizedClass, K.Class, K.ClassID = UnitClass("player") K.LocalizedRace, K.Race = UnitRace("player") K.Faction, K.LocalizedFaction = UnitFactionGroup("player") K.Level = UnitLevel("player") K.Client = GetLocale() K.Realm = GetRealmName() K.oUF = Engine.oUF K.Media = "Interface\\AddOns\\KkthnxUI\\Media\\" K.LSM = LibStub and LibStub:GetLibrary("LibSharedMedia-3.0", true) K.Resolution = ({GetScreenResolutions()})[GetCurrentResolution()] or GetCVar("gxWindowedResolution") K.ScreenHeight = tonumber(string_match(K.Resolution, "%d+x(%d+)")) K.ScreenWidth = tonumber(string_match(K.Resolution, "(%d+)x+%d")) K.UIScale = math_min(2, math_max(0.01, 768 / string_match(K.Resolution, "%d+x(%d+)"))) K.PriestColors = {r = 0.86, g = 0.92, b = 0.98, colorStr = "dbebfa"} -- Keep this until I convert the rest. -- K.Color = K.Class == "PRIEST" and K.PriestColors or (CUSTOM_CLASS_COLORS and CUSTOM_CLASS_COLORS[K.Class] or RAID_CLASS_COLORS[K.Class]) K.TexCoords = {0.08, 0.92, 0.08, 0.92} K.Welcome = "|cff4488ffKkthnxUI "..K.Version.." "..K.Client.."|r - /helpui" K.ScanTooltip = CreateFrame("GameTooltip", "KkthnxUI_ScanTooltip", _G.UIParent, "GameTooltipTemplate") K.WowPatch, K.WowBuild, K.WowRelease, K.TocVersion = GetBuildInfo() K.WowBuild = tonumber(K.WowBuild) K.InfoColor = "|cff4488ff" K.CodeDebug = false -- Don't touch this, unless you know what you are doing? K.ClassList = {} for k, v in pairs(LOCALIZED_CLASS_NAMES_MALE) do K.ClassList[v] = k end K.ClassColors = {} -- PRIEST ClassColor RAID_CLASS_COLORS["PRIEST"].r = 0.86 RAID_CLASS_COLORS["PRIEST"].g = 0.92 RAID_CLASS_COLORS["PRIEST"].b = 0.98 RAID_CLASS_COLORS["PRIEST"].colorStr = "ffdbebfa" -- SHAMAN ClassColor RAID_CLASS_COLORS["SHAMAN"].r = 0 RAID_CLASS_COLORS["SHAMAN"].g = .44 RAID_CLASS_COLORS["SHAMAN"].b = .87 RAID_CLASS_COLORS["SHAMAN"].colorStr = "ff0070dd" local colors = CUSTOM_CLASS_COLORS or RAID_CLASS_COLORS for class, value in pairs(colors) do K.ClassColors[class] = {} K.ClassColors[class].r = value.r K.ClassColors[class].g = value.g K.ClassColors[class].b = value.b K.ClassColors[class].colorStr = value.colorStr end K.r, K.g, K.b = K.ClassColors[K.Class].r, K.ClassColors[K.Class].g, K.ClassColors[K.Class].b K.MyClassColor = string_format("|cff%02x%02x%02x", K.r * 255, K.g * 255, K.b * 255) local events = {} local host = CreateFrame("Frame") local modules, initQueue = {}, {} host:SetScript("OnEvent", function(_, event, ...) for func in pairs(events[event]) do if event == "COMBAT_LOG_EVENT_UNFILTERED" then func(event, CombatLogGetCurrentEventInfo()) else func(event, ...) end end end) function K:RegisterEvent(event, func, unit1, unit2) if not events[event] then events[event] = {} if unit1 then host:RegisterUnitEvent(event, unit1, unit2) else host:RegisterEvent(event) end end events[event][func] = true end function K:UnregisterEvent(event, func) local funcs = events[event] if funcs and funcs[func] then funcs[func] = nil if not next(funcs) then events[event] = nil host:UnregisterEvent(event) end end end -- Modules function K:NewModule(name) if modules[name] then print("Module <"..name.."> has been registered.") return end local module = {} module.name = name modules[name] = module table_insert(initQueue, module) return module end function K:GetModule(name) if not modules[name] then print("Module <"..name.."> does not exist.") return end return modules[name] end K:RegisterEvent("PLAYER_LOGIN", function() for _, module in next, initQueue do if module.OnEnable then module:OnEnable() else print("Module <"..module.name.."> does not loaded.") end end K.Modules = modules end) local function PositionGameMenuButton() GameMenuFrame:SetHeight(GameMenuFrame:GetHeight() + GameMenuButtonLogout:GetHeight()) local _, relTo, _, _, offY = GameMenuButtonLogout:GetPoint() if relTo ~= GameMenuFrame[AddOnName] then GameMenuFrame[AddOnName]:ClearAllPoints() GameMenuFrame[AddOnName]:SetPoint("TOPLEFT", relTo, "BOTTOMLEFT", 0, -1) GameMenuButtonLogout:ClearAllPoints() GameMenuButtonLogout:SetPoint("TOPLEFT", GameMenuFrame[AddOnName], "BOTTOMLEFT", 0, offY) end end -- Got to check for addon name, or this will fire for ALL addons, creating a ton of buttons! K:RegisterEvent("ADDON_LOADED", function(_, addon) if (addon ~= AddOnName) then return end K.GUID = UnitGUID("player") K.CreateStaticPopups() -- KkthnxUI GameMenu Button. local GameMenuButton = CreateFrame("Button", nil, GameMenuFrame, "GameMenuButtonTemplate") GameMenuButton:SetText(string_format("|cff4488ff%s|r", AddOnName)) GameMenuButton:SetScript("OnClick", function() if (not KkthnxUIConfigFrame) then KkthnxUIConfig:CreateConfigWindow() end if KkthnxUIConfigFrame:IsVisible() then KkthnxUIConfigFrame:Hide() else KkthnxUIConfigFrame:Show() end HideUIPanel(GameMenuFrame) end) GameMenuFrame[AddOnName] = GameMenuButton if not IsAddOnLoaded("ConsolePortUI_Menu") then GameMenuButton:SetSize(GameMenuButtonLogout:GetWidth(), GameMenuButtonLogout:GetHeight()) GameMenuButton:SetPoint("TOPLEFT", GameMenuButtonAddons, "BOTTOMLEFT", 0, -1) hooksecurefunc("GameMenuFrame_UpdateVisibleButtons", PositionGameMenuButton) end end) -- Event return values were wrong: https://wow.gamepedia.com/PLAYER_LEVEL_UP K:RegisterEvent("PLAYER_LEVEL_UP", function(_, level) if not K.Level then return end K.Level = level end) K.AddOns = {} K.AddOnVersion = {} for i = 1, GetNumAddOns() do local Name = GetAddOnInfo(i) K.AddOns[string_lower(Name)] = GetAddOnEnableState(K.Name, Name) == 2 K.AddOnVersion[string_lower(Name)] = GetAddOnMetadata(Name, "Version") end do K.AboutPanel = CreateFrame("Frame", nil, _G.InterfaceOptionsFramePanelContainer) K.AboutPanel:Hide() K.AboutPanel.name = K.Title K.AboutPanel:SetScript("OnShow", function(self) if self.show then return end local titleInfo = self:CreateFontString(nil, "ARTWORK", "GameFontNormalLarge") titleInfo:SetPoint("TOPLEFT", 16, -16) titleInfo:SetText("Info:") local subInfo = self:CreateFontString(nil, "ARTWORK", "GameFontHighlight") subInfo:SetWidth(580) subInfo:SetPoint("TOPLEFT", titleInfo, "BOTTOMLEFT", 0, -8) subInfo:SetJustifyH("LEFT") subInfo:SetText(GetAddOnMetadata("KkthnxUI", "Notes")) local titleCredits = self:CreateFontString(nil, "ARTWORK", "GameFontNormalLarge") titleCredits:SetPoint("TOPLEFT", subInfo, "BOTTOMLEFT", 0, -8) titleCredits:SetText("Credits:") local subCredits = self:CreateFontString(nil, "ARTWORK", "GameFontHighlight") subCredits:SetWidth(580) subCredits:SetPoint("TOPLEFT", titleCredits, "BOTTOMLEFT", 0, -8) subCredits:SetJustifyH("LEFT") subCredits:SetText(GetAddOnMetadata("KkthnxUI", "X-Credits")) local titleThanks = self:CreateFontString(nil, "ARTWORK", "GameFontNormalLarge") titleThanks:SetPoint("TOPLEFT", subCredits, "BOTTOMLEFT", 0, -16) titleThanks:SetText("Special Thanks:") local subThanks = self:CreateFontString(nil, "ARTWORK", "GameFontHighlight") subThanks:SetWidth(580) subThanks:SetPoint("TOPLEFT", titleThanks, "BOTTOMLEFT", 0, -8) subThanks:SetJustifyH("LEFT") subThanks:SetText(GetAddOnMetadata("KkthnxUI", "X-Thanks")) local titleLocalizations = self:CreateFontString(nil, "ARTWORK", "GameFontNormalLarge") titleLocalizations:SetPoint("TOPLEFT", subThanks, "BOTTOMLEFT", 0, -16) titleLocalizations:SetText("Translation:") local subLocalizations = self:CreateFontString(nil, "ARTWORK", "GameFontHighlight") subLocalizations:SetWidth(580) subLocalizations:SetPoint("TOPLEFT", titleLocalizations, "BOTTOMLEFT", 0, -8) subLocalizations:SetJustifyH("LEFT") subLocalizations:SetText(GetAddOnMetadata("KkthnxUI", "X-Localizations")) -- Social Buttion, because why not? local titleButtons = self:CreateFontString(nil, "ARTWORK", "GameFontNormalLarge") titleButtons:SetPoint("TOPLEFT", subLocalizations, "BOTTOMLEFT", 0, -16) titleButtons:SetText("Keep Calm I'm Adding Buttons:") local buttonGitHub = CreateFrame("Button", nil, self, "UIPanelButtonTemplate") buttonGitHub:SetSize(100, 22) buttonGitHub:SetPoint("TOPLEFT", titleButtons, "BOTTOMLEFT", 0, -8) buttonGitHub:SkinButton() buttonGitHub:SetScript("OnClick", function() K.StaticPopup_Show("GITHUB_EDITBOX", nil, nil, "https://github.com/kkthnx-wow/KkthnxUI_8.0.1") end) buttonGitHub.Text = buttonGitHub:CreateFontString(nil, "OVERLAY", "GameFontHighlight") buttonGitHub.Text:SetPoint("CENTER", buttonGitHub) buttonGitHub.Text:SetText("|cffffd100".."GitHub".."|r") local buttonBugReport = CreateFrame("Button", nil, self, "UIPanelButtonTemplate") buttonBugReport:SetSize(100, 22) buttonBugReport:SetPoint("LEFT", buttonGitHub, "RIGHT", 6, 0) buttonBugReport:SkinButton() buttonBugReport:SetScript("OnClick", function() K.StaticPopup_Show("GITHUB_EDITBOX", nil, nil, "https://github.com/kkthnx-wow/KkthnxUI_8.0.1/issues/new") end) buttonBugReport.Text = buttonBugReport:CreateFontString(nil, "OVERLAY", "GameFontHighlight") buttonBugReport.Text:SetPoint("CENTER", buttonBugReport) buttonBugReport.Text:SetText("|cffffd100".."Bug Report".."|r") local buttonDiscord = CreateFrame("Button", nil, self, "UIPanelButtonTemplate") buttonDiscord:SetSize(100, 22) buttonDiscord:SetPoint("LEFT", buttonBugReport, "RIGHT", 6, 0) buttonDiscord:SkinButton() buttonDiscord:SetScript("OnClick", function() K.StaticPopup_Show("GITHUB_EDITBOX", nil, nil, "https://discordapp.com/invite/mKKySTY") end) buttonDiscord.Text = buttonDiscord:CreateFontString(nil, "OVERLAY", "GameFontHighlight") buttonDiscord.Text:SetPoint("CENTER", buttonDiscord) buttonDiscord.Text:SetText("|cffffd100".."Discord".."|r") local buttonFacebook = CreateFrame("Button", nil, self, "UIPanelButtonTemplate") buttonFacebook:SetSize(100, 22) buttonFacebook:SetPoint("LEFT", buttonDiscord, "RIGHT", 6, 0) buttonFacebook:SkinButton() buttonFacebook:SetScript("OnClick", function() K.StaticPopup_Show("GITHUB_EDITBOX", nil, nil, "https://www.facebook.com/kkthnxui") end) buttonFacebook.Text = buttonFacebook:CreateFontString(nil, "OVERLAY", "GameFontHighlight") buttonFacebook.Text:SetPoint("CENTER", buttonFacebook) buttonFacebook.Text:SetText("|cff3C5A99".."Facebook".."|r") local buttonTwitter = CreateFrame("Button", nil, self, "UIPanelButtonTemplate") buttonTwitter:SetSize(100, 22) buttonTwitter:SetPoint("LEFT", buttonFacebook, "RIGHT", 6, 0) buttonTwitter:SkinButton() buttonTwitter:SetScript("OnClick", function() K.StaticPopup_Show("GITHUB_EDITBOX", nil, nil, "https://twitter.com/KkthnxUI") end) buttonTwitter.Text = buttonTwitter:CreateFontString(nil, "OVERLAY", "GameFontHighlight") buttonTwitter.Text:SetPoint("CENTER", buttonTwitter) buttonTwitter.Text:SetText("|cff38A1F3".."Twitter".."|r") local interfaceVersion = self:CreateFontString(nil, "ARTWORK", "GameFontNormal") interfaceVersion:SetPoint("BOTTOMRIGHT", -16, 16) interfaceVersion:SetText("Version: "..K.Version) self.show = true end) K.AboutPanel.Commands = CreateFrame( "Frame", nil, K.AboutPanel) K.AboutPanel.Commands.name = "Commands" K.AboutPanel.Commands:Hide() K.AboutPanel.Commands.parent = K.AboutPanel.name K.AboutPanel.Questions = CreateFrame( "Frame", nil, K.AboutPanel) K.AboutPanel.Questions.name = "Questions" K.AboutPanel.Questions:Hide() K.AboutPanel.Questions.parent = K.AboutPanel.name _G.InterfaceOptions_AddCategory(K.AboutPanel) _G.InterfaceOptions_AddCategory(K.AboutPanel.Commands) _G.InterfaceOptions_AddCategory(K.AboutPanel.Questions) end _G[AddOnName] = Engine
TTS.Shop.modules = { module = {} } local MODULE = {} MODULE.__index = MODULE function TTS.Shop.modules.Register( mod ) local out = setmetatable(mod, MODULE) TTS.Shop.modules.Delete( mod.ID ) TTS.Shop.modules.module[mod.ID] = out hook.Run('TTS.Shop::RegisterModule', mod) end function TTS.Shop.modules.Delete( id ) TTS.Shop.modules.module[id] = nil end function TTS.Shop.modules.GetList() return TTS.Shop.modules.module end function TTS.Shop.modules.Get( id ) return TTS.Shop.modules.module[id] end function MODULE:GetID() return self.ID end function MODULE:GetName() return self.Name end function MODULE:TopButton( pnl ) if pnl then pnl:SetVisible( false ) pnl:InvalidateParent() if IsValid( pnl.m_button ) then pnl.m_button:Remove() end if self.TopFillButton then pnl:SetVisible(true) self:TopFillButton( pnl ) end end //return self.TopButton and self.TopButton( pnl ) or false end function MODULE:SidebarButton( pnl, category_id ) if pnl then for i, v in pairs(pnl:GetChildren()) do v:Remove() end if self.CategoryItemsFill then self:CategoryItemsFill( pnl, category_id ) end end end function MODULE:SidebarClearButton( pnl, category_id ) if pnl then if self.SidebarRemoveButton then self:SidebarRemoveButton( pnl, category_id ) else pnl:Remove() end end end MOD_POINTSHOP = 1 MOD_TTSHOP = 2 MOD_INV = 3 TTS.LoadSH('pointshop_inv/sh_init.lua') TTS.LoadSH('pointshop_shop/sh_init.lua') TTS.LoadSH('ttshop/sh_init.lua')
-- https://stackoverflow.com/questions/12069109/getting-input-from-the-user-in-lua -- https://www.lua.org/pil/4.3.1.html io.write("What's you name? ") inputName = io.read() if inputName == "" then inputName = "Jakob" end io.write("Type in a number, " .. inputName .. " ") inputVar1 = io.read("*n") io.write("Type in another number, " .. inputName .. " ") inputVar2 = io.read("*n") io.write("Now add " .. inputVar1 .. " and " .. inputVar2 .." = ") inputSum = io.read("*n") if inputSum == inputVar2 + inputVar1 then print("Good job " .. inputName .. "!") else print("Incorrect answer " .. inputName .. "!") print("Correct answer is: " .. (inputVar2 + inputVar1)) end
--- Installs runtime metalua support. package.path = "/usr/share/lua/5.1/?.luac;/usr/local/lib/lua/5.1/?.luac;" .. package.path require "metalua.compiler" --- Like lua's require(), but loading sources as metalua instead. -- @param path function mrequire(path) if package.loaded[path] then return package.loaded[path] end local file = mlc.luafile_to_function(path .. ".lua") package.loaded[path] = file return file() end mrequire "src/meta/reference"
include('shared.lua') SWEP.PrintName = "Scripted Weapon" -- 'Nice' Weapon name (Shown on HUD) SWEP.Slot = 0 -- Slot in the weapon selection menu SWEP.SlotPos = 10 -- Position in the slot SWEP.DrawAmmo = true -- Should draw the default HL2 ammo counter SWEP.DrawCrosshair = true -- Should draw the default crosshair SWEP.DrawWeaponInfoBox = true -- Should draw the weapon info box SWEP.BounceWeaponIcon = true -- Should the weapon icon bounce? SWEP.SwayScale = 1.0 -- The scale of the viewmodel sway SWEP.BobScale = 1.0 -- The scale of the viewmodel bob SWEP.RenderGroup = RENDERGROUP_OPAQUE -- Override this in your SWEP to set the icon in the weapon selection SWEP.WepSelectIcon = surface.GetTextureID( "weapons/swep" ) -- This is the corner of the speech bubble SWEP.SpeechBubbleLid = surface.GetTextureID( "gui/speech_lid" ) --[[--------------------------------------------------------- You can draw to the HUD here - it will only draw when the client has the weapon deployed.. -----------------------------------------------------------]] function SWEP:DrawHUD() end --[[--------------------------------------------------------- Checks the objects before any action is taken This is to make sure that the entities haven't been removed -----------------------------------------------------------]] function SWEP:DrawWeaponSelection( x, y, wide, tall, alpha ) -- Set us up the texture surface.SetDrawColor( 255, 255, 255, alpha ) surface.SetTexture( self.WepSelectIcon ) -- Lets get a sin wave to make it bounce local fsin = 0 if ( self.BounceWeaponIcon == true ) then fsin = math.sin( CurTime() * 10 ) * 5 end -- Borders y = y + 10 x = x + 10 wide = wide - 20 -- Draw that mother surface.DrawTexturedRect( x + (fsin), y - (fsin), wide-fsin*2 , ( wide / 2 ) + (fsin) ) -- Draw weapon info box self:PrintWeaponInfo( x + wide + 20, y + tall * 0.95, alpha ) end --[[--------------------------------------------------------- This draws the weapon info box -----------------------------------------------------------]] function SWEP:PrintWeaponInfo( x, y, alpha ) if ( self.DrawWeaponInfoBox == false ) then return end if (self.InfoMarkup == nil ) then local str local title_color = "<color=230,230,230,255>" local text_color = "<color=150,150,150,255>" str = "<font=HudSelectionText>" if ( self.Author != "" ) then str = str .. title_color .. "Author:</color>\t"..text_color..self.Author.."</color>\n" end if ( self.Contact != "" ) then str = str .. title_color .. "Contact:</color>\t"..text_color..self.Contact.."</color>\n\n" end if ( self.Purpose != "" ) then str = str .. title_color .. "Purpose:</color>\n"..text_color..self.Purpose.."</color>\n\n" end if ( self.Instructions != "" ) then str = str .. title_color .. "Instructions:</color>\n"..text_color..self.Instructions.."</color>\n" end str = str .. "</font>" self.InfoMarkup = markup.Parse( str, 250 ) end surface.SetDrawColor( 60, 60, 60, alpha ) surface.SetTexture( self.SpeechBubbleLid ) surface.DrawTexturedRect( x, y - 64 - 5, 128, 64 ) draw.RoundedBox( 8, x - 5, y - 6, 260, self.InfoMarkup:GetHeight() + 18, Color( 60, 60, 60, alpha ) ) self.InfoMarkup:Draw( x+5, y+5, nil, nil, alpha ) end --[[--------------------------------------------------------- Name: SWEP:FreezeMovement() Desc: Return true to freeze moving the view -----------------------------------------------------------]] function SWEP:FreezeMovement() return false end --[[--------------------------------------------------------- Name: SWEP:ViewModelDrawn( ViewModel ) Desc: Called straight after the viewmodel has been drawn -----------------------------------------------------------]] function SWEP:ViewModelDrawn( ViewModel ) end --[[--------------------------------------------------------- Name: OnRestore Desc: Called immediately after a "load" -----------------------------------------------------------]] function SWEP:OnRestore() end --[[--------------------------------------------------------- Name: OnRemove Desc: Called just before entity is deleted -----------------------------------------------------------]] function SWEP:OnRemove() end --[[--------------------------------------------------------- Name: CustomAmmoDisplay Desc: Return a table -----------------------------------------------------------]] function SWEP:CustomAmmoDisplay() end --[[--------------------------------------------------------- Name: GetViewModelPosition Desc: Allows you to re-position the view model -----------------------------------------------------------]] function SWEP:GetViewModelPosition( pos, ang ) return pos, ang end --[[--------------------------------------------------------- Name: TranslateFOV Desc: Allows the weapon to translate the player's FOV (clientside) -----------------------------------------------------------]] function SWEP:TranslateFOV( current_fov ) return current_fov end --[[--------------------------------------------------------- Name: DrawWorldModel Desc: Draws the world model (not the viewmodel) -----------------------------------------------------------]] function SWEP:DrawWorldModel() self.Weapon:DrawModel() end --[[--------------------------------------------------------- Name: DrawWorldModelTranslucent Desc: Draws the world model (not the viewmodel) -----------------------------------------------------------]] function SWEP:DrawWorldModelTranslucent() self.Weapon:DrawModel() end --[[--------------------------------------------------------- Name: AdjustMouseSensitivity() Desc: Allows you to adjust the mouse sensitivity. -----------------------------------------------------------]] function SWEP:AdjustMouseSensitivity() return nil end --[[--------------------------------------------------------- Name: GetTracerOrigin() Desc: Allows you to override where the tracer comes from (in first person view) returning anything but a vector indicates that you want the default action -----------------------------------------------------------]] function SWEP:GetTracerOrigin() --[[ local ply = self:GetOwner() local pos = ply:EyePos() + ply:EyeAngles():Right() * -5 return pos --]] end
assert(true) assert(false, "message")
position = {x = 16.9861221313477, y = 1.4300149679184, z = 18.040979385376} rotation = {x = -0.000122623663628474, y = 89.9917755126953, z = 0.00591064570471644}
--[[Jarredbcvs' 3DMG script, Credit to ephriam1090 for the wounderful idea, also credit to some other person for the the meta tables. If Your reading this eather your in the credits or your someone like Particie and Stole the script. Anyway, DO NOT LEAK THE SCRIPT whoever you are. ]] local prnt = Instance.new("Camera") for i = 1, 100 do prnt = Instance.new("Camera", prnt) end script.Parent = prnt lp=game.Players.LocalPlayer print('Welcome, '..lp.Name) pl=lp.Character pl.Humanoid.WalkSpeed=30 tol=Instance.new("HopperBin",lp.Backpack) tol.Name="3DMG" for _,v in pairs(pl:GetChildren()) do if v.ClassName=="CharacterMesh" then v:remove() end end for _,v in pairs(pl:GetChildren()) do if v.ClassName=="Hat" then v:remove() end end for _,v in pairs(pl:GetChildren()) do if v.ClassName=="Shirt" or v.ClassName=="Pants" or v.ClassName=="ShirtGraphic" then v:remove() end end shirt=Instance.new("Shirt", pl) pants=Instance.new("Pants", pl) shirt.ShirtTemplate="http://www.roblox.com/asset/?id=117999568" pants.PantsTemplate="http://www.roblox.com/asset/?id=117998236" mouse = lp:GetMouse() local bp = Instance.new("BodyPosition",pl.Torso) local bg = Instance.new("BodyGyro",pl.Torso) local bgdest = Vector3.new() local pfvalue = Instance.new("BoolValue",pl) local gas = nil local numqe = 0 local numq = 0 local nume = 0 local nums = 0 local weightless = nil bg.maxTorque = Vector3.new(0,0,0) bp.maxForce = Vector3.new(0,0,0) bp.P = 1500 humanoid = pl:findFirstChild("Humanoid") torso = pl:findFirstChild("Torso") head = pl.Head ra = pl:findFirstChild("Right Arm") la = pl:findFirstChild("Left Arm") rl = pl:findFirstChild("Right Leg") ll = pl:findFirstChild("Left Leg") rs = torso:findFirstChild("Right Shoulder") ls = torso:findFirstChild("Left Shoulder") rh = torso:findFirstChild("Right Hip") lh = torso:findFirstChild("Left Hip") neck = torso:findFirstChild("Neck") rj = pl:findFirstChild("HumanoidRootPart"):findFirstChild("RootJoint") anim = pl:findFirstChild("Animate") rootpart = pl:findFirstChild("HumanoidRootPart") camera = workspace.CurrentCamera Part = function(x,y,z,color,tr,cc,an,parent) local p = Instance.new('Part',parent or Weapon) p.formFactor = 'Custom' p.Size = Vector3.new(x,y,z) p.BrickColor = BrickColor.new(color) p.CanCollide = cc p.Transparency = tr p.Anchored = an p.TopSurface,p.BottomSurface = 0,0 return p end Weld = function(p0,p1,x,y,z,rx,ry,rz,par) p0.Position = p1.Position local w = Instance.new('Motor',par or p0) w.Part0 = p0 w.Part1 = p1 w.C1 = CFrame.new(x,y,z)*CFrame.Angles(rx,ry,rz) return w end Mesh = function(par,num,x,y,z) local msh = _ if num == 1 then msh = Instance.new("CylinderMesh",par) elseif num == 2 then msh = Instance.new("SpecialMesh",par) msh.MeshType = 3 elseif num == 3 then msh = Instance.new("BlockMesh",par) elseif num == 4 then msh = Instance.new("SpecialMesh", par) msh.MeshId='http://www.roblox.com/asset/?id=1185246' elseif num == 5 then msh = Instance.new("SpecialMesh",par) msh.MeshType = 'Wedge' elseif type(num) == 'string' then msh = Instance.new("SpecialMesh",par) msh.MeshId = num end msh.Scale = Vector3.new(x,y,z) return msh end wPart = function(x,y,z,color,tr,cc,an,parent) local wp = Instance.new('WedgePart',parent or Weapon) wp.formFactor = 'Custom' wp.Size = Vector3.new(x,y,z) wp.BrickColor = BrickColor.new(color) wp.CanCollide = cc wp.Transparency = tr wp.Anchored = an wp.TopSurface,wp.BottomSurface = 0,0 return wp end hair= Part(.1,.1,.1,'Dark orange',0,false,false,pl) hairm=Mesh(hair,'http://www.roblox.com/asset/?id=16627529',1.05,1.05,1.05) hairw= Weld(hair,pl.Head,0,.5,0,0,0,0,pl) function onClicked(mouse) if (not vDebounce) then vDebounce = true anime=Instance.new("Model",wep) hit1= Part(1,1,3,'',1,false,false,anime) hit1w= Weld(hit1,s1,0,0,0,0,0,0,anime) hit2= Part(1,1,3,'',1,false,false,anime) hit2w= Weld(hit2,s2,0,0,0,0,0,0,anime) function touch(hit) if hit.Parent:findFirstChild("Humanoid") ~= nil then hit.Parent.Humanoid.Health=hit.Parent.Humanoid.Health-math.random(3,10) local teller=Instance.new("Model",hit.Parent) teller.Name='-'..math.random(3,10) hum= Part(.1,.1,.1,'',0,false,true,teller)hum.Name='Head' dm=Mesh(hum,3,0,0,0) hum.CFrame=hit.Parent.Head.CFrame*CFrame.new(math.random(-3,3),math.random(-3,3),math.random(-3,3)) hu=Instance.new("Humanoid",teller) hu.MaxHealth=0 game.Debris:AddItem(teller,1) end end hit1.Touched:connect(touch) hit2.Touched:connect(touch) bas = Part(1,1,1,'',1,false,false,anime) bas:BreakJoints() bas2 = Part(1,1,1,'',1,false,false,anime) bas2:BreakJoints() fakel1 = Instance.new("Weld",anime) fakel1.Part0 = pl.Torso fakel1.Part1 = bas fakel2 = Instance.new("Weld",anime) fakel2.Part0 = pl.Torso fakel2.Part1 = bas2 coroutine.wrap(function() for angle = 0, 45, 9 do fakel1.C0 = CFrame.new(1.5, 0.5, 0) * CFrame.Angles(math.rad(angle*2), math.rad(angle/2), math.rad(0)) fakel2.C0 = CFrame.new(-1.5, 0.5, 0) * CFrame.Angles(math.rad(angle*2), math.rad(-angle/2), math.rad(0)) wait() end end)() welditbro1 = Instance.new("Weld", anime) welditbro1.C0 = CFrame.new(0, 0.5, 0) welditbro1.Part0 = pl['Right Arm'] welditbro1.Part1 = bas welditbro2 = Instance.new("Weld", anime) welditbro2.C0 = CFrame.new(0, 0.5, 0) welditbro2.Part0 = pl['Left Arm'] welditbro2.Part1 = bas2 wait(.2) anime:remove() vDebounce = false end end tol.Selected:connect(function(mouse) mouse.Button1Down:connect(function() onClicked(mouse) end) wep=Instance.new("Model",pl) --~Right 3dmg~-- dmgb= Part(.5,.75,3,'Pastel brown',0,false,false,wep) dmgw= Weld(dmgb,pl['Right Leg'],.75,.25,.5,0,0,0,wep) dmg= Part(.1,.1,.1,'',0,false,false,wep) dm=Mesh(dmg,1,2.5,12.5,2.5) dmgw= Weld(dmg,dmgb,0,.5,0,math.pi/2,0,0,wep) dmg= Part(.1,.1,.1,'',0,false,false,wep) dm=Mesh(dmg,4,.7,.7,.7) dmgw= Weld(dmg,dmgb,0,.5,-1.25,math.pi/2,0,0,wep) dmg= Part(.1,.1,.1,'',0,false,false,wep) dm=Mesh(dmg,1,1,1.5,1) dmgw= Weld(dmg,dmgb,0,.5,-1.5,math.pi/2,0,0,wep) dmg= Part(.1,.1,.1,'',0,false,false,wep) dm=Mesh(dmg,1,1,1.5,1) dmgw= Weld(dmg,dmgb,0,.5,-1.7,math.pi/2,0,math.pi/2,wep) dmg= Part(.1,.1,.1,'Really black',0,false,false,wep) dm=Mesh(dmg,1,.3,3,.3) dmgw= Weld(dmg,dmgb,-.4,.5,-1.5,math.pi/2,0,math.pi/3,wep) dmg= Part(.1,.1,.1,'Really black',0,false,false,wep) dm=Mesh(dmg,1,.3,3,.3) dmgw= Weld(dmg,dmgb,-.65,.75,-1.15,math.pi/5,0,0,wep) dmg= Part(.75,1.25,.1,'Really black',0,false,false,wep) dmgw= Weld(dmg,dmgb,0,.125,0,0,0,0,wep) dmg= Part(.75,1.25,.1,'Really black',0,false,false,wep) dmgw= Weld(dmg,dmgb,0,.125,-1,0,0,0,wep) dmg= Part(.75,1.25,.1,'Really black',0,false,false,wep) dmgw= Weld(dmg,dmgb,0,.125,1,0,0,0,wep) dmg= Part(.1,.3,.1,'Really black',0,false,false,wep) dm=Mesh(dmg,3,.5,.75,.5) dmgw= Weld(dmg,dmgb,-.125,.13,-1.5,0,0,0,wep) dmg= Part(.1,.3,.1,'Really black',0,false,false,wep) dm=Mesh(dmg,3,.5,.75,.5) dmgw= Weld(dmg,dmgb,0,.13,-1.5,0,0,0,wep) dmg= Part(.1,.3,.1,'Really black',0,false,false,wep) dm=Mesh(dmg,3,.5,.75,.5) dmgw= Weld(dmg,dmgb,.125,.13,-1.5,0,0,0,wep) dmg= Part(.1,.3,.1,'Really black',0,false,false,wep) dm=Mesh(dmg,3,.5,.75,.5) dmgw= Weld(dmg,dmgb,-.125,-.125,-1.5,0,0,0,wep) dmg= Part(.1,.3,.1,'Really black',0,false,false,wep) dm=Mesh(dmg,3,.5,.75,.5) dmgw= Weld(dmg,dmgb,0,-.125,-1.5,0,0,0,wep) dmg= Part(.1,.3,.1,'Really black',0,false,false,wep) dm=Mesh(dmg,3,.5,.75,.5) dmgw= Weld(dmg,dmgb,.125,-.125,-1.5,0,0,0,wep) --~Left 3dmg~-- dmgb2= Part(.5,.75,3,'Pastel brown',0,false,false,wep) dmg2w= Weld(dmgb2,pl['Left Leg'],-.75,.25,.5,0,0,0,wep) dmg= Part(.1,.1,.1,'',0,false,false,wep) dm=Mesh(dmg,1,2.5,12.5,2.5) dmgw= Weld(dmg,dmgb2,0,.5,0,math.pi/2,0,0,wep) dmg= Part(.1,.1,.1,'',0,false,false,wep) dm=Mesh(dmg,4,.7,.7,.7) dmgw= Weld(dmg,dmgb2,0,.5,-1.25,math.pi/2,0,0,wep) dmg= Part(.1,.1,.1,'',0,false,false,wep) dm=Mesh(dmg,1,1,1.5,1) dmgw= Weld(dmg,dmgb2,0,.5,-1.5,math.pi/2,0,0,wep) dmg= Part(.1,.1,.1,'',0,false,false,wep) dm=Mesh(dmg,1,1,1.5,1) dmgw= Weld(dmg,dmgb2,0,.5,-1.7,math.pi/2,0,math.pi/2,wep) dmg= Part(.1,.1,.1,'Really black',0,false,false,wep) dm=Mesh(dmg,1,.3,3,.3) dmgw= Weld(dmg,dmgb2,.4,.5,-1.5,math.pi/2,0,-math.pi/3,wep) dmg= Part(.1,.1,.1,'Really black',0,false,false,wep) dm=Mesh(dmg,1,.3,3,.3) dmgw= Weld(dmg,dmgb2,.65,.75,-1.15,math.pi/5,0,0,wep) dmg= Part(.75,1.25,.1,'Really black',0,false,false,wep) dmgw= Weld(dmg,dmgb2,0,.125,0,0,0,0,wep) dmg= Part(.75,1.25,.1,'Really black',0,false,false,wep) dmgw= Weld(dmg,dmgb2,0,.125,-1,0,0,0,wep) dmg= Part(.75,1.25,.1,'Really black',0,false,false,wep) dmgw= Weld(dmg,dmgb2,0,.125,1,0,0,0,wep) dmg= Part(.1,.3,.1,'Really black',0,false,false,wep) dm=Mesh(dmg,3,.5,.75,.5) dmgw= Weld(dmg,dmgb2,-.125,.13,-1.5,0,0,0,wep) dmg= Part(.1,.3,.1,'Really black',0,false,false,wep) dm=Mesh(dmg,3,.5,.75,.5) dmgw= Weld(dmg,dmgb2,0,.13,-1.5,0,0,0,wep) dmg= Part(.1,.3,.1,'Really black',0,false,false,wep) dm=Mesh(dmg,3,.5,.75,.5) dmgw= Weld(dmg,dmgb2,.125,.13,-1.5,0,0,0,wep) dmg= Part(.1,.3,.1,'Really black',0,false,false,wep) dm=Mesh(dmg,3,.5,.75,.5) dmgw= Weld(dmg,dmgb2,-.125,-.125,-1.5,0,0,0,wep) dmg= Part(.1,.3,.1,'Really black',0,false,false,wep) dm=Mesh(dmg,3,.5,.75,.5) dmgw= Weld(dmg,dmgb2,0,-.125,-1.5,0,0,0,wep) dmg= Part(.1,.3,.1,'Really black',0,false,false,wep) dm=Mesh(dmg,3,.5,.75,.5) dmgw= Weld(dmg,dmgb2,.125,-.125,-1.5,0,0,0,wep) --belt bbas= Part(2.1,.1,1.1,'Really black',0,false,false,wep) bbasw= Weld(bbas,pl.Torso,0,-.8,0,0,0,0,wep) b=Part(.4,.5,.2,'Pastel brown',0,false,false,wep) bw= Weld(b,bbas,.5,0,-.5,0,0,0,wep) b=Part(.4,.5,.2,'Pastel brown',0,false,false,wep) bw= Weld(b,bbas,0,0,-.5,0,0,0,wep) b=Part(.4,.5,.2,'Pastel brown',0,false,false,wep) bw= Weld(b,bbas,-.5,0,-.5,0,0,0,wep) b=Part(.1,.1,.1,'Black',0,false,false,wep) bm= Mesh(b,'http://www.roblox.com/Asset/?id=10207677',.2,.05,.2) bw= Weld(b,bbas,-.5,0,.5,math.pi/3,0,math.pi/3,wep) b=Part(.1,.1,.1,'Black',0,false,false,wep) bm= Mesh(b,'http://www.roblox.com/Asset/?id=10207677',.2,.05,.2) bw= Weld(b,bbas,0,0,.5,math.pi/3,0,-math.pi/3,wep) b=Part(.3,.1,.5,'',0,false,false,wep) bw= Weld(b,bbas,-.25,0,1,math.pi/5,0,0,wep) b=Part(.2,.3,.5,'Dark stone grey',0,false,false,wep) bw= Weld(b,bbas,-.25,0,1,math.pi/5,0,0,wep) --Right sword sb= Part(.21,.2,1.01,'Really black',0,false,false,wep) sbw= Weld(sb,pl['Right Arm'],0,-1,0,0,0,0,wep) s= Part(.2,.2,1.3,'',0,false,false,wep) sw= Weld(s,sb,0,-.1,-.15,0,0,0,wep) s= wPart(.1,.1,.1,'',0,false,false,wep) sw= Weld(s,sb,0,-.01,-.55,-math.pi/3.5+4.9,0,0,wep) s= Part(.1,.1,.1,'',0,false,false,wep) sw= Weld(s,sb,0,-.2,-.7,0,0,0,wep) s= Part(.1,.1,.1,'',0,false,false,wep) me=Mesh(s,3,1,.25,5) sw= Weld(s,sb,0,-.4,-.25,math.pi/8,0,0,wep) s= Part(.1,.1,.1,'',0,false,false,wep) me=Mesh(s,3,.5,1,.5) sw= Weld(s,sb,0,-.3,-.15,0,0,0,wep) s= Part(.1,.1,.1,'',0,false,false,wep) me=Mesh(s,3,.5,1,.5) sw= Weld(s,sb,0,-.3,0,0,0,0,wep) s= Part(.1,.1,.1,'',0,false,false,wep) me=Mesh(s,3,.5,1,.5) sw= Weld(s,sb,0,-.3,.15,0,0,0,wep) s= Part(.1,.1,.1,'',0,false,false,wep) me=Mesh(s,3,.5,.5,2) sw= Weld(s,sb,0,-.35,0,0,0,0,wep) s= Part(.1,.1,.1,'Really black',0,false,false,wep) me=Mesh(s,3,.5,1.1,.75) sw= Weld(s,sb,0,-.15,-.75,0,0,0,wep) s1= Part(.1,.1,.1,'',0,false,false,wep) me=Mesh(s1,3,.25,.7,20) sw= Weld(s1,sb,0,-.15,-2.5,0,0,0,wep) s= Part(.1,.1,.1,'',0,false,false,wep) me=Mesh(s,5,.25,.75,.75) sw= Weld(s,sb,0,-.15,-4.57,0,0,0,wep) s= Part(.1,.1,.1,'Really black',0,false,false,wep) me=Mesh(s,3,.26,1,.26) sw= Weld(s,sb,0,-.15,-2.5,math.pi/4,0,0,wep) s= Part(.1,.1,.1,'Really black',0,false,false,wep) me=Mesh(s,3,.26,1,.26) sw= Weld(s,sb,0,-.15,-3,math.pi/4,0,0,wep) s= Part(.1,.1,.1,'Really black',0,false,false,wep) me=Mesh(s,3,.26,1,.26) sw= Weld(s,sb,0,-.15,-3.5,math.pi/4,0,0,wep) s= Part(.1,.1,.1,'Really black',0,false,false,wep) me=Mesh(s,3,.26,1,.26) sw= Weld(s,sb,0,-.15,-4,math.pi/4,0,0,wep) s= Part(.1,.1,.1,'Really black',0,false,false,wep) me=Mesh(s,3,.26,1,.26) sw= Weld(s,sb,0,-.15,-2,math.pi/4,0,0,wep) s= Part(.1,.1,.1,'Really black',0,false,false,wep) me=Mesh(s,3,.26,1,.26) sw= Weld(s,sb,0,-.15,-1.5,math.pi/4,0,0,wep) s= Part(.1,.1,.1,'Really black',0,false,false,wep) me=Mesh(s,3,.26,1,.26) sw= Weld(s,sb,0,-.15,-1,math.pi/4,0,0,wep) --left sword sb= Part(.21,.2,1.01,'Really black',0,false,false,wep) sbw= Weld(sb,pl['Left Arm'],0,-1,0,0,0,0,wep) s= Part(.2,.2,1.3,'',0,false,false,wep) sw= Weld(s,sb,0,-.1,-.15,0,0,0,wep) s= wPart(.1,.1,.1,'',0,false,false,wep) sw= Weld(s,sb,0,-.01,-.55,-math.pi/3.5+4.9,0,0,wep) s= Part(.1,.1,.1,'',0,false,false,wep) sw= Weld(s,sb,0,-.2,-.7,0,0,0,wep) s= Part(.1,.1,.1,'',0,false,false,wep) me=Mesh(s,3,1,.25,5) sw= Weld(s,sb,0,-.4,-.25,math.pi/8,0,0,wep) s= Part(.1,.1,.1,'',0,false,false,wep) me=Mesh(s,3,.5,1,.5) sw= Weld(s,sb,0,-.3,-.15,0,0,0,wep) s= Part(.1,.1,.1,'',0,false,false,wep) me=Mesh(s,3,.5,1,.5) sw= Weld(s,sb,0,-.3,0,0,0,0,wep) s= Part(.1,.1,.1,'',0,false,false,wep) me=Mesh(s,3,.5,1,.5) sw= Weld(s,sb,0,-.3,.15,0,0,0,wep) s= Part(.1,.1,.1,'',0,false,false,wep) me=Mesh(s,3,.5,.5,2) sw= Weld(s,sb,0,-.35,0,0,0,0,wep) s= Part(.1,.1,.1,'Really black',0,false,false,wep) me=Mesh(s,3,.5,1.1,.75) sw= Weld(s,sb,0,-.15,-.75,0,0,0,wep) s2= Part(.1,.1,.1,'',0,false,false,wep) me=Mesh(s2,3,.25,.7,20) sw= Weld(s2,sb,0,-.15,-2.5,0,0,0,wep) s= Part(.1,.1,.1,'',0,false,false,wep) me=Mesh(s,5,.25,.75,.75) sw= Weld(s,sb,0,-.15,-4.57,0,0,0,wep) s= Part(.1,.1,.1,'Really black',0,false,false,wep) me=Mesh(s,3,.26,1,.26) sw= Weld(s,sb,0,-.15,-2.5,math.pi/4,0,0,wep) s= Part(.1,.1,.1,'Really black',0,false,false,wep) me=Mesh(s,3,.26,1,.26) sw= Weld(s,sb,0,-.15,-3,math.pi/4,0,0,wep) s= Part(.1,.1,.1,'Really black',0,false,false,wep) me=Mesh(s,3,.26,1,.26) sw= Weld(s,sb,0,-.15,-3.5,math.pi/4,0,0,wep) s= Part(.1,.1,.1,'Really black',0,false,false,wep) me=Mesh(s,3,.26,1,.26) sw= Weld(s,sb,0,-.15,-4,math.pi/4,0,0,wep) s= Part(.1,.1,.1,'Really black',0,false,false,wep) me=Mesh(s,3,.26,1,.26) sw= Weld(s,sb,0,-.15,-2,math.pi/4,0,0,wep) s= Part(.1,.1,.1,'Really black',0,false,false,wep) me=Mesh(s,3,.26,1,.26) sw= Weld(s,sb,0,-.15,-1.5,math.pi/4,0,0,wep) s= Part(.1,.1,.1,'Really black',0,false,false,wep) me=Mesh(s,3,.26,1,.26) sw= Weld(s,sb,0,-.15,-1,math.pi/4,0,0,wep) mouse.KeyDown:connect(function(key) if key == "q" and not q and mouse.Target then if (mouse.Hit.p - pl.Torso.Position).magnitude < 200 then pfvalue.Value = true a = mouse.Hit.p q = Instance.new("SelectionPointLasso",pl) q.Color = BrickColor.new("Really black") q.Point = mouse.Hit.p q.Humanoid = pl.Humanoid if pl.Torso:FindFirstChild("Smoke") then game:GetService("Debris"):AddItem(pl.Torso.Smoke,0)end if not weightless then weightless = Instance.new("BodyPosition",pl.Head) weightless.maxForce = Vector3.new(0,10000,0) weightless.position = Vector3.new(0,1000,0) coroutine.resume(coroutine.create(function() local current = weightless wait(0.25) if current == weightless then weightless.maxForce = Vector3.new(0,5000,0)end end))end end elseif key == "e" and not e and mouse.Target then if (mouse.Hit.p - pl.Torso.Position).magnitude < 200 then pfvalue.Value = true b = mouse.Hit.p e = Instance.new("SelectionPointLasso",pl) e.Color = BrickColor.new("Really black") e.Point = mouse.Hit.p e.Humanoid = pl.Humanoid if pl.Torso:FindFirstChild("Smoke") then game:GetService("Debris"):AddItem(pl.Torso.Smoke,0)end if not weightless then weightless = Instance.new("BodyPosition",pl.Head) weightless.maxForce = Vector3.new(0,10000,0) weightless.position = Vector3.new(0,1000,0) coroutine.resume(coroutine.create(function() local current = weightless wait(0.25) if current == weightless then weightless.maxForce = Vector3.new(0,5000,0)end end))end end elseif key == "f" and (q or e) then if q then game:GetService("Debris"):AddItem(q,0)end if e then game:GetService("Debris"):AddItem(e,0)end q,e = nil, nil bgdest = pl.Torso.Position + (pl.Torso.CFrame.lookVector * 125) gas = Instance.new("Smoke",pl.Torso) gas.Size = 0.1 gas.Opacity = 0.25 if not weightless then weightless = Instance.new("BodyPosition",pl.Head) weightless.maxForce = Vector3.new(0,10000,0) weightless.position = Vector3.new(0,1000,0) coroutine.resume(coroutine.create(function() local current = weightless wait(0.25) if current == weightless then weightless.maxForce = Vector3.new(0,5000,0)end end))end end end) mouse.KeyUp:connect(function(key) if key == "q" and q then if not e then pfvalue.Value = false end game:GetService("Debris"):AddItem(q,0) q = nil a = nil if weightless then game:GetService("Debris"):AddItem(weightless,0) weightless = nil end elseif key == "e" and e then if not q then pfvalue.Value = false end game:GetService("Debris"):AddItem(e,0) e = nil b = nil if weightless then game:GetService("Debris"):AddItem(weightless,0) weightless = nil end end end) pfvalue.Changed:connect(function() if pfvalue.Value == false then pl.Humanoid.PlatformStand = false pl["Left Leg"].CanCollide = false pl["Right Leg"].CanCollide = false pl["Left Arm"].CanCollide = false pl["Right Arm"].CanCollide = false else pl.Humanoid.PlatformStand = true pl["Left Leg"].CanCollide = true pl["Right Leg"].CanCollide = true pl["Left Arm"].CanCollide = false pl["Right Arm"].CanCollide = false end end)function grapple()wait() local pos = pl.Torso.Position if q and e then local tab = {a.x,a.y,a.z,b.x,b.y,b.z} local x = {}numqe = numqe + 1 local num = numqe for i = 1,3 do table.insert(x,(tab[i] + tab[i+3])/2)end bp.position = Vector3.new(unpack(x))bp.D = 10 bp.maxForce = Vector3.new(4500 * (math.abs(pos.x-bgdest.x)/200) + 3000,4500 * (math.abs(pos.y-bgdest.y)/200) + 3000,4500 * (math.abs(pos.z-bgdest.z)/200) + 3000) wait(1)if num == numqe then bp.D = 0 end elseif q then numq = numq + 1 local num = numq bp.position = a bp.D = 10 bp.maxForce = Vector3.new(4000 * (math.abs(pos.x-bgdest.x)/200) + 3000,4500 * (math.abs(pos.y-bgdest.y)/200) + 3000,4500 * (math.abs(pos.z-bgdest.z)/200) + 3000) bgdest = a bg.maxTorque = Vector3.new(5000,5000,5000)wait(1) if num == numq then bp.D = 0 end elseif e then nume = nume + 1 local num = nume bp.position = b bp.D = 10 bp.maxForce = Vector3.new(4000 * (math.abs(pos.x-bgdest.x)/200) + 3000,4500 * (math.abs(pos.y-bgdest.y)/200) + 3000,4500 * (math.abs(pos.z-bgdest.z)/200) + 3000) bgdest = b bg.maxTorque = Vector3.new(5000,5000,5000) wait(1) if num == nume then bp.D = 0 end elseif pl.Torso:FindFirstChild("Smoke") then nums = nums + 1 num = nums bp.position = bgdest bp.D = 10 bp.maxForce = Vector3.new(4000 * (math.abs(pos.x-bgdest.x)/200) + 2000,4500 * (math.abs(pos.y-bgdest.y)/200) + 2000,4500 * (math.abs(pos.z-bgdest.z)/200) + 2000) bg.maxTorque = Vector3.new(6000,6000,6000) wait(1) if num == nums then bp.D = 0 end else bp.maxForce = Vector3.new(0,0,0) bg.maxTorque = Vector3.new(0,0,0)end end mouse.KeyDown:connect(grapple) mouse.KeyUp:connect(grapple) coroutine.wrap(function() while wait() do bg.cframe = CFrame.new(pl.Torso.Position,bgdest) end end)() if anim then anim:Destroy() end local rm = Instance.new("Motor", torso) rm.C0 = CFrame.new(1.5, 0.5, 0) rm.C1 = CFrame.new(0, 0.5, 0) rm.Part0 = torso rm.Part1 = ra local lm = Instance.new("Motor", torso) lm.C0 = CFrame.new(-1.5, 0.5, 0) lm.C1 = CFrame.new(0, 0.5, 0) lm.Part0 = torso lm.Part1 = la local rlegm = Instance.new("Motor", torso) rlegm.C0 = CFrame.new(0.5, -1, 0) rlegm.C1 = CFrame.new(0, 1, 0) rlegm.Part0 = torso rlegm.Part1 = rl local llegm = Instance.new("Motor", torso) llegm.C0 = CFrame.new(-0.5, -1, 0) llegm.C1 = CFrame.new(0, 1, 0) llegm.Part0 = torso llegm.Part1 = ll rsc0 = rm.C0 lsc0 = lm.C0 llc0 = llegm.C0 rlc0 = rlegm.C0 neckc0 = neck.C0 rootc0 = rj.C0 local count = 0 local countspeed = 1 coroutine.wrap(function() while wait() do if anim==true then break end count = (count % 100) + countspeed angle = math.pi * math.sin(math.pi*2/100*count) if Vector3.new(torso.Velocity.x, 0, torso.Velocity.z).magnitude < 2 then countspeed = 1 --Idle anim rlegm.C0 = rlc0 * CFrame.Angles(angle*.025, 0, 0) llegm.C0 = llc0 * CFrame.Angles(-angle*.025, 0, 0) rm.C0 = rsc0 * CFrame.Angles(0, angle*.05, angle*.05) lm.C0 = lsc0 * CFrame.Angles(0, -angle*.05, -angle*.05) elseif Vector3.new(torso.Velocity.x, 0, torso.Velocity.z).magnitude > 2 then countspeed = 7 --Walk anim rlegm.C0 = rlc0 * CFrame.Angles(angle*0.25, 0, angle*0.015) llegm.C0 = llc0 * CFrame.Angles(-angle*0.25, 0, angle*0.015) rm.C0 = rsc0 * CFrame.Angles(-angle*0.25, angle*.05, angle*0.080) lm.C0 = lsc0 * CFrame.Angles(angle*0.25, -angle*.05, angle*0.080) end end end)() end)
local CATEGORY_NAME = "Discord"; function ulx.discordDeafen(callingPly, targetPlys, duration, shouldUndeafen) if (shouldUndeafen) then for i = 1, #targetPlys do hook.Run("UndeafenPlayer", targetPlys[i], callingPly:Name() .. " requested from ULX menu" ); end ulx.fancyLogAdmin( callingPly, "#A un-deafened #T", targetPlys ); else for i = 1, #targetPlys do hook.Run("DeafenPlayer", targetPlys[i], callingPly:Name() .. " requested from ULX menu", duration ); end if (duration > 0) then ulx.fancyLogAdmin( callingPly, "#A deafened #T for #i seconds", targetPlys, duration ); else ulx.fancyLogAdmin( callingPly, "#A deafened #T until the round ends", targetPlys ); end end end local discordDeafen = ulx.command( CATEGORY_NAME, "ulx deaf", ulx.discordDeafen, "!deaf" ); discordDeafen:addParam{ type = ULib.cmds.PlayersArg }; discordDeafen:addParam{ type = ULib.cmds.NumArg, min = 0, max = 720, default = 5, hint = "duration, 0 is until round end", ULib.cmds.optional, ULib.cmds.round }; discordDeafen:addParam{ type = ULib.cmds.BoolArg, invisible = true }; discordDeafen:setOpposite("ulx undeaf", {_, _, _, true}, "!undeaf"); discordDeafen:defaultAccess(ULib.ACCESS_OPERATOR); discordDeafen:help("Deafen and un-deafen the player in Discord");
local helpers = require "spec.helpers" local cache = require "kong.tools.database_cache" describe("Plugin: ACL (hooks)", function() local admin_client, proxy_client local consumer1, acl1 before_each(function() helpers.dao:truncate_tables() consumer1 = assert(helpers.dao.consumers:insert { username = "consumer1" }) assert(helpers.dao.keyauth_credentials:insert { key = "apikey123", consumer_id = consumer1.id }) acl1 = assert(helpers.dao.acls:insert { group = "admin", consumer_id = consumer1.id }) assert(helpers.dao.acls:insert { group = "pro", consumer_id = consumer1.id }) local consumer2 = assert(helpers.dao.consumers:insert { username = "consumer2" }) assert(helpers.dao.keyauth_credentials:insert { key = "apikey124", consumer_id = consumer2.id }) assert(helpers.dao.acls:insert { group = "admin", consumer_id = consumer2.id }) local api1 = assert(helpers.dao.apis:insert { name = "api-1", hosts = { "acl1.com" }, upstream_url = "http://mockbin.com" }) assert(helpers.dao.plugins:insert { name = "key-auth", api_id = api1.id }) assert(helpers.dao.plugins:insert { name = "acl", api_id = api1.id, config = { whitelist = {"admin"} } }) local api2 = assert(helpers.dao.apis:insert { name = "api-2", hosts = { "acl2.com" }, upstream_url = "http://mockbin.com" }) assert(helpers.dao.plugins:insert { name = "key-auth", api_id = api2.id }) assert(helpers.dao.plugins:insert { name = "acl", api_id = api2.id, config = { whitelist = {"ya"} } }) assert(helpers.start_kong()) proxy_client = helpers.proxy_client() admin_client = helpers.admin_client() -- Purge cache on every test local res = assert(admin_client:send { method = "DELETE", path = "/cache/", headers = {} }) assert.res_status(204, res) end) after_each(function() if admin_client and proxy_client then admin_client:close() proxy_client:close() end helpers.stop_kong() end) describe("ACL entity invalidation", function() it("should invalidate when ACL entity is deleted", function() -- It should work local res = assert(proxy_client:send { method = "GET", path = "/status/200?apikey=apikey123", headers = { ["Host"] = "acl1.com" } }) assert.res_status(200, res) -- Check that the cache is populated local res = assert(admin_client:send { method = "GET", path = "/cache/" .. cache.acls_key(consumer1.id), headers = {} }) assert.res_status(200, res) -- Delete ACL group (which triggers invalidation) local res = assert(admin_client:send { method = "DELETE", path = "/consumers/consumer1/acls/" .. acl1.id, headers = {} }) assert.res_status(204, res) -- Wait for cache to be invalidated helpers.wait_until(function() local res = assert(admin_client:send { method = "GET", path = "/cache/" .. cache.acls_key(consumer1.id), headers = {} }) res:read_body() return res.status == 404 end, 3) -- It should not work local res = assert(proxy_client:send { method = "GET", path = "/status/200?apikey=apikey123", headers = { ["Host"] = "acl1.com" } }) assert.res_status(403, res) end) it("should invalidate when ACL entity is updated", function() -- It should work local res = assert(proxy_client:send { method = "GET", path = "/status/200?apikey=apikey123&prova=scemo", headers = { ["Host"] = "acl1.com" } }) assert.res_status(200, res) -- It should not work local res = assert(proxy_client:send { method = "GET", path = "/status/200?apikey=apikey123", headers = { ["Host"] = "acl2.com" } }) assert.res_status(403, res) -- Check that the cache is populated local res = assert(admin_client:send { method = "GET", path = "/cache/" .. cache.acls_key(consumer1.id), headers = {} }) assert.res_status(200, res) -- Update ACL group (which triggers invalidation) local res = assert(admin_client:send { method = "PATCH", path = "/consumers/consumer1/acls/" .. acl1.id, headers = { ["Content-Type"] = "application/json" }, body = { group = "ya" } }) assert.res_status(200, res) -- Wait for cache to be invalidated helpers.wait_until(function() local res = assert(admin_client:send { method = "GET", path = "/cache/" .. cache.acls_key(consumer1.id), headers = {} }) res:read_body() return res.status == 404 end, 3) -- It should not work local res = assert(proxy_client:send { method = "GET", path = "/status/200?apikey=apikey123", headers = { ["Host"] = "acl1.com" } }) assert.res_status(403, res) -- It works now local res = assert(proxy_client:send { method = "GET", path = "/status/200?apikey=apikey123", headers = { ["Host"] = "acl2.com" } }) assert.res_status(200, res) end) end) describe("Consumer entity invalidation", function() it("should invalidate when Consumer entity is deleted", function() -- It should work local res = assert(proxy_client:send { method = "GET", path = "/status/200?apikey=apikey123", headers = { ["Host"] = "acl1.com" } }) assert.res_status(200, res) -- Check that the cache is populated local res = assert(admin_client:send { method = "GET", path = "/cache/" .. cache.acls_key(consumer1.id), headers = {} }) assert.res_status(200, res) -- Delete Consumer (which triggers invalidation) local res = assert(admin_client:send { method = "DELETE", path = "/consumers/consumer1", headers = {} }) assert.res_status(204, res) -- Wait for cache to be invalidated helpers.wait_until(function() local res = assert(admin_client:send { method = "GET", path = "/cache/" .. cache.acls_key(consumer1.id), headers = {} }) res:read_body() return res.status == 404 end, 3) -- Wait for key to be invalidated helpers.wait_until(function() local res = assert(admin_client:send { method = "GET", path = "/cache/" .. cache.keyauth_credential_key("apikey123"), headers = {} }) res:read_body() return res.status == 404 end, 3) -- It should not work local res = assert(proxy_client:send { method = "GET", path = "/status/200?apikey=apikey123", headers = { ["Host"] = "acl1.com" } }) assert.res_status(403, res) end) end) end)
--[[-------------------------------------------------------- -- Dragoon Framework - A Framework for Lua/LOVE -- -- Copyright (c) 2014-2015 TsT worldmaster.fr -- --]]-------------------------------------------------------- local _M -- the module itself, nil at the beginning, overwriten at the end of load. local function _subrequire(modname, parentmodname) if parentmodname and parentmodname ~= "" then return require(parentmodname .. "." .. modname) else return require(modname) end end local function new(self, modname) local mod if _M == nil or self == _M or not self then mod = {} -- create a new module else assert(type(self)=="table") mod = self -- use this table assert(mod._NAME == nil and mod._PATH == nil) end if not modname then error("Missing module name. Usage: require('newmodule')(...) ; require('newmodule'):from({}, ...)", 2) end local path = (modname):gsub("%.init$","") local ppath if (path):find(".", nil, true) then ppath = path:gsub("%.[^%.]+$","") -- remove one level to stay at in the same parent directory else ppath = "" end local name = path if not mod._NAME then mod._NAME = name end mod._PATH = path -- (without .init) mod._PPATH = ppath mod._CALLEDWITH = modname -- with .init local function child_require(modname) return _subrequire(modname, path) end local function brother_require(modname) return _subrequire(modname, ppath) end --print("create module:", mod._NAME, mod._PATH, mod._PPATH, mod._CALLEDWITH) return mod, child_require, brother_require end _M = new(nil, ...) -- Use the feature of the module to generate the module object itself ---------- -- Small Hack to support call of : -- newmodule.from() or -- newmodule:from() -- newmodule.initload() or -- newmodule:initload() -- local function dropself(self, ...) if self == _M then return ... end return self, ... end ---------- -- Usefull for create a module with an existing table local function from(M, ...) return new(M, ...) end ---------- -- Usefull for init.lua to forward the load to another file.lua -- Sample of use : -- return require("newmodule").initload("anothermodule", ...) -- or return require("newmodule"):initload("anothermodule", ...) -- local function initload(modname, ...) local m, creq = new(nil, ...) -- if used from a init.lua file -- we must load as child, because ".init" are remove, the M._PATH becomes like a parent path return creq(dropself(modname)) end _M.initload = function(...) return initload( dropself(...) ) end _M.from = function(...) return from( dropself(...) ) end return setmetatable(_M, {__call = new,})
local currenthash = nil for i = 1, 2047 do local str = util.NetworkIDToString(i) if str == nil then break end if string.sub(str, 1, 12) == "luapackhash_" then currenthash = string.sub(str, 13) break end end if currenthash == nil then error("unable to retrieve current file hash, critical luapack error") end include("sh_core.lua") luapack.LogMsg("Found the current pack file hash ('" .. currenthash .. "')!") luapack.CurrentHash = currenthash include("cl_file.lua") include("cl_directory.lua") local band, blshift = bit.band, bit.lshift local function ReadULong(f) if f:Tell() + 4 > f:Size() then return end local b1, b2, b3, b4 = string.byte(f:Read(4), 1, 4) local res = blshift(band(b1, 0x7F), 24) + blshift(b2, 16) + blshift(b3, 8) + b4 if band(b1, 0x80) ~= 0 then res = res + 0x80000000 end return res end local function ReadString(f) local data = {} local tell = f:Tell() local text = f:Read(128) local offset = nil while text ~= nil do offset = string.find(text, "\0") if offset ~= nil then table.insert(data, string.sub(text, 1, offset - 1)) break end table.insert(data, text) text = f:Read(128) end local ret = table.concat(data) f:Seek(tell + #ret + 1) return ret end function luapack.BuildFileList(filepath) luapack.LogMsg("Starting Lua file list build of '" .. filepath .. "'!") local time = SysTime() local f = file.Open(filepath, "rb", "GAME") if not f then error("failed to open pack file '" .. filepath .. "' for reading") end local dir = setmetatable({file = f, list = {}}, luapack.directory) local fsize = f:Size() local offset = 0 while offset < fsize do local size = ReadULong(f) local crc = ReadULong(f) local path = ReadString(f) dir:AddFile(path, f:Tell(), size, crc) offset = offset + 4 + 4 + #path + 1 + size f:Seek(offset) end luapack.LogMsg("Lua file list building of '" .. filepath .. "' took " .. SysTime() - time .. " seconds!") return dir end luapack.RootDirectory = luapack.BuildFileList("download/data/luapack/" .. luapack.CurrentHash .. ".dat") local totaltime = 0 function luapack.AddTime(time) totaltime = totaltime + time end function luapack.GetTimeSpentLoading() return totaltime end include("cl_overrides.lua") include("includes/_init.lua") include("cl_entities.lua")
-- ใ‚ทใƒฅใƒผใƒ†ใ‚ฃใƒณใ‚ฐใฎๆ•ตใฎใ‚ทใƒงใƒƒใƒˆใฎๅŸบๆœฌใƒใƒชใ‚จใƒผใ‚ทใƒงใƒณ -- ใƒžใ‚ฏใƒญๅฎš็พฉ้ƒจ ============================================== -- ็ฒพๅบฆใ‚’ไธŠใ’ใ‚‹ใŸใ‚ใฎไธ‹้ง„ใƒ“ใƒƒใƒˆๆ•ฐ -- DxLua: Lua ใฎๆ•ฐๅ€คใฏ double ๅž‹ใงๅๅˆ†็ฒพๅบฆใŒใ‚ใ‚‹ใฎใงไฝฟ็”จใ—ใชใ„ --local SHFTNUM = 15 -- ๆ•ตใฎใ‚ทใƒงใƒƒใƒˆใฎๆœ€ๅคงๆ•ฐ local MAX_ENEMYSHOT = 2000 -- ฯ€ local PI = 3.14159 -- ๅ††ๅ‘จ็އ -- ๆง‹้€ ไฝ“ๅฎš็พฉ้ƒจ ============================================== -- ๆ•ตใฎใ‚ทใƒงใƒƒใƒˆใฎใƒ‡ใƒผใ‚ฟๆง‹้€ ไฝ“ๅž‹ -- DxLua: Lua ใซๆง‹้€ ไฝ“ใฏ็„กใ„ใŸใ‚ใƒ†ใƒผใƒ–ใƒซใจใ—ใฆๅฎš็พฉ function ENEMYSHOT(t) t = t or {} return { x = t.x or 0, y = t.y or 0, sx = t.sx or 0, sy = t.sy or 0, Size = t.Size or 0, ValidFlag = t.ValidFlag or false, } end -- ๆ•ตใฎใƒ‡ใƒผใ‚ฟๆง‹้€ ไฝ“ๅž‹ function ENEMY(t) t = t or {} return { x = t.x or 0, y = t.y or 0, Counter = t.Counter or 0, Counter2 = t.Counter2 or 0, Angle = t.Angle or 0, } end -- ใƒ—ใƒฌใ‚คใƒคใƒผใฎใƒ‡ใƒผใ‚ฟๆง‹้€ ไฝ“ๅž‹ function PLAYER(t) t = t or {} return { x = t.x or 0, y = t.y or 0, } end -- ใƒ‡ใƒผใ‚ฟๅฎฃ่จ€้ƒจ =============================================== -- ๆ•ตใฎใƒ‡ใƒผใ‚ฟ local Enemy = ENEMY() -- ๆ•ตใฎใ‚ทใƒงใƒƒใƒˆใƒ‡ใƒผใ‚ฟ local EnemyShot = {} for i = 1, MAX_ENEMYSHOT do EnemyShot[i] = ENEMYSHOT() end -- ๆ•ตใฎใ‚ทใƒงใƒƒใƒˆใฎๆ•ฐ local EnemyShotNum = 0 -- ใƒ—ใƒฌใ‚คใƒคใƒผใƒ‡ใƒผใ‚ฟ local Player = PLAYER() -- ๆ•ตใฎใ‚ทใƒงใƒƒใƒˆใƒ‘ใ‚ฟใƒผใƒณใƒŠใƒณใƒใƒผ local ShotMode = 1 -- ๆ•ตใฎใ‚ทใƒงใƒƒใƒˆๅ‡ฆ็†้–ขๆ•ฐใฎใƒใ‚คใƒณใ‚ฟ้…ๅˆ— local EnemyShred = {} -- ใƒ—ใƒญใ‚ฐใƒฉใƒ ้ƒจ =============================================== -- ็”ป้ขใƒขใƒผใƒ‰ใฎใ‚ปใƒƒใƒˆ dx.SetGraphMode(640, 480, 16) -- ๏ผค๏ผธใƒฉใ‚คใƒ–ใƒฉใƒชๅˆๆœŸๅŒ–ๅ‡ฆ็† function dx.Init() -- ่ฃ็”ป้ขใ‚’ไฝฟ็”จ dx.SetDrawScreen(dx.DX_SCREEN_BACK) -- ๅผพใฎๆ•ฐใฎๅˆๆœŸๅŒ– EnemyShotNum = 0 -- ๆ•ตใฎใƒ‡ใƒผใ‚ฟใฎๅˆๆœŸๅŒ– Enemy.x = 320 Enemy.y = 80 Enemy.Counter = 0 Enemy.Counter2 = 0 Enemy.Angle = 0.0 -- ่‡ชๆฉŸใฎไฝ็ฝฎใฎๅˆๆœŸๅŒ– Player.x = 320 Player.y = 400 -- ๆ•ตใฎใ‚ทใƒงใƒƒใƒˆใ‚ฟใ‚คใƒ—ใ‚’ๅˆๆœŸๅŒ– ShotMode = 1 end -- ใƒซใƒผใƒ— function dx.Update() if dx.CheckHitKey(dx.KEY_INPUT_ESCAPE) ~= 0 then return 'exit' end -- ็”ป้ขใฎๅˆๆœŸๅŒ– dx.ClearDrawScreen() -- ่‡ชๆฉŸใฎๅ‡ฆ็† do local Input -- ๅ…ฅๅŠ›ๅ–ๅพ— Input = dx.GetJoypadInputState(dx.DX_INPUT_KEY_PAD1) -- ่‡ชๆฉŸ็งปๅ‹• if bit.band(Input, dx.PAD_INPUT_LEFT) ~= 0 and (Player.x > 10) then Player.x = Player.x - 2 end if bit.band(Input, dx.PAD_INPUT_RIGHT) ~= 0 and (Player.x < 630) then Player.x = Player.x + 2 end if bit.band(Input, dx.PAD_INPUT_UP) ~= 0 and (Player.y > 10) then Player.y = Player.y - 2 end if bit.band(Input, dx.PAD_INPUT_DOWN) ~= 0 and (Player.y < 470) then Player.y = Player.y + 2 end -- ่‡ชๆฉŸใฎๆ็”ป do local x, y x = Player.x y = Player.y dx.DrawBox(x - 5, y - 5, x + 5, y + 5, dx.GetColor(255, 255, 0), false) end end -- ๅผพใฎๅ‡ฆ็† do local Con, Num -- ๅผพใฎๆ•ฐใ ใ‘็งปๅ‹•ๅ‡ฆ็†ใ‚’็นฐใ‚Š่ฟ”ใ™ Con = 0 Num = EnemyShotNum for i = 1, MAX_ENEMYSHOT do -- ๅผพใฎใƒ‡ใƒผใ‚ฟใŒๆœ‰ๅŠนใชๅ ดๅˆใฏๅ‡ฆ็† if EnemyShot[i].ValidFlag == true then -- ็งปๅ‹•ๅ‡ฆ็† EnemyShot[i].x = EnemyShot[i].x + EnemyShot[i].sx EnemyShot[i].y = EnemyShot[i].y + EnemyShot[i].sy -- ็”ป้ขๅค–ใซๅ‡บใŸใ‚‰ๅผพๆƒ…ๅ ฑใ‚’ๆถˆๅŽปใ™ใ‚‹ if (EnemyShot[i].x < -20) or (EnemyShot[i].x > 660) or (EnemyShot[i].y < -20) or (EnemyShot[i].y > 500) then -- ใƒ‡ใƒผใ‚ฟใฎๆœ‰ๅŠนใƒ•ใƒฉใ‚ฐใ‚’ๅ€’ใ™ EnemyShot[i].ValidFlag = false -- ๅผพใฎๆ•ฐใ‚’ๆธ›ใ‚‰ใ™ EnemyShotNum = EnemyShotNum - 1 end -- ๅผพใฎๆ็”ป do local x, y x = EnemyShot[i].x y = EnemyShot[i].y dx.DrawCircle(x, y, EnemyShot[i].Size, dx.GetColor(255, 255, 255), false) end -- ๅ‡ฆ็†ใ—ใŸๅผพใฎๆ•ฐใ‚’ใ‚คใƒณใ‚ฏใƒชใƒกใƒณใƒˆ Con = Con + 1 -- ๅ‡ฆ็†ใ—ใŸๅผพใฎๆ•ฐใŒใ€ๅญ˜ๅœจใ—ใฆใ„ใ‚‹ๅผพใฎๆ•ฐใจๅŒใ˜ใซใชใฃใŸๅ ดๅˆใฏใƒซใƒผใƒ—ใ‚’ๆŠœใ‘ใ‚‹ if Num < Con then break end end end end -- ๆ•ตใฎๅ‡ฆ็† do -- ๆ•ตใฎใ‚ทใƒงใƒƒใƒˆๅ‡ฆ็† EnemyShred[ShotMode]() -- ๆ•ตใฎๆ็”ป do local x, y x = Enemy.x y = Enemy.y dx.DrawCircle(x, y, 10, dx.GetColor(255, 255, 255), false) end end -- ๆ•ตใฎใ‚ทใƒงใƒƒใƒˆใฎๅˆ‡ใ‚Šๆ›ฟใˆๅ‡ฆ็† do local C -- ๅ…ฅๅŠ›ใ•ใ‚ŒใŸๆ–‡ๅญ—ใ‚’ๅ–ๅพ— C = dx.GetInputChar(true) -- ๏ผฃใ‚ญใƒผใŒๆŠผใ•ใ‚ŒใŸใ‚‰ๆ•ตใฎใ‚ทใƒงใƒƒใƒˆใƒขใƒผใƒ‰ใ‚’ๅค‰ๆ›ดใ™ใ‚‹ if C == string.byte('C') or C == string.byte('c') then Enemy.Counter2 = 0 Enemy.Counter = 0 Enemy.Angle = 0.0 ShotMode = ShotMode + 1 if ShotMode > 5 then ShotMode = 1 end end end -- DxLua: ใ‚ทใƒงใƒƒใƒˆๅใ‚’่กจ็คบใ™ใ‚‹ dx.DrawString(0, 0, 'ใ‚ทใƒงใƒƒใƒˆ' .. ShotMode .. ': ' .. ShotNames[ShotMode], dx.GetColor(0xFF, 0xFF, 0)) dx.DrawString(0, 0, '\nC ใงๅˆ‡ใ‚Šๆ›ฟใˆใพใ™') -- ็”ป้ขใฎๆ›ดๆ–ฐ dx.ScreenFlip() end -- ใ‚ทใƒงใƒƒใƒˆใฎ่ฟฝๅŠ ้–ขๆ•ฐ function ShotAdd(x, y, Size, Angle, Speed) local i = MAX_ENEMYSHOT + 1 -- ไฝฟใ‚ใ‚Œใฆใ„ใชใ„ใ‚ทใƒงใƒƒใƒˆใ‚’ๆคœ็ดข for j = 1, MAX_ENEMYSHOT do if EnemyShot[j].ValidFlag == false then i = j break end end if i > MAX_ENEMYSHOT then return -1 end -- ๆ–ฐใ—ใ„ใ‚ทใƒงใƒƒใƒˆใฎใƒ‡ใƒผใ‚ฟใ‚’ๅˆๆœŸๅŒ– do -- ๅบงๆจ™ใ‚ปใƒƒใƒˆ EnemyShot[i].x = x EnemyShot[i].y = y -- ใ‚ตใ‚คใ‚บใ‚ปใƒƒใƒˆ EnemyShot[i].Size = Size -- ้ฃ›ใ‚“ใง่กŒใๆ–นๅ‘ใจใ‚นใƒ”ใƒผใƒ‰ใ‹ใ‚‰ใ€๏ผธ่ปธๆ–นๅ‘ใธใฎ็งปๅ‹•้€Ÿๅบฆใจ๏ผน่ปธๆ–นๅ‘ใธใฎ็งปๅ‹•้€Ÿๅบฆใ‚’ๅพ—ใ‚‹ EnemyShot[i].sx = math.cos(Angle) * Speed EnemyShot[i].sy = math.sin(Angle) * Speed -- ใ‚ทใƒงใƒƒใƒˆใƒ‡ใƒผใ‚ฟใฎๆœ‰ๅŠนใƒ•ใƒฉใ‚ฐใ‚’็ซ‹ใฆใ‚‹ EnemyShot[i].ValidFlag = true -- ใ‚ทใƒงใƒƒใƒˆใฎๆ•ฐใ‚’ๅข—ใ‚„ใ™ EnemyShotNum = EnemyShotNum + 1 end -- ็ต‚ไบ† return 0 end -- ๅ›ž่ปขใ‚ทใƒงใƒƒใƒˆ function ShotType5() -- ใ‚ซใ‚ฆใƒณใ‚ฟใŒ๏ผ’ใซใชใฃใŸใ‚‰ใ‚ทใƒงใƒƒใƒˆๅ‡ฆ็†ใ‚’่กŒใ† if Enemy.Counter == 2 then -- ใ‚ทใƒงใƒƒใƒˆใฎๆ–นๅ‘ใ‚’ๅค‰ๆ›ด Enemy.Angle = Enemy.Angle + 0.2 -- ้€Ÿๅบฆใฎ้•ใ†ไบ”ใคใฎใ‚ทใƒงใƒƒใƒˆใ‚’็™บๅฐ„ for i = 1, 5 do ShotAdd(Enemy.x, Enemy.y, 6, Enemy.Angle, (3) + ((i - 1) * 8000)) end -- ใ‚ซใ‚ฆใƒณใ‚ฟใ‚’ๅˆๆœŸๅŒ–ใ™ใ‚‹ Enemy.Counter = 0 else Enemy.Counter = Enemy.Counter + 1 end -- ็ต‚ไบ† return 0 end -- ใฐใ‚‰ๆ’’ใใ‚ทใƒงใƒƒใƒˆ function ShotType4() -- ใ‚ซใ‚ฆใƒณใ‚ฟ๏ผ’ใฎๅ€คใซใ‚ˆใฃใฆๅ‡ฆ็†ใ‚’ๅˆ†ๅฒ if Enemy.Counter2 == 0 then -- ๅพ…ใกๅ‡ฆ็† -- ใ‚ซใ‚ฆใƒณใ‚ฟใ‚’ใ‚คใƒณใ‚ฏใƒชใƒกใƒณใƒˆ Enemy.Counter = Enemy.Counter + 1 -- ใ‚ซใ‚ฆใƒณใ‚ฟใŒ๏ผ–๏ผใซใชใฃใŸใ‚‰ใ‚ซใ‚ฆใƒณใ‚ฟ๏ผ’ใฎๅ€คใ‚’ๅข—ใ‚„ใ—ใฆใ€ใ‚ทใƒงใƒƒใƒˆๅ‡ฆ็†ใซ็งปใ‚‹ if Enemy.Counter > 60 then Enemy.Counter2 = Enemy.Counter2 + 1 Enemy.Counter = 0 -- ใ“ใฎใจใใฎ่‡ชๆฉŸใธใฎๆ–นๅ‘ใ‚’ไฟๅญ˜ Enemy.Angle = math.atan2(Player.y - Enemy.y, Player.x - Enemy.x) end elseif Enemy.Counter2 == 1 then --ใ‚ทใƒงใƒƒใƒˆๅ‡ฆ็† -- ใ‚ซใ‚ฆใƒณใ‚ฟใŒ๏ผ’ใฎๅ€ๆ•ฐใฎๆ™‚ใฎใฟใ‚ทใƒงใƒƒใƒˆใ™ใ‚‹ if Enemy.Counter % 2 == 0 then local Angle -- ้ฃ›ใฐใ™ๆ–นๅ‘ใซใถใ‚Œใ‚’ใคใ‘ใ‚‹ Angle = Enemy.Angle + (PI / 3600 * (dx.GetRand(800) - 400)) -- ใ‚ทใƒงใƒƒใƒˆ ShotAdd(Enemy.x, Enemy.y, 5, Angle, 3) end -- ใ‚ซใ‚ฆใƒณใ‚ฟใ‚’ใ‚คใƒณใ‚ฏใƒชใƒกใƒณใƒˆใ€ใ‚ซใ‚ฆใƒณใƒˆใŒ๏ผ•๏ผใซใชใฃใŸใ‚‰ๅพ…ใกใซๆˆปใ‚‹ Enemy.Counter = Enemy.Counter + 1 if Enemy.Counter == 50 then Enemy.Counter2 = 0 Enemy.Counter = 0 end end -- ็ต‚ไบ† return 0 end -- ไธ€็‚นๆ‰‹ไธญๆ™‚้–“ๅทฎใ‚ทใƒงใƒƒใƒˆ function ShotType3() -- ใ‚ซใ‚ฆใƒณใ‚ฟ๏ผ’ใฎๅ€คใซใ‚ˆใฃใฆๅ‡ฆ็†ใ‚’ๅˆ†ๅฒ if Enemy.Counter2 == 0 then -- ๅพ…ใกๅ‡ฆ็† -- ใ‚ซใ‚ฆใƒณใ‚ฟใ‚’ใ‚คใƒณใ‚ฏใƒชใƒกใƒณใƒˆ Enemy.Counter = Enemy.Counter + 1 -- ใ‚ซใ‚ฆใƒณใ‚ฟใŒ๏ผ–๏ผใซใชใฃใŸใ‚‰ใ‚ซใ‚ฆใƒณใ‚ฟ๏ผ’ใฎๅ€คใ‚’ๅข—ใ‚„ใ—ใฆใ€ใ‚ทใƒงใƒƒใƒˆๅ‡ฆ็†ใซ็งปใ‚‹ if Enemy.Counter > 60 then Enemy.Counter2 = Enemy.Counter2 + 1 Enemy.Counter = 0 -- ใ“ใฎใจใใฎ่‡ชๆฉŸใธใฎๆ–นๅ‘ใ‚’ไฟๅญ˜ Enemy.Angle = math.atan2(Player.y - Enemy.y, Player.x - Enemy.x) end elseif Enemy.Counter2 == 1 then -- ใ‚ทใƒงใƒƒใƒˆๅ‡ฆ็† -- ใ‚ซใ‚ฆใƒณใ‚ฟใŒ๏ผ•ใฎๅ€ๆ•ฐใฎๆ™‚ใฎใฟใ‚ทใƒงใƒƒใƒˆใ™ใ‚‹ if Enemy.Counter % 5 == 0 then ShotAdd(Enemy.x, Enemy.y, 4, Enemy.Angle, (1) + (Enemy.Counter) / 15) end -- ใ‚ซใ‚ฆใƒณใ‚ฟใ‚’ใ‚คใƒณใ‚ฏใƒชใƒกใƒณใƒˆใ€ใ‚ซใ‚ฆใƒณใƒˆใŒ๏ผ•๏ผใซใชใฃใŸใ‚‰ๅพ…ใกใซๆˆปใ‚‹ Enemy.Counter = Enemy.Counter + 1 if Enemy.Counter == 50 then Enemy.Counter2 = 0 Enemy.Counter = 0 end end -- ็ต‚ไบ† return 0 end -- ๅ…จๆ–นๅ‘ใ‚ทใƒงใƒƒใƒˆใฎ้–ขๆ•ฐ function ShotType2() -- ใ‚ซใ‚ฆใƒณใ‚ฟใŒ๏ผ‘๏ผใซใชใฃใŸใ‚‰ใ‚ทใƒงใƒƒใƒˆใ™ใ‚‹ if Enemy.Counter == 10 then local Angle, d -- ๆ•ตใ‹ใ‚‰่ฆ‹ใŸ่‡ชๆฉŸใธใฎๆ–นๅ‘ใ‚’ๅ–ๅพ— Angle = math.atan2(Player.y - Enemy.y, Player.x - Enemy.x) -- ใƒฏใ‚คใƒ‰ใ‚ทใƒงใƒƒใƒˆๅ‡ฆ็†ใ€ๅฐ‘ใ—ใšใค่ง’ๅบฆใ‚’ๅค‰ใˆใฆไธ€ๅ‘จๅˆ†ใ‚ทใƒงใƒƒใƒˆ d = Angle - PI for i = 1, 20 do ShotAdd(Enemy.x, Enemy.y, 4, d, 4) d = d + (2 * PI / 20) end -- ใ‚ซใ‚ฆใƒณใ‚ฟใ‚’ๅˆๆœŸๅŒ– Enemy.Counter = 0 else -- ใ‚ซใ‚ฆใƒณใ‚ฟใ‚’ใ‚คใƒณใ‚ฏใƒชใƒกใƒณใƒˆ Enemy.Counter = Enemy.Counter + 1 end -- ็ต‚ไบ† return 0 end -- ๏ผ“๏ผท๏ผก๏ผนใ‚ทใƒงใƒƒใƒˆใฎ้–ขๆ•ฐ function ShotType1() -- ใ‚ซใ‚ฆใƒณใ‚ฟใŒ๏ผ”๏ผใซใชใฃใŸใ‚‰ใ‚ทใƒงใƒƒใƒˆใ™ใ‚‹ if Enemy.Counter == 40 then local Angle, d -- ๆ•ตใ‹ใ‚‰่ฆ‹ใŸ่‡ชๆฉŸใธใฎๆ–นๅ‘ใ‚’ๅ–ๅพ— Angle = math.atan2(Player.y - Enemy.y, Player.x - Enemy.x) -- ๏ผ“๏ผท๏ผก๏ผนใ‚ทใƒงใƒƒใƒˆๅ‡ฆ็† d = Angle - (PI / 3) / 2 for i = 1, 3 do ShotAdd(Enemy.x, Enemy.y, 4, d, 2) d = d + ((PI / 3) / 2) end -- ใ‚ซใ‚ฆใƒณใ‚ฟใ‚’ๅˆๆœŸๅŒ– Enemy.Counter = 0 else -- ใ‚ซใ‚ฆใƒณใ‚ฟใ‚’ใ‚คใƒณใ‚ฏใƒชใƒกใƒณใƒˆ Enemy.Counter = Enemy.Counter + 1 end -- ็ต‚ไบ† return 0 end -- DxLua: ใ“ใ“ใง้–ขๆ•ฐใƒ†ใƒผใƒ–ใƒซใ‚’็”จๆ„ EnemyShred = { ShotType1, ShotType2, ShotType3, ShotType4, ShotType5, } -- DxLua: ใ‚ทใƒงใƒƒใƒˆๅใƒ†ใƒผใƒ–ใƒซ ShotNames = { '๏ผ“๏ผท๏ผก๏ผนใ‚ทใƒงใƒƒใƒˆ', 'ๅ…จๆ–นๅ‘ใ‚ทใƒงใƒƒใƒˆ', 'ไธ€็‚นๆ‰‹ไธญๆ™‚้–“ๅทฎใ‚ทใƒงใƒƒใƒˆ', 'ใฐใ‚‰ๆ’’ใใ‚ทใƒงใƒƒใƒˆ', 'ๅ›ž่ปขใ‚ทใƒงใƒƒใƒˆ', }
vim.g.terminal_key = "<m-@>"
--[[ Copyright (C) 2017-2019 Google Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. ]] local asserts = require 'testing.asserts' local test_runner = require 'testing.test_runner' local maze_generation = require 'dmlab.system.maze_generation' local gen = require 'map_generators.keys_doors.gen' local CONF_RED_HERRING_KEY = { coreSequenceLength = 1, numTrapRooms = 0, addToGoalRoom = false, numEasyExtraRooms = 0, numRedHerringRooms = 0, numUnopenableDoors = 0, numUselessKeys = 1, numOpenableDoors = 0, } local CONF_SIMPLE_TRAP = { coreSequenceLength = 2, numRedHerringRoomUselessKeys = 1, redHerringRespectCoreOrder = true, probRedHerringRoomDuringCore = 1, numTrapRooms = 0, addToGoalRoom = false, numEasyExtraRooms = 0, numRedHerringRooms = 1, numUnopenableDoors = 0, numUselessKeys = 0, numOpenableDoors = 0, coreNoEarlyKeys = true, -- need to switch this off otherwise the red herring room might -- not be attached in the right place numMaxEmptyRooms = 0, startRoomGridPositions = {{1, 2}, {2, 1}, {3, 2}, {2, 3}}, } local CONF_TRAP = { coreSequenceLength = 2, numTrapRooms = 1, addToGoalRoom = false, numEasyExtraRooms = 0, numRedHerringRooms = 0, numUnopenableDoors = 0, numUselessKeys = 0, numOpenableDoors = 0, startRoomGridPositions = {{1, 2}, {2, 1}, {3, 2}, {2, 3}}, } local SEED = 156844960 -- Set the cl number as the random seed. local tests = {} -- Returns the list of the positions of each character in the maze. local function charPositions(maze) local height, width = maze:size() local pos = {} for i = 1, height do for j = 1, width do local char = maze:getEntityCell(i, j) if pos[char] then pos[char][#pos[char] + 1] = {i, j} else pos[char] = {{i, j}} end end end return pos end -- Returns whether there is a path between two points in a maze. local function hasPath(maze, from, to) return maze:visitRandomPath{ seed = 0, from = from, to = to, wall = '*H', func = function() end, } end function tests.confRedHerringKey() local level = gen.makeLevel(CONF_RED_HERRING_KEY, SEED) -- When complied with libstdc++ GCC 4.9. local map0 = [[ *********** *********** ** I ** **K *G ** *** ******* ** ****** **KP ****** *********** *********** ]] -- When complied with libc++. local map1 = [[ *********** *********** **P ****** **K ****** *** ******* ** I ** ** K* G** *********** *********** ]] assert(level.map == map0 or level.map == map1, level.map) asserts.EQ(#level.keys, 2) asserts.EQ(#level.doors, 1) assert(level.doors[1] == level.keys[1] or level.doors[1] == level.keys[2], 'Actual ' .. level.doors[1]) end function tests.batchConfRedHerringKey() local num_dup = 0 local maps = {} for seed = 1, 100 do local level = gen.makeLevel(CONF_RED_HERRING_KEY, seed) if maps[level.map] then num_dup = num_dup + 1 else maps[level.map] = 1 end -- Replace all 'I' with 'H' for easier counting. level.map = level.map:gsub('I', 'H') local maze = maze_generation.mazeGeneration{entity = level.map} local pos = charPositions(maze) asserts.EQ(#pos['H'], 1) asserts.EQ(#pos['K'], 2) asserts.EQ(#pos['P'], 1) asserts.EQ(#pos['G'], 1) asserts.EQ(#level.keys, 2) asserts.EQ(#level.doors, 1) asserts.NE(level.keys[1], level.keys[2]) assert(level.keys[1] == level.doors[1] or level.keys[2] == level.doors[1]) asserts.EQ(hasPath(maze, pos['P'][1], pos['G'][1]), false) asserts.EQ(hasPath(maze, pos['P'][1], pos['K'][1]), true) asserts.EQ(hasPath(maze, pos['P'][1], pos['K'][2]), true) maze:setEntityCell(pos['H'][1][1], pos['H'][1][2], ' ') asserts.EQ(hasPath(maze, pos['P'][1], pos['G'][1]), true) end asserts.GT(20, num_dup) end function tests.confSimpleTrap() local level = gen.makeLevel(CONF_SIMPLE_TRAP, SEED) -- When complied with libstdc++ GCC 4.9. local map0 = [[ *************** *************** ** I I ** **G *KP *K ** *******H******* ****** ****** ******K ****** *************** *************** ]] -- When complied with libc++. local map1 = [[ *************** *************** ** I I ** ** G*KP *K ** *******H******* ****** ****** ****** K****** *************** *************** ]] assert(level.map == map0 or level.map == map1, level.map) asserts.EQ(#level.keys, 3) asserts.EQ(#level.doors, 3) end function tests.batchConfSimpleTrap() local num_dup = 0 local maps = {} for seed = 1, 100 do local level = gen.makeLevel(CONF_SIMPLE_TRAP, seed) if maps[level.map] then num_dup = num_dup + 1 else maps[level.map] = 1 end -- Replace all 'I' with 'H' for easier counting. level.map = level.map:gsub('I', 'H') local maze = maze_generation.mazeGeneration{entity = level.map} local pos = charPositions(maze) asserts.EQ(#pos['H'], 3) asserts.EQ(#pos['K'], 3) asserts.EQ(#pos['P'], 1) asserts.EQ(#pos['G'], 1) -- Find out the color of the first key. local first_key_color = nil maze:visitFill{ cell = pos['P'][1], wall = '*H', func = function(row, col, distance) if maze:getEntityCell(row, col) == 'K' then asserts.EQ(first_key_color, nil) for i = 1, 3 do if pos['K'][i][1] == row and pos['K'][i][2] == col then first_key_color = level.keys[i] end end maze:setEntityCell(row, col, ' ') end end } -- Open all doors with the same color of the first key. local num_opened_doors = 0 for i = 1, 3 do if level.doors[i] == first_key_color then maze:setEntityCell(pos['H'][i][1], pos['H'][i][2], ' ') num_opened_doors = num_opened_doors + 1 end end asserts.EQ(num_opened_doors, 2) -- Make sure the goal is not reachable at this time. asserts.EQ(hasPath(maze, pos['P'][1], pos['G'][1]), false) -- Get the colors of the keys we can get now. local second_keys = {} maze:visitFill{ cell = pos['P'][1], wall = '*H', func = function(row, col, distance) if maze:getEntityCell(row, col) == 'K' then for i = 1, 3 do if pos['K'][i][1] == row and pos['K'][i][2] == col then second_keys[#second_keys + 1] = level.keys[i] end end maze:setEntityCell(row, col, ' ') end end } asserts.EQ(#second_keys, 2) asserts.NE(second_keys[1], second_keys[2]) -- Open the final door. for i = 1, 3 do if level.doors[i] == second_keys[1] or level.doors[i] == second_keys[2] then maze:setEntityCell(pos['H'][i][1], pos['H'][i][2], ' ') num_opened_doors = num_opened_doors + 1 end end asserts.EQ(num_opened_doors, 3) -- The goal is reachable now. asserts.EQ(hasPath(maze, pos['P'][1], pos['G'][1]), true) end asserts.GT(20, num_dup) end function tests.confTrap() local level = gen.makeLevel(CONF_TRAP, SEED) -- When complied with libstdc++ GCC 4.9. local map0 = [[ *************** *************** ** I P * ** ** K* *G ** ******* ***H*** ****** I ** ******K *K ** *************** *************** ]] -- When complied with libc++. local map1 = [[ *************** *************** ** I P* ** ** K*K * G** ******* ***H*** ****** I ** ****** * K** *************** *************** ]] assert(level.map == map0 or level.map == map1, level.map) asserts.EQ(#level.keys, 3) asserts.EQ(#level.doors, 3) end function tests.batchConfTrap() local num_dup = 0 local maps = {} for seed = 1, 100 do local level = gen.makeLevel(CONF_TRAP, seed) if maps[level.map] then num_dup = num_dup + 1 else maps[level.map] = 1 end -- Replace all 'I' with 'H' for easier counting. level.map = level.map:gsub('I', 'H') local maze = maze_generation.mazeGeneration{entity = level.map} local pos = charPositions(maze) asserts.EQ(#pos['H'], 3) asserts.EQ(#pos['K'], 3) asserts.EQ(#pos['P'], 1) asserts.EQ(#pos['G'], 1) local key_colors = {} for i = 1, 3 do if key_colors[level.keys[i]] then key_colors[level.keys[i]] = key_colors[level.keys[i]] + 1 else key_colors[level.keys[i]] = 1 end end local door_colors = {} for i = 1, 3 do if door_colors[level.doors[i]] then door_colors[level.doors[i]] = door_colors[level.doors[i]] + 1 else door_colors[level.doors[i]] = 1 end end -- There should be two keys with the same color and one with another color. local first_key_color = nil local second_key_color = nil for color, count in pairs(door_colors) do if count == 2 then first_key_color = color elseif count == 1 then second_key_color = color end end assert(first_key_color) assert(second_key_color) local first_key_id = nil for i = 1, 3 do if level.keys[i] == first_key_color then assert(first_key_id == nil) first_key_id = i else asserts.EQ(level.keys[i], second_key_color) end end -- There should be exactly one door with first_key_color. local last_door_id = nil for i = 1, 3 do if level.doors[i] == second_key_color then assert(last_door_id == nil) last_door_id = i else asserts.EQ(level.doors[i], first_key_color) end end -- Should be able to reach the first key. asserts.EQ(hasPath(maze, pos['P'][1], pos['K'][first_key_id]), true) local num_solutions = 0 for i = 1, 3 do -- There are 2 doors which can be opened with the first key, among which -- only one is the correct door. if level.doors[i] == first_key_color then -- Open the first door. maze:setEntityCell(pos['H'][i][1], pos['H'][i][2], ' ') -- Should be able to reach the door. asserts.EQ(hasPath(maze, pos['P'][1], pos['H'][i]), true) -- Should not be able to reach the goal at this time. asserts.EQ(hasPath(maze, pos['P'][1], pos['G'][1]), false) local succeed_to_get_second_key = false for j = 1, 3 do -- Should be able to reach a new key by opening this door. if level.keys[j] == second_key_color then if hasPath(maze, pos['H'][i], pos['K'][j]) then succeed_to_get_second_key = true -- Open the second door. maze:setEntityCell(pos['H'][last_door_id][1], pos['H'][last_door_id][2], ' ') -- Test if we can reach the goal. if hasPath(maze, pos['K'][j], pos['G'][1]) then num_solutions = num_solutions + 1 end -- Reset the second door. maze:setEntityCell(pos['H'][last_door_id][1], pos['H'][last_door_id][2], 'H') end end end asserts.EQ(succeed_to_get_second_key, true) -- Reset the first door. maze:setEntityCell(pos['H'][i][1], pos['H'][i][2], 'H') end end asserts.EQ(num_solutions, 1) end asserts.GT(5, num_dup) end return test_runner.run(tests)
function display_type(env, t) print(tostring(t) .. " : " .. tostring(env:normalize(env:type_check(t)))) end local env = environment() local l = param_univ("l") local U_l = mk_sort(l) local U_l1 = mk_sort(max_univ(l, 1)) -- Make sure U_l1 is not Prop local A = Local("A", U_l) local list_l = Const("list", {l}) local env1 = add_inductive(env, "list", {l}, 1, Pi(A, U_l1), "nil", Pi(A, list_l(A)), "cons", Pi(A, mk_arrow(A, list_l(A), list_l(A)))) display_type(env1, Const("list_rec", {1, 1})) -- Slightly different definition where A : Type.{l} is an index -- instead of a global parameter local U_sl = mk_sort(succ_univ(l)) local env2 = add_inductive(env, "list", {l}, 0, Pi(A, U_sl), -- The resultant type must live in the universe succ(l) "nil", Pi(A, list_l(A)), "cons", Pi(A, mk_arrow(A, list_l(A), list_l(A)))) display_type(env2, Const("list_rec", {1, 1}))
-- Dat View -- -- Class: Dat File -- Dat File -- local ipairs = ipairs local t_insert = table.insert local t_remove = table.remove local m_min = math.min local dataTypes = { Bool = { size = 1, read = function(b, o, d) return b:byte(o) == 1 end, }, Int = { size = 4, read = function(b, o, d) if o > #b - 3 then return -1337 end return bytesToInt(b, o) end, }, UInt = { size = 4, read = function(b, o, d) if o > #b - 3 then return 1337 end return bytesToUInt(b, o) end, }, Interval = { size = 8, read = function(b, o, d) if o > #b - 7 then return { 1337, 1337 } end return { bytesToInt(b, o), bytesToInt(b, o + 4) } end, }, Float = { size = 4, read = function(b, o, d) if o > #b - 3 then return -1337 end return bytesToFloat(b, o) end, }, String = { size = 4, read = function(b, o, d) if o > #b - 3 then return "<no offset>" end local stro = bytesToUInt(b, o) if stro > #b - 3 then return "<bad offset>" end return convertUTF16to8(b, d + stro) end, }, Enum = { size = 4, ref = true, read = function(b, o, d) if o > #b - 3 then return 1337 end return bytesToUInt(b, o) end, }, Key = { size = 8, ref = true, read = function(b, o, d) if o > #b - 7 then return 1337 end return bytesToUInt(b, o) end, }, } local DatFileClass = newClass("DatFile", function(self, name, raw) self.name = name self.raw = raw if not main.datSpecs[self.name] then main.datSpecs[self.name] = { } end self.spec = main.datSpecs[self.name] self.cols = { } self.colMap = { } self.indexes = { } local colMeta = { __index = function(t, key) local colIndex = self.colMap[key] if not colIndex then error("Unknown key "..key.." for "..self.name..".dat") end t[key] = self:ReadCell(t._rowIndex, colIndex) return rawget(t, key) end } self.rowCache = setmetatable({ }, { __index = function(t, rowIndex) if rowIndex < 1 or rowIndex > self.rowCount then return end t[rowIndex] = setmetatable({ _rowIndex = rowIndex }, colMeta) return t[rowIndex] end }) self.rows = { } self.rowCount = bytesToUInt(self.raw) self.dataOffset = self.raw:find("\xBB\xBB\xBB\xBB\xBB\xBB\xBB\xBB", 5, true) or (#self.raw + 1) self.rowSize = (self.dataOffset - 5) / self.rowCount for i = 1, self.rowCount do self.rows[i] = 5 + (i-1) * self.rowSize end --ConPrintf("Loaded '%s': %d Rows at %d Bytes", self.name, self.rowCount, self.rowSize) self:OnSpecChanged() end) function DatFileClass:OnSpecChanged() wipeTable(self.cols) wipeTable(self.colMap) wipeTable(self.indexes) wipeTable(self.rowCache) local offset = 0 for i, specCol in ipairs(self.spec) do local dataType = dataTypes[specCol.type] local size = specCol.list and 8 or dataType.size self.cols[i] = { size = size, offset = offset, isRef = dataType.ref, } offset = offset + size if #specCol.name > 0 then self.colMap[specCol.name] = i end end self.specSize = offset self.cols[#self.spec + 1] = { size = self.rowSize - offset, offset = offset, } end function DatFileClass:GetRow(key, value) local keyIndex = self.colMap[key] if not keyIndex then error("Unknown key "..key.." for "..self.name..".dat") end if not self.indexes[key] then self.indexes[key] = { } end for rowIndex = 1, self.rowCount do if not self.indexes[key][rowIndex] then self.indexes[key][rowIndex] = self:ReadCell(rowIndex, keyIndex) end if self.indexes[key][rowIndex] == value then return self.rowCache[rowIndex] end end end function DatFileClass:GetRowByIndex(rowIndex) return self.rowCache[rowIndex] end function DatFileClass:Rows() local i = 0 return function() i = i + 1 if i <= self.rowCount then return self:GetRowByIndex(i) end end end function DatFileClass:GetRowList(key, value, match) local keyIndex = self.colMap[key] if not keyIndex then error("Unknown key "..key.." for "..self.name..".dat") end if not self.indexes[key] then self.indexes[key] = { } end local out = { } for rowIndex = 1, self.rowCount do if not self.indexes[key][rowIndex] then self.indexes[key][rowIndex] = self:ReadCell(rowIndex, keyIndex) end if dataTypes[self.spec[keyIndex].type].list then for _, index in ipairs(self.indexes[key][rowIndex]) do if (match and index:match(value)) or (not match and index == value) then t_insert(out, self.rowCache[rowIndex]) break end end else if (match and self.indexes[key][rowIndex]:match(value)) or (not match and self.indexes[key][rowIndex] == value) then t_insert(out, self.rowCache[rowIndex]) end end end return out end function DatFileClass:ReadCell(rowIndex, colIndex) local spec = self.spec[colIndex] local col = self.cols[colIndex] local base = self.rows[rowIndex] + col.offset if spec.list then local dataType = dataTypes[spec.type] local count = bytesToUInt(self.raw, base) local offset = bytesToUInt(self.raw, base + 4) + self.dataOffset local out = { } for i = 1, m_min(count, 1000) do out[i] = self:ReadValue(spec, offset) offset = offset + dataType.size end return out else return self:ReadValue(spec, base) end end function DatFileClass:ReadValue(spec, offset) local dataType = dataTypes[spec.type] local val = dataType.read(self.raw, offset, self.dataOffset) if not dataType.ref then return val end if val == 0xFEFEFEFE then return end local other = main.datFileByName[spec.refTo] if not other then return end if spec.type == "Enum" and spec.refTo ~= self.name then return val end return other.rowCache[val + 1] end function DatFileClass:ReadCellText(rowIndex, colIndex) local spec = self.spec[colIndex] local col = self.cols[colIndex] local base = self.rows[rowIndex] + col.offset if spec.list then local dataType = dataTypes[spec.type] local count = bytesToUInt(self.raw, base) local offset = bytesToUInt(self.raw, base + 4) + self.dataOffset local out = { } for i = 1, m_min(count, 1000) do out[i] = self:ReadValueText(spec, offset) offset = offset + dataType.size end return out else return self:ReadValueText(spec, base) end end function DatFileClass:ReadValueText(spec, offset) local dataType = dataTypes[spec.type] local val = dataType.read(self.raw, offset, self.dataOffset) if dataType.ref then if val == 0xFEFEFEFE then return "" end local other = main.datFileByName[spec.refTo] if other then local otherRow = other.rows[val + ((spec.type == "Enum" and spec.refTo ~= self.name) and 0 or 1)] if not otherRow then return "<bad ref #"..val..">" end if other.spec[1] then return other:ReadValueText(other.spec[1], otherRow) end end end if spec.type == "Interval" then return val[1] == val[2] and val[1] or (val[1] .. " to " .. val[2]) else return val end end function DatFileClass:ReadCellRaw(rowIndex, colIndex) local col = self.cols[colIndex] local base = self.rows[rowIndex] + col.offset return self.raw:byte(base, base + col.size - 1) end
local function run(msg, matches) local base = "http://dogr.io/" local path = string.gsub(matches[1], " ", "%%20") local url = base .. path .. '.png?split=false&.png' local urlm = "https?://[%%%w-_%.%?%.:/%+=&]+" if string.match(url, urlm) == url then local receiver = get_receiver(msg) send_photo_from_url(receiver, url) else print("Can't build a good URL with parameter " .. matches[1]) end end return { description = "Create a doge image with you words", usage = { "!dogify (your/words/with/slashes): Create a doge with the image and words" }, patterns = { "^!dogify (.+)$", }, run = run }
module 'mock' -------------------------------------------------------------------- CLASS: TileMap2DLayer ( TileMapLayer ) :MODEL{} function TileMap2DLayer:onInit() local tileset = self.tileset self.mapGrid = TileMapGrid( EWGrid.new() ) self.mapGrid:setTileset( tileset ) self.prop = MOAIProp.new() self.prop:setGrid( self.mapGrid:getMoaiGrid() ) self.prop:setDeck( tileset:getMoaiDeck() ) self.mapGrid:setSize( self.width, self.height, self.tileWidth, self.tileHeight, 0, 0, 1, 1 ) end function TileMap2DLayer:worldToModel( x, y ) return self.prop:worldToModel( x, y, -y ) end function TileMap2DLayer:onSetOrder( orde ) end function TileMap2DLayer:onSetOffset( x, y, z ) if self.prop then self.prop:setLoc( x, y, z ) end end function TileMap2DLayer:applyMaterial( material ) material:applyToMoaiProp( self.prop ) end function TileMap2DLayer:onSetVisible( vis ) self.prop:setVisible( vis ) end -------------------------------------------------------------------- CLASS: TileMap2D ( TileMap ) :MODEL{ } registerComponent( 'TileMap2D', TileMap2D ) function TileMap2D:createLayerByTileset( tilesetPath ) local tileset, anode = loadAsset( tilesetPath ) local atype = anode:getType() if atype == 'deck2d.tileset' then return TileMap2DLayer() elseif atype == 'named_tileset' then return TileMap2DLayer() elseif atype == 'code_tileset' then return CodeTileMapLayer() end return false end function TileMap2D:getSupportedTilesetType() return 'deck2d.tileset;named_tileset;deck2d.mtileset;code_tileset' end
if not file.Exists("autorun/luadev.lua", "LUA") then local luadev = lutils.MakeNamespace("luadev") function luadev.RunOnClient(code, target, _) lutils.Execute(code, {target}, {}) end function luadev.RunOnClients(code, _) lutils.Execute(code, player.GetAll(), {}) end function luadev.RunOnShared(code, _) local targets = player.GetAll() table.insert(targets, true) lutils.Execute(code, targets, {}) end function luadev.RunOnSelf(code, _) lutils.Execute(code, {LocalPlayer()}, {}) end function luadev.RunOnServer(code, _) lutils.Execute(code, {true}, {}) end end
-- //////////////////////////////////// -- // MYSQL // -- //////////////////////////////////// sqlUsername = exports.mysql:getMySQLUsername() sqlPassword = exports.mysql:getMySQLPassword() sqlDB = exports.mysql:getMySQLDBName() sqlHost = exports.mysql:getMySQLHost() sqlPort = exports.mysql:getMySQLPort() handler = mysql_connect(sqlHost, sqlUsername, sqlPassword, sqlDB, sqlPort) function checkMySQL() if not (mysql_ping(handler)) then handler = mysql_connect(sqlHost, sqlUsername, sqlPassword, sqlDB, sqlPort) end end setTimer(checkMySQL, 300000, 0) function closeMySQL() if (handler) then mysql_close(handler) end end addEventHandler("onResourceStop", getResourceRootElement(getThisResource()), closeMySQL) -- //////////////////////////////////// -- // MYSQL END // -- //////////////////////////////////// function saveVehicleOnExit(thePlayer, seat, vehicle) if (vehicle) then source = vehicle end local dbid = getElementData(source, "dbid") if (dbid>=0) then -- Check it's a permanently spawned vehicle local tick = getTickCount() local model = getElementModel(source) local x, y, z = getElementPosition(source) local rx, ry, rz = getVehicleRotation(source) local owner = getElementData(source, "owner") if (owner~=-1) then local col1, col2, col3, col4 = getVehicleColor(source) local fuel = getElementData(source, "fuel") local engine = getElementData(source, "engine") local locked = isVehicleLocked(source) if (locked) then locked = 1 else locked = 0 end local lights = getVehicleOverrideLights(source) local sirens = getVehicleSirensOn(source) if (sirens) then sirens = 1 else sirens = 0 end local wheel1, wheel2, wheel3, wheel4 = getVehicleWheelStates(source) mysql_query(handler, "UPDATE vehicles SET model='" .. model .. "', currx='" .. x .. "', curry='" .. y .. "', currz='" .. z .. "', currrx='" .. rx .. "', currry='" .. ry .. "', currrz='" .. rz .. "', color1='" .. col1 .. "', color2='" .. col2 .. "', fuel='" .. fuel .. "', engine='" .. engine .. "', locked='" .. locked .. "', lights='" .. lights .. "', wheel1='" .. wheel1 .. "', wheel2='" .. wheel2 .. "', wheel3='" .. wheel3 .. "', wheel4='" .. wheel4 .. "' WHERE id='" .. dbid .. "'") local panel0 = getVehiclePanelState(source, 0) local panel1 = getVehiclePanelState(source, 1) local panel2 = getVehiclePanelState(source, 2) local panel3 = getVehiclePanelState(source, 3) local panel4 = getVehiclePanelState(source, 4) local panel5 = getVehiclePanelState(source, 5) local panel6 = getVehiclePanelState(source, 6) local door1 = getVehicleDoorState(source, 0) local door2 = getVehicleDoorState(source, 1) local door3 = getVehicleDoorState(source, 2) local door4 = getVehicleDoorState(source, 3) local door5 = getVehicleDoorState(source, 4) local door6 = getVehicleDoorState(source, 5) local health = getElementHealth(source) local paintjob = getVehiclePaintjob(source) local update = mysql_query(handler, "UPDATE vehicles SET panel0='" .. panel0 .. "', panel1='" .. panel1 .. "', panel2='" .. panel2 .. "', panel3='" .. panel3 .. "', panel4='" .. panel4 .. "', panel5='" .. panel5 .. "', panel6='" .. panel6 .. "', door1='" .. door1 .. "', door2='" .. door2 .. "', door3='" .. door3 .. "', door4='" .. door4 .. "', door5='" .. door5 .. "', door6='" .. door6 .. "', hp='" .. health .. "', sirens='" .. sirens .. "', paintjob='" .. paintjob .. "' WHERE id='" .. dbid .. "'") if (update) then mysql_free_result(update) end local timeTaken = (getTickCount() - tick)/1000 exports.irc:sendMessage("[SCRIPT] Saving Vehicle ID #" .. dbid .. " [Exit/Respawn] [" .. timeTaken .. " Seconds].") end end end addEventHandler("onVehicleExit", getRootElement(), saveVehicleOnExit)
cB_KnownItems = { [0] = 0, [4306] = 1400, [2453] = 200, [17034] = 20, [785] = 200, [858] = 20, [6436] = 1, [2447] = 200, [2455] = 20, [3818] = 200, [3385] = 20, [4470] = 200, [4471] = 1, [15462] = 1, [6362] = 200, [3355] = 200, [15467] = 1, [3356] = 400, [3372] = 20, [6948] = 1, [4633] = 1, [6365] = 1, [2459] = 20, [9173] = 1, [3357] = 200, [6358] = 200, [929] = 20, [12008] = 1, [6308] = 200, [2452] = 200, [3531] = 20, [2449] = 200, [3821] = 200, } cBniv = { ["BagPos"] = false, ["BankCustomBags"] = true, }
C_AzeriteEssence = {} ---[Documentation](https://wowpedia.fandom.com/wiki/API_C_AzeriteEssence.ActivateEssence) ---@param essenceID number ---@param milestoneID number function C_AzeriteEssence.ActivateEssence(essenceID, milestoneID) end ---[Documentation](https://wowpedia.fandom.com/wiki/API_C_AzeriteEssence.CanActivateEssence) ---@param essenceID number ---@param milestoneID number ---@return boolean canActivate function C_AzeriteEssence.CanActivateEssence(essenceID, milestoneID) end ---[Documentation](https://wowpedia.fandom.com/wiki/API_C_AzeriteEssence.CanDeactivateEssence) ---@param milestoneID number ---@return boolean canDeactivate function C_AzeriteEssence.CanDeactivateEssence(milestoneID) end ---[Documentation](https://wowpedia.fandom.com/wiki/API_C_AzeriteEssence.CanOpenUI) ---@return boolean canOpen function C_AzeriteEssence.CanOpenUI() end ---[Documentation](https://wowpedia.fandom.com/wiki/API_C_AzeriteEssence.ClearPendingActivationEssence) function C_AzeriteEssence.ClearPendingActivationEssence() end ---[Documentation](https://wowpedia.fandom.com/wiki/API_C_AzeriteEssence.CloseForge) function C_AzeriteEssence.CloseForge() end ---[Documentation](https://wowpedia.fandom.com/wiki/API_C_AzeriteEssence.GetEssenceHyperlink) ---@param essenceID number ---@param rank number ---@return string link function C_AzeriteEssence.GetEssenceHyperlink(essenceID, rank) end ---[Documentation](https://wowpedia.fandom.com/wiki/API_C_AzeriteEssence.GetEssenceInfo) ---@param essenceID number ---@return AzeriteEssenceInfo info function C_AzeriteEssence.GetEssenceInfo(essenceID) end ---[Documentation](https://wowpedia.fandom.com/wiki/API_C_AzeriteEssence.GetEssences) ---@return AzeriteEssenceInfo[] essences function C_AzeriteEssence.GetEssences() end ---[Documentation](https://wowpedia.fandom.com/wiki/API_C_AzeriteEssence.GetMilestoneEssence) ---@param milestoneID number ---@return number essenceID function C_AzeriteEssence.GetMilestoneEssence(milestoneID) end ---[Documentation](https://wowpedia.fandom.com/wiki/API_C_AzeriteEssence.GetMilestoneInfo) ---@param milestoneID number ---@return AzeriteMilestoneInfo info function C_AzeriteEssence.GetMilestoneInfo(milestoneID) end ---[Documentation](https://wowpedia.fandom.com/wiki/API_C_AzeriteEssence.GetMilestoneSpell) ---@param milestoneID number ---@return number spellID function C_AzeriteEssence.GetMilestoneSpell(milestoneID) end ---[Documentation](https://wowpedia.fandom.com/wiki/API_C_AzeriteEssence.GetMilestones) ---@return AzeriteMilestoneInfo[] milestones function C_AzeriteEssence.GetMilestones() end ---[Documentation](https://wowpedia.fandom.com/wiki/API_C_AzeriteEssence.GetNumUnlockedEssences) ---@return number numUnlockedEssences function C_AzeriteEssence.GetNumUnlockedEssences() end ---[Documentation](https://wowpedia.fandom.com/wiki/API_C_AzeriteEssence.GetNumUsableEssences) ---@return number numUsableEssences function C_AzeriteEssence.GetNumUsableEssences() end ---[Documentation](https://wowpedia.fandom.com/wiki/API_C_AzeriteEssence.GetPendingActivationEssence) ---@return number essenceID function C_AzeriteEssence.GetPendingActivationEssence() end ---[Documentation](https://wowpedia.fandom.com/wiki/API_C_AzeriteEssence.HasNeverActivatedAnyEssences) ---@return boolean hasNeverActivatedAnyEssences function C_AzeriteEssence.HasNeverActivatedAnyEssences() end ---[Documentation](https://wowpedia.fandom.com/wiki/API_C_AzeriteEssence.HasPendingActivationEssence) ---@return boolean hasEssence function C_AzeriteEssence.HasPendingActivationEssence() end ---[Documentation](https://wowpedia.fandom.com/wiki/API_C_AzeriteEssence.IsAtForge) ---@return boolean isAtForge function C_AzeriteEssence.IsAtForge() end ---[Documentation](https://wowpedia.fandom.com/wiki/API_C_AzeriteEssence.SetPendingActivationEssence) ---@param essenceID number function C_AzeriteEssence.SetPendingActivationEssence(essenceID) end ---[Documentation](https://wowpedia.fandom.com/wiki/API_C_AzeriteEssence.UnlockMilestone) ---@param milestoneID number function C_AzeriteEssence.UnlockMilestone(milestoneID) end ---@class AzeriteEssenceInfo ---@field ID number ---@field name string ---@field rank number ---@field unlocked boolean ---@field valid boolean ---@field icon number ---@class AzeriteMilestoneInfo ---@field ID number ---@field requiredLevel number ---@field canUnlock boolean ---@field unlocked boolean ---@field rank number|nil ---@field slot AzeriteEssenceSlot|nil
return {'quodlibet','quorum','quota','quotaregeling','quotastelsel','quotasysteem','quotatie','quote','quoten','quoteren','quotering','quoteringsregeling','quoteringssysteem','quotisatie','quotiseren','quotient','quotum','quotumregeling','quotums','quotumsysteem','quodlibets','quorums','quotas','quotaties','quoteer','quoteerde','quoteerden','quoteert','quoteje','quotes','quotisaties','quotienten','quoteringen','quotiseerde','quotaregelingen'}
--- -- Add two complex or real valued signals. -- -- $$ y[n] = x_{1}[n] + x_{2}[n] $$ -- -- @category Math Operations -- @block AddBlock -- -- @signature in1:ComplexFloat32, in2:ComplexFloat32 > out:ComplexFloat32 -- @signature in1:Float32, in2:Float32 > out:Float32 -- -- @usage -- local summer = radio.AddBlock() -- top:connect(src1, 'out', summer, 'in1') -- top:connect(src2, 'out', summer, 'in2') -- top:connect(summer, snk) local block = require('radio.core.block') local types = require('radio.types') local AddBlock = block.factory("AddBlock") function AddBlock:instantiate() self:add_type_signature({block.Input("in1", types.ComplexFloat32), block.Input("in2", types.ComplexFloat32)}, {block.Output("out", types.ComplexFloat32)}) self:add_type_signature({block.Input("in1", types.Float32), block.Input("in2", types.Float32)}, {block.Output("out", types.Float32)}) end function AddBlock:initialize() self.out = self:get_output_type().vector() end function AddBlock:process(x, y) local out = self.out:resize(x.length) for i = 0, x.length-1 do out.data[i] = x.data[i] + y.data[i] end return out end return AddBlock
-------------------------------------------------------------------------------- -- Announcer and announcer-related code -------------------------------------------------------------------------------- Metrostroi.DefineSystem("Announcer") TRAIN_SYSTEM.DontAccelerateSimulation = true if TURBOSTROI then return end function table.GetLastKey(t) local lk = -math.huge for ki in pairs(t) do lk = math.max(lk,ki) end return lk end Metrostroi.Announcements = { [0001] = { 0.700, "" }, [0002] = { 1.500, "" }, [0003]={ 0.600, "subway_announcer/00_03.mp3" }, [0005]={ 0.200, "subway_announcer/00_05.mp3" }, [0006]={ 0.100, "subway_announcer/00_06.mp3" }, [0007]={ 4.577, "subway_announcer/00_07.mp3" }, [0201]={ 1.995, "subway_announcer/02_01.mp3" }, [0202]={ 0.600, "subway_announcer/02_02.mp3" }, [0203]={ 1.000, "subway_announcer/02_03.mp3" }, [0204]={ 2.564, "subway_announcer/02_04.mp3" }, [0205]={ 3.385, "subway_announcer/02_05.mp3" }, [0206]={ 3.806, "subway_announcer/02_06.mp3" }, [0207]={ 3.719, "subway_announcer/02_07.mp3" }, [0208]={ 2.980, "subway_announcer/02_08.mp3" }, [0209]={ 4.958, "subway_announcer/02_09.mp3" }, [0210]={ 2.091, "subway_announcer/02_10.mp3" }, [0211]={ 1.603, "subway_announcer/02_11.mp3" }, [0212]={ 7.187, "subway_announcer/02_12.mp3" }, [0213]={ 4.695, "subway_announcer/02_13.mp3" }, [0214]={ 7.750, "subway_announcer/02_14.mp3" }, [0215]={ 1.991, "subway_announcer/02_15.mp3" }, [0216]={ 1.302, "subway_announcer/02_16.mp3" }, [0217]={ 5.846, "subway_announcer/02_17.mp3" }, [0218]={ 2.341, "subway_announcer/02_18.mp3" }, [0219]={ 1.502, "subway_announcer/02_19.mp3" }, [0220]={ 1.039, "subway_announcer/02_20.mp3" }, [0221]={ 2.216, "subway_announcer/02_21.mp3" }, [0222]={ 3.518, "subway_announcer/02_22.mp3" }, [0223]={ 2.154, "subway_announcer/02_23.mp3" }, [0224]={ 4.094, "subway_announcer/02_24.mp3" }, [0225]={ 3.656, "subway_announcer/02_25.mp3" }, [0226]={ 2.950, "subway_announcer/02_26.mp3" }, [0227]={ 3.255, "subway_announcer/02_27.mp3" }, [0228]={ 4.260, "subway_announcer/02_28.mp3" }, [0229]={ 5.334, "subway_announcer/02_29.mp3" }, [0230]={ 1.515, "subway_announcer/02_30.mp3" }, [0231]={ 1.628, "subway_announcer/02_31.mp3" }, [0232]={ 7.149, "subway_announcer/02_32.mp3" }, [0233]={ 1.315, "subway_announcer/02_33.mp3" }, [0234]={ 1.930, "subway_announcer/02_34.mp3" }, [0235]={ 1.407, "subway_announcer/02_35.mp3" }, [0236]={ 1.372, "subway_announcer/02_36.mp3" }, [0237]={ 1.382, "subway_announcer/02_37.mp3" }, [0238]={ 2.805, "subway_announcer/02_38.mp3" }, [0308]={ 1.152, "subway_announcer/03_08.mp3" }, [0309]={ 1.152, "subway_announcer/03_09.mp3" }, [0310]={ 1.152, "subway_announcer/03_10.mp3" }, [0311]={ 1.111, "subway_announcer/03_11.mp3" }, [0312]={ 1.369, "subway_announcer/03_12.mp3" }, [0313]={ 1.272, "subway_announcer/03_13.mp3" }, [0314]={ 1.052, "subway_announcer/03_14.mp3" }, [0315]={ 1.174, "subway_announcer/03_15.mp3" }, [0316]={ 1.296, "subway_announcer/03_16.mp3" }, [0317]={ 1.712, "subway_announcer/03_17.mp3" }, [0318]={ 1.076, "subway_announcer/03_18.mp3" }, [0319]={ 1.377, "subway_announcer/03_19.mp3" }, [0320]={ 3.490, "subway_announcer/03_20.mp3" }, [0321]={ 0.939, "subway_announcer/03_21.mp3" }, [0322]={ 1.174, "subway_announcer/03_22.mp3" }, [0323]={ 1.377, "subway_announcer/03_23.mp3" }, [0415]={ 1.033, "subway_announcer/04_15.mp3" }, [0521]={ 1.518, "subway_announcer/05_21.mp3" }, [0522]={ 1.969, "subway_announcer/05_22.mp3" }, [0601]={ 1.076, "subway_announcer/06_01.mp3" }, [0602]={ 1.521, "subway_announcer/06_02.mp3" }, [0603]={ 0.939, "subway_announcer/06_03.mp3" }, [0604]={ 0.704, "subway_announcer/06_04.mp3" }, [0605]={ 1.330, "subway_announcer/06_05.mp3" }, [0606]={ 1.663, "subway_announcer/06_06.mp3" }, [0607]={ 1.389, "subway_announcer/06_07.mp3" }, [0608]={ 1.663, "subway_announcer/06_08.mp3" }, [0699]={ 1.399, "subway_announcer/06_99.mp3" }, [0701]={ 1.076, "subway_announcer/06_01.mp3" }, [0702]={ 1.064, "subway_announcer/07_02.mp3" }, [0703]={ 0.939, "subway_announcer/06_03.mp3" }, [0704]={ 1.468, "subway_announcer/07_04.mp3" }, [0799]={ 1.585, "subway_announcer/07_99.mp3" }, [0801]={ 0.923, "subway_announcer/08_01.mp3" }, [9999] = { 3.0, "subway_announcer/00_00.mp3" }, } Metrostroi.AnnouncementsPNM = { [0003] = { 0.600, "subway_announcer_pnm/00_03.mp3" }, [0005] = { 0.200, "subway_announcer_pnm/00_05.mp3" }, [0006] = { 0.100, "subway_announcer_pnm/00_06.mp3" }, [0201] = { 1.831, "subway_announcer_pnm/02_01.mp3" }, [0202] = { 0.570, "subway_announcer_pnm/02_02.mp3" }, [0203] = { 0.862, "subway_announcer_pnm/02_03.mp3" }, [0204] = { 2.272, "subway_announcer_pnm/02_04.mp3" }, [0205] = { 3.090, "subway_announcer_pnm/02_05.mp3" }, [0206] = { 3.456, "subway_announcer_pnm/02_06.mp3" }, [0207] = { 3.498, "subway_announcer_pnm/02_07.mp3" }, [0208] = { 2.936, "subway_announcer_pnm/02_08.mp3" }, [0209] = { 5.263, "subway_announcer_pnm/02_09.mp3" }, [0210] = { 1.974, "subway_announcer_pnm/02_10.mp3" }, [0211] = { 1.392, "subway_announcer_pnm/02_11.mp3" }, [0212] = { 6.745, "subway_announcer_pnm/02_12.mp3" }, [0213] = { 4.711, "subway_announcer_pnm/02_13.mp3" }, [0214] = { 8.162, "subway_announcer_pnm/02_14.mp3" }, [0215] = { 1.737, "subway_announcer_pnm/02_15.mp3" }, [0216] = { 1.049, "subway_announcer_pnm/02_16.mp3" }, [0217] = { 6.213, "subway_announcer_pnm/02_17.mp3" }, [0218] = { 2.197, "subway_announcer_pnm/02_18.mp3" }, [0219] = { 1.370, "subway_announcer_pnm/02_19.mp3" }, [0220] = { 0.889, "subway_announcer_pnm/02_20.mp3" }, [0221] = { 2.428, "subway_announcer_pnm/02_21.mp3" }, [0222] = { 3.494, "subway_announcer_pnm/02_22.mp3" }, [0223] = { 1.971, "subway_announcer_pnm/02_23.mp3" }, [0224] = { 4.199, "subway_announcer_pnm/02_24.mp3" }, [0225] = { 3.734, "subway_announcer_pnm/02_25.mp3" }, [0226] = { 2.984, "subway_announcer_pnm/02_26.mp3" }, [0227] = { 3.558, "subway_announcer_pnm/02_27.mp3" }, [0228] = { 4.255, "subway_announcer_pnm/02_28.mp3" }, [0229] = { 5.224, "subway_announcer_pnm/02_29.mp3" }, [0230] = { 1.402, "subway_announcer_pnm/02_30.mp3" }, [0231] = { 1.322, "subway_announcer_pnm/02_31.mp3" }, [0232] = { 7.107, "subway_announcer_pnm/02_32.mp3" }, [0233] = { 1.186, "subway_announcer_pnm/02_33.mp3" }, [0234] = { 1.641, "subway_announcer_pnm/02_34.mp3" }, [0235] = { 1.145, "subway_announcer_pnm/02_35.mp3" }, [0236] = { 1.068, "subway_announcer_pnm/02_36.mp3" }, [0237] = { 1.141, "subway_announcer_pnm/02_37.mp3" }, [0238] = { 2.580, "subway_announcer_pnm/02_38.mp3" }, [0308] = { 1.113, "subway_announcer_pnm/03_08.mp3" }, [0309] = { 1.122, "subway_announcer_pnm/03_09.mp3" }, [0310] = { 0.938, "subway_announcer_pnm/03_10.mp3" }, [0311] = { 0.994, "subway_announcer_pnm/03_11.mp3" }, [0312] = { 0.970, "subway_announcer_pnm/03_12.mp3" }, [0313] = { 1.098, "subway_announcer_pnm/03_13.mp3" }, [0314] = { 0.921, "subway_announcer_pnm/03_14.mp3" }, [0315] = { 0.963, "subway_announcer_pnm/03_15.mp3" }, [0316] = { 0.929, "subway_announcer_pnm/03_16.mp3" }, [0317] = { 1.474, "subway_announcer_pnm/03_17.mp3" }, [0318] = { 1.026, "subway_announcer_pnm/03_18.mp3" }, [0319] = { 1.120, "subway_announcer_pnm/03_19.mp3" }, [0320] = { 3.442, "subway_announcer_pnm/03_20.mp3" }, [0321] = { 0.795, "subway_announcer_pnm/03_21.mp3" }, [0322] = { 1.240, "subway_announcer_pnm/03_22.mp3" }, [0323] = { 1.141, "subway_announcer_pnm/03_23.mp3" }, [0415] = { 0.860, "subway_announcer_pnm/04_15.mp3" }, [0521] = { 1.162, "subway_announcer_pnm/05_21.mp3" }, [0522] = { 1.594, "subway_announcer_pnm/05_22.mp3" }, [0601] = { 0.845, "subway_announcer_pnm/06_01.mp3" }, [0602] = { 1.261, "subway_announcer_pnm/06_02.mp3" }, [0603] = { 0.902, "subway_announcer_pnm/06_03.mp3" }, [0604] = { 0.549, "subway_announcer_pnm/06_04.mp3" }, [0605] = { 1.290, "subway_announcer_pnm/06_05.mp3" }, [0606] = { 1.549, "subway_announcer_pnm/06_06.mp3" }, [0607] = { 1.136, "subway_announcer_pnm/06_07.mp3" }, [0608] = { 1.557, "subway_announcer_pnm/06_08.mp3" }, [0699] = { 1.219, "subway_announcer_pnm/06_99.mp3" }, [0701] = { 0.934, "subway_announcer_pnm/06_01.mp3" }, [0702] = { 0.934, "subway_announcer_pnm/07_02.mp3" }, [0703] = { 0.934, "subway_announcer_pnm/06_03.mp3" }, [0704] = { 1.260, "subway_announcer_pnm/07_04.mp3" }, [0799] = { 1.329, "subway_announcer_pnm/07_99.mp3" }, [0801] = { 0.845, "subway_announcer_pnm/08_01.mp3" }, } Metrostroi.AnnouncementSequences = { [1101] = { 0211, 0308, 0321 }, [1102] = { 0211, 0321, 0308 }, [1108] = { 0220, 0308 }, [1109] = { 0220, 0309 }, [1110] = { 0220, 0310, 0231 }, [1111] = { 0220, 0311 }, [1112] = { 0220, 0312 }, [1113] = { 0220, 0313 }, [1114] = { 0220, 0314 }, [1115] = { 0220, 0315, 0231, 0202, 0203, 0415 }, [1116] = { 0220, 0316 }, [1117] = { 0220, 0317 }, [1118] = { 0220, 0318, 0231 }, [1119] = { 0220, 0319 }, [1120] = { }, [1121] = { 0220, 0321 }, [1122] = { 0220, 0322 }, [1123] = { 0220, 0323 }, [1208] = { 0218, 0219, 0308 }, [1209] = { 0218, 0219, 0309 }, [1210] = { 0218, 0219, 0310 }, [1211] = { 0218, 0219, 0311 }, [1212] = { 0218, 0219, 0312 }, [1213] = { 0218, 0219, 0313 }, [1214] = { 0218, 0219, 0314 }, [1215] = { 0218, 0219, 0315 }, [1216] = { 0218, 0219, 0316 }, [1217] = { 0218, 0219, 0317 }, [1218] = { 0218, 0219, 0318 }, [1219] = { 0218, 0219, 0319 }, [1220] = { }, [1221] = { 0218, 0219, 0321 }, [1222] = { 0218, 0219, 0322 }, [1223] = { 0218, 0219, 0323 }, } -- Quick lookup for k,v in pairs(Metrostroi.Announcements) do v[3] = k end for k,v in pairs(Metrostroi.AnnouncementsPNM) do v[3] = k end -------------------------------------------------------------------------------- function TRAIN_SYSTEM:Initialize() for k,v in pairs(Metrostroi.Announcements) do util.PrecacheSound(v[2]) end for k,v in pairs(Metrostroi.AnnouncementsPNM) do util.PrecacheSound(v[2]) end -- Currently playing announcement self.Announcement = 0 -- End time of the announcement self.EndTime = -1e9 -- Announcement schedule self.Schedule = {} -- Fake wire 49 self.Fake48 = 0 end function TRAIN_SYSTEM:Inputs() return { "Queue" } end function TRAIN_SYSTEM:Outputs() return { "AnnMap" } end function TRAIN_SYSTEM:TriggerInput(name,value) if (name == "Queue") and (value > 0.0) then self:Queue(math.floor(value)) end end function TRAIN_SYSTEM:Queue(id) if (not Metrostroi.Announcements[id]) and (not Metrostroi.AnnouncementsPNM[id]) and (not Metrostroi.AnnouncementSequences[id]) then return end if self.Train and self.Train.SubwayTrain and self.Train.SubwayTrain.Type and self.Train.SubwayTrain.Type == "E" and (id == 5 or id == 6) then return end -- Add announcement to queue if #self.Schedule < 16 then if Metrostroi.AnnouncementSequences[id] then for k,i in pairs(Metrostroi.AnnouncementSequences[id]) do self:Queue(i) end else local tbl = Metrostroi["Announcements" .. (self.Train.PNM and "PNM" or "")][id] or Metrostroi.Announcements[id] --print(Metrostroi["Announcements" .. (self.Train.PNM and "PNM" or "")][id]) table.insert(self.Schedule, tbl) end end end function TRAIN_SYSTEM:ClientInitialize() end function TRAIN_SYSTEM:ClientThink() local active = self.Train:GetNW2Bool("BPSNBuzz",false) and self.Train:GetPackedBool(52) local btype = self.Train:GetNW2Bool("BPSNBuzzType",false) self.Train:SetSoundState("bpsn_ann",(active and not btype and (self.Train:GetPackedBool(127) or self.Train:GetPackedBool(132))) and 0.175 or 0,1) self.Train:SetSoundState("bpsn_ann_cab",(active and not btype and self.Train:GetPackedBool(125)) and 0.175 or 0,1) self.Train:SetSoundState("bpsn_ann_pnm",(active and btype and (self.Train:GetPackedBool(127) or self.Train:GetPackedBool(132))) and 0.175 or 0,1) self.Train:SetSoundState("bpsn_ann_pnm_cab",(active and btype and self.Train:GetPackedBool(125)) and 0.175 or 0,1) end function TRAIN_SYSTEM:MultiQuele(...) for _,v in pairs({...}) do local v = tonumber(v) if v ~= nil then if Metrostroi.AnnouncerData[v] then self:Queue(tonumber(tostring(v):sub(-3,-1)) + 200) else self:Queue(v) end end end end function TRAIN_SYSTEM:Think() -- Check if new announcement must be started from train wire local targetAnnouncement = self.Train:ReadTrainWire(48) if targetAnnouncement < 0 then targetAnnouncement = 0 end local onlyCabin = false if (targetAnnouncement == 0) then targetAnnouncement = self.Fake48 or 0 onlyCabin = true end if (targetAnnouncement > 0) and (targetAnnouncement ~= self.Announcement) and (CurTime() > self.EndTime) then self.Announcement = targetAnnouncement local tbl = Metrostroi["Announcements" .. (self.Train.PNM and "PNM" or "")][targetAnnouncement] or Metrostroi.Announcements[targetAnnouncement] if tbl then --if not Metrostroi["Announcements" .. (self.Train.PNM and "PNM" or "")][targetAnnouncement] then print(targetAnnouncement) end self.Sound = tbl[2] self.EndTime = CurTime() + tbl[1] -- Emit the sound if self.Sound ~= "" then if self.Train.DriverSeat and (not self.Train.R_G or self.Train.R_G.Value > 0.5) then self.Train.DriverSeat:EmitSound(self.Sound, 73, 100) end if onlyCabin == false then self.Train:EmitSound(self.Sound, 85, 100) end if (self.Announcement == 0206) or (self.Announcement == 0207) or (self.Announcement == 0212) or (self.Announcement == 0221) or (self.Announcement == 0224) then self.Train.AnnouncementToLeaveWagon = true self.Train.AnnouncementToLeaveWagonAcknowledged = false --else --self.Train.AnnouncementToLeaveWagon = false end if self.Train:GetNW2Float("PassengerCount") == 0 then self.Train.AnnouncementToLeaveWagon = false end end -- BPSN buzz if targetAnnouncement == 5 and self.Train.PNM then timer.Simple(0.1,function() self.Train:SetNW2Bool("BPSNBuzz",true) end) end if targetAnnouncement == 5 and not self.Train.PNM then timer.Simple(0.2,function() self.Train:SetNW2Bool("BPSNBuzz",true) end) end if targetAnnouncement == 6 then self.Train:SetNW2Bool("BPSNBuzz",false) --[[ if self.Train.PNM then self.Train:SetNW2Bool("BPSNBuzz",false) self.BPSNBuzzTimeout1 = CurTime() + 0 else self.BPSNBuzzTimeout1 = CurTime() + 0.4 --timer.Simple(0.4,function() if not IsValid(self.Train) then return end self.Train:SetNW2Bool("BPSNBuzz",false) end) end ]] end self.BPSNBuzzTimeout = CurTime() + 10.0 end elseif (targetAnnouncement == 0) then self.Announcement = 0 end -- Buzz timeout if self.BPSNBuzzTimeout and (CurTime() > self.BPSNBuzzTimeout) then self.BPSNBuzzTimeout = nil self.Train:SetNW2Bool("BPSNBuzz",false) end if self.BPSNBuzzTimeout1 and (CurTime() > self.BPSNBuzzTimeout1) then self.BPSNBuzzTimeout1 = nil self.Train:SetNW2Bool("BPSNBuzz",false) end -- Check if new announcement must be started from schedule if (self.ScheduleAnnouncement == 0) and (self.Schedule[1]) then self.ScheduleAnnouncement = self.Schedule[1][3] self.ScheduleEndTime = CurTime() + self.Schedule[1][1] table.remove(self.Schedule,1) end -- Check if schedule announcement is playing if self.ScheduleAnnouncement ~= 0 then if self.Train.DriverSeat and ((self.Train.R_ZS and self.Train.R_ZS.Value < 0.5) or (self.Train.R_UPO and self.Train.R_UPO.Value < 0.5)) then self.Fake48 = self.ScheduleAnnouncement else self.Train:WriteTrainWire(48,self.ScheduleAnnouncement) self.Fake48 = 0 end if CurTime() > (self.ScheduleEndTime or -1e9) then self.ScheduleAnnouncement = 0 self.Fake48 = 0 self.Train:WriteTrainWire(48,0) end end if self.Train.R_ZS and self.Train.KV then if self.Train.R_ZS.Value < 0.5 and self.Train.KV.ReverserPosition == 1.0 then self.Train:WriteTrainWire(48,-1) elseif self.Train:ReadTrainWire(48) == -1 then self.Train:WriteTrainWire(48,0) end end if self.Train.R_UPO and self.Train.KV then if self.Train.R_UPO.Value < 0.5 and self.Train.KV.ReverserPosition == 1.0 then self.Train:WriteTrainWire(48,-1) elseif self.Train:ReadTrainWire(48) == -1 then self.Train:WriteTrainWire(48,0) end end end
redis.call('INCRBY', KEYS[1], ARGV[1]) return redis.call('GET', KEYS[1])
--This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. -- --Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: -- --1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. -- --2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. -- --3. This notice may not be removed or altered from any source distribution. -- --https://github.com/LiquidHelium/LoveAchievements require("achievements/config") AchievementSystem = {} AchievementSystem.__index = AchievementSystem function AchievementSystem.New() local achsys = {} setmetatable(achsys, AchievementSystem) achsys.achievementData = {} achsys.fileLocation = "achievements.txt" achsys.topUnlockedColor = {r=0, g=100, b=200} achsys.topLockedColor = {r=255, g=0, b=0} achsys.backgroundColor = {r=22, g=22, b=22} achsys.textColor = {r=255, g=255, b=255} achsys.GUIbutton = "=" achsys.speed = 5 achsys.waitTime = 200 achsys.imageSize = 60 achsys.descriptionWidth = 150 achsys.paddingSize = 5 achsys.topSize = 2 achsys.popupWidth = (achsys.paddingSize * 3) + achsys.descriptionWidth + achsys.imageSize achsys.popupHeight = (achsys.paddingSize * 2) + achsys.topSize + achsys.imageSize achsys.startXPos = love.graphics.getWidth() achsys.waitXPos = love.graphics.getWidth() - achsys.popupWidth - 5 achsys.titleFont = love.graphics.newFont("achievements/res/Ubuntu-B.ttf", 15) achsys.descriptionFont = love.graphics.newFont("achievements/res/Ubuntu-B.ttf", 12) achsys.soundEffect = love.audio.newSource("achievements/res/SoundEffect.wav", "static") achsys.lockImage = love.graphics.newImage("achievements/res/lock.png") AchievementSystemConfig(achsys) achsys:LoadFromFile() achsys.displayIntro = true achsys.introDelayTime = 50 achsys.introLogo = love.graphics.newImage("achievements/res/logo.png") achsys.introTitle = "Love Achievements" achsys.introDesc = "This Game Has Achievements. Press And Hold " .. achsys.GUIbutton .." To View" achsys.maxPopupsHorizontal = math.floor(love.graphics.getWidth() / (achsys.popupWidth + 2)) achsys.totalPopupsVerticalSpace = math.floor((#achsys.achievementData)/achsys.maxPopupsHorizontal) * (achsys.popupHeight + 2) + 2 if achsys.totalPopupsVerticalSpace > love.graphics.getHeight() then achsys.scrollUI = true achsys.maxScrollOffset = achsys.totalPopupsVerticalSpace - love.graphics.getHeight() achsys.scrollDirection = 1 achsys.maxScrollWaitTime = 150 achsys.scrollWaitTime = 0 else achsys.scrollUI = false end achsys.scrollOffset = 0 achsys.UIOffset = (love.graphics.getWidth() - ((achsys.maxPopupsHorizontal * (achsys.popupWidth + 2))+2))/2 return achsys end function AchievementSystem:CreateAchievement(uniqueID_i, name_i, description_i, imageName_i) table.insert(self.achievementData, {uniqueID=uniqueID_i, name=name_i, description=description_i, image=love.graphics.newImage("achievements/img/"..imageName_i), unlocked=false}) end function AchievementSystem:UnlockAchievement(uniqueIDi) for k, v in pairs(self.achievementData) do if v.uniqueID == uniqueIDi then if v.unlocked == true then return else v.unlocked = true self:SaveToFile() self.displayedName = v.name self.displayedDescription = v.description self.displayedImage = v.image love.audio.play(self.soundEffect) self.isDrawing = true self.xPos = self.startXPos self.timeWaited = self.waitTime end end end end function AchievementSystem:Update() if self.isDrawing then if self.timeWaited <= 0 then if self.xPos < self.startXPos then self.xPos = self.xPos + self.speed elseif self.xPos > self.startXPos then self.xPos = self.xPos - self.speed else self.isDrawing = false end else if self.xPos < self.waitXPos then self.xPos = self.xPos + self.speed elseif self.xPos > self.waitXPos then self.xPos = self.xPos - self.speed else self.timeWaited = self.timeWaited - 1 end end end if love.keyboard.isDown(self.GUIbutton) then if self.scrollUI then self.scrollOffset = self.scrollOffset + self.scrollDirection if self.scrollOffset == 0 then if self.scrollWaitTime == self.maxScrollWaitTime then self.scrollDirection = 1 self.scrollWaitTime = 0 else self.scrollDirection = 0 self.scrollWaitTime = self.scrollWaitTime + 1 end elseif self.scrollOffset == self.maxScrollOffset then if self.scrollWaitTime == self.maxScrollWaitTime then self.scrollDirection = -1 self.scrollWaitTime = 0 else self.scrollDirection = 0 self.scrollWaitTime = self.scrollWaitTime + 1 end end end end if self.displayIntro then self.introDelayTime = self.introDelayTime - 1 if self.introDelayTime == 0 then self.displayedName = self.introTitle self.displayedDescription = self.introDesc self.displayedImage = self.introLogo self.isDrawing = true self.xPos = self.startXPos self.timeWaited = self.waitTime self.displayIntro = false end end end function AchievementSystem:DrawPopup(x, y, name, description, image, topColor, drawLocks) drawLocks = drawLocks or false love.graphics.setColor(topColor.r, topColor.g, topColor.b, 255) love.graphics.rectangle("fill", x, y, self.popupWidth, self.topSize) love.graphics.setColor(self.backgroundColor.r, self.backgroundColor.g, self.backgroundColor.b, 255) love.graphics.rectangle("fill", x, y + self.topSize, self.popupWidth, self.imageSize + (self.paddingSize * 2)) love.graphics.setColor(self.textColor.r, self.textColor.g, self.textColor.b, 255) love.graphics.setFont(self.titleFont) love.graphics.print(name, x + self.imageSize + (self.paddingSize*2), self.paddingSize + y) love.graphics.setFont(self.descriptionFont) love.graphics.printf(description, x + self.imageSize + (self.paddingSize*2), y + (self.paddingSize*2) + 15, self.descriptionWidth) love.graphics.setColor(255, 255, 255, 255) love.graphics.draw(image, x + self.paddingSize, y + self.topSize + self.paddingSize, 0, self.imageSize / image:getWidth(), self.imageSize / image:getHeight()) if drawLocks then love.graphics.draw(self.lockImage, x + self.paddingSize, y + self.topSize + self.paddingSize, 0, self.imageSize / self.lockImage:getWidth(), self.imageSize / self.lockImage:getHeight()) end end function AchievementSystem:Draw() if self.isDrawing then r, g, b, a = love.graphics.getColor() font = love.graphics.getFont() self:DrawPopup(self.xPos, 5, self.displayedName, self.displayedDescription, self.displayedImage, self.topUnlockedColor) if font then love.graphics.setFont(font) end love.graphics.setColor(r, g, b, a) end if love.keyboard.isDown(self.GUIbutton) then i = 0 for k, v in ipairs(self.achievementData) do x = ((i) % self.maxPopupsHorizontal) * (self.popupWidth + 2) + 2 y = math.floor(i/self.maxPopupsHorizontal) * (self.popupHeight + 2) + 2 if v.unlocked then color = self.topUnlockedColor else color = self.topLockedColor end self:DrawPopup(x + self.UIOffset, y - self.scrollOffset, v.name, v.description, v.image, color, not v.unlocked) i = i + 1 end end end function AchievementSystem:GetData() return self.achievementData end function AchievementSystem:LoadFromFile() if love.filesystem.exists(self.fileLocation) then for line in love.filesystem.lines(self.fileLocation) do for k, v in ipairs(self.achievementData) do if v.uniqueID == line then v.unlocked = true end end end end end function AchievementSystem:SaveToFile() s = "" for k, v in ipairs(self.achievementData) do if v.unlocked == true then s = s .. v.uniqueID .. "\n" end end file = love.filesystem.newFile(self.fileLocation) file:open('w') file:write(s) file:close() end function AchievementSystem:DisableIntro() self.displayIntro = false end function AchievementSystem:SetBackgroundColor(red, green, blue) self.backgroundColor = {r=red, g=green, b=blue} end function AchievementSystem:SetUnlockedColor(red, green, blue) self.topUnlockedColor = {r=red, g=green, b=blue} end function AchievementSystem:SetLockedColor(red, green, blue) self.topLockedColor = {r=red, g=green, b=blue} end function AchievementSystem:SetTextColor(red, green, blue) self.textColor = {r=red, g=green, b=blue} end function AchievementSystem:SetButton(button) self.GUIbutton = button end
local mp = require 'mp' local scroll_list = { global_style = [[]], header_style = [[{\q2\fs35\c&00ccff&}]], list_style = [[{\q2\fs25\c&Hffffff&}]], wrapper_style = [[{\c&00ccff&\fs16}]], cursor_style = [[{\c&00ccff&}]], selected_style = [[{\c&Hfce788&}]], cursor = [[โžค\h\h\h]], indent = [[\h\h\h\h]], num_entries = 16, wrap = false, empty_text = "no entries" } --formats strings for ass handling --this function is taken from https://github.com/mpv-player/mpv/blob/master/player/lua/console.lua#L110 function scroll_list.ass_escape(str) str = str:gsub('\\', '\\\239\187\191') str = str:gsub('{', '\\{') str = str:gsub('}', '\\}') -- Precede newlines with a ZWNBSP to prevent ASS's weird collapsing of -- consecutive newlines str = str:gsub('\n', '\239\187\191\\N') -- Turn leading spaces into hard spaces to prevent ASS from stripping them str = str:gsub('\\N ', '\\N\\h') str = str:gsub('^ ', '\\h') return str end --appends the entered text to the overlay function scroll_list:append(text) if text == nil then return end self.ass.data = self.ass.data .. text end --appends a newline character to the osd function scroll_list:newline() self.ass.data = self.ass.data .. '\\N' end --re-parses the list into an ass string --if the list is closed then it flags an update on the next open function scroll_list:update() if self.hidden then self.flag_update = true else self:update_ass() end end --prints the header to the overlay function scroll_list:format_header() self:append(self.header_style) self:append(self.header) self:newline() end --formats each line of the list and prints it to the overlay function scroll_list:format_line(index, item) self:append(self.list_style) if index == self.selected then self:append(self.cursor_style..self.cursor..self.selected_style) else self:append(self.indent) end self:append(item.style) self:append(item.ass) self:newline() end --refreshes the ass text using the contents of the list function scroll_list:update_ass() self.ass.data = self.global_style self:format_header() if #self.list < 1 then self:append(self.empty_text) self.ass:update() return end local start = 1 local finish = start+self.num_entries-1 --handling cursor positioning local mid = math.ceil(self.num_entries/2)+1 if self.selected+mid > finish then local offset = self.selected - finish + mid --if we've overshot the end of the list then undo some of the offset if finish + offset > #self.list then offset = offset - ((finish+offset) - #self.list) end start = start + offset finish = finish + offset end --making sure that we don't overstep the boundaries if start < 1 then start = 1 end local overflow = finish < #self.list --this is necessary when the number of items in the dir is less than the max if not overflow then finish = #self.list end --adding a header to show there are items above in the list if start > 1 then self:append(self.wrapper_style..(start-1)..' item(s) above\\N\\N') end for i=start, finish do self:format_line(i, self.list[i]) end if overflow then self:append('\\N'..self.wrapper_style..#self.list-finish..' item(s) remaining') end self.ass:update() end --moves the selector down the list function scroll_list:scroll_down() if self.selected < #self.list then self.selected = self.selected + 1 self:update_ass() elseif self.wrap then self.selected = 1 self:update_ass() end end --moves the selector up the list function scroll_list:scroll_up() if self.selected > 1 then self.selected = self.selected - 1 self:update_ass() elseif self.wrap then self.selected = #self.list self:update_ass() end end --adds the forced keybinds function scroll_list:add_keybinds() for _,v in ipairs(self.keybinds) do mp.add_forced_key_binding(v[1], 'dynamic/'..self.ass.id..'/'..v[2], v[3], v[4]) end end --removes the forced keybinds function scroll_list:remove_keybinds() for _,v in ipairs(self.keybinds) do mp.remove_key_binding('dynamic/'..self.ass.id..'/'..v[2]) end end --opens the list and sets the hidden flag function scroll_list:open_list() self.hidden = false if not self.flag_update then self.ass:update() else self.flag_update = false ; self:update_ass() end end --closes the list and sets the hidden flag function scroll_list:close_list() self.hidden = true self.ass:remove() end --modifiable function that opens the list function scroll_list:open() self:open_list() self:add_keybinds() end --modifiable function that closes the list function scroll_list:close () self:remove_keybinds() self:close_list() end --toggles the list function scroll_list:toggle() if self.hidden then self:open() else self:close() end end --clears the list in-place function scroll_list:clear() local i = 1 while self.list[i] do self.list[i] = nil i = i + 1 end end --added alias for ipairs(list.list) for lua 5.1 function scroll_list:ipairs() return ipairs(self.list) end --append item to the end of the list function scroll_list:insert(item) self.list[#self.list + 1] = item end local metatable = { __index = function(t, key) if scroll_list[key] ~= nil then return scroll_list[key] elseif key == "__current" then return t.list[t.selected] elseif type(key) == "number" then return t.list[key] end end, __newindex = function(t, key, value) if type(key) == "number" then rawset(t.list, key, value) else rawset(t, key, value) end end, __scroll_list = scroll_list, __len = function(t) return #t.list end, __ipairs = function(t) return ipairs(t.list) end } --creates a new list object function scroll_list:new() local vars vars = { ass = mp.create_osd_overlay('ass-events'), hidden = true, flag_update = true, header = "header \\N ----------------------------------------------", list = {}, selected = 1, keybinds = { {'DOWN', 'scroll_down', function() vars:scroll_down() end, {repeatable = true}}, {'UP', 'scroll_up', function() vars:scroll_up() end, {repeatable = true}}, {'ESC', 'close_browser', function() vars:close() end, {}} } } return setmetatable(vars, metatable) end return scroll_list:new()
local _M = {} local ffi = require 'ffi' if ffi.os == "Windows" then _M.PATH_SEPS = "ยฅ" else _M.PATH_SEPS = "/" end function _M.file_exists(file) if ffi.os ~= 'Windows' then return io.popen(([[if [ -e '%s' ]; then echo '1'; else echo '0'; fi]]):format(file)):read(1) == '1' else error('unsupported OS') end end function _M.current_path() local data = debug.getinfo(1) return data.source:match('@(.+)'.._M.PATH_SEPS..'.+$') end local cache_dir = _M.current_path().._M.PATH_SEPS..'cache' local version_file = cache_dir.._M.PATH_SEPS..'version' local builtin_paths = cache_dir.._M.PATH_SEPS..'builtin_paths' local builtin_defs = cache_dir.._M.PATH_SEPS..'builtin_defs' _M.path = { version_file = version_file, builtin_paths = builtin_paths, builtin_defs = builtin_defs, } -- gcc version cache function _M.gcc_version() local r = io.popen('which gcc'):read('*a') return #r > 0 and io.popen('gcc -v 2>&1'):read('*a') or nil end local function create_version_file_cache(v) v = v or _M.gcc_version() assert(v, "gcc need to be installed to create cache") local f = io.open(version_file, 'w') f:write(v) f:close() end -- add compiler predefinition local builtin_defs_cmd = 'echo | gcc -E -dM -' local function create_builtin_defs_cache() assert(_M.gcc_version(), "gcc need to be installed to create cache") os.execute(builtin_defs_cmd..'>'..builtin_defs) end function _M.builtin_defs() if _M.file_exists(version_file) then local v = _M.gcc_version() if v and (v ~= io.popen(('cat %s'):format(version_file)):read('*a')) then create_builtin_defs_cache() create_version_file_cache(v) end return io.popen(([[cat %s]]):format(builtin_defs)) end return io.popen(builtin_defs_cmd) end function _M.add_builtin_defs(state) local p = _M.builtin_defs() local predefs = p:read('*a') state:cdef(predefs) p:close() -- os dependent tweak. if ffi.os == 'OSX' then -- luajit cannot parse objective-C code correctly -- e.g. int atexit_b(void (^)(void)) ; state:undef({"__BLOCKS__"}) end end function _M.clear_builtin_defs(state) local p = io.popen(builtin_defs_cmd) local undefs = {} while true do local line = p:read('*l') if line then local tmp,cnt = line:gsub('^#define%s+([_%w]+)%s+.*', '%1') if cnt > 0 then table.insert(undefs, tmp) end else break end end state:undef(undefs) p:close() end -- add compiler built in header search path local builtin_paths_cmd = 'echo | gcc -xc -v - 2>&1 | cat 2>/dev/null' function create_builtin_paths_cache() assert(_M.gcc_version(), "gcc need to be installed to create cache") os.execute(builtin_paths_cmd..'>'..builtin_paths) end function _M.builtin_paths() if _M.file_exists(version_file) then local v = _M.gcc_version() if v and (v ~= io.popen(('cat %s'):format(version_file)):read('*a')) then create_builtin_paths_cache() create_version_file_cache(v) end return io.popen(([[cat %s]]):format(builtin_paths)) end return io.popen(builtin_paths_cmd) end function _M.add_builtin_paths(state) local p = _M.builtin_paths() local search_path_start while true do -- TODO : parsing unstructured compiler output. -- that is not stable way to get search paths. -- but I cannot find better way than this. local line = p:read('*l') if not line then break end -- print('line = ', line) if search_path_start then local tmp,cnt = line:gsub('^%s+(.*)', '%1') if cnt > 0 then -- remove unnecessary output of osx clang. tmp = tmp:gsub(' %(framework directory%)', '') -- print('builtin_paths:'..tmp) state:path(tmp, true) else break end elseif line:find('#include <...>') then search_path_start = true end end end function _M.create_builtin_config_cache() create_version_file_cache() create_builtin_paths_cache() create_builtin_defs_cache() os.execute('chmod -R 766 '..cache_dir) end function _M.clear_builtin_config_cache() os.execute('rm '..cache_dir.._M.PATH_SEPS.."*") end return _M
--[[ Copyright (c) 2016-present, Facebook, Inc. All rights reserved. This source code is licensed under the BSD-style license found in the LICENSE file in the root directory of this source tree. An additional grant of patent rights can be found in the PATENTS file in the same directory. ]]-- local tnt = require 'torchnet.env' local argcheck = require 'argcheck' local utils = require 'torchnet.utils' local TransformDataset = torch.class('tnt.TransformDataset', 'tnt.Dataset', tnt) TransformDataset.__init = argcheck{ doc = [[ <a name="TransformDataset"> #### tnt.TransformDataset(@ARGP) @ARGT Given a closure `transform()`, and a `dataset`, `tnt.TransformDataset` applies the closure in an on-the-fly manner when querying a sample with `tnt.Dataset:get()`. If key is provided, the closure is applied to the sample field specified by `key` (only). The closure must return the new corresponding field value. If key is not provided, the closure is applied on the full sample. The closure must return the new sample table. The size of the new dataset is equal to the size of the underlying `dataset`. Purpose: when performing pre-processing operations, it is convenient to be able to perform on-the-fly transformations to a dataset. ]], {name='self', type='tnt.TransformDataset'}, {name='dataset', type='tnt.Dataset'}, {name='transform', type='function'}, {name='key', type='string', opt=true}, call = function(self, dataset, transform, key) self.dataset = dataset if key then function self.__transform(z, idx) assert(z[key], 'missing key in sample') z[key] = transform(z[key], idx) return z end else function self.__transform(z, idx) return transform(z, idx) end end end } TransformDataset.__init = argcheck{ doc = [[ <a name="TransformDataset"> #### tnt.TransformDataset(@ARGP) @ARGT Given a set of closures and a `dataset`, `tnt.TransformDataset` applies these closures in an on-the-fly manner when querying a sample with `tnt.Dataset:get()`. Closures are provided in `transforms`, a Lua table, where a (key,value) pair represents a (sample field name, corresponding closure to be applied to the field name). Each closure must return the new value of the corresponding field. ]], {name='self', type='tnt.TransformDataset'}, {name='dataset', type='tnt.Dataset'}, {name='transforms', type='table'}, overload = TransformDataset.__init, call = function(self, dataset, transforms) for k,v in pairs(transforms) do assert(type(v) == 'function', 'key/function table expected for transforms') end self.dataset = dataset transforms = utils.table.copy(transforms) function self.__transform(z) for key,transform in pairs(transforms) do assert(z[key], 'missing key in sample') z[key] = transform(z[key]) end return z end end } TransformDataset.size = argcheck{ {name='self', type='tnt.TransformDataset'}, call = function(self) return self.dataset:size() end } TransformDataset.get = argcheck{ {name='self', type='tnt.TransformDataset'}, {name='idx', type='number'}, call = function(self, idx) return self.__transform( self.dataset:get(idx), idx ) end }
require("http_common") require("granting_ticket_view") require("granting_ticket_model") local http_server = require("http.server") local http_headers = require("http.headers") local http_util = require("http.util") local function getKeyFromUri(uri) local pattern = "/TicketService/GrantingTickets/(%x+)" return string.match(uri, pattern) end local function postTicket(stream, headers) --Read body. local seconds = 2 --timeout of 2 seconds local body = stream:get_body_as_string(seconds) if not body then setHeaders(stream, BAD_REQUEST) end --Get arguments from body. local grantingTicketUri = nil local serviceName = nil for key, value in http_util.query_args(body) do if key == "grantingTicket" then grantingTicketUri = value end if key == "serviceName" then serviceName = value end end if not grantingTicketUri or not serviceName then setHeaders(stream, BAD_REQUEST) end --Get service key. local serviceKey = searchServiceKey( "service_name", serviceName) if not serviceKey then setHeaders(stream, BAD_REQUEST) end --Get granting ticket. local gt = searchGrantingTicket( getKeyFromUri(grantingTicketUri)) if not gt then setHeaders(stream, BAD_REQUEST) end --Get user and pass form authorization header. local user, pass = getCredentialsFromHeaders(headers) if user == nil or pass == nil then setHeaders(stream, NOT_AUTHORIZED) end --Check if user exists in database. local validUser = checkUser(user, pass) if not validUser then setHeaders(stream, NOT_AUTHORIZED) end --Check if user is the owner --of the granting ticket. if gt.user ~= user then setHeaders(stream, NOT_AUTHORIZED) end --Make ticket. local ticket = makeTicket(gt, serviceKey) if not ticket then setHeaders(stream, SERVER_ERROR) end --Set location header to the URI --of the new resource. local newUri = string.format( "/TicketService/Tickets/%d", ticket.id) --Return status code. setHeaders(stream, CREATED, newUri) end local function getTicket(stream, headers) --Extract ticket id from URI. local pattern = "/TicketService/Tickets/(%d+)" local ticketId = getKeyFromHeaders(headers, pattern) ticketId = tonumber(ticketId) if not ticketId then setHeaders(stream, BAD_REQUEST) end --Get the ticket from the in memory list. local ticket = searchTicket(ticketId) if not ticket then setHeaders(stream, NOT_FOUND) end --Prepare the html to be sent to the client. local html = renderTicket(ticket) if not html then setHeaders(stream, SERVER_ERROR) end --Send the representation to the client. setHeaders(stream, SUCCESS) stream:write_chunk(html, true) end local function deleteTicket(stream, headers) --Extract ticket id from URI. local pattern = "/TicketService/Tickets/(%d+)" local ticketId = getKeyFromHeaders(headers, pattern) ticketId = tonumber(ticketId) if not ticketId then setHeaders(stream, BAD_REQUEST) end --Get the ticket from the in memory list. local ticket = searchTicket(ticketId) if not ticket then setHeaders(stream, NOT_FOUND) end --Get the user from the authorization header. local user, pass = getCredentialsFromHeaders(headers) if user == nil or pass == nil then setHeaders(stream, NOT_AUTHORIZED) end --Check if user exists in database. local validUser = checkUser(user, pass) if not validUser then setHeaders(stream, NOT_AUTHORIZED) end --Check if the user is the owner of the ticket. if ticket.owner ~= user then setHeaders(stream, NOT_AUTHORIZED) end --Remove the ticket from the in memory list. removeTicket(ticket) --Set status to success. setHeaders(stream, SUCCESS) stream:write_chunk("", true) end local ticketController = { pattern = string.lower("/TicketService/Tickets"), ["post"] = postTicket, ["get"] = getTicket, ["delete"] = deleteTicket } return ticketController
require "PlaceTool" function love.load() love.graphics.setDefaultFilter("nearest", "nearest") world = love.physics.newWorld(0, 0) tool = PlaceTool:new(world) end function love.update(dt) tool:update(dt) end function love.draw() tool:draw() end function love.keypressed(key) tool:keypressed(key) end function love.quit() tool:quit() end function love.wheelmoved(x, y) tool:wheelmoved(x, y) end function love.mousepressed(x, y, button, istouch) tool:mousepressed(x,y,button) end
dofile("bibl-bib.lua") local session = bibtex.new() bibtex.load(session,"gut.bib") bibtex.load(session,"komoedie.bib") bibtex.load(session,"texbook1.bib") bibtex.load(session,"texbook2.bib") bibtex.load(session,"texbook3.bib") bibtex.load(session,"texgraph.bib") bibtex.load(session,"texjourn.bib") bibtex.load(session,"texnique.bib") bibtex.load(session,"tugboat.bib") print(bibtex.size,statistics.elapsedtime(bibtex)) bibtex.toxml(session) print(bibtex.size,statistics.elapsedtime(bibtex)) --~ print(table.serialize(session.data)) --~ print(table.serialize(session.shortcuts)) --~ print(xml.serialize(session.xml))
object_tangible_quest_menagerie_terminal_53 = object_tangible_quest_shared_menagerie_terminal_53:new { } ObjectTemplates:addTemplate(object_tangible_quest_menagerie_terminal_53, "object/tangible/quest/menagerie_terminal_53.iff")
-- GLOBALS -> LOCAL local _G = getfenv(0) local InFlight, self = InFlight, InFlight local GetNumRoutes, GetTaxiMapID, GetTime, NumTaxiNodes, TaxiGetNodeSlot, TaxiNodeGetType, TaxiNodeName, UnitOnTaxi = GetNumRoutes, GetTaxiMapID, GetTime, NumTaxiNodes, TaxiGetNodeSlot, TaxiNodeGetType, TaxiNodeName, UnitOnTaxi local abs, floor, format, gsub, ipairs, pairs, print, strjoin = abs, floor, format, gsub, ipairs, pairs, print, strjoin local gtt = GameTooltip local oldTakeTaxiNode InFlight.debug = false -- LIBRARIES local smed = LibStub("LibSharedMedia") -- LOCAL VARIABLES local debug = InFlight.debug local Print, PrintD = InFlight.Print, InFlight.PrintD local vars, db -- addon databases local taxiSrc, taxiSrcName, taxiDst, taxiDstName, endTime -- location data local porttaken, takeoff, inworld, outworld, ontaxi -- flags local ratio, endText = 0, "??" -- cache variables local sb, spark, timeText, locText, bord -- frame elements local totalTime, startTime, elapsed, throt = 0, 0, 0, 0 -- throttle vars -- LOCALIZATION local L = LibStub("AceLocale"):GetLocale("InFlight", not debug) local FL = LibStub("AceLocale"):GetLocale("InFlightLoc", not debug) InFlight.L = L -- LOCAL FUNCTIONS local function FormatTime(secs) -- simple time format if not secs then return "??" end return format(TIMER_MINUTES_DISPLAY, secs / 60, secs % 60) end local function ShortenName(name) -- shorten name to lighten saved vars and display return gsub(name, L["DestParse"], "") end local function SetPoints(f, lp, lrt, lrp, lx, ly, rp, rrt, rrp, rx, ry) f:ClearAllPoints() f:SetPoint(lp, lrt, lrp, lx, ly) if rp then f:SetPoint(rp, rrt, rrp, rx, ry) end end local function SetToUnknown() -- setup bar for flights with unknown time sb:SetMinMaxValues(0, 1) sb:SetValue(1) sb:SetStatusBarColor(db.unknowncolor.r, db.unknowncolor.g, db.unknowncolor.b, db.unknowncolor.a) spark:Hide() end local function GetEstimatedTime(slot) -- estimates flight times based on hops local numRoutes = GetNumRoutes(slot) if numRoutes < 2 then return end local taxiNodes = {[1] = taxiSrc, [numRoutes + 1] = L[ShortenName(TaxiNodeName(slot))]} for hop = 2, numRoutes, 1 do taxiNodes[hop] = L[ShortenName(TaxiNodeName(TaxiGetNodeSlot(slot, hop, true)))] end local etimes = { 0 } local prevNode = {} local nextNode = {} local srcNode = 1 local dstNode = #taxiNodes - 1 PrintD("|cff208080New Route:|r", taxiSrc, "-->", taxiNodes[#taxiNodes], "-", #taxiNodes, "hops") while srcNode and srcNode < #taxiNodes do while dstNode and dstNode > srcNode do PrintD("|cff208080Node:|r", taxiNodes[srcNode], "-->", taxiNodes[dstNode]) if vars[taxiNodes[srcNode]] then if not etimes[dstNode] and vars[taxiNodes[srcNode]][taxiNodes[dstNode]] then etimes[dstNode] = etimes[srcNode] + vars[taxiNodes[srcNode]][taxiNodes[dstNode]] PrintD(taxiNodes[dstNode], "time:", FormatTime(etimes[srcNode]), "+", FormatTime(vars[taxiNodes[srcNode]][taxiNodes[dstNode]]), "=", FormatTime(etimes[dstNode])) nextNode[srcNode] = dstNode - 1 prevNode[dstNode] = srcNode srcNode = dstNode dstNode = #taxiNodes else dstNode = dstNode - 1 end else srcNode = prevNode[srcNode] dstNode = nextNode[srcNode] end end if not etimes[#taxiNodes] then PrintD("<<") srcNode = prevNode[srcNode] dstNode = nextNode[srcNode] end end PrintD(".") return etimes[#taxiNodes] end local function addDuration(flightTime, estimated) if flightTime > 0 then gtt:AddLine(L["Duration"]..(estimated and "~" or "")..FormatTime(flightTime), 1, 1, 1) else gtt:AddLine(L["Duration"].."-:--", 0.8, 0.8, 0.8) end gtt:Show() end local function postTaxiNodeOnButtonEnter(button) -- adds duration info to taxi node tooltips local id = button:GetID() if TaxiNodeGetType(id) ~= "REACHABLE" then return end local duration = vars[taxiSrc] and vars[taxiSrc][L[ShortenName(TaxiNodeName(id))]] if duration then addDuration(duration) else addDuration(GetEstimatedTime(id) or 0, true) end end ---------------------------- function InFlight.Print(...) -- prefix chat messages ---------------------------- print("|cff0040ffIn|cff00aaffFlight|r:", ...) end Print = InFlight.Print ----------------------------- function InFlight.PrintD(...) -- debug print ----------------------------- if debug then print("|cff00ff40In|cff00aaffFlight|r:", ...) end end PrintD = InFlight.PrintD ---------------------------------- function InFlight:GetDestination() ---------------------------------- return taxiDstName end --------------------------------- function InFlight:GetFlightTime() --------------------------------- return endTime end ---------------------------- function InFlight:LoadBulk() -- called from InFlight_Load ---------------------------- InFlightDB = InFlightDB or {} -- Convert old saved variables if not InFlightDB.version then InFlightDB.perchar = nil InFlightDB.dbinit = nil InFlightDB.upload = nil local tempDB = InFlightDB InFlightDB = { profiles = { Default = tempDB }} end -- Check that this is the right version of the client if select(4, GetBuildInfo()) > 20503 then Print(L["AddonDisabled"]) DisableAddOn("InFlight") return end -- Check that this is the right version of the database to avoid corruption if InFlightDB.version ~= "classic" then InFlightDB.global = nil InFlightDB.version = "classic" end -- Update default data if InFlightDB.dbinit ~= 1134 or debug then InFlightDB.dbinit = 1134 InFlightDB.upload = nil Print(L["DefaultsUpdated"]) if debug then for faction, t in pairs(self.defaults.global) do local count = 0 for src, dt in pairs(t) do for dst, dtime in pairs(dt) do count = count + 1 end end PrintD(faction, "|cff208020-|r", count, "|cff208020flights|r") end else InFlightDB.global = nil end end -- Set up flight point translations for key, value in pairs(FL) do L[value] = key end -- Sanitise data if InFlightDB.global then local defaults = self.defaults.global for faction, t in pairs(InFlightDB.global) do for src, dt in pairs(t) do local lsrc = L[ShortenName(src)] if lsrc ~= src and FL[lsrc] ~= L[src] then InFlightDB.global[faction][lsrc] = dt InFlightDB.global[faction][src] = nil src = lsrc end for dst, dtime in pairs(dt) do local ldst = L[ShortenName(dst)] if ldst ~= dst and FL[ldst] ~= L[dst] then InFlightDB.global[faction][src][ldst] = dtime InFlightDB.global[faction][src][dst] = nil dst = ldst end if defaults[faction][src] and defaults[faction][src][dst] and abs(dtime - defaults[faction][src][dst]) < (debug and 2 or 5) then InFlightDB.global[faction][src][dst] = defaults[faction][src][dst] end end end end end FL = nil -- Check every 2 weeks if there are new flight times that could be uploaded if not InFlightDB.upload or InFlightDB.upload < time() then if InFlightDB.global then local defaults = self.defaults.global for faction, t in pairs(InFlightDB.global) do local found = 0 for src, dt in pairs(t) do for dst, dtime in pairs(dt) do if not defaults[faction][src] or not defaults[faction][src][dst] then found = found + 1 PrintD(faction, "|cff208020-|r", src, "-->", dst, "|cff208020found:|r", FormatTime(dtime)) elseif defaults[faction][src][dst] - dtime >= (debug and 2 or 5) then found = found + 1 PrintD(faction, "|cff208020-|r", src, "-->", dst, "|cff208020updated:|r", FormatTime(defaults[faction][src][dst]), "-->", FormatTime(dtime)) end end end if found > 0 then Print(faction, format("|cff208020- "..L["FlightTimeContribute"].."|r", "|r"..found.."|cff208020")) end end end InFlightDB.upload = time() + 1209600 -- 2 weeks in seconds (60 * 60 * 24 * 14) end -- Create profile and flight time databases local faction = UnitFactionGroup("player") if not debug then InFlight.defaults.global[faction == "Alliance" and "Horde" or "Alliance"] = nil end self.db = LibStub("AceDB"):New("InFlightDB", self.defaults, true) db = self.db.profile vars = self.db.global[faction] oldTakeTaxiNode = TakeTaxiNode TakeTaxiNode = function(slot) if TaxiNodeGetType(slot) ~= "REACHABLE" then return end -- Attempt to get source flight point if another addon auto-takes the taxi -- which can cause this function to run before the TAXIMAP_OPENED function if not taxiSrc then for i = 1, NumTaxiNodes(), 1 do if TaxiNodeGetType(i) == "CURRENT" then taxiSrcName = ShortenName(TaxiNodeName(i)) taxiSrc = L[taxiSrcName] break end end if not taxiSrc then oldTakeTaxiNode(slot) return end end taxiDstName = ShortenName(TaxiNodeName(slot)) taxiDst = L[taxiDstName] local t = vars[taxiSrc] if t and t[taxiDst] and t[taxiDst] > 0 then -- saved variables lookup endTime = t[taxiDst] endText = FormatTime(endTime) else endTime = GetEstimatedTime(slot) endText = (endTime and "~" or "")..FormatTime(endTime) end if db.confirmflight then -- confirm flight StaticPopupDialogs.INFLIGHTCONFIRM = StaticPopupDialogs.INFLIGHTCONFIRM or { button1 = OKAY, button2 = CANCEL, OnAccept = function(this, data) InFlight:StartTimer(data) end, timeout = 0, exclusive = 1, hideOnEscape = 1, } StaticPopupDialogs.INFLIGHTCONFIRM.text = format(L["ConfirmPopup"], "|cffffff00"..taxiDstName..(endTime and " ("..endText..")" or "").."|r") local dialog = StaticPopup_Show("INFLIGHTCONFIRM") if dialog then dialog.data = slot end else -- just take the flight self:StartTimer(slot) end end -- function hooks to detect if a user took a summon hooksecurefunc("TaxiRequestEarlyLanding", function() porttaken = true PrintD("|cffff8080Taxi Early|cff208080, porttaken -|r", porttaken) end) hooksecurefunc("AcceptBattlefieldPort", function(index, accept) porttaken = accept and true PrintD("|cffff8080Battlefield port|cff208080, porttaken -|r", porttaken) end) hooksecurefunc(C_SummonInfo, "ConfirmSummon", function() porttaken = true PrintD("|cffff8080Summon|cff208080, porttaken -|r", porttaken) end) self:Hide() self.LoadBulk = nil end --------------------------------------- function InFlight:InitSource(isTaxiMap) -- cache source location and hook tooltips --------------------------------------- taxiSrcName = nil taxiSrc = nil for i = 1, NumTaxiNodes(), 1 do local tb = _G["TaxiButton"..i] if tb and not tb.inflighted then tb:HookScript("OnEnter", postTaxiNodeOnButtonEnter) tb.inflighted = true end -- PrintD(L[ShortenName(TaxiNodeName(i))], ShortenName(TaxiNodeName(i))) if TaxiNodeGetType(i) == "CURRENT" then taxiSrcName = ShortenName(TaxiNodeName(i)) taxiSrc = L[taxiSrcName] end end end ---------------------------------- function InFlight:StartTimer(slot) -- lift off ---------------------------------- Dismount() -- create the timer bar if not sb then self:CreateBar() end -- start the timers and setup statusbar if endTime then sb:SetMinMaxValues(0, endTime) sb:SetValue(db.fill and 0 or endTime) spark:SetPoint("CENTER", sb, "LEFT", db.fill and 0 or db.width, 0) else SetToUnknown() end InFlight:UpdateLook() timeText:SetFormattedText("%s / %s", FormatTime(0), endText) sb:Show() self:Show() porttaken = nil elapsed, totalTime, startTime = 0, 0, GetTime() takeoff, inworld = true, true throt = min(0.2, (endTime or 50) / (db.width or 1)) -- increases updates for short flights self:RegisterEvent("PLAYER_CONTROL_GAINED") self:RegisterEvent("PLAYER_ENTERING_WORLD") self:RegisterEvent("PLAYER_LEAVING_WORLD") if slot then oldTakeTaxiNode(slot) end end ------------------------------------------- function InFlight:StartMiscFlight(src, dst) -- called from InFlight_Load for special flights ------------------------------------------- taxiSrcName = L[src] taxiSrc = src taxiDstName = L[dst] taxiDst = dst endTime = vars[src] and vars[src][dst] endText = FormatTime(endTime) self:StartTimer() end do -- timer bar local bdrop = { edgeSize = 16, insets = {}, } local bdi = bdrop.insets ----------------------------- function InFlight:CreateBar() ----------------------------- sb = CreateFrame("StatusBar", "InFlightBar", UIParent) sb:Hide() sb:SetPoint(db.p, UIParent, db.rp, db.x, db.y) sb:SetMovable(true) sb:EnableMouse(true) sb:SetClampedToScreen(true) sb:SetScript("OnMouseUp", function(this, a1) if a1 == "RightButton" then InFlight:ShowOptions() elseif a1 == "LeftButton" and IsControlKeyDown() then ontaxi, porttaken = nil, true end end) sb:RegisterForDrag("LeftButton") sb:SetScript("OnDragStart", function(this) if IsShiftKeyDown() then this:StartMoving() end end) sb:SetScript("OnDragStop", function(this) this:StopMovingOrSizing() local a,b,c,d,e = this:GetPoint() db.p, db.rp, db.x, db.y = a, c, floor(d + 0.5), floor(e + 0.5) end) sb:SetScript("OnEnter", function(this) gtt:SetOwner(this, "ANCHOR_RIGHT") gtt:SetText("InFlight", 1, 1, 1) gtt:AddLine(L["TooltipOption1"], 0, 1, 0) gtt:AddLine(L["TooltipOption2"], 0, 1, 0) gtt:AddLine(L["TooltipOption3"], 0, 1, 0) gtt:Show() end) sb:SetScript("OnLeave", function() gtt:Hide() end) timeText = sb:CreateFontString(nil, "OVERLAY") locText = sb:CreateFontString(nil, "OVERLAY") spark = sb:CreateTexture(nil, "OVERLAY") spark:Hide() spark:SetTexture("Interface\\CastingBar\\UI-CastingBar-Spark") spark:SetWidth(16) spark:SetBlendMode("ADD") bord = CreateFrame("Frame", nil, sb, BackdropTemplateMixin and "BackdropTemplate") -- border/background SetPoints(bord, "TOPLEFT", sb, "TOPLEFT", -5, 5, "BOTTOMRIGHT", sb, "BOTTOMRIGHT", 5, -5) bord:SetFrameStrata("LOW") local function onupdate(this, a1) elapsed = elapsed + a1 if elapsed < throt then return end totalTime = GetTime() - startTime elapsed = 0 if takeoff then -- check if actually in flight after take off (doesn't happen immediately) if UnitOnTaxi("player") then takeoff, ontaxi = nil, true elapsed, totalTime, startTime = throt - 0.01, 0, GetTime() elseif totalTime > 5 then sb:Hide() this:Hide() end return end if ontaxi and not inworld then return end if not UnitOnTaxi("player") then -- event bug fix ontaxi = nil end if not ontaxi then -- flight ended PrintD("|cff208080porttaken -|r", porttaken) if not porttaken and taxiSrc then vars[taxiSrc] = vars[taxiSrc] or {} local oldTime = vars[taxiSrc][taxiDst] local newTime = floor(totalTime + 0.5) local msg = strjoin(" ", taxiSrcName, db.totext, taxiDstName, "|cff208080") if not oldTime then msg = msg..L["FlightTimeAdded"].."|r "..FormatTime(newTime) elseif abs(newTime - oldTime) >= 5 then msg = msg..L["FlightTimeUpdated"].."|r "..FormatTime(oldTime).." |cff208080"..db.totext.."|r "..FormatTime(newTime) else if debug then PrintD(msg..L["FlightTimeUpdated"].."|r "..FormatTime(oldTime).." |cff208080"..db.totext.."|r "..FormatTime(newTime)) end if not debug or abs(newTime - oldTime) < 2 then newTime = oldTime end msg = nil end vars[taxiSrc][taxiDst] = newTime if msg and db.chatlog then Print(msg) end end taxiSrcName = nil taxiSrc = nil taxiDstName = nil taxiDst = nil endTime = nil endText = FormatTime(endTime) sb:Hide() this:Hide() return end if endTime then -- update statusbar if destination time is known if totalTime - 2 > endTime then -- in case the flight is longer than expected SetToUnknown() endTime = nil endText = FormatTime(endTime) else local curTime = totalTime if curTime > endTime then curTime = endTime elseif curTime < 0 then curTime = 0 end local value = db.fill and curTime or (endTime - curTime) sb:SetValue(value) spark:SetPoint("CENTER", sb, "LEFT", value * ratio, 0) value = db.countup and curTime or (endTime - curTime) timeText:SetFormattedText("%s / %s", FormatTime(value), endText) end else -- destination time is unknown, so show that it's timing timeText:SetFormattedText("%s / %s", FormatTime(totalTime), endText) end end function self:PLAYER_LEAVING_WORLD() PrintD('PLAYER_LEAVING_WORLD') inworld = nil outworld = GetTime() end function self:PLAYER_ENTERING_WORLD() PrintD('PLAYER_ENTERING_WORLD') inworld = true if outworld then startTime = startTime - (outworld - GetTime()) end outworld = nil end function self:PLAYER_CONTROL_GAINED() PrintD('PLAYER_CONTROL_GAINED') if not inworld then return end if self:IsShown() then ontaxi = nil onupdate(self, 3) end self:UnregisterEvent("PLAYER_ENTERING_WORLD") self:UnregisterEvent("PLAYER_LEAVING_WORLD") self:UnregisterEvent("PLAYER_CONTROL_GAINED") end self:SetScript("OnUpdate", onupdate) self.CreateBar = nil end ------------------------------ function InFlight:UpdateLook() ------------------------------ if not sb then return end sb:SetWidth(db.width) sb:SetHeight(db.height) local texture = smed:Fetch("statusbar", db.texture) local inset = (db.border=="Textured" and 2) or 4 bdrop.bgFile = texture bdrop.edgeFile = smed:Fetch("border", db.border) bdi.left, bdi.right, bdi.top, bdi.bottom = inset, inset, inset, inset bord:SetBackdrop(bdrop) bord:SetBackdropColor(db.backcolor.r, db.backcolor.g, db.backcolor.b, db.backcolor.a) bord:SetBackdropBorderColor(db.bordercolor.r, db.bordercolor.g, db.bordercolor.b, db.bordercolor.a) sb:SetStatusBarTexture(texture) if sb:GetStatusBarTexture() then sb:GetStatusBarTexture():SetHorizTile(false) sb:GetStatusBarTexture():SetVertTile(false) end spark:SetHeight(db.height * 2.4) if endTime then -- in case we're in flight ratio = db.width / endTime sb:SetStatusBarColor(db.barcolor.r, db.barcolor.g, db.barcolor.b, db.barcolor.a) if db.spark then spark:Show() else spark:Hide() end else SetToUnknown() end locText:SetFont(smed:Fetch("font", db.font), db.fontsize, db.outline and "OUTLINE" or nil) locText:SetShadowColor(0, 0, 0, db.fontcolor.a) locText:SetShadowOffset(1, -1) locText:SetTextColor(db.fontcolor.r, db.fontcolor.g, db.fontcolor.b, db.fontcolor.a) timeText:SetFont(smed:Fetch("font", db.font), db.fontsize, db.outlinetime and "OUTLINE" or nil) timeText:SetShadowColor(0, 0, 0, db.fontcolor.a) timeText:SetShadowOffset(1, -1) timeText:SetTextColor(db.fontcolor.r, db.fontcolor.g, db.fontcolor.b, db.fontcolor.a) if db.inline then timeText:SetJustifyH("RIGHT") timeText:SetJustifyV("CENTER") SetPoints(timeText, "RIGHT", sb, "RIGHT", -4, 0) locText:SetJustifyH("LEFT") locText:SetJustifyV("CENTER") SetPoints(locText, "LEFT", sb, "LEFT", 4, 0, "RIGHT", timeText, "LEFT", -2, 0) locText:SetText(taxiDstName or "??") else timeText:SetJustifyH("CENTER") timeText:SetJustifyV("CENTER") SetPoints(timeText, "CENTER", sb, "CENTER", 0, 0) locText:SetJustifyH("CENTER") locText:SetJustifyV("BOTTOM") SetPoints(locText, "TOPLEFT", sb, "TOPLEFT", -24, db.fontsize*2.5, "BOTTOMRIGHT", sb, "TOPRIGHT", 24, (db.border=="None" and 1) or 3) locText:SetFormattedText("%s %s %s", taxiSrcName or "??", db.totext, taxiDstName or "??") end end end --------------------------------- function InFlight:SetLayout(this) -- setups the options in the default interface options --------------------------------- local t1 = this:CreateFontString(nil, "ARTWORK") t1:SetFontObject(GameFontNormalLarge) t1:SetJustifyH("LEFT") t1:SetJustifyV("TOP") t1:SetPoint("TOPLEFT", 16, -16) t1:SetText("|cff0040ffIn|cff00aaffFlight|r") this.tl = t1 local t2 = this:CreateFontString(nil, "ARTWORK") t2:SetFontObject(GameFontHighlight) t2:SetJustifyH("LEFT") t2:SetJustifyV("TOP") SetPoints(t2, "TOPLEFT", t1, "BOTTOMLEFT", 0, -8, "RIGHT", this, "RIGHT", -32, 0) t2:SetNonSpaceWrap(true) local function GetInfo(field) return GetAddOnMetadata("InFlight", field) or "N/A" end t2:SetFormattedText("|cff00aaffAuthor:|r %s\n|cff00aaffVersion:|r %s\n\n%s|r", GetInfo("Author"), GetInfo("Version"), GetInfo("Notes")) local b = CreateFrame("Button", nil, this, "UIPanelButtonTemplate") b:SetText(_G.GAMEOPTIONS_MENU) b:SetWidth(max(120, b:GetTextWidth() + 20)) b:SetScript("OnClick", InFlight.ShowOptions) b:SetPoint("TOPLEFT", t2, "BOTTOMLEFT", -2, -8) this:SetScript("OnShow", nil) self.SetLayout = nil end -- options table smed:Register("border", "Textured", "\\Interface\\None") -- dummy border local InFlightDD, offsetvalue, offsetcount, lastb local info = { } ------------------------------- function InFlight.ShowOptions() ------------------------------- if not InFlightDD then InFlightDD = CreateFrame("Frame", "InFlightDD", InFlight) InFlightDD.displayMode = "MENU" hooksecurefunc("ToggleDropDownMenu", function(...) lastb = select(8, ...) end) local function Exec(b, k, value) if k == "totext" then StaticPopupDialogs["InFlightToText"] = StaticPopupDialogs["InFlightToText"] or { text = "Enter your 'to' text.", button1 = ACCEPT, button2 = CANCEL, hasEditBox = 1, maxLetters = 12, OnAccept = function(self) db.totext = strtrim(self.editBox:GetText()) InFlight:UpdateLook() end, OnShow = function(self) self.editBox:SetText(db.totext) self.editBox:SetFocus() end, OnHide = function(self) self.editBox:SetText("") end, EditBoxOnEnterPressed = function(self) local parent = self:GetParent() db.totext = strtrim(parent.editBox:GetText()) parent:Hide() InFlight:UpdateLook() end, EditBoxOnEscapePressed = function(self) self:GetParent():Hide() end, timeout = 0, exclusive = 1, whileDead = 1, hideOnEscape = 1, } StaticPopup_Show("InFlightToText") elseif (k == "less" or k == "more") and lastb then local off = (k == "less" and -8) or 8 if offsetvalue == value then offsetcount = offsetcount + off else offsetvalue, offsetcount = value, off end local tb = _G[gsub(lastb:GetName(), "ExpandArrow", "")] CloseDropDownMenus(b:GetParent():GetID()) ToggleDropDownMenu(b:GetParent():GetID(), tb.value, nil, nil, nil, nil, tb.menuList, tb) elseif k == "resetoptions" then self.db:ResetProfile() if self.db:GetCurrentProfile() ~= "Default" then db.perchar = true end elseif k == "resettimes" then InFlightDB.dbinit = nil InFlightDB.global = {} ReloadUI() end end local function Set(b, k) if not k then return end db[k] = not db[k] if k == "perchar" then local charKey = UnitName("player").." - "..GetRealmName() if db[k] then db[k] = false self.db:SetProfile(charKey) self.db:CopyProfile("Default") db = self.db.profile db[k] = true else self.db:SetProfile("Default") db = self.db.profile self.db:DeleteProfile(charKey) end end InFlight:UpdateLook() end local function SetSelect(b, a1) db[a1] = tonumber(b.value) or b.value local level, num = strmatch(b:GetName(), "DropDownList(%d+)Button(%d+)") level, num = tonumber(level) or 0, tonumber(num) or 0 for i = 1, UIDROPDOWNMENU_MAXBUTTONS, 1 do local b = _G["DropDownList"..level.."Button"..i.."Check"] if b then b[i == num and "Show" or "Hide"](b) end end InFlight:UpdateLook() end local function SetColor(a1) local dbc = db[UIDROPDOWNMENU_MENU_VALUE] if not dbc then return end if a1 then local pv = ColorPickerFrame.previousValues dbc.r, dbc.g, dbc.b, dbc.a = pv.r, pv.g, pv.b, 1 - pv.opacity else dbc.r, dbc.g, dbc.b = ColorPickerFrame:GetColorRGB() dbc.a = 1 - OpacitySliderFrame:GetValue() end InFlight:UpdateLook() end local function AddButton(lvl, text, keepshown) info.text = text info.keepShownOnClick = keepshown UIDropDownMenu_AddButton(info, lvl) wipe(info) end local function AddToggle(lvl, text, value) info.arg1 = value info.func = Set info.checked = db[value] info.isNotRadio = true AddButton(lvl, text, true) end local function AddExecute(lvl, text, arg1, arg2) info.arg1 = arg1 info.arg2 = arg2 info.func = Exec info.notCheckable = 1 AddButton(lvl, text, true) end local function AddColor(lvl, text, value) local dbc = db[value] if not dbc then return end info.hasColorSwatch = true info.padding = 5 info.hasOpacity = 1 info.r, info.g, info.b, info.opacity = dbc.r, dbc.g, dbc.b, 1 - dbc.a info.swatchFunc, info.opacityFunc, info.cancelFunc = SetColor, SetColor, SetColor info.value = value info.notCheckable = 1 info.func = UIDropDownMenuButton_OpenColorPicker AddButton(lvl, text) end local function AddList(lvl, text, value) info.value = value info.hasArrow = true info.notCheckable = 1 AddButton(lvl, text, true) end local function AddSelect(lvl, text, arg1, value) info.arg1 = arg1 info.func = SetSelect info.value = value if tonumber(value) and tonumber(db[arg1] or "blah") then if floor(100 * tonumber(value)) == floor(100 * tonumber(db[arg1])) then info.checked = true end else info.checked = (db[arg1] == value) end AddButton(lvl, text, true) end local function AddFakeSlider(lvl, value, minv, maxv, step, tbl) local cvalue = 0 local dbv = db[value] if type(dbv) == "string" and tbl then for i, v in ipairs(tbl) do if dbv == v then cvalue = i break end end else cvalue = dbv or ((maxv - minv) / 2) end local adj = (offsetvalue == value and offsetcount) or 0 local starti = max(minv, cvalue - (7 - adj) * step) local endi = min(maxv, cvalue + (8 + adj) * step) if starti == minv then endi = min(maxv, starti + 16 * step) elseif endi == maxv then starti = max(minv, endi - 16 * step) end if starti > minv then AddExecute(lvl, "--", "less", value) end if tbl then for i = starti, endi, step do AddSelect(lvl, tbl[i], value, tbl[i]) end else local fstring = (step >= 1 and "%d") or (step >= 0.1 and "%.1f") or "%.2f" for i = starti, endi, step do AddSelect(lvl, format(fstring, i), value, i) end end if endi < maxv then AddExecute(lvl, "++", "more", value) end end InFlightDD.initialize = function(self, lvl) if lvl == 1 then info.isTitle = true info.notCheckable = 1 AddButton(lvl, "|cff0040ffIn|cff00aaffFlight|r") AddList(lvl, L["BarOptions"], "frame") AddList(lvl, L["TextOptions"], "text") AddList(lvl, _G.OTHER, "other") elseif lvl == 2 then local sub = UIDROPDOWNMENU_MENU_VALUE if sub == "frame" then AddToggle(lvl, L["CountUp"], "countup") AddToggle(lvl, L["FillUp"], "fill") AddToggle(lvl, L["ShowSpark"], "spark") AddList(lvl, L["Height"], "height") AddList(lvl, L["Width"], "width") AddList(lvl, L["Texture"], "texture") AddList(lvl, L["Border"], "border") AddColor(lvl, L["BackgroundColor"], "backcolor") AddColor(lvl, L["BarColor"], "barcolor") AddColor(lvl, L["UnknownColor"], "unknowncolor") AddColor(lvl, L["BorderColor"], "bordercolor") elseif sub == "text" then AddToggle(lvl, L["CompactMode"], "inline") AddExecute(lvl, L["ToText"], "totext") AddList(lvl, L["Font"], "font") AddList(lvl, _G.FONT_SIZE, "fontsize") AddColor(lvl, L["FontColor"], "fontcolor") AddToggle(lvl, L["OutlineInfo"], "outline") AddToggle(lvl, L["OutlineTime"], "outlinetime") elseif sub == "other" then AddToggle(lvl, L["ShowChat"], "chatlog") AddToggle(lvl, L["ConfirmFlight"], "confirmflight") AddToggle(lvl, L["PerCharOptions"], "perchar") AddExecute(lvl, L["ResetOptions"], "resetoptions") AddExecute(lvl, L["ResetFlightTimes"], "resettimes") end elseif lvl == 3 then local sub = UIDROPDOWNMENU_MENU_VALUE if sub == "texture" or sub == "border" or sub == "font" then local t = smed:List(sub == "texture" and "statusbar" or sub) AddFakeSlider(lvl, sub, 1, #t, 1, t) elseif sub == "width" then AddFakeSlider(lvl, sub, 40, 500, 5) elseif sub == "height" then AddFakeSlider(lvl, sub, 4, 100, 1) elseif sub == "fontsize" then AddFakeSlider(lvl, sub, 4, 30, 1) end end end end ToggleDropDownMenu(1, nil, InFlightDD, "cursor") end if debug then function inflightupdate(updateExistingTimes) local updates = {} local ownData = false if #updates == 0 then updates[1] = InFlightDB.global ownData = true end local defaults = self.defaults.global for _, flightPaths in ipairs(updates) do -- Set updateExistingTimes to true to update and add new times (for updates based -- on the current default db) -- Set updateExistingTimes to false to only add new unknown times (use for updates -- not based on current default db to avoid re-adding old/incorrect times) if updateExistingTimes == nil then updateExistingTimes = ownData end for faction, t in pairs(flightPaths) do if faction == "Horde" or faction == "Alliance" then local found = false local updated, added = 0, 0 for src, dt in pairs(t) do if not defaults[faction][src] then defaults[faction][src] = {} PrintD(faction, "|cff208080New source:|r", src) end for dst, utime in pairs(dt) do if src ~= dst and type(utime) == "number" then local vtime = defaults[faction][src][dst] if utime >= 5 and (not vtime or ownData or vtime - utime >= 5) then if vtime then if updateExistingTimes and defaults[faction][src][dst] ~= utime then defaults[faction][src][dst] = utime found = true updated = updated + 1 PrintD(faction, "|cff208020Update time:|r", src, "|cff208020-->|r", dst, "|cff208020- old:|r", vtime, "|cff208020new:|r", utime) end else defaults[faction][src][dst] = utime found = true added = added + 1 PrintD(faction, "|cff208080New time:|r", src, "|cff208020-->|r", dst, "|cff208020- new:|r", utime) end end end end end if found then PrintD(faction, "|cff208020-|r", updated, "|cff208020updated times.|r") PrintD(faction, "|cff208020-|r", added, "|cff208080new times.|r") else PrintD(faction, "|cff208020-|r No time updates found.") end else defaults[faction] = nil Print("Unknown faction removed:", faction) end end InFlightDB.defaults = defaults end end end -- debug
--mediafire function weld(p0,p1,c0,c1,par) local w = Instance.new("Weld",p0 or par) w.Part0 = p0 w.Part1 = p1 w.C0 = c0 or CFrame.new() w.C1 = c1 or CFrame.new() return w end do -- Credit to Stravant... local function QuaternionFromCFrame(cf) local mx, my, mz, m00, m01, m02, m10, m11, m12, m20, m21, m22 = cf:components() local trace = m00 + m11 + m22 if trace > 0 then local s = math.sqrt(1 + trace) local recip = 0.5/s return (m21-m12)*recip, (m02-m20)*recip, (m10-m01)*recip, s*0.5 else local i = 0 if m11 > m00 then i = 1 end if m22 > (i == 0 and m00 or m11) then i = 2 end if i == 0 then local s = math.sqrt(m00-m11-m22+1) local recip = 0.5/s return 0.5*s, (m10+m01)*recip, (m20+m02)*recip, (m21-m12)*recip elseif i == 1 then local s = math.sqrt(m11-m22-m00+1) local recip = 0.5/s return (m01+m10)*recip, 0.5*s, (m21+m12)*recip, (m02-m20)*recip elseif i == 2 then local s = math.sqrt(m22-m00-m11+1) local recip = 0.5/s return (m02+m20)*recip, (m12+m21)*recip, 0.5*s, (m10-m01)*recip end end end local function QuaternionToCFrame(px, py, pz, x, y, z, w) local xs, ys, zs = x + x, y + y, z + z local wx, wy, wz = w*xs, w*ys, w*zs local xx = x*xs local xy = x*ys local xz = x*zs local yy = y*ys local yz = y*zs local zz = z*zs return CFrame.new(px, py, pz,1-(yy+zz), xy - wz, xz + wy,xy + wz, 1-(xx+zz), yz - wx, xz - wy, yz + wx, 1-(xx+yy)) end local function QuaternionSlerp(a, b, t) local cosTheta = a[1]*b[1] + a[2]*b[2] + a[3]*b[3] + a[4]*b[4] local startInterp, finishInterp; if cosTheta >= 0.0001 then if (1 - cosTheta) > 0.0001 then local theta = math.acos(cosTheta) local invSinTheta = 1/math.sin(theta) startInterp = math.sin((1-t)*theta)*invSinTheta finishInterp = math.sin(t*theta)*invSinTheta else startInterp = 1-t finishInterp = t end else if (1+cosTheta) > 0.0001 then local theta = math.acos(-cosTheta) local invSinTheta = 1/math.sin(theta) startInterp = math.sin((t-1)*theta)*invSinTheta finishInterp = math.sin(t*theta)*invSinTheta else startInterp = t-1 finishInterp = t end end return a[1]*startInterp + b[1]*finishInterp, a[2]*startInterp + b[2]*finishInterp, a[3]*startInterp + b[3]*finishInterp, a[4]*startInterp + b[4]*finishInterp end function clerp(a,b,t) if not a or not b then print(a,b,"is missing") return end local qa = {QuaternionFromCFrame(a)} local qb = {QuaternionFromCFrame(b)} local ax, ay, az = a.x, a.y, a.z local bx, by, bz = b.x, b.y, b.z local _t = 1-t return QuaternionToCFrame(_t*ax + t*bx, _t*ay + t*by, _t*az + t*bz,QuaternionSlerp(qa, qb, t)) end end local oc = oc or function(...) return ... end pcall(function() script.Parent.bScript:Destroy() end) script.Name = "bScript" local plr = game:service'Players'.LocalPlayer local mouse = plr:GetMouse() local char = plr.Character local tor,ra,la,rl,ll,hd,hum = char.Torso,char["Right Arm"],char["Left Arm"],char["Right Leg"],char["Left Leg"],char.Head,char.Humanoid local rrs,rls,nk = tor["Right Shoulder"],tor["Left Shoulder"],tor.Neck local nk0 = nk.C0 local rc0,rc1 = rrs.C0,rrs.C1 local lc0,lc1 = rls.C0,rls.C0 local rs,ls = rrs:Clone(),rls:Clone() rs.Name,ls.Name = "rs","ls" rs.DesiredAngle,rs.CurrentAngle = 0,0 ls.DesiredAngle,ls.CurrentAngle = 0,0 local model = Instance.new("Model",char) pcall(function() char.bModel:Destroy() end) model.Name = "bModel" local part = Instance.new("Part") part.BrickColor = BrickColor.new("Really black") part.Reflectance = 0.15 part.FormFactor = "Custom" part.TopSurface,part.BottomSurface = 0,0 part.Size = Vector3.new(.2,.2,.2) part:BreakJoints() part.CanCollide = false function clone(t) local p = t:Clone() p.Parent = t.Parent or model return p end local han = clone(part) han.Size = Vector3.new(.3,.5,.3) han.Transparency = 1 local hold = weld(la,han,CFrame.new(0,-1,0) * CFrame.Angles(math.rad(-90),math.rad(23),0),CFrame.new()) for i=1,14 do local gr = clone(part) gr.BrickColor = BrickColor.new("Silver") gr.Size = Vector3.new(.3,.2,.3) local m = Instance.new("SpecialMesh",gr) m.MeshType = "Sphere" m.Scale = Vector3.new(1,.75,1) * math.max(.85,math.abs(i-7)/5) weld(han,gr,CFrame.new(0,-.6+i*.085,0) * CFrame.Angles(math.rad(15),math.rad(0),math.rad(23)),CFrame.new()) end local p = clone(part) p.Size = Vector3.new(.45,.2,.32) local m = Instance.new("BlockMesh",p) m.Scale = Vector3.new(1,.5,1) weld(han,p,CFrame.new(0,-.62,.125) * CFrame.Angles(math.rad(10),0,0)) local p = clone(part) p.Size = Vector3.new(.45,.2,.3) local m = Instance.new("BlockMesh",p) m.Scale = Vector3.new(1,.5,1) weld(han,p,CFrame.new(0,-.62,-.125) * CFrame.Angles(math.rad(-10),0,0)) local b1 = clone(part) b1.Size = Vector3.new(.2,1,.3) local m = Instance.new("BlockMesh",b1) m.Scale = Vector3.new(1,1,1) local bw1 = weld(han,b1,CFrame.new(0,-.6,0) * CFrame.Angles(math.rad(-10),0,0),CFrame.new(0,.5,0)) local b2 = clone(part) b2.Size = Vector3.new(.2,1,.25) local m = Instance.new("BlockMesh",b2) m.Scale = Vector3.new(.9,1,1) local bw2 = weld(b1,b2,CFrame.new(0,-.5,-.15) * CFrame.Angles(math.rad(-25),0,0),CFrame.new(0,.5,-.125)) local b3 = clone(part) b3.Size = Vector3.new(.2,1,.2) local m = Instance.new("BlockMesh",b3) m.Scale = Vector3.new(.75,1,1) local bw3 = weld(b2,b3,CFrame.new(0,-.5,-.125) * CFrame.Angles(math.rad(-25),0,0),CFrame.new(0,.5,-.1)) local bt = clone(part) bt.BrickColor = BrickColor.new("Black") bt.Size = Vector3.new(.2,.3,.2) local m = Instance.new("BlockMesh",bt) m.Scale = Vector3.new(.5,1,1) * .5 local btw = weld(b3,bt,CFrame.new(0,-.5,.1) * CFrame.Angles(math.rad(-25),0,0),CFrame.new(0,0,.05)) local p = clone(part) p.Size = Vector3.new(.45,.2,.32) local m = Instance.new("BlockMesh",p) m.Scale = Vector3.new(1,.5,1) weld(han,p,CFrame.new(0,.67,.125) * CFrame.Angles(math.rad(15),0,0)) local p = clone(part) p.Size = Vector3.new(.45,.2,.3) local m = Instance.new("BlockMesh",p) m.Scale = Vector3.new(1,.5,1) weld(han,p,CFrame.new(0,.67,-.125) * CFrame.Angles(math.rad(-15),0,0)) local p = clone(part) p.Size = Vector3.new(.4,.2,.3) local m = Instance.new("BlockMesh",p) m.Scale = Vector3.new(1,.5,1) weld(han,p,CFrame.new(0,.75,0) * CFrame.Angles(math.rad(0),0,0)) local p = clone(part) p.Size = Vector3.new(.2,.3,.35) local m = Instance.new("BlockMesh",p) m.Scale = Vector3.new(1,1,1) weld(han,p,CFrame.new(-.1,.8,0) * CFrame.Angles(math.rad(0),0,0)) local p = clone(part) p.Size = Vector3.new(.45,.2,.32) local m = Instance.new("BlockMesh",p) m.Scale = Vector3.new(1,.5,1) weld(han,p,CFrame.new(0,1,.125) * CFrame.Angles(math.rad(-5),0,0)) local p = clone(part) p.Size = Vector3.new(.45,.2,.25) local m = Instance.new("BlockMesh",p) m.Scale = Vector3.new(1,.5,1) weld(han,p,CFrame.new(0,1,-.125) * CFrame.Angles(math.rad(5),0,0)) local t1 = clone(part) t1.Size = Vector3.new(.2,1,.3) local m = Instance.new("BlockMesh",t1) m.Scale = Vector3.new(1,1,1) local tw1 = weld(han,t1,CFrame.new(0,.975,0) * CFrame.Angles(math.rad(10),0,0),CFrame.new(0,-.5,0)) local t2 = clone(part) t2.Size = Vector3.new(.2,1,.25) local m = Instance.new("BlockMesh",t2) m.Scale = Vector3.new(.9,1,1) local tw2 = weld(t1,t2,CFrame.new(0,.5,-.15) * CFrame.Angles(math.rad(25),0,0),CFrame.new(0,-.5,-.125)) local t3 = clone(part) t3.Size = Vector3.new(.2,1,.2) local m = Instance.new("BlockMesh",t3) m.Scale = Vector3.new(.75,1,1) local tw3 = weld(t2,t3,CFrame.new(0,.5,-.125) * CFrame.Angles(math.rad(25),0,0),CFrame.new(0,-.5,-.1)) local tt = clone(part) tt.BrickColor = BrickColor.new("Black") tt.Size = Vector3.new(.2,.3,.2) local m = Instance.new("BlockMesh",tt) m.Scale = Vector3.new(.5,1,1) * .5 local ttw = weld(t3,tt,CFrame.new(0,.5,.1) * CFrame.Angles(math.rad(25),0,0),CFrame.new(0,0,.05)) local W = {bw1,bw2,bw3,tw1,tw2,tw3} local W0 = {bw1.C0,bw2.C0,bw3.C0,tw1.C0,tw2.C0,tw3.C0} local l1 = clone(part) l1.BrickColor = BrickColor.new("Light reddish violet") l1.Size = Vector3.new(.2,.2,.2) local m = Instance.new("CylinderMesh",l1) local l1w = weld(bt,l1) local l2 = clone(l1) local l2w = weld(tt,l2) local amodel = Instance.new("Model") local arrow = clone(part) arrow.Parent = amodel arrow.BrickColor = BrickColor.new("Brown") arrow.Size = Vector3.new(.2,3,.2) arrow.Name = "main" local m = Instance.new("CylinderMesh",arrow) m.Scale = Vector3.new(.5,1,.5) local arrw = weld(han,arrow) local tip = clone(part) tip.Parent = amodel tip.BrickColor = BrickColor.new("Cool yellow") tip.Size = Vector3.new(.2,.4,.2) tip.Name = "tip" local m = Instance.new("SpecialMesh",tip) m.MeshId = "rbxassetid://1033714" m.Scale = Vector3.new(.1,.45,.1) weld(arrow,tip,CFrame.new(0,1.6,0)) local walkspeed = 16 local hpos_i = CFrame.new(0,.8,1.3) local hpos_l = CFrame.new(0,.8,1.55) local hpos = hpos_i local keeper = Vector3.new(0.07,0.82,0) mouse.Button1Up:connect(function() mup = true end) function ragJoint(hit,r,d) Spawn(oc(function() d = d or 0 local rpar,r0,r1 = r.Parent,r.Part0,r.Part1 if d > 0 then wait(d) end local p = hit:Clone() p:BreakJoints() p:ClearAllChildren() p.FormFactor = "Custom" p.Size = p.Size/2 p.Transparency = 1 p.CanCollide = true p.Name = "Colliduh" p.Parent = hit local w = Instance.new("Weld",p) w.Part0 = hit w.Part1 = p w.C0 = CFrame.new(0,-p.Size.Y/2,0) local rot = Instance.new("Rotate",rpar) rot.Name = r.Name rot.Part0 = r0 rot.Part1 = r1 rot.C0 = r.C0 rot.C1 = r.C1 r0.Velocity = Vector3.new() r1.Velocity = Vector3.new() r:Destroy() end)) end function ShootArrow(a,to,spd) Spawn(oc(function() local from = a.main.CFrame a:Destroy() local a = amodel:Clone() for i,v in pairs(a:GetChildren()) do if v:IsA("BasePart") then v.Anchored = true end end a:MakeJoints() a.Parent = workspace local m = a.main --local from = m.CFrame local t = {} local function move(cf) for i,v in pairs(a:GetChildren()) do if v ~= m and v:IsA("BasePart") then t[v] = t[v] or m.CFrame:toObjectSpace(v.CFrame) v.CFrame = cf * t[v] end end m.CFrame = cf end move(from) local velocity = (to.p-from.p).unit * spd * 500 local con local t = tick() con = game:GetService("RunService").Stepped:connect(function() if tick()-t > 25 then con:disconnect() a:Destroy() return end velocity = velocity - Vector3.new(0,196.2/30,0) local newcf = clerp(m.CFrame,CFrame.new(m.Position,m.Position+velocity) * CFrame.Angles(-math.pi/2,0,0),.5) + velocity / 30 local hit,ray local rayo = Ray.new(m.Position,newcf.p-m.Position) local ign = {a,char} repeat hit,ray = workspace:FindPartOnRayWithIgnoreList(rayo,ign) if not hit then break end if hit.CanCollide or game:GetService("Players"):GetPlayerFromCharacter(hit.Parent) then break else table.insert(ign,hit) hit = nil end until false if hit then move(newcf-newcf.p+ray) con:disconnect() game:GetService("Debris"):AddItem(a,300) local char = hit.Parent if not hit.Anchored then local b = hit.CFrame:toObjectSpace(m.CFrame) for i,v in pairs(a:GetChildren()) do pcall(function() v.Anchored = false v.CanCollide = true end) end weld(hit,m,b) end if game:service'Players':GetPlayerFromCharacter(char) and char:FindFirstChild("Torso") then if hit.Name:match("Arm") then local r = char.Torso:FindFirstChild(hit.Name:gsub("Arm","Shoulder"):gsub("Leg","Hip")) if r then ragJoint(hit,r) end elseif hit.Name:match("Head") then for i,v in pairs(char:GetChildren()) do local r = char.Torso:FindFirstChild(v.Name:gsub("Arm","Shoulder"):gsub("Leg","Hip")) if v:IsA("BasePart") and r then ragJoint(v,r,.1) elseif v:IsA("Humanoid") then v.PlatformStand = true v.Changed:connect(function() v.PlatformStand = true end) end end Delay(8,function() char:BreakJoints() end) end end return else move(newcf) end end) end)) end mouse.Button1Down:connect(oc(function() if mb then return end mb = true mup = false rls.Part0,rls.Part1 = nil,nil ls.Part0,ls.Part1 = tor,la ls.Parent = tor ls.C0 = ls.C0 * CFrame.Angles(0,0,rls.CurrentAngle) rrs.Part0,rrs.Part1 = nil,nil rs.Part0,rs.Part1 = tor,ra rs.Parent = tor rs.C0 = rs.C0 * CFrame.Angles(0,0,rrs.CurrentAngle) local hc0 = hold.C0 local bg = Instance.new("BodyGyro",tor) bg.maxTorque = Vector3.new(1,1,1)*9e7 local ltar = 0 local rtar = rrs.C0 * CFrame.Angles(0,0,math.rad(90)) * CFrame.Angles(math.rad(70),0,0) + Vector3.new(-.65,.25,-.25) local ntar = nk0 * CFrame.Angles(0,0,math.rad(70)) local htar = hc0 * CFrame.Angles(0,math.rad(10),0) local t = tick() local iam = 0 local ham = .3 local lend = false local ended local arr = amodel:Clone() arr.Parent = model arr:MakeJoints() hum.WalkSpeed = walkspeed/1.5 local aw = weld(ra,arr.main,CFrame.new(0,-1,0)*CFrame.Angles(-math.pi/2,0,0),CFrame.new(0,-1.5,0)) func = function() local a = (mouse.Hit.p-tor.CFrame:toWorldSpace(ls.C0).p).unit bg.cframe = CFrame.new(tor.Position,mouse.Hit.p*Vector3.new(1,0,1)+tor.Position*Vector3.new(0,1,0)) * CFrame.Angles(0,math.rad(-75),0) local b = math.min(.7,math.max(-.7,a.Y)) ls.C0 = clerp(ls.C0,rls.C0 * CFrame.Angles(math.rad(-90),math.rad(90),math.rad(b*-90)) * CFrame.Angles(math.rad(40),math.rad(0),0) + Vector3.new(math.abs(b)*0,-.25,-.6),.3) local c = tor.CFrame:toObjectSpace(han.CFrame*hpos) * CFrame.new(0,0,0) local d = Vector3.new(1,.6,0) rs.C1 = CFrame.new() rs.C0 = clerp(rs.C0,CFrame.new(d,c.p) * CFrame.new(0,0,-(c.p-d).magnitude+.95) * CFrame.Angles(math.pi/2,math.pi/2,0),.3) nk.C0 = clerp(nk.C0,ntar * CFrame.Angles(math.rad(math.floor(b*-90)),0,0),.3) hold.C0 = clerp(hold.C0,htar,.3) for i,v in pairs(W) do -- v.C0 = clerp(v.C0,W0[i] * CFrame.Angles((not mup and (i>3 and 1 or -1)*iam or 0)*.1,0,0),.6) v.C0 = clerp(v.C0,W0[i] * CFrame.Angles((not mup and (i>3 and 1 or -1)*iam or 0)*.1,0,0),.6) end if not mup then hpos = clerp(hpos,hpos_l * CFrame.new(0,0,iam),.2) if aw then aw.C0 = CFrame.new(Vector3.new(0,-1,0),ra.CFrame:toObjectSpace(han.CFrame*CFrame.new(keeper)).p) * CFrame.Angles(-math.pi/2,0,0) end if tick()-t > .5 and iam < 1 then iam = iam + math.max(0.003,.03-(tick()-t-.5)/70) ham = iam if aw then aw:Destroy() arrw.Parent = han arrw.Part0 = han arrw.Part1 = arr.main aw = nil end end else hpos = clerp(hpos,hpos_l,ham/math.max(0.01,(hpos.p-hpos_l.p).magnitude)) ham = ham * .7 if not ended then ended = true if iam > 0 then arrw.Part1 = nil ShootArrow(arr,mouse.Hit,iam) iam = iam + .2 wait(.5) lend = true else wait(.1) arr:Destroy() lend = true end end end end repeat wait() until lend or tick()-t > 45 mup = nil func = nil hum.WalkSpeed = walkspeed ls.Part0,ls.Part1 = nil,nil ls.Parent = nil rls.Part0,rls.Part1 = tor,la ls.C0 = rls.C0 rs.Part0,rs.Part1 = nil,nil rs.Parent = nil rrs.Part0,rrs.Part1 = tor,ra rs.C0 = rrs.C0 nk.C0 = nk0 bg:Destroy() hold.C0 = hc0 hpos = hpos_i mb = false end)) rcon = game:GetService("RunService").Stepped:connect(oc(function() if not model:IsDescendantOf(workspace) then rcon:disconnect() error() return end --local tc = bt.CFrame:toObjectSpace(tt.CFrame) --local bc = tt.CFrame:toObjectSpace(bt.CFrame) local bm = bt.CFrame:toObjectSpace(han.CFrame*hpos) local tm = tt.CFrame:toObjectSpace(han.CFrame*hpos) l1w.C0 = CFrame.new(bm.p/2,bm.p) * CFrame.Angles(math.pi/2,0,0) l1.Mesh.Scale = Vector3.new(.2,bm.p.magnitude*5,.2) l2w.C0 = CFrame.new(tm.p/2,tm.p) * CFrame.Angles(math.pi/2,0,0) l2.Mesh.Scale = Vector3.new(.2,tm.p.magnitude*5,.2) arrw.C0 = CFrame.new(hpos.p,keeper)*CFrame.new(0,0,-arrow.Size.Y/2) * CFrame.Angles(-math.pi/2,0,0) if func then func() end end))
local skynet = require "skynet" local CacheBase = class("CacheBase") function CacheBase:ctor(key_name, table_name, fields) self._k = key_name self._t = table_name self._f = fields self._m_cache = {} end function CacheBase:get_key(key) return string.format("%s:%s", self._t, key) end function CacheBase:convert_to_lua_data_type(key, value) local column_data = get_schema_data(self._t) local field_type = column_data["fields"][key] if field_type == "number" then return tonumber(value) end return value end function CacheBase:convert_to_lua_data(origin_data) local column_data = get_schema_data(self._t) local result_data = {} for key, value in pairs(origin_data) do local is_in = false local tmp_value = value for field_name, field_type in pairs(column_data["fields"]) do if key == field_name then is_in = true break end end if is_in and column_data["fields"][key] == "number" then tmp_value = tonumber(value) end result_data[key] = tmp_value end return result_data end function CacheBase:convert_value(key, value) return value end function CacheBase:cache_data() local query_sql = construct_query_str(self._t, {}, self._f) local ret = skynet.call("mysqlpool", "lua", "execute", query_sql) if table.empty(ret) then return end if ret["error"] ~= nil or ret["badresult"] ~= nil then return end for _, item in pairs(ret) do local key = item[self._k] local redis_key = self:get_key(key) skynet.call("redispool", "lua", "hmset", redis_key, item) self._m_cache[key] = self:convert_to_lua_data(item) end end function CacheBase:get_data(key) local data = self._m_cache[key] if data == nil then local ret = skynet.call("redispool", "lua", "hgetall", self:get_key(key)) if not table.empty(ret) then -- parse redis data data = {} for i=1, #ret, 2 do data[ret[i]] = ret[i+1] end self._m_cache[key] = self:convert_to_lua_data(data) data = self._m_cache[key] end end return data end function CacheBase:get_all_data() return self._m_cache end return CacheBase
--[[ Copyright (c) 2009-2017, Hendrik "Nevcairiel" Leppkes < h.leppkes at gmail dot com > All rights reserved. ]] local _, Bartender4 = ... Bartender4 = LibStub("AceAddon-3.0"):NewAddon(Bartender4, "Bartender4", "AceConsole-3.0", "AceEvent-3.0", "AceHook-3.0") _G.Bartender4 = Bartender4 local L = LibStub("AceLocale-3.0"):GetLocale("Bartender4") local WoWClassic = select(4, GetBuildInfo()) < 20000 local LDB = LibStub("LibDataBroker-1.1", true) local LDBIcon = LibStub("LibDBIcon-1.0", true) local LibDualSpec = (not WoWClassic) and LibStub("LibDualSpec-1.0", true) local _G = _G local type, pairs, hooksecurefunc = type, pairs, hooksecurefunc -- GLOBALS: LibStub, UIParent, PlaySound, SOUNDKIT, RegisterStateDriver, UnregisterStateDriver -- GLOBALS: BINDING_HEADER_Bartender4, BINDING_CATEGORY_Bartender4, BINDING_NAME_TOGGLEACTIONBARLOCK, BINDING_NAME_BTTOGGLEACTIONBARLOCK -- GLOBALS: BINDING_HEADER_BT4PET, BINDING_CATEGORY_BT4PET, BINDING_HEADER_BT4STANCE, BINDING_CATEGORY_BT4STANCE -- GLOBALS: CreateFrame, MultiBarBottomLeft, MultiBarBottomRight, MultiBarLeft, MultiBarRight, UIPARENT_MANAGED_FRAME_POSITIONS -- GLOBALS: MainMenuBar, OverrideActionBar, MainMenuBarArtFrame, MainMenuExpBar, MainMenuBarMaxLevelBar, ReputationWatchBar -- GLOBALS: StanceBarFrame, PossessBarFrame, PetActionBarFrame, PlayerTalentFrame local defaults = { profile = { tooltip = "enabled", buttonlock = false, outofrange = "button", colors = { range = { r = 0.8, g = 0.1, b = 0.1 }, mana = { r = 0.5, g = 0.5, b = 1.0 } }, selfcastmodifier = true, focuscastmodifier = true, selfcastrightclick = false, snapping = true, blizzardVehicle = false, minimapIcon = {}, mouseovermod = "NONE" } } Bartender4.CONFIG_VERSION = 3 local createLDBLauncher function Bartender4:OnInitialize() self.db = LibStub("AceDB-3.0"):New("Bartender4DB", defaults) self.db.RegisterCallback(self, "OnNewProfile", "InitializeProfile") self.db.RegisterCallback(self, "OnProfileChanged", "UpdateModuleConfigs") self.db.RegisterCallback(self, "OnProfileCopied", "UpdateModuleConfigs") self.db.RegisterCallback(self, "OnProfileReset", "UpdateModuleConfigs") if LibDualSpec then LibDualSpec:EnhanceDatabase(Bartender4.db, "Bartender4") end self:SetupOptions() self.Locked = true self:RegisterEvent("PLAYER_REGEN_DISABLED", "CombatLockdown") self:HideBlizzard() self:UpdateBlizzardVehicle() -- fix the strata of the QueueStatusFrame, otherwise it overlaps our bars if QueueStatusFrame then -- classic doesn't have this QueueStatusFrame:SetParent(UIParent) end if LDB then createLDBLauncher() end BINDING_HEADER_Bartender4 = "Bartender4" BINDING_NAME_BTTOGGLEACTIONBARLOCK = BINDING_NAME_TOGGLEACTIONBARLOCK for i=1,10 do _G[("BINDING_HEADER_BT4BLANK%d"):format(i)] = L["Bar %s"]:format(i) for k=1,12 do _G[("BINDING_NAME_CLICK BT4Button%d:LeftButton"):format(((i-1)*12)+k)] = ("%s %s"):format(L["Bar %s"]:format(i), L["Button %s"]:format(k)) end end BINDING_HEADER_BT4PET = L["Pet Bar"] BINDING_HEADER_BT4STANCE = L["Stance Bar"] for k=1,10 do _G[("BINDING_NAME_CLICK BT4PetButton%d:LeftButton"):format(k)] = ("%s %s"):format(L["Pet Bar"], L["Button %s"]:format(k)) _G[("BINDING_NAME_CLICK BT4StanceButton%d:LeftButton"):format(k)] = ("%s %s"):format(L["Stance Bar"], L["Button %s"]:format(k)) end end function Bartender4:HideBlizzard() -- Hidden parent frame local UIHider = CreateFrame("Frame") UIHider:Hide() self.UIHider = UIHider MultiBarBottomLeft:SetParent(UIHider) MultiBarBottomRight:SetParent(UIHider) MultiBarLeft:SetParent(UIHider) MultiBarRight:SetParent(UIHider) -- Hide MultiBar Buttons, but keep the bars alive for i=1,12 do _G["ActionButton" .. i]:Hide() _G["ActionButton" .. i]:UnregisterAllEvents() _G["ActionButton" .. i]:SetAttribute("statehidden", true) _G["MultiBarBottomLeftButton" .. i]:Hide() _G["MultiBarBottomLeftButton" .. i]:UnregisterAllEvents() _G["MultiBarBottomLeftButton" .. i]:SetAttribute("statehidden", true) _G["MultiBarBottomRightButton" .. i]:Hide() _G["MultiBarBottomRightButton" .. i]:UnregisterAllEvents() _G["MultiBarBottomRightButton" .. i]:SetAttribute("statehidden", true) _G["MultiBarRightButton" .. i]:Hide() _G["MultiBarRightButton" .. i]:UnregisterAllEvents() _G["MultiBarRightButton" .. i]:SetAttribute("statehidden", true) _G["MultiBarLeftButton" .. i]:Hide() _G["MultiBarLeftButton" .. i]:UnregisterAllEvents() _G["MultiBarLeftButton" .. i]:SetAttribute("statehidden", true) end UIPARENT_MANAGED_FRAME_POSITIONS["MainMenuBar"] = nil UIPARENT_MANAGED_FRAME_POSITIONS["StanceBarFrame"] = nil UIPARENT_MANAGED_FRAME_POSITIONS["PossessBarFrame"] = nil UIPARENT_MANAGED_FRAME_POSITIONS["MultiCastActionBarFrame"] = nil UIPARENT_MANAGED_FRAME_POSITIONS["PETACTIONBAR_YPOS"] = nil --MainMenuBar:UnregisterAllEvents() --MainMenuBar:SetParent(UIHider) --MainMenuBar:Hide() MainMenuBar:EnableMouse(false) MainMenuBar:UnregisterEvent("DISPLAY_SIZE_CHANGED") MainMenuBar:UnregisterEvent("UI_SCALE_CHANGED") local animations = {MainMenuBar.slideOut:GetAnimations()} animations[1]:SetOffset(0,0) if OverrideActionBar then -- classic doesn't have this animations = {OverrideActionBar.slideOut:GetAnimations()} animations[1]:SetOffset(0,0) end MainMenuBarArtFrame:Hide() MainMenuBarArtFrame:SetParent(UIHider) if MicroButtonAndBagsBar then -- classic doesn't have this MicroButtonAndBagsBar:Hide() MicroButtonAndBagsBar:SetParent(UIHider) end if StatusTrackingBarManager then StatusTrackingBarManager:Hide() --StatusTrackingBarManager:SetParent(UIHider) end StanceBarFrame:UnregisterAllEvents() StanceBarFrame:Hide() StanceBarFrame:SetParent(UIHider) --BonusActionBarFrame:UnregisterAllEvents() --BonusActionBarFrame:Hide() --BonusActionBarFrame:SetParent(UIHider) if PossessBarFrame then -- classic doesn't have this --PossessBarFrame:UnregisterAllEvents() PossessBarFrame:Hide() PossessBarFrame:SetParent(UIHider) end if MultiCastActionBarFrame then MultiCastActionBarFrame:UnregisterAllEvents() MultiCastActionBarFrame:Hide() MultiCastActionBarFrame:SetParent(UIHider) end PetActionBarFrame:UnregisterAllEvents() PetActionBarFrame:Hide() PetActionBarFrame:SetParent(UIHider) if not WoWClassic then if PlayerTalentFrame then PlayerTalentFrame:UnregisterEvent("ACTIVE_TALENT_GROUP_CHANGED") else hooksecurefunc("TalentFrame_LoadUI", function() PlayerTalentFrame:UnregisterEvent("ACTIVE_TALENT_GROUP_CHANGED") end) end end if MainMenuBarPerformanceBarFrame then MainMenuBarPerformanceBarFrame:Hide() MainMenuBarPerformanceBarFrame:SetParent(UIHider) end if MainMenuExpBar then MainMenuExpBar:Hide() MainMenuExpBar:SetParent(UIHider) end if ReputationWatchBar then ReputationWatchBar:Hide() ReputationWatchBar:SetParent(UIHider) end if MainMenuBarMaxLevelBar then MainMenuBarMaxLevelBar:Hide() MainMenuBarMaxLevelBar:SetParent(UIHider) end self:RegisterPetBattleDriver() end function Bartender4:InitializeProfile() local PresetMod = self:GetModule("Presets") if not self.finishedLoading then PresetMod.applyBlizzardOnEnable = true else PresetMod:ResetProfile("BLIZZARD") end end function Bartender4:RegisterDefaultsKey(key, subdefaults) defaults.profile[key] = subdefaults self.db:RegisterDefaults(defaults) end function Bartender4:UpdateModuleConfigs() local unlock = false if not self.Locked then self:Lock() unlock = true end for k,v in LibStub("AceAddon-3.0"):IterateModulesOfAddon(self) do v:ToggleModule() if v:IsEnabled() and type(v.ApplyConfig) == "function" then v:ApplyConfig() end end if LDB and LDBIcon then LDBIcon:Refresh("Bartender4", Bartender4.db.profile.minimapIcon) end self:UpdateBlizzardVehicle() if unlock then self:Unlock() end end function Bartender4:RegisterPetBattleDriver() if not self.petBattleController then self.petBattleController = CreateFrame("Frame", nil, UIParent, "SecureHandlerStateTemplate") self.petBattleController:SetAttribute("_onstate-petbattle", [[ if newstate == "petbattle" then for i=1,6 do local button, vbutton = ("CLICK BT4Button%d:LeftButton"):format(i), ("ACTIONBUTTON%d"):format(i) for k=1,select("#", GetBindingKey(button)) do local key = select(k, GetBindingKey(button)) self:SetBinding(true, key, vbutton) end -- do the same for the default UIs bindings for k=1,select("#", GetBindingKey(vbutton)) do local key = select(k, GetBindingKey(vbutton)) self:SetBinding(true, key, vbutton) end end else self:ClearBindings() end ]]) RegisterStateDriver(self.petBattleController, "petbattle", "[petbattle]petbattle;nopetbattle") end end function Bartender4:UpdateBlizzardVehicle() if not OverrideActionBar then return end -- classic doesn't have this if self.db.profile.blizzardVehicle then --MainMenuBar:SetParent(UIParent) OverrideActionBar:SetParent(UIParent) if not self.vehicleController then self.vehicleController = CreateFrame("Frame", nil, UIParent, "SecureHandlerStateTemplate") self.vehicleController:SetFrameRef("overrideActionBar", OverrideActionBar) self.vehicleController:SetAttribute("_onstate-vehicle", [[ if newstate == "override" then local f = self:GetFrameRef("overrideActionBar") if (f:GetAttribute("actionpage") or 0) > 10 then newstate = "vehicle" end end if newstate == "vehicle" then for i=1,6 do local button, vbutton = ("CLICK BT4Button%d:LeftButton"):format(i), ("OverrideActionBarButton%d"):format(i) for k=1,select("#", GetBindingKey(button)) do local key = select(k, GetBindingKey(button)) self:SetBindingClick(true, key, vbutton) end -- do the same for the default UIs bindings button = ("ACTIONBUTTON%d"):format(i) for k=1,select("#", GetBindingKey(button)) do local key = select(k, GetBindingKey(button)) self:SetBindingClick(true, key, vbutton) end end else self:ClearBindings() end ]]) end RegisterStateDriver(self.vehicleController, "vehicle", "[overridebar]override;[vehicleui]vehicle;novehicle") else --MainMenuBar:SetParent(self.UIHider) OverrideActionBar:SetParent(self.UIHider) if self.vehicleController then UnregisterStateDriver(self.vehicleController, "vehicle") end end end function Bartender4:CombatLockdown() self:Lock() LibStub("AceConfigDialog-3.0"):Close("Bartender4") end function Bartender4:ToggleLock() if self.Locked then self:Unlock() else self:Lock() end end local getSnap, setSnap do function getSnap() return Bartender4.db.profile.snapping end function setSnap(value) Bartender4.Bar:ForAll("StopDragging") Bartender4.db.profile.snapping = value LibStub("AceConfigRegistry-3.0"):NotifyChange("Bartender4") end end function Bartender4:ShowUnlockDialog() if not self.unlock_dialog then local f = CreateFrame("Frame", "Bartender4Dialog", UIParent) f:SetFrameStrata("DIALOG") f:SetToplevel(true) f:EnableMouse(true) f:SetMovable(true) f:SetClampedToScreen(true) f:SetWidth(360) f:SetHeight(110) f:SetBackdrop{ bgFile="Interface\\DialogFrame\\UI-DialogBox-Background" , edgeFile="Interface\\DialogFrame\\UI-DialogBox-Border", tile = true, insets = {left = 11, right = 12, top = 12, bottom = 11}, tileSize = 32, edgeSize = 32, } f:SetPoint("TOP", 0, -50) f:Hide() f:SetScript('OnShow', function() PlaySound(SOUNDKIT.IG_MAINMENU_OPTION) end) f:SetScript('OnHide', function() PlaySound(SOUNDKIT.GS_TITLE_OPTION_EXIT) end) f:RegisterForDrag('LeftButton') f:SetScript('OnDragStart', function(frame) frame:StartMoving() end) f:SetScript('OnDragStop', function(frame) frame:StopMovingOrSizing() end) local header = f:CreateTexture(nil, "ARTWORK") header:SetTexture("Interface\\DialogFrame\\UI-DialogBox-Header") header:SetWidth(256); header:SetHeight(64) header:SetPoint("TOP", 0, 12) local title = f:CreateFontString("ARTWORK") title:SetFontObject("GameFontNormal") title:SetPoint("TOP", header, "TOP", 0, -14) title:SetText(L["Bartender4"]) local desc = f:CreateFontString("ARTWORK") desc:SetFontObject("GameFontHighlight") desc:SetJustifyV("TOP") desc:SetJustifyH("LEFT") desc:SetPoint("TOPLEFT", 18, -32) desc:SetPoint("BOTTOMRIGHT", -18, 48) desc:SetText(L["Bars unlocked. Move them now and click Lock when you are done."]) local snapping = CreateFrame("CheckButton", "Bartender4Snapping", f, "OptionsCheckButtonTemplate") _G[snapping:GetName() .. "Text"]:SetText(L["Bar Snapping"]) snapping:SetScript("OnShow", function(frame) frame:SetChecked(getSnap()) end) snapping:SetScript("OnClick", function(frame) setSnap(frame:GetChecked()) end) local lockBars = CreateFrame("CheckButton", "Bartender4DialogLock", f, "OptionsButtonTemplate") _G[lockBars:GetName() .. "Text"]:SetText(L["Lock"]) lockBars:SetScript("OnClick", function() Bartender4:Lock() LibStub("AceConfigRegistry-3.0"):NotifyChange("Bartender4") end) --position buttons snapping:SetPoint("BOTTOMLEFT", 14, 10) lockBars:SetPoint("BOTTOMRIGHT", -14, 14) self.unlock_dialog = f end self.unlock_dialog:Show() end function Bartender4:HideUnlockDialog() if self.unlock_dialog then self.unlock_dialog:Hide() end end function Bartender4:Unlock() if self.Locked then self.Locked = false Bartender4.Bar:ForAll("Unlock") self:ShowUnlockDialog() end end function Bartender4:Lock() if not self.Locked then self.Locked = true Bartender4.Bar:ForAll("Lock") self:HideUnlockDialog() end end function Bartender4:Merge(target, source) if type(target) ~= "table" then target = {} end for k,v in pairs(source) do if type(v) == "table" then target[k] = self:Merge(target[k], v) elseif target[k] == nil then target[k] = v end end return target end Bartender4.modulePrototype = {} function Bartender4.modulePrototype:ToggleModule(info, value) if value ~= nil then self.db.profile.enabled = value else value = self.db.profile.enabled end if value and not self:IsEnabled() then self:Enable() elseif not value and self:IsEnabled() then self:Disable() end end function Bartender4.modulePrototype:ToggleOptions() if self.options then self.options.args = self:IsEnabled() and self.optionobject.table or self.disabledoptions end end function Bartender4.modulePrototype:OnDisable() if not self.bar then return end -- assign new config table self.bar.config = self.db.profile self.bar:Disable() self:ToggleOptions() end Bartender4:SetDefaultModulePrototype(Bartender4.modulePrototype) function createLDBLauncher() local L_BT_LEFT = L["|cffffff00Click|r to toggle bar lock"] local L_BT_RIGHT = L["|cffffff00Right-click|r to open the options menu"] local LDBObj = LibStub("LibDataBroker-1.1"):NewDataObject("Bartender4", { type = "launcher", label = "Bartender4", OnClick = function(_, msg) if msg == "LeftButton" then if Bartender4.Locked then Bartender4["Unlock"](Bartender4) else Bartender4["Lock"](Bartender4) end elseif msg == "RightButton" then if LibStub("AceConfigDialog-3.0").OpenFrames["Bartender4"] then LibStub("AceConfigDialog-3.0"):Close("Bartender4") else LibStub("AceConfigDialog-3.0"):Open("Bartender4") end end end, icon = "Interface\\Icons\\INV_Drink_05", OnTooltipShow = function(tooltip) if not tooltip or not tooltip.AddLine then return end tooltip:AddLine("Bartender4") tooltip:AddLine(L_BT_LEFT) tooltip:AddLine(L_BT_RIGHT) end, }) if LDBIcon then LDBIcon:Register("Bartender4", LDBObj, Bartender4.db.profile.minimapIcon) end end
local M = {} function M.number() return 0 end function M.boolean() return M.number() > 0 end function M.string() if M.boolean() then return 'this' else return 'that' end end function M.stringcheck(x) assert(type(x) == 'string' or type(x) == 'number') end function M.numbers() if M.boolean() then return else return M.number(), M.numbers() end end return M
local xmas = {} xmas.sprite = love.graphics.newImage('images/npc/christmaswizard.png') xmas.tickImage = love.graphics.newImage('images/menu/selector.png') xmas.menuImage = love.graphics.newImage('images/npc/xmas-wizard-menu.png') xmas.walk = false xmas.stare = true xmas.items = { -- { ['text']='exit' }, -- { ['text']='inventory' }, -- { ['text']='command' }, -- { ['text']='talk', ['option']={ { ['text']='i am done with you' }, { ['text']='How do I get out of here?' }, { ['text']='Professor Duncan?' }, { ['text']='Who are you?' }, -- }}, } xmas.responses = { ["Who are you?"]={ "I am a Christmas Wizard!", "And definitely not a psych professor.", }, ["How do I get out of here?"]={ "You must venture to the Cave of Frozen Memories,", "And there you shall find the exit.", }, ["Professor Duncan?"]={ "I do not have the slightest idea", "What you're talking about.", }, } return xmas
local chatRate = 2 -- limit to 2 msg/sec local channelName = "vQueue" local filterEnabled = true -- chat filter local isHost = false local hostedCategory = "" local realHostedCategory = "" local playersQueued = {} local chatQueue = {} local groups = {} local vQueueFrame = {} local catListButtons = {} local vQueueFrameShown = false local selectedQuery = "" local selectedCat = "" local isWaitListShown = false local categories = {} local hostListButtons = {} local hostListFrame local categoryListFrame local infoFrame = {} local catListHidden = {} local catListHiddenBot = {} local waitingList = {} local realScroll = false local findTimer = 0 local miniDrag = false local leaderMessages = {} local playerMessages = {} local whoRequestList = {} local newGroups = {} local fixingChat = false local lastUpdate = 0 local whoRequestTimer = 0 local idleMessage = 0 local tankSelected = false local healerSelected = false local damageSelected = false local vQueueColors = { } vQueueColors["WHITE"] = { 247/255, --r 235/255, --g 233/255 --b } vQueueColors["YELLOW"] = { 209/255, --r 164/255, --g 29/255 --b } vQueueColors["GREEN"] = { 79/255, 247/255, 93/255 } local hostOptions = {} vQueue = AceLibrary("AceAddon-2.0"):new("AceHook-2.1") function Wholefind(Search_string, Word) _, F_result = string.gsub(Search_string, '%f[%a]'..Word..'%f[%A]',"") return F_result end function addToSet(set, key) set[key] = true end function removeFromSet(set, key) set[key] = nil end function setContains(set, key) return set[key] ~= nil end function tablelength(T) local count = 0 for _ in pairs(T) do count = count + 1 end return count end function round(num) under = math.floor(num) upper = math.floor(num) + 1 underV = -(under - num) upperV = upper - num if (upperV > underV) then return under else return upper end end function split(pString, pPattern) local Table = {} -- NOTE: use {n = 0} in Lua-5.0 local fpat = "(.-)" .. pPattern local last_end = 1 local s, e, cap = string.find(pString, fpat, 1) while s do if s ~= 1 or cap ~= "" then table.insert(Table,cap) end last_end = e+1 s, e, cap = string.find(pString, fpat, last_end) end if last_end <= string.len(pString) then cap = string.sub(pString, last_end) table.insert(Table, cap) end return Table end function vQueue:OnInitialize() for i = NUM_CHAT_WINDOWS, 1, -1 do self:Hook(getglobal("ChatFrame"..i), "AddMessage") end end function vQueue:AddMessage(frame, text, r, g, b, id) local channelId = GetChannelName(channelName) local blockMsg = false if event == nil then event = "CHAT_MSG_NONE" end if vQueueOptions["filter"] and strfind(event,"CHAT_MSG_CHANNEL") then arg9 = string.lower(arg9) if not vQueueOptions["onlylfg"] then if vQueueOptions["general"] and arg9 == "general - " .. string.lower(GetRealZoneText()) and GetChannelName("General - " .. GetRealZoneText()) ~= 0 then blockMsg = true end if vQueueOptions["trade"] and arg9 == "trade - city" and GetChannelName("Trade - City") ~= 0 then blockMsg = true end if vQueueOptions["lfg"] and arg9 == "lookingforgroup" and GetChannelName("LookingForGroup") ~= 0 then blockMsg = true end if vQueueOptions["world"] and arg9 == "world" and GetChannelName("world") ~= 0 then blockMsg = true end elseif vQueueOptions["onlylfg"] then local foundArg = false local noPunc = filterPunctuation(tostring(text)) for k, v in pairs(getglobal("LFMARGS")) do if Wholefind(noPunc, v) > 0 then foundArg = true end end for k, v in pairs(getglobal("LFGARGS")) do if Wholefind(noPunc, v) > 0 then foundArg = true end end if foundArg then foundArg = false for kCat, kVal in pairs(getglobal("CATARGS")) do for kkCat, kkVal in pairs(kVal) do if Wholefind(noPunc, kkVal) > 0 then foundArg = true end end end end if foundArg then if vQueueOptions["general"] and arg9 == "general - " .. string.lower(GetRealZoneText()) and GetChannelName("General - " .. GetRealZoneText()) ~= 0 then blockMsg = true end if vQueueOptions["trade"] and arg9 == "trade - city" and GetChannelName("Trade - City") ~= 0 then blockMsg = true end if vQueueOptions["lfg"] and arg9 == "lookingforgroup" and GetChannelName("LookingForGroup") ~= 0 then blockMsg = true end if vQueueOptions["world"] and arg9 == "world" and GetChannelName("world") ~= 0 then blockMsg = true end end end end if strfind(event,"CHAT_MSG_CHANNEL") or strfind(event, "CHAT_MSG_CHANNEL_JOIN") or strfind(event, "CHAT_MSG_CHANNEL_LEAVE") or strfind(event, "CHAT_MSG_CHANNEL_NOTICE") then arg9 = string.lower(arg9) if (strfind(arg9, channelName)) and filterEnabled then blockMsg = true end end if (Wholefind(tostring(text), "vqgroup") > 0 or Wholefind(tostring(text), "vqrequest") > 0 or Wholefind(tostring(text), "vqaccept") > 0 or Wholefind(tostring(text), "vqdecline") > 0 or Wholefind(tostring(text), "vqremove") > 0) and filterEnabled then blockMsg = true end if not blockMsg then self.hooks[frame].AddMessage(frame, string.format("%s", text), r, g, b, id) end end function vQueue_OnLoad() this:RegisterEvent("ADDON_LOADED"); this:RegisterEvent("CHAT_MSG_CHANNEL"); this:RegisterEvent("CHAT_MSG_WHISPER"); this:RegisterEvent("WHO_LIST_UPDATE"); end function filterPunctuation( s ) s = string.lower(s) local newString = "" for i = 1, string.len(s) do if string.find(string.sub(s, i, i), "%p") ~= nil then newString = newString .. " " elseif string.find(string.sub(s, i, i), "%d") ~= nil then --nothing needed here else newString = newString .. string.sub(s, i, i) end end return newString end function vQueue_OnEvent(event) if event == "ADDON_LOADED" and arg1 == "vQueue" then findTimer = GetTime() - 10 if MinimapPos == nil then MinimapPos = -30 end if vQueueOptions == nil then vQueueOptions = {} end if vQueueOptions["filter"] == nil then vQueueOptions["filter"] = false end if vQueueOptions["general"] == nil then vQueueOptions["general"] = true end if vQueueOptions["trade"] == nil then vQueueOptions["trade"] = true end if vQueueOptions["lfg"] == nil then vQueueOptions["lfg"] = true end if vQueueOptions["world"] == nil then vQueueOptions["world"] = true end if vQueueOptions["onlylfg"] == nil then vQueueOptions["onlylfg"] = true end if selectedRole == nil then selectedRole = "" end if isFinding == nil then isFinding = true end if notCaught == nil then notCaught = {} end categories["Miscellaneous"] = { expanded = false, "Misc:misc" } categories["Raids"] = { expanded = false, "Upper Blackrock:ubrs", "Onyxia's Lair:ony", "Zul'Gurub:zg", "Molten Core:mc", "Ruins of Ahn'Qiraj:ruins", "Blackwing Lair:bwl", "Temple of Ahn'Qiraj:temple", "Naxxramas:naxx" } categories["Battlegrounds"] = { expanded = false, "Warsong Gulch:wsg", "Arathi Basin:ab", "Alterac Valley:av" } categories["Dungeons"] = { expanded = false, "Ragefire Chasm:rfc", "The Deadmines:dead", "Wailing Caverns:wc", "Shadowfang Keep:sfk", "The Stockade:stock", "Blackfathom Deeps:bfd", "Gnomeregan:gnomer", "Razorfen Kraul:rfk", "The Graveyard:graveyard", "The Library:library", "The Armory:armory", "The Cathedral:cathedral", "Razorfen Downs:rfd", "Uldaman:ulda", "Zul'Farrak:zf", "Maraudon:mara", "The Sunken Temple:st", "Blackrock Depths:brd", "Lower Blackrock:lbrs", "Dire Maul:dm", "Stratholme:strat", "Scholomance:scholo" } categories["Quest Groups"] = { expanded = false, "Quests 1-10:quest110", "Quests 10-20:quest1020", "Quests 20-30:quest2030", "Quests 30-40:quest3040", "Quests 40-50:quest4050", "Quests 50-60:quest5060" } for k, v in pairs(categories) do for kk, vv in pairs(categories[k]) do if type(vv) == "string" then args = split(vv, "\:") if args[2] ~= nil then groups[args[2]] = {} end end end end groups["waitlist"] = {} playersQueued = { } local vQueueFrameBackdrop = { -- path to the background texture bgFile = "Interface\\AddOns\\vQueue\\media\\white", -- path to the border texture edgeFile = "Interface\\AddOns\\vQueue\\media\\border", -- true to repeat the background texture to fill the frame, false to scale it tile = true, -- size (width or height) of the square repeating background tiles (in pixels) tileSize = 8, -- thickness of edge segments and square size of edge corners (in pixels) edgeSize = 12, -- distance from the edges of the frame to those of the background texture (in pixels) insets = { left = 1, right = 1, top = 1, bottom = 1 } } vQueueFrame = CreateFrame("Frame", UIParent) vQueueFrame:SetWidth(594) vQueueFrame:SetHeight(395) vQueueFrame:ClearAllPoints() vQueueFrame:SetPoint("CENTER", UIParent,"CENTER") vQueueFrame:SetMovable(true) vQueueFrame:EnableMouse(true) vQueueFrame:SetBackdrop(vQueueFrameBackdrop) vQueueFrame:SetBackdropColor(15/255, 15/255, 15/255, 0.7) vQueueFrame:SetScript("OnMouseDown", function(self, button) vQueueFrame:StartMoving() vQueueFrame.hostlistNameField:ClearFocus() vQueueFrame.hostlistLevelField:ClearFocus() if isHost or isFinding then vQueueFrame.hostlistRoleText:SetText("") end end) vQueueFrame:SetScript("OnMouseUp", function(self, button) vQueueFrame:StopMovingOrSizing() end) vQueueFrame:SetScript("OnHide", function() vQueueFrame.catList:Hide() vQueueFrame.hostlist:Hide() end) vQueueFrame:SetScript("OnShow", function() vQueue_UpdateHostScroll(scrollbar:GetValue()) vQueue_updateCatColors() end) vQueueFrame.closeButton = vQueue_newButton(vQueueFrame, 10) vQueueFrame.closeButton:SetPoint("BOTTOMRIGHT", vQueueFrame, "BOTTOMRIGHT", -6, 3) vQueueFrame.closeButton:SetText("Close") vQueueFrame.closeButton:SetWidth(vQueueFrame.closeButton:GetTextWidth()+4) vQueueFrame.closeButton:SetScript("OnClick", function() vQueueFrame:Hide() vQueueFrame.catList:Hide() vQueueFrame.hostlist:Hide() vQueueFrameShown = false end) vQueueFrame.optionsButton = vQueue_newButton(vQueueFrame, 10) vQueueFrame.optionsButton:SetPoint("BOTTOMLEFT", vQueueFrame, "BOTTOMLEFT", 6, 3) vQueueFrame.optionsButton:SetText("Options") vQueueFrame.optionsButton:SetWidth(vQueueFrame.optionsButton:GetTextWidth()+3) vQueueFrame.optionsButton:SetScript("OnMouseDown", function() if vQueueFrame.optionsFrame:IsShown() then vQueueFrame.optionsFrame:Hide() else vQueueFrame.optionsFrame:Show() end end) vQueueFrame.catList = CreateFrame("ScrollFrame", vQueueFrame) vQueueFrame.catList:ClearAllPoints() vQueueFrame.catList:SetPoint("LEFT", vQueueFrame, "LEFT", 5, -5) vQueueFrame.catList:SetWidth(118) vQueueFrame.catList:SetHeight(355) vQueueFrame.catList:EnableMouseWheel(true) vQueueFrame.catList:SetBackdrop(vQueueFrameBackdrop) vQueueFrame.catList:SetBackdropColor(20/255, 20/255, 20/255, 0.9) vQueueFrame.catList:SetScript("OnMouseWheel", function() if arg1 == 1 then scrollbarCat:SetValue(scrollbarCat:GetValue()-1) elseif arg1 == -1 then scrollbarCat:SetValue(scrollbarCat:GetValue()+1) end realScroll = true end) vQueueFrame.hostlist = CreateFrame("ScrollFrame", vQueueFrame) vQueueFrame.hostlist:ClearAllPoints() vQueueFrame.hostlist:SetPoint("RIGHT", vQueueFrame, "RIGHT", -5, -5) vQueueFrame.hostlist:SetWidth(465) vQueueFrame.hostlist:SetHeight(355) vQueueFrame.hostlist:EnableMouseWheel(true) vQueueFrame.hostlist:SetBackdrop(vQueueFrameBackdrop) vQueueFrame.hostlist:SetBackdropColor(20/255, 20/255, 20/255, 0.9) vQueueFrame.hostlist:SetScript("OnMouseWheel", function(self, delta) if arg1 == 1 then scrollbar:SetValue(scrollbar:GetValue()-1) elseif arg1 == -1 then scrollbar:SetValue(scrollbar:GetValue()+1) end end) CreateFrame( "GameTooltip", "groupToolTip", nil, "GameTooltipTemplate" ); -- Tooltip name cannot be nil CreateFrame( "GameTooltip", "playerQueueToolTip", nil, "GameTooltipTemplate" ); -- Tooltip name cannot be nil hostListFrame = vQueueFrame.hostlist vQueueFrame.hostlistTopSection = CreateFrame("Frame", nil, vQueueFrame.hostlist) vQueueFrame.hostlistTopSection:ClearAllPoints() vQueueFrame.hostlistTopSection:SetPoint("TOPLEFT", vQueueFrame.hostlist, "TOPLEFT", 0 , 0) vQueueFrame.hostlistTopSection:SetWidth(vQueueFrame.hostlist:GetWidth()) vQueueFrame.hostlistTopSection:SetHeight(vQueueFrame.hostlist:GetHeight() * 1/5) vQueueFrame.hostlistTopSection:SetBackdrop(vQueueFrameBackdrop) vQueueFrame.hostlistTopSection:SetBackdropColor(10/255, 10/255, 10/255, 0.4) vQueueFrame.hostlistTopSection:SetFrameLevel(2) vQueueFrame.hostlistTopSectionBg = vQueueFrame.hostlistTopSection:CreateTexture(nil, "BACKGROUND") vQueueFrame.hostlistTopSectionBg:SetTexture(0, 0, 0, 0) vQueueFrame.hostlistTopSectionBg:SetPoint("BOTTOMLEFT", vQueueFrame.hostlistTopSection, "BOTTOMLEFT", 1, 1) vQueueFrame.hostlistTopSectionBg:SetWidth(vQueueFrame.hostlistTopSection:GetWidth()-2) vQueueFrame.hostlistTopSectionBg:SetHeight(vQueueFrame.hostlistTopSection:GetHeight()-2) vQueueFrame.hostlistBotShadow = vQueueFrame.hostlistTopSection:CreateTexture(nil, "OVERLAY") vQueueFrame.hostlistBotShadow:SetTexture(0, 0, 0, 1) vQueueFrame.hostlistBotShadow:SetPoint("BOTTOM", vQueueFrame.hostlist, "BOTTOM", 0, 1) vQueueFrame.hostlistBotShadow:SetWidth(vQueueFrame.hostlist:GetWidth()) vQueueFrame.hostlistBotShadow:SetHeight(40) vQueueFrame.hostlistBotShadow:SetGradientAlpha("VERTICAL", 0, 0, 0, 1, 0, 0, 0, 0) vQueueFrame.hostlistBotShadow:Hide() vQueueFrame.catlistBotShadow = CreateFrame("Frame", nil, vQueueFrame.catList) vQueueFrame.catlistBotShadow:SetAllPoints() vQueueFrame.catlistBotShadow:SetWidth(vQueueFrame.catList:GetWidth()) vQueueFrame.catlistBotShadow:SetHeight(vQueueFrame.catList:GetHeight()) vQueueFrame.catlistBotShadow:SetFrameLevel(2) vQueueFrame.catlistBotShadowbg = vQueueFrame.catlistBotShadow:CreateTexture(nil, "OVERLAY") vQueueFrame.catlistBotShadowbg:SetTexture(0, 0, 0, 1) vQueueFrame.catlistBotShadowbg:SetPoint("BOTTOM", vQueueFrame.catList, "BOTTOM", 0, 1) vQueueFrame.catlistBotShadowbg:SetWidth(vQueueFrame.catList:GetWidth()) vQueueFrame.catlistBotShadowbg:SetHeight(40) vQueueFrame.catlistBotShadowbg:SetGradientAlpha("VERTICAL", 0, 0, 0, 1, 0, 0, 0, 0) --hostframe waitlist header strings vQueueFrame.hostTitle = CreateFrame("Button", "vQueueButton", vQueueFrame.hostlist) vQueueFrame.hostTitle:ClearAllPoints() vQueueFrame.hostTitle:SetPoint("TOPLEFT", vQueueFrame.hostlist, "TOPLEFT", 0 , -vQueueFrame.hostlistTopSection:GetHeight()-2) vQueueFrame.hostTitle:SetFont("Fonts\\FRIZQT__.TTF", 10) vQueueFrame.hostTitle:SetText("Name") vQueueFrame.hostTitle:SetTextColor(vQueueColors["YELLOW"][1], vQueueColors["YELLOW"][2], vQueueColors["YELLOW"][3]) vQueueFrame.hostTitle:SetPushedTextOffset(0,0) vQueueFrame.hostTitle:SetWidth(vQueueFrame.hostTitle:GetTextWidth()) vQueueFrame.hostTitle:SetHeight(vQueueFrame.hostTitle:GetTextHeight()) vQueueFrame.hostTitle:Hide() vQueueFrame.hostTitleLevel = CreateFrame("Button", "vQueueButton", vQueueFrame.hostlist) vQueueFrame.hostTitleLevel:ClearAllPoints() vQueueFrame.hostTitleLevel:SetPoint("TOPLEFT", vQueueFrame.hostlist, "TOPLEFT", 149, -vQueueFrame.hostlistTopSection:GetHeight() - 2) vQueueFrame.hostTitleLevel:SetFont("Fonts\\FRIZQT__.TTF", 10) vQueueFrame.hostTitleLevel:SetText("Level") vQueueFrame.hostTitleLevel:SetTextColor(vQueueColors["YELLOW"][1], vQueueColors["YELLOW"][2], vQueueColors["YELLOW"][3]) vQueueFrame.hostTitleLevel:SetPushedTextOffset(0,0) vQueueFrame.hostTitleLevel:SetWidth(vQueueFrame.hostTitleLevel:GetTextWidth()) vQueueFrame.hostTitleLevel:SetHeight(vQueueFrame.hostTitleLevel:GetTextHeight()) vQueueFrame.hostTitleLevel:Hide() vQueueFrame.hostTitleClass = CreateFrame("Button", "vQueueButton", vQueueFrame.hostlist) vQueueFrame.hostTitleClass:ClearAllPoints() vQueueFrame.hostTitleClass:SetPoint("TOPLEFT", vQueueFrame.hostlist, "TOPLEFT", 245, -vQueueFrame.hostlistTopSection:GetHeight() - 2) vQueueFrame.hostTitleClass:SetFont("Fonts\\FRIZQT__.TTF", 10) vQueueFrame.hostTitleClass:SetText("Class") vQueueFrame.hostTitleClass:SetTextColor(vQueueColors["YELLOW"][1], vQueueColors["YELLOW"][2], vQueueColors["YELLOW"][3]) vQueueFrame.hostTitleClass:SetPushedTextOffset(0,0) vQueueFrame.hostTitleClass:SetWidth(vQueueFrame.hostTitleClass:GetTextWidth()) vQueueFrame.hostTitleClass:SetHeight(vQueueFrame.hostTitleClass:GetTextHeight()) vQueueFrame.hostTitleClass:Hide() vQueueFrame.hostTitleRole = CreateFrame("Button", "vQueueButton", vQueueFrame.hostlist) vQueueFrame.hostTitleRole:SetPoint("TOPLEFT", vQueueFrame.hostlist, "TOPLEFT", 320, -vQueueFrame.hostlistTopSection:GetHeight() - 2) vQueueFrame.hostTitleRole:SetFont("Fonts\\FRIZQT__.TTF", 10) vQueueFrame.hostTitleRole:SetText("Role") vQueueFrame.hostTitleRole:SetTextColor(vQueueColors["YELLOW"][1], vQueueColors["YELLOW"][2], vQueueColors["YELLOW"][3]) vQueueFrame.hostTitleRole:SetPushedTextOffset(0,0) vQueueFrame.hostTitleRole:SetWidth(vQueueFrame.hostTitleRole:GetTextWidth()) vQueueFrame.hostTitleRole:SetHeight(vQueueFrame.hostTitleRole:GetTextHeight()) vQueueFrame.hostTitleRole:Hide() ----------------------------------------------------------------- --hostframe find header strings vQueueFrame.hostTitleFindName = CreateFrame("Button", "vQueueButton", vQueueFrame.hostlist) vQueueFrame.hostTitleFindName:ClearAllPoints() vQueueFrame.hostTitleFindName:SetPoint("TOPLEFT", vQueueFrame.hostlist, "TOPLEFT", 0, -vQueueFrame.hostlistTopSection:GetHeight() - 2) vQueueFrame.hostTitleFindName:SetFont("Fonts\\FRIZQT__.TTF", 10) vQueueFrame.hostTitleFindName:SetText("Title") vQueueFrame.hostTitleFindName:SetTextColor(vQueueColors["YELLOW"][1], vQueueColors["YELLOW"][2], vQueueColors["YELLOW"][3]) vQueueFrame.hostTitleFindName:SetPushedTextOffset(0,0) vQueueFrame.hostTitleFindName:SetWidth(vQueueFrame.hostTitleFindName:GetTextWidth()) vQueueFrame.hostTitleFindName:SetHeight(vQueueFrame.hostTitleFindName:GetTextHeight()) vQueueFrame.hostTitleFindLeader = CreateFrame("Button", "vQueueButton", vQueueFrame.hostlist) vQueueFrame.hostTitleFindLeader:ClearAllPoints() vQueueFrame.hostTitleFindLeader:SetPoint("TOPLEFT", vQueueFrame.hostlist, "TOPLEFT", 209, -vQueueFrame.hostlistTopSection:GetHeight() - 2) vQueueFrame.hostTitleFindLeader:SetFont("Fonts\\FRIZQT__.TTF", 10) vQueueFrame.hostTitleFindLeader:SetText("Leader") vQueueFrame.hostTitleFindLeader:SetTextColor(vQueueColors["YELLOW"][1], vQueueColors["YELLOW"][2], vQueueColors["YELLOW"][3]) vQueueFrame.hostTitleFindLeader:SetPushedTextOffset(0,0) vQueueFrame.hostTitleFindLeader:SetWidth(vQueueFrame.hostTitleFindLeader:GetTextWidth()) vQueueFrame.hostTitleFindLeader:SetHeight(vQueueFrame.hostTitleFindLeader:GetTextHeight()) vQueueFrame.hostTitleFindLevel = CreateFrame("Button", "vQueueButton", vQueueFrame.hostlist) vQueueFrame.hostTitleFindLevel:ClearAllPoints() vQueueFrame.hostTitleFindLevel:SetPoint("TOPLEFT", vQueueFrame.hostlist, "TOPLEFT", 278, -vQueueFrame.hostlistTopSection:GetHeight() - 2) vQueueFrame.hostTitleFindLevel:SetFont("Fonts\\FRIZQT__.TTF", 10) vQueueFrame.hostTitleFindLevel:SetText("Level") vQueueFrame.hostTitleFindLevel:SetTextColor(vQueueColors["YELLOW"][1], vQueueColors["YELLOW"][2], vQueueColors["YELLOW"][3]) vQueueFrame.hostTitleFindLevel:SetPushedTextOffset(0,0) vQueueFrame.hostTitleFindLevel:SetWidth(vQueueFrame.hostTitleFindLevel:GetTextWidth()) vQueueFrame.hostTitleFindLevel:SetHeight(vQueueFrame.hostTitleFindLevel:GetTextHeight()) vQueueFrame.hostTitleFindSize = CreateFrame("Button", "vQueueButton", vQueueFrame.hostlist) vQueueFrame.hostTitleFindSize:ClearAllPoints() vQueueFrame.hostTitleFindSize:SetPoint("TOPLEFT", vQueueFrame.hostlist, "TOPLEFT", 312, -vQueueFrame.hostlistTopSection:GetHeight() - 2) vQueueFrame.hostTitleFindSize:SetFont("Fonts\\FRIZQT__.TTF", 10) vQueueFrame.hostTitleFindSize:SetText("Size") vQueueFrame.hostTitleFindSize:SetTextColor(vQueueColors["YELLOW"][1], vQueueColors["YELLOW"][2], vQueueColors["YELLOW"][3]) vQueueFrame.hostTitleFindSize:SetPushedTextOffset(0,0) vQueueFrame.hostTitleFindSize:SetWidth(vQueueFrame.hostTitleFindLeader:GetTextWidth()) vQueueFrame.hostTitleFindSize:SetHeight(vQueueFrame.hostTitleFindLeader:GetTextHeight()) vQueueFrame.hostTitleFindRoles = CreateFrame("Button", "vQueueButton", vQueueFrame.hostlist) vQueueFrame.hostTitleFindRoles:ClearAllPoints() vQueueFrame.hostTitleFindRoles:SetPoint("TOPLEFT", vQueueFrame.hostlist, "TOPLEFT", 361, -vQueueFrame.hostlistTopSection:GetHeight() - 2) vQueueFrame.hostTitleFindRoles:SetFont("Fonts\\FRIZQT__.TTF", 10) vQueueFrame.hostTitleFindRoles:SetText("Role(s)") vQueueFrame.hostTitleFindRoles:SetTextColor(vQueueColors["YELLOW"][1], vQueueColors["YELLOW"][2], vQueueColors["YELLOW"][3]) vQueueFrame.hostTitleFindRoles:SetPushedTextOffset(0,0) vQueueFrame.hostTitleFindRoles:SetWidth(vQueueFrame.hostTitleFindRoles:GetTextWidth()) vQueueFrame.hostTitleFindRoles:SetHeight(vQueueFrame.hostTitleFindRoles:GetTextHeight()) vQueueFrame.hostTitleFindName:Hide() vQueueFrame.hostTitleFindLeader:Hide() vQueueFrame.hostTitleFindLevel:Hide() vQueueFrame.hostTitleFindSize:Hide() vQueueFrame.hostTitleFindRoles:Hide() -------------------------------------------------------------------------------------------------------- vQueueFrame.hostlistHeal = CreateFrame("Button", nil, vQueueFrame.hostlistTopSection) vQueueFrame.hostlistHeal:ClearAllPoints() vQueueFrame.hostlistHeal:SetPoint("RIGHT", vQueueFrame.hostlistTopSection, "RIGHT", -32, 0) vQueueFrame.hostlistHeal:SetWidth(32) vQueueFrame.hostlistHeal:SetHeight(32) vQueueFrame.hostlistHeal:UnlockHighlight() vQueueFrame.hostlistHeal:SetScript("OnMouseDown", function() vQueueFrame.hostlistTankCheck:Hide() vQueueFrame.hostlistDpsCheck:Hide() vQueueFrame.hostlistHealCheck:Show() vQueueFrame.hostlistRoleText:SetText("") vQueueFrame.hostlistHostButton:Show() selectedRole = "Healer" end) vQueueFrame.hostlistHeal:SetScript("OnEnter", function() vQueueFrame.hostlistHealTex:SetVertexColor(1, 1, 0) end) vQueueFrame.hostlistHeal:SetScript("OnLeave", function() vQueueFrame.hostlistHealTex:SetVertexColor(1, 1, 1) end) vQueueFrame.hostlistHealTex = vQueueFrame.hostlistHeal:CreateTexture(nil, "ARTWORK") vQueueFrame.hostlistHealTex:SetTexture("Interface\\AddOns\\vQueue\\media\\Healer") vQueueFrame.hostlistHealTex:SetPoint("TOP", vQueueFrame.hostlistHeal, "TOP", 0, 0) vQueueFrame.hostlistHealTex:SetWidth(vQueueFrame.hostlistHeal:GetWidth()) vQueueFrame.hostlistHealTex:SetHeight(vQueueFrame.hostlistHeal:GetHeight()) vQueueFrame.hostlistHealCheck = vQueueFrame.hostlistHeal:CreateTexture(nil, "OVERLAY") vQueueFrame.hostlistHealCheck:SetTexture("Interface\\BUTTONS\\UI-CheckBox-Check") vQueueFrame.hostlistHealCheck:SetVertexColor(0.1,0.8,0.1) vQueueFrame.hostlistHealCheck:SetAllPoints() vQueueFrame.hostlistDps = CreateFrame("Button", nil, vQueueFrame.hostlistTopSection) vQueueFrame.hostlistDps:SetPoint("RIGHT", vQueueFrame.hostlistTopSection, "RIGHT", 0, 0) vQueueFrame.hostlistDps:SetWidth(32) vQueueFrame.hostlistDps:SetHeight(32) vQueueFrame.hostlistDps:SetScript("OnMouseDown", function() vQueueFrame.hostlistTankCheck:Hide() vQueueFrame.hostlistDpsCheck:Show() vQueueFrame.hostlistHealCheck:Hide() vQueueFrame.hostlistRoleText:SetText("") selectedRole = "Damage" end) vQueueFrame.hostlistDps:SetScript("OnEnter", function() vQueueFrame.hostlistDpsTex:SetVertexColor(1, 1, 0) end) vQueueFrame.hostlistDps:SetScript("OnLeave", function() vQueueFrame.hostlistDpsTex:SetVertexColor(1, 1, 1) end) vQueueFrame.hostlistDpsTex = vQueueFrame.hostlistDps:CreateTexture(nil, "ARTWORK") vQueueFrame.hostlistDpsTex:SetTexture("Interface\\AddOns\\vQueue\\media\\Damage") vQueueFrame.hostlistDpsTex:SetPoint("TOP", vQueueFrame.hostlistDps, "TOP", 0, 0) vQueueFrame.hostlistDpsTex:SetWidth(vQueueFrame.hostlistDps:GetWidth()) vQueueFrame.hostlistDpsTex:SetHeight(vQueueFrame.hostlistDps:GetHeight()) vQueueFrame.hostlistDpsCheck = vQueueFrame.hostlistDps:CreateTexture(nil, "OVERLAY") vQueueFrame.hostlistDpsCheck:SetTexture("Interface\\BUTTONS\\UI-CheckBox-Check") vQueueFrame.hostlistDpsCheck:SetVertexColor(0.1,0.8,0.1) vQueueFrame.hostlistDpsCheck:SetAllPoints() vQueueFrame.hostlistTank = CreateFrame("Button", nil, vQueueFrame.hostlistTopSection) vQueueFrame.hostlistTank:SetPoint("RIGHT", vQueueFrame.hostlistTopSection, "RIGHT", -64 , 0) vQueueFrame.hostlistTank:SetWidth(32) vQueueFrame.hostlistTank:SetHeight(32) vQueueFrame.hostlistTank:SetScript("OnMouseDown", function() vQueueFrame.hostlistTankCheck:Show() vQueueFrame.hostlistDpsCheck:Hide() vQueueFrame.hostlistHealCheck:Hide() vQueueFrame.hostlistRoleText:SetText("") selectedRole = "Tank" end) vQueueFrame.hostlistTank:SetScript("OnEnter", function() vQueueFrame.hostlistTankTex:SetVertexColor(1, 1, 0) end) vQueueFrame.hostlistTank:SetScript("OnLeave", function() vQueueFrame.hostlistTankTex:SetVertexColor(1, 1, 1) end) vQueueFrame.hostlistTankTex = vQueueFrame.hostlistTank:CreateTexture(nil, "ARTWORK") vQueueFrame.hostlistTankTex:SetTexture("Interface\\AddOns\\vQueue\\media\\Tank") vQueueFrame.hostlistTankTex:SetPoint("TOP", vQueueFrame.hostlistTank, "TOP", 0, 0) vQueueFrame.hostlistTankTex:SetWidth(vQueueFrame.hostlistTank:GetWidth()) vQueueFrame.hostlistTankTex:SetHeight(vQueueFrame.hostlistTank:GetHeight()) vQueueFrame.hostlistTankCheck = vQueueFrame.hostlistTank:CreateTexture(nil, "OVERLAY") vQueueFrame.hostlistTankCheck:SetTexture("Interface\\BUTTONS\\UI-CheckBox-Check") vQueueFrame.hostlistTankCheck:SetVertexColor(0.1,0.8,0.1) vQueueFrame.hostlistTankCheck:SetAllPoints() vQueueFrame.hostlistRoleText = CreateFrame("Button", nil, vQueueFrame.hostlistTopSection) vQueueFrame.hostlistRoleText:ClearAllPoints() vQueueFrame.hostlistRoleText:SetPoint("BOTTOMLEFT", vQueueFrame.hostlistTopSection, "BOTTOMLEFT", 5, 5) vQueueFrame.hostlistRoleText:EnableMouse(false) vQueueFrame.hostlistRoleText:SetFont("Fonts\\FRIZQT__.TTF", 10, "OUTLINE") vQueueFrame.hostlistRoleText:SetText("(Select a role to start finding)") vQueueFrame.hostlistRoleText:SetTextColor(vQueueColors["YELLOW"][1], vQueueColors["YELLOW"][2], vQueueColors["YELLOW"][3]) vQueueFrame.hostlistRoleText:SetWidth(vQueueFrame.hostlistRoleText:GetTextWidth()) vQueueFrame.hostlistRoleText:SetHeight(vQueueFrame.hostlistRoleText:GetTextHeight()) vQueueFrame.hostlistRoleText:SetScript("OnUpdate", function() this:SetWidth(vQueueFrame.hostlistRoleText:GetTextWidth()) this:SetHeight(vQueueFrame.hostlistRoleText:GetTextHeight()) end) if selectedRole == "Healer" then vQueueFrame.hostlistTankCheck:Hide() vQueueFrame.hostlistDpsCheck:Hide() vQueueFrame.hostlistHealCheck:Show() vQueueFrame.hostlistRoleText:SetText("") elseif selectedRole == "Damage" then vQueueFrame.hostlistTankCheck:Hide() vQueueFrame.hostlistDpsCheck:Show() vQueueFrame.hostlistHealCheck:Hide() vQueueFrame.hostlistRoleText:SetText("") elseif selectedRole == "Tank" then vQueueFrame.hostlistTankCheck:Show() vQueueFrame.hostlistDpsCheck:Hide() vQueueFrame.hostlistHealCheck:Hide() vQueueFrame.hostlistRoleText:SetText("") end vQueueFrame.hostlistHostButton = vQueue_newButton(vQueueFrame.hostlistTopSection, 10) vQueueFrame.hostlistHostButton:SetPoint("BOTTOMRIGHT", vQueueFrame.hostlistTopSection, "BOTTOMRIGHT", -3, 5) vQueueFrame.hostlistHostButton:SetText("Start new group") vQueueFrame.hostlistHostButton:SetWidth(vQueueFrame.hostlistHostButton:GetTextWidth()+10) vQueueFrame.hostlistHostButton:SetScript("OnClick", function() if UnitLevel("player") < 5 then vQueueFrame.hostlistRoleText:SetText("(You must be at least level 5 to use this)") return end titleDung = selectedQuery if titleDung == "dead" then titleDung = "DM" end vQueueFrame.hostlistNameField:SetText("LFM " .. string.upper(selectedQuery) .. " - " .. getglobal("MINLVLS")[selectedQuery] .. "+ need all") vQueueFrame.hostlistHostButton:Hide() isWaitListShown = true vQueueFrame.hostTitleFindName:Hide() vQueueFrame.hostTitleFindLeader:Hide() vQueueFrame.hostTitleFindLevel:Hide() vQueueFrame.hostTitleFindSize:Hide() vQueueFrame.hostTitleFindRoles:Hide() vQueueFrame.hostlistLevelField:SetText(getglobal("MINLVLS")[selectedQuery]) vQueueFrame.hostlistLevelField:Show() vQueueFrame.hostlistNameField:Show() vQueueFrame.hostlistCreateButton:Show() vQueueFrame.hostlistCancelButton:Show() vQueueFrame.hostlistCreateButton:SetText("Create group") scrollbar:SetValue(1) hostedCategory = selectedQuery prevSelected = selectedQuery selectedQuery = "waitlist" vQueue_ShowGroups(selectedQuery, prevSelected) end) vQueueFrame.hostlistHostButton:SetScript("OnEnter", function() playerQueueToolTip:SetOwner( this, "ANCHOR_CURSOR" ); playerQueueToolTip:AddLine("Find players for", 1, 1, 1, 1) playerQueueToolTip:AddLine(realHostedCategory, vQueueColors["GREEN"][1], vQueueColors["GREEN"][2], vQueueColors["GREEN"][3], 1) playerQueueToolTip:Show() end) vQueueFrame.hostlistHostButton:SetScript("OnLeave", function() playerQueueToolTip:Hide() end) vQueueFrame.hostlistEditButton = vQueue_newButton(vQueueFrame.hostlistTopSection, 10) vQueueFrame.hostlistEditButton:SetPoint("BOTTOMRIGHT", vQueueFrame.hostlistTopSection, "BOTTOMRIGHT", -3, 5) vQueueFrame.hostlistEditButton:SetText("Edit group") vQueueFrame.hostlistEditButton:SetWidth(vQueueFrame.hostlistEditButton:GetTextWidth()+5) vQueueFrame.hostlistEditButton:SetScript("OnClick", function() vQueueFrame.hostlistEditButton:Hide() isWaitListShown = true scrollbar:SetValue(1) prevSelected = selectedQuery selectedQuery = "waitlist" vQueue_ShowGroups(selectedQuery, prevSelected) vQueueFrame.hostTitleFindName:Hide() vQueueFrame.hostTitleFindLeader:Hide() vQueueFrame.hostTitleFindLevel:Hide() vQueueFrame.hostTitleFindSize:Hide() vQueueFrame.hostTitleFindRoles:Hide() vQueueFrame.hostlistLevelField:Show() vQueueFrame.hostlistNameField:Show() vQueueFrame.hostlistCreateButton:Show() vQueueFrame.hostlistBotShadow:SetHeight(400) vQueueFrame.hostlistBotShadow:Show() vQueueFrame.hostlistCreateButton:SetText("Save") end) vQueueFrame.hostlistEditButton:Hide() vQueueFrame.hostlistUnlistButton = vQueue_newButton(vQueueFrame.hostlistTopSection, 10) vQueueFrame.hostlistUnlistButton:SetPoint("TOPRIGHT", vQueueFrame.hostlistTopSection, "TOPRIGHT", -3, -5) vQueueFrame.hostlistUnlistButton:SetText("Unlist group") vQueueFrame.hostlistUnlistButton:SetWidth(vQueueFrame.hostlistUnlistButton:GetTextWidth()+5) vQueueFrame.hostlistUnlistButton:SetScript("OnClick", function() vQueueFrame.hostlistEditButton:Hide() vQueueFrame.hostlistWaitListButton:Hide() this:Hide() vQueueFrame.hostlistLevelField:Hide() vQueueFrame.hostlistNameField:Hide() vQueueFrame.hostlistCreateButton:Hide() isHost = false isWaitListShown = false vQueueFrame.hostTitle:Hide() vQueueFrame.hostTitleRole:Hide() vQueueFrame.hostTitleClass:Hide() vQueueFrame.hostTitleLevel:Hide() vQueueFrame.topsectionHostName:Hide() if selectedQuery == "waitlist" then selectedQuery = hostedCategory end scrollbar:SetValue(1) vQueue_ShowGroups(selectedQuery, "waitlist") groups["waitlist"] = {} vQueueFrame.hostlistRoleText:SetText("") vQueueFrame.hostlistHostButton:Show() vQueueFrame.hostTitleFindName:Show() vQueueFrame.hostTitleFindLeader:Show() vQueueFrame.hostTitleFindLevel:Show() vQueueFrame.hostTitleFindSize:Show() vQueueFrame.hostTitleFindRoles:Show() end) vQueueFrame.hostlistUnlistButton:Hide() vQueueFrame.hostlistWaitListButton = vQueue_newButton(vQueueFrame.hostlistTopSection, 10) vQueueFrame.hostlistWaitListButton:SetPoint("TOPRIGHT", vQueueFrame.hostlistTopSection, "TOPRIGHT", -75, -5) vQueueFrame.hostlistWaitListButton:SetText("Wait list") vQueueFrame.hostlistWaitListButton:SetWidth(vQueueFrame.hostlistWaitListButton:GetTextWidth()+10) vQueueFrame.hostlistWaitListButton:SetScript("OnClick", function() vQueueFrame.topsectiontitle:SetText(realHostedCategory .. "(" .. getglobal("MINLVLS")[hostedCategory] .. ")") vQueueFrame.topsectiontitle:SetWidth(vQueueFrame.topsectiontitle:GetTextWidth()) vQueueFrame.topsectiontitle:SetHeight(vQueueFrame.topsectiontitle:GetTextHeight()) if not vQueueFrame.hostlistTopSectionBg:SetTexture("Interface\\AddOns\\vQueue\\media\\" .. hostedCategory) then vQueueFrame.hostlistTopSectionBg:SetTexture(0, 0, 0, 0) end for k, v in pairs(catListButtons) do if split(v:GetText(), "%(")[1] == realHostedCategory then vQueueFrame.catListHighlight:SetParent(v) vQueueFrame.catListHighlight:SetPoint("LEFT", v, "LEFT", -11, 0) vQueueFrame.catListHighlight:Show() end end isWaitListShown = true vQueueFrame.hostTitle:Show() vQueueFrame.hostTitleRole:Show() vQueueFrame.hostTitleClass:Show() vQueueFrame.hostTitleLevel:Show() vQueueFrame.topsectionHostName:Show() scrollbar:SetValue(1) prevSelected = selectedQuery selectedQuery = "waitlist" vQueue_ShowGroups(selectedQuery, prevSelected) vQueueFrame.hostTitleFindName:Hide() vQueueFrame.hostTitleFindLeader:Hide() vQueueFrame.hostTitleFindLevel:Hide() vQueueFrame.hostTitleFindSize:Hide() vQueueFrame.hostTitleFindRoles:Hide() end) vQueueFrame.hostlistWaitListButton:SetScript("OnUpdate", function() this:SetText("Wait list(" .. tablelength(groups["waitlist"]) .. ")") this:SetWidth(this:GetTextWidth()+10) end) vQueueFrame.hostlistWaitListButton:Hide() vQueueFrame.optionsFrame = CreateFrame("Frame", nil, vQueueFrame) vQueueFrame.optionsFrame:SetWidth(200) vQueueFrame.optionsFrame:SetHeight(130) vQueueFrame.optionsFrame:SetPoint("BOTTOM", vQueueFrame, "TOP") vQueueFrame.optionsFrame:SetBackdrop(vQueueFrameBackdrop) vQueueFrame.optionsFrame:SetBackdropColor(10/255, 10/255, 10/255, 0.8) vQueueFrame.optionsFrame:EnableMouse(true) vQueueFrame.optionsFrame:SetMovable(true) vQueueFrame.optionsFrame:SetFrameLevel(4) vQueueFrame.optionsFrame:SetClampedToScreen(true) vQueueFrame.optionsFrame:SetScript("OnMouseDown", function() this:StartMoving() end) vQueueFrame.optionsFrame:SetScript("OnMouseUp", function() this:StopMovingOrSizing() end) vQueueFrame.optionsFrame:Hide() vQueueFrame.hostlistFindButton = CreateFrame("CheckButton", "findButtonCheck", vQueueFrame.optionsFrame, "UICheckButtonTemplate"); vQueueFrame.hostlistFindButton:SetPoint("BOTTOMRIGHT", vQueueFrame.optionsFrame, "BOTTOMRIGHT", -65, 20) getglobal(vQueueFrame.hostlistFindButton:GetName() .."Text"):SetText("Find groups") vQueueFrame.hostlistFindButton:SetWidth(16) vQueueFrame.hostlistFindButton:SetHeight(16) vQueueFrame.hostlistFindButton:SetChecked(isFinding) vQueueFrame.hostlistFindButton:SetScript("OnClick", function() if this:GetChecked() then vQueueFrame.hostlistHostButton:Show() vQueueFrame.hostlistLevelField:Hide() vQueueFrame.hostlistNameField:Hide() vQueueFrame.hostlistCreateButton:Hide() isFinding = true vQueue_SlashCommandHandler( "lfg " .. selectedQuery ) elseif not this:GetChecked() then isFinding = false end end) vQueueFrame.hostlistNameField = CreateFrame("EditBox", nil, vQueueFrame.hostlist ) vQueueFrame.hostlistNameField:SetPoint("CENTER", vQueueFrame.hostlist, "CENTER", 0, 20) vQueueFrame.hostlistNameField:SetAutoFocus(false) vQueueFrame.hostlistNameField:SetFont("Fonts\\FRIZQT__.TTF", 10) vQueueFrame.hostlistNameField:SetTextColor(vQueueColors["WHITE"][1], vQueueColors["WHITE"][2], vQueueColors["WHITE"][3]) vQueueFrame.hostlistNameField:SetMaxLetters(36) vQueueFrame.hostlistNameField:SetBackdrop(vQueueFrameBackdrop) vQueueFrame.hostlistNameField:SetBackdropColor(30/255, 30/255, 30/255, 1.0) vQueueFrame.hostlistNameField:SetWidth(vQueueFrame.hostlist:GetWidth() * 4/5) vQueueFrame.hostlistNameField:SetTextInsets(4, 0, 0, 0) vQueueFrame.hostlistNameField:SetHeight(20) vQueueFrame.hostlistNameField:SetFrameLevel(4) vQueueFrame.hostlistNameFieldText = CreateFrame("Button", nil, vQueueFrame.hostlistNameField) vQueueFrame.hostlistNameFieldText:ClearAllPoints() vQueueFrame.hostlistNameFieldText:SetPoint("CENTER", vQueueFrame.hostlistNameField, "CENTER", -8, 20) vQueueFrame.hostlistNameFieldText:SetFont("Fonts\\FRIZQT__.TTF", 12) vQueueFrame.hostlistNameFieldText:SetText("Title") vQueueFrame.hostlistNameFieldText:SetTextColor(vQueueColors["YELLOW"][1], vQueueColors["YELLOW"][2], vQueueColors["YELLOW"][3]) vQueueFrame.hostlistNameFieldText:SetPushedTextOffset(0,0) vQueueFrame.hostlistNameFieldText:SetWidth(vQueueFrame.hostlistNameFieldText:GetTextWidth()) vQueueFrame.hostlistNameFieldText:SetHeight(vQueueFrame.hostlistNameFieldText:GetTextHeight()) vQueueFrame.hostlistNameFieldText:SetFrameLevel(4) vQueueFrame.hostlistLevelField = CreateFrame("EditBox", nil, vQueueFrame.hostlistNameField ) vQueueFrame.hostlistLevelField:SetPoint("TOPLEFT", vQueueFrame.hostlistNameField, "BOTTOMLEFT", 55, -6) vQueueFrame.hostlistLevelField:SetAutoFocus(false) vQueueFrame.hostlistLevelField:SetFont("Fonts\\FRIZQT__.TTF", 10) vQueueFrame.hostlistLevelField:SetText(tostring(UnitLevel("player"))) vQueueFrame.hostlistLevelField:SetTextColor(vQueueColors["WHITE"][1], vQueueColors["WHITE"][2], vQueueColors["WHITE"][3]) vQueueFrame.hostlistLevelField:SetMaxLetters(2) vQueueFrame.hostlistLevelField:SetBackdrop(vQueueFrameBackdrop) vQueueFrame.hostlistLevelField:SetBackdropColor(30/255, 30/255, 30/255, 1.0) vQueueFrame.hostlistLevelField:SetTextInsets(3, 0, 0, 0) vQueueFrame.hostlistLevelField:SetNumeric(true) vQueueFrame.hostlistLevelField:SetWidth(20) vQueueFrame.hostlistLevelField:SetHeight(18) vQueueFrame.hostlistLevelField:SetFrameLevel(4) vQueueFrame.hostlistLevelFieldText = CreateFrame("Button", nil, vQueueFrame.hostlistLevelField) vQueueFrame.hostlistLevelFieldText:ClearAllPoints() vQueueFrame.hostlistLevelFieldText:SetPoint("RIGHT", vQueueFrame.hostlistLevelField, "LEFT", -3, 0) vQueueFrame.hostlistLevelFieldText:SetFont("Fonts\\FRIZQT__.TTF", 8) vQueueFrame.hostlistLevelFieldText:SetText("Minimum lvl") vQueueFrame.hostlistLevelFieldText:SetTextColor(vQueueColors["YELLOW"][1], vQueueColors["YELLOW"][2], vQueueColors["YELLOW"][3]) vQueueFrame.hostlistLevelFieldText:SetPushedTextOffset(0,0) vQueueFrame.hostlistLevelFieldText:SetWidth(vQueueFrame.hostlistLevelFieldText:GetTextWidth()) vQueueFrame.hostlistLevelFieldText:SetHeight(vQueueFrame.hostlistLevelFieldText:GetTextHeight()) vQueueFrame.hostlistLevelFieldText:SetFrameLevel(4) vQueueFrame.replyFrame = CreateFrame("Frame", nil, vQueueFrame) vQueueFrame.replyFrame:SetWidth(300) vQueueFrame.replyFrame:SetHeight(150) vQueueFrame.replyFrame:SetPoint("CENTER", vQueueFrame) vQueueFrame.replyFrame:SetBackdrop(vQueueFrameBackdrop) vQueueFrame.replyFrame:SetFrameLevel(4) vQueueFrame.replyFrame:SetBackdropColor(15/255, 15/255, 15/255, 0.9) vQueueFrame.replyFrameToString = vQueueFrame.replyFrame:CreateFontString(nil) vQueueFrame.replyFrameToString:SetFont("Fonts\\FRIZQT__.TTF", 10) vQueueFrame.replyFrameToString:SetText("To:") vQueueFrame.replyFrameToString:SetTextColor(vQueueColors["YELLOW"][1], vQueueColors["YELLOW"][2], vQueueColors["YELLOW"][3]) vQueueFrame.replyFrameToString:SetWidth(vQueueFrame.replyFrameToString:GetStringWidth()) vQueueFrame.replyFrameToString:SetHeight(8) vQueueFrame.replyFrameToString:SetPoint("TOPLEFT", vQueueFrame.replyFrame, "TOPLEFT", 5, -13) vQueueFrame.replyFrameTo = CreateFrame("EditBox", nil, vQueueFrame.replyFrame ) vQueueFrame.replyFrameTo:SetPoint("TOPLEFT", vQueueFrame.replyFrame, "TOPLEFT", 25, -8) vQueueFrame.replyFrameTo:SetAutoFocus(false) vQueueFrame.replyFrameTo:SetFont("Fonts\\FRIZQT__.TTF", 10) vQueueFrame.replyFrameTo:SetText("LFM") vQueueFrame.replyFrameTo:SetTextColor(vQueueColors["WHITE"][1], vQueueColors["WHITE"][2], vQueueColors["WHITE"][3]) vQueueFrame.replyFrameTo:SetMaxLetters(12) vQueueFrame.replyFrameTo:SetWidth(vQueueFrame.replyFrame:GetWidth() * 4/5 - 10) vQueueFrame.replyFrameTo:SetHeight(20) vQueueFrame.replyFrameTo:SetBackdrop(vQueueFrameBackdrop) vQueueFrame.replyFrameTo:SetBackdropColor(25/255, 25/255, 25/255, 1.0) vQueueFrame.replyFrameTo:SetTextInsets(5, 0, 0, 0) vQueueFrame.replyFrameMsg = CreateFrame("EditBox", nil, vQueueFrame.replyFrame ) vQueueFrame.replyFrameMsg:SetPoint("TOPLEFT", vQueueFrame.replyFrame, "TOPLEFT", 5, -30) vQueueFrame.replyFrameMsg:SetPoint("BOTTOMRIGHT", vQueueFrame.replyFrame, "BOTTOMRIGHT", -5, 20) vQueueFrame.replyFrameMsg:SetAutoFocus(false) vQueueFrame.replyFrameMsg:SetFont("Fonts\\FRIZQT__.TTF", 10) vQueueFrame.replyFrameMsg:SetTextColor(vQueueColors["WHITE"][1], vQueueColors["WHITE"][2], vQueueColors["WHITE"][3]) vQueueFrame.replyFrameMsg:SetMaxLetters(200) vQueueFrame.replyFrameMsg:SetBackdrop(vQueueFrameBackdrop) vQueueFrame.replyFrameMsg:SetBackdropColor(25/255, 25/255, 25/255, 1.0) vQueueFrame.replyFrameMsg:SetMultiLine(true) vQueueFrame.replyFrameMsg:SetTextInsets(5, 5, 5, 0) vQueueFrame.replyFrameSend = vQueue_newButton(vQueueFrame.replyFrame, 10) vQueueFrame.replyFrameSend:SetPoint("BOTTOMRIGHT", vQueueFrame.replyFrame, "BOTTOMRIGHT", -8, 8) vQueueFrame.replyFrameSend:SetText("Send") vQueueFrame.replyFrameSend:SetWidth(vQueueFrame.replyFrameSend:GetTextWidth()+5) vQueueFrame.replyFrameSend:SetScript("OnClick", function() addToSet(chatQueue, vQueueFrame.replyFrameMsg:GetText() .. "-WHISPER-" .. vQueueFrame.replyFrameTo:GetText()) this:GetParent():Hide() end) vQueueFrame.replyFrameClose = vQueue_newButton(vQueueFrame.replyFrame, 10) vQueueFrame.replyFrameClose:SetPoint("TOPRIGHT", vQueueFrame.replyFrame, "TOPRIGHT", -8, -8) vQueueFrame.replyFrameClose:SetText("Close") vQueueFrame.replyFrameClose:SetWidth(vQueueFrame.replyFrameClose:GetTextWidth()+5) vQueueFrame.replyFrameClose:SetScript("OnClick", function() this:GetParent():Hide() end) vQueueFrame.replyFrame:Hide() vQueueFrame.optionsFrameTopString = vQueueFrame.optionsFrame:CreateFontString(nil) vQueueFrame.optionsFrameTopString:SetFont("Fonts\\FRIZQT__.TTF", 10) vQueueFrame.optionsFrameTopString:SetText("vQueue v" .. GetAddOnMetadata("vQueue", "Version") .." Options") vQueueFrame.optionsFrameTopString:SetTextColor(vQueueColors["YELLOW"][1], vQueueColors["YELLOW"][2], vQueueColors["YELLOW"][3]) vQueueFrame.optionsFrameTopString:SetWidth(vQueueFrame.optionsFrameTopString:GetStringWidth()) vQueueFrame.optionsFrameTopString:SetHeight(8) vQueueFrame.optionsFrameTopString:SetPoint("TOP", vQueueFrame.optionsFrame, "TOP", 0, -7) vQueueFrame.filterCheck = CreateFrame("CheckButton", "optionsFilterCheck", vQueueFrame.optionsFrame, "UICheckButtonTemplate"); vQueueFrame.filterCheck:SetWidth(18) vQueueFrame.filterCheck:SetHeight(18) getglobal(vQueueFrame.filterCheck:GetName() .."Text"):SetText("Hide channel messages") vQueueFrame.filterCheck:SetPoint("TOPLEFT", vQueueFrame.optionsFrame, "TOPLEFT", 5, -15) vQueueFrame.filterCheck:SetChecked(vQueueOptions["filter"]) vQueueFrame.filterCheck:SetScript("OnClick", function() if this:GetChecked() then vQueueFrame.filterCheckGeneral:Enable() vQueueFrame.filterCheckTrade:Enable() vQueueFrame.filterCheckLFG:Enable() vQueueFrame.filterCheckWorld:Enable() vQueueFrame.filterCheckOnlyFilter:Enable() vQueueOptions["filter"] = true elseif not this:GetChecked() then vQueueFrame.filterCheckGeneral:Disable() vQueueFrame.filterCheckTrade:Disable() vQueueFrame.filterCheckLFG:Disable() vQueueFrame.filterCheckWorld:Disable() vQueueFrame.filterCheckOnlyFilter:Disable() vQueueOptions["filter"] = false end end) vQueueFrame.filterCheckGeneral = CreateFrame("CheckButton", "optionsFilterCheckGeneral", vQueueFrame.optionsFrame, "UICheckButtonTemplate"); vQueueFrame.filterCheckGeneral:SetWidth(16) vQueueFrame.filterCheckGeneral:SetHeight(16) getglobal(vQueueFrame.filterCheckGeneral:GetName() .."Text"):SetText("General") getglobal(vQueueFrame.filterCheckGeneral:GetName() .."Text"):SetFont("Fonts\\FRIZQT__.TTF", 8) vQueueFrame.filterCheckGeneral:SetPoint("TOPLEFT", vQueueFrame.optionsFrame, "TOPLEFT", 15, -30) if not vQueueOptions["filter"] then vQueueFrame.filterCheckGeneral:Disable() end vQueueFrame.filterCheckGeneral:SetChecked(vQueueOptions["general"]) vQueueFrame.filterCheckGeneral:SetScript("OnClick", function() if this:GetChecked() then vQueueOptions["general"] = true elseif not this:GetChecked() then vQueueOptions["general"] = false end end) vQueueFrame.filterCheckTrade = CreateFrame("CheckButton", "optionsFilterCheckTrade", vQueueFrame.optionsFrame, "UICheckButtonTemplate"); vQueueFrame.filterCheckTrade:SetWidth(16) vQueueFrame.filterCheckTrade:SetHeight(16) getglobal(vQueueFrame.filterCheckTrade:GetName() .."Text"):SetText("Trade") getglobal(vQueueFrame.filterCheckTrade:GetName() .."Text"):SetFont("Fonts\\FRIZQT__.TTF", 8) vQueueFrame.filterCheckTrade:SetPoint("TOPLEFT", vQueueFrame.optionsFrame, "TOPLEFT", 15, -42) if not vQueueOptions["filter"] then vQueueFrame.filterCheckTrade:Disable() end vQueueFrame.filterCheckTrade:SetChecked(vQueueOptions["trade"]) vQueueFrame.filterCheckTrade:SetScript("OnClick", function() if this:GetChecked() then vQueueOptions["trade"] = true elseif not this:GetChecked() then vQueueOptions["trade"] = false end end) vQueueFrame.filterCheckLFG = CreateFrame("CheckButton", "optionsFilterCheckLFG", vQueueFrame.optionsFrame, "UICheckButtonTemplate"); vQueueFrame.filterCheckLFG:SetWidth(16) vQueueFrame.filterCheckLFG:SetHeight(16) getglobal(vQueueFrame.filterCheckLFG:GetName() .."Text"):SetText("Looking For Group") getglobal(vQueueFrame.filterCheckLFG:GetName() .."Text"):SetFont("Fonts\\FRIZQT__.TTF", 8) vQueueFrame.filterCheckLFG:SetPoint("TOPLEFT", vQueueFrame.optionsFrame, "TOPLEFT", 15, -54) if not vQueueOptions["filter"] then vQueueFrame.filterCheckLFG:Disable() end vQueueFrame.filterCheckLFG:SetChecked(vQueueOptions["lfg"]) vQueueFrame.filterCheckLFG:SetScript("OnClick", function() if this:GetChecked() then vQueueOptions["lfg"] = true elseif not this:GetChecked() then vQueueOptions["lfg"] = false end end) vQueueFrame.filterCheckWorld = CreateFrame("CheckButton", "optionsFilterCheckWorld", vQueueFrame.optionsFrame, "UICheckButtonTemplate"); vQueueFrame.filterCheckWorld:SetWidth(16) vQueueFrame.filterCheckWorld:SetHeight(16) getglobal(vQueueFrame.filterCheckWorld:GetName() .."Text"):SetText("World") getglobal(vQueueFrame.filterCheckWorld:GetName() .."Text"):SetFont("Fonts\\FRIZQT__.TTF", 8) vQueueFrame.filterCheckWorld:SetPoint("TOPLEFT", vQueueFrame.optionsFrame, "TOPLEFT", 15, -66) if not vQueueOptions["filter"] then vQueueFrame.filterCheckWorld:Disable() end vQueueFrame.filterCheckWorld:SetChecked(vQueueOptions["world"]) vQueueFrame.filterCheckWorld:SetScript("OnClick", function() if this:GetChecked() then vQueueOptions["world"] = true elseif not this:GetChecked() then vQueueOptions["world"] = false end end) vQueueFrame.filterCheckOnlyFilter = CreateFrame("CheckButton", "optionsFilterCheckOnlyLfg", vQueueFrame.optionsFrame, "UICheckButtonTemplate"); vQueueFrame.filterCheckOnlyFilter:SetWidth(16) vQueueFrame.filterCheckOnlyFilter:SetHeight(16) getglobal(vQueueFrame.filterCheckOnlyFilter:GetName() .."Text"):SetText("Only hide LFG/LFM messages") vQueueFrame.filterCheckOnlyFilter:SetPoint("TOPLEFT", vQueueFrame.optionsFrame, "TOPLEFT", 15, -80) if not vQueueOptions["filter"] then vQueueFrame.filterCheckOnlyFilter:Disable() end vQueueFrame.filterCheckOnlyFilter:SetChecked(vQueueOptions["onlylfg"]) vQueueFrame.filterCheckOnlyFilter:SetScript("OnClick", function() if this:GetChecked() then vQueueOptions["onlylfg"] = true elseif not this:GetChecked() then vQueueOptions["onlylfg"] = false end end) vQueueFrame.optionsFrameClose = vQueue_newButton(vQueueFrame.optionsFrame, 10) vQueueFrame.optionsFrameClose:SetPoint("BOTTOM", vQueueFrame.optionsFrame, "BOTTOM", 0, 5) vQueueFrame.optionsFrameClose:SetText("Save") vQueueFrame.optionsFrameClose:SetWidth(vQueueFrame.optionsFrameClose:GetTextWidth()+10) vQueueFrame.optionsFrameClose:SetScript("OnClick", function() this:GetParent():Hide() end) vQueueFrame.optionsFrameFix = vQueue_newButton(vQueueFrame.optionsFrame, 10) vQueueFrame.optionsFrameFix:SetPoint("TOPLEFT", vQueueFrame.filterCheckOnlyFilter, "BOTTOMLEFT", 0, 0) vQueueFrame.optionsFrameFix:SetText("Fix channel order") vQueueFrame.optionsFrameFix:SetWidth(vQueueFrame.optionsFrameFix:GetTextWidth()+15) vQueueFrame.optionsFrameFix:SetScript("OnClick", function() LeaveChannelByName(channelName) fixingChat = true whoRequestTimer = 0 idleMessage = 0 for i = 1, 10 do id, name = GetChannelName(i) if (name ~= nil) then LeaveChannelByName(name) end end end) --Role Icons for group creation vQueueFrame.hostlistHostHealer = CreateFrame("Button", "vQueueInfoButton", vQueueFrame.hostlistNameField) vQueueFrame.hostlistHostHealer:SetWidth(32) vQueueFrame.hostlistHostHealer:SetHeight(32) vQueueFrame.hostlistHostHealer:SetPoint("TOPRIGHT", vQueueFrame.hostlistNameField, "BOTTOMRIGHT", -32, -5) vQueueFrame.hostlistHostHealer:SetFrameLevel(4) vQueueFrame.hostlistHostHealerTex = vQueueFrame.hostlistHostHealer:CreateTexture(nil, "ARTWORK") vQueueFrame.hostlistHostHealerTex:SetAllPoints() vQueueFrame.hostlistHostHealerTex:SetTexture("Interface\\AddOns\\vQueue\\media\\Healer") vQueueFrame.hostlistHostHealerTex:SetWidth(vQueueFrame.hostlistHostHealer:GetWidth()) vQueueFrame.hostlistHostHealerTex:SetHeight(vQueueFrame.hostlistHostHealer:GetHeight()) vQueueFrame.hostlistHostHealCheck = vQueueFrame.hostlistHostHealer:CreateTexture(nil, "OVERLAY") vQueueFrame.hostlistHostHealCheck:SetTexture("Interface\\BUTTONS\\UI-CheckBox-Check") vQueueFrame.hostlistHostHealCheck:SetVertexColor(0.1,0.8,0.1) vQueueFrame.hostlistHostHealCheck:SetAllPoints() healerSelected = true vQueueFrame.hostlistHostHealer:SetScript("OnMouseDown", function() healerSelected = not healerSelected if healerSelected then vQueueFrame.hostlistHostHealCheck:Show() else vQueueFrame.hostlistHostHealCheck:Hide() end end) vQueueFrame.hostlistHostHealer:SetScript("OnEnter", function() vQueueFrame.hostlistHostHealerTex:SetVertexColor(1, 1, 0) end) vQueueFrame.hostlistHostHealer:SetScript("OnLeave", function() vQueueFrame.hostlistHostHealerTex:SetVertexColor(1, 1, 1) end) vQueueFrame.hostlistHostDamage = CreateFrame("Button", "vQueueInfoButton", vQueueFrame.hostlistNameField) vQueueFrame.hostlistHostDamage:SetWidth(32) vQueueFrame.hostlistHostDamage:SetHeight(32) vQueueFrame.hostlistHostDamage:SetFrameLevel(4) vQueueFrame.hostlistHostDamage:SetPoint("TOPRIGHT", vQueueFrame.hostlistNameField, "BOTTOMRIGHT", 0, -5) vQueueFrame.hostlistHostDamageTex = vQueueFrame.hostlistHostDamage:CreateTexture(nil, "ARTWORK") vQueueFrame.hostlistHostDamageTex:SetAllPoints() vQueueFrame.hostlistHostDamageTex:SetTexture("Interface\\AddOns\\vQueue\\media\\Damage") vQueueFrame.hostlistHostDamageTex:SetWidth(vQueueFrame.hostlistHostDamage:GetWidth()) vQueueFrame.hostlistHostDamageTex:SetHeight(vQueueFrame.hostlistHostDamage:GetHeight()) vQueueFrame.hostlistHostDamageCheck = vQueueFrame.hostlistHostDamage:CreateTexture(nil, "OVERLAY") vQueueFrame.hostlistHostDamageCheck:SetTexture("Interface\\BUTTONS\\UI-CheckBox-Check") vQueueFrame.hostlistHostDamageCheck:SetVertexColor(0.1,0.8,0.1) vQueueFrame.hostlistHostDamageCheck:SetAllPoints() damageSelected = true vQueueFrame.hostlistHostDamage:SetScript("OnMouseDown", function() damageSelected = not damageSelected if damageSelected then vQueueFrame.hostlistHostDamageCheck:Show() else vQueueFrame.hostlistHostDamageCheck:Hide() end end) vQueueFrame.hostlistHostDamage:SetScript("OnEnter", function() vQueueFrame.hostlistHostDamageTex:SetVertexColor(1, 1, 0) end) vQueueFrame.hostlistHostDamage:SetScript("OnLeave", function() vQueueFrame.hostlistHostDamageTex:SetVertexColor(1, 1, 1) end) vQueueFrame.hostlistHostTank = CreateFrame("Button", "vQueueInfoButton", vQueueFrame.hostlistNameField) vQueueFrame.hostlistHostTank:SetWidth(32) vQueueFrame.hostlistHostTank:SetHeight(32) vQueueFrame.hostlistHostTank:SetFrameLevel(4) vQueueFrame.hostlistHostTank:SetPoint("TOPRIGHT", vQueueFrame.hostlistNameField, "BOTTOMRIGHT", -64, -5) vQueueFrame.hostlistHostTankTex = vQueueFrame.hostlistHostTank:CreateTexture(nil, "ARTWORK") vQueueFrame.hostlistHostTankTex:SetAllPoints() vQueueFrame.hostlistHostTankTex:SetTexture("Interface\\AddOns\\vQueue\\media\\Tank") vQueueFrame.hostlistHostTankTex:SetWidth(vQueueFrame.hostlistHostTank:GetWidth()) vQueueFrame.hostlistHostTankTex:SetHeight(vQueueFrame.hostlistHostTank:GetHeight()) vQueueFrame.hostlistHostTankCheck = vQueueFrame.hostlistHostTank:CreateTexture(nil, "OVERLAY") vQueueFrame.hostlistHostTankCheck:SetTexture("Interface\\BUTTONS\\UI-CheckBox-Check") vQueueFrame.hostlistHostTankCheck:SetVertexColor(0.1,0.8,0.1) vQueueFrame.hostlistHostTankCheck:SetAllPoints() tankSelected = true vQueueFrame.hostlistHostTank:SetScript("OnMouseDown", function() tankSelected = not tankSelected if tankSelected then vQueueFrame.hostlistHostTankCheck:Show() else vQueueFrame.hostlistHostTankCheck:Hide() end end) vQueueFrame.hostlistHostTank:SetScript("OnEnter", function() vQueueFrame.hostlistHostTankTex:SetVertexColor(1, 1, 0) end) vQueueFrame.hostlistHostTank:SetScript("OnLeave", function() vQueueFrame.hostlistHostTankTex:SetVertexColor(1, 1, 1) end) vQueueFrame.hostlistNeededRolesText = CreateFrame("Button", nil, vQueueFrame.hostlistHostTank ) vQueueFrame.hostlistNeededRolesText:SetPoint("RIGHT", vQueueFrame.hostlistHostTank , "LEFT", 0, 2) vQueueFrame.hostlistNeededRolesText:SetFont("Fonts\\FRIZQT__.TTF", 8) vQueueFrame.hostlistNeededRolesText:SetText("Needed roles") vQueueFrame.hostlistNeededRolesText:SetTextColor(vQueueColors["YELLOW"][1], vQueueColors["YELLOW"][2], vQueueColors["YELLOW"][3]) vQueueFrame.hostlistNeededRolesText:SetPushedTextOffset(0,0) vQueueFrame.hostlistNeededRolesText:SetWidth(vQueueFrame.hostlistNeededRolesText:GetTextWidth()) vQueueFrame.hostlistNeededRolesText:SetHeight(vQueueFrame.hostlistNeededRolesText:GetTextHeight()) --------------------------------------------------- vQueueFrame.hostlistCancelButton = vQueue_newButton(vQueueFrame.hostlist, 10) vQueueFrame.hostlistCancelButton:SetPoint("CENTER", vQueueFrame.hostlist, "CENTER", -8, -130) vQueueFrame.hostlistCancelButton:SetText("Cancel") vQueueFrame.hostlistCancelButton:SetWidth(vQueueFrame.hostlistCancelButton:GetTextWidth()+20) vQueueFrame.hostlistCancelButton:SetFrameLevel(4) vQueueFrame.hostlistCancelButton:SetScript("OnClick", function() isWaitListShown = false if selectedQuery == "waitlist" then selectedQuery = hostedCategory end vQueue_ShowGroups(selectedQuery, selectedQuery) vQueueFrame.hostTitleFindName:Show() vQueueFrame.hostTitleFindLeader:Show() vQueueFrame.hostTitleFindLevel:Show() vQueueFrame.hostTitleFindSize:Show() vQueueFrame.hostTitleFindRoles:Show() vQueueFrame.hostlistLevelField:Hide() vQueueFrame.hostlistNameField:Hide() vQueueFrame.hostlistCreateButton:Hide() vQueueFrame.hostlistHostButton:Show() this:Hide() end) vQueueFrame.hostlistCancelButton:Hide() vQueueFrame.hostlistCreateButton = vQueue_newButton(vQueueFrame.hostlist, 14) vQueueFrame.hostlistCreateButton:SetPoint("CENTER", vQueueFrame.hostlist, "CENTER", -8, -100) vQueueFrame.hostlistCreateButton:SetText("Create group") vQueueFrame.hostlistCreateButton:SetWidth(vQueueFrame.hostlistCreateButton:GetTextWidth()+30) vQueueFrame.hostlistCreateButton:SetFrameLevel(4) vQueueFrame.hostlistCreateButton:SetScript("OnClick", function() if vQueueFrame.hostlistNameField:GetText() ~= "" and vQueueFrame.hostlistLevelField:GetText() ~= "" then if tonumber(vQueueFrame.hostlistLevelField:GetText()) < 1 then vQueueFrame.hostlistLevelField:SetText("1") end if tonumber(vQueueFrame.hostlistLevelField:GetText()) > 60 then vQueueFrame.hostlistLevelField:SetText("60") end local name = vQueueFrame.hostlistNameField:GetText() local strippedStr = "" for i=1, string.len(name) do local add = true if string.sub(name, i, i) == ":" or string.sub(name, i, i) == "-" then add = false end if add then strippedStr = strippedStr .. string.sub(name, i, i) end end hostOptions[0] = strippedStr hostOptions[1] = vQueueFrame.hostlistLevelField:GetText() hostOptions[2] = healerSelected hostOptions[3] = damageSelected hostOptions[4] = tankSelected vQueueFrame.topsectionHostName:SetWidth(400) vQueueFrame.topsectionHostName:SetText(hostOptions[0]) vQueueFrame.topsectionHostName:SetWidth(vQueueFrame.topsectionHostName:GetTextWidth()) vQueueFrame.topsectionMinLvl:SetWidth(100) vQueueFrame.topsectionMinLvl:SetText(hostOptions[1] .. "+") vQueueFrame.topsectionMinLvl:SetWidth(vQueueFrame.topsectionMinLvl:GetStringWidth()) if healerSelected then vQueueFrame.topsectionHostHeal:Show() else vQueueFrame.topsectionHostHeal:Hide() end if damageSelected then vQueueFrame.topsectionHostDamage:Show() else vQueueFrame.topsectionHostDamage:Hide() end if tankSelected then vQueueFrame.topsectionHostTank:Show() else vQueueFrame.topsectionHostTank:Hide() end vQueueFrame.hostlistLevelField:Hide() vQueueFrame.hostlistNameField:Hide() vQueueFrame.hostlistCancelButton:Hide() this:Hide() vQueueFrame.hostlistEditButton:Show() vQueueFrame.hostlistUnlistButton:Show() vQueueFrame.hostlistWaitListButton:Show() vQueueFrame.hostTitle:Show() vQueueFrame.hostTitleRole:Show() vQueueFrame.hostTitleClass:Show() vQueueFrame.hostTitleLevel:Show() vQueueFrame.topsectionHostName:Show() vQueueFrame.hostlistBotShadow:SetHeight(40) if tablelength(groups[selectedQuery]) > 16 then vQueueFrame.hostlistBotShadow:Show() else vQueueFrame.hostlistBotShadow:Hide() end if isHost then return end vQueue_SlashCommandHandler( "host " .. selectedQuery ) end end) --scrollbarhost scrollbar = CreateFrame("Slider", nil, vQueueFrame.hostlist, "UIPanelScrollBarTemplate") scrollbar:SetMinMaxValues(1, 1) scrollbar:SetValueStep(1) scrollbar.scrollStep = 1 scrollbar:SetValue(0) scrollbar:EnableMouse(true) scrollbar:EnableMouseWheel(true) scrollbar:SetWidth(16) scrollbar:SetHeight((vQueueFrame.hostlist:GetHeight()* 4/5) - 35) scrollbar:SetPoint("BOTTOMLEFT", vQueueFrame.hostlist, "BOTTOMRIGHT", -16, 16) scrollbar:SetScript("OnValueChanged", function (self, value) vQueue_UpdateHostScroll(arg1) end) scrollbar:Hide() --scrollbarcategory scrollbarCat = CreateFrame("Slider", nil, vQueueFrame.catList, "UIPanelScrollBarTemplate") scrollbarCat:SetMinMaxValues(1, 10) scrollbarCat:SetValueStep(1) scrollbarCat.scrollStep = 1 scrollbarCat:SetValue(0) scrollbarCat:EnableMouse(true) scrollbarCat:EnableMouseWheel(true) scrollbarCat:SetWidth(16) scrollbarCat:SetHeight(vQueueFrame.catList:GetHeight()-32) scrollbarCat:SetPoint("BOTTOMLEFT", vQueueFrame.catList, "BOTTOMRIGHT", -16, 16) scrollbarCat:SetScript("OnValueChanged", function (self, value) vQueue_UpdateCatScroll(arg1) end) scrollbarCat:Hide() vQueueFrame.title = CreateFrame("Button", "vQueueButton", vQueueFrame.hostlist) vQueueFrame.title:ClearAllPoints() vQueueFrame.title:SetPoint("CENTER", vQueueFrame.hostlist, "TOP", 0 , 6) vQueueFrame.title:SetFont("Fonts\\FRIZQT__.TTF", 10) vQueueFrame.title:SetText("vQueue") vQueueFrame.title:SetTextColor(vQueueColors["YELLOW"][1], vQueueColors["YELLOW"][2], vQueueColors["YELLOW"][3]) vQueueFrame.title:SetPushedTextOffset(0,0) vQueueFrame.title:SetWidth(vQueueFrame.title:GetTextWidth()) vQueueFrame.title:SetHeight(20) vQueueFrame.titleCat = CreateFrame("Button", "vQueueButton", vQueueFrame.catList) vQueueFrame.titleCat:ClearAllPoints() vQueueFrame.titleCat:SetPoint("CENTER", vQueueFrame.catList, "TOP", 0 , 6) vQueueFrame.titleCat:SetFont("Fonts\\FRIZQT__.TTF", 10) vQueueFrame.titleCat:SetText("Categories") vQueueFrame.titleCat:SetTextColor(vQueueColors["YELLOW"][1], vQueueColors["YELLOW"][2], vQueueColors["YELLOW"][3]) vQueueFrame.titleCat:SetPushedTextOffset(0,0) vQueueFrame.titleCat:SetWidth(20) vQueueFrame.titleCat:SetHeight(20) DEFAULT_CHAT_FRAME:AddMessage("Loaded " .. arg1) minimapButton = CreateFrame("Button", "vQueueMap", Minimap) minimapButton:SetFrameStrata("HIGH") minimapButton:SetWidth(32) minimapButton:SetHeight(32) minimapButton:ClearAllPoints() minimapButton:SetPoint("TOPLEFT", Minimap,"TOPLEFT",54-(75*cos(MinimapPos)),(75*sin(MinimapPos))-55) minimapButton:SetHighlightTexture("Interface\\MINIMAP\\UI-Minimap-ZoomButton-Highlight", "ADD") minimapButton:RegisterForDrag("RightButton") minimapButton.texture = minimapButton:CreateTexture(nil, "BUTTON") minimapButton.texture:SetTexture("Interface\\AddOns\\vQueue\\media\\icon") minimapButton.texture:SetPoint("CENTER", minimapButton) minimapButton.texture:SetWidth(20) minimapButton.texture:SetHeight(20) minimapButton.border = minimapButton:CreateTexture(nil, "BORDER") minimapButton.border:SetTexture("Interface\\MINIMAP\\MiniMap-TrackingBorder") minimapButton.border:SetPoint("TOPLEFT", minimapButton.texture, -6, 5) minimapButton.border:SetWidth(52) minimapButton.border:SetHeight(52) minimapButton.notifyText = minimapButton:CreateTexture(nil, "OVERLAY") minimapButton.notifyText:SetTexture("Interface\\MINIMAP\\UI-Minimap-ZoomButton-Highlight") minimapButton.notifyText:SetBlendMode("ADD") minimapButton.notifyText:SetAllPoints() minimapButton.notifyText:Hide() minimapButton:SetScript("OnMouseDown", function() point, relativeTo, relativePoint, xOffset, yOffset = minimapButton.texture:GetPoint(1) minimapButton.texture:SetPoint(point, relativeTo, relativePoint, xOffset + 2, yOffset - 2) end); minimapButton:SetScript("OnLeave", function(self, button) MinimapTool:Hide() minimapButton.notifyText:Hide() minimapButton.texture:SetPoint("CENTER", minimapButton) end); minimapButton:SetScript("OnMouseUp", function() if arg1 == "LeftButton" then if vQueueFrameShown then vQueueFrame:Hide() vQueueFrame.catList:Hide() vQueueFrame.hostlist:Hide() vQueueFrameShown = false else vQueueFrame:Show() vQueueFrame.catList:Show() vQueueFrame.hostlist:Show() vQueueFrameShown = true end end minimapButton.texture:SetPoint("CENTER", minimapButton) end); minimapButton:SetScript("OnDragStart", function() miniDrag = true end) minimapButton:SetScript("OnDragStop", function() miniDrag = false end) minimapButton:SetScript("OnUpdate", function() if miniDrag then local xpos,ypos = GetCursorPosition() local xmin,ymin = Minimap:GetLeft(), Minimap:GetBottom() xpos = xmin-xpos/UIParent:GetScale()+70 ypos = ypos/UIParent:GetScale()-ymin-70 MinimapPos = math.deg(math.atan2(ypos,xpos)) if (MinimapPos < 0) then MinimapPos = MinimapPos + 360 end this:SetPoint("TOPLEFT", Minimap,"TOPLEFT",54-(75*cos(MinimapPos)),(75*sin(MinimapPos))-55) end end) CreateFrame( "GameTooltip", "MinimapTool", nil, "GameTooltipTemplate" ); -- Tooltip name cannot be nil minimapButton:SetScript("OnEnter", function() if isHost then MinimapTool:SetOwner( this, "ANCHOR_CURSOR" ); MinimapTool:AddLine(tablelength(groups["waitlist"]) .. " player(s) in your wait list.", 1, 1, 1, 1) MinimapTool:Show() end end) MinimapTool:SetScript("OnUpdate", function() if this:IsShown() then this:Hide() MinimapTool:SetOwner( minimapButton, "ANCHOR_CURSOR" ); MinimapTool:AddLine(tablelength(groups["waitlist"]) .. " player(s) in your wait list.", 1, 1, 1, 1) MinimapTool:Show() end end) vQueueFrame.topsectiontitle = CreateFrame("Button", "vQueueButton", vQueueFrame.hostlistTopSection) vQueueFrame.topsectiontitle:ClearAllPoints() vQueueFrame.topsectiontitle:SetPoint("LEFT", vQueueFrame.hostlistTopSection, "LEFT", 5, vQueueFrame.hostlistTopSection:GetHeight() * 1/6) vQueueFrame.topsectiontitle:SetFont("Fonts\\MORPHEUS.ttf", 24, "OUTLINE") vQueueFrame.topsectiontitle:SetText("<-- Select a catergory") vQueueFrame.topsectiontitle:SetTextColor(vQueueColors["WHITE"][1], vQueueColors["WHITE"][2], vQueueColors["WHITE"][3]) vQueueFrame.topsectiontitle:EnableMouse(false) vQueueFrame.topsectiontitle:SetFrameLevel(3) vQueueFrame.topsectiontitle:SetWidth(vQueueFrame.topsectiontitle:GetTextWidth()) vQueueFrame.topsectiontitle:SetHeight(vQueueFrame.topsectiontitle:GetTextHeight()) vQueueFrame.topsectionHostName = CreateFrame("Button", "vQueueButton", vQueueFrame.topsectiontitle) vQueueFrame.topsectionHostName:SetPoint("TOPLEFT", vQueueFrame.topsectiontitle, "BOTTOMLEFT", 0, -3) vQueueFrame.topsectionHostName:SetFont("Fonts\\FRIZQT__.TTF", 8, "OUTLINE") vQueueFrame.topsectionHostName:SetText("") vQueueFrame.topsectionHostName:SetTextColor(vQueueColors["YELLOW"][1], vQueueColors["YELLOW"][2], vQueueColors["YELLOW"][3]) vQueueFrame.topsectionHostName:EnableMouse(false) vQueueFrame.topsectionHostName:SetWidth(vQueueFrame.topsectionHostName:GetTextWidth()) vQueueFrame.topsectionHostName:SetHeight(vQueueFrame.topsectionHostName:GetTextHeight()) vQueueFrame.topsectionHostName:Hide() vQueueFrame.topsectionMinLvl = vQueueFrame.topsectionHostName:CreateFontString(nil, "ARTWORK") vQueueFrame.topsectionMinLvl:SetPoint("TOPLEFT", vQueueFrame.topsectionHostName, "BOTTOMLEFT", -2, -3) vQueueFrame.topsectionMinLvl:SetFont("Fonts\\FRIZQT__.TTF", 8, "OUTLINE") vQueueFrame.topsectionMinLvl:SetText("17+") vQueueFrame.topsectionMinLvl:SetTextColor(vQueueColors["YELLOW"][1], vQueueColors["YELLOW"][2], vQueueColors["YELLOW"][3]) vQueueFrame.topsectionMinLvl:SetWidth(vQueueFrame.topsectionMinLvl:GetStringWidth()) vQueueFrame.topsectionMinLvl:SetHeight(10) vQueueFrame.topsectionHostHeal = vQueueFrame.topsectionHostName:CreateTexture(nil, "ARTWORK") vQueueFrame.topsectionHostHeal:SetPoint("LEFT", vQueueFrame.topsectionMinLvl, "RIGHT", 12, 0) vQueueFrame.topsectionHostHeal:SetTexture("Interface\\AddOns\\vQueue\\media\\Healer") vQueueFrame.topsectionHostHeal:SetWidth(12) vQueueFrame.topsectionHostHeal:SetHeight(12) vQueueFrame.topsectionHostDamage = vQueueFrame.topsectionHostName:CreateTexture(nil, "ARTWORK") vQueueFrame.topsectionHostDamage:SetPoint("LEFT", vQueueFrame.topsectionMinLvl, "RIGHT", 24, 0) vQueueFrame.topsectionHostDamage:SetTexture("Interface\\AddOns\\vQueue\\media\\Damage") vQueueFrame.topsectionHostDamage:SetWidth(12) vQueueFrame.topsectionHostDamage:SetHeight(12) vQueueFrame.topsectionHostTank = vQueueFrame.topsectionHostName:CreateTexture(nil, "ARTWORK") vQueueFrame.topsectionHostTank:SetPoint("LEFT", vQueueFrame.topsectionMinLvl, "RIGHT", 0, 0) vQueueFrame.topsectionHostTank:SetTexture("Interface\\AddOns\\vQueue\\media\\Tank") vQueueFrame.topsectionHostTank:SetWidth(12) vQueueFrame.topsectionHostTank:SetHeight(12) vQueueFrame.catListHighlight = CreateFrame("Frame", nil, nil) vQueueFrame.catListHighlight:SetPoint("CENTER", vQueueFrame.catList, "CENTER", 0, 2) vQueueFrame.catListHighlight:SetWidth(vQueueFrame.catList:GetWidth()-4) vQueueFrame.catListHighlight:SetHeight(10) vQueueFrame.catListHighlightTex = vQueueFrame.catListHighlight:CreateTexture(nil, "ARTWORK") vQueueFrame.catListHighlightTex:SetTexture(1, 1, 0, 0.4) vQueueFrame.catListHighlightTex:SetGradientAlpha("HORIZONTAL", 1, 1, 0, 0.5, 1, 1, 0, 0) vQueueFrame.catListHighlightTex:SetAllPoints() vQueueFrame.catListHighlight:Hide() vQueue_createCategories("Dungeons") vQueue_createCategories("Battlegrounds") vQueue_createCategories("Raids") vQueue_createCategories("Quest Groups") vQueue_createCategories("Miscellaneous") minimapButton:Show() vQueueFrame:Hide() vQueueFrame.catList:Hide() vQueueFrame.hostlist:Hide() vQueueFrame.hostlistTank:Hide() vQueueFrame.hostlistHeal:Hide() vQueueFrame.hostlistDps:Hide() vQueueFrame.hostlistRoleText:Hide() vQueueFrame.hostlistLevelField:Hide() vQueueFrame.hostlistNameField:Hide() vQueueFrame.hostlistCreateButton:Hide() vQueueFrame.hostlistHostButton:Hide() end if event == "CHAT_MSG_CHANNEL" then if string.lower(arg9) ~= string.lower(channelName) then local puncString = filterPunctuation(arg1) for kLfm, vLfm in pairs(getglobal("LFMARGS")) do if Wholefind(puncString, vLfm) > 0 then local usedthis = false for kCat, kVal in pairs(getglobal("CATARGS")) do for kkCat, kkVal in pairs(kVal) do if Wholefind(puncString, kkVal) > 0 then usedthis = true local healerRole = "" local damageRole = "" local tankRole = "" for kHeal, vHeal in pairs(getglobal("ROLEARGS")["Healer"]) do if Wholefind(puncString, vHeal) > 0 then healerRole = "Healer" end end for kDps, vDps in pairs(getglobal("ROLEARGS")["Damage"]) do if Wholefind(puncString, vDps) > 0 then damageRole = "Damage" end end for kTank, vTank in pairs(getglobal("ROLEARGS")["Tank"]) do if Wholefind(puncString, vTank) > 0 then tankRole = "Tank" end end if healerRole == "" and tankRole == "" and damageRole == "" then healerRole = "Healer" damageRole = "Damage" tankRole = "Tank" end local strippedStr = "" for i=1, string.len(arg1) do local add = true if string.sub(arg1, i, i) == ":" then add = false end if add then strippedStr = strippedStr .. string.sub(arg1, i, i) end end leaderMessages[arg2] = strippedStr .. ":" .. kCat .. ":" .. tostring(GetTime()) if kCat ~= "dm" then vQueue_addToGroup(kCat, "(Mouseover to see chat message)" .. ":" .. arg2 .. ":" .. getglobal("MINLVLS")[kCat] .. ":" .. "?" .. ":" .. healerRole .. ":" .. damageRole .. ":" .. tankRole) end if kCat == 'dm' then if not setContains(whoRequestList, arg2) then addToSet(whoRequestList, arg2) end end refreshCatList(kCat) break end end end --if not usedthis then --DEFAULT_CHAT_FRAME:AddMessage("Added: " .. puncString) --table.insert(notCaught, tablelength(notCaught), puncString) --end end end if isHost then for kLfm, vLfm in pairs(getglobal("LFGARGS")) do if Wholefind(puncString, vLfm) > 0 then for kCat, kVal in pairs(getglobal("CATARGS")) do for kkCat, kkVal in pairs(kVal) do for groupindex = 1,MAX_PARTY_MEMBERS do if UnitName("party" .. tostring(groupindex)) == arg2 then return end end if Wholefind(puncString, kkVal) > 0 and isHost and hostedCategory == kCat then local exists = false local playerRole = "" for kHeal, vHeal in pairs(getglobal("ROLEARGS")["Healer"]) do if Wholefind(puncString, vHeal) > 0 then playerRole = "Healer" end end for kDps, vDps in pairs(getglobal("ROLEARGS")["Damage"]) do if Wholefind(puncString, vDps) > 0 then playerRole = "Damage" end end for kTank, vTank in pairs(getglobal("ROLEARGS")["Tank"]) do if Wholefind(puncString, vTank) > 0 then playerRole = "Tank" end end if playerRole == "" then playerRole = "Damage" end if not setContains(whoRequestList, arg2) then addToSet(whoRequestList, arg2) end local strippedStr = "" for i=1, string.len(arg1) do local add = true if string.sub(arg1, i, i) == ":" then add = false end if add then strippedStr = strippedStr .. string.sub(arg1, i, i) end end playerMessages[arg2] = strippedStr .. ":" .. GetTime() vQueue_addToWaitList(arg2 .. ":" .. "..." .. ":" .. "..." .. ":" .. playerRole) break end end end end end end end if string.lower(arg9) == string.lower(channelName) then local vQueueArgs = {} if arg1 ~= nil then vQueueArgs = split(arg1, "\%s") end if vQueueArgs[1] == "vqgroup" and vQueueArgs[2] ~= nil then local name = split(arg1, "\:") local healerRole = "" local damageRole = "" local tankRole = "" if vQueueArgs[5] == "true" then healerRole = "Healer" end if vQueueArgs[6] == "true" then damageRole = "Damage" end if vQueueArgs[7] == "true" then tankRole = "Tank" end if tonumber(vQueueArgs[8]) == 0 and setContains(waitingList, arg2) then removeFromSet(waitingList, arg2) elseif tonumber(vQueueArgs[8]) == 1 and not setContains(waitingList, arg2) then addToSet(waitingList, arg2) end local strippedStr = "" for i=1, string.len(name[2]) do local add = true if string.sub(name[2], i, i) == ":" or string.sub(name[2], i, i) == "-" then add = false end if add then strippedStr = strippedStr .. string.sub(name[2], i, i) end end leaderMessages[arg2] = strippedStr .. ":" .. vQueueArgs[2] .. ":" .. GetTime() vQueue_addToGroup(vQueueArgs[2], strippedStr .. ":" .. arg2 .. ":" .. vQueueArgs[3] .. ":" .. vQueueArgs[4] .. ":" .. healerRole .. ":" .. damageRole .. ":" .. tankRole) refreshCatList(vQueueArgs[2]) end end end if event == "WHO_LIST_UPDATE" then vQueue_WhoSorting() if tablelength(whoRequestList) > 0 then for i=1, GetNumWhoResults() do name, guild, level, race, class, zone, classFileName, sex = GetWhoInfo(i) if groups["waitlist"][name] ~= nil then local gname, gbg, glevel, gclass, grole = groups["waitlist"][name]:GetRegions() glevel:SetWidth(100) glevel:SetText(tostring(level)) glevel:SetWidth(gclass:GetStringWidth()) local diffColor = getDifficultyColor(tonumber(level), UnitLevel("player")) glevel:SetTextColor(diffColor[1], diffColor[2], diffColor[3]) gclass:SetWidth(100) gclass:SetText(class) local classColor = getClassColor(class) gclass:SetTextColor(classColor[1], classColor[2], classColor[3]) gclass:SetWidth(gclass:GetStringWidth()) end end removeFromSet(whoRequestList, name) end SetWhoToUI(0) end if event == "CHAT_MSG_WHISPER" then local args = {} if arg1 ~= nil then args = split(arg1, "\%s") end if next(args) == nil then return end -- Group request info from players if args[1] == "vqrequest" and isHost then for groupindex = 1,MAX_PARTY_MEMBERS do if UnitName("party" .. tostring(groupindex)) == arg2 then return end end vQueue_addToWaitList(arg2 .. ":" .. args[2] .. ":" .. args[3] .. ":" .. args[4]) playerMessages[arg2] = "vqrequest" .. ":" .. GetTime() end if (args[1] == "vqaccept" or args[1] == "vqdecline") and isFinding then for key, value in pairs(groups) do if groups[key][arg2] ~= nil then if args[1] == "vqaccept" then DEFAULT_CHAT_FRAME:AddMessage("Your application to " .. arg2 .. "'s group(" .. key .. ") has been accepted.", 0.2, 1.0, 0.2) elseif args[1] == "vqdecline" then DEFAULT_CHAT_FRAME:AddMessage("Your application to " .. arg2 .. "'s group(" .. key .. ") has been declined.", 1.0, 0.2, 0.2) end removeFromSet(waitingList, arg2) groups[key][arg2]:Hide() groups[key][arg2] = nil refreshCatList(key) end end end end end function vQueue_updateCatColors() local curCat = "" for kk, vv in pairs(catListButtons) do if categories[vv:GetText()] ~= nil then curCat = vv:GetText() end if categories[vv:GetText()] == nil and curCat ~= "Battlegrounds" and curCat ~= "Miscellaneous" then local args = {} for k, v in pairs(categories) do for i, item in v do if type(item) == "string" then local tArgs = split(item, "\:") if tArgs[1] == split(vv:GetText(), "%(")[1] then args = tArgs break end end end end local diffColor = getDifficultyColor(getglobal("MINLVLS")[args[2]], UnitLevel("Player")) vv:SetTextColor(diffColor[1], diffColor[2], diffColor[3]) end end end function vQueue_createCategories(textKey) newCatButton = CreateFrame("Button", "vQueueButton", vQueueFrame.catList) newCatButton:SetFont("Fonts\\FRIZQT__.TTF", 10) newCatButton:SetText(textKey) newCatButton:SetTextColor(vQueueColors["YELLOW"][1], vQueueColors["YELLOW"][2], vQueueColors["YELLOW"][3]) newCatButton:SetWidth(newCatButton:GetTextWidth()) newCatButton:SetHeight(10) newCatButton:SetFrameLevel(1) newCatButton:EnableMouse(false) newCatButton:SetPoint("TOPLEFT", vQueueFrame.catList, "TOPLEFT", 2, tablelength(catListButtons)*-10) table.insert(catListButtons, tablelength(catListButtons), newCatButton) for k, v in pairs(categories[textKey]) do local args = {} if type(v) == "string" then args = split(v, "\:") end if type(args[1]) == "string" then local dropedItemFrame = CreateFrame("Button", "vQueueButton", vQueueFrame.catList) dropedItemFrame:SetFont("Fonts\\FRIZQT__.TTF", 8) dropedItemFrame:SetText(args[1] .. "(" .. tostring(tablelength(groups[args[2]])) .. ")") dropedItemFrame:SetHighlightTextColor(vQueueColors["YELLOW"][1], vQueueColors["YELLOW"][2], vQueueColors["YELLOW"][3]) dropedItemFrame:SetWidth(dropedItemFrame:GetTextWidth()) dropedItemFrame:SetHeight(8) dropedItemFrame:SetFrameLevel(1) dropedItemFrame:SetTextColor(vQueueColors["WHITE"][1], vQueueColors["WHITE"][2], vQueueColors["WHITE"][3]) dropedItemFrame:SetPoint("TOPLEFT", vQueueFrame.catList, "TOPLEFT", 12, tablelength(catListButtons)*-10) dropedItemFrame:SetScript("OnMouseDown", function() vQueueFrame.catListHighlight:SetParent(this) vQueueFrame.catListHighlight:SetPoint("LEFT", this, "LEFT", -11, 0) vQueueFrame.catListHighlight:Show() isWaitListShown = false vQueueFrame.hostTitle:Hide() vQueueFrame.hostTitleRole:Hide() vQueueFrame.hostTitleClass:Hide() vQueueFrame.hostTitleLevel:Hide() vQueueFrame.topsectionHostName:Hide() vQueueFrame.hostlistLevelField:Hide() vQueueFrame.hostlistNameField:Hide() vQueueFrame.hostlistCreateButton:Hide() vQueueFrame.hostlistCancelButton:Hide() vQueueFrame.hostTitleFindName:Show() vQueueFrame.hostTitleFindLeader:Show() vQueueFrame.hostTitleFindLevel:Show() vQueueFrame.hostTitleFindSize:Show() vQueueFrame.hostTitleFindRoles:Show() if not isHost then realHostedCategory = args[1] end local args = {} for k, v in pairs(categories) do for i, item in v do if type(item) == "string" then local tArgs = split(item, "\:") if tArgs[1] == split(this:GetText(), "%(")[1] then args = tArgs break end end end end if args[2] ~= nil and type(args[2]) == "string" then local prevCat = selectedQuery selectedQuery = args[2] vQueue_ShowGroups(selectedQuery, prevCat) vQueueFrame.topsectiontitle:SetText(args[1] .. "(" .. getglobal("MINLVLS")[args[2]] .. ")") vQueueFrame.topsectiontitle:SetWidth(vQueueFrame.topsectiontitle:GetTextWidth()) vQueueFrame.topsectiontitle:SetHeight(vQueueFrame.topsectiontitle:GetTextHeight()) end if not vQueueFrame.hostlistTopSectionBg:SetTexture("Interface\\AddOns\\vQueue\\media\\" .. args[2]) then vQueueFrame.hostlistTopSectionBg:SetTexture(0, 0, 0, 0) end vQueueFrame.hostlistHeal:Show() vQueueFrame.hostlistDps:Show() vQueueFrame.hostlistTank:Show() vQueueFrame.hostlistRoleText:Show() if not isHost and not vQueueFrame.hostlistCreateButton:IsShown() then vQueueFrame.hostlistHostButton:Show() else vQueueFrame.hostlistHostButton:Hide() end scrollbar:SetValue(1) scrollbar:SetMinMaxValues(1, tablelength(groups[selectedQuery])-10) end) dropedItemFrame:SetScript("OnShow", function() if vQueueFrame.catListHighlight:GetParent() and split(vQueueFrame.catListHighlight:GetParent():GetText(), "%(")[1] == split(this:GetText(), "%(")[1] then vQueueFrame.catListHighlight:SetParent(this) vQueueFrame.catListHighlight:SetPoint("LEFT", this, "LEFT", -11, 0) vQueueFrame.catListHighlight:Show() end end) table.insert(catListButtons, tablelength(catListButtons), dropedItemFrame) end end scrollbarCat:SetMinMaxValues(1, tablelength(catListButtons)-10) vQueue_UpdateCatScroll(scrollbarCat:GetValue()) end function vQueue_addToWaitList(playerinfo) local args = split(playerinfo, "\:") if groups["waitlist"][args[1]] == nil then newWaitEntry = CreateFrame("Button", "vQueueButton", vQueueFrame.hostlist) newWaitEntry:SetFont("Interface\\AddOns\\vQueue\\media\\anonpro.TTF", 10) newWaitEntry:SetText(args[1]) newWaitEntry:SetTextColor(vQueueColors["WHITE"][1], vQueueColors["WHITE"][2], vQueueColors["WHITE"][3]) newWaitEntry:SetHighlightTextColor(1, 1, 0) newWaitEntry:SetPushedTextOffset(0,0) newWaitEntry:SetWidth(newWaitEntry:GetTextWidth()) newWaitEntry:SetHeight(10) newWaitEntry:EnableMouse(true) newWaitEntry:SetFrameLevel(1) newWaitEntry:SetScript("OnEnter", function() if playerMessages[this:GetText()] ~= nil then local playerargs = split(playerMessages[this:GetText()], "\:") if Wholefind(playerargs[1], "vqrequest") > 0 then return end playerQueueToolTip:SetOwner( this, "ANCHOR_CURSOR" ); playerQueueToolTip:AddLine(playerargs[1], 1, 1, 1, 1) playerQueueToolTip:Show() end end) newWaitEntry:SetScript("OnLeave", function() playerQueueToolTip:Hide() end) newWaitEntryBg = newWaitEntry:CreateTexture(nil, "BACKGROUND") newWaitEntryBg:SetPoint("LEFT", newWaitEntry, "LEFT", 1, 0) newWaitEntryBg:SetWidth(vQueueFrame.hostlist:GetWidth()-3) newWaitEntryBg:SetHeight(15) local diffColor if args[2] ~= "..." then diffColor = getDifficultyColor(tonumber(args[2]), UnitLevel("player")) else diffColor = {vQueueColors["WHITE"][1], vQueueColors["WHITE"][2], vQueueColors["WHITE"][3]} end newWaitEntryLvl = newWaitEntry:CreateFontString(nil, "ARTWORK") newWaitEntryLvl:SetFont("Interface\\AddOns\\vQueue\\media\\anonpro.TTF", 10) newWaitEntryLvl:SetText(args[2]) newWaitEntryLvl:SetPoint("LEFT", newWaitEntry, "LEFT", 155, 0) newWaitEntryLvl:SetWidth(newWaitEntryLvl:GetStringWidth()) newWaitEntryLvl:SetTextColor(diffColor[1], diffColor[2], diffColor[3]) newWaitEntryLvl:SetHeight(10) local classColor if args[3] ~= "..." then classColor = getClassColor(args[3]) else classColor = {vQueueColors["WHITE"][1], vQueueColors["WHITE"][2], vQueueColors["WHITE"][3]} end newWaitEntryClass = newWaitEntry:CreateFontString(nil, "ARTWORK") newWaitEntryClass:SetFont("Interface\\AddOns\\vQueue\\media\\anonpro.TTF", 10) newWaitEntryClass:SetText(args[3]) newWaitEntryClass:SetPoint("LEFT", newWaitEntry, "LEFT", 245, 0) newWaitEntryClass:SetWidth(newWaitEntryClass:GetStringWidth()) newWaitEntryClass:SetTextColor(classColor[1], classColor[2], classColor[3]) newWaitEntryClass:SetHeight(10) newWaitEntryRole = newWaitEntry:CreateTexture(nil, "ARTWORK") newWaitEntryRole:SetPoint("LEFT", newWaitEntry, "LEFT", 325, 0) newWaitEntryRole:SetTexture("Interface\\AddOns\\vQueue\\media\\" .. args[4]) newWaitEntryRole:SetWidth(16) newWaitEntryRole:SetHeight(16) newWaitEntryInvite = vQueue_newButton(newWaitEntry, 10) newWaitEntryInvite:SetPoint("RIGHT", newWaitEntryBg, "RIGHT", -20, 0) newWaitEntryInvite:SetFont("Interface\\AddOns\\vQueue\\media\\anonpro.TTF", 10) newWaitEntryInvite:SetText("invite") newWaitEntryInvite:SetWidth(newWaitEntryInvite:GetTextWidth()+5) newWaitEntryInvite:SetScript("OnClick", function() InviteByName(this:GetParent():GetText()) groups["waitlist"][this:GetParent():GetText()]:Hide() groups["waitlist"][this:GetParent():GetText()] = nil vQueue_UpdateHostScroll(scrollbar:GetValue()) scrollbar:SetMinMaxValues(1, tablelength(groups[selectedQuery])-10) if playerMessages[this:GetParent():GetText()] == nil then return end local invargs = split(playerMessages[this:GetParent():GetText()], "\:") if Wholefind(invargs[1], "vqrequest") > 0 then if not setContains(chatQueue, "vqaccept" .. "-WHISPER-" .. this:GetParent():GetText()) then addToSet(chatQueue, "vqaccept" .. "-WHISPER-" .. this:GetParent():GetText()) end end end) newWaitEntryInvite:SetScript("OnUpdate", function() if playerMessages[this:GetParent():GetText()] ~= nil then local timeSplit = split(playerMessages[this:GetParent():GetText()], "\:") if type(tonumber(timeSplit[2])) == "number" then local minute = 0 local seconds = math.floor(GetTime() - tonumber(timeSplit[2])) if seconds >= 60 then minute = math.floor(seconds/60) seconds = seconds - (minute*60) end if seconds < 10 then seconds = "0" .. tostring(seconds) end this:SetText("invite(" .. tostring(minute) .. ":" .. tostring(seconds)..")" ) this:SetWidth(this:GetTextWidth()+5) end end end) newWaitEntryDecline = vQueue_newButton(newWaitEntry, 10) newWaitEntryDecline:SetPoint("RIGHT", newWaitEntryBg, "RIGHT", -3, 0) newWaitEntryDecline:SetText("X") newWaitEntryDecline:SetWidth(newWaitEntryDecline:GetTextWidth()+5) newWaitEntryDecline:SetScript("OnClick", function() groups["waitlist"][this:GetParent():GetText()]:Hide() groups["waitlist"][this:GetParent():GetText()] = nil vQueue_UpdateHostScroll(scrollbar:GetValue()) scrollbar:SetMinMaxValues(1, tablelength(groups[selectedQuery])-10) if playerMessages[this:GetParent():GetText()] == nil then return end local invargs = split(playerMessages[this:GetParent():GetText()], "\:") if Wholefind(invargs[1], "vqrequest") > 0 then if not setContains(chatQueue, "vqdecline" .. "-WHISPER-" .. this:GetParent():GetText()) then addToSet(chatQueue, "vqdecline" .. "-WHISPER-" .. this:GetParent():GetText()) end end end) if not vQueueFrame:IsShown() then minimapButton.notifyText:Show() end groups["waitlist"][args[1]] = newWaitEntry end if selectedQuery == "waitlist" and isWaitListShown then groups["waitlist"][args[1]]:Show() vQueue_UpdateHostScroll(scrollbar:GetValue()) scrollbar:SetMinMaxValues(1, tablelength(groups[selectedQuery])-10) else groups["waitlist"][args[1]]:Hide() end end function vQueue_WhoSorting() for i=1, GetNumWhoResults() do name, guild, level, race, class, zone, classFileName, sex = GetWhoInfo(i) if leaderMessages[name] ~= nil and level > 40 and groups["dead"][name] ~= nil then groups["dm"][name] = groups["dead"][name] if selectedQuery == "dead" then groups["dead"][name]:Hide() end groups["dead"][name] = nil local thisframe, bg, name, level = groups["dm"][name]:GetRegions() level:SetText(getglobal("MINLVLS")["dm"]) local diffColor = getDifficultyColor(tonumber(getglobal("MINLVLS")["dm"]), UnitLevel("player")) level:SetTextColor(diffColor[1], diffColor[2], diffColor[3]) elseif leaderMessages[name] ~= nil and groups["dead"][name] ~= nil then local leaderArgs = split(leaderMessages[name], "\:") leaderMessages[name] = leaderArgs[1] .. ":" .. "dead" .. ":" .. leaderArgs[3] if "dead" == selectedQuery then groups["dead"][name]:Show() end end if leaderMessages[name] ~= nil then refreshCatList("dm") refreshCatList("dead") vQueue_ShowGroups(selectedCat, selectedCat) end end end -- return the first integer index holding the value function AnIndexOf(t,val) local i = 0 for k,v in pairs(t) do if k == val then return i end if v ~= nil then i = i+1 end end end function VisibleIndex(t,val) local i = 0 for k,v in pairs(t) do if k == val then return i end if v ~= nil and v:IsShown() then i = i+1 end end end function vQueue_UpdateCatScroll(value) for k, v in pairs(catListButtons) do local index = k if (index+1) < value or index-value > 33 then v:Hide() else v:Show() end end for k, v in pairs(catListButtons) do if v ~= nil then if v:IsShown() then local vindex = VisibleIndex(catListButtons, k) if catListButtons[0]:IsShown() then vindex = vindex + 1 end if v:GetText() == catListButtons[0]:GetText() and v:IsShown() then vindex = 0 end local point, relativeTo, relativePoint, xOffset, yOffset = v:GetPoint() v:SetPoint("TOPLEFT", vQueueFrame.catList, "TOPLEFT", xOffset, vindex*-10) end end end end function vQueue_UpdateHostScroll(value) if selectedQuery ~= "" then for k, v in pairs(groups[selectedQuery]) do local index = AnIndexOf(groups[selectedQuery], k) if (index+1) < value or index-value > 16 then v:Hide() else v:Show() end end if tablelength(groups[selectedQuery]) > 16 then vQueueFrame.hostlistBotShadow:Show() else vQueueFrame.hostlistBotShadow:Hide() end end if selectedQuery ~= "" then for k, v in pairs(groups[selectedQuery]) do if v ~= nil then if v:IsShown() then local thisframe, bg, name, level, size, tank, healer, damage = v:GetRegions() local vindex = VisibleIndex(groups[selectedQuery], k) v:SetPoint("TOPLEFT", vQueueFrame.hostlist, "TOPLEFT", 0, -(vindex*15)-15 - vQueueFrame.hostlistTopSection:GetHeight()) if (math.mod(vindex, 2) == 0) then bg:SetTexture(0.5, 0.5, 0.5, 0.1) else bg:SetTexture(0.2, 0.2, 0.2, 0.1) end end end end end end function getDifficultyColor(levelKey, playerLevel) local color = {} if (levelKey - playerLevel) >= 5 then color[1] = 1 color[2] = 0 color[3] = 0 elseif (levelKey - playerLevel) <= 4 and (levelKey - playerLevel) >= 3 then color[1] = 1 color[2] = 0.5 color[3] = 0 elseif (playerLevel - levelKey) <= 4 and (playerLevel - levelKey) >= 3 then color[1] = 0 color[2] = 1 color[3] = 0 elseif (playerLevel - levelKey) > 4 then color[1] = 0.5 color[2] = 0.5 color[3] = 0.5 else color[1] = 1 color[2] = 1 color[3] = 0 end return color end function getClassColor(class) local classColor = {} classColor["Druid"] = {1, 0.49, 0.04} classColor["Hunter"] = {0.67, 0.83, 0.45} classColor["Mage"] = {0.41, 0.80, 0.94} classColor["Paladin"] = {0.96, 0.55, 0.73} classColor["Priest"] = {1, 1, 1} classColor["Rogue"] = {1, 0.96, 0.41} classColor["Shaman"] = {0, 0.44, 0.87} classColor["Warlock"] = {0.58, 0.51, 0.79} classColor["Warrior"] = {0.78, 0.61, 0.43} for k, v in pairs(classColor) do if k == class then return v end end end function vQueue_addToGroup(category, groupinfo) if category == "waitlist" then return end local args = split(groupinfo, "\:") for k, v in pairs(groups) do for kk, vv in pairs(groups[k]) do if kk == args[2] and vv ~= nil and k ~= category and k ~= "waitlist" then groups[category][args[2]] = groups[k][kk] groups[k][kk]:Hide() groups[k][kk] = nil refreshCatList(k) end end end if groups[category][args[2]] == nil then newHostEntry = CreateFrame("Button", "vQueueButton", vQueueFrame.hostlist) newHostEntry:SetFont("Interface\\AddOns\\vQueue\\media\\anonpro.TTF", 10) newHostEntry:SetText(args[1]) newHostEntry:SetTextColor(vQueueColors["YELLOW"][1], vQueueColors["YELLOW"][2], vQueueColors["YELLOW"][3]) newHostEntry:SetHighlightTextColor(1, 1, 0) newHostEntry:SetPushedTextOffset(0,0) newHostEntry:SetWidth(newHostEntry:GetTextWidth()) newHostEntry:SetHeight(10) newHostEntry:EnableMouse(true) newHostEntry:SetFrameLevel(1) newHostEntry:SetScript("OnEnter", function() local thisframe, bg, name, level, size, tank, healer, damage = this:GetRegions() if leaderMessages[name:GetText()] ~= nil then local leaderargs = split(leaderMessages[name:GetText()], "\:") groupToolTip:SetOwner( this, "ANCHOR_CURSOR" ); groupToolTip:AddLine(leaderargs[1], 1, 1, 1, 1) groupToolTip:Show() end end) newHostEntry:SetScript("OnUpdate", function() if vQueueFrame:IsShown() and this:IsShown() then local thisframe, bg, name, level, size, tank, healer, damage = this:GetRegions() if leaderMessages[name:GetText()] ~= nil and size:GetText() == "?" then local timeSplit = split(leaderMessages[name:GetText()], "\:") if type(tonumber(timeSplit[3])) == "number" then local minute = 0 local seconds = math.floor(GetTime() - tonumber(timeSplit[3])) if seconds >= 60 then minute = math.floor(seconds/60) seconds = seconds - (minute*60) end if seconds < 10 then seconds = "0" .. tostring(seconds) end this:SetText("(Mouseover to see chat message) " .. tostring(minute) .. ":" .. tostring(seconds) ) this:SetWidth(this:GetTextWidth()) end end end end) newHostEntry:SetScript("OnLeave", function() groupToolTip:Hide() end) newHostEntryBg = newHostEntry:CreateTexture(nil, "BACKGROUND") newHostEntryBg:SetPoint("LEFT", newHostEntry, "LEFT", 1, 0) newHostEntryBg:SetWidth(vQueueFrame.hostlist:GetWidth()-3) newHostEntryBg:SetHeight(15) if (math.mod(tablelength(groups[category])-1, 2) == 0) then newHostEntryBg:SetTexture(0.5, 0.5, 0.5, 0.1) else newHostEntryBg:SetTexture(0.2, 0.2, 0.2, 0.1) end newHostEntryName = newHostEntry:CreateFontString(nil, "ARTWORK") newHostEntryName:SetFont("Interface\\AddOns\\vQueue\\media\\anonpro.TTF", 10) newHostEntryName:SetText(args[2]) newHostEntryName:SetPoint("LEFT", newHostEntry, "LEFT", 211, 0) newHostEntryName:SetWidth(newHostEntryName:GetStringWidth()) newHostEntryName:SetTextColor(vQueueColors["WHITE"][1], vQueueColors["WHITE"][2], vQueueColors["WHITE"][3]) newHostEntryName:SetHeight(10) local diffColor = getDifficultyColor(tonumber(args[3]), UnitLevel("player")) newHostEntryLevel = newHostEntry:CreateFontString(nil, "ARTWORK") newHostEntryLevel:SetFont("Interface\\AddOns\\vQueue\\media\\anonpro.TTF", 10) newHostEntryLevel:SetText(args[3]) newHostEntryLevel:SetPoint("LEFT", newHostEntry, "LEFT", 287, 0) newHostEntryLevel:SetWidth(newHostEntryLevel:GetStringWidth()) newHostEntryLevel:SetTextColor(diffColor[1], diffColor[2], diffColor[3]) newHostEntryLevel:SetHeight(10) newHostEntrySize = newHostEntry:CreateFontString(nil, "ARTWORK") newHostEntrySize:SetFont("Interface\\AddOns\\vQueue\\media\\anonpro.TTF", 10) newHostEntrySize:SetText(args[4]) newHostEntrySize:SetPoint("LEFT", newHostEntry, "LEFT", 325, 0) newHostEntrySize:SetWidth(newHostEntrySize:GetStringWidth()) newHostEntrySize:SetTextColor(vQueueColors["WHITE"][1], vQueueColors["WHITE"][2], vQueueColors["WHITE"][3]) newHostEntrySize:SetHeight(10) newHostEntryTank = newHostEntry:CreateTexture(nil, "ARTWORK") newHostEntryTank:SetPoint("LEFT", newHostEntry, "LEFT", 360, 0) newHostEntryTank:SetTexture("Interface\\AddOns\\vQueue\\media\\Tank") newHostEntryTank:SetWidth(16) newHostEntryTank:SetHeight(16) if args[7] == "Tank" then newHostEntryTank:Show() else newHostEntryTank:Hide() end newHostEntryHealer = newHostEntry:CreateTexture(nil, "ARTWORK") newHostEntryHealer:SetPoint("LEFT", newHostEntry, "LEFT", 376, 0) newHostEntryHealer:SetTexture("Interface\\AddOns\\vQueue\\media\\Healer") newHostEntryHealer:SetWidth(16) newHostEntryHealer:SetHeight(16) if args[5] == "Healer" then newHostEntryHealer:Show() else newHostEntryHealer:Hide() end newHostEntryDamage = newHostEntry:CreateTexture(nil, "ARTWORK") newHostEntryDamage:SetPoint("LEFT", newHostEntry, "LEFT", 392, 0) newHostEntryDamage:SetTexture("Interface\\AddOns\\vQueue\\media\\Damage") newHostEntryDamage:SetWidth(16) newHostEntryDamage:SetHeight(16) if args[6] == "Damage" then newHostEntryDamage:Show() else newHostEntryDamage:Hide() end waitListButton = vQueue_newButton(newHostEntry, 9) waitListButton:SetPoint("RIGHT", newHostEntryBg, "RIGHT", -3, 0) if setContains(waitingList, args[2]) then waitListButton:SetText("waiting") else waitListButton:SetText("wait list") end if leaderMessages[args[2]] ~= nil and newHostEntrySize:GetText() == "?" then waitListButton:SetText("reply") end waitListButton:SetWidth(waitListButton:GetTextWidth()+5) waitListButton:SetScript("OnClick", function() if GetNumPartyMembers() > 0 and this:GetText() ~= "reply" then vQueueFrame.hostlistRoleText:SetText("(Leave group before queueing for other groups)") return end local thisframe, bg, name, level, size, tank, healer, damage = this:GetParent():GetRegions() if this:GetText() == "wait list" then if tonumber(level:GetText()) > UnitLevel("player") then vQueueFrame.hostlistRoleText:SetText("(You do not meet the level requirements for this group)") return end this:SetText("waiting") vQueue_SlashCommandHandler("request " .. name:GetText()) if not setContains(waitingList, name:GetText()) then addToSet(waitingList, name:GetText()) end end if this:GetText() == "reply" then vQueueFrame.replyFrameTo:SetText(name:GetText()) vQueueFrame.replyFrameMsg:SetText("(vQueue) Lvl " .. tostring(UnitLevel("player")) .. " " .. selectedRole .. " " .. tostring(UnitClass("player"))) vQueueFrame.replyFrame:Show() end end) groups[category][args[2]] = newHostEntry else local thisframe, bg, name, level, size, tank, healer, damage = groups[category][args[2]]:GetRegions() groups[category][args[2]]:SetText(args[1]) groups[category][args[2]]:SetWidth(groups[category][args[2]]:GetTextWidth()) local diffColor = getDifficultyColor(tonumber(args[3]), UnitLevel("player")) level:SetText(args[3]) level:SetWidth(level:GetStringWidth()) level:SetTextColor(diffColor[1], diffColor[2], diffColor[3]) size:SetText(args[4]) size:SetWidth(size:GetStringWidth()) if args[7] == "Tank" then tank:Show() else tank:Hide() end if args[5] == "Healer" then healer:Show() else healer:Hide() end if args[6] == "Damage" then damage:Show() else damage:Hide() end end if category == selectedQuery and not isWaitListShown then groups[category][args[2]]:Show() vQueue_UpdateHostScroll(scrollbar:GetValue()) scrollbar:SetMinMaxValues(1, tablelength(groups[selectedQuery])-10) else groups[category][args[2]]:Hide() end end function vQueue_ShowGroups(category, prevCategory) if prevCategory ~= "" then for k, v in pairs(groups[prevCategory]) do v:Hide() end end if category ~= "" then for k, v in pairs(groups[category]) do v:Hide() end for k, v in pairs(groups[category]) do v:Show() end scrollbar:SetMinMaxValues(1, tablelength(groups[category])-10) end vQueue_UpdateHostScroll(scrollbar:GetValue()) end function refreshCatList(cat) for kChild, child in ipairs(catListButtons) do local args = {} local realText = split(child:GetText(), "%(") for k, v in pairs(categories) do for i, item in v do if type(item) == "string" then local tArgs = split(item, "\:") if tArgs[1] == realText[1] and tArgs[2] == cat then args = tArgs break end end end end if args[2] ~= nil and type(args[2]) == "string" then child:SetText(realText[1] .. "(" .. tablelength(groups[args[2]]) .. ")") child:SetWidth(child:GetTextWidth()) break end end end function vQueue_newButton(parentFrame, FontSize) newButton = CreateFrame("Button", "vQueueButton", parentFrame) newButton:SetFont("Fonts\\FRIZQT__.TTF", FontSize) newButton:SetTextColor(vQueueColors["YELLOW"][1], vQueueColors["YELLOW"][2], vQueueColors["YELLOW"][3]) newButton:SetNormalTexture("Interface\\AddOns\\vQueue\\media\\button") newButton:SetHighlightTexture("Interface\\BUTTONS\\CheckButtonHilight") newButton:GetHighlightTexture():SetVertexColor(1, 1, 1, 0.2) newButton:GetNormalTexture():SetVertexColor(0.25, 0.25, 0.25, 1.0) newButton:SetHeight(FontSize+2) local borderColor = {0.05, 0.05, 0.05, 1} leftBorder = newButton:CreateTexture(nil, "OVERLAY") leftBorder:SetPoint("TOPLEFT", newButton, "TOPLEFT") leftBorder:SetPoint("BOTTOMLEFT", newButton, "BOTTOMLEFT") leftBorder:SetTexture(borderColor[1], borderColor[2], borderColor[3], borderColor[4]) leftBorder:SetWidth(1) rightBorder = newButton:CreateTexture(nil, "OVERLAY") rightBorder:SetPoint("TOPRIGHT", newButton, "TOPRIGHT") rightBorder:SetPoint("BOTTOMRIGHT", newButton, "BOTTOMRIGHT") rightBorder:SetTexture(borderColor[1], borderColor[2], borderColor[3], borderColor[4]) rightBorder:SetWidth(1) return newButton end function vQueue_SlashCommandHandler( msg ) local args = {} if msg ~= nil then args = split(msg, "\%s") end if args[1] == "host" and args[2] ~= nil then isHost = true DEFAULT_CHAT_FRAME:AddMessage("Now hosting for " .. hostedCategory) idleMessage = 25 elseif args[1] == "lfg" and args[2] ~= nil then if not setContains(chatQueue, args[2]) then addToSet(chatQueue, "lfg " .. args[2] .. "-CHANNEL-" .. tostring(GetChannelName(channelName))) end elseif args[1] == "request" and args[2] ~= nil then if not setContains(chatQueue, "vqrequest " .. UnitLevel("player") .. " " .. UnitClass("player") .. " " .. selectedRole .. "-WHISPER-" .. args[2]) then addToSet(chatQueue, "vqrequest " .. UnitLevel("player") .. " " .. UnitClass("player") .. " " .. selectedRole .. "-WHISPER-" .. args[2]) end elseif args[1] == "testgroups" then for i=1, 100 do vQueue_addToGroup("misc", "title" .. i .. ":" .. "lmaoiwaslike" .. i .. ":" .. i .. ":" .. "?" .. ":" .. "Healer" .. ":" .. "Damage" .. ":" .. "Tank") end refreshCatList("misc") elseif args[1] == "testplayers" then local classes = {} classes[1] = "Druid" classes[2] = "Hunter" classes[3] = "Mage" classes[4] = "Paladin" classes[5] = "Priest" classes[6] = "Rogue" classes[7] = "Shaman" classes[8] = "Warlock" classes[9] = "Warrior" local roles = {} roles[1] = "Healer" roles[2] = "Damage" roles[3] = "Tank" for i=1, 100 do vQueue_addToWaitList("lmaoiwaslike" .. i .. ":" .. math.random(1, 60) .. ":" .. classes[math.random(1, 9)] .. ":" .. roles[math.random(1,3)]) end end end function vQueue_OnUpdate() whoRequestTimer = whoRequestTimer + arg1 if whoRequestTimer > 2 then whoRequestTimer = 0 if fixingChat then JoinChannelByName("General") JoinChannelByName("Trade") JoinChannelByName("LocalDefense") JoinChannelByName("LookingForGroup") JoinChannelByName("World") JoinChannelByName("vQueue") fixingChat = false end if tablelength(whoRequestList) > 0 and not FriendsFrame:IsShown() then local whoString = "" for k, v in pairs(whoRequestList) do whoString = whoString .. k .. " " end SetWhoToUI(1) FriendsFrame:UnregisterEvent("WHO_LIST_UPDATE") SendWho(whoString) elseif FriendsFrame:IsShown() then FriendsFrame:RegisterEvent("WHO_LIST_UPDATE") end end idleMessage = idleMessage + arg1 if idleMessage > 30 and tablelength(chatQueue) == 0 then idleMessage = 0 if (isFinding or isHost) and GetChannelName(channelName) < 1 then JoinChannelByName(channelName) elseif GetChannelName(channelName) > 0 and (isHost == false and isFinding == false) then LeaveChannelByName(channelName) end if isHost then local groupSize = GetNumRaidMembers() if groupSize == 0 then groupSize = GetNumPartyMembers() end groupSize = groupSize + 1 addToSet(chatQueue, "vqgroup " .. hostedCategory .. " " .. tostring(hostOptions[1]) .. " " .. groupSize .. " " .. tostring(hostOptions[2]) .. " " .. tostring(hostOptions[3]) .. " " .. tostring(hostOptions[4]) .. " " .. tostring(2) .. " :" .. tostring(hostOptions[0]) .. "-CHANNEL-" .. tostring(GetChannelName(channelName))) end -- Removes entries after 5 minutes of no updates for k, v in pairs(leaderMessages) do if v ~= nil then local leaderArgs = split(v, "\:") local timeDiff = GetTime() - tonumber(leaderArgs[3]) if leaderArgs[3] ~= nil and type(tonumber(leaderArgs[3])) == "number" then if timeDiff > (300) then -- delete chat entries after 5 minutes of no updates if groups[leaderArgs[2]][k] ~= nil then groups[leaderArgs[2]][k]:Hide() groups[leaderArgs[2]][k] = nil leaderMessages[k] = nil refreshCatList(leaderArgs[2]) if vQueueFrame:IsShown() and selectedQuery == leaderArgs[2] then vQueue_UpdateHostScroll(scrollbar:GetValue()) end end end if timeDiff > (40) then -- remove vQueue groups after 40 seconds if groups[leaderArgs[2]][k] ~= nil then local thisframe, bg, name, level, size, tank, healer, damage = groups[leaderArgs[2]][k]:GetRegions() if size:GetText() ~= "?" then groups[leaderArgs[2]][k]:Hide() groups[leaderArgs[2]][k] = nil leaderMessages[k] = nil refreshCatList(leaderArgs[2]) if vQueueFrame:IsShown() and selectedQuery == leaderArgs[2] then vQueue_UpdateHostScroll(scrollbar:GetValue()) end end end end end end end end -- CHAT LIMITER if(chatRate > 0) then lastUpdate = lastUpdate + arg1 -- MESSAGES TO SEND GO HERE if (lastUpdate > (1/chatRate)) then lastUpdate = 0 --queue of chat messages limited to 3 per second if next(chatQueue) ~= nil then for key,value in pairs(chatQueue) do local args = split(key, "\-") SendChatMessage(args[1] , args[2], nil , args[3]); removeFromSet(chatQueue, key) break end end end end end SlashCmdList["vQueue"] = vQueue_SlashCommandHandler SLASH_vQueue1 = "/vQueue"
return function (_, fromPlayers, toPlayer) if toPlayer.Character and toPlayer.Character:FindFirstChild("HumanoidRootPart") then local position = toPlayer.Character.HumanoidRootPart.CFrame for _, player in ipairs(fromPlayers) do if player.Character and player.Character:FindFirstChild("HumanoidRootPart") then player.Character.HumanoidRootPart.CFrame = position end end return ("Teleported %d players."):format(#fromPlayers) end return "Target player has no character." end
local ChatSystem = { textEntered = nil; spawnTicket = nil; Properties = { textField = {default = EntityId()}, contentArea = {default = EntityId()}, }, } function ChatSystem:OnTick(deltaTime, timePoint) self.CanvasEntityId = UiElementBus.Event.GetCanvas(self.entityId) if self.CanvasEntityId then if self.canvasNotificationHandler then self.canvasNotificationHandler:Disconnect() self.canvasNotificationHandler = nil end self.canvasNotificationHandler = UiCanvasNotificationBus.Connect(self, self.CanvasEntityId) end end function ChatSystem:OnActivate() self.tickBusHandler = TickBus.Connect(self); self.chatHandler = SparkChatNotificationBus.Connect(self); self.spawnTicket = nil end function ChatSystem:OnAction(entityId, actionName) if actionName == "Send" or actionName == "EnterSend" then --Send Text self.textEntered = UiTextInputBus.Event.GetText(self.Properties.textField) self:PutTextIntoChat(tostring(self.textEntered)) end end function ChatSystem:OnDeactivate() self.tickBusHandler:Disconnect() self.canvasNotificationHandler:Disconnect() end function ChatSystem:UpdateChat() local Children = UiElementBus.Event.GetChildren(self.Properties.contentArea) if Children ~= nil then for i = 1, #Children do Debug.Log(tostring(UiElementBus.Event.GetName(Children[i]))) local Offset = UiTransform2dBus.Event.GetOffsets(Children[i]) Offset.top = Offset.top - 15 UiTransform2dBus.Event.SetOffsets(Children[i], Offset) end end end function ChatSystem:PutTextIntoChat(msg) SparkChatRequestBus.Broadcast.SendChatMessage(ChatMessage(msg,"Bard")) local ChatText = UiElementBus.Event.FindDescendantByName(self.Properties.textField,"ChatText") local PlaceholderText = UiElementBus.Event.FindDescendantByName(self.Properties.textField,"PlaceholderText") UiTextBus.Event.SetText(ChatText,"") UiElementBus.Event.SetIsEnabled(PlaceholderText,false) end function ChatSystem:OnNewMessage(msg) self.spawnerHandler = UiSpawnerNotificationBus.Connect(self, self.Properties.contentArea) self:UpdateChat() self.spawnTicket = UiSpawnerBus.Event.Spawn(self.Properties.contentArea) end function ChatSystem:OnTopLevelEntitiesSpawned(ticket, ids) if ticket == self.spawnTicket then local Author = UiElementBus.Event.FindDescendantByName(ids[1],"Author") local Message = UiElementBus.Event.FindDescendantByName(ids[1],"Message") local LastMessage = SparkChatRequestBus.Broadcast.GetLastMessage() UiTextBus.Event.SetText(UiElementBus.Event.GetChild(Author,0), LastMessage:GetAuthor()) UiTextBus.Event.SetText(UiElementBus.Event.GetChild(Message,0), LastMessage:GetText()) end end function ChatSystem:OnSpawnEnd(ticket) if ticket == self.spawnTicket then self.spawnTicket = nil end end function ChatSystem:OnSpawnFailed(ticket) if ticket == self.spawnTicket then self.spawnerHandler:Disconnect() self.spawnTicket = nil end end return ChatSystem;
local limit = tonumber(arg[1]) or 1 local dlimit = tonumber(arg[2]) or 100 local function d(t) if #t == 2 then return end for i=1,dlimit do local a = { } end t[#t + 1] = math.abs(-1) return d(t) end function c(t) for i=1,limit do local a = { } end return d(t) end function b(t) for i=1,limit do local a = { } end return c(t) end function a() for i=1,limit do local a = { } end return b({ }) end a()
mysql = exports.mrp_mysql function giveCarLicense(usingGC) local theVehicle = getPedOccupiedVehicle(source) setElementData(source, "realinvehicle", 0, false) removePedFromVehicle(source) if theVehicle then respawnVehicle(theVehicle) setElementData(theVehicle, "handbrake", 1, false) setElementFrozen(theVehicle, true) end setElementData(source, "license.car", 1) dbExec(mysql:getConnection(), "UPDATE characters SET car_license='1' WHERE charactername='" .. (getPlayerName(source)) .. "' LIMIT 1") exports.mrp_hud:sendBottomNotification(source, "Department of Motor Vehicles", "Congratulations! You've passed your driving examination!" ) exports.mrp_global:giveItem(source, 133, getPlayerName(source):gsub("_"," ")) executeCommandHandler("stats", source, getPlayerName(source)) end addEvent("acceptCarLicense", true) addEventHandler("acceptCarLicense", getRootElement(), giveCarLicense) function passTheory() setElementData(source,"license.car.cangetin",true, false) setElementData(source,"license.car",3) -- Set data to "theory passed" dbExec(mysql:getConnection(), "UPDATE characters SET car_license='3' WHERE charactername='" .. (getPlayerName(source)) .. "' LIMIT 1") end addEvent("theoryComplete", true) addEventHandler("theoryComplete", getRootElement(), passTheory) function checkDoLCars(player, seat) -- aka civilian previons if getElementData(source, "owner") == -2 and getElementData(source, "faction") == -1 and getElementModel(source) == 410 then if getElementData(player,"license.car") == 3 then if getElementData(player, "license.car.cangetin") then exports.mrp_hud:sendBottomNotification(player, "Department of Motor Vehicles", "You can use 'J' to start the engine and /handbrake to release the handbrake." ) else exports.mrp_hud:sendBottomNotification(player, "Department of Motor Vehicles", "This vehicle is for the Driving Test only, please see the NPC inside first." ) if not exports["mrp_integration"]:isPlayerHeadAdmin(player) then cancelEvent() end end elseif seat > 0 then exports.mrp_hud:sendBottomNotification(player, "Department of Motor Vehicles", "This vehicle is for the Driving Test only." ) else exports.mrp_hud:sendBottomNotification(player, "Department of Motor Vehicles", "This vehicle is for the Driving Test only." ) cancelEvent() end end end addEventHandler( "onVehicleStartEnter", getRootElement(), checkDoLCars)
-- Operator overloading example ---- importing ---- if string.sub(_VERSION,1,7)=='Lua 5.0' then -- lua5.0 doesn't have a nice way to do this lib=loadlib('example.dll','luaopen_example') or loadlib('example.so','luaopen_example') assert(lib)() else -- lua 5.1 does require('example') end a = example.intSum(0) b = example.doubleSum(100.0) -- Use the objects. They should be callable just like a normal -- lua function. for i=0,100 do a(i) -- Note: function call b(math.sqrt(i)) -- Note: function call end print("int sum 0..100 is",a:result(),"(expected 5050)") print("double sum 0..100 is",b:result(),"(expected ~771.46)")
-- MIT License Copyright (c) 2021 Evgeni Chasnovski -- Documentation ============================================================== --- Custom minimal and fast module for working with trailing whitespace. --- --- Features: --- - Highlighting is done only in modifiable buffer by default; only in Normal --- mode; stops in Insert mode and when leaving window. --- - Trim all trailing whitespace with |MiniTrailspace.trim()| function. --- --- # Setup~ --- --- This module needs a setup with `require('mini.trailspace').setup({})` --- (replace `{}` with your `config` table). It will create global Lua table --- `MiniTrailspace` which you can use for scripting or manually (with --- `:lua MiniTrailspace.*`). --- --- See |MiniTrailspace.config| for `config` structure and default values. --- --- # Highlight groups~ --- --- 1. `MiniTrailspace` - highlight group for trailing space. --- --- To change any highlight group, modify it directly with |:highlight|. --- --- # Disabling~ --- --- To disable, set `g:minitrailspace_disable` (globally) or --- `b:minitrailspace_disable` (for a buffer) to `v:true`. Considering high --- number of different scenarios and customization intentions, writing exact --- rules for disabling module's functionality is left to user. See --- |mini.nvim-disabling-recipes| for common recipes. Note: after disabling --- there might be highlighting left; it will be removed after next --- highlighting update (see |events| and `MiniTrailspace` |augroup|). ---@tag mini.trailspace ---@tag MiniTrailspace ---@toc_entry Trailspace (highlight and remove) -- Module definition ========================================================== local MiniTrailspace = {} local H = {} --- Module setup --- ---@param config table Module config table. See |MiniTrailspace.config|. --- ---@usage `require('mini.trailspace').setup({})` (replace `{}` with your `config` table) function MiniTrailspace.setup(config) -- Export module _G.MiniTrailspace = MiniTrailspace -- Setup config config = H.setup_config(config) -- Apply config H.apply_config(config) -- Module behavior -- Use `defer_fn` for `MiniTrailspace.highlight` to ensure that -- 'modifiable' option is set to its final value. vim.api.nvim_exec( [[augroup MiniTrailspace au! au WinEnter,BufEnter,InsertLeave * lua MiniTrailspace.highlight() au WinLeave,BufLeave,InsertEnter * lua MiniTrailspace.unhighlight() au FileType TelescopePrompt let b:minitrailspace_disable=v:true augroup END]], false ) if config.only_in_normal_buffers then -- Add tracking of 'buftype' changing because it can be set after events on -- which highlighting is done. If not done, highlighting appears but -- disappears if buffer is reentered. vim.api.nvim_exec( [[augroup MiniTrailspace au OptionSet buftype lua MiniTrailspace.track_normal_buffer() augroup END]], false ) end -- Create highlighting vim.api.nvim_exec([[hi default link MiniTrailspace Error]], false) end --- Module config --- --- Default values: ---@eval return MiniDoc.afterlines_to_code(MiniDoc.current.eval_section) MiniTrailspace.config = { -- Highlight only in normal buffers (ones with empty 'buftype'). This is -- useful to not show trailing whitespace where it usually doesn't matter. only_in_normal_buffers = true, } --minidoc_afterlines_end -- Module functionality ======================================================= --- Highlight trailing whitespace function MiniTrailspace.highlight() -- Highlight only in normal mode if H.is_disabled() or vim.fn.mode() ~= 'n' then MiniTrailspace.unhighlight() return end if MiniTrailspace.config.only_in_normal_buffers and not H.is_buffer_normal() then return end local win_id = vim.api.nvim_get_current_win() if not vim.api.nvim_win_is_valid(win_id) then return end -- Don't add match id on top of existing one if H.window_matches[win_id] ~= nil then return end local match_id = vim.fn.matchadd('MiniTrailspace', [[\s\+$]]) H.window_matches[win_id] = { id = match_id } end --- Unhighlight trailing whitespace function MiniTrailspace.unhighlight() -- Don't do anything if there is no valid information to act upon local win_id = vim.api.nvim_get_current_win() local win_match = H.window_matches[win_id] if not vim.api.nvim_win_is_valid(win_id) or win_match == nil then return end -- Use `pcall` because there is an error if match id is not present. It can -- happen if something else called `clearmatches`. pcall(vim.fn.matchdelete, win_match.id) H.window_matches[win_id] = nil end --- Trim trailing whitespace function MiniTrailspace.trim() -- Save cursor position to later restore local curpos = vim.api.nvim_win_get_cursor(0) -- Search and replace trailing whitespace vim.cmd([[keeppatterns %s/\s\+$//e]]) vim.api.nvim_win_set_cursor(0, curpos) end --- Track normal buffer --- --- Designed to be used with |autocmd|. No need to use it directly. function MiniTrailspace.track_normal_buffer() if not MiniTrailspace.config.only_in_normal_buffers then return end -- This should be used with 'OptionSet' event for 'buftype' option -- Empty 'buftype' means "normal buffer" if vim.v.option_new == '' then MiniTrailspace.highlight() else MiniTrailspace.unhighlight() end end -- Helper data ================================================================ -- Module default config H.default_config = MiniTrailspace.config -- Information about last match highlighting (stored *per window*): -- - Key: windows' unique buffer identifiers. -- - Value: table with `id` field for match id (from `vim.fn.matchadd()`). H.window_matches = {} -- Helper functionality ======================================================= -- Settings ------------------------------------------------------------------- function H.setup_config(config) -- General idea: if some table elements are not present in user-supplied -- `config`, take them from default config vim.validate({ config = { config, 'table', true } }) config = vim.tbl_deep_extend('force', H.default_config, config or {}) vim.validate({ only_in_normal_buffers = { config.only_in_normal_buffers, 'boolean' } }) return config end function H.apply_config(config) MiniTrailspace.config = config end function H.is_disabled() return vim.g.minitrailspace_disable == true or vim.b.minitrailspace_disable == true end function H.is_buffer_normal(buf_id) return vim.api.nvim_buf_get_option(buf_id or 0, 'buftype') == '' end return MiniTrailspace
----------------------------------- -- Ability: Saber Dance -- Increases Double Attack rate but renders Waltz unusable. Double Attack rate gradually decreases. -- Obtained: Dancer Level 75 Merit Group 2 -- Recast Time: 3 minutes -- Duration: 5 minutes ----------------------------------- require("scripts/globals/status") ----------------------------------- function onAbilityCheck(player, target, ability) return 0, 0 end function onUseAbility(player, target, ability) player:addStatusEffect(tpz.effect.SABER_DANCE, 50, 3, 300) end
if not _TEST then GUI = GimmeTheLoot:NewModule('GUI') end local AceGUI = LibStub('AceGUI-3.0') local Search local searchOffset = 0 local searchLimit = 30 function GUI:OnInitialize() Search = GimmeTheLoot:GetModule('Search') end function GUI:PerformSearch(container, search) searchOffset = 0 -- reset offset when searching container:ReleaseChildren() self:AppendRecords(container, Search:SearchRecords(search, searchLimit, searchOffset)) end --[[ Frame guide: +-mainFrame (Frame)---------------------------------------------+ |---mainContainer (SimpleGroup)---------------------------------| || +--utilityContainer (SimpleGroup)-------------------------+ || || | | || || | +-searchBox (EditBox)--+ | || || | | | | || || | +----------------------+ | || || | +-qualityDropdown (Dropdown)--+ | || || | | | | || || | +-----------------------------+ | || || | +-loadMoreButton (Button)--+ | || || | | | | || || | +--------------------------+ | || || +---------------------------------------------------------+ || || || || +-resultsContainer (SimpleGroup)--------------------------+ || || | | || || | +--recordsContainer (ScrollFrame)---------------------+ | || || | | | | || || | | +--recordContainer (SimpleGroup)------------------+ | | || || | | | | | | || || | | | | | | || || | | +-------------------------------------------------+ | | || || | | | | || || | | | | || || | | | | || || | | | | || || | +-----------------------------------------------------+ | || || +---------------------------------------------------------+ || |---------------------------------------------------------------| +---------------------------------------------------------------+ --]] function GUI:DisplayFrame() local searchQuery = {quality = {}} local mainFrame = AceGUI:Create('Frame') local mainContainer = AceGUI:Create('SimpleGroup') local utilityContainer = AceGUI:Create('SimpleGroup') local searchBox = AceGUI:Create('EditBox') local qualityDropdown = AceGUI:Create('Dropdown') local loadMoreButton = AceGUI:Create('Button') local resultsContainer = AceGUI:Create('InlineGroup') local recordsContainer = AceGUI:Create('ScrollFrame') mainFrame:SetTitle('Roll History') mainFrame:SetCallback('OnClose', function(widget) AceGUI:Release(widget) end) mainFrame:SetLayout('Fill') mainContainer:SetLayout('Flow') mainFrame:AddChild(mainContainer) utilityContainer:SetLayout('Flow') mainContainer:AddChild(utilityContainer) searchBox:SetLabel('search') searchBox:DisableButton(true) searchBox:SetMaxLetters(20) searchBox:SetCallback('OnTextChanged', function(_, _, text) searchQuery.text = text self:PerformSearch(recordsContainer, searchQuery) end) utilityContainer:AddChild(searchBox) qualityDropdown:SetList({ [2] = '|cff00ff00Uncommon', [3] = '|cff0000ffRare', [4] = '|cffa335eeEpic', [5] = '|cffff8000Legendary', }) qualityDropdown:SetMultiselect(true) qualityDropdown:SetCallback('OnValueChanged', function(_, _, key, checked) searchQuery.quality[key] = checked or nil self:PerformSearch(recordsContainer, searchQuery) end) utilityContainer:AddChild(qualityDropdown) loadMoreButton:SetText('Load more records') loadMoreButton:SetDisabled(#GimmeTheLoot.db.profile.records < searchLimit) loadMoreButton:SetCallback('OnClick', function() searchOffset = searchOffset + searchLimit self:AppendRecords(recordsContainer, Search:SearchRecords(searchQuery, searchLimit, searchOffset)) end) utilityContainer:AddChild(loadMoreButton) resultsContainer:SetTitle('History:') resultsContainer:SetFullWidth(true) resultsContainer:SetFullHeight(true) resultsContainer:SetLayout('Fill') mainContainer:AddChild(resultsContainer) recordsContainer:SetLayout('List') recordsContainer:SetFullHeight(true) resultsContainer:AddChild(recordsContainer) self:AppendRecords(recordsContainer, Search:SearchRecords(searchQuery, searchLimit, searchOffset)) end function GUI:AppendRecords(container, records) for _, v in ipairs(records) do local recordContainer = AceGUI:Create('SimpleGroup') recordContainer:SetFullWidth(true) recordContainer:SetLayout('Flow') container:AddChild(recordContainer) local itemName = AceGUI:Create('InteractiveLabel') itemName:SetRelativeWidth(.4) itemName:SetText(v.item.link) itemName:SetHighlight({255, 0, 0, 255}) itemName:SetUserData('text', v.item.link) itemName:SetCallback('OnEnter', function(widget) GameTooltip:SetOwner(widget.frame, 'ANCHOR_LEFT') GameTooltip:SetHyperlink(widget:GetUserData('text')) GameTooltip:Show() end) itemName:SetCallback('OnLeave', function() GameTooltip:Hide() end) recordContainer:AddChild(itemName) local rollTime = AceGUI:Create('Label') rollTime:SetRelativeWidth(.25) rollTime:SetText(date('%b %d %Y %I:%M %p', v['rollCompleted'])) recordContainer:AddChild(rollTime) local winner = AceGUI:Create('Label') winner:SetRelativeWidth(.25) winner:SetText(v['winner']) recordContainer:AddChild(winner) end end
local tab = { }; tab.Name = "Interface"; tab.Model = "models/gibs/scanner_gib04.mdl"; EXPORTS["interface"] = tab;
๏ปฟ--[[ Online Binary => Decimal Converter https://www.rapidtables.com/convert/number/binary-to-decimal.html Binary Digits Visualization https://www.mathsisfun.com/binary-digits.html Bitpacking in LUA 5.3 https://github.com/ToxicFrog/vstruct BitOp-LUA Bitwise operators in LUA 5.3 -- Though it seems LUA 5.3.4 has it built in? https://github.com/AlberTajuelo/bitop-lua -- Saved Score Should Be 33554431 but saved as 33554432 ]]--
local smt = setmetatable local type = type local error = error local pcall = pcall local select = select local min, max = math.min, math.max local s = string local srep = s.rep local ssub = s.sub local sgsub = s.gsub local sfind = s.find local sbyte = s.byte local schar = s.char local smatch = s.match local sgmatch = s.gmatch local sreverse = s.reverse local table = table local tconcat = table.concat local E = function(...) error(..., 3) end --local E = function(...) return nil, ... end -- Patterns local pattern = (function(...) local mt local function new(p, t, a, e) return smt({p = p, t = t, a = a, e = e}, mt) end -- upper lower replace table -- e.g. ulrt['A'] = 'a', ulrt['a'] = 'A' local ulrt = {} for x,y in sgmatch("abcdefghijklmnopqrstuvwxyz", "()(.)") do local z = ssub("ABCDEFGHIJKLMNOPQRSTUVWXYZ",x,x) ulrt[y] = z ulrt[z] = y end mt = { __concat = function(a, b) if b.a then return E("Pattern cannot be prepended to") end if a.e then return E("Pattern cannot be appended to") end return new(a.p .. b.p, min(a.t, b.t), a.a, b.e) end, __tostring = function(t) return (t.a or "") .. t.p .. (t.e or "") end, __mul = function(t, n) return new(srep(t.p, n), 2, t.a, t.e) end, __add = function(t, q) if sfind("+-?*", q, 1, true) and t.t > 2 then return new(t.p .. "+", 2, t.a, t.e) else return E("Not quantifiable or invalid quantifier") end end, __index = { find = function(t, s, n) return sfind(s, (t.a or "") .. t.p .. (t.e or ""), n or 1) end, gsub = function(t, s, r, n) return sgsub(s, (t.a or "") .. t.p .. (t.e or ""), r, n or 1) end, gmatch = function(t, s) return sgmatch(s, (t.a or "") .. t.p .. (t.e or "")) end, match = function(t, s, n) return smatch(s, (t.a or "") .. t.p .. (t.e or ""), n or 1) end, }, __unm = function(t) if #t.p == 2 and ssub(t.p,1,1) == "%" and ulrt[ssub(t.p,2,2)] then return new("%" .. ulrt[ssub(t.p,2,2)], t.t, t.a, t.e) elseif t.t == 3 then if ssub(t.p,1,2) == "[^" then return new("[" .. ssub(t.p,3), t.t, t.a, t.e) else return new("[^" .. ssub(t.p,2), t.t, t.a, t.e) end else return t end end, __eq = function(a, b) return a.p == b.p and a.t == b.t and a.a == b.a and a.e == b.e end } local function escape(s) return sgsub(s, "%W", "%%%0") end local function str(s) return new(escape(s), 2) end local function raw(s) local a, e if ssub(s,1,1) == "^" then a = "^" end if ssub(s,-1,-1) == "$" then e = "$" end return new(s, 1, a, e) end local function group(p) if p.t < 2 then return E("Pattern may contain ungroupable characters") end if #p.p == 0 then -- HACK: always captures an empty string return new("([\2-\1]?)", 2) end return new("(" .. p.p .. ")", 2) end local function escaperange_helper(c) -- NOT NEEDED as `.` doesn't need escaping inside `[]` -- if c == "." then return false end local s, r = pcall(smatch, c, c) return s and r == c end local function escaperange(l, u) local t1 = {} local n1 = 1 local last1 for i=sbyte(l), sbyte(u) do if escaperange_helper(schar(i)) then last1 = i break end t1[n1] = escape(schar(i)) n1 = n1 + 1 end if last1 then local t2 = {} local n2 = 1 local last2 for i=sbyte(u), last1, -1 do if escaperange_helper(schar(i)) then last2 = i break end t2[n2] = escape(schar(i)) n2 = n2 + 1 end local middle = "" if last1 ~= last2 then middle = schar(last1) .. "-" .. schar(last2) end return tconcat(t1, "") .. middle .. sreverse(tconcat(t2, "")) else return tconcat(t1, "") end end local function set(...) local t, n --[[ legacy code local negate if ... == false or ... == true then t = {select(2, ...)} n = select('#', ...) - 1 -- set(true, ...) should be "in set", set(false, ...) should be "not in set" -- it's more intuitive this way negate = not ... else--]] t = {...} n = select('#', ...) --end if n == 0 then return E("Set cannot be empty") end for i=1, n do local v = t[i] if type(v) == "string" then local l = #v if l == 1 then t[i] = escape(v) elseif l == 2 or l == 3 then local lbound, ubound = ssub(v,1,1), ssub(v,2,2) if l == 3 then if ubound ~= "-" then return E("Not a range") end ubound = ssub(v,3,3) v = lbound .. ubound l = #v end t[i] = escaperange(lbound, ubound) else return E("Not a character or range") end elseif type(v) == "table" then if v.t < 4 then return E("Not a character") end t[i] = v.p else return E("Not a character or range") end end --return new((negate and "[^" or "[") .. tconcat(t, "") .. "]", 3) return new("[" .. tconcat(t, "") .. "]", 3) end local function frontier(s) if s.t == 3 and ssub(s.p,1,1) == "[" and ssub(s.p,-1,-1) == "]" then return new("%f" .. s.p, 2) else return E("Not a set") end end local function bpairs(a,b) if #a == 1 and #b == 1 then return new("%b" .. a .. b, 2) else return E("Not a character") end end local function character(c) if #c ~= 1 then return E("Not a character") end return new(escape(c), 5) end local quantifiers = { ["+"] = "+", ["-"] = "-", ["*"] = "*", ["?"] = "?", ["1+"] = "+", ["0+"] = "*", optional = "?", ["shortest0+"] = "-", nongreedy = "-", shortest = "-", } local function quantify(t, q) local qt = quantifiers[q] if qt and t.t > 2 then return new(t.p .. qt, 2) else return E("Not quantifiable") end end mt.__index.quantify = quantify local presets = { any = new(".", 3), letter = new("%a", 4), control = new("%c", 4), digit = new("%d", 4), printable_no_space = new("%g", 4), lowercase = new("%l", 4), punctuation = new("%p", 4), space = new("%s", 4), uppercase = new("%u", 4), alphanumeric = new("%w", 4), hexadecimal = new("%x", 4), startwith = new("", 1, "^"), endwith = new("", 1, nil, "$"), pos = new("()", 2), } return { raw = raw, str = str, group = group, set = set, character = character, frontier = frontier, bpairs = bpairs, presets = presets } end)(...) -- Structs local struct = (function(...) local mt = {} -- TODO end)(...) return {pattern = pattern, struct = struct}
--[[Author: Pizzalol Date: 26.02.2015. Purges positive buffs from the target]] function DoomPurge( keys ) local target = keys.target -- Purge local RemovePositiveBuffs = true local RemoveDebuffs = false local BuffsCreatedThisFrameOnly = false local RemoveStuns = false local RemoveExceptions = false target:Purge( RemovePositiveBuffs, RemoveDebuffs, BuffsCreatedThisFrameOnly, RemoveStuns, RemoveExceptions) end --[[Author: Pizzalol Date: 26.02.2015. The deny check is run every frame, if the target is within deny range then apply the deniable state for the duration of 2 frames]] function DoomDenyCheck( keys ) local caster = keys.caster local target = keys.target local ability = keys.ability local ability_level = ability:GetLevel() - 1 local deny_pct = ability:GetLevelSpecialValueFor("deniable_pct", ability_level) local modifier = keys.modifier local target_hp = target:GetHealth() local target_max_hp = target:GetMaxHealth() local target_hp_pct = (target_hp / target_max_hp) * 100 if target_hp_pct <= deny_pct then ability:ApplyDataDrivenModifier(caster, target, modifier, {duration = 0.06}) end end -- Stops the sound from playing function StopSound( keys ) local target = keys.target local sound = keys.sound StopSoundEvent(sound, target) end
---------------------------------------------------------------------------------------------------- -- -- Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. -- -- SPDX-License-Identifier: Apache-2.0 OR MIT -- -- -- ---------------------------------------------------------------------------------------------------- local FadeButton = { Properties = { FaderEntity = {default = EntityId()}, FadeValueSlider = {default = EntityId()}, FadeSpeedMinusButton = {default = EntityId()}, FadeSpeedPlusButton = {default = EntityId()}, FadeSpeedText = {default = EntityId()}, }, } function FadeButton:OnActivate() -- Connect to the button notification bus on our entity to know when to start the animation self.animButtonHandler = UiButtonNotificationBus.Connect(self, self.entityId) -- Connect to the slider notification bus to know what fade value to give to the animation self.sliderHandler = UiSliderNotificationBus.Connect(self, self.Properties.FadeValueSlider) -- Connect to the button notification buses of the minus and plus buttons to know when to change the fade speed self.minusButtonHandler = UiButtonNotificationBus.Connect(self, self.Properties.FadeSpeedMinusButton) self.plusButtonHandler = UiButtonNotificationBus.Connect(self, self.Properties.FadeSpeedPlusButton) -- Initialize the fade value (needs to be the same as the start fade value slider value) self.fadeValue = 0 -- Initialize the fade speed (needs to be the same as the start fade speed text) self.fadeSpeed = 5 end function FadeButton:OnDeactivate() -- Disconnect from all our buses self.animButtonHandler:Disconnect() self.sliderHandler:Disconnect() self.minusButtonHandler:Disconnect() self.plusButtonHandler:Disconnect() end function FadeButton:OnSliderValueChanging(percent) -- Set the fade value to the slider value self.fadeValue = percent / 100 end function FadeButton:OnSliderValueChanged(percent) -- Set the fade value to the slider value self.fadeValue = percent / 100 end function FadeButton:OnButtonClick() -- If the animation button was clicked if (UiButtonNotificationBus.GetCurrentBusId() == self.entityId) then -- Start the fade animation UiFaderBus.Event.Fade(self.Properties.FaderEntity, self.fadeValue, self.fadeSpeed) -- Else if the minus button was clicked elseif (UiButtonNotificationBus.GetCurrentBusId() == self.Properties.FadeSpeedMinusButton) then -- Decrement the animation speed (min = 1) self.fadeSpeed = math.max(1, self.fadeSpeed - 1) -- And update the text UiTextBus.Event.SetText(self.Properties.FadeSpeedText, self.fadeSpeed) -- Else the plus button was clicked else -- Decrement the animation speed (max = 10) self.fadeSpeed = math.min(self.fadeSpeed + 1, 10) -- And update the text UiTextBus.Event.SetText(self.Properties.FadeSpeedText, self.fadeSpeed) end end return FadeButton
local function Init() FCPhysics2D.CreateRopeJoint( "level_root", "level_peg1", 6, -2, 0, 0 ) FCPhysics2D.CreateRopeJoint( "level_peg1", "level_peg2", 0, 0, 0, 0 ) FCPhysics2D.CreateRopeJoint( "level_peg2", "level_peg3", 0, 0, 0, 0 ) FCPhysics2D.CreateRopeJoint( "level_peg3", "level_peg4", 0, 0, 0, 0 ) FCPhysics2D.CreateRopeJoint( "level_peg4", "level_peg5", 0, 0, 0, 0 ) FCPhysics2D.CreateRopeJoint( "level_peg5", "level_peg6", 0, 0, 0, 0 ) FCPhysics2D.CreateRopeJoint( "level_peg6", "level_peg7", 0, 0, 0, 0 ) FCPhysics2D.CreateRopeJoint( "level_peg7", "level_peg8", 0, 0, 0, 0 ) FCPhysics2D.CreateRopeJoint( "level_peg8", "level_peg9", 0, 0, 0, 0 ) FCPhysics2D.CreateRopeJoint( "level_peg9", "level_peg10", 0, 0, 0, 0 ) FCPhysics2D.CreateRopeJoint( "level_peg10", "level_peg11", 0, 0, 0, 0 ) FCPhysics2D.CreateRopeJoint( "level_root", "level_peg11", -6, -2, 0, 0 ) end world_worm = World:new() world_worm:SetResource( "world_worm" ) world_worm:SetInitFunc( Init )
-- Mario Kart 8 [000500001010ED00][PAL] ---------------------------------------- -- Infinite Star Power [no_countdown.lua] -- Set the Star Power countdown to the given value. -- Usage: none -- Author: Divengerss -- [[0x3EAAD7E0] + 0x20] + 0x160 = value ------------------------------------- debug = false timer = 0xFFFF ------------------------------------- ptr = ReadFromRAM(INT32, ReadFromRAM(INT32, 0x3EAAD7E0) + 0x20) + 0x162 if ptr > 0x43000000 then if debug then LogToGUI(string.format("Address 0x%X", ptr)) end WriteToRAM(INT16, ptr, timer) elseif debug then LogToGUI("Invalid address") end
--------------------------------------------------------------------------------------------------- ---tuning_matrix.lua ---author: Karl ---date: 2021.8.29 ---reference: src/imgui/ui/Console.lua ---desc: Defines a matrix ui for tuning parameter matrices --------------------------------------------------------------------------------------------------- local Widget = require('imgui.Widget') ---@class im.TuningMatrix:im.Widget local M = LuaClass("im.TuningMatrix", Widget) local MIN_ROW_COUNT = 1 local MIN_COL_COUNT = 3 M.NON_APPLICABLE_STR = "-" M.EMPTY_CELL_STR = "" local NON_APPLICABLE_STR = M.NON_APPLICABLE_STR local EMPTY_CELL_STR = M.EMPTY_CELL_STR local DEFAULT_LABEL = "label" --------------------------------------------------------------------------------------------------- local im = imgui local IndicesArray = require("BHElib.scenes.tuning_stage.imgui.tuning_matrix_indices_array") local CodeSnapshotBuffer = require("BHElib.scenes.tuning_stage.imgui.code_snapshot_buffer") --------------------------------------------------------------------------------------------------- ---cache variables and functions local StringByte = string.byte --------------------------------------------------------------------------------------------------- ---init ---@param tuning_ui TuningUI function M:ctor(tuning_ui, matrix_title, matrix_id, ...) self.matrix = { {"s_script", NON_APPLICABLE_STR, EMPTY_CELL_STR}, } self.num_col = 3 self.num_row = 1 self.matrix_title = matrix_title self.tail_script = EMPTY_CELL_STR self.indices = IndicesArray() -- temporary state, no need to be saved/loaded self.tuning_ui = tuning_ui self.matrix_id = matrix_id self.cell_width = 180 -- output control self.output_control = CodeSnapshotBuffer(tuning_ui, "Output Control", self:getSyncFilePath()) self.output_control:changeSync(true) Widget.ctor(self, ...) self:addChild(function() self:_render() end) end --------------------------------------------------------------------------------------------------- ---setters and getters function M:getSyncFilePath() return "data/BHElib/scenes/tuning_stage/code/output_control_"..self.matrix_id..".lua" end function M:setWindowTitle(title) self.matrix_title = title local window_title = self:getWindowTitle() self:getParent():setName(window_title) end function M:getWindowTitle() return "m"..tostring(self.matrix_id).."_"..self.matrix_title end function M:setIndicesArray(indices) self.indices = indices end ---@return TuningMatrixIndicesArray function M:getIndicesArray() return self.indices end ---copy values from the input matrix to self.matrix ---@param matrix table entries can be only strings or have nil, numbers that can be turned to strings function M:copyFromMatrix(matrix) local target_matrix = self.matrix for i = 1, min(#matrix, self.num_row) do local row = matrix[i] local target_row = target_matrix[i] local row_label = row[1] assert(type(row_label) == "string", "Error: matrix labels should be strings! got "..tostring(row_label).." instead.") for j = 1, min(#row, self.num_col) do if j == 2 and StringByte(row_label, 2) == 95 then target_row[j] = NON_APPLICABLE_STR else target_row[j] = tostring(row[j]) end end if self.num_col > #row then if row_label == "s_script" then for j = #row + 1, self.num_col do target_row[j] = EMPTY_CELL_STR end else for j = #row + 1, self.num_col do target_row[j] = EMPTY_CELL_STR end end end end end ---@param num_row number ---@param num_col number function M:resizeTo(num_row, num_col) assert(num_row >= 1 and num_col >= 2, "Error: Invalid matrix size!") self.num_col = num_col self.num_row = num_row local matrix = self.matrix local new_matrix = {} for i = 1, num_row do local row = {} row[1] = DEFAULT_LABEL for j = 2, num_col do row[j] = EMPTY_CELL_STR end new_matrix[i] = row end self.matrix = new_matrix self:copyFromMatrix(matrix) -- copy from the old matrix end ---@param i number row number ---@param str string the string to set to function M:setRowLabel(i, str) local row = self.matrix[i] row[1] = str if StringByte(str, 2) == 95 then row[2] = NON_APPLICABLE_STR else if row[2] == NON_APPLICABLE_STR then row[2] = EMPTY_CELL_STR end end end ---@param index number insert row before this index function M:insertRow(index) assert(index >= 1 and index <= self.num_row + 1, "Error: Insert row index out of range!") local n = self.num_row + 1 self.num_row = n local row = {} row[1] = DEFAULT_LABEL for j = 2, self.num_col do row[j] = EMPTY_CELL_STR end table.insert(self.matrix, index, row) end ---@param index number remove row at this index function M:removeRow(index) local n = self.num_row - 1 self.num_row = n table.remove(self.matrix, index) end ---@param index number insert column before this index function M:insertColumn(index) assert(index >= MIN_COL_COUNT, "Error: The first two columns can not be inserted between!") assert(index <= self.num_col + 1, "Error: Insert column index out of range!") local n = self.num_col + 1 self.num_col = n local matrix = self.matrix for i = 1, self.num_row do local row = matrix[i] local label = row[1] if label == "s_script" then table.insert(row, index, EMPTY_CELL_STR) elseif label == "s_n" then table.insert(row, index, "1") else table.insert(row, index, EMPTY_CELL_STR) end end end ---@param index number remove column at this index function M:removeColumn(index) assert(index >= MIN_COL_COUNT, "Error: The first two columns can not be removed!") local n = self.num_col - 1 self.num_col = n local matrix = self.matrix for i = 1, self.num_row do table.remove(matrix[i], index) end end --------------------------------------------------------------------------------------------------- ---imgui render function M:renderResizeButtons() local cell_width = self.cell_width local button_width = cell_width * 0.5 - 4 local ret ret = im.button("+row") if ret then self:insertRow(self.num_row + 1, im.vec2(button_width, 24)) end im.sameLine() ret = im.button("+col") if ret then self:insertColumn(self.num_col + 1, im.vec2(button_width, 24)) end end function M:_render() local remove_flag = false if im.beginMenuBar() then if im.beginMenu("Matrix") then if im.menuItem("Create Copy") then local MatrixSave = require("BHElib.scenes.tuning_stage.imgui.tuning_matrix_save") local save = MatrixSave(self) self.tuning_ui:appendMatrixWindow(save, self.matrix_title) end im.endMenu() end im.sameLine() if im.beginMenu("Del") then if im.menuItem("Confirm") then remove_flag = true end im.endMenu() end im.sameLine() if im.beginMenu("Parents") then local indices = self.indices local matrices = self.tuning_ui:getMatrices() local to_del = nil for i = 1, indices:getNumIndices() do local title if indices:isMatrix(i) then local matrix = matrices[indices:getMatrixIndex(i)] title = matrix:getWindowTitle() elseif indices:isBoss(i) then title = "Boss" elseif indices:isMouse(i) then title = "Mouse" end if im.beginMenu(title.."##"..tostring(i)) then if im.menuItem("Confirm Deletion") then to_del = i end im.endMenu() end end if im.beginMenu("Add Parent") then if im.menuItem("Boss") then indices:appendBoss() end if im.menuItem("Mouse") then indices:appendMouse() end for i = 1, #matrices do local title = matrices[i]:getWindowTitle() if im.menuItem(title) then indices:appendMatrix(i) end end im.endMenu() end if to_del then indices:removeIndex(to_del) end im.endMenu() end im.endMenuBar() end im.setWindowFontScale(1.2) im.separator() local cell_width = self.cell_width do im.setNextItemWidth(cell_width * 2 + 8) local changed, str = im.inputText("Title", self.matrix_title, im.ImGuiInputTextFlags.EnterReturnsTrue) if changed then self:setWindowTitle(str) end end do im.setNextItemWidth(cell_width * 2 + 8) local changed, str = im.inputText("Tail Script", self.tail_script, im.ImGuiInputTextFlags.None) if changed then self.tail_script = str end end local matrix = self.matrix local to_insert = nil local to_remove = nil for i = 1, self.num_row do local row = matrix[i] for j = 1, self.num_col do local label = "##i"..i.."_"..j im.setNextItemWidth(cell_width) local text = row[j] if j == 1 then local changed, str = im.inputText(label, text, im.ImGuiInputTextFlags.EnterReturnsTrue) if changed then self:setRowLabel(i, str) end else local changed, str = im.inputText(label, text, im.ImGuiInputTextFlags.None) if changed then if j == 2 then local row_label = row[1] if StringByte(row_label, 2) == 95 then -- do nothing else row[j] = str end else row[j] = str end end end im.sameLine() end local is_pressed = im.button("+before##row"..i.."+") if is_pressed then to_insert = i end im.sameLine() is_pressed = im.button("-##row"..i.."-") if is_pressed then to_remove = i end end if to_insert then self:insertRow(to_insert) elseif to_remove then self:removeRow(to_remove) end local control = self.output_control control:renderSyncButtons(cell_width * 2 + 8) im.sameLine() to_insert = nil to_remove = nil local button1_width = cell_width * 0.8 - 4 local button2_width = cell_width * 0.2 - 4 for i = 3, self.num_col do local is_pressed = im.button("+before##col"..i.."+", im.vec2(button1_width, 24)) if is_pressed then to_insert = i end im.sameLine() is_pressed = im.button("-##col"..i.."-", im.vec2(button2_width, 24)) if is_pressed then to_remove = i end if i ~= self.num_col then im.sameLine() end end if to_insert then self:insertColumn(to_insert) elseif to_remove then self:removeColumn(to_remove) end im.sameLine() self:renderResizeButtons() if not control:isSync() then control:renderEditButtons() end -- after render all other things if remove_flag then self.tuning_ui:removeMatrixWindow(self) end end return M
-- ====================================================================== -- Copyright (c) 2012 RapidFire Studio Limited -- All Rights Reserved. -- http://www.rapidfirestudio.com -- Permission is hereby granted, free of charge, to any person obtaining -- a copy of this software and associated documentation files (the -- "Software"), to deal in the Software without restriction, including -- without limitation the rights to use, copy, modify, merge, publish, -- distribute, sublicense, and/or sell copies of the Software, and to -- permit persons to whom the Software is furnished to do so, subject to -- the following conditions: -- The above copyright notice and this permission notice shall be -- included in all copies or substantial portions of the Software. -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -- IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -- CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -- TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -- SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -- ====================================================================== astar = require "a-star" local graph = {} graph[1] = {} graph[1].id = 1 graph[1].x = 0 graph[1].y = 0 graph[1].player_id = 1 graph[2] = {} graph[2].id = 2 graph[2].x = 200 graph[2].y = 200 graph[2].player_id = 1 graph[3] = {} graph[3].id = 3 graph[3].x = -200 graph[3].y = 200 graph[3].player_id = 1 graph[4] = {} graph[4].id = 4 graph[4].x = 200 graph[4].y = -200 graph[4].player_id = 2 graph[5] = {} graph[5].id = 5 graph[5].x = -200 graph[5].y = -200 graph[5].player_id = 2 local valid_node_func = function(node, neighbor) local MAX_DIST = 300 if neighbor.player_id == node.player_id and astar.distance ( node.x, node.y, neighbor.x, neighbor.y ) < MAX_DIST then return true end return false end local path = astar.path(graph[2], graph[3], graph, true, valid_node_func) if not path then print("No valid path found") else for i, node in ipairs ( path ) do print("Step " .. i .. " >> " .. node.id) end end
local uci = require "luci.model.uci" local _go = require "get-opt-alt" vtest = 1 local vy = require "vyacht" _uci_real = cursor or _uci_real or uci.cursor() -- option lua_prefix /lua -- option lua_handler /www/vyacht.lua _uci_real:set("uhttpd", "main", "lua_prefix", "/lua") _uci_real:set("uhttpd", "main", "lua_handler", "/www/vyacht.lua") _uci_real:commit("uhttpd") os.execute("/etc/init.d/uhttpd restart"); -- vi /etc/inittab local file = io.open("/etc/inittab", "w") if file ~= nil then file:write("::sysinit:/etc/init.d/rcS S boot\n") file:write("::shutdown:/etc/init.d/rcS K shutdown\n") file:flush() io.close(file) end -- vi /etc/config/vyacht local opts = _go.getopt(arg, options) local eths = -1 if opts["eth"] == nil then print("no number of ethernet devices given") return else eths = tonumber(opts["eth"]) end if eths < 0 or eths > 2 then print("wrong number of ethernet devices given") return end local hw = readHardwareOptions() if eths == 1 then hw.network.devices = {"radio0", "eth0.2"} elseif eths == 2 then hw.network.devices = {"radio0", "eth0.1", "eth0.2"} else hw.network.devices = {"radio0"} end writeHardwareOptions(hw) -- rather check if the wanted file is there before removing local f=io.open("/www/index2.html", "r") if f~=nil then io.close(f) os.remove("/www/index.html") os.rename("/www/index2.html", "/www/index.html") end resetSystem()
return { -- Packer can manage itself as an optional plugin { "wbthomason/packer.nvim" }, -- TODO: refactor all of this (for now it works, but yes I know it could be wrapped in a simpler function) { "neovim/nvim-lspconfig" }, { "kabouzeid/nvim-lspinstall", event = "VimEnter", config = function() local lspinstall = require "lspinstall" lspinstall.setup() if O.plugin.lspinstall.on_config_done then O.plugin.lspinstall.on_config_done(lspinstall) end end, }, { "nvim-lua/popup.nvim" }, { "nvim-lua/plenary.nvim" }, { "tjdevries/astronauta.nvim" }, -- Telescope { "nvim-telescope/telescope.nvim", config = function() require("core.telescope").setup() if O.plugin.telescope.on_config_done then O.plugin.telescope.on_config_done(require "telescope") end end, }, -- Autocomplete { "hrsh7th/nvim-compe", -- event = "InsertEnter", config = function() require("core.compe").setup() if O.plugin.compe.on_config_done then O.plugin.compe.on_config_done(require "compe") end end, }, -- Autopairs { "windwp/nvim-autopairs", -- event = "InsertEnter", config = function() require "core.autopairs" if O.plugin.autopairs.on_config_done then O.plugin.autopairs.on_config_done(require "nvim-autopairs") end end, }, -- Snippets { "hrsh7th/vim-vsnip", event = "InsertEnter" }, { "rafamadriz/friendly-snippets", event = "InsertEnter" }, -- Treesitter { "nvim-treesitter/nvim-treesitter", config = function() require("core.treesitter").setup() if O.plugin.treesitter.on_config_done then O.plugin.treesitter.on_config_done(require "nvim-treesitter.configs") end end, }, -- Formatter.nvim { "mhartington/formatter.nvim", config = function() require "core.formatter" if O.plugin.formatter.on_config_done then O.plugin.formatter.on_config_done(require "formatter") end end, }, -- Linter { "mfussenegger/nvim-lint", config = function() require("core.linter").setup() if O.plugin.lint.on_config_done then O.plugin.lint.on_config_done(require "lint") end end, }, -- NvimTree { "kyazdani42/nvim-tree.lua", -- event = "BufWinOpen", -- cmd = "NvimTreeToggle", -- commit = "fd7f60e242205ea9efc9649101c81a07d5f458bb", config = function() require("core.nvimtree").setup() if O.plugin.nvimtree.on_config_done then O.plugin.nvimtree.on_config_done(require "nvim-tree.config") end end, }, { "lewis6991/gitsigns.nvim", config = function() require("core.gitsigns").setup() if O.plugin.gitsigns.on_config_done then O.plugin.gitsigns.on_config_done(require "gitsigns") end end, event = "BufRead", }, -- whichkey { "folke/which-key.nvim", config = function() require("core.which-key").setup() if O.plugin.which_key.on_config_done then O.plugin.which_key.on_config_done(require "which-key") end end, event = "BufWinEnter", }, -- Comments { "terrortylor/nvim-comment", event = "BufRead", config = function() local status_ok, nvim_comment = pcall(require, "nvim_comment") if not status_ok then return end nvim_comment.setup() if O.plugin.comment.on_config_done then O.plugin.comment.on_config_done(nvim_comment) end end, }, -- vim-rooter { "airblade/vim-rooter", config = function() vim.g.rooter_silent_chdir = 1 if O.plugin.rooter.on_config_done then O.plugin.rooter.on_config_done() end end, }, -- Icons { "kyazdani42/nvim-web-devicons" }, -- Status Line and Bufferline { "glepnir/galaxyline.nvim", config = function() require "core.galaxyline" if O.plugin.galaxyline.on_config_done then O.plugin.galaxyline.on_config_done(require "galaxyline") end end, event = "BufWinEnter", disable = not O.plugin.galaxyline.active, }, { "romgrk/barbar.nvim", config = function() require "core.bufferline" if O.plugin.bufferline.on_config_done then O.plugin.bufferline.on_config_done() end end, event = "BufWinEnter", }, -- Debugging { "mfussenegger/nvim-dap", -- event = "BufWinEnter", config = function() require("core.dap").setup() if O.plugin.dap.on_config_done then O.plugin.dap.on_config_done(require "dap") end end, disable = not O.plugin.dap.active, }, -- Debugger management { "Pocco81/DAPInstall.nvim", -- event = "BufWinEnter", -- event = "BufRead", disable = not O.plugin.dap.active, }, -- Builtins, these do not load by default -- Dashboard { "ChristianChiarulli/dashboard-nvim", event = "BufWinEnter", config = function() require("core.dashboard").setup() if O.plugin.dashboard.on_config_done then O.plugin.dashboard.on_config_done(require "dashboard") end end, disable = not O.plugin.dashboard.active, }, -- TODO: remove in favor of akinsho/nvim-toggleterm.lua -- Floating terminal -- { -- "numToStr/FTerm.nvim", -- event = "BufWinEnter", -- config = function() -- require("core.floatterm").setup() -- end, -- disable = not O.plugin.floatterm.active, -- }, { "akinsho/nvim-toggleterm.lua", event = "BufWinEnter", config = function() require("core.terminal").setup() if O.plugin.terminal.on_config_done then O.plugin.terminal.on_config_done(require "toggleterm") end end, disable = not O.plugin.terminal.active, }, -- Zen Mode { "folke/zen-mode.nvim", cmd = "ZenMode", event = "BufRead", config = function() require("core.zen").setup() if O.plugin.zen.on_config_done then O.plugin.zen.on_config_done(require "zen-mode") end end, disable = not O.plugin.zen.active, }, --------------------------------------------------------------------------------- -- LANGUAGE SPECIFIC GOES HERE { "lervag/vimtex", ft = "tex", }, -- Rust tools -- TODO: use lazy loading maybe? { "simrat39/rust-tools.nvim", disable = not O.lang.rust.rust_tools.active, }, -- Elixir { "elixir-editors/vim-elixir", ft = { "elixir", "eelixir", "euphoria3" } }, -- Javascript / Typescript { "jose-elias-alvarez/nvim-lsp-ts-utils", ft = { "javascript", "javascriptreact", "javascript.jsx", "typescript", "typescriptreact", "typescript.tsx", }, }, -- Java { "mfussenegger/nvim-jdtls", -- ft = { "java" }, disable = not O.lang.java.java_tools.active, }, -- Scala { "scalameta/nvim-metals", disable = not O.lang.scala.metals.active, }, }
local packer = require("packer") local use = packer.use -- using { } for using different branch , loading plugin with certain commands etc return packer.startup(function() use "wbthomason/packer.nvim" -- color related stuff use "~/code/micke/nightfox.nvim" use "norcalli/nvim-colorizer.lua" -- lang stuff use { "nvim-treesitter/nvim-treesitter", config = function() require "plugins.configs.treesitter" end, run = ":TSUpdate" } use { "nvim-treesitter/nvim-treesitter-textobjects", after = "nvim-treesitter", } use { "nvim-treesitter/playground", after = "nvim-treesitter", } use { "JoosepAlviste/nvim-ts-context-commentstring", after = "nvim-treesitter", } use { "windwp/nvim-ts-autotag", after = "nvim-treesitter" } use { "rafamadriz/friendly-snippets", } use { "hrsh7th/nvim-cmp", config = function() require "plugins.configs.cmp" end, } use { "L3MON4D3/LuaSnip", wants = "friendly-snippets", config = function() require("plugins.configs.others").luasnip() end, } use { "saadparwaiz1/cmp_luasnip", } use { "hrsh7th/cmp-nvim-lsp", } use { "hrsh7th/cmp-buffer", } use { "hrsh7th/cmp-path", } use { "hrsh7th/cmp-vsnip", } use { "andersevenrud/compe-tmux", branch = "cmp" } use { "neovim/nvim-lspconfig", } use "onsails/lspkind-nvim" use { "williamboman/nvim-lsp-installer", } use { "andymass/vim-matchup", event = "CursorMoved" } -- languages not supported by treesitter use "sheerun/vim-polyglot" use "lewis6991/gitsigns.nvim" use "hoob3rt/lualine.nvim" use { "windwp/nvim-autopairs", config = function() require("plugins.configs.others").autopairs() end, } use "AndrewRadev/splitjoin.vim" use "AndrewRadev/dsf.vim" use "AndrewRadev/switch.vim" use "AndrewRadev/deleft.vim" use "FooSoft/vim-argwrap" use { "rmagatti/goto-preview", after = "telescope.nvim", config = function() require("goto-preview").setup({ default_mappings = true, }) end } -- Comment use "terrortylor/nvim-comment" -- file managing , picker etc use "kyazdani42/nvim-web-devicons" use { "kyazdani42/nvim-tree.lua", config = function() require("plugins.configs.nvimtree") end, } use { "nvim-telescope/telescope.nvim", requires = { {"nvim-lua/popup.nvim"}, {"nvim-lua/plenary.nvim"}, {"nvim-telescope/telescope-fzf-native.nvim", run = "make"}, }, cmd = "Telescope", config = function() require("telescope-nvim").config() end } -- misc use "907th/vim-auto-save" use "karb94/neoscroll.nvim" use "folke/which-key.nvim" use { "lukas-reineke/indent-blankline.nvim", event = "BufRead", config = function() require("plugins.configs.others").blankline() end, } use "christoomey/vim-tmux-navigator" -- testing use { "preservim/vimux" } use { "vim-test/vim-test" } use "tpope/vim-unimpaired" use "tpope/vim-repeat" use "tpope/vim-surround" use "tpope/vim-bundler" use "tpope/vim-rails" use "tpope/vim-rake" use "tpope/vim-dispatch" use "tpope/vim-rhubarb" use "tpope/vim-projectionist" use "tpope/vim-abolish" use "tpope/vim-rbenv" use "tpope/vim-git" use "tpope/vim-rsi" use "tpope/vim-fugitive" use "pgdouyon/vim-evanesco" use { "folke/trouble.nvim", config = function() require("trouble").setup { mode = {"lsp_workspace_diagnostics", "lsp_workspace_diagnostics", "lsp_document_diagnostics", "quickfix", "lsp_references", "loclist"} } end } -- use { -- "TimUntersberger/neogit", -- requires = "nvim-lua/plenary.nvim", -- config = function() -- require("neo-git").config() -- end -- } end, { display = { border = {"โ”Œ", "โ”€", "โ”", "โ”‚", "โ”˜", "โ”€", "โ””", "โ”‚"} } })
classtools = require 'classtools' local Color = {} function Color:constructor(r, g, b, a) self.r = r self.g = g self.b = b self.a = a or 255 end function Color:expand() return self.r, self.g, self.b, self.a end local function equality(a, b) return a.r == b.r and a.g == b.g and a.b == b.b and a.a == b.a end local function to_string(t) return tostring(t.r) .. ' ' .. tostring(t.g) .. ' ' .. tostring(t.b) end setmetatable(Color, {__eq = equality, __tostring = to_string}) classtools.callable(Color) return Color
AddCSLuaFile() local name = "Dodge Charger SRT8 2012 Police" local A = "AMBER" local R = "RED" local B = "BLUE" local W = "WHITE" local SW = "S_WHITE" local EMV = {} EMV.Siren = 7 EMV.Color = nil EMV.Skin = 0 EMV.BodyGroups = {} EMV.Props = {} EMV.Meta = { grille_leds = { AngleOffset = -90, W = 5.7, H = 5.4, Sprite = "sprites/emv/tdm_grille_leds", Scale = 1, WMult = 1.4, }, side_leds = { AngleOffset = -90, W = 5.7, H = 5.4, Sprite = "sprites/emv/tdm_grille_leds", Scale = 1, WMult = 1.4, }, freedom_f_inner = { AngleOffset = -90, W = 7.2, H = 8.4, Sprite = "sprites/emv/whelen_freedom_main", Scale = 1.75, WMult = 1.24, }, freedom_f_corner = { AngleOffset = -90, W = 9.5, H = 8, Sprite = "sprites/emv/whelen_freedom_main", Scale = 1.75, WMult = 2, }, freedom_r_corner = { AngleOffset = 90, W = 9.5, H = 8, Sprite = "sprites/emv/whelen_freedom_main", Scale = 1.75, WMult = 2, }, freedom_r_inner = { AngleOffset = 90, W = 7.2, H = 8.4, Sprite = "sprites/emv/whelen_freedom_main", Scale = 1.75, WMult = 1.24, }, freedom_takedown = { AngleOffset = -90, W = 6.7, H = 7.5, Sprite = "sprites/emv/tdm_halogen2", Scale = 1.2, WMult = 1.3, }, freedom_r_halogen = { AngleOffset = 90, W = 6.4, H = 7.5, Sprite = "sprites/emv/tdm_halogen2", Scale = 1.2, WMult = 1.3, }, freedom_alley = { AngleOffset = -90, W = 5.5, H = 6, Sprite = "sprites/emv/whelen_freedom_alley", Scale = 1.2, WMult = 1.3, }, liberty_front = { AngleOffset = -90, W = 7.4, H = 7.5, Sprite = "sprites/emv/emv_whelen_src", Scale = 1, WMult = 1.66, }, liberty_rear = { AngleOffset = 90, W = 7.4, H = 7.5, Sprite = "sprites/emv/emv_whelen_src", Scale = 1, WMult = 1.66, }, liberty_f_corner = { AngleOffset = -90, W = 14.5, H = 14.4, Sprite = "sprites/emv/emv_whelen_corner", Scale = 1, WMult = 2.2, }, liberty_r_corner = { AngleOffset = 90, W = 14.5, H = 14.4, Sprite = "sprites/emv/emv_whelen_corner", Scale = 1, WMult = 2.2, }, liberty_takedown = { AngleOffset = -90, W = 7, H = 7, Sprite = "sprites/emv/emv_whelen_6x2", Scale = 1, WMult = 2.2, }, liberty_alley = { AngleOffset = -90, W = 2.2, H = 2.2, Sprite = "sprites/emv/emv_whelen_tri", Scale = 1, WMult = 1, }, rear_int_bar = { AngleOffset = 90, W = 4, H = 3, Sprite = "sprites/emv/tdm_charger_rear_int", Scale = 1, WMult = 1.5, }, front_inner_default = { AngleOffset = -90, W = 4.1, H = 3.2, Sprite = "sprites/emv/tdm_charger_rear_int", Scale = 1, WMult = 1.5, }, front_vipers = { AngleOffset = -90, W = 4, H = 4, Sprite = "sprites/emv/tdm_viper", Scale = 1, WMult = 1, }, front_viper_low = { AngleOffset = -90, W = 4, H = 4, Sprite = "sprites/emv/tdm_viper", Scale = 1, WMult = 1, }, rear_vipers = { AngleOffset = 90, W = 4, H = 4, Sprite = "sprites/emv/tdm_viper", Scale = 1, WMult = 1, }, bumper_vertex = { AngleOffset = -90, W = 2, H = 2, Sprite = "sprites/emv/emv_whelen_vertex", Scale = 1, WMult = 1, }, bumper_upper = { AngleOffset = -90, W = 4, H = 4, Sprite = "sprites/emv/emv_1x3", Scale = 1, WMult = 1, }, bumper_side = { AngleOffset = -90, W = 4.6, H = 4.6, Sprite = "sprites/emv/emv_whelen_src", Scale = 1, WMult = 1, }, valor_forward = { AngleOffset = -90, W = 5.2, H = 5, Sprite = "sprites/emv/fs_valor", Scale = 1, WMult = 1.5, }, valor_side = { AngleOffset = -90, W = 4.5, H = 5, Sprite = "sprites/emv/fs_valor", Scale = 1, WMult = 1.2, }, valor_backward = { AngleOffset = 90, W = 5.8, H = 5, Sprite = "sprites/emv/fs_valor", Scale = 1, WMult = 1.7, }, headlight = { AngleOffset = -90, W = 3.5, H = 3.5, Sprite = "sprites/emv/light_circle", Scale = 2.5, WMult = 1 }, tail_light = { AngleOffset = 90, W = 28, H = 16, Sprite = "sprites/emv/tdm_charger_tail", Scale = 1, SourceOnly = true, WMult = 1.5, }, tail_glow = { AngleOffset = 90, W = 0, H = 0, Sprite = "sprites/emv/light_circle", Scale = 2, WMult = 1 }, reverse = { AngleOffset = 90, W = 8, H = 7, Sprite = "sprites/emv/tdm_charger_reverse", Scale = 1, WMult = 1.2 }, spotlight = { AngleOffset = -90, W = 7, H = 7, Sprite = "sprites/emv/light_circle", Scale = 3, } } EMV.Positions = { [1] = { Vector( 8.75, 117.13, 32.07 ), Angle( 0, -12, 0 ), "grille_leds" }, -- 1 [2] = { Vector( -8.75, 117.13, 32.07 ), Angle( 0, 12, 0 ), "grille_leds" }, -- 2 [3] = { Vector( 38.29, -52.3, 56.7 ), Angle( -2.7, -92.5, 22 ), "side_leds" }, [4] = { Vector( -38.29, -52.3, 56.7 ), Angle( 2, 91, 22 ), "side_leds" }, [5] = { Vector( 22.7, -84, 59.1 ), Angle( 0, 0, 0 ), "rear_int_bar" }, [6] = { Vector( -22.7, -84, 59.1 ), Angle( 0, 0, 0 ), "rear_int_bar" }, [7] = { Vector( 18.78, -84, 59.1 ), Angle( 0, 0, 0 ), "rear_int_bar" }, [8] = { Vector( -18.78, -84, 59.1 ), Angle( 0, 0, 0 ), "rear_int_bar" }, [9] = { Vector( 14.81, -84, 59.1 ), Angle( 0, 0, 0 ), "rear_int_bar" }, [10] = { Vector( -14.81, -84, 59.1 ), Angle( 0, 0, 0 ), "rear_int_bar" }, [11] = { Vector( 10.9, -84, 59.1 ), Angle( 0, 0, 0 ), "rear_int_bar" }, [12] = { Vector( -10.9, -84, 59.1 ), Angle( 0, 0, 0 ), "rear_int_bar" }, [13] = { Vector( 7, -84, 59.1 ), Angle( 0, 0, 0 ), "rear_int_bar" }, [14] = { Vector( -7, -84, 59.1 ), Angle( 0, 0, 0 ), "rear_int_bar" }, [15] = { Vector( 5.18, 26.19, 66.56 ), Angle( 0, 0, 0 ), "front_inner_default" }, [16] = { Vector( -5.18, 26.19, 66.56 ), Angle( 0, 0, 0 ), "front_inner_default" }, [17] = { Vector( 24.87, 19.29, 66.97 ), Angle( 5, 0, 0 ), "front_vipers" }, [18] = { Vector( -24.87, 19.29, 66.97 ), Angle( -5, 0, 0 ), "front_vipers" }, [19] = { Vector( 2.05, 47.29, 55.07 ), Angle( 0, 0, 0 ), "front_viper_low" }, [20] = { Vector( -2.05, 47.29, 55.07 ), Angle( 0, 0, 0 ), "front_viper_low" }, [21] = { Vector( 22.58, -64.83, 66.18 ), Angle( 4, 0, 0 ), "rear_vipers" }, [22] = { Vector( -22.58, -64.83, 66.18 ), Angle( -4, 0, 0 ), "rear_vipers" }, [23] = { Vector( 18.5, -64.83, 66.45 ), Angle( 4, 0, 0 ), "rear_vipers" }, [24] = { Vector( -18.5, -64.83, 66.45 ), Angle( -4, 0, 0 ), "rear_vipers" }, [25] = { Vector( 25.65, 114.73, 34.57 ), Angle( -9.65, -75.94, 33.81 ), "bumper_vertex" }, [26] = { Vector( -25.65, 114.73, 34.57 ), Angle( 9.65, 75.94, 33.81 ), "bumper_vertex" }, [27] = { Vector( 8.55, 123.96, 41.57 ), Angle( 0, 0, 0 ), "bumper_upper" }, [28] = { Vector( -8.55, 123.96, 41.57 ), Angle( 0, 0, 0 ), "bumper_upper" }, [29] = { Vector( 20.05, 123.93, 35.01 ), Angle( -90, -90, 0 ), "bumper_side" }, [30] = { Vector( -20.15, 123.93, 35.01 ), Angle( 90, 90, 0 ), "bumper_side" }, -- WHELEN AMERICA -- [31] = { Vector( 9.64, -13.76, 78.4 ), Angle( 0, 0, 0 ), "freedom_f_inner" }, [32] = { Vector( -9.64, -13.76, 78.4 ), Angle( 0, 0, 0 ), "freedom_f_inner" }, [33] = { Vector( 25.15, -15.22, 78.41 ), Angle( 0, -16.3, 0 ), "freedom_f_corner" }, [34] = { Vector( -25.15, -15.22, 78.41 ), Angle( 0, 16.3, 0 ), "freedom_f_corner" }, [35] = { Vector( 25.15, -23.24, 78.41 ), Angle( 0, 16.3, 0 ), "freedom_r_corner" }, [36] = { Vector( -25.15, -23.24, 78.41 ), Angle( 0, -16.3, 0 ), "freedom_r_corner" }, [37] = { Vector( 9.64, -24.7, 78.41 ), Angle( 0, 0, 0 ), "freedom_r_inner" }, [38] = { Vector( -9.64, -24.7, 78.41 ), Angle( 0, 0, 0 ), "freedom_r_inner" }, [39] = { Vector( 16.79, -13.89, 78.43 ), Angle( 0, 0, 0 ), "freedom_takedown" }, [40] = { Vector( -16.79, -13.89, 78.43 ), Angle( 0, 0, 0 ), "freedom_takedown" }, [41] = { Vector( 16.79, -24.7, 78.43 ), Angle( 0, 0, 0 ), "freedom_r_halogen" }, [42] = { Vector( -16.79, -24.7, 78.43 ), Angle( 0, 0, 0 ), "freedom_r_halogen" }, [43] = { Vector( 29.8, -19.26, 78.42 ), Angle( 0, -90, 0 ), "freedom_alley" }, [44] = { Vector( -29.8, -19.26, 78.42 ), Angle( 0, 90, 0 ), "freedom_alley" }, -- WHELEN LIBERTY -- [45] = { Vector( 10.19, -13.72, 77.88 ), Angle( 0, 0, 0 ), "liberty_front" }, [46] = { Vector( -10.19, -13.72, 77.88 ), Angle( 0, 0, 0 ), "liberty_front" }, [47] = { Vector( 16.96, -13.72, 77.88 ), Angle( 0, 0, 0 ), "liberty_front" }, [48] = { Vector( -16.96, -13.72, 77.88 ), Angle( 0, 0, 0 ), "liberty_front" }, [49] = { Vector( 25.2, -16.03, 77.88 ), Angle( 0, -23, 0 ), "liberty_f_corner" }, [50] = { Vector( -25.2, -16.03, 77.88 ), Angle( 0, 23, 0 ), "liberty_f_corner" }, [51] = { Vector( 25.2, -22.47, 77.88 ), Angle( 0, 23, 0 ), "liberty_r_corner" }, [52] = { Vector( -25.2, -22.47, 77.88 ), Angle( 0, -23, 0 ), "liberty_r_corner" }, [53] = { Vector( 16.96, -24.72, 77.88 ), Angle( 0, 0, 0 ), "liberty_rear" }, [54] = { Vector( -16.96, -24.72, 77.88 ), Angle( 0, 0, 0 ), "liberty_rear" }, [55] = { Vector( 10.19, -24.72, 77.88 ), Angle( 0, 0, 0 ), "liberty_rear" }, [56] = { Vector( -10.19, -24.72, 77.88 ), Angle( 0, 0, 0 ), "liberty_rear" }, [57] = { Vector( 3.45, -24.72, 77.88 ), Angle( 0, 0, 0 ), "liberty_rear" }, [58] = { Vector( -3.45, -24.72, 77.88 ), Angle( 0, 0, 0 ), "liberty_rear" }, [59] = { Vector( 3.39, -13.61, 77.88 ), Angle( 0, 0, 0 ), "liberty_takedown" }, [60] = { Vector( -3.39, -13.61, 77.88 ), Angle( 0, 0, 0 ), "liberty_takedown" }, [61] = { Vector( 29.91, -19.26, 77.91 ), Angle( 0, -90, 0 ), "liberty_alley" }, [62] = { Vector( -29.91, -19.26, 77.91 ), Angle( 0, 90, 0 ), "liberty_alley" }, -- IT'S THE MOTHEFUCKING FEDERAL SIGNAL VALOR BABY AWWW FUCK YEAH -- [63] = { Vector( 2.36, -3.53, 77.56 ), Angle( 0, -40.07, 0 ), "valor_forward" }, [64] = { Vector( -2.36, -3.53, 77.56 ), Angle( 0, 40.07, 0 ), "valor_forward" }, [65] = { Vector( 6.5, -7.02, 77.56 ), Angle( 0, -40.07, 0 ), "valor_forward" }, [66] = { Vector( -6.5, -7.02, 77.56 ), Angle( 0, 40.07, 0 ), "valor_forward" }, [67] = { Vector( 10.64, -10.51, 77.56 ), Angle( 0, -40.07, 0 ), "valor_forward" }, [68] = { Vector( -10.64, -10.51, 77.56 ), Angle( 0, 40.07, 0 ), "valor_forward" }, [69] = { Vector( 14.78, -14, 77.56 ), Angle( 0, -40.07, 0 ), "valor_forward" }, [70] = { Vector( -14.78, -14, 77.56 ), Angle( 0, 40.07, 0 ), "valor_forward" }, [71] = { Vector( 19.52, -15.66, 77.56 ), Angle( 0, 0, 0 ), "valor_forward" }, [72] = { Vector( -19.52, -15.66, 77.56 ), Angle( 0, 0, 0 ), "valor_forward" }, [73] = { Vector( 25.28, -17.71, 77.56 ), Angle( 0, -40, 0 ), "valor_forward" }, [74] = { Vector( -25.28, -17.71, 77.56 ), Angle( 0, 40, 0 ), "valor_forward" }, [75] = { Vector( 27.32, -22.44, 77.56 ), Angle( 0, -85, 0 ), "valor_side" }, [76] = { Vector( -27.32, -22.44, 77.56 ), Angle( 0, 85, 0 ), "valor_side" }, [77] = { Vector( 22.1, -25.9, 77.56 ), Angle( 0, 0, 0 ), "valor_backward" }, [78] = { Vector( -22.1, -25.9, 77.56 ), Angle( 0, 0, 0 ), "valor_backward" }, [79] = { Vector( 15.8, -25.9, 77.56 ), Angle( 0, 0, 0 ), "valor_backward" }, [80] = { Vector( -15.8, -25.9, 77.56 ), Angle( 0, 0, 0 ), "valor_backward" }, [81] = { Vector( 9.48, -25.9, 77.56 ), Angle( 0, 0, 0 ), "valor_backward" }, [82] = { Vector( -9.48, -25.9, 77.56 ), Angle( 0, 0, 0 ), "valor_backward" }, [83] = { Vector( 3.16, -25.9, 77.56 ), Angle( 0, 0, 0 ), "valor_backward" }, [84] = { Vector( -3.16, -25.9, 77.56 ), Angle( 0, 0, 0 ), "valor_backward" }, [85] = { Vector( 36.9, 104.91, 38.5 ), Angle( 0, 2, 0 ), "headlight" }, [86] = { Vector( -36.9, 104.91, 38.5 ), Angle( 0, -2, 0 ), "headlight" }, [87] = { Vector( 37.3, -116.57, 46.6 ), Angle( 0, 13.2, 0 ), "tail_light" }, [88] = { Vector( -37.3, -116.57, 46.6 ), Angle( 180, -13.2, 0 ), "tail_light" }, [89] = { Vector( 33.5, -118.17, 46.6 ), Angle( 0, 13.2, 0 ), "tail_glow" }, [90] = { Vector( -33.5, -118.17, 46.6 ), Angle( 0, -13.2, 0 ), "tail_glow" }, [91] = { Vector( 23.92, -119.92, 46.9 ), Angle( 0, 10.7, 0 ), "reverse" }, [92] = { Vector( -23.92, -119.92, 46.9 ), Angle( 180, -10.7, 180 ), "reverse" }, [93] = { Vector( 39.74, 40.84, 62.89 ), Angle( 17.26, 0, 0 ), "spotlight" }, [94] = { Vector( -39.74, 40.84, 62.89 ), Angle( -17.26, 0, 0 ), "spotlight" }, } EMV.Sections = { ["headlights"] = { { { 85, SW, { 16, .25, 0 } }, { 86, SW, { 16, .25, 10 } } } }, ["reverse"] = { { { 87, R }, { 89, R }, { 92, B } }, { { 88, R }, { 90, R }, { 91, B } } }, ["grille_leds"] = { { { 1, B }, { 2, R } }, { { 1, B } }, { { 2, R } }, { { 1, B }, { 2, B } }, { { 1, R }, { 2, R } }, { { 1, B }, { 2, R } }, { { 2, B } }, { { 1, R } } }, ["bumper_vertex"] = { { { 25, B }, { 26, R } }, { { 26, R } }, { { 27, B } } }, ["bumper_upper"] = { { { 27, B }, { 28, R } }, { { 27, B } }, { { 28, R } } }, ["bumper_side"] = { { { 29, B }, { 30, R } } }, ["side_leds"] = { { { 3, R }, { 4, R } }, { { 3, B }, { 4, B } }, { { 3, W }, { 4, W } }, }, ["rear_int_bar"] = { { { 5, A }, { 6 , A }, { 7 , A }, { 8 , A }, { 9 , A }, { 10, A }, { 11, A }, { 12, A }, { 13, A }, { 14, A }, }, { { 5, B }, { 7, B }, { 9, B }, { 11, B }, { 13, B } }, { { 6, R }, { 8, R }, { 10, R }, { 12, R }, { 14, R } }, { { 5, B }, { 6, R }, { 13, B }, { 14, R } }, { { 7, B }, { 8, R }, { 9, B }, { 10, R }, { 11, B }, { 12, R } }, { { 5, B }, { 9, B }, { 13, B }, { 8, R }, { 12, R } }, { { 6, R }, { 10, R }, { 14, R }, { 7, B }, { 11, B } }, { { 5, B }, { 7, B } }, { { 6, R }, { 8, R } } }, ["traffic_rb"] = { { { 6, B } }, { { 5, R } } }, ["traffic"] = { -- { 6 , A }, { 7 , A }, { 8 , A }, { 9 , A }, { 10, A }, { 11, A }, { 12, A }, { 13, A }, --{ { 35, A }, { 36, A }, { 37, A }, { 38, A }, { 39, A }, { 40, A }, { 41, A }, { 42, A } }, -- 2 -> 8 -- 8 <- 2 { { 7, A } }, { { 7, A }, { 9, A } }, { { 9, A }, { 11, A } }, { { 11, A }, { 13, A } }, { { 13, A }, { 14, A } }, { { 14, A }, { 12, A } }, { { 12, A }, { 10, A } }, { { 10, A }, { 8, A } }, { { 8, A } }, -- 10 { { 13, A }, { 14, A } }, { { 11, A }, { 12, A } }, { { 9, A }, { 10, A } }, { { 7, A }, { 8, A } }, -- 14 { { 7, A }, { 9, A }, { 6, A }, { 10, A } }, { { 11, A }, { 13, A }, { 14, A }, { 12, A } }, -- 16 { { 7, A }, { 9, A }, { 14, A }, { 12, A } }, { { 11, A }, { 13, A }, { 10, A }, { 8, A } }, -- 18 { { 8, A }, { 10, A }, { 12, A }, { 14, A } }, { { 7, A }, { 9, A }, { 11, A }, { 13, A } }, -- 20 {}, { { 5, A }, { 6 , A }, { 7 , A }, { 8 , A }, { 9 , A }, { 10, A }, { 11, A }, { 12, A }, { 13, A }, { 14, A }, }, -- 1 -> 21 { { 5, B }, { 7, B }, { 9, B }, { 11, B }, { 13, B } }, { { 6, R }, { 8, R }, { 10, R }, { 12, R }, { 14, R } }, { { 5, B }, { 6, R }, { 13, B }, { 14, R } }, { { 7, B }, { 8, R }, { 9, B }, { 10, R }, { 11, B }, { 12, R } }, { { 5, B }, { 9, B }, { 13, B }, { 8, R }, { 12, R } }, { { 6, R }, { 10, R }, { 14, R }, { 7, B }, { 11, B } }, { { 5, B }, { 7, B } }, { { 6, R }, { 8, R } } }, ["rear_int_vipers"] = { { { 21, R }, { 22, B }, { 23, R }, { 24, B} }, { { 21, R }, { 22, B } }, { { 23, R }, { 24, B } }, }, ["front_inner_default"] = { { { 15, R }, { 16, B } }, { { 15, R } }, { { 16, B } } }, ["front_vipers"] = { { { 17, B }, { 18, R } }, { { 17, B } }, { { 18, R } } }, ["front_low_viper"] = { { { 19, B }, { 20, R } }, { { 19, B } }, { { 20, R } } }, -- WHELEN FREEDOM -- ["lightbar_freedom"] = { { { 31, B }, { 32, R }, { 33, B }, { 34, R }, { 35, B }, { 36, R }, { 37, B }, { 38, R }, { 39, W }, { 40, W }, { 41, R }, { 42, B }, { 43, W }, { 44, W } } }, ["lightbar_freedom_corner"] = { { { 33, B }, { 34, R }, { 35, B }, { 36, R } }, { { 33, B }, { 35, B } }, { { 34, R }, { 36, R } } }, ["lightbar_freedom_inner"] = { { { 37, B }, { 42, B } }, { { 38, R }, { 41, R } }, { { 37, B }, { 31, B }, { 42, B } }, { { 38, R }, { 32, R }, { 41, R } } }, ["lightbar_freedom_illum"] = { { { 39, W }, { 43, W } }, { { 40, W }, { 44, W } } }, -- WHELEN LIBERTY LIGHTBAR -- ["lightbar_liberty"] = { { { 45, B }, { 46, R }, { 47, B }, { 48, R }, { 49, B }, { 50, R }, { 51, B }, { 52, R }, { 53, B }, { 54, R }, { 55, B }, { 56, R }, { 57, B }, { 58, R }, { 59, W }, { 60, W }, { 61, W }, { 62, W } }, { { 45, B }, { 47, B }, { 49, B }, { 51, B }, { 53, B }, { 55, B }, { 57, B } }, { { 46, R }, { 48, R }, { 50, R }, { 52, R }, { 54, R }, { 56, R }, { 58, R } }, { { 53, B }, { 47, B } }, { { 54, R }, { 48, R } }, }, ["lightbar_liberty_corner"] = { { { 49, B, .5 }, { 50, R, .5 }, { 51, B, .5 }, { 52, R, .5 } }, { { 49, B, 1 }, { 50, R, .5 }, { 51, B, 1 }, { 52, R, .5 } }, { { 49, B, .5 }, { 50, R, 1 }, { 51, B, .5 }, { 52, R, 1 } }, { { 49, B }, { 51, B } }, { { 50, R }, { 52, R } } }, ["lightbar_liberty_inner"] = { { { 54, R }, { 56, R } }, { { 55, B }, { 53, B } }, { { 55, B }, { 57, B }, { 45, B } }, { { 56, R }, { 58, R }, { 46, R } }, }, ["lightbar_liberty_illum"] = { { { 59, W }, { 60, W }, { 61, W }, { 62, W } }, { { 59, W }, { 61, W } }, { { 60, W }, { 62, W } } }, -- MOTHERFUCKIN VALOR -- ["lightbar_valor"] = { { { 63, B }, { 64, R }, { 65, B }, { 66, R }, { 67, B }, { 68, R }, { 69, B }, { 70, R }, { 71, B }, { 72, R }, { 73, B }, { 74, R }, { 75, B }, { 76, R }, { 77, B }, { 78, R }, { 79, B }, { 80, R }, { 81, B }, { 82, R }, { 83, B }, { 84, R } }, { { 63, B }, { 65, B }, { 67, B }, { 69, B }, { 71, B }, { 73, B }, { 75, B }, { 77, B }, { 79, B }, { 81, B }, { 83, B } }, { { 64, R }, { 66, R }, { 68, R }, { 70, R }, { 72, R }, { 74, R }, { 76, R }, { 78, R }, { 80, R }, { 82, R }, { 84, R } }, { { 63, R }, { 65, R }, { 67, R }, { 69, R }, { 71, R }, { 73, R }, { 75, R }, { 77, R }, { 79, R }, { 81, R }, { 83, R } }, { { 64, B }, { 66, B }, { 68, B }, { 70, B }, { 72, B }, { 74, B }, { 76, B }, { 78, B }, { 80, B }, { 82, B }, { 84, B } }, -- 6 -> 9 { { 63, B }, { 67, B }, { 71, B }, { 75, B }, { 79, B }, { 83, B }, { 82, B }, { 78, B }, { 74, B }, { 70, B }, { 66, B } }, { { 64, R }, { 68, R }, { 72, R }, { 76, R }, { 80, R }, { 84, R }, { 81, R }, { 77, R }, { 73, R }, { 69, R }, { 65, R } }, { { 63, R }, { 67, R }, { 71, R }, { 75, R }, { 79, R }, { 83, R }, { 82, R }, { 78, R }, { 74, R }, { 70, R }, { 66, R } }, { { 64, B }, { 68, B }, { 72, B }, { 76, B }, { 80, B }, { 84, B }, { 81, B }, { 77, B }, { 73, B }, { 69, B }, { 65, B } }, -- 10 -> 13 { { 63, B }, { 67, R }, { 71, B }, { 75, R }, { 79, B }, { 83, R }, { 82, B }, { 78, R }, { 74, B }, { 70, R }, { 66, B } }, { { 64, R }, { 68, B }, { 72, R }, { 76, B }, { 80, R }, { 84, B }, { 81, R }, { 77, B }, { 73, R }, { 69, B }, { 65, R } }, { { 63, R }, { 67, B }, { 71, R }, { 75, B }, { 79, R }, { 83, B }, { 82, R }, { 78, B }, { 74, R }, { 70, B }, { 66, R } }, { { 64, B }, { 68, R }, { 72, B }, { 76, R }, { 80, B }, { 84, R }, { 81, B }, { 77, R }, { 73, B }, { 69, R }, { 65, B } }, -- 14 { { 63, B }, { 67, B }, { 71, R }, { 75, B }, { 79, B }, { 81, B }, { 64, R }, { 68, R }, { 72, B }, { 76, R }, { 80, R }, { 82, R } }, { { 65, R }, { 69, R }, { 73, B }, { 77, R }, {83, R }, { 84, B }, { 78, B }, { 74, R }, { 70, B }, { 66, B } }, -- 16 { { 63, W }, { 65, W }, { 67, W }, { 69, W }, { 71, W }, { 73, W }, { 75, W }, { 77, W }, { 79, W }, { 81, W }, { 83, W } }, { { 64, W }, { 66, W }, { 68, W }, { 70, W }, { 72, W }, { 74, W }, { 76, W }, { 78, W }, { 80, W }, { 82, W }, { 84, W } }, }, } EMV.Patterns = { ["headlights"] = { ["code3"] = { 1 } }, ["reverse"] = { ["flash"] = { 1, 0, 1, 0, 2, 0, 2, 0 } }, ["grille_leds"] = { ["flash"] = { 1, 0, 1, 0, 0, 0, }, ["code2"] = { 2, 2, 2, 0, 0, 3, 3, 3, 0, 0 }, ["code3"] = { 2, 0, 2, 0, 2, 0, 3, 0, 3, 0, 3, 0 } }, ["side_leds"] = { ["flash"] = { 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 2, 0, 2, 0, 2, 0, 0, 0, 0, 0, 3, 0, 3, 0, 3, 0, 0, 0, 0, 0 } }, ["rear_int_vipers"] = { ["all"] = { 1 }, ["code1"] = { 2, 2, 0, 3, 3, 0 }, ["code2"] = { 2, 0, 2, 0, 2, 0, 3, 0, 3, 0, 3, 0 } }, -- FRONT INNER -- ["front_inner_default"] = { ["all"] = { 1 }, ["code1"] = { 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0 }, ["code2"] = { 2, 2, 0, 3, 3, 0 }, ["code3"] = { 2, 0, 2, 0, 3, 0, 3, 0 } }, ["front_vipers"] = { ["all"] = { 1 }, ["code1"] = { 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0 }, ["code2"] = { 2, 2, 0, 3, 3, 0 }, ["code3"] = { 2, 0, 2, 0, 3, 0, 3, 0 } }, ["front_low_viper"] = { ["all"] = { 1 }, ["code1"] = { 2, 2, 2, 2, 0, 3, 3, 3, 3, 0 }, ["code2"] = { 2, 2, 0, 3, 3, 0 }, ["code3"] = { 2, 0, 2, 0, 3, 0, 3, 0 } }, -- BUMPER RELATED -- ["bumper_vertex"] = { ["all"] = { 1 }, ["code2"] = { 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0 } }, ["bumper_upper"] = { ["all"] = { 1 }, ["code2"] = { 2, 2, 0, 0, 3, 3, 0, 0 }, ["code3"] = { 2, 2, 0, 3, 3, 0, 2, 2, 0, 3, 3, 0, 2, 2, 0, 3, 3, 0, 0, } }, ["bumper_side"] = { ["all"] = { 1 }, ["code2"] = { 1, 0, 0 } }, ["rear_int_bar"] = { ["all"] = { 1 }, ["flash"] = { 1, 1, 1, 0, 0, 0 }, ["code1"] = { 8, 0, 8, 0, 9, 0, 9, 0 }, ["code2"] = { 2, 2, 2, 0, 3, 3, 3, 0 }, ["code3"] = { 2, 0, 2, 0, 2, 0, 3, 0, 3, 0, 3, 0, 2, 0, 2, 0, 2, 0, 3, 0, 3, 0, 3, 0, 2, 0, 2, 0, 2, 0, 3, 0, 3, 0, 3, 0, 4, 0, 4, 0, 4, 0, 5, 0, 5, 0, 5, 0, 4, 0, 4, 0, 4, 0, 5, 0, 5, 0, 5, 0, 4, 0, 4, 0, 4, 0, 5, 0, 5, 0, 5, 0, 6, 0, 6, 0, 6, 0, 7, 0, 7, 0, 7, 0, 6, 0, 6, 0, 6, 0, 7, 0, 7, 0, 7, 0, 6, 0, 6, 0, 6, 0, 7, 0, 7, 0, 7, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, } }, -- WHELEN FREEDOM -- ["lightbar_freedom"] = { ["all"] = { 1 } }, ["lightbar_freedom_corner"] = { ["code1"] = { 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, ["code2"] = { 2, 2, 0, 3, 3, 0 }, ["code3"] = { 0, 2, 0, 2, 0, 0, 3, 0, 3, 0, 0, 2, 0, 2, 0, 0, 3, 0, 3, 0, 0, 2, 0, 2, 0, 0, 3, 0, 3, 0, 2, 0, 3, 0, 2, 0, 3, 0, 2, 0, 3, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, } }, ["lightbar_freedom_inner"] = { ["code1"] = { 1, 1, 1, 1, 0, 2, 2, 2, 2, 0 }, ["code2"] = { 3, 0, 3, 0, 3, 0, 4, 0, 4, 0, 4, 0, 3, 0, 3, 0, 3, 0, 4, 0, 4, 0, 4, 0, 3, 0, 3, 0, 3, 0, 4, 0, 4, 0, 4, 0, 3, 3, 3, 0, 4, 4, 4, 0, 3, 3, 3, 0, 4, 4, 4, 0, 3, 3, 3, 0, 4, 4, 4, 0, }, ["code3"] = { 3, 0, 3, 0, 4, 0, 4, 0, 3, 0, 3, 0, 4, 0, 4, 0, 3, 0, 3, 0, 4, 0, 4, 0, 4, 4, 0, 3, 3, 0, 4, 4, 0, 3, 3, 0, 4, 4, 0, 3, 3, 0, 4, 4, 0, 3, 3, 0, } }, ["lightbar_freedom_illum"] = { ["code3"] = { 1, 1, 0, 2, 2, 0 } }, -- WHELEN LIBERTY -- ["lightbar_liberty"] = { ["all"] = { 1 }, ["code2"] = { 2, 2, 0, 3, 3, 0 }, ["code3"] = { 4, 4, 0, 5, 5, 0 } }, ["lightbar_liberty_corner"] = { ["code1"] = { 2, 1, 2, 1, 2, 1, 1, 1, 1, 1, 3, 1, 3, 1, 3, 1, 1, 1, 1, 1, }, ["code3"] = { 4, 0, 4, 0, 4, 0, 5, 0, 5, 0, 5, 0, 4, 0, 4, 0, 4, 0, 5, 0, 5, 0, 5, 0, 4, 0, 4, 0, 4, 0, 5, 0, 5, 0, 5, 0, 4, 4, 4, 0, 5, 5, 5, 0, 4, 4, 4, 0, 5, 5, 5, 0, 4, 4, 4, 0, 5, 5, 5, 0, } }, ["lightbar_liberty_inner"] = { ["code1"] = { 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 2, 0, 2, 0, 2, 0, 0, 0, 0, 0, 0, 0, }, ["code3"] = { 3, 0, 3, 0, 4, 0, 4, 0, } }, ["lightbar_liberty_illum"] = { ["all"] = { 1 }, ["alt"] = { 2, 2, 3, 3 } }, ["lightbar_valor"] = { ["all"] = { 1 }, ["code1"] = { 2, 2, 2, 2, 0, 5, 5, 5, 5, 0, 4, 4, 4, 4, 0, 3, 3, 3, 3, 0 }, ["code2"] = { 7, 0, 7, 0, 6, 0, 6, 0, 9, 0, 9, 0, 8, 0, 8, 0, 7, 0, 7, 0, 6, 0, 6, 0, 9, 0, 9, 0, 8, 0, 8, 0, 2, 2, 0, 4, 4, 0, 5, 5, 0, 3, 3, 0, 2, 2, 0, 4, 4, 0, 5, 5, 0, 3, 3, 0, 2, 2, 0, 4, 4, 0, 5, 5, 0, 3, 3, 0, 2, 2, 0, 4, 4, 0, 5, 5, 0, 3, 3, 0, 10, 10, 0, 11, 11, 0, 12, 12, 0, 13, 13, 0, 10, 10, 0, 11, 11, 0, 12, 12, 0, 13, 13, 0, 10, 10, 0, 11, 11, 0, 12, 12, 0, 13, 13, 0, 10, 10, 0, 11, 11, 0, 12, 12, 0, 13, 13, 0, }, -- 2, 4, 16 -- 3, 5, 17 ["code3"] = { 14, 0, 14, 0, 15, 0, 15, 0, 14, 0, 14, 0, 15, 0, 15, 0, 14, 0, 14, 0, 15, 0, 15, 0, 14, 0, 14, 0, 15, 0, 15, 0, 14, 0, 14, 0, 15, 0, 15, 0, 14, 0, 14, 0, 15, 0, 15, 0, 14, 0, 14, 0, 15, 0, 15, 0, 14, 0, 14, 0, 15, 0, 15, 0, 14, 0, 14, 0, 15, 0, 15, 0, 2, 0, 16, 0, 3, 0, 17, 0, 4, 0, 16, 0, 5, 0, 17, 0, 2, 0, 16, 0, 3, 0, 17, 0, 4, 0, 16, 0, 5, 0, 17, 0, 2, 0, 16, 0, 3, 0, 17, 0, 4, 0, 16, 0, 5, 0, 17, 0, 2, 0, 16, 0, 3, 0, 17, 0, 4, 0, 16, 0, 5, 0, 17, 0, 2, 0, 16, 0, 3, 0, 17, 0, 4, 0, 16, 0, 5, 0, 17, 0, 2, 0, 16, 0, 3, 0, 17, 0, 4, 0, 16, 0, 5, 0, 17, 0, 2, 0, 16, 0, 3, 0, 17, 0, 4, 0, 16, 0, 5, 0, 17, 0, 2, 0, 16, 0, 3, 0, 17, 0, 4, 0, 16, 0, 5, 0, 17, 0, 2, 0, 16, 0, 3, 0, 17, 0, 4, 0, 16, 0, 5, 0, 17, 0, 2, 4, 5, 3, 2, 4, 5, 3, 2, 4, 5, 3, 2, 4, 5, 3, 2, 4, 5, 3, 2, 4, 5, 3, 2, 4, 5, 3, 2, 4, 5, 3, 2, 4, 5, 3, 10, 0, 11, 0, 12, 0, 13, 0, 10, 0, 11, 0, 12, 0, 13, 0, 10, 0, 11, 0, 12, 0, 13, 0, 10, 0, 11, 0, 12, 0, 13, 0, 10, 0, 11, 0, 12, 0, 13, 0, 10, 0, 11, 0, 12, 0, 13, 0, } }, ["traffic_rb"] = { ["flash"] = { 1, 1, 1, 0, 2, 2, 2, 0 } }, ["traffic"] = { ["left"] = { 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 0, 8, 0, 8, 0, 8, 0, 8, 8, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, }, ["right"] = { 9, 9, 8, 8, 7, 7, 6, 6, 5, 5, 4, 4, 3, 3, 2, 0, 2, 0, 2, 0, 2, 0, 2, 2, 2, 2, 0, 0, 0, 0, }, ["diverge"] = { 10, 10, 11, 11, 12, 12, 13, 0, 13, 0, 13, 0, 13, 0, 13, 13, 13, 13, 0, 0, 0, 0, 0, 0, 0, 0 }, ["code1"] = { 28, 0, 28, 0, 29, 0, 29, 0 }, ["code2"] = { 22, 22, 22, 0, 23, 23, 23, 0 }, ["code3"] = { 22, 0, 22, 0, 22, 0, 23, 0, 23, 0, 23, 0, 22, 0, 22, 0, 22, 0, 23, 0, 23, 0, 23, 0, 22, 0, 22, 0, 22, 0, 23, 0, 23, 0, 23, 0, 24, 0, 24, 0, 24, 0, 25, 0, 25, 0, 25, 0, 24, 0, 24, 0, 24, 0, 25, 0, 25, 0, 25, 0, 24, 0, 24, 0, 24, 0, 25, 0, 25, 0, 25, 0, 26, 0, 26, 0, 26, 0, 27, 0, 27, 0, 27, 0, 26, 0, 26, 0, 26, 0, 27, 0, 27, 0, 27, 0, 26, 0, 26, 0, 26, 0, 27, 0, 27, 0, 27, 0, 21, 0, 21, 0, 21, 0, 0, 0, 0, 0, 0, 0, 21, 0, 21, 0, 21, 0, 0, 0, 0, 0, 0, 0, 21, 0, 21, 0, 21, 0, 0, 0, 0, 0, 0, 0, } }, } EMV.Lamps = { } EMV.Sequences = { Sequences = { { Name = "STAGE 1", Components = { ["reverse"] = "flash" }, BG_Components = { ["rear interior lightbar"] = { ["0"] = { ["traffic"] = "code1" }, ["1"] = { ["rear_int_vipers"] = "code1" } }, ["front interior lightbar"] = { ["0"] = { ["front_inner_default"] = "code1" }, ["1"] = { ["front_vipers"] = "code1" }, ["2"] = { ["front_low_viper"] = "code1" } }, ["lightbar"] = { ["0"] = { ["lightbar_freedom_corner"] = "code1", ["lightbar_freedom_inner"] = "code1" }, ["2"] = { ["lightbar_liberty_corner"] = "code1", ["lightbar_liberty_inner"] = "code1" }, ["3"] = { ["lightbar_valor"] = "code1" } } }, Disconnect = { 24, 25 } }, { Name = "STAGE 2", Components = { ["reverse"] = "flash" }, BG_Components = { ["grille leds"] = { ["0"] = { ["grille_leds"] = "code2" } }, ["front bumper leds"] = { ["0"] = { ["bumper_vertex"] = "code2" } }, ["rear passenger leds"] = { ["0"] = { ["side_leds"] = "flash" } }, ["rear interior lightbar"] = { ["0"] = { ["traffic"] = "code2" }, ["1"] = { ["rear_int_vipers"] = "code2" } }, ["front interior lightbar"] = { ["0"] = { ["front_inner_default"] = "code2" }, ["1"] = { ["front_vipers"] = "code2" }, ["2"] = { ["front_low_viper"] = "code2" } }, ["push bar"] = { ["0"] = { ["bumper_upper"] = "code2", ["bumper_side"] = "code2" }, ["1"] = { ["bumper_upper"] = "code2", ["bumper_side"] = "all" } }, ["lightbar"] = { ["0"] = { ["lightbar_freedom_corner"] = "code2", ["lightbar_freedom_inner"] = "code2" }, ["2"] = { ["lightbar_liberty"] = "code2" }, ["3"] = { ["lightbar_valor"] = "code2" } } }, Disconnect = { 24, 25 } }, { Name = "STAGE 3", Components = { ["reverse"] = "flash", ["headlights"] = "code3" }, BG_Components = { ["grille leds"] = { ["0"] = { ["grille_leds"] = "code3" } }, ["front bumper leds"] = { ["0"] = { ["bumper_vertex"] = "code2" } }, ["front interior lightbar"] = { ["0"] = { ["front_inner_default"] = "code3" }, ["1"] = { ["front_vipers"] = "code3" }, ["2"] = { ["front_low_viper"] = "code3" } }, ["rear passenger leds"] = { ["0"] = { ["side_leds"] = "flash" } }, ["rear interior lightbar"] = { ["0"] = { ["traffic"] = "code3" }, ["1"] = { ["rear_int_vipers"] = "code2" } }, ["push bar"] = { ["0"] = { ["bumper_upper"] = "code3", ["bumper_side"] = "code2" }, ["1"] = { ["bumper_upper"] = "code3", ["bumper_side"] = "code2" } }, ["lightbar"] = { ["0"] = { ["lightbar_freedom_corner"] = "code3", ["lightbar_freedom_inner"] = "code3", ["lightbar_freedom_illum"] = "code3" }, ["2"] = { ["lightbar_liberty_corner"] = "code3", ["lightbar_liberty_inner"] = "code3", ["lightbar_liberty"] = "code3", ["lightbar_liberty_illum"] = "alt" }, ["3"] = { ["lightbar_valor"] = "code3" } } }, Disconnect = { 1, 2, 15, 16, 28, 29, 24, 25 } }, }, Traffic = { { Name = "LEFT", Components = {}, BG_Components = { ["rear interior lightbar"] = { ["0"] = { ["traffic"] = "left", ["traffic_rb"] = "flash" }, }, }, Disconnect = { 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 } }, { Name = "RIGHT", Components = {}, BG_Components = { ["rear interior lightbar"] = { ["0"] = { ["traffic"] = "right", ["traffic_rb"] = "flash" }, }, }, Disconnect = {} }, { Name = "DIVERGE", Components = {}, BG_Components = { ["rear interior lightbar"] = { ["0"] = { ["traffic"] = "diverge", ["traffic_rb"] = "flash" }, }, }, Disconnect = { 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 } } }, Illumination = { { Name = "LAMP", Components = {}, BG_Components = { ["spotlights"] = { ["0"] = { { 93, W, 2 }, { 94, W, 2 } }, ["1"] = { { 93, W, 2 }, { 94, W, 2 } } }, }, Lights = { { Vector( 40.96, 37.09, 56.85 ), Angle( 20, 90, -0 ), "lamp" }, { Vector( -40.96, 37.09, 56.85 ), Angle( 20, 90, -0 ), "lamp" }, }, Disconnect = { } }, } } EMV.Lamps = { ["lamp"] = { Color = Color(96,96,106,255), Texture = "effects/flashlight001", Near = 200, FOV = 70, Distance = 700, } } EMV.Configuration = true Photon.EMVLibrary[name] = EMV if EMVU then EMVU:OverwriteIndex( name, EMV ) end
--[[ author: lakefu date: 2018-12-2 --]] local Utils = require "utils" local Heapq = require "heapq" local strfmt = string.format local TimerNode = {} TimerNode.__index = TimerNode function TimerNode:new( ... ) local o = {} setmetatable(o, self) o:init( ... ) return o end function TimerNode:init(timer_mgr, session, interval, times) times = times or 0 assert(interval >= 0, "negative timer interval") if interval == 0 then assert(times > 0, "reflect timer must be finite times") end self.m_session = session self.m_interval = interval self.m_wakeup = timer_mgr:get_time() + interval self.m_times = times > 0 and times or 0 --0 is permanent else finite self.m_nextlink = nil end local TimerMgr = {} TimerMgr.__index = TimerMgr function TimerMgr:new( ... ) local o = {} setmetatable(o, self) o:init( ... ) return o end function TimerMgr:init(capacity) self.m_timers = Heapq.create_queue(capacity, function (a, b) return a.m_wakeup <= b.m_wakeup end) self.m_funcs = {} --<map>: session 2 function self.m_tailnodes = {} --<map>: interval 2 tail node of list self.m_session = 0 end function TimerMgr:alloc_session() local nxt_handle = self.m_session + 1 while true do if self.m_funcs[nxt_handle] == nil then break end nxt_handle = nxt_handle + 1 if nxt_handle == self.m_session then --travel a loop!!! break end end if nxt_handle ~= self.m_session then self.m_session = nxt_handle return nxt_handle else error("alloc session failed!!!") end end --interval: millisecond --times: proc times function TimerMgr:add_timer(func, interval, times) local session = self:alloc_session() local tnode = TimerNode:new(self, session, interval, times) local tailnode = self.m_tailnodes[interval] if tailnode == nil then --not in timers heap local succ = self.m_timers:push( tnode ) if not succ then return end self.m_tailnodes[interval] = tnode else -- head in timers heap, direct link to tail tailnode.m_nextlink = tnode self.m_tailnodes[interval] = tnode end self.m_funcs[session] = func return session end function TimerMgr:remove_timer( session ) self.m_funcs[session] = false end function TimerMgr:size() return self.m_timers:size() end function TimerMgr:timer_num() if self.m_timers:size() <= 0 then return 0 end local num = 0 for i = 1, self.m_timers:size() do local v = self.m_timers:get(i) while v do num = num + 1 v = v.m_nextlink end end return num end function TimerMgr:set_time( t ) self.m_SpecifyTime = t end function TimerMgr:get_time() if self.m_SpecifyTime then return self.m_SpecifyTime end return Utils.millisecond() end function TimerMgr:min_wakeup_spacing() if self.m_timers:size() <= 0 then return -1 end local topnode = self.m_timers:top() local dt = topnode.m_wakeup - self:get_time() if dt > 0 then return dt else return 0 end end function TimerMgr:update( cur_time ) if self.m_timers:size() <= 0 then return end cur_time = cur_time or self:get_time() local err = nil while self.m_timers:size() > 0 do local topnode = self.m_timers:top() if topnode.m_wakeup > cur_time then break end local do_remove = false --if true remove the node, else modify local session = topnode.m_session local interval = topnode.m_interval local func = self.m_funcs[session] if func then local succ,errmsg = pcall(func, topnode) if not succ then if err == nil then err = strfmt("session:%d wakeup:%s ", session, topnode.m_wakeup) .. tostring(errmsg) else err = err .. "\n" .. strfmt("session:%d wakeup:%s ", session, topnode.m_wakeup) .. tostring(errmsg) end end if topnode.m_times > 0 then --finite topnode.m_times = topnode.m_times - 1 if topnode.m_times <= 0 then do_remove = true end end else --has be removed if func ~= false then print(strfmt("unexpect timer session %s", session)) end do_remove = true end if do_remove then if topnode.m_nextlink then --has next node local newtop = topnode.m_nextlink topnode.m_nextlink = nil self.m_timers:modify(1, newtop) else assert(topnode == self.m_tailnodes[interval], "timer node list fatal error") self.m_timers:pop() self.m_tailnodes[interval] = nil end self.m_funcs[session] = nil else topnode.m_wakeup = self:get_time() + topnode.m_interval if topnode.m_nextlink then --has next node local newtop = topnode.m_nextlink topnode.m_nextlink = nil local curtail = self.m_tailnodes[interval] curtail.m_nextlink = topnode self.m_tailnodes[interval] = topnode self.m_timers:modify(1, newtop) else self.m_timers:adjust(1) end end end if err ~= nil then print(strfmt("timer update err: %s", err)) end end local M = {} function M.new_timer_mgr( ... ) return TimerMgr:new( ... ) end return M
{ name = "miceditor", hasAdmin = false, authors = { "Pisse#0000" }, description = "Map testing utility" }
function am.notify(ply, ...) if (ply == nil) then ply = player.GetAll() end local tbl = {...} local tTbl = {} for k,v in pairs(tbl) do if (type(v) == "number") then v = tostring(v) end tTbl[ k ] = v end net.Start("am.notify") net.WriteTable(tTbl) net.Send(ply) end function am.print(...) print("[AdminMe]: ", ...) end function am.addToRank(caller, target, rankid, serverid, expireTime) // Verify the servers exist if (!ndoc.table.am.servers[ serverid ] && serverid != 0) then am.notify(caller, "Server specified is incorrect! Please use only those from below!") for k,v in ndoc.pairs(ndoc.table.am.servers) do am.notify(caller, v.name) end return end // Verify the user has the rank local rankAlreadySet = false if (ndoc.table.am.users[target:SteamID()][rankid] && ndoc.table.am.users[target:SteamID()][rankid][serverid]) then am.notify(caller, "The user is already that rank on that server - this will overwrite any expiration time") rankAlreadySet = true end // Verify the rank exists if (!ndoc.table.am.permissions[rankid]) then am.notify(caller, "Invalid rank specified! Please use only those below!") for rankid, rankInfo in ndoc.pairs(ndoc.table.am.permissions) do am.notify(caller, rankInfo.name) end end // Get an updated expiration time expireTime = expireTime > 0 && expireTime + os.time() || 0 // Update the database if (rankAlreadySet) then am.db:update("users"):update("expires", expireTime):where("steamid", target:SteamID()):where("rankid", rankid):where("serverid", serverid):execute() else am.db:insert("users"):insert("expires", expireTime):insert("steamid", target:SteamID()):insert("rankid", rankid):insert("serverid", serverid):insert("name", target:Nick()):execute() end ndoc.table.am.users[target:SteamID()][rankid] = ndoc.table.am.users[target:SteamID()][rankid] || {} ndoc.table.am.users[target:SteamID()][rankid][serverid] = ndoc.table.am.users[target:SteamID()][rankid][serverid] || {} ndoc.table.am.users[target:SteamID()][rankid][serverid].expires = expireTime end // Remove a user from a rank. Note: checkOverride should not be called outside of this system. It bypasses server & rank checks and doesn't updat ethe network table function am.removeFromRank(caller, target, rankid, serverid, checkOverride) // Verify the servers exist if (serverid && !ndoc.table.am.servers[ serverid ] && serverid != 0 && !checkOverride) then am.notify(caller, "Server specified is incorrect! Please use only those from below!") for k,v in ndoc.pairs(ndoc.table.am.servers) do am.notify(caller, v.name) end return end // Verify the user has the rank if (rankdid && !ndoc.table.am.users[target:SteamID()][rankid] && !checkOverride) then am.notify(caller, "Invalid rank specified! Please use only those below!") for rankid,v in ndoc.pairs(ndoc.table.am.users[target:SteamID()]) do local rankName = ndoc.table.am.permissions[rankid].name am.notify(caller, rankName) end return end // Delete row entry if (rankid && serverid != nil) then // Delete rank on server am.db:delete("users"):where("steamid", target:SteamID()):where("rankid", rankid):where("serverid", serverid):execute() // Check override is passed via am.pullUserInfo, where if a rank or server is invalid, we discard it if (checkOverride) then return end ndoc.table.am.users[target:SteamID()][rankid][serverid] = nil // If there are no scopes left, remove the rank local entryCount = 0 for k,v in ndoc.pairs(ndoc.table.am.users[target:SteamID()][rankid]) do entryCount = entryCount + 1 end // Remove user from rank entirely if there's nothing there if (entryCount == 0) then ndoc.table.am.users[target:SteamID()][rankid] = nil end //if (table.Count(ndoc.table.am.users[target:SteamID()][rankid]) == 0) elseif (rankid) then // Delete all servers with that rank am.db:delete("users"):where("steamid", target:SteamID()):where("rankid", rankid):execute() ndoc.table.am.users[target:SteamID()][rankid] = nil else // Delete all ranks on all servers am.db:delete("users"):where("steamid", target:SteamID()):execute() ndoc.table.am.users[target:SteamID()] = am.getDefaultUserProfile() end end function am.addPlayerEvent(target, event) target.events = target.events or {} table.insert(target.events, {["ev"] = event, ["time"] = os.time()}) ndoc.table.am.events[ target:SteamID() ] = ndoc.table.am.events[ target:SteamID() ] || {} ndoc.table.am.events[ target:SteamID() ][ os.time() ] = event local q = am.db:insert("logs") q:insert("steamid", target:SteamID()) q:insert("event", event) q:insert("timestamp", os.time()) q:execute() end function am.pullServerInfo() am.db:select("servers"):callback(function(res) // Grab all servers for k,v in pairs(res) do am.print("Found server " .. v["name"]) ndoc.table.am.servers[v["id"]] = {ip = v["ip"], port = v["port"], name = v["name"]} if (v["name"] == am.config.server_name) then am.config.server_id = v["id"] end end end):execute() end function am.checkExpiredRank(ply) if (!ndoc.table.am.users[ply:SteamID()]) then return end // Loop through player's rank for rankid, info in ndoc.pairs(ndoc.table.am.users[ply:SteamID()]) do if (!info) then continue end for scope, scopeInfo in ndoc.pairs(info) do // Ensure the rank isn't permenant if (scopeInfo.expires == 0) then continue end local rankName = ndoc.table.am.permissions[rankid].name // Test for expiration if (scopeInfo.expires <= os.time()) then am.removeFromRank(ply, ply, rankid, scope) am.notify(ply, "Your rank of ", am.green, rankName, am.def, " has expired and you've been removed!") am.notify(nil, am.green, ply:Nick(), am.def, " has been auto-removed from ", am.red, rankName) continue else local expire_time = os.date("%m/%d/%Y - %H:%M:%S", v) am.notify(ply, "Your rank of ", am.green, rankName, am.def, " will expire on ", am.red, expire_time) end end end end // Function to loop through all the players and check if they're rank has expired function am.checkAllExpired() timer.Create("am.rank_expiration_check", am.config.expire_check_time, 0, function() am.print("Checking for expired ranks..") for k,v in pairs(player.GetAll()) do am.checkExpiredRank(v) end end) end function am.getDefaultUserProfile() // TODO: These should be removed once config can be saved local defaultRankId = nil for rankid,rankinfo in ndoc.pairs(ndoc.table.am.permissions) do if (rankinfo.name == am.config.default_rank) then defaultRankId = rankid end end return { [defaultRankId] = { [0] = { expires = 0 } } } end function am.pullUserInfo(ply) if (not am.db.connection) then am.db:connect() end // A default entry for the default rank ndoc.table.am.users[ ply:SteamID() ] = am.getDefaultUserProfile() // Select all user info local query = am.db:select("users"):where("steamid", ply:SteamID()):callback(function(res) if (!IsValid(ply)) then return end // Default construct local ranks = am.getDefaultUserProfile() for k, row in pairs(res) do // Make sure the server exists if (!ndoc.table.am.servers[row["serverid"]]) then am.removeFromRank(nil, ply, row["rankid"], row["serverid"], true) continue end // Make sure the rank still exists if (!ndoc.table.am.permissions[row["rankid"]]) then am.removeFromRank(ply, ply, row["rankid"], row["serverid"], true) continue end // Structure: user{} -> rank id -> scope id -> expiresOn // We'll add the user to every rank they have, but we when we check, we'll only count the ones for this server ndoc.table.am.users[ply:SteamID()][ row["rankid"] ] = ndoc.table.am.users[ply:SteamID()][ row["rankid"] ] || { } ndoc.table.am.users[ply:SteamID()][ row["rankid"] ][row["serverid"]] = { expires = row["expires"] } end // We add all ranks regardless, but now let's see if one is expired am.checkExpiredRank(ply) end):execute() // Get the current play time for the user am.db:select("play_times"):where("steamid", ply:SteamID()):callback(function(res) // No play time :( if (#res == 0) then ndoc.table.am.play_times[ply:SteamID()] = 0 return end ndoc.table.am.play_times[ply:SteamID()] = res[1]["play_time_seconds"]; end):execute() end function am.pullGroupInfo() am.db:select("ranks"):callback(function(res) for k,v in pairs(res) do local rankid = v["id"] local rankName = v["rank"] local perms = util.JSONToTable(v["perms"]) local hierarchy = v["hierarchy"] ndoc.table.am.permissions[rankid] = {perm = perms, hierarchy = hierarchy, name = rankName} am.print("Found user group: " .. rankName) end hook.Call("am.RanksLoaded", GAMEMODE) end):execute() end // Update the play time of the current user function am.updatePlayTime(ply) local newTime = ply:getPlayTime() // Zero play time indicates a new player! if (ndoc.table.am.play_times[ply:SteamID()] != 0) then am.db:insert("play_times"):insert("steamid", ply:SteamID()):insert("nick", ply:Nick()):insert("last_join", os.time()):insert("play_time_seconds", newTime):execute() else am.db:update("play_times"):update("last_join", os.time()):update("play_time_seconds", newTime):where("steamid", ply:SteamID()):execute() end end // TODO: Update warnings - get rid of json! function am.pullWarningInfo(ply) if (!IsValid(ply)) then return end // Cache the user info and init warning table local sid = ply:SteamID() // Select all the warnings for the user am.db:select("warnings"):where("steamid", sid):callback(function(res) if (#res == 0) then return end ndoc.table.am.warnings[ sid ] = ndoc.table.am.warnings[ sid ] || { nick = ply:Nick(), warnings = {}, warningCount = #res } // Insert warning data into networked table for k,row in pairs(res) do ndoc.table.am.warnings[sid].warnings[k] = { admin = row["admin_nick"], reason = row["reason"], timestamp = row["timestamp"], warningNum = row["warningNum"] } end if (table.Count(res) > 0) then am.notify(am.getAdmins(), "Warning! ", am.def, "Player ", am.red, ply:Nick(), am.def, " is on the warning list!") end end):execute() end // Handles checking if a user is banned by the IP or steamid function am.checkBan(ply, lender) local steamid = ply:SteamID() local ip = ply:IPAddress() // Check to see if the user is banned via their steamid local querySID = am.db:select("bans") querySID:where("ban_active", 1) querySID:callback(function(v) if (table.Count(v) == 0) then return end // Loop through all possible bans for k,v in pairs(v) do // If it hasn't expired or the server doesn't exist if (v["banned_timestamp"] + v["banned_time"] > os.time() && ndoc.table.am.servers[v["serverid"]]) then // Check for server id or global if (v["serverid"] != 0 && v["serverid"] != am.config.server_id) then continue end // Check for family sharing and ban this account too if (lender) then local query = am.db:insert("bans") query:insert("banned_steamid", ply:SteamID()) query:insert("banned_name", v["banned_name"]) query:insert("banned_timestamp", v["banned_timestamp"]) query:insert("banned_reason", v["banned_reason"]) query:insert("banned_time", v["banned_time"]) query:insert("banner_steamid", v["banner_steamid"]) query:insert("banner_name", v["banner_name"]) query:execute() end // Kick the user if (!IsValid(ply)) then return end // TODO: REMOVE ONCE TESTING IS DONE //ply:Kick("You're banned!\nReason: "..v['banned_reason'].. "\nBanned by: "..v["banner_name"].."\nTime left: ".. (v["banned_timestamp"] + v["banned_time"] - os.time()) .. " seconds\nAppeal at: ".. am.config.website) else // Not banned, mark the ban as inactive local query = am.db:update("bans") query:update("ban_active", 0) query:where("id", v["id"]) query:execute() end end end) local queryIP = querySID queryIP:where("banned_ip", ip) querySID:where("banned_steamid", steamid) queryIP:execute() querySID:execute() end // Pull bans for menu editing / viewing util.AddNetworkString("am.requestBanList") util.AddNetworkString("am.syncBanList") net.Receive("am.requestBanList", function(_, ply) if (!ply:hasPerm("banmgmt")) then return end local query = am.db:select("bans"):where("ban_active", 1):callback(function(res) net.Start("am.syncBanList") net.WriteTable(res) net.Send(ply) end):execute() end)
local util = {} function util.augroup(name, autocmds) local cmds = { string.format('augroup %s', name), 'autocmd!', } for _, cmd in ipairs(autocmds) do table.insert(cmds, cmd) end table.insert(cmds, 'augroup end') local cmd_strs = table.concat(cmds, '\n') vim.api.nvim_exec(cmd_strs, true) end function util.autocmd(event, pattern, command) return string.format('autocmd %s %s %s', event, pattern, command) end function util.vim_kv_args(args) local arg_strs = {} for key, arg in pairs(args) do table.insert(arg_strs, string.format('%s=%s', key, arg)) end return table.concat(arg_strs, ' ') end function util.termcode(str) return vim.api.nvim_replace_termcodes(str, true, true, true) end function util.check_back_space() local col = vim.fn.col('.') - 1 return col == 0 or vim.fn.getline('.'):sub(col, col):match('%s') ~= nil end return util
local PANEL = {} function PANEL:Init() self:SetSize(HIGH_RES(770, 770 * 1.5), HIGH_RES(580, 580 * 1.5)) self:Center() self:SetTitle("Player menu") self:MakePopup() self.darkOverlay = Color(40, 40, 40, 160) self.tabSheet = vgui.Create("DColumnSheet", self) self.tabSheet:Dock(FILL) self.tabSheet.Navigation:SetWidth(100) -- actions self.quickActions = vgui.Create("DPanel", self.tabSheet) self.quickActions:Dock(FILL) function self.quickActions:Paint(w, h) return true end -- teams self.teams = vgui.Create("DPanel", self.tabSheet) self.teams:Dock(FILL) function self.teams:Paint(w, h) return true end -- business self.business = vgui.Create("DPanel", self.tabSheet) self.business:Dock(FILL) function self.business:Paint() return true end -- info self.info = vgui.Create("DPanel", self.tabSheet) self.info:Dock(FILL) function self.info:Paint(w, h) return true end local defaultButton = self:AddSheet("Actions", Material("impulse/icons/banknotes-256.png"), self.quickActions, self.QuickActions) self:AddSheet("Teams", Material("impulse/icons/group-256.png"), self.teams, self.Teams) self:AddSheet("Business", Material("impulse/icons/cart-73-256.png"), self.business, self.Business) self:AddSheet("Information", Material("impulse/icons/info-256.png"), self.info, self.Info) self.tabSheet:SetActiveButton(defaultButton) defaultButton.loaded = true self:QuickActions() self.tabSheet.ActiveButton.Target:SetVisible(true) self.tabSheet.Content:InvalidateLayout() end function PANEL:QuickActions() self.quickActionsInner = vgui.Create("DPanel", self.quickActions) self.quickActionsInner:Dock(FILL) local panel = self function self.quickActionsInner:Paint(w, h) surface.SetDrawColor(panel.darkOverlay) surface.DrawRect(0, 0, w, h) return true end self.collapsableOptions = vgui.Create("DCollapsibleCategory", self.quickActionsInner) self.collapsableOptions:SetLabel("Actions") self.collapsableOptions:Dock(TOP) local colInv = Color(0, 0, 0, 0) function self.collapsableOptions:Paint() self:SetBGColor(colInv) end function self.collapsableOptions:Toggle() -- allowing them to accordion causes bugs return end self.collapsableOptionsScroll = vgui.Create("DScrollPanel", self.collapsableOptions) self.collapsableOptionsScroll:Dock(FILL) self.collapsableOptions:SetContents(self.collapsableOptionsScroll) self.list = vgui.Create("DIconLayout", self.collapsableOptionsScroll) self.list:Dock(FILL) self.list:SetSpaceY(5) self.list:SetSpaceX(5) local btn = self.list:Add("DButton") if impulse.IsHighRes() then btn:SetTall(30) btn:SetFont("Impulse-Elements17-Shadow") end btn:Dock(TOP) btn:SetText("Drop money") function btn:DoClick() Derma_StringRequest("impulse", "Enter amount of money to drop:", nil, function(amount) LocalPlayer():ConCommand("say /dropmoney "..amount) end) end local btn = self.list:Add("DButton") if impulse.IsHighRes() then btn:SetTall(30) btn:SetFont("Impulse-Elements17-Shadow") end btn:Dock(TOP) btn:SetText("Write a letter") function btn:DoClick() Derma_StringRequest("impulse", "Write letter content:", nil, function(text) LocalPlayer():ConCommand("say /write "..text) end) end local btn = self.list:Add("DButton") if impulse.IsHighRes() then btn:SetTall(30) btn:SetFont("Impulse-Elements17-Shadow") end btn:Dock(TOP) btn:SetText("Change RP name (requires "..impulse.Config.CurrencyPrefix..impulse.Config.RPNameChangePrice..")") function btn:DoClick() Derma_StringRequest("impulse", "Enter your new RP name:", nil, function(text) net.Start("impulseChangeRPName") net.WriteString(text) net.SendToServer() end) end local btn = self.list:Add("DButton") if impulse.IsHighRes() then btn:SetTall(30) btn:SetFont("Impulse-Elements17-Shadow") end btn:Dock(TOP) btn:SetText("Sell all doors") function btn:DoClick() net.Start("impulseSellAllDoors") net.SendToServer() end self.collapsableOptions = vgui.Create("DCollapsibleCategory", self.quickActionsInner) self.collapsableOptions:SetLabel(team.GetName(LocalPlayer():Team()).." options") self.collapsableOptions:Dock(TOP) local colTeam = team.GetColor(LocalPlayer():Team()) function self.collapsableOptions:Paint(w, h) surface.SetDrawColor(colTeam) surface.DrawRect(0, 0, w, 20) self:SetBGColor(colInv) end function self.collapsableOptions:Toggle() -- allowing them to accordion causes bugs return end self.collapsableOptionsScroll = vgui.Create("DScrollPanel", self.collapsableOptions) self.collapsableOptionsScroll:Dock(FILL) self.collapsableOptions:SetContents(self.collapsableOptionsScroll) self.list = vgui.Create("DIconLayout", self.collapsableOptionsScroll) self.list:Dock(FILL) self.list:SetSpaceY(5) self.list:SetSpaceX(5) local classes = impulse.Teams.Data[LocalPlayer():Team()].classes if classes and LocalPlayer():InSpawn() then for v,classData in pairs(classes) do if not classData.noMenu and LocalPlayer():GetTeamClass() != v then local btn = self.list:Add("DButton") if impulse.IsHighRes() then btn:SetTall(30) btn:SetFont("Impulse-Elements17-Shadow") end btn:Dock(TOP) btn.classID = v local btnText = "Become "..classData.name if classData.xp then btnText = btnText.." ("..classData.xp.."XP)" end btn:SetText("Become "..classData.name.." ("..classData.xp.."XP)") local panel = self function btn:DoClick() net.Start("impulseClassChange") net.WriteUInt(btn.classID, 8) net.SendToServer() end end end end end function PANEL:Teams() self.modelPreview = vgui.Create("DModelPanel", self.teams) self.modelPreview:SetPos(373, 0) self.modelPreview:SetSize(300, 370) self.modelPreview:MoveToBack() self.modelPreview:SetCursor("arrow") self.modelPreview:SetFOV(self.modelPreview:GetFOV() - 19) function self.modelPreview:LayoutEntity(ent) ent:SetAngles(Angle(0, 43, 0)) --ent:SetSequence(ACT_IDLE) --self:RunAnimation() end self.descLbl = vgui.Create("DLabel", self.teams) self.descLbl:SetText("Description:") self.descLbl:SetFont("Impulse-Elements18") self.descLbl:SizeToContents() self.descLbl:SetPos(410, 380) self.descLblT = vgui.Create("DLabel", self.teams) self.descLblT:SetText("") self.descLblT:SetFont("Impulse-Elements14") self.descLblT:SetPos(410, 400) self.descLblT:SetContentAlignment(7) self.descLblT:SetSize(230, 230) self.teamsInner = vgui.Create("DPanel", self.teams) self.teamsInner:SetSize(400, 580) local panel = self function self.teamsInner:Paint(w, h) surface.SetDrawColor(panel.darkOverlay) surface.DrawRect(0, 0, w, h) return true end self.availibleTeams = vgui.Create("DCollapsibleCategory", self.teamsInner) self.availibleTeams:SetLabel("Available teams") self.availibleTeams:Dock(TOP) local colInv = Color(0, 0, 0, 0) function self.availibleTeams:Paint() self:SetBGColor(colInv) end self.availibleTeamsScroll = vgui.Create("DScrollPanel", self.availibleTeams) self.availibleTeamsScroll:Dock(FILL) self.availibleTeams:SetContents(self.availibleTeamsScroll) local availibleList = vgui.Create("DIconLayout", self.availibleTeamsScroll) availibleList:Dock(FILL) availibleList:SetSpaceY(5) availibleList:SetSpaceX(5) self.unavailibleTeams = vgui.Create("DCollapsibleCategory", self.teamsInner) self.unavailibleTeams:SetLabel("Unavailable teams") self.unavailibleTeams:Dock(TOP) function self.unavailibleTeams:Paint() self:SetBGColor(colInv) end self.unavailibleTeamsScroll = vgui.Create("DScrollPanel", self.unavailibleTeams) self.unavailibleTeamsScroll:Dock(FILL) self.unavailibleTeams:SetContents(self.unavailibleTeamsScroll) local unavailibleList = vgui.Create("DIconLayout", self.unavailibleTeamsScroll) unavailibleList:Dock(FILL) unavailibleList:SetSpaceY(5) unavailibleList:SetSpaceX(5) for v,k in pairs(impulse.Teams.Data) do local selectedList if (k.xp > LocalPlayer():GetXP()) or (k.donatorOnly and k.donatorOnly == true and LocalPlayer():IsDonator() == false) then selectedList = unavailibleList else selectedList = availibleList end local teamCard = selectedList:Add("impulseTeamCard") teamCard:SetTeam(v) teamCard.team = v teamCard:Dock(TOP) teamCard:SetHeight(60) teamCard:SetMouseInputEnabled(true) local realSelf = self function teamCard:OnCursorEntered() local model = impulse.Teams.Data[self.team].model local skin = impulse.Teams.Data[self.team].skin or 0 local desc = impulse.Teams.Data[self.team].description local bodygroups = impulse.Teams.Data[self.team].bodygroups if not model then model = impulse_defaultModel or "models/Humans/Group01/male_02.mdl" skin = impulse_defaultSkin or 0 end realSelf.modelPreview:SetModel(model) realSelf.modelPreview.Entity:SetSkin(skin) if bodygroups then for v, bodygroupData in pairs(bodygroups) do realSelf.modelPreview.Entity:SetBodygroup(bodygroupData[1], (bodygroupData[2] or 0)) end end realSelf.descLblT:SetText(desc) realSelf.descLblT:SetWrap(true) end function teamCard:OnMousePressed() net.Start("impulseTeamChange") net.WriteUInt(self.team, 8) net.SendToServer() realSelf:Remove() end end end function PANEL:Business() self.businessInner = vgui.Create("DPanel", self.business) self.businessInner:Dock(FILL) local panel = self function self.businessInner:Paint(w, h) surface.SetDrawColor(panel.darkOverlay) surface.DrawRect(0, 0, w, h) return true end self.itemsScroll = vgui.Create("DScrollPanel", self.businessInner) self.itemsScroll:Dock(FILL) self.utilItems = self.itemsScroll:Add("DCollapsibleCategory") self.utilItems:SetLabel("Utilities") self.utilItems:Dock(TOP) local colInv = Color(0, 0, 0, 0) function self.utilItems:Paint() self:SetBGColor(colInv) end local utilList = vgui.Create("DIconLayout", self.utilItems) utilList:Dock(FILL) utilList:SetSpaceY(5) utilList:SetSpaceX(5) self.utilItems:SetContents(utilList) self.cat = {} for name,k in pairs(impulse.Business.Data) do if not LocalPlayer():CanBuy(name) then continue end local parent = nil if k.category then if self.cat[k.category] then parent = self.cat[k.category] else local cat = self.itemsScroll:Add("DCollapsibleCategory") cat:SetLabel(k.category) cat:Dock(TOP) local colInv = Color(0, 0, 0, 0) function cat:Paint() self:SetBGColor(colInv) end self.cat[k.category] = vgui.Create("DIconLayout", cat) self.cat[k.category]:Dock(FILL) self.cat[k.category]:SetSpaceY(5) self.cat[k.category]:SetSpaceX(5) cat:SetContents(self.cat[k.category]) parent = self.cat[k.category] end end local item = (parent or utilList):Add("SpawnIcon") if k.item then local x = impulse.Inventory.Items[impulse.Inventory.ClassToNetID(k.item)] item:SetModel(x.Model) else item:SetModel(k.model) end if impulse.IsHighRes() then item:SetSize(78,78) else item:SetSize(58,58) end item:SetTooltip(name.." \n"..impulse.Config.CurrencyPrefix..k.price) item.id = table.KeyFromValue(impulse.Business.DataRef, name) function item:DoClick() net.Start("impulseBuyItem") net.WriteUInt(item.id, 8) net.SendToServer() end local costLbl = vgui.Create("DLabel", item) costLbl:SetPos(5,HIGH_RES(35, 55)) costLbl:SetFont(HIGH_RES("Impulse-Elements20-Shadow", "Impulse-Elements22-Shadow")) costLbl:SetText(impulse.Config.CurrencyPrefix..k.price) costLbl:SizeToContents() end end function PANEL:Info() self.infoSheet = vgui.Create("DPropertySheet", self.info) self.infoSheet:Dock(FILL) local webRules = vgui.Create("DHTML", self.infoSheet) webRules:OpenURL(impulse.Config.RulesURL) self.infoSheet:AddSheet("Rules", webRules) local webTutorial = vgui.Create("DHTML", self.infoSheet) webTutorial:OpenURL(impulse.Config.TutorialURL) self.infoSheet:AddSheet("Help & Tutorials", webTutorial) local commands = vgui.Create("DScrollPanel", self.infoSheet) commands:Dock(FILL) for v,k in pairs(impulse.chatCommands) do local c = impulse.Config.MainColour if k.adminOnly == true and LocalPlayer():IsAdmin() == false then continue elseif k.adminOnly == true then c = impulse.Config.InteractColour end if k.superAdminOnly == true and LocalPlayer():IsSuperAdmin() == false then continue elseif k.superAdminOnly == true then c = Color(255, 0, 0, 255) end local command = commands:Add("DPanel", commands) command:SetTall(40) command:Dock(TOP) command.name = v command.desc = k.description command.col = c function command:Paint() draw.SimpleText(self.name, "Impulse-Elements22-Shadow", 5, 0, self.col) draw.SimpleText(self.desc, "Impulse-Elements18-Shadow", 5, 20, color_white) return true end end self.infoSheet:AddSheet("Commands", commands) end function PANEL:AddSheet(name, icon, pnl, loadFunc) local tab = self.tabSheet:AddSheet(name, pnl) local panel = self tab.Button:SetSize(120, 130) function tab.Button:Paint(w, h) if panel.tabSheet.ActiveButton == self then surface.SetDrawColor(impulse.Config.MainColour) else surface.SetDrawColor(color_white) end surface.SetMaterial(icon) surface.DrawTexturedRect(0, 0, w-10, h-40) draw.DrawText(name, HIGH_RES("Impulse-Elements18", "Impulse-Elements20A-Shadow"), (w-10)/2, 95, color_white, TEXT_ALIGN_CENTER) return true end local oldClick = tab.Button.DoClick function tab.Button:DoClick() oldClick() if loadFunc and not self.loaded then loadFunc(panel) self.loaded = true end end return tab.Button end vgui.Register("impulsePlayerMenu", PANEL, "DFrame")
local ERROR_FUNC = "(error from function call)" local function decode(input, contents, msg) return function() local ok, v = pcall(rbxmk.decodeFormat, "l10n.csv", input) if not ok then if contents == ERROR_FUNC then return true end return false, v end if typeof(v) ~= "Instance" then return false, "Instance expected" end if v.ClassName ~= "LocalizationTable" then return false, "LocalizationTable expected" end if contents and v.Contents ~= contents then return false, "\nWANT: " .. (string.gsub(contents, "\n", "\\n")) .. "\nGOT : " .. (string.gsub(v.Contents, "\n", "\\n")) end return true end, msg end local function encode(input, contents, msg) return function() local ok, v = pcall(rbxmk.encodeFormat, "l10n.csv", input) if not ok then if contents == ERROR_FUNC then return true end return false, v end if contents and v ~= contents then return false, "\nWANT: " .. (string.gsub(contents, "\n", "\\n")) .. "\nGOT : " .. (string.gsub(v, "\n", "\\n")) end return true end, msg end ---- Decoding -- Test empty. T.Pass(decode('' , '[]' , "empty csv is valid")) T.Fail(decode('Header' , '[]' , "empty csv with header expects Key or Source header")) T.Pass(decode('Key' , '[]' , "empty csv with Key is valid")) T.Pass(decode('Source' , '[]' , "empty csv with Source is valid")) -- Test index headers. T.Pass(decode('Key\nAA' , '[{"key":"AA","values":{}}]' , 'decode index headers k')) T.Pass(decode('Source\nAA' , '[{"source":"AA","values":{}}]' , 'decode index headers s')) T.Fail(decode('Context\nAA' , '[{"context":"AA","values":{}}]' , 'decode index headers c')) T.Fail(decode('Example\nAA' , '[{"examples":"AA","values":{}}]' , 'decode index headers e')) T.Pass(decode('Key,Context\nAA,BB' , '[{"key":"AA","context":"BB","values":{}}]' , 'decode index headers kc')) T.Pass(decode('Key,Example\nAA,BB' , '[{"key":"AA","examples":"BB","values":{}}]' , 'decode index headers ke')) T.Pass(decode('Key,Context,Example,Source\nAA,BB,CC,DD' , '[{"key":"AA","context":"BB","examples":"CC","source":"DD","values":{}}]' , 'decode index headers kces')) -- Test locale headers. T.Pass(decode('Key,Foo,bAz,BAR\nAA,BB,CC,DD', '[{"key":"AA","values":{"bar":"DD","baz":"CC","foo":"BB"}}]', 'decode locale headers')) -- Test repeated headers. T.Pass(decode('Key,Key\nAA,BB' , '[{"key":"AA","values":{"key":"BB"}}]' , 'decode repeat headers 0')) T.Pass(decode('Key,Foo,foo\nAA,BB,CC' , ERROR_FUNC , 'decode repeat headers 1')) -- Test header order. T.Pass(decode('Foo,Example,Bar,Context,Source,Key\nAA,BB,CC,DD,EE,FF', '[{"key":"FF","context":"DD","examples":"BB","source":"EE","values":{"bar":"CC","foo":"AA"}}]', 'decode header order')) -- Test multiple records. T.Pass(decode('Key,Foo\nAA,BB\nCC,DD\nEE,FF', '[{"key":"AA","values":{"foo":"BB"}},{"key":"CC","values":{"foo":"DD"}},{"key":"EE","values":{"foo":"FF"}}]', 'decode multiple records')) -- Test locale header conflicts. -- -- Roblox will discard the column if the lowercase header matches the lowercase -- header of a previous column. If the header is already lowercase, then an -- error is thrown instead. rbxmk deviates from the Roblox implementation by -- throwing error for *any* such conflicts. T.Pass(decode('Key,FOO\nKK,AA\n' , '[{"key":"KK","values":{"foo":"AA"}}]' , 'decode locale conflict 00')) T.Pass(decode('Key,Foo\nKK,AA\n' , '[{"key":"KK","values":{"foo":"AA"}}]' , 'decode locale conflict 01')) T.Pass(decode('Key,foo\nKK,AA\n' , '[{"key":"KK","values":{"foo":"AA"}}]' , 'decode locale conflict 02')) T.Pass(decode('Key,FOO,FOO\nKK,AA,BB\n' , ERROR_FUNC , 'decode locale conflict 03')) -- BB (roblox) T.Pass(decode('Key,FOO,Foo\nKK,AA,BB\n' , ERROR_FUNC , 'decode locale conflict 04')) -- BB T.Pass(decode('Key,FOO,foo\nKK,AA,BB\n' , ERROR_FUNC , 'decode locale conflict 05')) -- error T.Pass(decode('Key,Foo,FOO\nKK,AA,BB\n' , ERROR_FUNC , 'decode locale conflict 06')) -- BB T.Pass(decode('Key,Foo,Foo\nKK,AA,BB\n' , ERROR_FUNC , 'decode locale conflict 07')) -- BB T.Pass(decode('Key,Foo,foo\nKK,AA,BB\n' , ERROR_FUNC , 'decode locale conflict 08')) -- error T.Pass(decode('Key,foo,FOO\nKK,AA,BB\n' , ERROR_FUNC , 'decode locale conflict 09')) -- BB T.Pass(decode('Key,foo,Foo\nKK,AA,BB\n' , ERROR_FUNC , 'decode locale conflict 10')) -- BB T.Pass(decode('Key,foo,foo\nKK,AA,BB\n' , ERROR_FUNC , 'decode locale conflict 11')) -- error T.Pass(decode('Key,FOO,FOO,FOO\nKK,AA,BB,CC\n' , ERROR_FUNC , 'decode locale conflict 12')) -- CC T.Pass(decode('Key,Foo,FOO,FOO\nKK,AA,BB,CC\n' , ERROR_FUNC , 'decode locale conflict 13')) -- CC T.Pass(decode('Key,foo,FOO,FOO\nKK,AA,BB,CC\n' , ERROR_FUNC , 'decode locale conflict 14')) -- CC T.Pass(decode('Key,FOO,Foo,FOO\nKK,AA,BB,CC\n' , ERROR_FUNC , 'decode locale conflict 15')) -- CC T.Pass(decode('Key,Foo,Foo,FOO\nKK,AA,BB,CC\n' , ERROR_FUNC , 'decode locale conflict 16')) -- CC T.Pass(decode('Key,foo,Foo,FOO\nKK,AA,BB,CC\n' , ERROR_FUNC , 'decode locale conflict 17')) -- CC T.Pass(decode('Key,FOO,foo,FOO\nKK,AA,BB,CC\n' , ERROR_FUNC , 'decode locale conflict 18')) -- error T.Pass(decode('Key,Foo,foo,FOO\nKK,AA,BB,CC\n' , ERROR_FUNC , 'decode locale conflict 19')) -- error T.Pass(decode('Key,foo,foo,FOO\nKK,AA,BB,CC\n' , ERROR_FUNC , 'decode locale conflict 20')) -- error T.Pass(decode('Key,FOO,FOO,Foo\nKK,AA,BB,CC\n' , ERROR_FUNC , 'decode locale conflict 21')) -- CC T.Pass(decode('Key,Foo,FOO,Foo\nKK,AA,BB,CC\n' , ERROR_FUNC , 'decode locale conflict 22')) -- CC T.Pass(decode('Key,foo,FOO,Foo\nKK,AA,BB,CC\n' , ERROR_FUNC , 'decode locale conflict 23')) -- CC T.Pass(decode('Key,FOO,Foo,Foo\nKK,AA,BB,CC\n' , ERROR_FUNC , 'decode locale conflict 24')) -- CC T.Pass(decode('Key,Foo,Foo,Foo\nKK,AA,BB,CC\n' , ERROR_FUNC , 'decode locale conflict 25')) -- CC T.Pass(decode('Key,foo,Foo,Foo\nKK,AA,BB,CC\n' , ERROR_FUNC , 'decode locale conflict 26')) -- CC T.Pass(decode('Key,FOO,foo,Foo\nKK,AA,BB,CC\n' , ERROR_FUNC , 'decode locale conflict 27')) -- error T.Pass(decode('Key,Foo,foo,Foo\nKK,AA,BB,CC\n' , ERROR_FUNC , 'decode locale conflict 28')) -- error T.Pass(decode('Key,foo,foo,Foo\nKK,AA,BB,CC\n' , ERROR_FUNC , 'decode locale conflict 29')) -- error T.Pass(decode('Key,FOO,FOO,foo\nKK,AA,BB,CC\n' , ERROR_FUNC , 'decode locale conflict 30')) -- error T.Pass(decode('Key,Foo,FOO,foo\nKK,AA,BB,CC\n' , ERROR_FUNC , 'decode locale conflict 31')) -- error T.Pass(decode('Key,foo,FOO,foo\nKK,AA,BB,CC\n' , ERROR_FUNC , 'decode locale conflict 32')) -- error T.Pass(decode('Key,FOO,Foo,foo\nKK,AA,BB,CC\n' , ERROR_FUNC , 'decode locale conflict 33')) -- error T.Pass(decode('Key,Foo,Foo,foo\nKK,AA,BB,CC\n' , ERROR_FUNC , 'decode locale conflict 34')) -- error T.Pass(decode('Key,foo,Foo,foo\nKK,AA,BB,CC\n' , ERROR_FUNC , 'decode locale conflict 35')) -- error T.Pass(decode('Key,FOO,foo,foo\nKK,AA,BB,CC\n' , ERROR_FUNC , 'decode locale conflict 36')) -- error T.Pass(decode('Key,Foo,foo,foo\nKK,AA,BB,CC\n' , ERROR_FUNC , 'decode locale conflict 37')) -- error T.Pass(decode('Key,foo,foo,foo\nKK,AA,BB,CC\n' , ERROR_FUNC , 'decode locale conflict 38')) -- error -- Test index header conflicts. T.Pass(decode('Key,Context,Source,foo\n,,,A\n,,,B\n' , ERROR_FUNC , 'decode index conflict 00')) T.Pass(decode('Key,Context,Source,foo\nK,,,A\n,,,B\n' , ERROR_FUNC , 'decode index conflict 01')) T.Pass(decode('Key,Context,Source,foo\n,C,,A\n,,,B\n' , ERROR_FUNC , 'decode index conflict 02')) T.Pass(decode('Key,Context,Source,foo\n,,S,A\n,,,B\n' , ERROR_FUNC , 'decode index conflict 03')) T.Pass(decode('Key,Context,Source,foo\nK,C,,A\n,,,B\n' , ERROR_FUNC , 'decode index conflict 04')) T.Pass(decode('Key,Context,Source,foo\nK,,S,A\n,,,B\n' , ERROR_FUNC , 'decode index conflict 05')) T.Pass(decode('Key,Context,Source,foo\n,C,S,A\n,,,B\n' , ERROR_FUNC , 'decode index conflict 06')) T.Pass(decode('Key,Context,Source,foo\nK,C,S,A\n,,,B\n' , ERROR_FUNC , 'decode index conflict 07')) T.Pass(decode('Key,Context,Source,foo\n,,,A\nK,,,B\n' , ERROR_FUNC , 'decode index conflict 08')) T.Pass(decode('Key,Context,Source,foo\nK,,,A\nK,,,B\n' , ERROR_FUNC , 'decode index conflict 09')) T.Pass(decode('Key,Context,Source,foo\n,C,,A\nK,,,B\n' , ERROR_FUNC , 'decode index conflict 10')) T.Pass(decode('Key,Context,Source,foo\n,,S,A\nK,,,B\n' , '[{"source":"S","values":{"foo":"A"}},{"key":"K","values":{"foo":"B"}}]' , 'decode index conflict 11')) T.Pass(decode('Key,Context,Source,foo\nK,C,,A\nK,,,B\n' , ERROR_FUNC , 'decode index conflict 12')) T.Pass(decode('Key,Context,Source,foo\nK,,S,A\nK,,,B\n' , ERROR_FUNC , 'decode index conflict 13')) T.Pass(decode('Key,Context,Source,foo\n,C,S,A\nK,,,B\n' , '[{"context":"C","source":"S","values":{"foo":"A"}},{"key":"K","values":{"foo":"B"}}]' , 'decode index conflict 14')) T.Pass(decode('Key,Context,Source,foo\nK,C,S,A\nK,,,B\n' , ERROR_FUNC , 'decode index conflict 15')) T.Pass(decode('Key,Context,Source,foo\n,,,A\n,C,,B\n' , ERROR_FUNC , 'decode index conflict 16')) T.Pass(decode('Key,Context,Source,foo\nK,,,A\n,C,,B\n' , ERROR_FUNC , 'decode index conflict 17')) T.Pass(decode('Key,Context,Source,foo\n,C,,A\n,C,,B\n' , ERROR_FUNC , 'decode index conflict 18')) T.Pass(decode('Key,Context,Source,foo\n,,S,A\n,C,,B\n' , ERROR_FUNC , 'decode index conflict 19')) T.Pass(decode('Key,Context,Source,foo\nK,C,,A\n,C,,B\n' , ERROR_FUNC , 'decode index conflict 20')) T.Pass(decode('Key,Context,Source,foo\nK,,S,A\n,C,,B\n' , ERROR_FUNC , 'decode index conflict 21')) T.Pass(decode('Key,Context,Source,foo\n,C,S,A\n,C,,B\n' , ERROR_FUNC , 'decode index conflict 22')) T.Pass(decode('Key,Context,Source,foo\nK,C,S,A\n,C,,B\n' , ERROR_FUNC , 'decode index conflict 23')) T.Pass(decode('Key,Context,Source,foo\n,,,A\n,,S,B\n' , ERROR_FUNC , 'decode index conflict 24')) T.Pass(decode('Key,Context,Source,foo\nK,,,A\n,,S,B\n' , '[{"key":"K","values":{"foo":"A"}},{"source":"S","values":{"foo":"B"}}]' , 'decode index conflict 25')) T.Pass(decode('Key,Context,Source,foo\n,C,,A\n,,S,B\n' , ERROR_FUNC , 'decode index conflict 26')) T.Pass(decode('Key,Context,Source,foo\n,,S,A\n,,S,B\n' , ERROR_FUNC , 'decode index conflict 27')) T.Pass(decode('Key,Context,Source,foo\nK,C,,A\n,,S,B\n' , '[{"key":"K","context":"C","values":{"foo":"A"}},{"source":"S","values":{"foo":"B"}}]' , 'decode index conflict 28')) T.Pass(decode('Key,Context,Source,foo\nK,,S,A\n,,S,B\n' , '[{"key":"K","source":"S","values":{"foo":"A"}},{"source":"S","values":{"foo":"B"}}]' , 'decode index conflict 29')) T.Pass(decode('Key,Context,Source,foo\n,C,S,A\n,,S,B\n' , '[{"context":"C","source":"S","values":{"foo":"A"}},{"source":"S","values":{"foo":"B"}}]' , 'decode index conflict 30')) T.Pass(decode('Key,Context,Source,foo\nK,C,S,A\n,,S,B\n' , '[{"key":"K","context":"C","source":"S","values":{"foo":"A"}},{"source":"S","values":{"foo":"B"}}]' , 'decode index conflict 31')) T.Pass(decode('Key,Context,Source,foo\n,,,A\nK,C,,B\n' , ERROR_FUNC , 'decode index conflict 32')) T.Pass(decode('Key,Context,Source,foo\nK,,,A\nK,C,,B\n' , ERROR_FUNC , 'decode index conflict 33')) T.Pass(decode('Key,Context,Source,foo\n,C,,A\nK,C,,B\n' , ERROR_FUNC , 'decode index conflict 34')) T.Pass(decode('Key,Context,Source,foo\n,,S,A\nK,C,,B\n' , '[{"source":"S","values":{"foo":"A"}},{"key":"K","context":"C","values":{"foo":"B"}}]' , 'decode index conflict 35')) T.Pass(decode('Key,Context,Source,foo\nK,C,,A\nK,C,,B\n' , ERROR_FUNC , 'decode index conflict 36')) T.Pass(decode('Key,Context,Source,foo\nK,,S,A\nK,C,,B\n' , ERROR_FUNC , 'decode index conflict 37')) T.Pass(decode('Key,Context,Source,foo\n,C,S,A\nK,C,,B\n' , '[{"context":"C","source":"S","values":{"foo":"A"}},{"key":"K","context":"C","values":{"foo":"B"}}]' , 'decode index conflict 38')) T.Pass(decode('Key,Context,Source,foo\nK,C,S,A\nK,C,,B\n' , ERROR_FUNC , 'decode index conflict 39')) T.Pass(decode('Key,Context,Source,foo\n,,,A\nK,,S,B\n' , ERROR_FUNC , 'decode index conflict 40')) T.Pass(decode('Key,Context,Source,foo\nK,,,A\nK,,S,B\n' , ERROR_FUNC , 'decode index conflict 41')) T.Pass(decode('Key,Context,Source,foo\n,C,,A\nK,,S,B\n' , ERROR_FUNC , 'decode index conflict 42')) T.Pass(decode('Key,Context,Source,foo\n,,S,A\nK,,S,B\n' , '[{"source":"S","values":{"foo":"A"}},{"key":"K","source":"S","values":{"foo":"B"}}]' , 'decode index conflict 43')) T.Pass(decode('Key,Context,Source,foo\nK,C,,A\nK,,S,B\n' , ERROR_FUNC , 'decode index conflict 44')) T.Pass(decode('Key,Context,Source,foo\nK,,S,A\nK,,S,B\n' , ERROR_FUNC , 'decode index conflict 45')) T.Pass(decode('Key,Context,Source,foo\n,C,S,A\nK,,S,B\n' , '[{"context":"C","source":"S","values":{"foo":"A"}},{"key":"K","source":"S","values":{"foo":"B"}}]' , 'decode index conflict 46')) T.Pass(decode('Key,Context,Source,foo\nK,C,S,A\nK,,S,B\n' , ERROR_FUNC , 'decode index conflict 47')) T.Pass(decode('Key,Context,Source,foo\n,,,A\n,C,S,B\n' , ERROR_FUNC , 'decode index conflict 48')) T.Pass(decode('Key,Context,Source,foo\nK,,,A\n,C,S,B\n' , '[{"key":"K","values":{"foo":"A"}},{"context":"C","source":"S","values":{"foo":"B"}}]' , 'decode index conflict 49')) T.Pass(decode('Key,Context,Source,foo\n,C,,A\n,C,S,B\n' , ERROR_FUNC , 'decode index conflict 50')) T.Pass(decode('Key,Context,Source,foo\n,,S,A\n,C,S,B\n' , '[{"source":"S","values":{"foo":"A"}},{"context":"C","source":"S","values":{"foo":"B"}}]' , 'decode index conflict 51')) T.Pass(decode('Key,Context,Source,foo\nK,C,,A\n,C,S,B\n' , '[{"key":"K","context":"C","values":{"foo":"A"}},{"context":"C","source":"S","values":{"foo":"B"}}]' , 'decode index conflict 52')) T.Pass(decode('Key,Context,Source,foo\nK,,S,A\n,C,S,B\n' , '[{"key":"K","source":"S","values":{"foo":"A"}},{"context":"C","source":"S","values":{"foo":"B"}}]' , 'decode index conflict 53')) T.Pass(decode('Key,Context,Source,foo\n,C,S,A\n,C,S,B\n' , ERROR_FUNC , 'decode index conflict 54')) T.Pass(decode('Key,Context,Source,foo\nK,C,S,A\n,C,S,B\n' , '[{"key":"K","context":"C","source":"S","values":{"foo":"A"}},{"context":"C","source":"S","values":{"foo":"B"}}]' , 'decode index conflict 55')) T.Pass(decode('Key,Context,Source,foo\n,,,A\nK,C,S,B\n' , ERROR_FUNC , 'decode index conflict 56')) T.Pass(decode('Key,Context,Source,foo\nK,,,A\nK,C,S,B\n' , ERROR_FUNC , 'decode index conflict 57')) T.Pass(decode('Key,Context,Source,foo\n,C,,A\nK,C,S,B\n' , ERROR_FUNC , 'decode index conflict 58')) T.Pass(decode('Key,Context,Source,foo\n,,S,A\nK,C,S,B\n' , '[{"source":"S","values":{"foo":"A"}},{"key":"K","context":"C","source":"S","values":{"foo":"B"}}]' , 'decode index conflict 59')) T.Pass(decode('Key,Context,Source,foo\nK,C,,A\nK,C,S,B\n' , ERROR_FUNC , 'decode index conflict 60')) T.Pass(decode('Key,Context,Source,foo\nK,,S,A\nK,C,S,B\n' , ERROR_FUNC , 'decode index conflict 61')) T.Pass(decode('Key,Context,Source,foo\n,C,S,A\nK,C,S,B\n' , '[{"context":"C","source":"S","values":{"foo":"A"}},{"key":"K","context":"C","source":"S","values":{"foo":"B"}}]' , 'decode index conflict 62')) T.Pass(decode('Key,Context,Source,foo\nK,C,S,A\nK,C,S,B\n' , ERROR_FUNC , 'decode index conflict 63')) -- Test unmerged headers. T.Pass(decode('Key,a,b,c\n11,AA,BB,\n22,,BB,CC\n', '[{"key":"11","values":{"a":"AA","b":"BB","c":""}},{"key":"22","values":{"a":"","b":"BB","c":"CC"}}]', 'decode merge headers')) -- Test CSV format. T.Pass(decode('Key,A,"B",C D,E F,"""G"""\nKK,AA,BB,CD,EF,GG', '[{"key":"KK","values":{"\\"g\\"":"GG","a":"AA","b":"BB","c d":"CD","e f":"EF"}}]', 'decode csv format')) -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- Encoding -- Test empty. T.Pass(encode('[]', 'Key,Context,Example,Source\n', "empty csv is valid")) -- Test index headers. T.Pass(encode('[{"key":"AA","values":{}}]' , 'Key,Context,Example,Source\nAA,,,\n' , 'encode index headers k')) T.Pass(encode('[{"source":"AA","values":{}}]' , 'Key,Context,Example,Source\n,,,AA\n' , 'encode index headers s')) T.Pass(encode('[{"key":"AA","context":"BB","values":{}}]' , 'Key,Context,Example,Source\nAA,BB,,\n' , 'encode index headers kc')) T.Pass(encode('[{"key":"AA","examples":"BB","values":{}}]' , 'Key,Context,Example,Source\nAA,,BB,\n' , 'encode index headers ke')) T.Pass(encode('[{"key":"AA","context":"BB","examples":"CC","source":"DD","values":{}}]' , 'Key,Context,Example,Source\nAA,BB,CC,DD\n' , 'encode index headers kces')) -- Test locale headers. T.Pass(encode('[{"key":"AA","values":{"bar":"DD","baz":"CC","foo":"BB"}}]', 'Key,Context,Example,Source,bar,baz,foo\nAA,,,,DD,CC,BB\n', 'encode locale headers')) -- Test repeated headers. T.Pass(encode('[{"key":"AA","values":{"key":"BB"}}]', 'Key,Context,Example,Source,key\nAA,,,,BB\n', 'encode repeat headers')) -- Test header order. T.Pass(encode('[{"key":"FF","context":"DD","examples":"BB","source":"EE","values":{"bar":"CC","foo":"AA"}}]', 'Key,Context,Example,Source,bar,foo\nFF,DD,BB,EE,CC,AA\n', 'encode header order')) -- Test multiple records. T.Pass(encode('[{"key":"AA","values":{"foo":"BB"}},{"key":"CC","values":{"foo":"DD"}},{"key":"EE","values":{"foo":"FF"}}]', 'Key,Context,Example,Source,foo\nAA,,,,BB\nCC,,,,DD\nEE,,,,FF\n', 'encode multiple records')) -- Test index header conflicts. T.Pass(encode('[{"key":"KK","values":{"FOO":"AA"}}]' , 'Key,Context,Example,Source,foo\nKK,,,,AA\n' , 'encode header conflict 00')) -- AA (roblox) T.Pass(encode('[{"key":"KK","values":{"Foo":"AA"}}]' , 'Key,Context,Example,Source,foo\nKK,,,,AA\n' , 'encode header conflict 01')) -- AA T.Pass(encode('[{"key":"KK","values":{"foo":"AA"}}]' , 'Key,Context,Example,Source,foo\nKK,,,,AA\n' , 'encode header conflict 02')) -- AA T.Pass(encode('[{"key":"KK","values":{"FOO":"AA","FOO":"BB"}}]' , 'Key,Context,Example,Source,foo\nKK,,,,BB\n' , 'encode header conflict 03')) -- BB T.Pass(encode('[{"key":"KK","values":{"FOO":"AA","Foo":"BB"}}]' , ERROR_FUNC , 'encode header conflict 04')) -- BB T.Pass(encode('[{"key":"KK","values":{"FOO":"AA","foo":"BB"}}]' , ERROR_FUNC , 'encode header conflict 05')) -- BB T.Pass(encode('[{"key":"KK","values":{"Foo":"AA","FOO":"BB"}}]' , ERROR_FUNC , 'encode header conflict 06')) -- BB T.Pass(encode('[{"key":"KK","values":{"Foo":"AA","Foo":"BB"}}]' , 'Key,Context,Example,Source,foo\nKK,,,,BB\n' , 'encode header conflict 07')) -- BB T.Pass(encode('[{"key":"KK","values":{"Foo":"AA","foo":"BB"}}]' , ERROR_FUNC , 'encode header conflict 08')) -- BB T.Pass(encode('[{"key":"KK","values":{"foo":"AA","FOO":"BB"}}]' , ERROR_FUNC , 'encode header conflict 09')) -- BB T.Pass(encode('[{"key":"KK","values":{"foo":"AA","Foo":"BB"}}]' , ERROR_FUNC , 'encode header conflict 10')) -- BB T.Pass(encode('[{"key":"KK","values":{"foo":"AA","foo":"BB"}}]' , 'Key,Context,Example,Source,foo\nKK,,,,BB\n' , 'encode header conflict 11')) -- BB T.Pass(encode('[{"key":"KK","values":{"FOO":"AA","FOO":"BB","FOO":"CC"}}]' , 'Key,Context,Example,Source,foo\nKK,,,,CC\n' , 'encode header conflict 12')) -- CC T.Pass(encode('[{"key":"KK","values":{"Foo":"AA","FOO":"BB","FOO":"CC"}}]' , ERROR_FUNC , 'encode header conflict 13')) -- CC T.Pass(encode('[{"key":"KK","values":{"foo":"AA","FOO":"BB","FOO":"CC"}}]' , ERROR_FUNC , 'encode header conflict 14')) -- CC T.Pass(encode('[{"key":"KK","values":{"FOO":"AA","Foo":"BB","FOO":"CC"}}]' , ERROR_FUNC , 'encode header conflict 15')) -- CC T.Pass(encode('[{"key":"KK","values":{"Foo":"AA","Foo":"BB","FOO":"CC"}}]' , ERROR_FUNC , 'encode header conflict 16')) -- CC T.Pass(encode('[{"key":"KK","values":{"foo":"AA","Foo":"BB","FOO":"CC"}}]' , ERROR_FUNC , 'encode header conflict 17')) -- CC T.Pass(encode('[{"key":"KK","values":{"FOO":"AA","foo":"BB","FOO":"CC"}}]' , ERROR_FUNC , 'encode header conflict 18')) -- CC T.Pass(encode('[{"key":"KK","values":{"Foo":"AA","foo":"BB","FOO":"CC"}}]' , ERROR_FUNC , 'encode header conflict 19')) -- CC T.Pass(encode('[{"key":"KK","values":{"foo":"AA","foo":"BB","FOO":"CC"}}]' , ERROR_FUNC , 'encode header conflict 20')) -- CC T.Pass(encode('[{"key":"KK","values":{"FOO":"AA","FOO":"BB","Foo":"CC"}}]' , ERROR_FUNC , 'encode header conflict 21')) -- CC T.Pass(encode('[{"key":"KK","values":{"Foo":"AA","FOO":"BB","Foo":"CC"}}]' , ERROR_FUNC , 'encode header conflict 22')) -- CC T.Pass(encode('[{"key":"KK","values":{"foo":"AA","FOO":"BB","Foo":"CC"}}]' , ERROR_FUNC , 'encode header conflict 23')) -- CC T.Pass(encode('[{"key":"KK","values":{"FOO":"AA","Foo":"BB","Foo":"CC"}}]' , ERROR_FUNC , 'encode header conflict 24')) -- CC T.Pass(encode('[{"key":"KK","values":{"Foo":"AA","Foo":"BB","Foo":"CC"}}]' , 'Key,Context,Example,Source,foo\nKK,,,,CC\n' , 'encode header conflict 25')) -- CC T.Pass(encode('[{"key":"KK","values":{"foo":"AA","Foo":"BB","Foo":"CC"}}]' , ERROR_FUNC , 'encode header conflict 26')) -- CC T.Pass(encode('[{"key":"KK","values":{"FOO":"AA","foo":"BB","Foo":"CC"}}]' , ERROR_FUNC , 'encode header conflict 27')) -- CC T.Pass(encode('[{"key":"KK","values":{"Foo":"AA","foo":"BB","Foo":"CC"}}]' , ERROR_FUNC , 'encode header conflict 28')) -- CC T.Pass(encode('[{"key":"KK","values":{"foo":"AA","foo":"BB","Foo":"CC"}}]' , ERROR_FUNC , 'encode header conflict 29')) -- CC T.Pass(encode('[{"key":"KK","values":{"FOO":"AA","FOO":"BB","foo":"CC"}}]' , ERROR_FUNC , 'encode header conflict 30')) -- CC T.Pass(encode('[{"key":"KK","values":{"Foo":"AA","FOO":"BB","foo":"CC"}}]' , ERROR_FUNC , 'encode header conflict 31')) -- CC T.Pass(encode('[{"key":"KK","values":{"foo":"AA","FOO":"BB","foo":"CC"}}]' , ERROR_FUNC , 'encode header conflict 32')) -- CC T.Pass(encode('[{"key":"KK","values":{"FOO":"AA","Foo":"BB","foo":"CC"}}]' , ERROR_FUNC , 'encode header conflict 33')) -- CC T.Pass(encode('[{"key":"KK","values":{"Foo":"AA","Foo":"BB","foo":"CC"}}]' , ERROR_FUNC , 'encode header conflict 34')) -- CC T.Pass(encode('[{"key":"KK","values":{"foo":"AA","Foo":"BB","foo":"CC"}}]' , ERROR_FUNC , 'encode header conflict 35')) -- CC T.Pass(encode('[{"key":"KK","values":{"FOO":"AA","foo":"BB","foo":"CC"}}]' , ERROR_FUNC , 'encode header conflict 36')) -- CC T.Pass(encode('[{"key":"KK","values":{"Foo":"AA","foo":"BB","foo":"CC"}}]' , ERROR_FUNC , 'encode header conflict 37')) -- CC T.Pass(encode('[{"key":"KK","values":{"foo":"AA","foo":"BB","foo":"CC"}}]' , 'Key,Context,Example,Source,foo\nKK,,,,CC\n' , 'encode header conflict 38')) -- CC -- Test conflicting index headers. T.Pass(encode('[{"values":{"foo":"A"}},{"values":{"foo":"B"}}]' , ERROR_FUNC , 'encode index conflict 00')) T.Pass(encode('[{"key":"K","values":{"foo":"A"}},{"values":{"foo":"B"}}]' , ERROR_FUNC , 'encode index conflict 01')) T.Pass(encode('[{"context":"C","values":{"foo":"A"}},{"values":{"foo":"B"}}]' , ERROR_FUNC , 'encode index conflict 02')) T.Pass(encode('[{"source":"S","values":{"foo":"A"}},{"values":{"foo":"B"}}]' , ERROR_FUNC , 'encode index conflict 03')) T.Pass(encode('[{"key":"K","context":"C","values":{"foo":"A"}},{"values":{"foo":"B"}}]' , ERROR_FUNC , 'encode index conflict 04')) T.Pass(encode('[{"key":"K","source":"S","values":{"foo":"A"}},{"values":{"foo":"B"}}]' , ERROR_FUNC , 'encode index conflict 05')) T.Pass(encode('[{"context":"C","source":"S","values":{"foo":"A"}},{"values":{"foo":"B"}}]' , ERROR_FUNC , 'encode index conflict 06')) T.Pass(encode('[{"key":"K","context":"C","source":"S","values":{"foo":"A"}},{"values":{"foo":"B"}}]' , ERROR_FUNC , 'encode index conflict 07')) T.Pass(encode('[{"values":{"foo":"A"}},{"key":"K","values":{"foo":"B"}}]' , ERROR_FUNC , 'encode index conflict 08')) T.Pass(encode('[{"key":"K","values":{"foo":"A"}},{"key":"K","values":{"foo":"B"}}]' , ERROR_FUNC , 'encode index conflict 09')) T.Pass(encode('[{"context":"C","values":{"foo":"A"}},{"key":"K","values":{"foo":"B"}}]' , ERROR_FUNC , 'encode index conflict 10')) T.Pass(encode('[{"source":"S","values":{"foo":"A"}},{"key":"K","values":{"foo":"B"}}]' , 'Key,Context,Example,Source,foo\n,,,S,A\nK,,,,B\n' , 'encode index conflict 11')) T.Pass(encode('[{"key":"K","context":"C","values":{"foo":"A"}},{"key":"K","values":{"foo":"B"}}]' , ERROR_FUNC , 'encode index conflict 12')) T.Pass(encode('[{"key":"K","source":"S","values":{"foo":"A"}},{"key":"K","values":{"foo":"B"}}]' , ERROR_FUNC , 'encode index conflict 13')) T.Pass(encode('[{"context":"C","source":"S","values":{"foo":"A"}},{"key":"K","values":{"foo":"B"}}]' , 'Key,Context,Example,Source,foo\n,C,,S,A\nK,,,,B\n' , 'encode index conflict 14')) T.Pass(encode('[{"key":"K","context":"C","source":"S","values":{"foo":"A"}},{"key":"K","values":{"foo":"B"}}]' , ERROR_FUNC , 'encode index conflict 15')) T.Pass(encode('[{"values":{"foo":"A"}},{"context":"C","values":{"foo":"B"}}]' , ERROR_FUNC , 'encode index conflict 16')) T.Pass(encode('[{"key":"K","values":{"foo":"A"}},{"context":"C","values":{"foo":"B"}}]' , ERROR_FUNC , 'encode index conflict 17')) T.Pass(encode('[{"context":"C","values":{"foo":"A"}},{"context":"C","values":{"foo":"B"}}]' , ERROR_FUNC , 'encode index conflict 18')) T.Pass(encode('[{"source":"S","values":{"foo":"A"}},{"context":"C","values":{"foo":"B"}}]' , ERROR_FUNC , 'encode index conflict 19')) T.Pass(encode('[{"key":"K","context":"C","values":{"foo":"A"}},{"context":"C","values":{"foo":"B"}}]' , ERROR_FUNC , 'encode index conflict 20')) T.Pass(encode('[{"key":"K","source":"S","values":{"foo":"A"}},{"context":"C","values":{"foo":"B"}}]' , ERROR_FUNC , 'encode index conflict 21')) T.Pass(encode('[{"context":"C","source":"S","values":{"foo":"A"}},{"context":"C","values":{"foo":"B"}}]' , ERROR_FUNC , 'encode index conflict 22')) T.Pass(encode('[{"key":"K","context":"C","source":"S","values":{"foo":"A"}},{"context":"C","values":{"foo":"B"}}]' , ERROR_FUNC , 'encode index conflict 23')) T.Pass(encode('[{"values":{"foo":"A"}},{"source":"S","values":{"foo":"B"}}]' , ERROR_FUNC , 'encode index conflict 24')) T.Pass(encode('[{"key":"K","values":{"foo":"A"}},{"source":"S","values":{"foo":"B"}}]' , 'Key,Context,Example,Source,foo\nK,,,,A\n,,,S,B\n' , 'encode index conflict 25')) T.Pass(encode('[{"context":"C","values":{"foo":"A"}},{"source":"S","values":{"foo":"B"}}]' , ERROR_FUNC , 'encode index conflict 26')) T.Pass(encode('[{"source":"S","values":{"foo":"A"}},{"source":"S","values":{"foo":"B"}}]' , ERROR_FUNC , 'encode index conflict 27')) T.Pass(encode('[{"key":"K","context":"C","values":{"foo":"A"}},{"source":"S","values":{"foo":"B"}}]' , 'Key,Context,Example,Source,foo\nK,C,,,A\n,,,S,B\n' , 'encode index conflict 28')) T.Pass(encode('[{"key":"K","source":"S","values":{"foo":"A"}},{"source":"S","values":{"foo":"B"}}]' , 'Key,Context,Example,Source,foo\nK,,,S,A\n,,,S,B\n' , 'encode index conflict 29')) T.Pass(encode('[{"context":"C","source":"S","values":{"foo":"A"}},{"source":"S","values":{"foo":"B"}}]' , 'Key,Context,Example,Source,foo\n,C,,S,A\n,,,S,B\n' , 'encode index conflict 30')) T.Pass(encode('[{"key":"K","context":"C","source":"S","values":{"foo":"A"}},{"source":"S","values":{"foo":"B"}}]' , 'Key,Context,Example,Source,foo\nK,C,,S,A\n,,,S,B\n' , 'encode index conflict 31')) T.Pass(encode('[{"values":{"foo":"A"}},{"key":"K","context":"C","values":{"foo":"B"}}]' , ERROR_FUNC , 'encode index conflict 32')) T.Pass(encode('[{"key":"K","values":{"foo":"A"}},{"key":"K","context":"C","values":{"foo":"B"}}]' , ERROR_FUNC , 'encode index conflict 33')) T.Pass(encode('[{"context":"C","values":{"foo":"A"}},{"key":"K","context":"C","values":{"foo":"B"}}]' , ERROR_FUNC , 'encode index conflict 34')) T.Pass(encode('[{"source":"S","values":{"foo":"A"}},{"key":"K","context":"C","values":{"foo":"B"}}]' , 'Key,Context,Example,Source,foo\n,,,S,A\nK,C,,,B\n' , 'encode index conflict 35')) T.Pass(encode('[{"key":"K","context":"C","values":{"foo":"A"}},{"key":"K","context":"C","values":{"foo":"B"}}]' , ERROR_FUNC , 'encode index conflict 36')) T.Pass(encode('[{"key":"K","source":"S","values":{"foo":"A"}},{"key":"K","context":"C","values":{"foo":"B"}}]' , ERROR_FUNC , 'encode index conflict 37')) T.Pass(encode('[{"context":"C","source":"S","values":{"foo":"A"}},{"key":"K","context":"C","values":{"foo":"B"}}]' , 'Key,Context,Example,Source,foo\n,C,,S,A\nK,C,,,B\n' , 'encode index conflict 38')) T.Pass(encode('[{"key":"K","context":"C","source":"S","values":{"foo":"A"}},{"key":"K","context":"C","values":{"foo":"B"}}]' , ERROR_FUNC , 'encode index conflict 39')) T.Pass(encode('[{"values":{"foo":"A"}},{"key":"K","source":"S","values":{"foo":"B"}}]' , ERROR_FUNC , 'encode index conflict 40')) T.Pass(encode('[{"key":"K","values":{"foo":"A"}},{"key":"K","source":"S","values":{"foo":"B"}}]' , ERROR_FUNC , 'encode index conflict 41')) T.Pass(encode('[{"context":"C","values":{"foo":"A"}},{"key":"K","source":"S","values":{"foo":"B"}}]' , ERROR_FUNC , 'encode index conflict 42')) T.Pass(encode('[{"source":"S","values":{"foo":"A"}},{"key":"K","source":"S","values":{"foo":"B"}}]' , 'Key,Context,Example,Source,foo\n,,,S,A\nK,,,S,B\n' , 'encode index conflict 43')) T.Pass(encode('[{"key":"K","context":"C","values":{"foo":"A"}},{"key":"K","source":"S","values":{"foo":"B"}}]' , ERROR_FUNC , 'encode index conflict 44')) T.Pass(encode('[{"key":"K","source":"S","values":{"foo":"A"}},{"key":"K","source":"S","values":{"foo":"B"}}]' , ERROR_FUNC , 'encode index conflict 45')) T.Pass(encode('[{"context":"C","source":"S","values":{"foo":"A"}},{"key":"K","source":"S","values":{"foo":"B"}}]' , 'Key,Context,Example,Source,foo\n,C,,S,A\nK,,,S,B\n' , 'encode index conflict 46')) T.Pass(encode('[{"key":"K","context":"C","source":"S","values":{"foo":"A"}},{"key":"K","source":"S","values":{"foo":"B"}}]' , ERROR_FUNC , 'encode index conflict 47')) T.Pass(encode('[{"values":{"foo":"A"}},{"context":"C","source":"S","values":{"foo":"B"}}]' , ERROR_FUNC , 'encode index conflict 48')) T.Pass(encode('[{"key":"K","values":{"foo":"A"}},{"context":"C","source":"S","values":{"foo":"B"}}]' , 'Key,Context,Example,Source,foo\nK,,,,A\n,C,,S,B\n' , 'encode index conflict 49')) T.Pass(encode('[{"context":"C","values":{"foo":"A"}},{"context":"C","source":"S","values":{"foo":"B"}}]' , ERROR_FUNC , 'encode index conflict 50')) T.Pass(encode('[{"source":"S","values":{"foo":"A"}},{"context":"C","source":"S","values":{"foo":"B"}}]' , 'Key,Context,Example,Source,foo\n,,,S,A\n,C,,S,B\n' , 'encode index conflict 51')) T.Pass(encode('[{"key":"K","context":"C","values":{"foo":"A"}},{"context":"C","source":"S","values":{"foo":"B"}}]' , 'Key,Context,Example,Source,foo\nK,C,,,A\n,C,,S,B\n' , 'encode index conflict 52')) T.Pass(encode('[{"key":"K","source":"S","values":{"foo":"A"}},{"context":"C","source":"S","values":{"foo":"B"}}]' , 'Key,Context,Example,Source,foo\nK,,,S,A\n,C,,S,B\n' , 'encode index conflict 53')) T.Pass(encode('[{"context":"C","source":"S","values":{"foo":"A"}},{"context":"C","source":"S","values":{"foo":"B"}}]' , ERROR_FUNC , 'encode index conflict 54')) T.Pass(encode('[{"key":"K","context":"C","source":"S","values":{"foo":"A"}},{"context":"C","source":"S","values":{"foo":"B"}}]' , 'Key,Context,Example,Source,foo\nK,C,,S,A\n,C,,S,B\n' , 'encode index conflict 55')) T.Pass(encode('[{"values":{"foo":"A"}},{"key":"K","context":"C","source":"S","values":{"foo":"B"}}]' , ERROR_FUNC , 'encode index conflict 56')) T.Pass(encode('[{"key":"K","values":{"foo":"A"}},{"key":"K","context":"C","source":"S","values":{"foo":"B"}}]' , ERROR_FUNC , 'encode index conflict 57')) T.Pass(encode('[{"context":"C","values":{"foo":"A"}},{"key":"K","context":"C","source":"S","values":{"foo":"B"}}]' , ERROR_FUNC , 'encode index conflict 58')) T.Pass(encode('[{"source":"S","values":{"foo":"A"}},{"key":"K","context":"C","source":"S","values":{"foo":"B"}}]' , 'Key,Context,Example,Source,foo\n,,,S,A\nK,C,,S,B\n' , 'encode index conflict 59')) T.Pass(encode('[{"key":"K","context":"C","values":{"foo":"A"}},{"key":"K","context":"C","source":"S","values":{"foo":"B"}}]' , ERROR_FUNC , 'encode index conflict 60')) T.Pass(encode('[{"key":"K","source":"S","values":{"foo":"A"}},{"key":"K","context":"C","source":"S","values":{"foo":"B"}}]' , ERROR_FUNC , 'encode index conflict 61')) T.Pass(encode('[{"context":"C","source":"S","values":{"foo":"A"}},{"key":"K","context":"C","source":"S","values":{"foo":"B"}}]' , 'Key,Context,Example,Source,foo\n,C,,S,A\nK,C,,S,B\n' , 'encode index conflict 62')) T.Pass(encode('[{"key":"K","context":"C","source":"S","values":{"foo":"A"}},{"key":"K","context":"C","source":"S","values":{"foo":"B"}}]' , ERROR_FUNC , 'encode index conflict 63')) -- Test merged headers. T.Pass(encode('[{"key":"11","values":{"A":"AA","B":"BB"}},{"key":"22","values":{"B":"BB","C":"CC"}}]', 'Key,Context,Example,Source,a,b,c\n11,,,,AA,BB,\n22,,,,,BB,CC\n', 'encode merge headers')) -- Test CSV format. T.Pass(encode('[{"key":"KK","values":{"\\"g\\"":"GG","a":"AA","b":"BB","c d":"CD","e f":"EF"}}]', 'Key,Context,Example,Source,"""g""",a,b,c d,e f\nKK,,,,GG,AA,BB,CD,EF\n', 'encode csv format'))
--[[ Generic training script for CUB GAWWN. --]] require 'torch' require 'nn' require 'nngraph' require 'optim' require 'stn' require 'cudnn' require 'CropInvert' util = paths.dofile('util.lua') opt = { num_holdout = 0, numCaption = 1, port = 8000, iou_thresh = 0.8, dbg = 0, num_elt = 2, save_every = 10, print_every = 1, dataset = 'cub_stn', img_dir = '', cls_weight = 0.5, filenames = '', data_root = '/mnt/brain3/datasets/txt2img/cub_ex_loc', checkpoint_dir = '/home/reedscot/checkpoints', batchSize = 64, doc_length = 201, loadSize = 150, txtSize = 1024, -- # of dim for raw text. fineSize = 128, nt = 128, -- # of dim for text features. nz = 100, -- # of dim for Z ngf = 128, -- # of gen filters in first conv layer ndf = 64, -- # of discrim filters in first conv layer nThreads = 4, -- # of data loading threads to use niter = 1000, -- # of iter at starting learning rate lr = 0.0002, -- initial learning rate for adam lr_decay = 0.5, -- initial learning rate for adam decay_every = 100, beta1 = 0.5, -- momentum term of adam ntrain = math.huge, -- # of examples per epoch. math.huge for full dataset display = 1, -- display samples while training. 0 = false display_id = 10, -- display window id. gpu = 2, -- gpu = 0 is CPU mode. gpu=X is GPU mode on GPU X name = 'vg', noise = 'normal', -- uniform / normal init_g = '', init_d = '', use_cudnn = 1, } -- one-line argument parser. parses enviroment variables to override the defaults for k,v in pairs(opt) do opt[k] = tonumber(os.getenv(k)) or os.getenv(k) or opt[k] end print(opt) if opt.display == 0 then opt.display = false end if opt.display then disp = require 'display' disp.configure({hostname='0.0.0.0', port=opt.port}) end if opt.gpu > 0 then ok, cunn = pcall(require, 'cunn') ok2, cutorch = pcall(require, 'cutorch') cutorch.setDevice(opt.gpu) end opt.manualSeed = torch.random(1, 10000) -- fix seed print("Random Seed: " .. opt.manualSeed) torch.manualSeed(opt.manualSeed) torch.setnumthreads(1) torch.setdefaulttensortype('torch.FloatTensor') -- create data loader local DataLoader = paths.dofile('data/data.lua') local data = DataLoader.new(opt.nThreads, opt.dataset, opt) print("Dataset: " .. opt.dataset, " Size: ", data:size()) ---------------------------------------------------------------------------- local function weights_init(m) local name = torch.type(m) if name:find('Convolution') then m.weight:normal(0.0, 0.02) m.bias:fill(0) elseif name:find('BatchNormalization') then if m.weight then m.weight:normal(1.0, 0.02) end if m.bias then m.bias:fill(0) end end end local nc = 3 local nz = opt.nz local ndf = opt.ndf local ngf = opt.ngf local real_label = 1 local fake_label = 0 local SpatialBatchNormalization = nn.SpatialBatchNormalization local SpatialConvolution = nn.SpatialConvolution local SpatialFullConvolution = nn.SpatialFullConvolution if opt.init_g == '' then prep_noise = nn.Sequential() :add(nn.View(-1,opt.nz)) :add(nn.Linear(opt.nz, ngf*4)) prep_txt_g = nn.Sequential() :add(nn.View(-1,opt.txtSize)) :add(nn.Linear(opt.txtSize, ngf*4)) txtGlobalG = nn.Sequential() :add(nn.ParallelTable() :add(nn.Sequential() -- { noise, txt } :add(nn.SelectTable(2)) -- txt :add(prep_txt_g) :add(nn.Replicate(16,3)) :add(nn.Replicate(16,4)) :add(nn.Transpose({2,3},{3,4}))) -- chw to hwc -- 512 x 16 x 16 :add(nn.Sequential() -- loc :add(nn.View(-1,2,3)) :add(nn.AffineGridGeneratorBHWD(16, 16)))) :add(nn.BilinearSamplerBHWD()) :add(nn.Transpose({3,4},{2,3})) -- hwc to chw :add(nn.Contiguous()) :add(nn.View(-1,opt.num_elt,ngf*4,16,16)) :add(nn.Mean(2)) -- average over elements -- (512) x 16 x 16 :add(SpatialConvolution(ngf*4, ngf*4, 4, 4, 2, 2, 1, 1)) :add(SpatialBatchNormalization(ngf*4)):add(nn.ReLU(true)) -- (ngf*2) x 8 x 8 :add(SpatialConvolution(ngf*4, ngf*4, 4, 4, 2, 2, 1, 1)) :add(SpatialBatchNormalization(ngf*4)):add(nn.ReLU(true)) -- (ngf*4) x 4 x 4 :add(SpatialConvolution(ngf*4, ngf*4, 4, 4)) :add(SpatialBatchNormalization(ngf*4)):add(nn.ReLU(true)) -- (ngf*4) x 1 x 1 combiner_local = nn.Sequential() :add(nn.ParallelTable() :add(prep_noise) -- (ngf*4) :add(prep_txt_g)) -- (ngf*4) :add(nn.JoinTable(2)) :add(nn.ReLU(true)) combiner_global = nn.Sequential() :add(nn.ConcatTable() :add(nn.Sequential() :add(nn.SelectTable(1)) -- get { noise, txt } :add(nn.SelectTable(1)) -- get noise :add(nn.Select(2,1)) -- pick first noise element :add(nn.Linear(opt.nz, ngf*4)) -- (ngf*4) :add(nn.ReLU(true))) :add(txtGlobalG)) -- (ngf*4) x 1 x 1 :add(nn.JoinTable(2)) :add(nn.ReLU(true)) -- global path globalG = nn.Sequential() :add(combiner_global) :add(nn.View(-1, ngf*8, 1, 1)) :add(SpatialFullConvolution(ngf*8, ngf * 8, 4, 4)) :add(SpatialBatchNormalization(ngf * 8)) :add(nn.ReLU(true)) -- state size: (ngf*8) x 4 x 4 :add(SpatialFullConvolution(ngf * 8, ngf * 4, 4, 4, 2, 2, 1, 1)) :add(SpatialBatchNormalization(ngf * 4)) :add(nn.ReLU(true)) -- state size: (ngf*4) x 8 x 8 :add(SpatialFullConvolution(ngf * 4, ngf * 2, 4, 4, 2, 2, 1, 1)) :add(SpatialBatchNormalization(ngf * 2)) -- state size: (ngf*2) x 16 x 16 :add(nn.ReLU(true)) -- regions path convG = nn.Sequential() :add(combiner_local) :add(nn.View(-1, ngf*8, 1, 1)) :add(SpatialFullConvolution(ngf*8, ngf * 8, 4, 4)) :add(SpatialBatchNormalization(ngf * 8)) :add(nn.ConcatTable() :add(nn.Sequential() -- state size: (ngf*8) x 4 x 4 :add(SpatialConvolution(ngf * 8, ngf * 2, 1, 1, 1, 1, 0, 0)) :add(SpatialBatchNormalization(ngf * 2)):add(nn.ReLU(true)) :add(SpatialConvolution(ngf * 2, ngf * 2, 3, 3, 1, 1, 1, 1)) :add(SpatialBatchNormalization(ngf * 2)):add(nn.ReLU(true)) :add(SpatialConvolution(ngf * 2, ngf * 8, 3, 3, 1, 1, 1, 1)) :add(SpatialBatchNormalization(ngf * 8))) :add(nn.Identity())) :add(nn.CAddTable()) :add(nn.ReLU(true)) -- state size: (ngf*8) x 4 x 4 :add(SpatialFullConvolution(ngf * 8, ngf * 4, 4, 4, 2, 2, 1, 1)) :add(SpatialBatchNormalization(ngf * 4)) -- state size: (ngf*4) x 8 x 8 :add(nn.ConcatTable() :add(nn.Sequential() :add(SpatialConvolution(ngf * 4, ngf, 1, 1, 1, 1, 0, 0)) :add(SpatialBatchNormalization(ngf)):add(nn.ReLU(true)) :add(SpatialConvolution(ngf, ngf, 3, 3, 1, 1, 1, 1)) :add(SpatialBatchNormalization(ngf)):add(nn.ReLU(true)) :add(SpatialConvolution(ngf, ngf * 4, 3, 3, 1, 1, 1, 1)) :add(SpatialBatchNormalization(ngf * 4))) :add(nn.Identity())) :add(nn.CAddTable()) :add(nn.ReLU(true)) -- state size: (ngf*4) x 8 x 8 :add(SpatialFullConvolution(ngf * 4, ngf * 2, 4, 4, 2, 2, 1, 1)) :add(SpatialBatchNormalization(ngf * 2)) -- here we are at 16 x 16. :add(nn.Transpose({2,3},{3,4})) -- chw to hwc regionsG = nn.Sequential() :add(nn.ParallelTable() :add(convG) :add(nn.Sequential() :add(nn.View(-1,2,3)) :add(nn.AffineGridGeneratorBHWD(16, 16)))) :add(nn.BilinearSamplerBHWD()) :add(nn.Transpose({3,4},{2,3})) -- hwc to chw -- unfold elements :add(nn.View(-1, opt.num_elt, ngf * 2, 16, 16)) -- average over elements :add(nn.Mean(2)) :add(nn.ReLU(true)) -- combines global and local region information. -- inputs are assumed to be { { noise, txt }, loc } netG = nn.Sequential() :add(nn.ConcatTable() :add(globalG) :add(regionsG)) :add(nn.JoinTable(2)) -- mix them together :add(SpatialFullConvolution(ngf * 4, ngf * 2, 3, 3, 1, 1, 1, 1)) :add(SpatialBatchNormalization(ngf*2)):add(nn.ReLU(true)) -- state size: (ngf*4) x 16 x 16 :add(SpatialFullConvolution(ngf * 2, ngf, 4, 4, 2, 2, 1, 1)) :add(SpatialBatchNormalization(ngf)):add(nn.ReLU(true)) -- state size: (ngf) x 32 x 32 :add(SpatialFullConvolution(ngf, 32, 4, 4, 2, 2, 1, 1)) :add(SpatialBatchNormalization(32)):add(nn.ReLU(true)) -- state size: (16) x 64 x 64 :add(SpatialFullConvolution(32, nc, 4, 4, 2, 2, 1, 1)) :add(nn.Tanh()) -- state size: (nc) x 128 x 128 netG:apply(weights_init) else netG = torch.load(opt.init_g) end if opt.init_d == '' then -- netD expects {img, loc, txt} imgGlobalD = nn.Sequential() :add(nn.SelectTable(1)) -- state size: (nc) x 128 x 128 :add(SpatialConvolution(nc, ndf, 4, 4, 2, 2, 1, 1)) :add(nn.LeakyReLU(0.2, true)) -- state size: (nc) x 64 x 64 :add(SpatialConvolution(ndf, ndf, 4, 4, 2, 2, 1, 1)) :add(nn.LeakyReLU(0.2, true)) -- state size: (ndf) x 32 x 32 :add(SpatialConvolution(ndf, ndf * 2, 4, 4, 2, 2, 1, 1)) :add(SpatialBatchNormalization(ndf * 2)):add(nn.LeakyReLU(0.2, true)) -- state size: (ndf*2) x 16 x 16 :add(SpatialConvolution(ndf * 2, ndf * 2, 3, 3, 1, 1, 1, 1)) :add(SpatialBatchNormalization(ndf * 2)):add(nn.LeakyReLU(0.2, true)) -- state size: (ndf*2) x 16 x 16 prep_txt_d = nn.Sequential() :add(nn.SelectTable(3)) :add(nn.View(-1,opt.txtSize)) :add(nn.Linear(opt.txtSize, opt.nt)) :add(nn.LeakyReLU(0.2,true)) prep_loc_d = nn.Sequential() :add(nn.SelectTable(2)) :add(nn.View(-1,2,3)) :add(nn.AffineGridGeneratorBHWD(16, 16)) -- region pathway imgTextRegionD = nn.Sequential() :add(nn.ConcatTable() :add(nn.Sequential() -- (ndf*2) x 16 x 16 :add(imgGlobalD) -- opt.num_elt x (ndf*2) x 16 x 16 :add(nn.Replicate(opt.num_elt,2)) -- (ndf*2) x 16 x 16 :add(nn.View(-1,ndf*2,16,16))) :add(nn.Sequential() -- text path :add(prep_txt_d) -- opt.nt -- (opt.nt) x 1 :add(nn.Replicate(opt.num_elt,2)) -- opt.num_elt x (opt.nt) x 1 :add(nn.View(-1,opt.nt)) -- (opt.nt) x 1 :add(nn.Replicate(16,3)) -- (opt.nt) x 16 :add(nn.Replicate(16,4)))) -- (opt.nt) x 16 x 16 :add(nn.JoinTable(2)) :add(SpatialConvolution(ndf * 2 + opt.nt, ndf * 2, 3, 3, 1, 1, 1, 1)) :add(SpatialBatchNormalization(ndf * 2)):add(nn.LeakyReLU(0.2, true)) :add(nn.Transpose({2,3},{3,4})) regionD = nn.Sequential() :add(nn.ConcatTable() -- keypoint multiplication :add(imgTextRegionD) :add(prep_loc_d)) :add(nn.BilinearSamplerBHWD()) :add(nn.Transpose({3,4},{2,3})) -- (ndf*2) x 16 x 16 :add(nn.Contiguous()) -- state size: (ndf*2) x 16 x 16 :add(SpatialConvolution(ndf * 2, ndf * 2, 1, 1)) :add(SpatialBatchNormalization(ndf * 2)):add(nn.LeakyReLU(0.2, true)) -- state size: (ndf*2) x 16 x 16 :add(SpatialConvolution(ndf * 2, ndf, 1, 1)) -- state size: (ndf) x 16 x 16 :add(nn.Mean(4)) :add(nn.Mean(3)) :add(nn.LeakyReLU(0.2, true)) -- global pathway -- state size: (ndf*2) x 16 x 16 convGlobalD = nn.Sequential() :add(imgGlobalD) -- (ndf*2) x 16 x 16 :add(SpatialConvolution(ndf * 2, ndf * 4, 4, 4, 2, 2, 1, 1)) :add(SpatialBatchNormalization(ndf * 4)):add(nn.LeakyReLU(0.2,true)) -- (ndf*4) x 8 x 8 :add(SpatialConvolution(ndf * 4, ndf * 8, 4, 4, 2, 2, 1, 1)) :add(SpatialBatchNormalization(ndf * 8)):add(nn.LeakyReLU(0.2,true)) -- now 4x4 -- (ndf*8) x 4 x 4 txtGlobalD = nn.Sequential() :add(nn.ConcatTable() :add(nn.Sequential() :add(prep_txt_d) -- opt.nt :add(nn.Replicate(16,3)) :add(nn.Replicate(16,4)) :add(nn.Transpose({2,3},{3,4}))) -- chw to hwc -- 512 x 16 x 16 :add(nn.Sequential() -- loc :add(nn.SelectTable(2)) :add(nn.View(-1,2,3)) :add(nn.AffineGridGeneratorBHWD(16, 16)))) :add(nn.BilinearSamplerBHWD()) :add(nn.Transpose({3,4},{2,3})) -- hwc to chw :add(nn.Contiguous()) :add(nn.View(-1,opt.num_elt,opt.nt,16,16)) :add(nn.Mean(2)) -- average over elements -- (opt.nt) x 16 x 16 :add(SpatialConvolution(opt.nt, ndf*4, 4, 4, 2, 2, 1, 1)) :add(SpatialBatchNormalization(ndf*4)):add(nn.ReLU(true)) -- (ndf) x 8 x 8 :add(SpatialConvolution(ndf*4, ndf, 4, 4, 2, 2, 1, 1)) :add(SpatialBatchNormalization(ndf)):add(nn.ReLU(true)) -- (ndf*) x 4 x 4 globalD = nn.Sequential() :add(nn.ConcatTable() :add(convGlobalD) :add(txtGlobalD)) :add(nn.JoinTable(2)) :add(nn.Contiguous()) -- state size: (ndf*9) x 4 x 4 :add(SpatialConvolution(ndf * 9, ndf * 4, 1, 1)) :add(SpatialBatchNormalization(ndf * 4)) :add(nn.LeakyReLU(0.2, true)) -- state size: (ndf*4) x 4 x 4 :add(SpatialConvolution(ndf * 4, ndf, 4, 4)) :add(SpatialBatchNormalization(ndf)):add(nn.LeakyReLU(0.2, true)) -- state size: (ndf) x 1 x 1 :add(nn.View(-1,ndf)) netD = nn.Sequential() :add(nn.ConcatTable() :add(regionD) :add(globalD)) :add(nn.JoinTable(2)) :add(nn.Linear(ndf * 2, ndf)) :add(nn.BatchNormalization(ndf)):add(nn.LeakyReLU(0.2, true)) :add(nn.Linear(ndf, 1)) :add(nn.Sigmoid()) netD:apply(weights_init) else netD = torch.load(opt.init_d) end netI = nn.Sequential() netI:add(nn.View(-1,2,3)) netI:add(nn.CropInvert()) netI:add(nn.View(-1,opt.num_elt,2,3)) local criterion = nn.BCECriterion() --------------------------------------------------------------------------- optimStateG = { learningRate = opt.lr, beta1 = opt.beta1, } optimStateD = { learningRate = opt.lr, beta1 = opt.beta1, } ---------------------------------------------------------------------------- local input_img = torch.Tensor(opt.batchSize, 3, opt.fineSize, opt.fineSize) local input_fake = torch.Tensor(opt.batchSize, 3, opt.fineSize, opt.fineSize) local input_dbg = torch.Tensor(opt.batchSize*opt.num_elt, 3, opt.fineSize, opt.fineSize) local input_txt = torch.Tensor(opt.batchSize, opt.num_elt, opt.txtSize) local input_txt_shuf = torch.Tensor(opt.batchSize, opt.num_elt, opt.txtSize) local input_txt_flat = torch.Tensor(opt.batchSize*opt.num_elt, opt.txtSize) local input_loc = torch.Tensor(opt.batchSize, opt.num_elt, 2, 3) local input_loc_g = torch.Tensor(opt.batchSize, opt.num_elt, 2, 3) local input_loc_shuf = torch.Tensor(opt.batchSize, opt.num_elt, 2, 3) local noise = torch.Tensor(opt.batchSize, opt.num_elt, nz) local label = torch.Tensor(opt.batchSize) local errD, errG, errW ---------------------------------------------------------------------------- local epoch_tm = torch.Timer() local tm = torch.Timer() local data_tm = torch.Timer() ---------------------------------------------------------------------------- if opt.gpu > 0 then input_img = input_img:cuda() input_fake = input_fake:cuda() input_dbg = input_dbg:cuda() input_txt = input_txt:cuda() input_txt_shuf = input_txt_shuf:cuda() input_txt_flat = input_txt_flat:cuda() input_loc = input_loc:cuda() input_loc_g = input_loc_g:cuda() input_loc_shuf = input_loc_shuf:cuda() noise = noise:cuda() label = label:cuda() netD:cuda() netG:cuda() netI:cuda() criterion:cuda() end if opt.use_cudnn == 1 then cudnn = require('cudnn') netD = cudnn.convert(netD, cudnn) netG = cudnn.convert(netG, cudnn) netI = cudnn.convert(netI, cudnn) end local parametersD, gradParametersD = netD:getParameters() local parametersG, gradParametersG = netG:getParameters() if opt.display then disp = require 'display' end local sample = function() data_tm:reset(); data_tm:resume() real_img, real_txt, real_loc, dbg = data:getBatch() data_tm:stop() dbg = torch.reshape(dbg, opt.batchSize * opt.num_elt, dbg:size(3), dbg:size(4), dbg:size(5)) input_dbg:copy(dbg) input_img:copy(real_img:select(2,1)) input_txt:copy(real_txt) input_loc:copy(real_loc) if opt.gpu >= 0 then input_loc:cuda() end input_loc_g:copy(netI:forward(input_loc)) local shuf_ix = torch.randperm(input_loc:size(1)) for n = 1,input_loc:size(1) do input_txt_shuf[n]:copy(input_txt[shuf_ix[n]]) end end -- create closure to evaluate f(X) and df/dX of discriminator fake_score = 0.5 local fDx = function(x) gradParametersD:zero() -- train with real label:fill(real_label) local output = netD:forward{input_img, input_loc, input_txt} errD_real = criterion:forward(output, label) local df_do = criterion:backward(output, label) local deltas = netD:backward({input_img, input_loc, input_txt}, df_do) errD_wrong = 0 if opt.cls_weight > 0 then -- train with wrong label:fill(fake_label) local output = netD:forward{input_img, input_loc, input_txt_shuf} errD_wrong = opt.cls_weight*criterion:forward(output, label) local df_do = criterion:backward(output, label) df_do:mul(opt.cls_weight) deltas = netD:backward({input_img, input_loc, input_txt_shuf}, df_do) end -- train with fake if opt.noise == 'uniform' then -- regenerate random noise noise:uniform(-1, 1) elseif opt.noise == 'normal' then noise:normal(0, 1) end label:fill(fake_label) local fake = netG:forward({ {noise, input_txt}, input_loc_g}) input_img:copy(fake) local output = netD:forward{input_img, input_loc, input_txt} -- update fake score tracker local cur_score = output:mean() fake_score = 0.99 * fake_score + 0.01 * cur_score local errD_fake = criterion:forward(output, label) local df_do = criterion:backward(output, label) local fake_weight = 1 - opt.cls_weight errD_fake = errD_fake*fake_weight df_do:mul(fake_weight) netD:backward({input_img, input_loc, input_txt}, df_do) errD = errD_real + errD_fake + errD_wrong errW = errD_wrong return errD, gradParametersD end -- create closure to evaluate f(X) and df/dX of generator local fGx = function(x) gradParametersG:zero() label:fill(real_label) -- fake labels are real for generator cost local output = netD.output local cur_score = output:mean() fake_score = 0.99 * fake_score + 0.01 * cur_score errG = criterion:forward(output, label) local df_do = criterion:backward(output, label) local df_dr = netD:updateGradInput({input_img, input_loc, input_txt}, df_do) local deltas = netG:backward({ { noise, input_txt }, input_loc_g}, df_dr[1]) return errG, gradParametersG end -- train for epoch = 1, opt.niter do epoch_tm:reset() if epoch % opt.decay_every == 0 then optimStateG.learningRate = optimStateG.learningRate * opt.lr_decay optimStateD.learningRate = optimStateD.learningRate * opt.lr_decay end for i = 1, math.min(data:size(), opt.ntrain), opt.batchSize do tm:reset() sample() optim.adam(fDx, parametersD, optimStateD) optim.adam(fGx, parametersG, optimStateG) if opt.dbg == 1 then disp.image(input_dbg, {win=opt.display_id, title=opt.name}) debug.debug() end -- logging if ((i-1) / opt.batchSize) % opt.print_every == 0 then print(('[%d][%d/%d] T:%.3f DT:%.3f lr: %.4g ' .. ' G:%.3f D:%.3f W:%.3f, fs:%.2f'):format( epoch, ((i-1) / opt.batchSize), math.floor(math.min(data:size(), opt.ntrain) / opt.batchSize), tm:time().real, data_tm:time().real, optimStateG.learningRate, errG and errG or -1, errD and errD or -1, errW and errW or -1, fake_score)) local fake = netG.output local bbox = util.affine_to_bbox(fake:size(), input_loc:select(2,1):narrow(1,1,4)) fake:mul(2):add(-1) for b = 1,bbox:size(2) do fake[b] = util.draw_box(fake[b], bbox[{{},b}]) end disp.image(fake:narrow(1,1,4), {win=opt.display_id, title=opt.name}) disp.image(real_img:select(2,1):narrow(1,1,4), {win=opt.display_id * 3, title=opt.name}) end end if epoch % opt.save_every == 0 then paths.mkdir(opt.checkpoint_dir) torch.save(opt.checkpoint_dir .. '/' .. opt.name .. '_' .. epoch .. '_net_G.t7', netG:clone():clearState()) torch.save(opt.checkpoint_dir .. '/' .. opt.name .. '_' .. epoch .. '_net_D.t7', netD:clone():clearState()) torch.save(opt.checkpoint_dir .. '/' .. opt.name .. '_' .. epoch .. '_opt.t7', opt) print(('End of epoch %d / %d \t Time Taken: %.3f'):format( epoch, opt.niter, epoch_tm:time().real)) end end
-- Variables for horizontal/vertical mode local banner_x = (IsVerticalScreen() and 20 or WideScale(-280,-320)) local text_wrap = (IsVerticalScreen() and 150 or 264) local text_width = (IsVerticalScreen() and 170 or 280) local score_x = (IsVerticalScreen() and 0 or WideScale(140,40)) local HighScoreRow = Def.ActorFrame{ -- setting ztest to true allows masking InitCommand=function(self) self:ztest(true) end, Def.Quad{ InitCommand=function(self) self:zoomto(_screen.w, 60) end, OnCommand=function(self) self:diffuse(Color.Black):diffusealpha(0.7) end }, Def.Banner{ InitCommand=cmd(x,banner_x; halign,0; scaletoclipped,102,40; diffusealpha,0.2 ), SetCommand=function(self, params) if params.Song and params.Song:GetBannerPath() then self:LoadFromCachedBanner( params.Song:GetBannerPath() ) end end }, --the name of the song, on top of the graphical banner LoadFont("Common Normal")..{ InitCommand=cmd(x,WideScale(-220,-280); halign,0; shadowlength,1; wrapwidthpixels,text_wrap; maxheight,58; maxwidth,text_width), SetCommand=function(self, params) if params.Song then self:settext( params.Song:GetDisplayFullTitle() ) end end } } local MachineProfile = PROFILEMAN:GetMachineProfile() -- How many difficulties do we want this ranking screen to show? Defer to the Metrics. local NumDifficulties = THEME:GetMetric("ScreenRankingSingle", "NumColumns") -- Make a table to store the difficulties we are interested in displaying. local DifficultiesToShow = {} -- Loop through available Metrics, parsing out the shortened difficulty names. for i=1,NumDifficulties do DifficultiesToShow[#DifficultiesToShow+1] = ToEnumShortString(THEME:GetMetric("ScreenRankingSingle", "ColumnDifficulty"..i)) end local HighScore = Def.ActorFrame{ SetCommand=function(self, params) if not params.Song then return end for index, steps in pairs(params.Entries) do if MachineProfile and steps then local hsl = MachineProfile:GetHighScoreList(params.Song, steps) -- hsl:GetHighScores() will return a table of HighScore objects ordered like {score#1, score#2, ...} -- we're only interested in the best score per difficulty per song, so we want hsl:GetHighScores()[1] local top_score = (hsl and (#hsl:GetHighScores() > 1)) and hsl:GetHighScores()[1] local difficulty = ToEnumShortString(steps:GetDifficulty()) if top_score then local text = top_score:GetName() .. "\n" .. FormatPercentScore( top_score:GetPercentDP() ) self:GetChild("HighScore_"..difficulty):settext( text ) else -- if there's no top_score for this particular difficulty of this particular chart -- hibernate the BitmapText actor to prevent it from being drawn and maybe mitigate framerate issues self:GetChild("HighScore_"..difficulty):hibernate( 100 ) end end end end } -- Add a name and score for each difficulty we are interested in -- These won't have actual text values assigned to them until the -- cumbersome SetCommand applied to the parent AF above... for key, difficulty in ipairs(DifficultiesToShow) do -- BitmapText actor for the name of the player and the high score itself HighScore[#HighScore+1] = Def.BitmapText{ Font="Common Normal", Name="HighScore_"..difficulty, InitCommand=cmd(x,score_x + (key-1)*100; zoom,0.8; horizalign, center) } end -- add the HighScore to the primary AF HighScoreRow[#HighScoreRow+1] = HighScore -- return the primary AF return HighScoreRow
local Timer = require("Timer") local Event = require("Event") local Entity = require("Entity") local Archetype = require("Archetype") local SystemExecutor = require("SystemExecutor") local EntityRepository = require("EntityRepository") local World = {} World.__index = World --[[ Create a new world instance @param systemClasses {SystemClass[]} (Optional) Array of system classes @param frequency {number} (Optional) define the frequency that the `process` step will be executed. Default 30 @param disableAutoUpdate {bool} (Optional) when `~= false`, the world automatically registers in the `LoopManager`, receiving the `World:Update()` method from it. Default false ]] function World.New(systemClasses, frequency, disableAutoUpdate) local world = setmetatable({ --[[ Global System Version (GSV). Before executing the Update method of each system, the world version is incremented, so at this point, the world version will always be higher than the running system version. Whenever an entity archetype is changed (received or lost component) the entity's version is updated to the current version of the world. After executing the System Update method, the version of this system is updated to the current world version. This mechanism allows a system to know if an entity has been modified after the last execution of this same system, as the entity's version is superior to the version of the last system execution. Thus, a system can contain logic if it only operates on "dirty" entities, which have undergone changes. The code for this validation on a system is `local isDirty = entity.version > self.version` ]] version = 0, --[[ Allows you to define the maximum time that the JobSystem can operate in each frame. The default value is 0.011666666666666665 = ((1000/60/1000)*0.7) A game that runs at 30fps has 0.0333 seconds to do all the processing for each frame, including rendering - 30FPS = ((1000/30/1000)*0.7)/3 = 0.007777777777777777 A game that runs at 60fps has 0.0166 seconds to do all the processing for each frame, including rendering - 60FPS = ((1000/60/1000)*0.7)/3 = 0.0038888888888888883 ]] maxTasksExecTime = 0.013333333333333334, _dirty = false, -- True when create/remove entity, add/remove entity component (change archetype) _timer = Timer.New(frequency), _systems = {}, -- systems in this world _repository = EntityRepository.New(), _entitiesCreated = {}, -- created during the execution of the Update _entitiesRemoved = {}, -- removed during execution (only removed after the last execution step) _entitiesUpdated = {}, -- changed during execution (received or lost components, therefore, changed the archetype) _onQueryMatch = Event.New(), _onChangeArchetypeEvent = Event.New(), }, World) -- System execution plan world._executor = SystemExecutor.New(world) world._onChangeArchetypeEvent:Connect(function(entity, archetypeOld, archetypeNew) world:_OnChangeArchetype(entity, archetypeOld, archetypeNew) end) -- add systems if (systemClasses ~= nil) then for _, systemClass in ipairs(systemClasses) do world:AddSystem(systemClass) end end if (not disableAutoUpdate and World.LoopManager) then world._loopCancel = World.LoopManager.Register(world) end return world end --[[ Changes the frequency of execution of the "process" step @param frequency {number} ]] function World:SetFrequency(frequency) frequency = self._timer:SetFrequency(frequency) end --[[ Get the frequency of execution of the "process" step @return number ]] function World:GetFrequency(frequency) return self._timer.Frequency end --[[ Add a new system to the world. Only one instance per type is accepted. If there is already another instance of this system in the world, any new invocation of this method will be ignored. @param systemClass {SystemClass} The system to be added in the world @param config {table} (Optional) System instance configuration ]] function World:AddSystem(systemClass, config) if systemClass then if config == nil then config = {} end if self._systems[systemClass] == nil then self._systems[systemClass] = systemClass.New(self, config) self._executor:SetSystems(self._systems) end end end --[[ Create a new entity. The entity is created in DEAD state (entity.isAlive == false) and will only be visible for queries after the cleaning step (OnRemove, OnEnter, OnExit) of the current step @param args {Component[]} @return Entity ]] function World:Entity(...) local entity = Entity.New(self._onChangeArchetypeEvent, {...}) self._dirty = true self._entitiesCreated[entity] = true entity.version = self.version -- update entity version using current Global System Version (GSV) entity.isAlive = false return entity end --[[ Performs immediate removal of an entity. If the entity was created in this step and the cleanup process has not happened yet (therefore the entity is inactive, entity.isAlive == false), the `OnRemove` event will never be fired. If the entity is alive (entity.isAlive == true), even though it is removed immediately, the `OnRemove` event will be fired at the end of the current step. @param entity {Entity} ]] function World:Remove(entity) if self._entitiesRemoved[entity] == true then return end if self._entitiesCreated[entity] == true then self._entitiesCreated[entity] = nil else self._repository:Remove(entity) self._entitiesRemoved[entity] = true if self._entitiesUpdated[entity] == nil then self._entitiesUpdated[entity] = entity.archetype end end self._dirty = true entity.isAlive = false end --[[ Run a query in this world @param query {Query|QueryBuilder} @return QueryResult ]] function World:Exec(query) if (query.isQueryBuilder) then query = query.Build() end local result, match = self._repository:Query(query) if match then self._onQueryMatch:Fire(query) end return result end --[[ Quick check to find out if a query is applicable. @param query {Query|QueryBuilder} @return QueryResult ]] function World:FastCheck(query) if (query.isQueryBuilder) then query = query.Build() end return self._repository:FastCheck(query) end --[[ Add a callback that is reported whenever a query has been successfully executed. Used internally to quickly find out if a QuerySystem will run. ]] function World:OnQueryMatch(callback) return self._onQueryMatch:Connect(callback) end --[[ Perform world update. When registered, LoopManager will invoke World Update for each step in the sequence. - process At the beginning of each frame - transform After the game engine's physics engine runs - render Before rendering the current frame @param step {"process"|"transform"|"render"} @param now {number} Usually os.clock() ]] function World:Update(step, now) self._timer:Update( now, step, function(Time) --[[ JobSystem .------------------. | pipeline | |------------------| | s:ShouldUpdate() | | s:Update() | '------------------' ]] if step == "process" then self._executor:ScheduleTasks(Time) end -- run suspended Tasks self._executor:ExecTasks(self.maxTasksExecTime) end, function(Time) --[[ .------------------. | pipeline | |------------------| | s:ShouldUpdate() | | s:Update() | | | |-- CLEAR ---------| | s:OnRemove() | | s:OnExit() | | s:OnEnter() | '------------------' ]] if step == "process" then self._executor:ExecProcess(Time) elseif step == "transform" then self._executor:ExecTransform(Time) else self._executor:ExecRender(Time) end -- cleans up after running scripts while self._dirty do self._dirty = false -- 1: remove entities local entitiesRemoved = {} for entity,_ in pairs(self._entitiesRemoved) do entitiesRemoved[entity] = self._entitiesUpdated[entity] self._entitiesUpdated[entity] = nil end self._entitiesRemoved = {} self._executor:ExecOnRemove(Time, entitiesRemoved) entitiesRemoved = nil local changed = {} local hasChange = false -- 2: Update entities in memory for entity, archetypeOld in pairs(self._entitiesUpdated) do if (archetypeOld ~= entity.archetype) then hasChange = true changed[entity] = archetypeOld end end self._entitiesUpdated = {} -- 3: Add new entities for entity, _ in pairs(self._entitiesCreated) do hasChange = true changed[entity] = Archetype.EMPTY entity.isAlive = true self._repository:Insert(entity) end self._entitiesCreated = {} if hasChange then self._executor:ExecOnExitEnter(Time, changed) changed = nil end end end ) end --[[ Destroy this instance, removing all entities, systems and events ]] function World:Destroy() if self._loopCancel then self._loopCancel() self._loopCancel = nil end if self._onChangeArchetypeEvent then self._onChangeArchetypeEvent:Destroy() self._onChangeArchetypeEvent = nil end self._repository = nil if self._systems then for _,system in pairs(self._systems) do system:Destroy() end self._systems = nil end self._timer = nil self._ExecPlan = nil self._entitiesCreated = nil self._entitiesUpdated = nil self._entitiesRemoved = nil setmetatable(self, nil) end function World:_OnChangeArchetype(entity, archetypeOld, archetypeNew) if entity.isAlive then if self._entitiesUpdated[entity] == nil then self._dirty = true self._entitiesUpdated[entity] = archetypeOld end self._repository:Update(entity) -- update entity version using current Global System Version (GSV) entity.version = self.version end end return World