content
stringlengths
5
1.05M
--[[ 网络错误 ]] local NetError = { SHAKE_PACK_FLAG = 1, -- 握手包标识 PROTOCOL_VERSION = 2, -- 协议版本号 RSA_ENCRYPT = 3, -- rsa加密 RSA_DECRYPT = 4, -- rsa解密 DATA_SEND = 5, -- 数据发送 UNK_DATA_ENCRYPT = 6, -- 未知数据加密算法 UNK_DATA_DECRYPT = 7, -- 未知数据解密算法 NOT_DATA_ENCKEY = 8, -- 无数据加密密钥 NOT_DATA_DECKEY = 9, -- 无数据解密密钥 AES_ENCRYPT = 10, -- aes加密 AES_DECRYPT = 11, -- aes解密 SHAKE_ENCRYPT_FLAG = 12, -- 握手加密标识 SHAKE_ENCRYPT_METHOD = 13, -- 握手加密方式 HEART_TIMEOUT = 14, -- 心跳超时 SHAKE_TIMEOUT = 15, -- 握手超时 DATA_COMPRESS = 16, -- 数据压缩 DATA_UNCOMPRESS = 17, -- 数据解压 DATA_RECIVE = 18, -- 数据接收 PACK_TYPE = 19, -- 包类型 } return NetError
local m, s, o if luci.sys.call("pgrep haproxy-tcp >/dev/null") == 0 then m = Map("haproxy-tcp", translate("HAProxy-TCP"), "%s - %s" %{translate("HAProxy-TCP"), translate("RUNNING")}) else m = Map("haproxy-tcp", translate("HAProxy-TCP"), "%s - %s" %{translate("HAProxy-TCP"), translate("NOT RUNNING")}) end s = m:section(TypedSection, "general", translate("General Setting"), "<a target=\"_blank\" href=\"http://%s:%s\">%s</a>" %{ luci.sys.exec("uci get network.lan.ipaddr | tr -d '\r\n'"), luci.sys.exec("uci get haproxy-tcp.general.admin_stats | tr -d '\r\n'"), translate("Status Admin") }) s.anonymous = true o = s:option(Flag, "enable", translate("Enable")) o.rmempty = false o = s:option(Value, "startup_delay", translate("Startup Delay")) o:value(0, translate("Not enabled")) for _, v in ipairs({5, 10, 15, 25, 40}) do o:value(v, translate("%u seconds") %{v}) end o.datatype = "uinteger" o.default = 0 o.rmempty = false o = s:option(Value, "admin_stats", "%s%s" %{translate("Status Admin"), translate("Port")}) o.placeholder = "7777" o.default = "7777" o.datatype = "port" o.rmempty = false o = s:option(Value, "listen", translate("Listen Address:Port")) o.placeholder = "0.0.0.0:6666" o.default = "0.0.0.0:6666" o.rmempty = false o = s:option(Value, "timeout", translate("Timeout Connect (ms)")) o.placeholder = "666" o.default = "666" o.datatype = "range(33, 10000)" o.rmempty = false o = s:option(Value, "retries", translate("Retries")) o.placeholder = "1" o.default = "1" o.datatype = "range(1, 10)" o.rmempty = false o = s:option(DynamicList, "upstreams", translate("UpStream Server"), translate("e.g. [8.8.8.8:53 weight 100]")) o.placeholder = "8.8.8.8:53" o.rmempty = false return m
local cjson = require('cjson.safe') local jencode = cjson.encode local cache = require "apps.resty.cache" local system_conf = require "config.init" local redis_conf = system_conf.redisConf local request = require "apps.lib.request" local args,method = request:get() local ip = args['ip'] or nil if not ip then ngx.print('IP is not empty') return end local red = cache:new(redis_conf) local ok, err = red:connectdb() if not ok then return end local ip_blacklist, err = red.redis:sadd('ip_blacklist',ip); if err then ngx_log(ngx.ERR, "failed to query Redis:" .. err); end red:keepalivedb() ngx.print('{"error":0,"message":"Success"}')
-- Copyright (c) 2021 Trevor Redfern -- -- This software is released under the MIT License. -- https://opensource.org/licenses/MIT local components = require "moonpie.ui.components" local connect = require "moonpie.redux.connect" local player = require "game.rules.player" local LabelPair = require "game.ui.widgets.label_pair" local character_stats = components("character_stats", function(props) return { character_name = props.character_name, character_health = props.character_health, render = function(self) return { LabelPair { id = "characterName", label = "Name", value = self.character_name }, LabelPair { id = "characterHealth", label = "Health", value = self.character_health } } end } end) return connect(character_stats, function(state) local pc = player.selectors.getPlayer(state) if pc then return { character_name = pc.name, character_health = pc.health } end end)
--ZFUNC-splice-v1 local function splice( tab, idx, n, ... ) --> removed local values = { ... } local init_tab_size = #tab local removed = {} if n > 0 then for i = idx, ( idx + n - 1 ) do table.insert( removed, tab[ i ] ) tab[ i ] = nil end end local tail = {} for i = ( idx + n ), init_tab_size do table.insert( tail, tab[ i ] ) tab[ i ] = nil end local i = idx for _, v in ipairs( values ) do tab[ i ] = v i = i + 1 end i = idx + #values for _, v in ipairs( tail ) do tab[ i ] = v i = i + 1 end return removed end return splice
--[[ MIT License Copyright (c) 2019-2021 Marco Lizza 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 Class = require("tofu.core").Class local System = require("tofu.core").System local Input = require("tofu.events").Input local Bank = require("tofu.graphics").Bank local Canvas = require("tofu.graphics").Canvas local Display = require("tofu.graphics").Display local Palette = require("tofu.graphics").Palette local Font = require("tofu.graphics").Font local Main = Class.define() local IDS <const> = { "a", "b", "x", "y", "lb", "rb", "up", "down", "left", "right", "select", "start" } local INDICES <const> = { 0, 1, 2, 3, 4, 5, 12, 13, 14, 15, 24, 25 } function Main:__ctor() Display.palette(Palette.new("pico-8")) local canvas = Canvas.default() self.bank = Bank.new(Canvas.new("assets/sheet.png", 0), 12, 12) self.font = Font.default(0, 15) self.down = {} self.scale = {} Input.auto_repeat("x", 0.25) Input.auto_repeat("y", 0.5) Input.cursor_area(0, 0, canvas:size()) -- FIXME: painful! end function Main:process() for _, id in ipairs(IDS) do self.down[id] = Input.is_down(id) if Input.is_pressed(id) then self.scale[id] = 3.0 end end end function Main:update(delta_time) for _, id in ipairs(IDS) do if self.scale[id] and self.scale[id] > 1.0 then self.scale[id] = math.max(1.0, self.scale[id] - delta_time * 12.0) end end end local function draw_stick(canvas, cx, cy, radius, _, _, angle, magnitude, pressed) local dx, dy = math.floor(math.cos(angle) * magnitude * radius + 0.5), math.floor(math.sin(angle) * magnitude * radius + 0.5) -- local dx, dy = x * radius, y * radius if pressed then canvas:circle("fill", cx, cy, radius, 2) end canvas:circle("line", cx, cy, radius, 1) canvas:line(cx, cy, cx + dx, cy + dy, 3) end local function draw_trigger(canvas, cx, cy, radius, magnitude) if magnitude > 0.0 then canvas:circle("fill", cx, cy, magnitude * radius, 2) end canvas:circle("line", cx, cy, radius, 1) end function Main:render(_) local t = System.time() local canvas = Canvas.default() canvas:clear() local cw, ch = self.bank:size(Bank.NIL) local width, height = canvas:size() local x, y = (width - #IDS * cw) * 0.5, (height - ch) * 0.5 for index, id in ipairs(IDS) do local dy = math.sin(t * 2.5 + x * 0.5) * ch if self.down[id] then dy = 0 end local ox, oy = 0, 0 local s = 1.0 if self.scale[id] then s = self.scale[id] ox = (cw * s - cw) * 0.5 oy = (ch * s - ch) * 0.5 end self.bank:blit(canvas, x - ox, y - oy + dy, INDICES[index], s, s) x = x + cw end local cy = height * 0.5 local lx, ly, la, lm = Input.stick("left") local rx, ry, ra, rm = Input.stick("right") draw_stick(canvas, 24, cy - 12, 8, lx, ly, la, lm, Input.is_down("lt")) draw_stick(canvas, 232, cy - 12, 8, rx, ry, ra, rm, Input.is_down("rt")) local tl, tr = Input.triggers() draw_trigger(canvas, 24, cy + 12, 8, tl) draw_trigger(canvas, 232, cy + 12, 8, tr) local mx, my = Input.cursor() canvas:line(mx - 3, my, mx - 1, my, 2) canvas:line(mx + 1, my, mx + 3, my, 2) canvas:line(mx, my - 3, mx, my - 1, 2) canvas:line(mx, my + 1, mx, my + 3, 2) self.font:write(canvas, 0, 0, string.format("FPS: %d", System.fps())) self.font:write(canvas, width, height, string.format("X:%.2f Y:%.2f A:%.2f M:%.2f", lx, ly, la, lm), "right", "bottom") end return Main
data:extend({ { --nuclear furnace type = "item", name = "nuclear-furnace", icon = "__GnosticTest__/graphics/item/nuclear-furnace-icon.png", icon_size = 64, icon_mipmaps = 4, subgroup = "smelting-machine", place_result = "nuclear-furnace", stack_size = 50, order = "d", }, { --nuclear inserter type = "item", name = "nuclear-inserter", icon = "__GnosticTest__/graphics/item/nuclear-inserter-icon.png", icon_size = 64, icon_mipmaps = 4, subgroup = "inserter", place_result = "nuclear-inserter", stack_size = 50, order = "h", }, { --cinnabar ore type = "item", name = "cinnabar", icon = "__GnosticTest__/graphics/resources/cinnabar/cinnabar.png", icon_size = 64, icon_mipmaps = 4, pictures = { {size = 64, filename = "__GnosticTest__/graphics/resources/cinnabar/cinnabar.png", scale = 0.25, mipmap_count = 4}, {size = 64, filename = "__GnosticTest__/graphics/resources/cinnabar/cinnabar-1.png", scale = 0.25, mipmap_count = 4}, {size = 64, filename = "__GnosticTest__/graphics/resources/cinnabar/cinnabar-2.png", scale = 0.25, mipmap_count = 4}, {size = 64, filename = "__GnosticTest__/graphics/resources/cinnabar/cinnabar-3.png", scale = 0.25, mipmap_count = 4}, }, subgroup ="raw-resource", stack_size = 50, order = "h[cinnabar]", }, { --salt type = "item", name = "salt", icon = "__GnosticTest__/graphics/item/salt.png", icon_size = 64, icon_mipmaps = 4, subgroup = "raw-material", stack_size = 100, order = "h[salt]", }, { --molten salt fuel cell type = "item", name = "molten-salt-fuel-cell", icon = "__GnosticTest__/graphics/item/molten-salt-fuel-cell.png", icon_size = 64, icon_mipmaps = 4, subgroup = "intermediate-product", stack_size = 50, order = "r[uranium-processing]-h[molten-salt-fuel-cell]", fuel_category = "nuclear", --fuel type and value burnt_result = "depleted-molten-salt-fuel-cell", fuel_value = "20GJ", pictures = { layers = { { size = 64, filename = "__GnosticTest__/graphics/item/molten-salt-fuel-cell.png", scale = 0.25, mipmap_count = 4, }, { draw_as_light = true, flags = {"light"}, size = 64, filename = "__GnosticTest__/graphics/item/molten-salt-fuel-cell-light.png", scale = 0.25, mipmap_count = 4, }, }, }, }, { --depleted molten salt fuel cell type = "item", name = "depleted-molten-salt-fuel-cell", icon = "__GnosticTest__/graphics/item/depleted-molten-salt-fuel-cell.png", icon_size = 64, icon_mipmaps = 4, subgroup = "intermediate-product", stack_size = 50, order = "r[uranium-processing]-i[molten-salt-fuel-cell]", }, { --sodium type = "item", name = "sodium", icon = "__GnosticTest__/graphics/item/sodium.png", icon_size = 64, icon_mipmaps = 4, subgroup = "raw-material", stack_size = 100, order = "h[salt]-g[sodium]", }, { --biolab type = "item", name = "biolab", icon = "__GnosticTest__/graphics/item/biolab-icon.png", icon_size = 64, icon_mipmaps = 4, subgroup = "production-machine", place_result = "biolab", stack_size = 50, order = "l", }, { --offal type = "item", name = "offal", icon = "__GnosticTest__/graphics/item/offal.png", icon_size = 64, icon_mipmaps = 4, subgroup = "raw-material", stack_size = 100, order = "h[salt]-j[organic-slop]", }, { --fish bones type = "item", name = "fish-bones", icon = "__GnosticTest__/graphics/item/fish-bones.png", icon_size =64, icon_mipmaps = 4, subgroup = "raw-material", stack_size = 100, order = "h[salt]-i[fish-bones]" }, { --biological waste type = "item", name = "biological-waste", icon = "__GnosticTest__/graphics/item/biological-waste.png", icon_size = 64, icon_mipmaps = 4, subgroup = "raw-material", stack_size = 100, order = "f[biological-waste]", }, { --geothermal derrick type = "item", name = "geothermal-derrick", icon = "__GnosticTest__/graphics/item/geothermal-derrick-icon.png", icon_size = 64, icon_mipmaps = 4, subgroup = "extraction-machine", place_result = "geothermal-derrick", stack_size = 20, order = "b[fluids]-b[pumpjack]-c[geothermal-derrick]", }, } )
local package = { plugin='modal', platform='html5', appName='ModalDemo', appVersion='1.0', dstPath="/Users/daddyjam/Documents/Projects/Plugins-HTML5/corona-html5-modal-plugin/output_html5", projectPath="/Users/daddyjam/Documents/Projects/Plugins-HTML5/corona-html5-modal-plugin/corona_project/ModalDemo", includeStandardResources=true } return package
--if tonumber(GetCVar'modUnitFrame') == 0 then return end local _, class = UnitClass'player' if class ~= 'DRUID' then return end local TEXTURE = [[Interface\AddOns\UnitFramesImproved_TBC\Textures\sb.tga]] local BACKDROP = {bgFile = [[Interface\Tooltips\UI-Tooltip-Background]],} --local DruidManaLib = AceLibrary'DruidManaLib-1.0' local DruidManaLib = AceLibrary'LibDruidMana-1.0' local f = CreateFrame'Frame' PlayerFrame.ExtraManaBar = CreateFrame('StatusBar', 'ExtraManaBar', PlayerFrame) PlayerFrame.ExtraManaBar:SetWidth(100) PlayerFrame.ExtraManaBar:SetHeight(10) PlayerFrame.ExtraManaBar:SetPoint('TOP', PlayerFrame, 'BOTTOM', 50, 37) PlayerFrame.ExtraManaBar:SetStatusBarTexture(TEXTURE) PlayerFrame.ExtraManaBar:SetStatusBarColor(ManaBarColor[0].r, ManaBarColor[0].g, ManaBarColor[0].b) PlayerFrame.ExtraManaBar:SetBackdrop(BACKDROP) PlayerFrame.ExtraManaBar:SetBackdropColor(0, 0, 0) PlayerFrame.ExtraManaBar.Text = PlayerFrame.ExtraManaBar:CreateFontString('ExtraManaBarText', 'OVERLAY', 'TextStatusBarText') PlayerFrame.ExtraManaBar.Text:SetFont(STANDARD_TEXT_FONT, 12, 'OUTLINE') PlayerFrame.ExtraManaBar.Text:SetPoint('TOP', PlayerFrame.ExtraManaBar, 'BOTTOM', 0, 8) PlayerFrame.ExtraManaBar.Text:SetTextColor(.6, .65, 1) PlayerFrame.ExtraManaBar:SetScript('OnMouseUp', function(bu) PlayerFrame:Click(bu) end) modSkin(PlayerFrame.ExtraManaBar, 1) modSkinColor(PlayerFrame.ExtraManaBar, .7, .7, .7) local OnUpdate = function() --DruidManaLib:MaxManaScript() --local v, max = DruidManaLib:GetMana() DruidManaLib:GetMaximumMana() local v, max = DruidManaLib:GetMana() PlayerFrame.ExtraManaBar:SetMinMaxValues(0, max) PlayerFrame.ExtraManaBar:SetValue(v) --PlayerFrame.ExtraManaBar.Text:SetText(true_format(v)) PlayerFrame.ExtraManaBar.Text:SetText(v) end local OnEvent = function() if event == 'PLAYER_AURAS_CHANGED' then if not PlayerFrame.ExtraManaBar:IsShown() then return end end if f.loaded and UnitPowerType'player' ~= 0 then PlayerFrame.ExtraManaBar:Show() else PlayerFrame.ExtraManaBar:Hide() f.loaded = true end end f:RegisterEvent'UNIT_DISPLAYPOWER' f:RegisterEvent'PLAYER_AURAS_CHANGED' f:SetScript('OnUpdate', OnUpdate) f:SetScript('OnEvent', OnEvent) --
------------------------------------------------------------------------------- -- ElvUI Chat Tweaks By Crackpotx (US, Lightbringer) -- Based on functionality provided by Prat and/or Chatter ------------------------------------------------------------------------------- -- thanks to NinjaFish for the 5.51 fixes! :-) local Module = ElvUI_ChatTweaks:NewModule("Player Names", "AceHook-3.0", "AceEvent-3.0", "AceConsole-3.0") local L = LibStub("AceLocale-3.0"):GetLocale("ElvUI_ChatTweaks", false) local AceTab = LibStub("AceTab-3.0") Module.name = L["Player Names"] Module.namespace = string.gsub(Module.name, " ", "") local UnitName = _G["UnitName"] local UnitClass = _G["UnitClass"] local ChatEdit_GetActiveWindow = _G["ChatEdit_GetActiveWindow"] local GetChannelName = _G["GetChannelName"] local BNGetToonInfo = _G["BNGetToonInfo"] local GetQuestDifficultyColor = _G["GetQuestDifficultyColor"] local GetNumFriends = _G["GetNumFriends"] local GetFriendInfo = _G["GetFriendInfo"] local IsInGuild = _G["IsInGuild"] local GetNumGuildMembers = _G["GetNumGuildMembers"] local GetGuildRosterInfo = _G["GetGuildRosterInfo"] local IsInRaid = _G["IsInRaid"] local GetNumGroupMembers = _G["GetNumGroupMembers"] local GetRaidRosterInfo = _G["GetRaidRosterInfo"] local IsInGroup = _G["IsInGroup"] local GetNumSubgroupMembers = _G["GetNumSubgroupMembers"] local UnitExists = _G["UnitExists"] local UnitIsPlayer = _G["UnitIsPlayer"] local UnitIsFriend = _G["UnitIsFriend"] local GetNumWhoResults = _G["GetNumWhoResults"] local GetWhoInfo = _G["GetWhoInfo"] local BNGetNumFriends = _G["BNGetNumFriends"] local BNGetFriendInfo = _G["BNGetFriendInfo"] local GetAddOnMemoryUsage = _G["GetAddOnMemoryUsage"] local gsub = string.gsub local match = string.match local find = string.find local format = string.format local upper = string.upper local wipe = table.wipe local split = strsplit local localNames = {} local localClass = {} local cache = {} local storedName = {} local player = UnitName("player") local kByteString = "%d kb" local mByteString = "%.2f mb" local channels = { GUILD = {}, PARTY = {}, RAID = {} } local filterString = "CHAT_MSG_%s" local filterChannels = { "CHANNEL", "GUILD", "SAY", "YELL", "OFFICER", "EMOTE", "INSTANCE_CHAT", -- added in patch 5.1 "INSTANCE_CHAT_LEADER", -- added in patch 5.1 "PARTY", "PARTY_LEADER", "RAID", "RAID_LEADER", "RAID_WARNING", "WHISPER" } local db local options local defaults = { realm = { names = {}, levels = {}, }, global = { saveData = false, nameColoring = "CLASS", leftBracket = "[", rightBracket = "]", levelColor = "DIFF", levelLocation = "AFTER", bnetBrackets = true, separator = ":", useTabComplete = true, colorSelfInText = true, nickColor = {r = 0.627, g = 0.627, b = 0.627}, emphasizeSelfInText = true, noRealNames = false, classes = { DRUID = L["Druid"], MAGE = L["Mage"], PALADIN = L["Paladin"], PRIEST = L["Priest"], ROGUE = L["Rogue"], HUNTER = L["Hunter"], SHAMAN = L["Shaman"], WARLOCK = L["Warlock"], WARRIOR = L["Warrior"], DEATHKNIGHT = L["Death Knight"], MONK = L["Monk"], -- added in mop } } } local function formatMemory(memory) local mult = 10^1 if memory > 999 then local mem = ((memory/1024) * mult) / mult return format(mByteString, mem) else local mem = (memory * mult) / mult return format(kByteString, mem) end end local origUnitClass = UnitClass local function UnitClass(unit) local loc, sys = origUnitClass(unit) if sys and Module.db.global.classes[sys] then Module.db.global.classes[sys] = loc localClass = sys end return loc, sys end local tabComplete do function tabComplete(t, text, pos) local word = text:sub(pos) if #word == 0 then return end local CF = ChatEdit_GetActiveWindow() local channel = CF:GetAttribute("chatType") if channel == "CHANNEL" then channel = select(2, GetChannelName(CF:GetAttribute("channelTarget"))):lower() elseif channel == "OFFICER" then channel = "GUILD" elseif channel == "RAID_WARNING" or channel == "RAID_LEADER" then channel = "RAID" end if channels[channel] then for index, _ in pairs(channels[channel]) do if index:lower():match("^" .. word:lower()) then tinsert(t, index) end end end return t end end local getNameColor do local sq2 = sqrt(2) local pi = _G.math.pi local cos = _G.math.cos local fmod = _G.math.fmod local strbyte = _G.strbyte local t = {} -- http://www.tecgraf.puc-rio.br/~mgattass/color/HSVtoRGB.htm local function HSVtoRGB(h, s, v) if ( s == 0 ) then --achromatic=fail t.r = v t.g = v t.b = v if not t.r then t.r = 0 end if not t.g then t.g = 0 end if not t.b then t.b = 0 end return t.r,t.g,t.b end h = h/60 local i = floor(h) local i1 = v * (1 - s) local i2 = v * (1 - s * (h - i)) local i3 = v * (1 - s * (1 - (h - i))) if i == 0 then -- return v, i3, i1 t.r = v t.g = i3 t.b = i1 elseif i == 1 then -- return i2, v, i1 t.r = i2 t.g = v t.b = i1 elseif i == 2 then -- return i1, v, i3 t.r = i1 t.g = v t.b = i3 elseif i == 3 then -- return i3, i2, v t.r = i3 t.g = i2 t.b = v elseif i == 4 then -- return i3, i1, v t.r = i3 t.g = i1 t.b = v elseif i == 5 then -- return v, i1, i2 t.r = v t.g = i1 t.b = i2 else DEFAULT_CHAT_FRAME:AddMessage("Chatter HSVtoRGB failed") end if not t.r then t.r = 0 end if not t.g then t.g = 0 end if not t.b then t.b = 0 end return t.r,t.g,t.b end function getNameColor(name) local seed = 5381 --old seed: 5124 local h, s, v = 1, 1, 1 local r, g, b for i = 1, #name do seed = 33 * seed + strbyte(name, i) --used to use 29 here end -- h = fmod(seed, 255) / 255 h = fmod(seed, 360) --changed the HSVtoRGB to acompany this change if (h > 220) and (h < 270) then h = h + 60 end t.r, t.g, t.b = HSVtoRGB(h, s, v) return t end end function Module:GetColor(class, isLocal) if not class then return end if Module.debug then self:Print(("Class: %s"):format(class)) end if isLocal then local found = false for index, value in pairs(LOCALIZED_CLASS_NAMES_FEMALE) do if value == class then class = index; found = true; break; end end if not found then for index, value in pairs(LOCALIZED_CLASS_NAMES_MALE) do if value == class then class = index; break; end end end end local colors = CUSTOM_CLASS_COLORS and CUSTOM_CLASS_COLORS[class:upper()] or RAID_CLASS_COLORS[class:upper()] if not colors then colors = {r = 1, g = 1, b = 1} end return ("%02x%02x%02x"):format(colors.r * 255, colors.g * 255, colors.b * 255) end function Module:WipeCache() wipe(cache) end function Module:UpdateSaveData(v) if v then for k, v in pairs(localNames) do Module.db.realm.names[k] = v end end end local function fixLogin(head, id, misc, who, extra, colon) local left, right = "", "" if not Module.db.global.bnetBrackets then left = Module.db.global.leftBracket or "[" right = Module.db.global.rightBracket or "]" end return head .. id .. misc .. left .. who .. right .. extra .. (misc:match("BN_INLINE_TOAST_ALERT")) and "" or colon end local function changeBNetName(misc, id, moreMisc, fakeName, tag, colon) local _, charName, _, _, _, _, _, english = BNGetGameAccountInfo(id) local left, right = "", "" if chatName and charName ~= "" then if storedName then storedName[id] = charName end fakeName = Module.db.global.noRealNames and charName or fakeName else if Module.db.global.noRealNames and storedName and storedName[id] then fakeName = storedName[id] storedName[id] = nil end end if moreMisc:match("BN_INLINE_TOAST_ALERT") then misc = misc:sub(1, -2) end if not Module.db.global.bnetBrackets then left = Module.db.global.leftBracket right = Module.db.global.rightBracket end if english and english ~= "" then if not fakeName:match("|cff") then if Module.db.global.nameColoring == "CLASS" then fakeName = "|cff" .. Module:GetColor(english) .. fakeName .. "|r" elseif Module.db.global.nameColoring == "NAME" then fakeName = Module:ColorName(fakeName) end end end return misc .. id .. moreMisc .. left .. fakeName .. right .. tag .. ":" end local function changeName(header, name, extra, count, display, body) if name == player then if emphasizeSelfInText then body = body:gsub("(" .. player .. ")", "|cffffff00>|r%1|cffffff00<|r"):gsub("(" .. player:lower() .. ")", "|cffffff>|r%1|cffffff00<|r") end if colorSelfInText then body = body:gsub("(" .. player .. ")", "|cffff0000%1|r"):gsub("(" .. player:lower() .. ")", "|cffff0000%1|r") end end if not display:match("|cff") then display = Module:ColorName(name) end cache[name] = display local level local tab = Module.db.realm.names[name] or localNames[name] if tab then level = Module.db.global.includeLevel and tab.level or nil end if level and (level ~= MAX_PLAYER_LEVEL or not Module.db.global.excludeMaxLevel) then if Module.db.global.levelColor == "DIFF" then local color = GetQuestDifficultyColor(level) level = ("|cff%02x%02x%02x%s|r"):format(color.r * 255, color.g * 255, color.b * 255, level) elseif Module.db.global.levelColor == "CLASS" and display:match("|cff......") then level = gsub(display, "((|cff......).-|r)", function(string, color) return format("%s%s|r", color, level) end) end display = ("%s%s%s"):format(Module.db.global.levelLocation == "BEFORE" and level or display, Module.db.global.separator, Module.db.global.levelLocation == "AFTER" and level or display) end return ("|Hplayer:%s%s%s|h%s%s%s|h%s"):format(name, extra, count, Module.db.global.leftBracket, display, Module.db.global.rightBracket, body) end local function capitalize(str) return str:gsub("^%l", upper) end function Module:ColorName(name) local class local tab = Module.db.realm.names[name] or localNames[name] if tab then class = tab.class end if cache[name] then name = cache[name] else if Module.db.global.nameColoring ~= "NONE" then local color = Module.db.global.nickColor if Module.db.global.nameColoring == "CLASS" then color = CUSTOM_CLASS_COLORS and CUSTOM_CLASS_COLORS[class:upper()] or (class and RAID_CLASS_COLORS[class:upper()] or Module.db.global.nickColor) elseif coloring == "NAME" then color = getNameColor(name) end name = ("|cff%02x%02x%02x%s|r"):format(color.r * 255, color.g * 255, color.b * 255, name) end end return name end function Module:AddMessage(frame, text, ...) if text and type(text) == "string" then text = text:gsub("(|Hplayer:([^|:]+)([:%d+]*)([^|]*)|h%[([^%]]+)%]|h)(.-)$", changeName) --text = text:gsub("(|HBNplayer:%S-|k:)(%d-)(:%S-|h)%[(%S-)%](|?h?)(:?)", changeBNetName) text = text:gsub("(|HBNplayer%S-|k)(%d-)(:%S-BN_INLINE_TOAST_ALERT%S-|h)%[(%S-)%](|?h?)(:?)", fixLogin) end return self.hooks[frame].AddMessage(frame, text, ...) end function Module:FRIENDLIST_UPDATE(event) for i = 1, GetNumFriends() do local name, level, class = GetFriendInfo(i) if class then self:AddPlayer(name, localClass[class], level, Module.db.global.saveFriends) end end end function Module:GUILD_ROSTER_UPDATE(event) if not IsInGuild() then return end wipe(channels.GUILD) for i = 1, GetNumGuildMembers() do local name, _, _, level, _, _, _, _, online, _, class, _, _, isMobile = GetGuildRosterInfo(i) if online and not isMobile then channels.GUILD[name] = name end if not isMobile then self:AddPlayer(name, class, level, Module.db.global.saveGuild) end end end function Module:GROUP_ROSTER_UPDATE(event) wipe(channels.PARTY) wipe(channels.RAID) if IsInRaid() then for i = 1, GetNumGroupMembers() do local name, _, _, level, _, class = GetRaidRosterInfo(i) if name and level and class then channels.RAID[name] = true self:AddPlayer(name, class, level, Module.db.global.saveGroup) end end elseif IsInGroup() then for i = 1, GetNumSubgroupMembers() do local unit = ("party%d"):format(i) local name = UnitName(unit) local _, class = UnitClass(unit) local level = UnitLevel(unit) channels.PARTY[name] = true self:AddPlayer(name, class, level, Module.db.global.saveGroup) end end end function Module:PLAYER_TARGET_CHANGED(event) if not UnitExists("target") or not UnitIsPlayer("target") or not UnitIsFriend("player", "target") then return end local _, class = UnitClass("target") local name, level = UnitName("target"), UnitLevel("target") self:AddPlayer(name, class, level, Module.db.global.saveTarget) end function Module:UPDATE_MOUSEOVER_UNIT(event) if not UnitExists("mouseover") or not UnitIsPlayer("mouseover") or not UnitIsFriend("player", "mouseover") then return end local _, class = UnitClass("mouseover") local name, level = UnitName("mouseover"), UnitLevel("mouseover") self:AddPlayer(name, class, level, Module.db.global.saveTarget) end function Module:WHO_LIST_UPDATE(event) if GetNumWhoResults() <= 3 or Module.db.global.saveAllWho then for i =1, GetNumWhoResults() do local name, _, level, _, _, _, class = GetWhoInfo(i) if class then self:AddPlayer(name, class, level, Module.db.global.saveWho) end end end end function Module:CHAT_MSG_CHANNEL_JOIN(event, _, name, _, _, _, _, _, _, channel) channels[channel:lower()] = channels[channel:lower()] or {} channels[channel:lower()][name] = true end function Module:CHAT_MSG_CHANNEL_LEAVE(event, _, name, _, _, _, _, _, _, channel) if not channels[channel:lower()] then return end channels[channel:lower()][name] = nil end function Module:AddPlayer(name, class, level, save) if name and class and class ~= UNKNOWN then if save or Module.db.realm.names[name] then Module.db.realm.names[name] = Module.db.realm.names[name] or {} Module.db.realm.names[name].class = class if level and level ~= 0 then Module.db.realm.names[name].level = level end else localNames[name] = localNames[name] or {} localNames[name].class = class if level and level ~= 0 then localNames[name].level = level end end cache[name] = nil end end function Module:Decorate(frame) if not self:IsHooked(frame, "AddMessage") then self:RawHook(frame, "AddMessage", true) end end function Module:OnEnable() self:RegisterEvent("GROUP_ROSTER_UPDATE") self:RegisterEvent("WHO_LIST_UPDATE") self:RegisterEvent("PLAYER_TARGET_CHANGED") self:RegisterEvent("UPDATE_MOUSEOVER_UNIT") self:RegisterEvent("CHAT_MSG_SYSTEM", "WHO_LIST_UPDATE") self:RegisterEvent("FRIENDLIST_UPDATE") self:RegisterEvent("GUILD_ROSTER_UPDATE") self:RegisterEvent("CHAT_MSG_CHANNEL_JOIN") self:RegisterEvent("CHAT_MSG_CHANNEL_LEAVE") self:RegisterEvent("CHAT_MSG_CHANNEL", "CHAT_MSG_CHANNEL_JOIN") if IsInGuild() then GuildRoster() end self:GROUP_ROSTER_UPDATE() for i = 1, NUM_CHAT_WINDOWS do local frame = _G[format("ChatFrame%d", i)] if frame ~= COMBATLOG then self:RawHook(frame, "AddMessage", true) end end for index, frame in ipairs(self.TempChatFrames) do local cf = _G[frame] self:RawHook(cf, "AddMessage", true) end if Module.db.global.useTabComplete then AceTab:RegisterTabCompletion("ElvUI_ChatTweaks", nil, tabComplete) end if CUSTOM_CLASS_COLORS and CUSTOM_CLASS_COLORS.RegisterCallback then CUSTOM_CLASS_COLORS:RegisterCallback(wipeCache) end if Module.db.global.noRealNames then local _, n = BNGetNumFriends() for i = 1, n do local _, _, _, _, toon, id, _ = BNGetFriendInfo(i) storedName[id] = toon end end options.save.args.notice.name = format(L["\n\n|cffff0000NOTE:|r If this addon starts to use a substantial amount of memory, simply reset the name data and it will return to a normal level.\n\nAddon Usage: |cff00ff00%s|r"], formatMemory(GetAddOnMemoryUsage("ElvUI_ChatTweaks"))) end function Module:OnDisable() self:UnregisterEvent("GROUP_ROSTER_UPDATE") self:UnregisterEvent("WHO_LIST_UPDATE") self:UnregisterEvent("PLAYER_TARGET_CHANGED") self:UnregisterEvent("UPDATE_MOUSEOVER_UNIT") self:UnregisterEvent("CHAT_MSG_SYSTEM") self:UnregisterEvent("FRIENDLIST_UPDATE") self:UnregisterEvent("GUILD_ROSTER_UPDATE") self:UnregisterEvent("CHAT_MSG_CHANNEL_JOIN") self:UnregisterEvent("CHAT_MSG_CHANNEL_LEAVE") self:UnregisterEvent("CHAT_MSG_CHANNEL") if AceTab:IsTabCompletionRegistered("ElvUI_ChatTweaks") then AceTab:UnregisterTabCompletion("ElvUI_ChatTweaks") end if CUSTOM_CLASS_COLORS and CUSTOM_CLASS_COLORS.UnregisterCallback then CUSTOM_CLASS_COLORS:UnregisterCallback(wipeCache) end end function Module:OnInitialize() self.db = ElvUI_ChatTweaks.db:RegisterNamespace(Module.namespace, defaults) for index, value in pairs(self.db.realm.names) do if type(value) == "string" then self.db.realm.names[index] = {class = v} end end --db = self.Module.db.global.profile --Module.db.realm = self.Module.db.realm --Module.db.global = self.Module.db.global for index, value in pairs(self.db.global.classes) do localClass[value] = index end self.debug = ElvUI_ChatTweaks.db.global.debugging end function Module:Info() return L["Provides options to color player names, add player levels, and add tab completion of player names."] end function Module:GetOptions() if not options then options = { save = { type = "group", name = L["Save Data"], desc = L["Save data between sessions. Will increase memory usage"], args = { guild = { type = "toggle", name = L["Guild"], desc = L["Save class data from guild between sessions."], get = function() return Module.db.global.saveGuild end, set = function(_, v) Module.db.global.saveGuild = v Module:UpdateSaveData(v) end }, group = { type = "toggle", name = L["Group"], desc = L["Save class data from groups between sessions."], get = function() return Module.db.global.saveGroup end, set = function(_, v) Module.db.global.saveGroup = v Module:UpdateSaveData(v) end }, friend = { type = "toggle", name = L["Friends"], desc = L["Save class data from friends between sessions."], get = function() return Module.db.global.saveFriends end, set = function(_, v) Module.db.global.saveFriends = v Module:UpdateSaveData(v) end }, target = { type = "toggle", name = L["Target/Mouseover"], desc = L["Save class data from target/mouseover between sessions."], get = function() return Module.db.global.saveTarget end, set = function(_, v) Module.db.global.saveTarget = v Module:UpdateSaveData(v) end }, who = { type = "toggle", name = L["Who"], desc = L["Save class data from /who queries between sessions."], order = 104, get = function() return Module.db.global.saveWho end, set = function(_, v) Module.db.global.saveWho = v Module:UpdateSaveData(v) end }, saveAllWho = { type = "toggle", name = L["Save all /who data"], desc = L["Will save all data for large /who queries"], disabled = function() return not Module.db.global.saveWho end, order = 105, get = function() return Module.db.global.saveAllWho end, set = function(_, v) Module.db.global.saveAllWho = v end }, resetDB = { type = "execute", name = L["Reset Data"], desc = L["Destroys all your saved class/level data"], func = function() wipe(Module.db.realm.names) end, order = 106, confirm = function() return L["Are you sure you want to delete all your saved class/level data?"] end }, notice = { type = "description", name = L["\n\n|cffff0000NOTE:|r If this addon starts to use a substantial amount of memory, simply reset the name data and it will return to a normal level."], order = 107, }, } }, level = { type = "group", name = L["Player Level"], desc = L["Player level display options."], args = { includeLevel = { type = "toggle", name = L["Include level"], desc = L["Include the player's level"], order = 1, get = function() return Module.db.global.includeLevel end, set = function(_, val) Module.db.global.includeLevel = val Module:WipeCache() end }, separator = { type = "input", order = 2, name = L["Separator"], desc = L["Character to use between the name and level"], disabled = function() return not Module.db.global.includeLevel end, get = function() return Module.db.global.separator end, set = function(i, v) Module.db.global.separator = v end }, colorLevelByDifficulty = { type = "select", name = L["Color Level"], desc = L["Select how you want the player's level colored."], order = 3, values = { ["DIFF"] = L["Level Difference"], ["CLASS"] = L["Player Class"], ["NONE"] = L["None"], }, disabled = function() return not Module.db.global.includeLevel end, get = function() return Module.db.global.levelColor end, set = function(_, v) Module.db.global.levelColor = v Module:WipeCache() end, }, excludeMaxLevel = { type = "toggle", name = L["Exclude max levels"], desc = L["Exclude level display for max level characters"], order = 4, disabled = function() return not Module.db.global.includeLevel end, get = function() return Module.db.global.excludeMaxLevel end, set = function(_, val) Module.db.global.excludeMaxLevel = val Module:WipeCache() end, }, levelLocation = { type = "select", name = L["Level Location"], desc = L["Place the level before or after the player's name."], values = { ["BEFORE"] = L["Before"], ["AFTER"] = L["After"], }, disabled = function() return not Module.db.global.includeLevel end, get = function() return Module.db.global.levelLocation end, set = function(_, value) Module.db.global.levelLocation = value end, } } }, leftbracket = { type = "input", order = 14, name = L["Left Bracket"], desc = L["Character to use for the left bracket"], get = function() return Module.db.global.leftBracket end, set = function(i, v) Module.db.global.leftBracket = v leftBracket = v end }, rightbracket = { type = "input", order = 14, name = L["Right Bracket"], desc = L["Character to use for the right bracket"], get = function() return Module.db.global.rightBracket end, set = function(i, v) Module.db.global.rightBracket = v rightBracket = v end }, bnetHeader = { type = "header", name = L["Battle.Net Options"], order = 20 }, bnetBrackets = { type = "toggle", order = 21, name = L["RealID Brackets"], desc = L["Strip RealID brackets"], get = function() return Module.db.global.bnetBrackets end, set = function(_, v) Module.db.global.bnetBrackets = v end, }, bnetRealNames = { type = "toggle", order = 22, name = L["No RealNames"], desc = L["Show toon names instead of real names"], get = function() return Module.db.global.noRealNames end, set = function(_, v) Module.db.global.noRealNames = v end, }, useTabComplete = { type = "toggle", order = 19, name = L["Use Tab Complete"], desc = L["Use tab key to automatically complete character names."], get = function() return Module.db.global.useTabComplete end, set = function(_, v) Module.db.global.useTabComplete = v if v and not AceTab:IsTabCompletionRegistered("ElvUI_ChatTweaks") then AceTab:RegisterTabCompletion("ElvUI_ChatTweaks", nil, tabComplete) elseif not v and AceTab:IsTabCompletionRegistered("ElvUI_ChatTweaks") then AceTab:UnregisterTabCompletion("ElvUI_ChatTweaks") end end }, colorSelfInText = { type = "toggle", order = 17, name = L["Color self in messages"], desc = L["Color own charname in messages."], get = function() return Module.db.global.colorSelfInText end, set = function(i, v) Module.db.global.colorSelfInText = v colorSelfInText = v end }, emphasizeSelfInText = { type = "toggle", order = 18, name = L["Emphasize Self"], desc = L["Add surrounding brackets to own charname in messages."], get = function() return Module.db.global.emphasizeSelfInText end, set = function(i, v) Module.db.global.emphasizeSelfInText = v emphasizeSelfInText = v end }, colorBy = { type = "select", order = 13, name = L["Color Player Names By..."], desc = L["Select a method for coloring player names"], values = { CLASS = L["Class"], NAME = L["Name"], NONE = L["None"], }, get = function() return Module.db.global.nameColoring end, set = function(_, val) Module.db.global.nameColoring = val Module:WipeCache() end }, nickColor = { type = "color", order = 16, name = L["Default Name Color"], desc = L["The default color to use to color names."], get = function() return Module.db.global.nickColor.r, Module.db.global.nickColor.g, Module.db.global.nickColor.b end, set = function(_, r, g, b) Module.db.global.nickColor.r = r Module.db.global.nickColor.g = g Module.db.global.nickColor.b = b end }, } end return options end
--------------------------------------------- -- Provoke --------------------------------------------- require("scripts/globals/automatonweaponskills") require("scripts/globals/settings") require("scripts/globals/status") require("scripts/globals/msg") --------------------------------------------- function onMobSkillCheck(target, automaton, skill) return 0 end function onPetAbility(target, automaton, skill, master, action) automaton:addRecast(tpz.recast.ABILITY, skill:getID(), 30) target:addEnmity(automaton, 1, 1800) skill:setMsg(tpz.msg.basic.USES) return 0 end
local _local_1_ = require("paperplanes.util.providers") local set_field = _local_1_["set-field"] local function make(content_arg, meta) local args do local _2_ = {} table.insert(_2_, "--data-binary") table.insert(_2_, content_arg) table.insert(_2_, "https://paste.rs") args = _2_ end local function after(response, status) local _3_ = status if (_3_ == 201) then return string.match(response, "^(https?://.*)\n") elseif true then local _ = _3_ return nil, response else return nil end end return args, after end local function post_string(string, meta) return make(string, meta) end local function post_file(file, meta) return make(("@" .. file), meta) end return {["post-string"] = post_string, ["post-file"] = post_file}
local ffi = require 'ffi' local uni = require 'ffi.unicode' ffi.cdef[[ int GetModuleHandleW(const wchar_t* libname); ]] return function(name) local wpath = uni.u2w(name) return ffi.C.GetModuleHandleW(wpath) end
return { short_music_name = "song03", bpm = 720, offset_time = 0, music_name = "bgm-song03", left_track = { { begin_time = "1.583333", key_flag = "K_LEFT", end_time = "1.583333" }, { begin_time = "2.25", key_flag = "K_LEFT", end_time = "2.25" }, { begin_time = "2.916667", key_flag = "K_LEFT", end_time = "2.916667" }, { begin_time = "3.582746", key_flag = "K_LEFT", end_time = "3.582746" }, { begin_time = "4.58485", key_flag = "K_LEFT", end_time = "4.58485" }, { begin_time = "5.25", key_flag = "K_LEFT", end_time = "5.25" }, { begin_time = "6.916667", key_flag = "K_LEFT", end_time = "6.916667" }, { begin_time = "7.583797", key_flag = "K_LEFT", end_time = "7.583797" }, { begin_time = "8.25", key_flag = "K_LEFT", end_time = "8.25" }, { begin_time = "8.916667", key_flag = "K_LEFT", end_time = "8.916667" }, { begin_time = "9.915988", key_flag = "K_LEFT", end_time = "9.915988" }, { begin_time = "10.58333", key_flag = "K_LEFT", end_time = "10.58333" }, { begin_time = "11.25", key_flag = "K_LEFT", end_time = "11.25" }, { begin_time = "11.91667", key_flag = "K_LEFT", end_time = "11.91667" }, { begin_time = "12.58455", key_flag = "K_LEFT", end_time = "12.58455" }, { begin_time = "13.25", key_flag = "K_LEFT", end_time = "13.25" }, { begin_time = "14.91667", key_flag = "K_LEFT", end_time = "14.91667" }, { begin_time = "15.58309", key_flag = "K_LEFT", end_time = "15.58309" }, { begin_time = "16.25188", key_flag = "K_LEFT", end_time = "16.25188" }, { begin_time = "16.91802", key_flag = "K_LEFT", end_time = "16.91802" }, { begin_time = "17.91667", key_flag = "K_LEFT", end_time = "17.91667" }, { begin_time = "18.58333", key_flag = "K_LEFT", end_time = "18.58333" }, { begin_time = "20.25", key_flag = "K_BOTH", end_time = "20.25" }, { begin_time = "21.58333", key_flag = "K_BOTH", end_time = "21.58333" }, { begin_time = "22.91667", key_flag = "K_LEFT", end_time = "22.91667" }, { begin_time = "23.58333", key_flag = "K_LEFT", end_time = "23.58333" }, { begin_time = "24.25", key_flag = "K_LEFT", end_time = "24.25" }, { begin_time = "26.25602", key_flag = "K_LEFT", end_time = "26.25602" }, { begin_time = "26.91667", key_flag = "K_LEFT", end_time = "27.58333" }, { begin_time = "30.25", key_flag = "K_LEFT", end_time = "30.25" }, { begin_time = "30.91667", key_flag = "K_LEFT", end_time = "30.91667" }, { begin_time = "33.58333", key_flag = "K_LEFT", end_time = "33.58333" }, { begin_time = "34.91667", key_flag = "K_LEFT", end_time = "34.91667" }, { begin_time = "38.58333", key_flag = "K_LEFT", end_time = "38.58333" }, { begin_time = "38.91667", key_flag = "K_LEFT", end_time = "38.91667" }, { begin_time = "40.91667", key_flag = "K_LEFT", end_time = "40.91667" }, { begin_time = "41.25", key_flag = "K_LEFT", end_time = "42.58333" }, { begin_time = "43.25", key_flag = "K_LEFT", end_time = "43.25" }, { begin_time = "44.25", key_flag = "K_LEFT", end_time = "44.25" }, { begin_time = "44.91667", key_flag = "K_LEFT", end_time = "44.91667" }, { begin_time = "45.58333", key_flag = "K_LEFT", end_time = "45.58333" }, { begin_time = "49.58333", key_flag = "K_LEFT", end_time = "49.58333" }, { begin_time = "50.25", key_flag = "K_LEFT", end_time = "50.25" }, { begin_time = "50.91667", key_flag = "K_LEFT", end_time = "50.91667" }, { begin_time = "51.57849", key_flag = "K_LEFT", end_time = "51.57849" }, { begin_time = "52.25201", key_flag = "K_LEFT", end_time = "52.25201" }, { begin_time = "52.91667", key_flag = "K_LEFT", end_time = "52.91667" }, { begin_time = "53.25", key_flag = "K_LEFT", end_time = "53.25" }, { begin_time = "53.58333", key_flag = "K_LEFT", end_time = "54.91667" }, { begin_time = "56.91667", key_flag = "K_LEFT", end_time = "56.91667" }, { begin_time = "57.25", key_flag = "K_LEFT", end_time = "57.25" }, { begin_time = "59.91667", key_flag = "K_LEFT", end_time = "59.91667" }, { begin_time = "60.25", key_flag = "K_LEFT", end_time = "60.25" }, { begin_time = "60.918", key_flag = "K_LEFT", end_time = "60.918" }, { begin_time = "61.25", key_flag = "K_LEFT", end_time = "61.91667" }, { begin_time = "63.91666", key_flag = "K_LEFT", end_time = "63.91666" }, { begin_time = "64.25", key_flag = "K_LEFT", end_time = "64.25" }, { begin_time = "64.58334", key_flag = "K_LEFT", end_time = "64.58334" }, { begin_time = "65.58334", key_flag = "K_LEFT", end_time = "65.58334" }, { begin_time = "68.25", key_flag = "K_LEFT", end_time = "68.25" }, { begin_time = "68.91666", key_flag = "K_LEFT", end_time = "68.91666" }, { begin_time = "69.58334", key_flag = "K_LEFT", end_time = "69.58334" }, { begin_time = "69.91666", key_flag = "K_LEFT", end_time = "69.91666" }, { begin_time = "70.25", key_flag = "K_LEFT", end_time = "70.25" }, { begin_time = "71.25636", key_flag = "K_LEFT", end_time = "71.25636" }, { begin_time = "73.58334", key_flag = "K_LEFT", end_time = "73.58334" }, { begin_time = "74.25", key_flag = "K_LEFT", end_time = "74.25" }, { begin_time = "74.91666", key_flag = "K_LEFT", end_time = "74.91666" }, { begin_time = "75.25", key_flag = "K_LEFT", end_time = "75.25" }, { begin_time = "75.58334", key_flag = "K_LEFT", end_time = "75.58334" }, { begin_time = "76.58334", key_flag = "K_LEFT", end_time = "76.58334" }, { begin_time = "78.91666", key_flag = "K_LEFT", end_time = "78.91666" }, { begin_time = "79.58334", key_flag = "K_LEFT", end_time = "79.58334" }, { begin_time = "80.25", key_flag = "K_LEFT", end_time = "80.25" }, { begin_time = "80.92558", key_flag = "K_LEFT", end_time = "80.92558" }, { begin_time = "83.91666", key_flag = "K_LEFT", end_time = "83.91666" }, { begin_time = "84.25", key_flag = "K_LEFT", end_time = "85.58334" }, { begin_time = "89.66666", key_flag = "K_LEFT", end_time = "89.66666" }, { begin_time = "91.58334", key_flag = "K_LEFT", end_time = "91.58334" }, { begin_time = "91.91666", key_flag = "K_LEFT", end_time = "95" }, { begin_time = "97.58334", key_flag = "K_LEFT", end_time = "97.58334" }, { begin_time = "98.25", key_flag = "K_LEFT", end_time = "98.25" }, { begin_time = "98.91666", key_flag = "K_LEFT", end_time = "98.91666" }, { begin_time = "99.58334", key_flag = "K_LEFT", end_time = "99.58334" }, { begin_time = "101.915", key_flag = "K_LEFT", end_time = "101.915" }, { begin_time = "102.248", key_flag = "K_LEFT", end_time = "102.248" }, { begin_time = "103.5833", key_flag = "K_LEFT", end_time = "103.5833" }, { begin_time = "104.5833", key_flag = "K_LEFT", end_time = "104.5833" }, { begin_time = "104.9167", key_flag = "K_LEFT", end_time = "104.9167" }, { begin_time = "105.5833", key_flag = "K_LEFT", end_time = "105.5833" }, { begin_time = "106.25", key_flag = "K_LEFT", end_time = "106.25" }, { begin_time = "106.5833", key_flag = "K_LEFT", end_time = "107.5833" }, { begin_time = "108.9167", key_flag = "K_LEFT", end_time = "108.9167" }, { begin_time = "110.2504", key_flag = "K_LEFT", end_time = "110.2504" }, { begin_time = "110.5918", key_flag = "K_LEFT", end_time = "110.5918" }, { begin_time = "113.5833", key_flag = "K_LEFT", end_time = "113.5833" }, { begin_time = "114.25", key_flag = "K_LEFT", end_time = "114.25" }, { begin_time = "114.9167", key_flag = "K_LEFT", end_time = "114.9167" }, { begin_time = "115.5833", key_flag = "K_LEFT", end_time = "115.5833" }, { begin_time = "118.2571", key_flag = "K_LEFT", end_time = "118.2571" }, { begin_time = "118.9167", key_flag = "K_LEFT", end_time = "122.5833" }, { begin_time = "124.262", key_flag = "K_LEFT", end_time = "124.262" }, { begin_time = "124.9167", key_flag = "K_LEFT", end_time = "124.9167" }, { begin_time = "126.25", key_flag = "K_LEFT", end_time = "126.25" }, { begin_time = "126.5833", key_flag = "K_LEFT", end_time = "126.5833" }, { begin_time = "127.25", key_flag = "K_LEFT", end_time = "127.25" }, { begin_time = "127.9167", key_flag = "K_LEFT", end_time = "127.9167" }, { begin_time = "128.9167", key_flag = "K_LEFT", end_time = "128.9167" }, { begin_time = "129.5833", key_flag = "K_LEFT", end_time = "129.5833" }, { begin_time = "130.25", key_flag = "K_LEFT", end_time = "130.25" }, { begin_time = "130.9167", key_flag = "K_LEFT", end_time = "130.9167" }, { begin_time = "131.5833", key_flag = "K_LEFT", end_time = "131.5833" }, { begin_time = "132.5833", key_flag = "K_LEFT", end_time = "132.5833" }, { begin_time = "133.25", key_flag = "K_LEFT", end_time = "133.25" }, { begin_time = "134.9167", key_flag = "K_LEFT", end_time = "134.9167" }, { begin_time = "135.5833", key_flag = "K_LEFT", end_time = "135.5833" }, { begin_time = "136.25", key_flag = "K_LEFT", end_time = "136.25" }, { begin_time = "136.9167", key_flag = "K_LEFT", end_time = "136.9167" }, { begin_time = "137.5833", key_flag = "K_BOTH", end_time = "137.5833" }, { begin_time = "138.9167", key_flag = "K_BOTH", end_time = "138.9167" }, { begin_time = "141.25", key_flag = "K_LEFT", end_time = "145.25" } }, right_track = { { begin_time = "1.915992", key_flag = "K_RIGHT", end_time = "1.915992" }, { begin_time = "2.583333", key_flag = "K_RIGHT", end_time = "2.583333" }, { begin_time = "4.25", key_flag = "K_RIGHT", end_time = "4.25" }, { begin_time = "4.916251", key_flag = "K_RIGHT", end_time = "4.916251" }, { begin_time = "5.583333", key_flag = "K_RIGHT", end_time = "5.583333" }, { begin_time = "6.25", key_flag = "K_RIGHT", end_time = "6.25" }, { begin_time = "7.25", key_flag = "K_RIGHT", end_time = "7.25" }, { begin_time = "7.916667", key_flag = "K_RIGHT", end_time = "7.916667" }, { begin_time = "9.583333", key_flag = "K_RIGHT", end_time = "9.583333" }, { begin_time = "10.25", key_flag = "K_RIGHT", end_time = "10.25" }, { begin_time = "11.58333", key_flag = "K_RIGHT", end_time = "11.58333" }, { begin_time = "12.25", key_flag = "K_RIGHT", end_time = "12.25" }, { begin_time = "12.91667", key_flag = "K_RIGHT", end_time = "12.91667" }, { begin_time = "13.5852", key_flag = "K_RIGHT", end_time = "13.5852" }, { begin_time = "14.24984", key_flag = "K_RIGHT", end_time = "14.24984" }, { begin_time = "15.25", key_flag = "K_RIGHT", end_time = "15.25" }, { begin_time = "15.91667", key_flag = "K_RIGHT", end_time = "15.91667" }, { begin_time = "17.58334", key_flag = "K_RIGHT", end_time = "17.58334" }, { begin_time = "18.2483", key_flag = "K_RIGHT", end_time = "18.2483" }, { begin_time = "18.91768", key_flag = "K_RIGHT", end_time = "18.91768" }, { begin_time = "19.58273", key_flag = "K_RIGHT", end_time = "19.58273" }, { begin_time = "20.25", key_flag = "K_BOTH", end_time = "20.25" }, { begin_time = "21.58333", key_flag = "K_BOTH", end_time = "21.58333" }, { begin_time = "24.91667", key_flag = "K_RIGHT", end_time = "24.91667" }, { begin_time = "25.58333", key_flag = "K_RIGHT", end_time = "25.58333" }, { begin_time = "28.25", key_flag = "K_RIGHT", end_time = "28.25" }, { begin_time = "28.91667", key_flag = "K_RIGHT", end_time = "28.91667" }, { begin_time = "29.58333", key_flag = "K_RIGHT", end_time = "29.58333" }, { begin_time = "31.5", key_flag = "K_RIGHT", end_time = "31.5" }, { begin_time = "32.16667", key_flag = "K_RIGHT", end_time = "32.91667" }, { begin_time = "34.25", key_flag = "K_RIGHT", end_time = "34.25" }, { begin_time = "35.59435", key_flag = "K_RIGHT", end_time = "35.59435" }, { begin_time = "36.25", key_flag = "K_RIGHT", end_time = "36.91667" }, { begin_time = "37.58334", key_flag = "K_RIGHT", end_time = "37.58334" }, { begin_time = "39.58791", key_flag = "K_RIGHT", end_time = "39.58791" }, { begin_time = "39.91667", key_flag = "K_RIGHT", end_time = "40.58333" }, { begin_time = "42.91697", key_flag = "K_RIGHT", end_time = "42.91697" }, { begin_time = "46.92215", key_flag = "K_RIGHT", end_time = "46.92215" }, { begin_time = "47.58364", key_flag = "K_RIGHT", end_time = "47.58364" }, { begin_time = "47.91667", key_flag = "K_RIGHT", end_time = "48.91667" }, { begin_time = "51.25671", key_flag = "K_RIGHT", end_time = "51.25671" }, { begin_time = "55.57795", key_flag = "K_RIGHT", end_time = "55.57795" }, { begin_time = "55.91667", key_flag = "K_RIGHT", end_time = "56.58333" }, { begin_time = "57.921", key_flag = "K_RIGHT", end_time = "57.921" }, { begin_time = "58.25", key_flag = "K_RIGHT", end_time = "59.58333" }, { begin_time = "62.2536", key_flag = "K_RIGHT", end_time = "62.2536" }, { begin_time = "62.58333", key_flag = "K_RIGHT", end_time = "63.25" }, { begin_time = "66.25001", key_flag = "K_RIGHT", end_time = "66.25001" }, { begin_time = "66.9115", key_flag = "K_RIGHT", end_time = "66.9115" }, { begin_time = "67.58009", key_flag = "K_RIGHT", end_time = "67.58009" }, { begin_time = "68.58334", key_flag = "K_RIGHT", end_time = "68.58334" }, { begin_time = "70.91666", key_flag = "K_RIGHT", end_time = "70.91666" }, { begin_time = "71.58353", key_flag = "K_RIGHT", end_time = "71.58353" }, { begin_time = "72.25018", key_flag = "K_RIGHT", end_time = "72.25018" }, { begin_time = "72.58447", key_flag = "K_RIGHT", end_time = "72.58447" }, { begin_time = "72.91879", key_flag = "K_RIGHT", end_time = "72.91879" }, { begin_time = "73.91751", key_flag = "K_RIGHT", end_time = "73.91751" }, { begin_time = "76.25", key_flag = "K_RIGHT", end_time = "76.25" }, { begin_time = "76.91666", key_flag = "K_RIGHT", end_time = "76.91666" }, { begin_time = "77.58334", key_flag = "K_RIGHT", end_time = "77.58334" }, { begin_time = "77.91666", key_flag = "K_RIGHT", end_time = "77.91666" }, { begin_time = "78.25", key_flag = "K_RIGHT", end_time = "78.25" }, { begin_time = "81.58334", key_flag = "K_RIGHT", end_time = "81.58334" }, { begin_time = "82.25", key_flag = "K_RIGHT", end_time = "82.25" }, { begin_time = "82.91666", key_flag = "K_RIGHT", end_time = "82.91666" }, { begin_time = "83.5844", key_flag = "K_RIGHT", end_time = "83.5844" }, { begin_time = "85.92366", key_flag = "K_RIGHT", end_time = "85.92366" }, { begin_time = "86.25", key_flag = "K_RIGHT", end_time = "86.25" }, { begin_time = "86.58334", key_flag = "K_RIGHT", end_time = "86.58334" }, { begin_time = "87.25", key_flag = "K_RIGHT", end_time = "89" }, { begin_time = "90.83334", key_flag = "K_RIGHT", end_time = "90.83334" }, { begin_time = "97.92889", key_flag = "K_RIGHT", end_time = "97.92889" }, { begin_time = "99.25186", key_flag = "K_RIGHT", end_time = "99.25186" }, { begin_time = "100.25", key_flag = "K_RIGHT", end_time = "100.25" }, { begin_time = "100.9167", key_flag = "K_RIGHT", end_time = "100.9167" }, { begin_time = "101.5833", key_flag = "K_RIGHT", end_time = "101.5833" }, { begin_time = "102.9167", key_flag = "K_RIGHT", end_time = "102.9167" }, { begin_time = "104.2537", key_flag = "K_RIGHT", end_time = "104.2537" }, { begin_time = "108.2527", key_flag = "K_RIGHT", end_time = "108.2527" }, { begin_time = "109.5899", key_flag = "K_RIGHT", end_time = "109.5899" }, { begin_time = "110.9167", key_flag = "K_RIGHT", end_time = "110.9167" }, { begin_time = "111.5833", key_flag = "K_RIGHT", end_time = "111.5833" }, { begin_time = "112.25", key_flag = "K_RIGHT", end_time = "112.9167" }, { begin_time = "116.25", key_flag = "K_RIGHT", end_time = "116.25" }, { begin_time = "116.9167", key_flag = "K_RIGHT", end_time = "116.9167" }, { begin_time = "117.5833", key_flag = "K_RIGHT", end_time = "117.5833" }, { begin_time = "123.5863", key_flag = "K_RIGHT", end_time = "123.5863" }, { begin_time = "123.9168", key_flag = "K_RIGHT", end_time = "123.9168" }, { begin_time = "124.5833", key_flag = "K_RIGHT", end_time = "124.5833" }, { begin_time = "125.25", key_flag = "K_RIGHT", end_time = "125.25" }, { begin_time = "125.9167", key_flag = "K_RIGHT", end_time = "125.9167" }, { begin_time = "126.9167", key_flag = "K_RIGHT", end_time = "126.9167" }, { begin_time = "127.5833", key_flag = "K_RIGHT", end_time = "127.5833" }, { begin_time = "128.5833", key_flag = "K_RIGHT", end_time = "128.5833" }, { begin_time = "129.25", key_flag = "K_RIGHT", end_time = "129.25" }, { begin_time = "129.9167", key_flag = "K_RIGHT", end_time = "129.9167" }, { begin_time = "130.5844", key_flag = "K_RIGHT", end_time = "130.5844" }, { begin_time = "132.25", key_flag = "K_RIGHT", end_time = "132.25" }, { begin_time = "132.9167", key_flag = "K_RIGHT", end_time = "132.9167" }, { begin_time = "133.5833", key_flag = "K_RIGHT", end_time = "133.5833" }, { begin_time = "134.25", key_flag = "K_RIGHT", end_time = "134.25" }, { begin_time = "135.25", key_flag = "K_RIGHT", end_time = "135.25" }, { begin_time = "135.9167", key_flag = "K_RIGHT", end_time = "135.9167" }, { begin_time = "137.5833", key_flag = "K_BOTH", end_time = "137.5833" }, { begin_time = "138.9167", key_flag = "K_BOTH", end_time = "138.9167" } } }
return Component.create("Health", {"remaining"}, {remaining = MAX_HEALTH})
/* * @package : rlib * @module : calc * @author : Richard [http://steamcommunity.com/profiles/76561198135875727] * @copyright : (C) 2018 - 2020 * @since : 1.0.0 * @website : https://rlib.io * @docs : https://docs.rlib.io * * MIT License * * 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. */ /* * standard tables and localization */ rlib = rlib or { } local base = rlib local mf = base.manifest local prefix = mf.prefix local script = mf.name local settings = base.settings /* * lib includes */ local access = base.a local helper = base.h /* * localizations */ local math = math local module = module local smt = setmetatable local sf = string.format /* * simplifiy funcs */ local function con( ... ) base:console( ... ) end local function log( ... ) base:log( ... ) end /* * prefix :: create id */ local function pref( id, suffix ) local affix = istable( suffix ) and suffix.id or isstring( suffix ) and suffix or prefix affix = affix:sub( -1 ) ~= '.' and sf( '%s.', affix ) or affix id = isstring( id ) and id or 'noname' id = id:gsub( '[%c%s]', '.' ) return sf( '%s%s', affix, id ) end /* * prefix :: handle */ local function pid( str, suffix ) local state = ( isstring( suffix ) and suffix ) or ( base and mf.prefix ) or false return pref( str, state ) end /* * define module */ module( 'calc', package.seeall ) /* * local declarations */ local pkg = calc local pkg_name = _NAME or 'calc' /* * pkg declarations */ local manifest = { author = 'richard', desc = 'mathmatical calculations related to time, memory, data counts, etc', build = 040220, version = { 2, 1, 0 }, } /* * required tables */ settings = settings or { } sys = sys or { } pos = pos or { } fs = fs or { } /* * return number of human players on server */ function players( ) return #player.GetHumans( ) or 0 end /* * return number of bots on server */ function bots( ) return #player.GetBots( ) or 0 end /* * count from a min to max number set * * @param : int from * @param : int to */ function sequence( from, to ) return coroutine.wrap( function( ) for i = from, to do coroutine.yield( i ) end end ) end /* * get percentage of two numbers * * @param : int num * @param : int max * @param : bool bFormat * @return : int */ function percent( num, max, bFormat ) num = tonumber( num ) or 0 max = tonumber( max ) or 100 local pcalc = 100 * num / max pcalc = math.Clamp( pcalc, 0, 100 ) pcalc = math.Round( pcalc ) return not bFormat and pcalc or string.format( '%.f%%', pcalc ) end /* * bIsInf * * checks for infinity ( -inf, inf ) * * @param : int num * @return : bool */ function bIsInf( num ) return not ( num ~= num or num == math.huge or num == -math.huge ) end /* * bIsNum * * a more controlled version of isnumber used in various circumstances * * @param : int num * @return : bool */ function bIsNum( num ) num = num and tonumber( num ) if num ~= num then return false end if not isnumber( num ) or num < 0 then return false end if num == math.huge or num == -math.huge then return false end return true end /* * converts bytes to various other size types progressively; KB, MB, GB, TB * * @ex : fs.size( 1024 ) : returns 1KB * : fs.size( 1048576 ) : returns 1MB * : fs.size( 1078000000 ) : returns 1GB * * @param : int bytes * @return : str */ function fs.size( bytes ) local rpos = 2 local kb = 1024 local mb = kb * 1024 local gb = mb * 1024 local tb = gb * 1024 if ( ( bytes >= 0 ) and ( bytes < kb ) ) then return bytes .. ' Bytes' elseif ( ( bytes >= kb ) and ( bytes < mb ) ) then return math.Round( bytes / kb, rpos ) .. ' KB' elseif ( ( bytes >= mb ) and ( bytes < gb ) ) then return math.Round( bytes / mb, rpos ) .. ' MB' elseif ( ( bytes >= gb ) and (bytes < tb ) ) then return math.Round(bytes / gb, rpos ) .. ' GB' elseif ( bytes >= tb ) then return math.Round( bytes / tb, rpos ) .. ' TB' else return bytes .. ' B' end end /* * returns the count of files from a specificed path and the * total diskspace used * * @ex : sys.uconn_sz, sys.uconn_ct = calc.fs.diskTotal( 'data/rlib/uconn' ) * * @param : str path * @return : int, int */ function fs.diskTotal( path ) local files, _ = file.Find( path .. '/*', 'DATA' ) local ct_files = #files or 0 local ct_folders = #_ local ct_size = 0 local function recurv( path_sub ) local sub_path = path .. '/' .. path_sub local ifiles, _ = file.Find( sub_path .. '/*', 'DATA' ) ct_files = ct_files + #ifiles for k, v in pairs( ifiles ) do local file_path = sf( '%s/%s', sub_path, v ) local file_size = file.Size( file_path, 'DATA' ) ct_size = ct_size + file_size end end /* * add folders */ for _, v in pairs( _ ) do recurv( v ) end local sz_output = fs.size( ct_size ) return sz_output, ct_files, ct_folders end /* * ratio * * determines the ratio of two numbers ( normally for k:d ratio ), however two different outputs are * available depending on your needs. * * by default, negative numbers can occur, so it is possible ot get -5.00 for a K:D ratio, but if * bPositive is true, this is avoided and all numbers are positive, which is how a majority of k:d * trackers do things * * view examples of the outputs below: * * @ex : ratio( 5, -10 ) : -0.50 * : ratio( 5, -10, true ) : 5.00 * : ratio( -10, 5 ) : -2.00 * : ratio( -10, 5, true ) : 0.00 * * @param : int k * @param : int d * @param : bool bPositive * @return : str */ function ratio( k, d, bPositive ) local response = 0 local params = '%.2f' k = bPositive and bIsNum( k ) and k or tonumber( k ) or 0 d = bPositive and bIsNum( d ) and d or tonumber( d ) or 0 if ( d == 0 and k == 0 ) then return sf( params, response ) end if d == 0 then d = 1 end response = math.Round( k / d, 2 ) if k == 0 and d > 0 then response = -d elseif k == d then response = 1 elseif k > 0 and d == 0 then response = k end if bPositive then response = d < 1 and k or response response = k <= 0 and 0 or response end return sf( params, response ) end /* * seed * * creates random seed based on length ; can be returned as a string using bString = true * * @param : int len * @param : bool bString * @return : int, str */ function seed( len, bString ) len = isnumber( len ) and len or tonumber( len ) or 10 local response = '' for i = 1, len do local min = response == '' and 1 or 0 local index = math.random( min, 9 ) response = response .. index end return not bString and tonumber( response ) or tostring( response ) end /* * calc :: xp percent * * returns information about a users xp * * @param : ply ply * @param : int multiplier * @return : int */ function xp_percent( ply, multiplier ) local pl_level = ( isfunction( ply.getlevel ) and ply:getlevel( ) ) or 0 local pl_xp = ( isfunction( ply.getxp ) and math.floor( ply:getxp( ) ) ) or 0 local xp_format = 0 local xp_calc = 0 local output = 0 if LevelSystemConfiguration then local xp_perc = ( ( pl_xp or 0 ) / ( ( ( 10 + ( ( ( pl_level or 1 ) * ( ( pl_level or 1 ) + 1 ) * 90 ) ) ) ) * ( ( isnumber( multiplier ) and multiplier ) or LevelSystemConfiguration.XPMult or 1.0 ) ) ) or 0 xp_calc = xp_perc * 100 or 0 xp_calc = math.Round( xp_calc ) or 0 xp_format = math.Clamp( xp_calc, 0, 99 ) output = xp_format or 0 elseif DARKRP_LVL_SYSTEM then local lvl_format = DARKRP_LVL_SYSTEM[ 'XP' ][ tonumber( pl_level ) ] if not lvl_format then return end xp_calc = ( pl_xp * 100 / lvl_format ) or 0 xp_format = math.floor( xp_calc ) or 0 output = xp_format or 0 elseif DARKRP_LEVELING_ENTRESTRICT then local maxexp = ExpFormula( ply:GetNWInt( "lvl", 0 )) xp_calc = ( pl_xp * 100 / maxexp ) or 0 xp_format = math.Round( xp_calc ) output = xp_format end return ( isnumber( output ) and output ) or 0 end /* * calc :: xp percentage float * * returns the percentage completed based on a 0 - 1 float * * @ex : 0% 0 * : 50% 0.5 * : 100% 1 * * @param : ply ply * @param : int multiplier * @return : float */ function xp_percent_float( ply, multiplier ) if not LevelSystemConfiguration then return 0 end local pl_level = ( isfunction( ply.getlevel ) and ply:getlevel( ) ) or 0 local pl_xp = ( isfunction( ply.getxp ) and math.floor( ply:getxp( ) ) ) or 0 local pl_calc = ( ( pl_xp or 0 ) / ( ( ( 10 + ( ( ( pl_level or 1 ) * ( ( pl_level or 1 ) + 1 ) * 90 ) ) ) ) * ( ( isnumber( multiplier ) and multiplier ) or LevelSystemConfiguration.XPMult or 1.0 ) ) ) or 0 return pl_calc end /* * calc :: date :: ending trail * * attaches an ending trail onto days * * @ex : 21 21st * : 15 15th * * @param : int dayn * @return : str */ function date_trailing( dayn ) local getday = tonumber( dayn ) last_digit = dayn % 10 if last_digit == 1 and getday ~= 11 then return 'st' elseif last_digit == 2 and getday ~= 12 then return 'nd' elseif last_digit == 3 and getday ~= 13 then return 'rd' else return 'th' end end /* * calc :: is finite * * determines if a value is finite */ function bIsFinite( num ) return not ( num ~= num or num == math.huge or num == -math.huge ) end /* * calc :: pos :: midpoint */ function pos.midpoint( min, max ) local angle = Angle( ) local mid = Vector( ( min.x + max.x ) / 2, ( min.y + max.y ) / 2, ( min.z + max.z ) / 2 ) min = WorldToLocal( min, angle, mid, angle ) max = WorldToLocal( max, angle, mid, angle ) return mid, min, max end /* * calc :: pos :: find floor pos in area */ function pos.findfloorinarea( area ) local trData = { } local trRes = { } local data = area.data local i_pos = Vector( 0, 0, 0 ) local dist = 0 data = data[ math.random( 1, #data ) ] local min = data.min + Vector( 16, 16, 0 ) local max = data.max - Vector( 16, 16, 36 ) i_pos.x = math.random( min.x, max.x ) i_pos.y = math.random( min.y, max.y ) if isvector( area.LastFoundPos ) then while Vector( i_pos.x, i_pos.y, 0 ):Distance( area.LastFoundPos ) < 16 do i_pos.x = math.random( min.x, max.x ) i_pos.y = math.random( min.y, max.y ) end end area.LastFoundPos = Vector( i_pos.x, i_pos.y, 0 ) -- Trying to find the floor. trData.start = Vector( i_pos.x, i_pos.y, max.z ) trData.endpos = Vector( i_pos.x, i_pos.y, min.z ) trRes = util.TraceLine( trData ) dist = trRes.HitPos:Distance( trData.start ) i_pos.z = trRes.HitPos.z if dist < 40 then -- Attempt to place under objects. trData.start = Vector( i_pos.x, i_pos.y, min.z ) trData.endpos = Vector( i_pos.x, i_pos.y, max.z ) trRes = util.TraceLine( trData ) trData.start = trRes.HitPos trData.endpos = Vector( i_pos.x, i_pos.y, min.z ) trRes = util.TraceLine( trData ) dist = trRes.HitPos:Distance( trData.start ) i_pos.z = trRes.HitPos.z end i_pos.z = i_pos.z + 10 return i_pos, ( dist > 40 ) end /* * calc :: pos :: fix min max * * @param : int min * @param : int max * * @return : vector */ function pos.fix_minmax( min, max ) local minX = math.min( min.x, max.x ) local minY = math.min( min.y, max.y ) local minZ = math.min( min.z, max.z ) local maxX = math.max( min.x, max.x ) local maxY = math.max( min.y, max.y ) local maxZ = math.max( min.z, max.z ) return Vector( minX, minY, minZ ), Vector( maxX, maxY, maxZ ) end /* * calc :: int2hex * * converts intger to hex * * @param : int num * * @return : str */ function int2hex( num ) local b, str, val, cur, d = 16, '0123456789ABCDEF', '', 0 while num > 0 do cur = cur + 1 num, d = math.floor( num / b ), math.fmod( num, b ) + 1 val = string.sub( str, d, d ) .. val end val = '0x' .. val return val end /* * calc :: hex2int * * converts hex to integer * * @param : str hex * * @return : int */ function hex2int( hex ) return ( tonumber( hex, 16 ) + 2^31 ) % 2^32 - 2^31 end /* * calc :: equation * * chain mathmatics * * @ex : calc:equation( 10 ):add( 5 ):sub( 3 ):mul( 2 ):result( ) * * @return : int */ local equations = { __index = { add = function( s, num ) s._r = s._r + num return s end, sub = function( s, num ) s._r = s._r - num return s end, mul = function( s, num ) s._r = s._r * num return s end, div = function( s, num ) s._r = s._r / num return s end, result = function( s) return s._r end } } equation = function( s, num ) return smt( { _r = num or 0 }, equations ) end /* * rcc :: base command * * base package command */ function rcc.call:Calc( ply, cmd, args ) /* * permissions */ local ccmd = base.calls:get( 'commands', 'calc' ) if ( ccmd.scope == 1 and not base.con:Is( ply ) ) then access:deny_consoleonly( ply, script, ccmd.id ) return end if not access:bIsRoot( ply ) then access:deny_permission( ply, script, ccmd.id ) return end /* * output */ con( pl, 1 ) con( pl, 0 ) con( pl, Color( 255, 255, 0 ), sf( 'Manifest » %s', pkg_name ) ) con( pl, 0 ) con( pl, manifest.desc ) con( pl, 1 ) local a1_l = sf( '%-20s', 'Version' ) local a2_l = sf( '%-5s', '»' ) local a3_l = sf( '%-35s', sf( 'v%s build-%s', rlib.get:ver2str( manifest.version ), manifest.build ) ) con( pl, Color( 255, 255, 0 ), a1_l, Color( 255, 255, 255 ), a2_l, a3_l ) local b1_l = sf( '%-20s', 'Author' ) local b2_l = sf( '%-5s', '»' ) local b3_l = sf( '%-35s', sf( '%s', manifest.author ) ) con( pl, Color( 255, 255, 0 ), b1_l, Color( 255, 255, 255 ), b2_l, b3_l ) con( pl, 2 ) end /* * register new commands */ local function register_commands( ) local pkg_commands = { [ pkg_name ] = { enabled = true, warn = true, id = pkg_name, name = pkg_name, desc = 'returns package information', scope = 2, clr = Color( 255, 255, 0 ), assoc = function( ... ) rcc.call:Calc( ... ) end, }, } base.calls.commands:Register( pkg_commands ) end hook.Add( pid( 'cmd.register' ), pid( '__calc.cmd.register' ), register_commands ) /* * register package */ local function register_pkg( ) if not istable( _M ) then return end base.package:Register( _M ) end hook.Add( pid( 'pkg.register' ), pid( '__calc.pkg.register' ), register_pkg ) /* * module info :: manifest */ function pkg:manifest( ) return self.__manifest end /* * __tostring */ function pkg:__tostring( ) return self:_NAME( ) end /* * create new class */ function pkg:new( class ) class = class or { } self.__index = self return smt( class, self ) end /* * __index / manifest declarations */ pkg.__manifest = { __index = _M, name = _NAME, build = manifest.build, version = manifest.version, author = manifest.author, desc = manifest.desc } pkg.__index = pkg
local M = {} M.LEFT=1 M.RIGHT=2 function M.play_animation(self,anim,facing) if facing and facing ~= self.current_facing then self.current_facing=facing if facing==M.LEFT then sprite.set_hflip("#sprite", true) else sprite.set_hflip("#sprite", false) end end if anim==nil or anim == self.current_anim then return end msg.post("#sprite", "play_animation", { id = hash(anim) }) self.current_anim = anim end return M
require "export-compile-commands" DIR = path.getabsolute("..") print(DIR) THIRDPARTYDIR = path.join(DIR, "3rdparty") BUILDDIR = path.join(DIR, "build") TESTDIR = path.join(DIR, "tests") workspace "Gabibits" configurations { "Debug", "Release" } platforms { "Android-Arm", "Win32", "Win64", "Linux32", "Linux64" } toolset "clang" include("toolchain.lua") --newoption { --trigger = "prefix", --value = "bin", --description = "Install directory", --} --newaction { --trigger = "install", --description = "Install software in desired prefix, default is bin", --execute = function() --path = "bin/" --if _OPTIONS["prefix"] then --path = _OPTIONS["prefix"] --end --os.mkdir(path) --os.copy('%{cfg.buildtarget.directory}/client', path) --os.copy('%{cfg.buildtarget.directory}/server', path) --end --} project "common" kind "StaticLib" language "C" includedirs { path.join(DIR, "include"), path.join(DIR, "3rdparty"), } links { "m", "pthread", } files { path.join(DIR, "src/http.c"), path.join(DIR, "src/url.c"), } --project "sx" --kind "StaticLib" --language "C" --includedirs { --path.join(DIR, "include"), --path.join(DIR, "3rdparty"), --} --links { --"m", --"pthread", --} --files { --path.join(DIR, "src/sx/*.c"), ----DIR .. "/src/sx/*.c", --} --filter "platforms:Linux64" --system "Linux" --architecture "x86_64" --files { --DIR .. "/src/sx/asm/make_x86_64_sysv_elf_gas.S", --DIR .. "/src/sx/asm/jump_x86_64_sysv_elf_gas.S", --DIR .. "/src/sx/asm/ontop_x86_64_sysv_elf_gas.S", --} --filter "architecture:x86" --system "Linux" --filter {} project "server" kind "ConsoleApp" language "C" includedirs { path.join(DIR, "include"), path.join(DIR, "3rdparty"), } links { --"sx", } prebuildcommands('{MKDIR} %{cfg.buildtarget.directory}/www') postbuildcommands{ 'touch ../server', 'rm ../server', 'ln -s build/%{cfg.buildtarget.abspath} ../server', } filter "platforms:Linux64" system "Linux" architecture "x86_64" symbols "on" links { "common", "pthread", "m", } filter {} files { path.join(DIR, "src/server.c"), } removefiles { path.join(DIR, "src/sx/*.c"), } project "client" kind "ConsoleApp" language "C" includedirs { path.join(DIR, "include"), path.join(DIR, "3rdparty"), } links { --"sx", } prebuildcommands('{MKDIR} %{cfg.buildtarget.directory}/www') postbuildcommands{ 'touch ../client', 'rm ../client', 'ln -s build/%{cfg.buildtarget.abspath} ../client', } filter "platforms:Linux64" system "Linux" architecture "x86_64" symbols "on" --optimize "On" links { "common", "pthread", "m", } filter {} files { path.join(DIR, "src/client.c"), } removefiles { path.join(DIR, "src/sx/*.c"), } --include "tests.lua"
local iter = require("plenary.iterators").iter local utils = require("neo-tree.utils") -- File nesting a la JetBrains (#117). local M = {} M.config = {} --- Checks if file-nesting module is enabled by config ---@return boolean function M.is_enabled() return next(M.config) ~= nil end --- Returns `item` nesting parent path if exists ---@return string? function M.get_parent(item) for base_exts, nesting_exts in pairs(M.config) do for _, exts in ipairs(nesting_exts) do if item.exts == exts then return utils.path_join(item.parent_path, item.base) .. "." .. base_exts end end end return nil end --- Checks if `item` have a valid nesting lookup ---@return boolean function M.can_have_nesting(item) return utils.truthy(M.config[item.exts]) end --- Checks if `target` should be nested into `base` ---@return boolean function M.should_nest_file(base, target) local ext_lookup = M.config[base.exts] return utils.truthy( base.base == target.base and ext_lookup and iter(ext_lookup):find(target.exts) ) end ---Setup the module with the given config ---@param config table function M.setup(config) M.config = config or {} end return M
local button_table = require 'input.button_table' local gamepad = {} function gamepad.new() return setmetatable({ connected = true, leftx = 0, lefty = 0, rightx = 0, righty = 0, triggerleft = 0, triggerright = 0, }, gamepad) end gamepad.pressed = button_table.pressed gamepad.released = button_table.released function gamepad:axis(id, value) self[id] = value end local methods = { pressed = gamepad.pressed, released = gamepad.released, axis = gamepad.axis, } function gamepad:__index(index) return methods[index] or button_table.EMPTY end return gamepad
-- vim: filetype=markdown: --[[ &copy; 2022 Tim Menzies, Jamie Jennings ## Inexact, yet Reasonable Algorithms make choices. Choices have consequences. Many choices are ethical but not choosing is unethical and irrational. Algorithms, once written, have to be wrangled. Do you know how to reason with your algorithms? For example: <table> <tr> <td> <small> <pre> local my= { sames= 512, bins= .5, best= .5, cohen= .35, combine= "mode", far= .9, conf= .05, k= 2, cliffs= .25, loud= false, bootstraps=512, p= 2, seed= 10011, some= 256, wait= 10 } </pre> </small> </td> <td> <img src="https://user-images.githubusercontent.com/29195/130842711-01c78419-c8d4-4b96-8064-2fba3c33d6c4.png"> </td> </tr> </table> But before answering that, perhaps we should ask "why is it important to ask that question?" It has often been said, this is the age of the algorithm. Algorithms control nearly all aspects of our life from the power distribution to the cars, to how we find new friends on the internet, right down to the beating of our hearts (as controlled by pacemakers). We once asked ours students "can you think of anything not controlled by algorithms?" and someone said "my shoes!". In reply we asked "did you buy those shoes via some search engine? Did you pay for those shows on-line? Did the shoes come from overseas and were deliered to you via vast software-controlled develiery system?". You get the point: algorithms rule. But who rules the alorithms? Much has [been said](https://www.thesocialdilemma.com/) the effect of algorithm AI on, say, social media. And a common comment is that these algorithms are beyond our control, that they have emigrant properties that no programmer ever realized could occur. For example, consider the following little experiment. Some data miner is preciting XXX and y as ix SSS. an farness vs accuract So instead of being exact and precise things with simple correct outputs, there are other kinds of inexact algorithms with many internal design choices. And those choices have consequences (here, they critically effective the fairness of the output). to say is that these inexact algorithms have many choices and those choices have consequences. For example, unless we are careful, we can accidentals choose to generate models that - consume too much energy - run too slowly - discriminate against some member of society - or do not achieve any number of domains specific goals. Our premise is that we need tore ason more abut the internal choces inside our algorthms. We should stop always believing thatye theya re exact tools with single correct answers (since if you beleive that, you get consifed ad even wfearful when the algorithms go wild and do what we did not expect). Some algorithm are exact, deterministic, and are guaranteed to generate correct outout. But some are not. ANd those that arenot are uusally better as scaling to very data sets. So we need to be able to reason about that **other kind of algorithm**. What we will say is, to reason about this other other kind of inexact aglorithm, we need to reason about the _data_ it is processing and the _goals_ of the people using it. So when we reason about those kinds of algorithms, we need to reason not just about the program, but also: - the data they analyze (which may chage from day to day). - and the particular goals we want to achieve (which may change from user to user). It turns out that this data-centric and goal-centric approach is astonoshingly useful. semu supervised learning manifolds data reduction. Hence we offer a data-centric and human-centric of inexact algorithms. Our approach includes data mining and optimization and geometry. ALso, we will talk about human psychology., inparticualr heuristics, satisficing, and knowledge acqusition. - _Heuristics_: Firstly, humans use heuristics to explore complex spaces Herusitcs are: - short-cuts that simplify a task - ways to scale some method to large problem (but sometimes might actually introduce errors). - and when , applied to algoriths, heursi makes them inexact - _Satisficing:_ (which is actually a special kind of heuristic) is a combination of satisfy and suffice. Satisficing algorithms search through the available alternatives until an acceptability threshold is met. For example, it is hard to choose between two options if their average performance is very similar and each has some "wriggle" in their putputs - For example, depending on wind conditions, two sailboats with mean speeds of 20 and 22 knots, where that speed might "wriggle" &plusmn; 5 knots. - A satisficing algorirhm might choose either boat at random since the two performances are so similar, we cannot tell them apart. - _Biased_: When humans look at data, they often have _reaons_ for being biased towards some parts of thed ata to others. Such biases can be good or bad: - Suppose our biases let us quickly discard the worst half of any set of solutions. If so, then 20 yes-or-no questions (2<sup>20</sup>) could let find a usefil option within a million possibiltiies. - But those biases can blind us to various aspects of the problem or (accidently or deliberately) make choices that harm people. In this case, we need tools that "shake up the bias" and let us (sometimes) explore the options discreacred by our biases. - Since bias can have negative connotations, we weill call these biases _reasons_ given some model _Y=F(X)_ these _reasons_ (to prefer soemthigns ver another) might be preferemce crtaie across the _X_ space or the _Y_ space. - _Knowledge elicitiation by irritation_: These reasons many not become apparent until after humans see some output. Humans often never realize that they do not like something until they can see specific examples. This means we must assume that the reaosons may be ijitially empty and grow over time. ## About our technology This tutorial is is two parts: theory and practice. The theory is langauge and platform indepdnent while the practical exercises are written in the Lua scripting language. We use Lua since: - It installs, very, quickly on most platforms. - It is fast to learn (see ["Learn Lua in Y minutes"](https://learnxinyminutes.com/docs/lua/); - It uses constructs familiar to a lot of programmers (LUA is like Python, but without the overhead or the needless elaborations) - Lua code has far fewer dependencies that code written in other languages. Having taught (a lot) programming for many eyars, we know that many peopl have (e.g.) local Python environments that differ from platform to platform. These platforms can be idiosyncratic. For example, we know what many data scientists like Anaconda which is a decision that many other programmers prefer to avoid. - Lua has some interesting teaching advantages: - The code for one class can be spread across multiple files. So teaching can work week to week, presenting new ideas on a class, in different weeks. - Lua serves very nicely as an executable specification language. we've had some past success giving people the Lua code then saying "code this up in any language you like, except Lua". We find that students can readily read and reproduce the code (in another language). And during that development work, the students can run our Lua code to see what output is expected. ## Not Complexity, Complicity simple Emergent patterns in Apparently complex systems. While some human problems are inherently complex, others are not. And it is prudent to try simple before complex. ## Data Here, we say that we are reasoning froma _sample_ of data, _rows_ and _columns_. Columns are also known as features, attributes, or variables. Rows contain multiple _X, Y_ features where _X_ are the independent variables (that can be observed, and sometimes controlled) while _Y_ are the dependent variables (e.g. number of defects). When _Y_ is absent, then _unsupervised learners_ seek mappings between the _X_ values. For example, clustering algorithms find groupings of similar rows (i.e. rows with similar X values). Usually most rows have values for most _X_ values. But with text mining, the opposite is true. In principle, text miners have one column for each work in text’s language. Since not all documents use all words, these means that the rows of a text mining data set are often “sparse”; i.e. has mostly missing values. - When _Y_ is present and there is only one of them (i.e. _|Y| = 1_) then supervised learners seek mappings from the X features to the _Y_ values. For example, logistic regression tries to fit the _X, Y_ mapping to a particular equation. - When there are many _Y_ values (i.e. _|Y| > 1_), then another array _W_ stores a set of weights indicating what we want to minimize or maximize (e.g. we would seek to minimize _Y.i_ when _W.i &lt; 0s_). In this case, multi-objective optimizers seek X values that most minimize or maximize their associated Y values. So: - Clustering algorithms find groups of rows; - and Classifiers (and regression algorithms) find how those groups relate to the target Y variables; - and Optimizers are tools that suggest “better” settings for the X values (and, here, “better” means settings that improve the expected value of the Y values). Apart from _W, X, Y_ , we add _Z_, the hyperparameter settings that control how learners performs regression or clustering. For example, a K-th nearest neighbors algorithm needs to know how many nearby rows to use for its classification (in which case, that _k ∈ Z_). Usually the _Z_ values are shared across all rows (exception: some optimizers first cluster the data and use different _Z_ settings for different clusters) Y = F(X) Often easuer to find X than Y. Samples arnot all data so we are always must guess how well some model _F_ learned from old data appies to new data. --]]
local K, C = unpack(select(2, ...)) local Module = K:NewModule("Cooldowns") local _G = _G local math_floor = _G.math.floor local pairs = _G.pairs local select = _G.select local string_find = _G.string.find local CreateFrame = _G.CreateFrame local GetActionCooldown = _G.GetActionCooldown local getmetatable = _G.getmetatable local GetTime = _G.GetTime local hooksecurefunc = _G.hooksecurefunc local SetCVar = _G.SetCVar local FONT_SIZE = 19 local MIN_DURATION = 2 -- the minimum duration to show cooldown text for local MIN_SCALE = 0.5 -- the minimum scale we want to show cooldown counts at, anything below this will be hidden local ICON_SIZE = 36 local hideNumbers, active, hooked = {}, {}, {} function Module:StopTimer() self.enabled = nil self:Hide() end function Module:ForceUpdate() self.nextUpdate = 0 self:Show() end function Module:OnSizeChanged(width) local cooldownFont = K.GetFont(C["UIFonts"].ActionBarsFonts) local fontScale = math_floor(width + 0.5) / ICON_SIZE if fontScale == self.fontScale then return end self.fontScale = fontScale if fontScale < MIN_SCALE then self:Hide() else self.text:SetFontObject(cooldownFont) self.text:SetFont(select(1, self.text:GetFont()), fontScale * FONT_SIZE, select(3, self.text:GetFont())) self.text:SetShadowColor(0, 0, 0, 0) if self.enabled then Module.ForceUpdate(self) end end end function Module:TimerOnUpdate(elapsed) if self.nextUpdate > 0 then self.nextUpdate = self.nextUpdate - elapsed else local remain = self.duration - (GetTime() - self.start) if remain > 0 then local getTime, nextUpdate = K.FormatTime(remain) self.text:SetText(getTime) self.nextUpdate = nextUpdate else Module.StopTimer(self) end end end function Module:OnCreate() local scaler = CreateFrame("Frame", nil, self) scaler:SetAllPoints(self) local timer = CreateFrame("Frame", nil, scaler) timer:Hide() timer:SetAllPoints(scaler) timer:SetScript("OnUpdate", Module.TimerOnUpdate) local text = timer:CreateFontString(nil, "BACKGROUND") text:SetPoint("CENTER", 2, 0) text:SetJustifyH("CENTER") timer.text = text Module.OnSizeChanged(timer, scaler:GetSize()) scaler:SetScript("OnSizeChanged", function(_, ...) Module.OnSizeChanged(timer, ...) end) self.timer = timer return timer end function Module:StartTimer(start, duration) if self:IsForbidden() then return end if self.noOCC or self.noCooldownCount or hideNumbers[self] then return end local frameName = self.GetName and self:GetName() or "" if C["ActionBar"].OverrideWA and string_find(frameName, "WeakAuras") then self.noOCC = true return end if start > 0 and duration > MIN_DURATION then local timer = self.timer or Module.OnCreate(self) timer.start = start timer.duration = duration timer.enabled = true timer.nextUpdate = 0 -- Wait For Blizz To Fix Itself local parent = self:GetParent() local charge = parent and parent.chargeCooldown local chargeTimer = charge and charge.timer if chargeTimer and chargeTimer ~= timer then Module.StopTimer(chargeTimer) end if timer.fontScale >= MIN_SCALE then timer:Show() end elseif self.timer then Module.StopTimer(self.timer) end -- Hide Cooldown Flash If Barfader Enabled if self:GetParent().__faderParent then if self:GetEffectiveAlpha() > 0 then self:Show() else self:Hide() end end end function Module:HideCooldownNumbers() hideNumbers[self] = true if self.timer then Module.StopTimer(self.timer) end end function Module:CooldownOnShow() active[self] = true end function Module:CooldownOnHide() active[self] = nil end local function shouldUpdateTimer(self, start) local timer = self.timer if not timer then return true end return timer.start ~= start end function Module:CooldownUpdate() local button = self:GetParent() local start, duration = GetActionCooldown(button.action) if shouldUpdateTimer(self, start) then Module.StartTimer(self, start, duration) end end function Module:ActionbarUpateCooldown() for cooldown in pairs(active) do Module.CooldownUpdate(cooldown) end end function Module:RegisterActionButton() local cooldown = self.cooldown if not hooked[cooldown] then cooldown:HookScript("OnShow", Module.CooldownOnShow) cooldown:HookScript("OnHide", Module.CooldownOnHide) hooked[cooldown] = true end end function Module:OnEnable() if K.CheckAddOnState("OmniCC") or K.CheckAddOnState("ncCooldown") or K.CheckAddOnState("CooldownCount") then return end if not C["ActionBar"].Cooldowns then return end local cooldownIndex = getmetatable(ActionButton1Cooldown).__index hooksecurefunc(cooldownIndex, "SetCooldown", Module.StartTimer) hooksecurefunc("CooldownFrame_SetDisplayAsPercentage", Module.HideCooldownNumbers) K:RegisterEvent("ACTIONBAR_UPDATE_COOLDOWN", Module.ActionbarUpateCooldown) if _G["ActionBarButtonEventsFrame"].frames then for _, frame in pairs(_G["ActionBarButtonEventsFrame"].frames) do Module.RegisterActionButton(frame) end end hooksecurefunc("ActionBarButtonEventsFrame_RegisterFrame", Module.RegisterActionButton) -- Hide Default Cooldown if not InCombatLockdown() then SetCVar("countdownForCooldowns", 0) end K.HideInterfaceOption(InterfaceOptionsActionBarsPanelCountdownCooldowns) end
local Pipeline = {} local Pobj = {} function Pipeline.output(self, list, flg) if flg == 0 then return end for k,v in pairs(list) do print(k,v) end end function Pipeline.new(self, elements) self.element_list = elements self:output(elements, 0) return PObj end function Pipeline.run(self, pcapdata) local src = { metadata= { data= pcapdata, request = { uri="http://www.candylab.net" } } } for k,v in pairs(self.element_list) do v:init() v:push(src) local src, sink = v:match(pcapdata) if type(sink) == "table" then self:output(sink, 0) end src = sink end end return Pipeline
local L = Grid2Options.L Grid2Options:RegisterStatusOptions("ready-check", "misc", function(self, status, options, optionParams) self:MakeStatusColorOptions(status, options, optionParams) self:MakeStatusThresholdOptions(status, options, optionParams, 1, 20, 1, false) end, { color1 = L["Waiting color"], colorDesc1 = L["Color for Waiting."], color2 = L["Ready color"], colorDesc2 = L["Color for Ready."], color3 = L["Not Ready color"], colorDesc3 = L["Color for Not Ready."], color4 = L["AFK color"], colorDesc4 = L["Color for AFK."], threshold = L["Delay"], thresholdDesc = L["Set the delay until ready check results are cleared."], width = "full", titleIcon = "Interface\\RAIDFRAME\\ReadyCheck-Ready", })
local musicChannel = g_sounds.getChannel(1) -- Public functions function init() connect(g_game, 'onTextMessage', getParams) connect(g_game, { onGameEnd = terminate} ) end function getParams(mode, text) if not g_game.isOnline() then return end if mode == MessageModes.Failure then if string.sub(text, 1, 5) == "Audio" then local ad = string.sub(text, 7, #text) audio = "som/"..ad.."" musicChannel:play(audio) end end end
modifier_pango_mobility_displacement = class({}) function modifier_pango_mobility_displacement:DeclareFunctions() return { MODIFIER_PROPERTY_OVERRIDE_ANIMATION, MODIFIER_PROPERTY_OVERRIDE_ANIMATION_RATE, } end function modifier_pango_mobility_displacement:GetOverrideAnimation() return ACT_DOTA_FLAIL end function modifier_pango_mobility_displacement:GetOverrideAnimationRate() return 1.0 end function modifier_pango_mobility_displacement:CheckState() return { [MODIFIER_STATE_NO_UNIT_COLLISION] = true, } end if IsClient() then require("wrappers/modifiers") end Modifiers.Displacement(modifier_pango_mobility_displacement) Modifiers.Animation(modifier_pango_mobility_displacement)
tigris.magic.register_spell("tigris_magic:snuff", { description = "Snuff", longdesc = "Launches a projectile that puts out fire with water.", cost = {mana = 30}, emblem = "defense", color = "#70F", on_use = function(itemstack, player, pointed_thing) tigris.create_projectile("tigris_magic:snuff_projectile", { pos = vector.add(player:getpos(), vector.new(0, 1.4, 0)), velocity = vector.multiply(player:get_look_dir(), 20), gravity = 0.25, owner = player:get_player_name(), owner_object = player, }) return true end, }) local function f(self, pos) local search = vector.new(8, 8, 8) local start = vector.subtract(pos, search) local last = vector.add(pos, search) for _,pos in ipairs(minetest.find_nodes_in_area(start, last, {"fire:basic_flame"})) do if not minetest.is_protected(pos, self._owner) then minetest.set_node(pos, {name = "default:water_flowing"}) end end return true end tigris.register_projectile("tigris_magic:snuff_projectile", { texture = "default_water.png", on_any_hit = f, on_entity_hit = function(self, obj) return f(self, obj:getpos()) end, }) minetest.register_craft({ output = "tigris_magic:snuff", recipe = { {"tigris_magic:freeze", "", "tigris_magic:freeze"}, {"tigris_mobs:water_lung", "tigris_mobs:water_lung", "tigris_mobs:water_lung"}, {"tigris_magic:freeze", "", "tigris_magic:freeze"}, }, })
object_tangible_item_beast_converted_blurrg_decoration = object_tangible_item_beast_shared_converted_blurrg_decoration:new { } ObjectTemplates:addTemplate(object_tangible_item_beast_converted_blurrg_decoration, "object/tangible/item/beast/converted_blurrg_decoration.iff")
local bit32 = require("bit") local lshift = bit32.lshift local rshift = bit32.rshift local band = bit32.band function apply(opcodes, opcode_cycles, z80, memory) -- ld r, r opcodes[0x40] = function(self, reg, flags, mem) reg[4] = reg[4] end opcodes[0x41] = function(self, reg, flags, mem) reg[4] = reg[5] end opcodes[0x42] = function(self, reg, flags, mem) reg[4] = reg[6] end opcodes[0x43] = function(self, reg, flags, mem) reg[4] = reg[7] end opcodes[0x44] = function(self, reg, flags, mem) reg[4] = reg[9] end opcodes[0x45] = function(self, reg, flags, mem) reg[4] = reg[10] end opcode_cycles[0x46] = 8 opcodes[0x46] = function(self, reg, flags, mem) reg[4] = self.read_at_hl() end opcodes[0x47] = function(self, reg, flags, mem) reg[4] = reg[3] end opcodes[0x48] = function(self, reg, flags, mem) reg[5] = reg[4] end opcodes[0x49] = function(self, reg, flags, mem) reg[5] = reg[5] end opcodes[0x4A] = function(self, reg, flags, mem) reg[5] = reg[6] end opcodes[0x4B] = function(self, reg, flags, mem) reg[5] = reg[7] end opcodes[0x4C] = function(self, reg, flags, mem) reg[5] = reg[9] end opcodes[0x4D] = function(self, reg, flags, mem) reg[5] = reg[10] end opcode_cycles[0x4E] = 8 opcodes[0x4E] = function(self, reg, flags, mem) reg[5] = self.read_at_hl() end opcodes[0x4F] = function(self, reg, flags, mem) reg[5] = reg[3] end opcodes[0x50] = function(self, reg, flags, mem) reg[6] = reg[4] end opcodes[0x51] = function(self, reg, flags, mem) reg[6] = reg[5] end opcodes[0x52] = function(self, reg, flags, mem) reg[6] = reg[6] end opcodes[0x53] = function(self, reg, flags, mem) reg[6] = reg[7] end opcodes[0x54] = function(self, reg, flags, mem) reg[6] = reg[9] end opcodes[0x55] = function(self, reg, flags, mem) reg[6] = reg[10] end opcode_cycles[0x56] = 8 opcodes[0x56] = function(self, reg, flags, mem) reg[6] = self.read_at_hl() end opcodes[0x57] = function(self, reg, flags, mem) reg[6] = reg[3] end opcodes[0x58] = function(self, reg, flags, mem) reg[7] = reg[4] end opcodes[0x59] = function(self, reg, flags, mem) reg[7] = reg[5] end opcodes[0x5A] = function(self, reg, flags, mem) reg[7] = reg[6] end opcodes[0x5B] = function(self, reg, flags, mem) reg[7] = reg[7] end opcodes[0x5C] = function(self, reg, flags, mem) reg[7] = reg[9] end opcodes[0x5D] = function(self, reg, flags, mem) reg[7] = reg[10] end opcode_cycles[0x5E] = 8 opcodes[0x5E] = function(self, reg, flags, mem) reg[7] = self.read_at_hl() end opcodes[0x5F] = function(self, reg, flags, mem) reg[7] = reg[3] end opcodes[0x60] = function(self, reg, flags, mem) reg[9] = reg[4] end opcodes[0x61] = function(self, reg, flags, mem) reg[9] = reg[5] end opcodes[0x62] = function(self, reg, flags, mem) reg[9] = reg[6] end opcodes[0x63] = function(self, reg, flags, mem) reg[9] = reg[7] end opcodes[0x64] = function(self, reg, flags, mem) reg[9] = reg[9] end opcodes[0x65] = function(self, reg, flags, mem) reg[9] = reg[10] end opcode_cycles[0x66] = 8 opcodes[0x66] = function(self, reg, flags, mem) reg[9] = self.read_at_hl() end opcodes[0x67] = function(self, reg, flags, mem) reg[9] = reg[3] end opcodes[0x68] = function(self, reg, flags, mem) reg[10] = reg[4] end opcodes[0x69] = function(self, reg, flags, mem) reg[10] = reg[5] end opcodes[0x6A] = function(self, reg, flags, mem) reg[10] = reg[6] end opcodes[0x6B] = function(self, reg, flags, mem) reg[10] = reg[7] end opcodes[0x6C] = function(self, reg, flags, mem) reg[10] = reg[9] end opcodes[0x6D] = function(self, reg, flags, mem) reg[10] = reg[10] end opcode_cycles[0x6E] = 8 opcodes[0x6E] = function(self, reg, flags, mem) reg[10] = self.read_at_hl() end opcodes[0x6F] = function(self, reg, flags, mem) reg[10] = reg[3] end opcode_cycles[0x70] = 8 opcodes[0x70] = function(self, reg, flags, mem) self.set_at_hl(reg, mem, reg[4]) end opcode_cycles[0x71] = 8 opcodes[0x71] = function(self, reg, flags, mem) self.set_at_hl(reg, mem, reg[5]) end opcode_cycles[0x72] = 8 opcodes[0x72] = function(self, reg, flags, mem) self.set_at_hl(reg, mem, reg[6]) end opcode_cycles[0x73] = 8 opcodes[0x73] = function(self, reg, flags, mem) self.set_at_hl(reg, mem, reg[7]) end opcode_cycles[0x74] = 8 opcodes[0x74] = function(self, reg, flags, mem) self.set_at_hl(reg, mem, reg[9]) end opcode_cycles[0x75] = 8 opcodes[0x75] = function(self, reg, flags, mem) self.set_at_hl(reg, mem, reg[10]) end -- 0x76 is HALT, we implement that elsewhere opcode_cycles[0x77] = 8 opcodes[0x77] = function(self, reg, flags, mem) self.set_at_hl(reg, mem, reg[3]) end opcodes[0x78] = function(self, reg, flags, mem) reg[3] = reg[4] end opcodes[0x79] = function(self, reg, flags, mem) reg[3] = reg[5] end opcodes[0x7A] = function(self, reg, flags, mem) reg[3] = reg[6] end opcodes[0x7B] = function(self, reg, flags, mem) reg[3] = reg[7] end opcodes[0x7C] = function(self, reg, flags, mem) reg[3] = reg[9] end opcodes[0x7D] = function(self, reg, flags, mem) reg[3] = reg[10] end opcode_cycles[0x7E] = 8 opcodes[0x7E] = function(self, reg, flags, mem) reg[3] = self.read_at_hl() end opcodes[0x7F] = function(self, reg, flags, mem) reg[3] = reg[3] end -- ld r, n opcode_cycles[0x06] = 8 opcodes[0x06] = function(self, reg, flags, mem) reg[4] = self.read_nn() end opcode_cycles[0x0E] = 8 opcodes[0x0E] = function(self, reg, flags, mem) reg[5] = self.read_nn() end opcode_cycles[0x16] = 8 opcodes[0x16] = function(self, reg, flags, mem) reg[6] = self.read_nn() end opcode_cycles[0x1E] = 8 opcodes[0x1E] = function(self, reg, flags, mem) reg[7] = self.read_nn() end opcode_cycles[0x26] = 8 opcodes[0x26] = function(self, reg, flags, mem) reg[9] = self.read_nn() end opcode_cycles[0x2E] = 8 opcodes[0x2E] = function(self, reg, flags, mem) reg[10] = self.read_nn() end opcode_cycles[0x36] = 12 opcodes[0x36] = function(self, reg, flags, mem) self.set_at_hl(reg, mem, self.read_nn()) end opcode_cycles[0x3E] = 8 opcodes[0x3E] = function(self, reg, flags, mem) reg[3] = self.read_nn() end -- ld A, (xx) opcode_cycles[0x0A] = 8 opcodes[0x0A] = function(self, reg, flags, mem) reg[3] = mem[reg.bc()] end opcode_cycles[0x1A] = 8 opcodes[0x1A] = function(self, reg, flags, mem) reg[3] = mem[reg.de()] end opcode_cycles[0xFA] = 16 opcodes[0xFA] = function(self, reg, flags, mem) reg[3] = mem[self.read_nn() + self.read_nn() * 256] end -- ld (xx), A opcode_cycles[0x02] = 8 opcodes[0x02] = function(self, reg, flags, mem) mem[reg.bc()] = reg[3] end opcode_cycles[0x12] = 8 opcodes[0x12] = function(self, reg, flags, mem) mem[reg.de()] = reg[3] end opcode_cycles[0xEA] = 16 opcodes[0xEA] = function(self, reg, flags, mem) local lower = self.read_nn() local upper = lshift(self.read_nn(), 8) mem[upper + lower] = reg[3] end -- ld a, (FF00 + nn) opcode_cycles[0xF0] = 12 opcodes[0xF0] = function(self, reg, flags, mem) reg[3] = mem[0xFF00 + self.read_nn()] end -- ld (FF00 + nn), a opcode_cycles[0xE0] = 12 opcodes[0xE0] = function(self, reg, flags, mem) mem[0xFF00 + self.read_nn()] = reg[3] end -- ld a, (FF00 + C) opcode_cycles[0xF2] = 8 opcodes[0xF2] = function(self, reg, flags, mem) reg[3] = mem[0xFF00 + reg[5]] end -- ld (FF00 + C), a opcode_cycles[0xE2] = 8 opcodes[0xE2] = function(self, reg, flags, mem) mem[0xFF00 + reg[5]] = reg[3] end -- ldi (HL), a opcode_cycles[0x22] = 8 opcodes[0x22] = function(self, reg, flags, mem) self.set_at_hl(reg, mem, reg[3]) reg.set_hl(band(reg.hl() + 1, 0xFFFF)) end -- ldi a, (HL) opcode_cycles[0x2A] = 8 opcodes[0x2A] = function(self, reg, flags, mem) reg[3] = self.read_at_hl() reg.set_hl(band(reg.hl() + 1, 0xFFFF)) end -- ldd (HL), a opcode_cycles[0x32] = 8 opcodes[0x32] = function(self, reg, flags, mem) self.set_at_hl(reg, mem, reg[3]) reg.set_hl(band(reg.hl() - 1, 0xFFFF)) end -- ldd a, (HL) opcode_cycles[0x3A] = 8 opcodes[0x3A] = function(self, reg, flags, mem) reg[3] = self.read_at_hl() reg.set_hl(band(reg.hl() - 1, 0xFFFF)) end -- ====== GMB 16-bit load commands ====== -- ld BC, nnnn opcode_cycles[0x01] = 12 opcodes[0x01] = function(self, reg, flags, mem) reg[5] = self.read_nn() reg[4] = self.read_nn() end -- ld DE, nnnn opcode_cycles[0x11] = 12 opcodes[0x11] = function(self, reg, flags, mem) reg[7] = self.read_nn() reg[6] = self.read_nn() end -- ld HL, nnnn opcode_cycles[0x21] = 12 opcodes[0x21] = function(self, reg, flags, mem) reg[10] = self.read_nn() reg[9] = self.read_nn() end -- ld SP, nnnn opcode_cycles[0x31] = 12 opcodes[0x31] = function(self, reg, flags, mem) local lower = self.read_nn() local upper = lshift(self.read_nn(), 8) reg[2] = band(0xFFFF, upper + lower) end -- ld SP, HL opcode_cycles[0xF9] = 8 opcodes[0xF9] = function(self, reg, flags, mem) reg[2] = reg.hl() end -- ld HL, SP + dd opcode_cycles[0xF8] = 12 opcodes[0xF8] = function(self, reg, flags, mem) -- cheat local old_sp = reg[2] opcodes[0xE8](self, reg, flags, mem) reg.set_hl(reg[2]) reg[2] = old_sp end -- ====== GMB Special Purpose / Relocated Commands ====== -- ld (nnnn), SP opcode_cycles[0x08] = 20 opcodes[0x08] = function(self, reg, flags, mem) local lower = self.read_nn() local upper = lshift(self.read_nn(), 8) local address = upper + lower mem[address] = band(reg[2], 0xFF) mem[band(address + 1, 0xFFFF)] = rshift(band(reg[2], 0xFF00), 8) end end return apply
 -- Place this file into your %FARPROFILE%\Macros\scripts -- Switch visibility of ConEmu Panel Views -- You may customize Panel Views display in ConEmu Settings -> Views local ConEmuTh = "bd454d48-448e-46cc-909d-b6cf789c2d65" Macro { area="Shell"; key="CtrlShiftF1"; flags=""; description="ConEmu: Switch Thumbnails view on active panel"; action = function() Plugin.Call(ConEmuTh,1) end } Macro { area="Shell"; key="CtrlShiftF2"; flags=""; description="ConEmu: Switch Tiles view on active panel"; action = function() Plugin.Call(ConEmuTh,2) end } Macro { area="Shell"; --key="CtrlAltF2"; flags=""; description="ConEmu: Turn off Tiles or Thumbnails on active panel"; action = function() Plugin.Call(ConEmuTh,256) end }
class("DoneNumbersDisabled").extends() function DoneNumbersDisabled:init(puzzle) self.left = table.create(puzzle.height, 0) for y = 1, puzzle.height do self.left[y] = {} end self.top = table.create(puzzle.width, 0) for x = 1, puzzle.width do self.top[x] = {} end end function DoneNumbersDisabled:updatePosition() end function DoneNumbersDisabled:updateAll() end
#!/usr/bin/env lua -- -- Reads data from a streaming API method. -- local cfg = require "_config"() local twitter = require "luatwit" local util = require "luatwit.util" local pretty = require "pl.pretty" -- initialize the twitter client local oauth_params = util.load_keys(cfg.app_keys, cfg.user_keys) local client = twitter.api.new(oauth_params) -- open the streaming connection (must be async) local stream = client:stream_user{ _async = true } local function format_tweet(tweet) local rt = "" if tweet.retweeted_status then rt = "[RT] " tweet = tweet.retweeted_status end local text = tweet.text:gsub("&(%a+);", { lt = "<", gt = ">", amp = "&" }) return string.format("%s<%s> %s" , rt, tweet.user.screen_name, text) end local function printf(fmt, ...) return print(fmt:format(...)) end local n = 0 -- consume the stream data while stream:is_active() do -- iterate over the received items for data in stream:iter() do local t_data = util.type(data) -- tweet if t_data == "tweet" then print(format_tweet(data)) -- deleted tweet elseif t_data == "tweet_deleted" then printf("[tweet deleted] %s", data.delete.status.id_str) -- stream events (blocks, favs, follows, list operations, profile updates) elseif t_data == "stream_event" then local desc = "" local t_obj = util.type(data.target_object) if t_obj == "tweet" then desc = format_tweet(data.target_object) elseif t_obj == "userlist" then desc = data.target_object.full_name end printf("[%s] %s -> %s %s", data.event, data.source.screen_name, data.target.screen_name, desc) -- list of following user ids elseif t_data == "friend_list_str" then printf("[friend list] (%s users)", #data.friends_str) -- number sent when the option `delimited = "length"` is set elseif t_data == "number" then print("[size delimiter] " .. data) -- everything else else printf("[%s] %s", t_data, pretty.write(data)) end n = n + 1 end -- close the stream after receiving 100 messages if n > 100 then stream:close() end -- wait for data to arrive client.http:wait() end
-- Pretty much everything here is dangerous. Possibly life-threatening. local FIXED local function FixAllErrors() if FIXED then return end local NIL = getmetatable(nil) or {} local NUMBER = getmetatable(0) or {} local STRING = getmetatable("") local VECTOR = FindMetaTable("Vector") local NULL_META = getmetatable(NULL) table.Merge(NIL,{ __add = function(a,b) return a or b end, __sub = function(a,b) return a or b end, __mul = function(a,b) return a or b end, __div = function(a,b) return a end, __pow = function(a,b) if not b then return 1 else return 0 end end, __unm = function(a) return a end, __concat = function(a,b) return tostring(a) .. tostring(b) end, __len = function() return 0 end, __lt = function(a,b) if isnumber(a) or isnumber(b) then return (a or 0) < (b or 0) else return tostring(a) < tostring(b) end end, __le = function(a,b) if isnumber(a) or isnumber(b) then return (a or 0) <= (b or 0) else return tostring(a) <= tostring(b) end end, __index = function() end, __newindex = function() end, __call = function() end }) NUMBER.__lt = NIL.__lt NUMBER.__le = NIL.__le STRING.__lt = NIL.__lt STRING.__le = NIL.__le STRING.__add = function(a,b) return tostring(a)..tostring(b) end STRING.__concat = function(a,b) return tostring(a)..tostring(b) end STRING.IsValid = function() return true end local oldadd,oldsub = VECTOR.__add,VECTOR.__sub local oldmul,olddiv = VECTOR.__mul,VECTOR.__div VECTOR.__add = function(a,b) return oldadd(isvector(a) and a or Vector(a),isvector(b) and b or Vector(b)) end VECTOR.__sub = function(a,b) return oldsub(isvector(a) and a or Vector(a),isvector(b) and b or Vector(b)) end VECTOR.__mul = function(a,b) return oldmul(a or 1,b or 1) end VECTOR.__div = function(a,b) return olddiv(a or 1,b or 1) end local oldGC = NULL_META.GetClass NULL_META.GetClass = function(ent,...) if not IsValid(ent) then return ent.__tostring(ent,...) else return oldGC(ent,...) end end local oldPos = NULL_META.GetPos NULL_META.GetPos = function(ent,...) if not IsValid(ent) then return vector_origin else return oldPos(ent,...) end end --[[local oldindex = NULL_META.__index NULL_META.__index = function(ent,key) if rawget() then local args = {pcall(oldindex,ent,key)} if not args[1] then error("Attempt to call \""..key.."\" on a NULL entity (tell the owner of \"Lua and Model Error Fixers\" about it!)") end else return oldindex(ent,key) end end]] debug.setmetatable(nil,NIL) debug.setmetatable(0,NUMBER) FIXED = true end if SERVER then util.AddNetworkString("error_fixer_tool") end local EnabledVar = CreateConVar("lua_errfixer_auto","1",FCVAR_ARCHIVE) if CLIENT then concommand.Add("lua_errfixer_run",function(ply,cmd,args,str) FixAllErrors() net.Start("error_fixer_tool") net.SendToServer() end) end net.Receive("error_fixer_tool",function() FixAllErrors() end) hook.Add("AddToolMenuCategories","error_fixer_tool",function() spawnmenu.AddToolCategory("Main","error_fixers","Error Fixers") end) hook.Add("OnReloaded","error_fixer_tool",function() if FIXED and CLIENT then chat.AddText(Color(255,0,0),"Make sure to turn off the Lua Error Fixer first before editing any Lua files! Make sure Automatically Run On Initialization is disabled, then restart the map.") end end) hook.Add("PopulateToolMenu","error_fixer_tool",function() spawnmenu.AddToolMenuOption("Main","error_fixers","model_error_fixer","Model Error Fixer","gmod_tool model_errfixer","",function(DForm) DForm:Help("You can use Left Click to select an ERROR model, or you can input it manually.") DForm:TextEntry("ERROR Model","model_errfixer_old_model") DForm:Button("Get Info About ERROR Model","model_errfixer_info","model_errfixer_old_model") DForm:Help("You can use Right Click to select a model to use to replace the ERROR model, or you can input it manually.") DForm:Help("Right Click on the world to make this field blank. Leave this field blank if you wish to delete the ERROR model.") DForm:TextEntry("New Model","model_errfixer_new_model") DForm:Button("Get Info About New Model","model_errfixer_info","model_errfixer_new_model") DForm:Help("ERROR models can't be hit directly with a Tool Gun. This value determines the radius to check for ERROR models.") local NS = DForm:NumSlider("Sphere Radius","model_errfixer_sphere_radius",0,300) NS:SetDefaultValue(100) DForm:CheckBox("Draw Sphere","model_errfixer_draw_sphere") end) spawnmenu.AddToolMenuOption("Main","error_fixers","lua_error_fixer","Lua Error Fixer","","",function(DForm) local DLabel = DForm:Help("WARNING: If you are a Lua developer, make sure that this feature is OFF before testing your code! \z Otherwise, those who don't have this addon may receive numerous errors from your code!\n\n\z Note that this functionality might cause slight performance issues.") DLabel:SetTextColor(Color(255,0,0)) DForm:Button("Loosen Lua Rules","lua_errfixer_run") DForm:CheckBox("Automatically Run On Initialization","lua_errfixer_auto") end) end) hook.Add("Initialize","error_fixer_tool",function() if EnabledVar:GetBool() then FixAllErrors() end end)
--[[ This file was extracted by 'EsoLuaGenerator' at '2021-09-04 16:42:29' using the latest game version. NOTE: This file should only be used as IDE support; it should NOT be distributed with addons! **************************************************************************** CONTENTS OF THIS FILE IS COPYRIGHT ZENIMAX MEDIA INC. **************************************************************************** ]] function ZO_Tooltip:LayoutServiceTokenTooltip(tokenType) local tokenTypeString = GetString("SI_SERVICETOKENTYPE", tokenType) local headerSection = self:AcquireSection(self:GetStyle("bodyHeader")) local title = zo_strformat(SI_SERVICE_TOOLTIP_HEADER_FORMATTER, tokenTypeString) headerSection:AddLine(title, self:GetStyle("title")) self:AddSection(headerSection) local descriptionSection = self:AcquireSection(self:GetStyle("bodySection")) local tokenDescription = GetServiceTokenDescription(tokenType) descriptionSection:AddLine(tokenDescription, self:GetStyle("bodyDescription")) self:AddSection(descriptionSection) if tokenType == SERVICE_TOKEN_ALLIANCE_CHANGE then local anyRaceCollectibleId = GetAnyRaceAnyAllianceCollectibleId() local collectibleName = GetCollectibleName(anyRaceCollectibleId) local categoryName = GetCollectibleCategoryNameByCollectibleId(anyRaceCollectibleId) local tokensAvailableText = zo_strformat(SI_SERVICE_TOOLTIP_REQUIRES_COLLECTIBLE_TO_USE, collectibleName, categoryName) local meetsRequirementTextStyle local numTokens = GetNumServiceTokens(tokenType) if CanPlayAnyRaceAsAnyAlliance() then meetsRequirementTextStyle = self:GetStyle("succeeded") else meetsRequirementTextStyle = self:GetStyle("failed") end local requiredCollectibleSection = self:AcquireSection(self:GetStyle("bodySection")) requiredCollectibleSection:AddLine(tokensAvailableText, self:GetStyle("bodyDescription"), meetsRequirementTextStyle) self:AddSection(requiredCollectibleSection) end local tokensAvailableText local tokensAvailableTextStyle local numTokens = GetNumServiceTokens(tokenType) if numTokens ~= 0 then tokensAvailableText = zo_strformat(SI_SERVICE_TOOLTIP_SERVICE_TOKENS_AVAILABLE, numTokens, tokenTypeString) tokensAvailableTextStyle = self:GetStyle("succeeded") else tokensAvailableText = zo_strformat(SI_SERVICE_TOOLTIP_NO_SERVICE_TOKENS_AVAILABLE, tokenTypeString) tokensAvailableTextStyle = self:GetStyle("failed") end local tokenSection = self:AcquireSection(self:GetStyle("bodySection")) tokenSection:AddLine(tokensAvailableText, self:GetStyle("bodyDescription"), tokensAvailableTextStyle) self:AddSection(tokenSection) end
local Widget = require "widgets/widget" local UIAnim = require "widgets/uianim" local Text = require "widgets/text" local SavingIndicator = Class(Widget, function(self, owner) self.owner = owner Widget._ctor(self, "Saving") self.anim = self:AddChild(UIAnim()) self.anim:GetAnimState():SetBank("saving") self.anim:GetAnimState():SetBuild("saving") self:Hide() local scale = .5 self.text = self:AddChild(Text(UIFONT, 50/scale)) self.text:SetString(STRINGS.UI.HUD.SAVING) self.text:SetColour(241/255, 199/255, 66/255, 1) self.text:SetHAlign(ANCHOR_LEFT) self.text:SetPosition(160, -170, 0) self.text:Hide() self:SetScale(scale,scale,scale) self:SetPosition(100, 0,0) end) function SavingIndicator:EndSave() self.text:Hide() self.anim:GetAnimState():PlayAnimation("save_post") end function SavingIndicator:StartSave() self:Show() self.anim:GetAnimState():PlayAnimation("save_pre") self.inst:DoTaskInTime(.5, function() self.text:Show()end) self.anim:GetAnimState():PushAnimation("save_loop", true) end return SavingIndicator
-- local a = vim.api ----------------------------- -- Export ----------------------------- ---@class lir_utils local utils = {} ---@param msg string function utils.error(msg) vim.cmd([[redraw]]) vim.cmd([[echohl Error]]) vim.cmd(string.format([[echomsg '%s']], msg)) vim.cmd([[echohl None]]) end return utils
object_mobile_azure_cabal_mystril_slicer_02 = object_mobile_shared_azure_cabal_mystril_slicer_02:new { } ObjectTemplates:addTemplate(object_mobile_azure_cabal_mystril_slicer_02, "object/mobile/azure_cabal_mystril_slicer_02.iff")
rule("c++.reflection") after_load(function (target, opt) import("gen_refl") local headerfiles = {} local files = target:extraconf("rules", "c++.reflection", "files") for _, file in ipairs(files) do local p = path.join(target:scriptdir(), file) for __, filepath in ipairs(os.files(p)) do table.insert(headerfiles, filepath) end end gen_refl(target, headerfiles) end) on_config(function (target, opt) import("gen_refl") local rootdir = target:extraconf("rules", "c++.reflection", "rootdir") local abs_rootdir = path.absolute(path.join(target:scriptdir(), rootdir)) if has_config("is_msvc") then opt = opt or {} opt.cl = true end gen_refl.generate_refl_files(target, abs_rootdir, opt) -- add to sourcebatch local sourcebatches = target:sourcebatches() local gendir = path.join(target:autogendir({root = true}), target:plat(), "reflection/generated") if os.exists(gendir) then target:add("includedirs", gendir, {public = true}) target:add("includedirs", path.join(gendir, target:name())) end local cppfiles = os.files(path.join(gendir, "/**.cpp")) for _, file in ipairs(cppfiles) do target:add("files", file) end end)
technic.register_tier("MV", "Medium Voltage") local path = technic.modpath.."/machines/MV" -- Wiring stuff dofile(path.."/cables.lua") dofile(path.."/battery_box.lua") -- Generators if technic.config:get_bool("enable_wind_mill") then dofile(path.."/wind_mill.lua") end dofile(path.."/generator.lua") dofile(path.."/solar_array.lua") -- Machines dofile(path.."/alloy_furnace.lua") dofile(path.."/electric_furnace.lua") dofile(path.."/grinder.lua") dofile(path.."/extractor.lua") dofile(path.."/compressor.lua") dofile(path.."/centrifuge.lua") dofile(path.."/tool_workshop.lua") -- The power radiator supplies appliances with inductive coupled power: -- Lighting and associated textures is taken directly from VanessaE's homedecor and made electric. -- This is currently useless, slow, and mostly copied --dofile(path.."/power_radiator.lua") --dofile(path.."/lighting.lua")
-- mod-version:2 -- lite-xl 2.0 local style = require "core.style" local config = require "core.config" local DocView = require "core.docview" -- TODO: replace with `doc:get_indent_info()` when 2.1 releases local function get_indent_info(doc) if doc.get_indent_info then return doc:get_indent_info() end return config.tab_type, config.indent_size end local function get_line_spaces(doc, idx, dir) local _, indent_size = get_indent_info(doc) local text = doc.lines[idx] if not text or #text == 1 then return -1 end local s, e = text:find("^%s*") if e == #text then return get_line_spaces(doc, idx + dir, dir) end local n = 0 for _,b in pairs({text:byte(s, e)}) do n = n + (b == 9 and indent_size or 1) end return n end local function get_line_indent_guide_spaces(doc, idx) if doc.lines[idx]:find("^%s*\n") then return math.max( get_line_spaces(doc, idx - 1, -1), get_line_spaces(doc, idx + 1, 1)) end return get_line_spaces(doc, idx) end local docview_update = DocView.update function DocView:update() docview_update(self) local function get_indent(idx) if idx < 1 or idx > #self.doc.lines then return -1 end if not self.indentguide_indents[idx] then self.indentguide_indents[idx] = get_line_indent_guide_spaces(self.doc, idx) end return self.indentguide_indents[idx] end self.indentguide_indents = {} self.indentguide_indent_active = {} local minline, maxline = self:get_visible_line_range() for i = minline, maxline do self.indentguide_indents[i] = get_line_indent_guide_spaces(self.doc, i) end local _, indent_size = get_indent_info(self.doc) for _,line in self.doc:get_selections() do local lvl = get_indent(line) local top, bottom if not self.indentguide_indent_active[line] or self.indentguide_indent_active[line] > lvl then -- check if we're the header or the footer of a block if get_indent(line + 1) > lvl and get_indent(line + 1) <= lvl + indent_size then top = true lvl = get_indent(line + 1) elseif get_indent(line - 1) > lvl and get_indent(line - 1) <= lvl + indent_size then bottom = true lvl = get_indent(line - 1) end self.indentguide_indent_active[line] = lvl -- check if the lines before the current are part of the block local i = line - 1 if i > 0 and not top then repeat if get_indent(i) <= lvl - indent_size then break end self.indentguide_indent_active[i] = lvl i = i - 1 until i < minline end -- check if the lines after the current are part of the block i = line + 1 if i <= #self.doc.lines and not bottom then repeat if get_indent(i) <= lvl - indent_size then break end self.indentguide_indent_active[i] = lvl i = i + 1 until i > maxline end end end end local draw_line_text = DocView.draw_line_text function DocView:draw_line_text(idx, x, y) local spaces = self.indentguide_indents[idx] or -1 local _, indent_size = get_indent_info(self.doc) local w = math.max(1, SCALE) local h = self:get_line_height() local font = self:get_font() local space_sz = font:get_width(" ") for i = 0, spaces - 1, indent_size do local color = style.guide or style.selection local active_lvl = self.indentguide_indent_active[idx] or -1 if i < active_lvl and i + indent_size >= active_lvl then color = style.guide_highlight or style.accent end local sw = space_sz * i renderer.draw_rect(math.ceil(x + sw), y, w, h, color) end draw_line_text(self, idx, x, y) end
local sourcelessvalue = false; function setState(state) local datavalue = 1; if state == nil or state == false or state == 0 then datavalue = 0; end if source and not source.isStatic() then source.setValue(datavalue); else if datavalue == 0 then sourcelessvalue = false; else sourcelessvalue = true; end update(); end end function update() if source then if source.getValue() ~= 0 then setIcon(stateicons[1].on[1]); else setIcon(stateicons[1].off[1]); end else if sourcelessvalue then setIcon(stateicons[1].on[1]); else setIcon(stateicons[1].off[1]); end end if self.onValueChanged then self.onValueChanged(); end end function getState() if source then local datavalue = source.getValue(); return datavalue ~= 0; else return sourcelessvalue; end end function onClickDown(button, x, y) self.setState(not getState()); end function onInit() setIcon(stateicons[1].off[1]); if not sourceless and window.getDatabaseNode() then -- Get value from source node if sourcename then source = window.getDatabaseNode().createChild(sourcename[1], "number"); else source = window.getDatabaseNode().createChild(getName(), "number"); end if source then source.onUpdate = update; update(); end else -- Use internal value, initialize to checked if <checked /> is specified if checked then sourcelessvalue = true; update(); end end end
local setmetatable = setmetatable local ipairs = ipairs local math = math local base = require('wibox.widget.base') local color = require("gears.color") local beautiful = require("beautiful") local lgi = require("lgi") local cairo = lgi.cairo local Pango = lgi.Pango local assault = { mt = {} } local data = setmetatable({}, { __mode = "k" }) local properties = { "width", "height" } function assault.fit (assault, width, height) local width = 2 + data[assault].width + (data[assault].stroke_width * 2) + data[assault].peg_width local height = 2 + data[assault].height + (data[assault].stroke_width * 2) print('fit out: ' .. width .. ' / ' .. height) return width, height end local round = function (num, idp) return tonumber(string.format("%." .. (idp or 0) .. "f", num)) end local acpi_is_on_ac_power = function (adapter) local f = io.open('/sys/class/power_supply/' .. adapter .. '/online'):read() return string.find(f, '1') end local acpi_battery_is_charging = function (battery) local f = io.open('/sys/class/power_supply/' .. battery .. '/status') if f == nil then return false end return string.find(f:read(), 'Charging') end local acpi_battery_percent = function (battery) local f = io.open('/sys/class/power_supply/' .. battery .. '/charge_now') if f == nil then return 0 end local now = tonumber(f:read()) local full = tonumber(io.open('/sys/class/power_supply/' .. battery .. '/charge_full'):read()) return now / full end local battery_bolt_generate = function (width, height) local surface = cairo.ImageSurface(cairo.Format.A8, width, height) local cr = cairo.Context(surface) cr:new_path() cr:move_to(width * ( 0.0/19), height * ( 3.0/11)) cr:line_to(width * (11.0/19), height * (11.0/11)) cr:line_to(width * (11.0/19), height * ( 5.5/11)) cr:line_to(width * (19.0/19), height * ( 8.0/11)) cr:line_to(width * ( 8.0/19), height * ( 0.0/11)) cr:line_to(width * ( 8.0/19), height * ( 5.5/11)) cr:close_path() return cr:copy_path() end local battery_border_generate = function (args) local args = args or {} local surface = cairo.ImageSurface(cairo.Format.A8, args.width, args.height) local cr = cairo.Context(surface) local outside_width = args.width + (args.stroke_width * 2) local outside_height = args.height + (args.stroke_width * 2) cr:new_path() cr:move_to(0 , 0 ) cr:line_to(outside_width , 0 ) cr:line_to(outside_width , args.peg_top ) cr:line_to(outside_width + args.peg_width, args.peg_top ) cr:line_to(outside_width + args.peg_width, args.peg_top + args.peg_height) cr:line_to(outside_width , args.peg_top + args.peg_height) cr:line_to(outside_width , outside_height ) cr:line_to(0 , outside_height ) cr:rectangle(args.stroke_width, args.stroke_width, args.width, args.height); cr:close_path() return cr:copy_path() end local battery_text_generate = function (text, font) local surface = cairo.ImageSurface(cairo.Format.A8, 100, 100) local cr = cairo.Context(surface) cr:new_path() cr:select_font_face(font:get_family(), cairo.FontSlant.NORMAL, cairo.FontWeight.NORMAL) cr:set_font_size(font:get_size() / Pango.SCALE) cr:move_to(0, 0) cr:text_path(text) cr:close_path() return cr:copy_path() end local battery_text_draw = function (cr, args, text) local font = Pango.FontDescription.from_string(args.font) --font:set_size(10) cr:select_font_face(font:get_family(), cairo.FontSlant.NORMAL, cairo.FontWeight.NORMAL) cr:set_font_size(font:get_size() / Pango.SCALE) local extents = cr:text_extents(text) local text_x = (args.width / 2.0) - ((extents.width + (extents.x_bearing * 2)) / 2.0) local text_y = (args.height / 2.0) - ((extents.height + (extents.y_bearing * 2)) / 2.0) cr:translate(text_x, text_y) cr:append_path(battery_text_generate(text, font)) cr:translate(-text_x, -text_y) return true end local battery_fill_generate = function (width, height, percent) -- Sanity check on the percentage local percent = percent if percent > 1 then percent = 1 end if percent < 0 then percent = 0 end local surface = cairo.ImageSurface(cairo.Format.A8, width, height) local cr = cairo.Context(surface) cr:new_path() cr:rectangle(0, 0, round(width * percent), height) cr:close_path() return cr:copy_path() end local properties = { "battery", "adapter", "width", "height", "peg_top", "peg_height", "peg_width", "stroke_width", "font", "critical_level", "normal_color", "charging_color", "critical_color" } function assault.draw (assault, wibox, cr, width, height) local center_x = (width / 2.0) - ((data[assault].width + (data[assault].stroke_width * 2)) / 2.0) local center_y = (height / 2.0) - ((data[assault].height + (data[assault].stroke_width * 2)) / 2.0) cr:translate(center_x, center_y) cr:append_path(battery_border_generate({ width = data[assault].width, height = data[assault].height, stroke_width = data[assault].stroke_width, peg_top = data[assault].peg_top, peg_height = data[assault].peg_height, peg_width = data[assault].peg_width })) cr.fill_rule = "EVEN_ODD" local percent = acpi_battery_percent(data[assault].battery) local draw_color = color(data[assault].normal_color) if acpi_battery_is_charging(data[assault].battery) then draw_color = color(data[assault].charging_color) elseif percent <= data[assault].critical_level then draw_color = color(data[assault].critical_color) end -- Draw fill cr:translate(data[assault].stroke_width, data[assault].stroke_width) cr:append_path(battery_fill_generate(data[assault].width, data[assault].height, percent)) if acpi_is_on_ac_power(data[assault].adapter) then local bolt_x = (data[assault].width / 2.0) - (data[assault].bolt_width / 2.0) local bolt_y = (data[assault].height / 2.0) - (data[assault].bolt_height / 2.0) cr:translate( bolt_x, bolt_y) cr:append_path(battery_bolt_generate(data[assault].bolt_width, data[assault].bolt_height)) cr:translate(-bolt_x, -bolt_y) else local percentstr = string.format('%d%%', round(percent * 100)) battery_text_draw(cr, data[assault], percentstr) end cr:set_source(draw_color) cr:fill() end -- Build properties function for _, prop in ipairs(properties) do if not assault["set_" .. prop] then assault["set_" .. prop] = function(widget, value) data[widget][prop] = value widget:emit_signal("widget::updated") return widget end end end --- Create an assault widget function assault.new (args) local args = args or {} local battery = args.battery or 'BAT0' local adapter = args.adapter or 'ADP0' local stroke_width = args.stroke_width or 1 local width = args.width or 20 local height = args.height or 10 local bolt_width = args.bolt_width or 15 local bolt_height = args.bolt_height or 6 local peg_height = args.peg_height or (height / 3) local peg_width = args.peg_width or 2 local peg_top = args.peg_top or (((height + (stroke_width * 2)) / 2.0) - (peg_height / 2.0)) local font = args.font or beautiful.font local critical_level = args.critical_level or 0.18 local normal_color = args.normal_color or beautiful.fg_normal local critical_color = args.critical_color or "#ff0000" local charging_color = args.charging_color or "#ffffff" args.type = "imagebox" local widget = base.make_widget() data[widget] = { battery = battery, adapter = adapter, width = width, height = height, bolt_width = bolt_width, bolt_height = bolt_height, stroke_width = stroke_width, peg_top = peg_top, peg_height = peg_height, peg_width = peg_width, font = font, critical_level = critical_level, normal_color = normal_color, critical_color = critical_color, charging_color = charging_color } -- Set methods for _, prop in ipairs(properties) do widget["set_" .. prop] = assault["set_" .. prop] end widget.draw = assault.draw widget.fit = assault.fit return widget end function assault.mt:__call(...) return assault.new(...) end return setmetatable(assault, assault.mt)
Config = {} Config.EnableBlips = true Config.EnableJerryCans = true Config.EnableBuyableJerryCans = true -- Coming soon, currently useless Config.VehicleFailure = 10 -- At what fuel-percentage should the engine stop functioning properly? (Defualt: 10) Config.ShouldDisplayHud = true
local formatters = require("lvim.lsp.null-ls.formatters") formatters.setup({ { command = "isort", filetypes = { "python" } }, { command = "black", filetypes = { "python" } }, { command = "stylua", filetypes = { "lua" } }, { command = "shfmt", extra_args = { "-i", "2", "-ci" } }, { command = "prettier", filetypes = { "markdown", "css", "typescript", "javascript" } }, }) local linters = require("lvim.lsp.null-ls.linters") linters.setup({ { command = "eslint", filetypes = { "typescript", "javascript" } }, { command = "flake8", filetypes = { "python" } }, { command = "shellcheck", extra_args = { "--severity", "warning" } }, { command = "codespell" }, })
require 'inv_manager' require 'inv_common' require 'craft_manager' local config_path = shell.dir().."/server.json" local file = io.open(config_path,"r") local data = file:read("*all") local config = textutils.unserialiseJSON(data) file:close() file = io.open(shell.dir().."/recipes/minecraft.json","r") data = file:read("*all") --print(data) local recipes = textutils.unserialiseJSON(data) file:close() --print(textutils.serialize(recipes)) mgr = InvManager:new(config.overrides or {}) cmgr = CraftManager:new(mgr, recipes) --print(cmgr:pullOrCraftItemsExt("minecraft:wooden_pickaxe",10,"turtle_1",1)) --print(textutils.serialize(cmgr:scanItemsCraftable())) --print(textutils.serialize(mgr.itemDB)) rednet.open(getModemSide()) --rednet.host(PROTOCOL,os.getComputerLabel()) while true do evt = {os.pullEventRaw()} --print(textutils.serialize(evt)) if evt[1] == "rednet_message" then local msg = evt[3] if cmgr[msg[1]] then print("Calling CraftManager") rednet.send(evt[2],cmgr[msg[1]](cmgr,unpack(msg[2])),PROTOCOL) elseif mgr[msg[1]] then rednet.send(evt[2],mgr[msg[1]](mgr,unpack(msg[2])),PROTOCOL) else --print("Unknown command "..msg[1]) end elseif evt[1] == "terminate" then return end end --rednet.unhost(PROTOCOL) rednet.close(getModemSide())
local Class = require("lib.Class") local CC = Class:derive("CircleCollider") function CC:new(radius) self.r = radius end function CC:on_start() assert(self.entity.Transform ~=nil, "CircleCollider component requires a Transform component to exist in the attached entity!") self.tr = self.entity.Transform end -- function CC:update(dt) -- end function CC:draw() love.graphics.circle("line", self.tr.x, self.tr.y, self.r) end return CC
local utf8 = require("utf8") -- NOTE (rinqu): this is a basic implementation function utf8.sub(s, i, j) assert(type(s) == "number" or type(s) == "string", string.format("bad argument #1 to 'sub' (string expected, got %s)", type(s) ~= "nil" and type(s) or "no value")) assert(type(i) == "number" or type(tonumber(i)) == "number", string.format("bad argument #2 to 'sub' (number expected, got %s)", type(i) ~= "nil" and type(i) or "no value")) assert(type(j) == "nil" or type(j) == "number" or type(tonumber(j) == "number"), string.format("bad argument #3 to 'sub' (number expeted, got %s)", type(i))) s, i, j = tostring(s), tonumber(i), tonumber(j) local offset_i, offset_j local s_len = utf8.len(s) if (i > s_len) then offset_i = utf8.offset(s, s_len + 1) elseif (i < -s_len) then offset_i = 0 else offset_i = utf8.offset(s, i) end if (j ~= nil) then if (j > s_len or j == -1) then offset_j = utf8.offset(s, s_len + 1) - 1 elseif (j < -s_len) then offset_j = 0 else offset_j = utf8.offset(s, j + 1) - 1 end end return string.sub(s, offset_i, offset_j) end -- NOTE (rinqu): this is a basic implementation function utf8.find(s, pattern, index) assert(type(s) == "number" or type(s) == "string", string.format("bad argument #1 to 'find' (string expected, got %s)", type(s) ~= "nil" and type(s) or "no value")) assert(type(pattern) == "number" or type(pattern) == "string", string.format("bad argument #2 to 'find' (string expected, got %s)", type(pattern) ~= "nil" and type(pattern) or "no value")) s, pattern, index = tostring(s), tostring(pattern), index or 1 local function depattern(pattern) local tp = {"%%x", "%%.", "%%[", "%%]"} local td = {"x", ".", "[", "]"} local p = pattern for i, v in pairs(tp) do pattern = string.gsub(pattern, v, td[i]) end return pattern end local s_len = utf8.len(s) local p_len = string.len(depattern(pattern)) for i = index, s_len do local s_ = utf8.sub(s, i, i + p_len - 1) if (string.find(s_, pattern) ~= nil) then return i, i + p_len - 1 end end return nil end return utf8
return (function(self) local s = m(self, 'GetEffectiveScale') local b, l, w, h = m(self, 'GetRect') return b * s, l * s, w * s, h * s end)(...)
room_menu_toolbar= { name="room_menu_toolbar",type=0,typeName="View",time=0,report=0,x=0,y=0,width=1280,height=720,visible=1,fillParentWidth=1,fillParentHeight=1,nodeAlign=kAlignTopLeft, { name="shield",type=1,typeName="Image",time=92557376,report=0,x=0,y=0,width=2,height=2,visible=1,fillParentWidth=1,fillParentHeight=1,nodeAlign=kAlignCenter,file="games/common/blank.png" }, { name="menu_view",type=0,typeName="View",time=92557695,report=0,x=10,y=0,width=247,height=415,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignTopRight, { name="menu_btn",type=2,typeName="Button",time=92557784,report=0,x=10,y=0,width=110,height=88,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignTopRight,file="games/common/blank.png", { name="btn_img",type=1,typeName="Image",time=92557871,report=0,x=0,y=0,width=110,height=88,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignCenter,file="games/common/menuToolbar/more_down.png" } }, { name="more_view",type=0,typeName="View",time=92557955,report=0,x=0,y=-355,width=247,height=375,visible=0,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignTop, { name="bg",type=1,typeName="Image",time=92561857,report=0,x=0,y=0,width=247,height=375,visible=1,fillParentWidth=1,fillParentHeight=1,nodeAlign=kAlignCenter,file="games/common/menuToolbar/more_frame_bg.png" }, { name="split_line_1",type=1,typeName="Image",time=92558073,report=0,x=0,y=-75,width=204,height=2,visible=0,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignCenter,file="games/common/menuToolbar/more_split_line.png" }, { name="split_line_2",type=1,typeName="Image",time=92558104,report=0,x=0,y=0,width=204,height=2,visible=0,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignCenter,file="games/common/menuToolbar/more_split_line.png" }, { name="split_line_3",type=1,typeName="Image",time=107199614,report=0,x=0,y=75,width=204,height=2,visible=0,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignCenter,file="games/common/menuToolbar/more_split_line.png" }, { name="split_line_4",type=1,typeName="Image",time=112551269,report=0,x=0,y=150,width=204,height=2,visible=0,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignCenter,file="games/common/menuToolbar/more_split_line.png" }, { name="exit_btn",type=2,typeName="Button",time=92558166,report=0,x=0,y=0,width=210,height=77,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignTop,file="games/common/blank.png", { name="btn_img",type=1,typeName="Image",time=92558210,report=0,x=0,y=0,width=184,height=58,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignCenter,file="games/common/menuToolbar/exit_btn.png" } }, { name="setting_btn",type=2,typeName="Button",time=92558234,report=0,x=0,y=75,width=210,height=77,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignTop,file="games/common/blank.png", { name="btn_img",type=1,typeName="Image",time=92558235,report=0,x=0,y=0,width=184,height=58,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignCenter,file="games/common/menuToolbar/setting_btn.png" } }, { name="ai_btn",type=2,typeName="Button",time=92558236,report=0,x=0,y=150,width=210,height=77,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignTop,file="games/common/blank.png", { name="btn_img",type=1,typeName="Image",time=92558237,report=0,x=0,y=0,width=184,height=58,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignCenter,file="games/common/menuToolbar/ai_btn.png" } }, { name="shop_btn",type=2,typeName="Button",time=92558238,report=0,x=0,y=225,width=210,height=77,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignTop,file="games/common/blank.png", { name="btn_img",type=1,typeName="Image",time=92558239,report=0,x=0,y=0,width=184,height=58,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignCenter,file="games/common/menuToolbar/shop_btn.png" } }, { name="qukuan_btn",type=2,typeName="Button",time=112551230,report=0,x=0,y=300,width=210,height=77,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignTop,file="games/common/blank.png", { name="btn_img",type=1,typeName="Image",time=112551231,report=0,x=0,y=0,width=184,height=58,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignCenter,file="games/common/menuToolbar/qukuan_btn.png" } } } } } return room_menu_toolbar;
---------------------------------- -- Add your custom functions here: ---------------------------------- function AuxiliaryConsoleClose(...) debugFunc("AuxiliaryConsoleClose",...) local consoleHandle=... return sim.auxiliaryConsoleClose(consoleHandle) end function AuxiliaryConsoleOpen(...) debugFunc("AuxiliaryConsoleOpen",...) local title,maxLines,mode,position,size,textColor,backgroundColor=... for i=1,3,1 do textColor[i]=textColor[i]/255 backgroundColor[i]=backgroundColor[i]/255 end return sim.auxiliaryConsoleOpen(title,maxLines,mode,position,size,textColor,backgroundColor) end function AuxiliaryConsolePrint(...) debugFunc("AuxiliaryConsolePrint",...) local consoleHandle,text=... if #text==0 then text=nil end return sim.auxiliaryConsolePrint(consoleHandle,text) end function AuxiliaryConsoleShow(...) debugFunc("AuxiliaryConsoleShow",...) local consoleHandle,showState=... return sim.auxiliaryConsoleShow(consoleHandle,showState) end function AddDrawingObject_points(...) debugFunc("AddDrawingObject_points",...) local size,color,coords=... local adCol={0,0,0} local eCol={0,0,0} if color[1]>=0 then adCol={color[1]/255,color[2]/255,color[3]/255} else eCol={-color[1]/255,-color[2]/255,-color[3]/255} end local obj=sim.addDrawingObject(sim.drawing_points,size,0,-1,10000,adCol,nil,nil,eCol) for i=0,math.floor(#coords/3)-1,1 do sim.addDrawingObjectItem(obj,{coords[3*i+1],coords[3*i+2],coords[3*i+3]}) end return obj end function AddDrawingObject_spheres(...) debugFunc("AddDrawingObject_spheres",...) local size,color,coords=... local adCol={0,0,0} local eCol={0,0,0} if color[1]>=0 then adCol={color[1]/255,color[2]/255,color[3]/255} else eCol={-color[1]/255,-color[2]/255,-color[3]/255} end local obj=sim.addDrawingObject(sim.drawing_spherepoints,size,0,-1,10000,adCol,nil,nil,eCol) for i=0,math.floor(#coords/3)-1,1 do sim.addDrawingObjectItem(obj,{coords[3*i+1],coords[3*i+2],coords[3*i+3]}) end return obj end function AddDrawingObject_cubes(...) debugFunc("AddDrawingObject_cubes",...) local size,color,coords=... local adCol={0,0,0} local eCol={0,0,0} if color[1]>=0 then adCol={color[1]/255,color[2]/255,color[3]/255} else eCol={-color[1]/255,-color[2]/255,-color[3]/255} end local obj=sim.addDrawingObject(sim.drawing_cubepoints,size,0,-1,10000,adCol,nil,nil,eCol) for i=0,math.floor(#coords/3)-1,1 do sim.addDrawingObjectItem(obj,{coords[3*i+1],coords[3*i+2],coords[3*i+3],0,0,1}) end return obj end function AddDrawingObject_segments(...) debugFunc("AddDrawingObject_segments",...) local lineSize,color,segments=... local adCol={0,0,0} local eCol={0,0,0} if color[1]>=0 then adCol={color[1]/255,color[2]/255,color[3]/255} else eCol={-color[1]/255,-color[2]/255,-color[3]/255} end local obj=sim.addDrawingObject(sim.drawing_lines,lineSize,0,-1,10000,adCol,nil,nil,eCol) for i=0,math.floor(#segments/6)-1,1 do sim.addDrawingObjectItem(obj,{segments[6*i+1],segments[6*i+2],segments[6*i+3],segments[6*i+4],segments[6*i+5],segments[6*i+6]}) end return obj end function AddDrawingObject_triangles(...) debugFunc("AddDrawingObject_triangles",...) local color,triangles=... local adCol={0,0,0} local eCol={0,0,0} if color[1]>=0 then adCol={color[1]/255,color[2]/255,color[3]/255} else eCol={-color[1]/255,-color[2]/255,-color[3]/255} end local obj=sim.addDrawingObject(sim.drawing_triangles,0,0,-1,10000,adCol,nil,nil,eCol) for i=0,math.floor(#triangles/9)-1,1 do sim.addDrawingObjectItem(obj,{triangles[9*i+1],triangles[9*i+2],triangles[9*i+3],triangles[9*i+4],triangles[9*i+5],triangles[9*i+6],triangles[9*i+7],triangles[9*i+8],triangles[9*i+9]}) end return obj end function RemoveDrawingObject(...) debugFunc("RemoveDrawingObject",...) local handle=... return sim.removeDrawingObject(handle) end function CallScriptFunction(...) local funcAtObjName,scriptType,packedArg=... local arg=messagePack.unpack(packedArg) debugFunc("CallScriptFunction",funcAtObjName,scriptType,arg) if type(scriptType)=='string' then scriptType=evalStr(scriptType) end return sim.callScriptFunction(funcAtObjName,scriptType,arg) end function CheckCollision(...) debugFunc("CheckCollision",...) local entity1,entity2=... if type(entity2)=='string' then entity2=evalStr(entity2) end return sim.checkCollision(entity1,entity2) end function ReadCollision(...) debugFunc("ReadCollision",...) local handle=... return sim.readCollision(handle) end function CheckDistance(...) debugFunc("CheckDistance",...) local entity1,entity2,threshold=... if type(entity2)=='string' then entity2=evalStr(entity2) end local r,d=sim.checkDistance(entity1,entity2,threshold) return r,d[7],{d[1],d[2],d[3]},{d[4],d[5],d[6]} end function ReadDistance(...) debugFunc("ReadDistance",...) local handle=... return sim.readDistance(handle) end function CheckProximitySensor(...) debugFunc("CheckProximitySensor",...) local sensor,entity=... if type(entity)=='string' then entity=evalStr(entity) end return sim.checkProximitySensor(sensor,entity) end function ReadProximitySensor(...) debugFunc("ReadProximitySensor",...) local handle=... return sim.readProximitySensor(handle) end function CheckVisionSensor(...) debugFunc("CheckVisionSensor",...) local sensor,entity=... if type(entity2)=='string' then entity=evalStr(entity) end return sim.checkVisionSensor(sensor,entity) end function ReadVisionSensor(...) debugFunc("ReadVisionSensor",...) local handle=... return sim.readVisionSensor(handle) end function ReadForceSensor(...) debugFunc("ReadForceSensor",...) local handle=... return sim.readForceSensor(handle) end function BreakForceSensor(...) debugFunc("BreakForceSensor",...) local handle=... return sim.breakForceSensor(handle) end function ClearFloatSignal(...) debugFunc("ClearFloatSignal",...) local sig=... return sim.clearFloatSignal(sig) end function ClearIntegerSignal(...) debugFunc("ClearIntegerSignal",...) local sig=... return sim.clearIntegerSignal(sig) end function ClearStringSignal(...) debugFunc("ClearStringSignal",...) local sig=... return sim.clearStringSignal(sig) end function SetFloatSignal(...) debugFunc("SetFloatSignal",...) local sig,v=... return sim.setFloatSignal(sig,v) end function SetIntSignal(...) debugFunc("SetIntSignal",...) local sig,v=... return sim.setIntegerSignal(sig,v) end function SetStringSignal(...) debugFunc("SetStringSignal",...) local sig,v=... return sim.setStringSignal(sig,v) end function GetFloatSignal(...) debugFunc("GetFloatSignal",...) local sig=... return sim.getFloatSignal(sig) end function GetIntSignal(...) debugFunc("GetIntSignal",...) local sig=... return sim.getIntegerSignal(sig) end function GetStringSignal(...) debugFunc("GetStringSignal",...) local sig=... return sim.getStringSignal(sig) end function AddStatusbarMessage(...) debugFunc("AddStatusbarMessage",...) local txt=... return sim.addStatusbarMessage(txt) end function GetObjectPosition(...) debugFunc("GetObjectPosition",...) local objHandle,relObjHandle=... if type(relObjHandle)=='string' then relObjHandle=evalStr(relObjHandle) end return sim.getObjectPosition(objHandle,relObjHandle) end function GetObjectHandle(...) debugFunc("GetObjectHandle",...) local objName=... if string.find(objName,'#')==nil then objName=objName..'#' end return sim.getObjectHandle(objName) end function StartSimulation(...) debugFunc("StartSimulation",...) return sim.startSimulation() end function StopSimulation(...) debugFunc("StopSimulation",...) return sim.stopSimulation() end function PauseSimulation(...) debugFunc("PauseSimulation",...) return sim.pauseSimulation() end function GetVisionSensorImage(...) debugFunc("GetVisionSensorImage",...) local objHandle,greyScale=... if greyScale then objHandle=objHandle+sim.handleflag_greyscale end local img,x,y=sim.getVisionSensorCharImage(objHandle) return {x,y},img end function GetVisionSensorResolution(...) debugFunc("GetVisionSensorResolution",...) local objHandle=... return sim.getVisionSensorResolution(objHandle) end function GetVisionSensorDepthBuffer(...) debugFunc("GetVisionSensorDepthBuffer",...) local objHandle,toMeters,asByteArray=... if toMeters then objHandle=objHandle+sim.handleflag_depthbuffermeters end if asByteArray then objHandle=objHandle+sim.handleflag_codedstring end local buff=sim.getVisionSensorDepthBuffer(objHandle) return {x,y},buff end function SetVisionSensorImage(...) debugFunc("SetVisionSensorImage",...) local objHandle,greyScale,img=... if greyScale then objHandle=objHandle+sim.handleflag_greyscale end return sim.setVisionSensorCharImage(objHandle,img) end function SetObjectPosition(...) debugFunc("SetObjectPosition",...) local objHandle,relObjHandle,pos=... if type(relObjHandle)=='string' then relObjHandle=evalStr(relObjHandle) end return sim.setObjectPosition(objHandle,relObjHandle,pos) end function GetObjectOrientation(...) debugFunc("GetObjectOrientation",...) local objHandle,relObjHandle=... if type(relObjHandle)=='string' then relObjHandle=evalStr(relObjHandle) end return sim.getObjectOrientation(objHandle,relObjHandle) end function SetObjectOrientation(...) debugFunc("SetObjectOrientation",...) local objHandle,relObjHandle,euler=... if type(relObjHandle)=='string' then relObjHandle=evalStr(relObjHandle) end return sim.setObjectOrientation(objHandle,relObjHandle,euler) end function GetObjectQuaternion(...) debugFunc("GetObjectQuaternion",...) local objHandle,relObjHandle=... if type(relObjHandle)=='string' then relObjHandle=evalStr(relObjHandle) end return sim.getObjectQuaternion(objHandle,relObjHandle) end function SetObjectQuaternion(...) debugFunc("SetObjectQuaternion",...) local objHandle,relObjHandle,quat=... if type(relObjHandle)=='string' then relObjHandle=evalStr(relObjHandle) end return sim.setObjectQuaternion(objHandle,relObjHandle,quat) end function GetObjectPose(...) debugFunc("GetObjectPose",...) local objHandle,relObjHandle=... if type(relObjHandle)=='string' then relObjHandle=evalStr(relObjHandle) end local pose=sim.getObjectPosition(objHandle,relObjHandle) local quat=sim.getObjectQuaternion(objHandle,relObjHandle) pose[4]=quat[1] pose[5]=quat[2] pose[6]=quat[3] pose[7]=quat[4] return pose end function SetObjectPose(...) debugFunc("SetObjectPose",...) local objHandle,relObjHandle,pose=... if type(relObjHandle)=='string' then relObjHandle=evalStr(relObjHandle) end sim.setObjectPosition(objHandle,relObjHandle,pose) sim.setObjectQuaternion(objHandle,relObjHandle,{pose[4],pose[5],pose[6],pose[7]}) return 1 end function GetObjectMatrix(...) debugFunc("GetObjectMatrix",...) local objHandle,relObjHandle=... if type(relObjHandle)=='string' then relObjHandle=evalStr(relObjHandle) end return sim.getObjectMatrix(objHandle,relObjHandle) end function SetObjectMatrix(...) debugFunc("SetObjectMatrix",...) local objHandle,relObjHandle,matr=... if type(relObjHandle)=='string' then relObjHandle=evalStr(relObjHandle) end return sim.setObjectMatrix(objHandle,relObjHandle,matr) end function CopyPasteObjects(...) debugFunc("CopyPasteObjects",...) local objHandles,options=... return sim.copyPasteObjects(objHandles,options) end function RemoveObjects(...) debugFunc("RemoveObjects",...) local objHandles,options=... local allObjs1=sim.getObjectsInTree(sim.handle_scene,sim.handle_all,0) if sim.boolAnd32(options,2)>0 then sim.removeObject(sim.handle_all) else if sim.boolAnd32(options,1)>0 then for i=1,#objHandles,1 do local h=objHandles[i] if sim.isHandleValid(h)>0 then local mp=sim.getModelProperty(h) if sim.boolAnd32(mp,sim.modelproperty_not_model)>0 then sim.removeObject(objHandles[i]) else sim.removeModel(objHandles[i]) end end end else for i=1,#objHandles,1 do sim.removeObject(objHandles[i]) end end end local allObjs2=sim.getObjectsInTree(sim.handle_scene,sim.handle_all,0) return #allObjs1-#allObjs2 end function CloseScene(...) debugFunc("CloseScene",...) return sim.closeScene() end function SetStringParameter(...) debugFunc("SetStringParameter",...) local paramId,val=... if type(paramId)=='string' then paramId=evalStr(paramId) end return sim.setStringParameter(paramId,val) end function GetStringParameter(...) debugFunc("GetStringParameter",...) local paramId=... if type(paramId)=='string' then paramId=evalStr(paramId) end return sim.getStringParameter(paramId) end function SetFloatParameter(...) debugFunc("SetFloatParameter",...) local paramId,val=... if type(paramId)=='string' then paramId=evalStr(paramId) end return sim.setFloatParameter(paramId,val) end function GetFloatParameter(...) debugFunc("GetFloatParameter",...) local paramId=... if type(paramId)=='string' then paramId=evalStr(paramId) end return sim.getFloatParameter(paramId) end function SetIntParameter(...) debugFunc("SetIntParameter",...) local paramId,val=... if type(paramId)=='string' then paramId=evalStr(paramId) end return sim.setInt32Parameter(paramId,val) end function GetIntParameter(...) debugFunc("GetIntParameter",...) local paramId=... if type(paramId)=='string' then paramId=evalStr(paramId) end return sim.getInt32Parameter(paramId) end function SetBoolParameter(...) debugFunc("SetBoolParameter",...) local paramId,val=... if type(paramId)=='string' then paramId=evalStr(paramId) end return sim.setBoolParameter(paramId,val) end function GetBoolParameter(...) debugFunc("GetBoolParameter",...) local paramId=... if type(paramId)=='string' then paramId=evalStr(paramId) end return sim.getBoolParameter(paramId) end function SetArrayParameter(...) debugFunc("SetArrayParameter",...) local paramId,val=... if type(paramId)=='string' then paramId=evalStr(paramId) end return sim.setArrayParameter(paramId,val) end function GetArrayParameter(...) debugFunc("GetArrayParameter",...) local paramId=... if type(paramId)=='string' then paramId=evalStr(paramId) end return sim.getArrayParameter(paramId) end function DisplayDialog(...) debugFunc("DisplayDialog",...) local titleText,mainText,dlgType,initText=... if type(dlgType)=='string' then dlgType=evalStr(dlgType) end return sim.displayDialog(titleText,mainText,dlgType,initText) end function GetDialogResult(...) debugFunc("GetDialogResult",...) local dlgHandle=... return tostring(sim.getDialogResult(dlgHandle)) end function GetDialogInput(...) debugFunc("GetDialogInput",...) local dlgHandle=... return sim.getDialogInput(dlgHandle) end function EndDialog(...) debugFunc("EndDialog",...) local dlgHandle=... return sim.endDialog(dlgHandle) end function ExecuteScriptString(...) debugFunc("ExecuteScriptString",...) local str=... return evalStr(str) end function GetCollectionHandle(...) debugFunc("GetCollectionHandle",...) local objName=... if string.find(objName,'#')==nil then objName=objName..'#' end return sim.getCollectionHandle(objName..'#') end function GetCollisionHandle(...) debugFunc("GetCollisionHandle",...) local name=... if string.find(name,'#')==nil then name=name..'#' end return sim.getCollisionHandle(name) end function GetDistanceHandle(...) debugFunc("GetDistanceHandle",...) local name=... if string.find(name,'#')==nil then name=name..'#' end return sim.getDistanceHandle(name) end function GetJointForce(...) debugFunc("GetJointForce",...) local handle=... return sim.getJointForce(handle) end function SetJointForce(...) debugFunc("SetJointForce",...) local handle,f=... return sim.setJointForce(handle,f) end function GetJointPosition(...) debugFunc("GetJointPosition",...) local handle=... return sim.getJointPosition(handle) end function SetJointPosition(...) debugFunc("SetJointPosition",...) local handle,p=... return sim.setJointPosition(handle,p) end function GetJointTargetPosition(...) debugFunc("GetJointTargetPosition",...) local handle=... return sim.getJointTargetPosition(handle) end function SetJointTargetPosition(...) debugFunc("SetJointTargetPosition",...) local handle,tp=... return sim.setJointTargetPosition(handle,tp) end function GetJointTargetVelocity(...) debugFunc("GetJointTargetVelocity",...) local handle=... return sim.getJointTargetVelocity(handle) end function SetJointTargetVelocity(...) debugFunc("SetJointTargetVelocity",...) local handle,tv=... return sim.setJointTargetVelocity(handle,tv) end function GetObjectChild(...) debugFunc("GetObjectChild",...) local handle,index=... return sim.getObjectChild(handle,index) end function GetObjectParent(...) debugFunc("GetObjectParent",...) local handle=... return sim.getObjectParent(handle) end function SetObjectParent(...) debugFunc("SetObjectParent",...) local handle,parentHandle,assembly,keepInPlace=... if assembly then handle=handle+sim.handleflag_assembly end return sim.setObjectParent(handle,parentHandle,keepInPlace) end function GetObjectsInTree(...) debugFunc("GetObjectsInTree",...) local treeBase,objType,options=... if type(treeBase)=='string' then treeBase=evalStr(treeBase) end if type(objType)=='string' then objType=evalStr(objType) end return sim.getObjectsInTree(treeBase,objType,options) end function GetObjectName(...) debugFunc("GetObjectName",...) local handle,altName=... if altName then handle=handle+sim.handleflag_altname end return sim.getObjectName(handle) end function GetObjectFloatParameter(...) debugFunc("GetObjectFloatParameter",...) local handle,paramId=... if type(paramId)=='string' then paramId=evalStr(paramId) end local r,retV=sim.getObjectFloatParameter(handle,paramId) return retV end function GetObjectIntParameter(...) debugFunc("GetObjectIntParameter",...) local handle,paramId=... if type(paramId)=='string' then paramId=evalStr(paramId) end local r,retV=sim.getObjectInt32Parameter(handle,paramId) return retV end function GetObjectStringParameter(...) debugFunc("GetObjectStringParameter",...) local handle,paramId=... if type(paramId)=='string' then paramId=evalStr(paramId) end local r,retV=sim.getObjectStringParameter(handle,paramId) return retV end function SetObjectFloatParameter(...) debugFunc("SetObjectFloatParameter",...) local handle,paramId,v=... if type(paramId)=='string' then paramId=evalStr(paramId) end return sim.setObjectFloatParameter(handle,paramId,v) end function SetObjectIntParameter(...) debugFunc("SetObjectIntParameter",...) local handle,paramId,v=... if type(paramId)=='string' then paramId=evalStr(paramId) end return sim.setObjectInt32Parameter(handle,paramId,v) end function SetObjectStringParameter(...) debugFunc("SetObjectStringParameter",...) local handle,paramId,v=... if type(paramId)=='string' then paramId=evalStr(paramId) end return sim.setObjectStringParameter(handle,paramId,v) end function GetSimulationTime(...) debugFunc("GetSimulationTime",...) return sim.getSimulationTime() end function GetSimulationTimeStep(...) debugFunc("GetSimulationTimeStep",...) return sim.getSimulationTimeStep() end function GetServerTimeInMs(...) debugFunc("GetServerTimeInMs",...) return sim.getSystemTimeInMs(-2) end function GetSimulationState(...) debugFunc("GetSimulationState",...) local s=sim.getSimulationState() if s~=sim.simulation_stopped and s~=sim.simulation_paused then s=sim.simulation_advancing end return s end function EvaluateToInt(...) debugFunc("EvaluateToInt",...) local str=... return evalStr(str) end function EvaluateToStr(...) debugFunc("EvaluateToStr",...) local str=... return evalStr(str) end function GetObjects(...) debugFunc("GetObjects",...) local objType=... local retVal={} local i=0 local h=sim.getObjects(i,objType) while h>=0 do retVal[#retVal+1]=handle h=sim.getObjects(i,objType) end return retVal end function CreateDummy(...) debugFunc("CreateDummy",...) local cols={0,0,0,0,0,0,0.5,0.5,0.5,0,0,0} local size,color=... if color[1]>=0 then cols[1]=color[1]/255 cols[2]=color[2]/255 cols[3]=color[3]/255 else cols[10]=-color[1]/255 cols[11]=-color[2]/255 cols[12]=-color[3]/255 end return sim.createDummy(size,cols) end function GetObjectSelection(...) debugFunc("GetObjectSelection",...) local t=sim.getObjectSelection() if t==nil then t={} end return t end function SetObjectSelection(...) debugFunc("SetObjectSelection",...) local sel=... sim.removeObjectFromSelection(sim.handle_all,-1); return sim.addObjectToSelection(sel) end function GetObjectVelocity(...) debugFunc("GetObjectVelocity",...) local handle=... return sim.getObjectVelocity(handle+sim.handleflag_axis) end function LoadModel(...) debugFunc("LoadModel",...) local filename=... local s=sim.getObjectSelection() local h=sim.loadModel(filename) sim.removeObjectFromSelection(sim.handle_all,-1); if s then sim.addObjectToSelection(s) end return h end function LoadScene(...) debugFunc("LoadScene",...) local filename=... return sim.loadScene(filename) end ----------------------------------------- ----------------------------------------- function evalStr(str) local f=loadstring('return ('..str..')') return f() end function timeStr() local t if sim.getSimulationState()==sim.simulation_stopped then t=os.date('*t') t=string.format('[%02d:%02d:%02d] ',t.hour,t.min,t.sec) else local st=sim.getSimulationTime() t=os.date('*t',3600*23+st) t=string.format('[%02d:%02d:%02d.%02d] ',t.hour,t.min,t.sec,st%1) end return t end function Synchronous(...) debugFunc("Synchronous",...) local enable=... if enable and not syncMode then syncModeWait=true end syncMode=enable return true end function SynchronousTrigger(...) debugFunc("SynchronousTrigger",...) syncModeWait=false return true end function GetSimulationStepDone(...) -- debugFunc("GetSimulationStepDone",...) local retVal={} retVal.simulationTime=sim.getSimulationTime() retVal.simulationState=tostring(sim.getSimulationState()) retVal.simulationTimeStep=sim.getSimulationTimeStep() return retVal end function GetSimulationStepStarted(...) -- debugFunc("GetSimulationStepStarted",...) local retVal={} retVal.simulationTime=sim.getSimulationTime() retVal.simulationState=tostring(sim.getSimulationState()) retVal.simulationTimeStep=sim.getSimulationTimeStep() return retVal end function DisconnectClient(...) debugFunc("DisconnectClient",...) local clientId=... local val=allPublishers[clientId] if val then for topic,value in pairs(val) do if value.handle~=defaultPublisher then simB0.socketCleanup(value.handle) simB0.publisherDestroy(value.handle) end end allPublishers[clientId]=nil end local val=dedicatedSubscribers[clientId] if val then for topic,value in pairs(val) do simB0.socketCleanup(value.handle) simB0.subscriberDestroy(value.handle) end dedicatedSubscribers[clientId]=nil end allClients[clientId]=nil end function Ping(...) debugFunc("Ping",...) return 'Pong' end ----------------------------------------- ----------------------------------------- function debugFunc(funcName,...) lastFuncName=funcName if modelData and modelData.debugLevel>=3 then local arg=getAsString(...) if arg=='' then arg='none' end local a=timeStr()..b0RemoteApiServerNameDebug..": calling function '"..funcName.."' with following arguments: "..arg a="<font color='#4B4'>"..a.."</font>@html" sim.addStatusbarMessage(a) end end function PCALL(func,printErrors,...) local res,a,b,c,d,e,f,g,h,i,j,k=pcall(func,...) if modelData and modelData.debugLevel>=1 and (not res) and printErrors then local a=string.format(timeStr()..b0RemoteApiServerNameDebug..": error while calling function '%s': %s",lastFuncName,a) a="<font color='#a00'>"..a.."</font>@html" sim.addStatusbarMessage(a) end return res,a,b,c,d,e,f,g,h,i,j,k -- res,val1,val2,val3,val4,val5,val6,val7,val8=pcall(func,...) -- if val1==nil then val1='__##LUANIL##__' end -- make sure we have 2 ret arguments --- val=func(...) --- print(res,val) -- return res,val1,val2,val3,val4,val5,val6,val7,val8 end function PACKPUBMSG(topic,res,...) local a={...} local b={topic,{res}} for i=1,#a,1 do b[2][#b[2]+1]=a[i] end return messagePack.pack(b) end function PACKSERVMSG(...) local a={...} return messagePack.pack(a) end function createNode() if not b0Node then if modelData.debugLevel>=1 then local a=string.format(timeStr()..b0RemoteApiServerNameDebug..": creating BlueZero node '%s' and associated publisher, subscriber and service server (on channel '%s')",modelData.nodeName,modelData.channelName) a="<font color='#070'>"..a.."</font>@html" sim.addStatusbarMessage(a) end modelData.currentNodeName=modelData.nodeName modelData.currentChannelName=modelData.channelName if not initStg then local xml = [[ <ui closeable="false" resizable="false" title="BlueZero" modal="true"> <label text="Looking for BlueZero resolver..." style="* {font-size: 20px; font-weight: bold; margin-left: 20px; margin-right: 20px;}"/> <label text="This can take several seconds." style="* {font-size: 20px; font-weight: bold; margin-left: 20px; margin-right: 20px;}"/> </ui> ]] local ui=simUI.create(xml) if not simB0.pingResolver() then sim.addStatusbarMessage("<font color='#070'>B0 Remote API: B0 resolver was not detected. Launching it from here...</font>@html") sim.launchExecutable('b0_resolver','',1) end simUI.destroy(ui) if simB0.pingResolver() then messagePack=require('messagePack') if modelData.packStrAsBin then messagePack.set_string('binary') else messagePack.set_string('string') end initStg=1 else initStg=0 sim.addStatusbarMessage("<font color='#070'>"..timeStr()..b0RemoteApiServerNameDebug..": B0 resolver could not be launched.".."</font>@html") end end if initStg==1 then b0Node=simB0.nodeCreate(modelData.nodeName) serviceServer=simB0.serviceServerCreate(b0Node,modelData.channelName..'SerX','serviceServer_callback') defaultPublisher=simB0.publisherCreate(b0Node,modelData.channelName..'PubX') defaultSubscriber=simB0.subscriberCreate(b0Node,modelData.channelName..'SubX','defaultSubscriber_callback') dedicatedSubscribers={} -- key is clientId, value is a map with: key is subscriberTopic, value is another map: handle allPublishers={} -- key is clientId, value is a map with: key is publisherTopic, value is another map: pubHandle, cmds=listOfRegisteredCmds simB0.nodeInit(b0Node) allClients={} allSubscribers={} end end end function destroyNode() if b0Node then if modelData.debugLevel>=1 then local a=string.format(timeStr()..b0RemoteApiServerNameDebug..": destroying BlueZero node '%s' and associated publisher, subscriber and service server (on channel '%s')",modelData.currentNodeName,modelData.currentChannelName) a="<font color='#070'>"..a.."</font>@html" sim.addStatusbarMessage(a) end modelData.currentNodeName=nil modelData.currentChannelName=nil local clients={} for key,val in pairs(allClients) do clients[#clients+1]=key end for i=1,#clients,1 do DisconnectClient(clients[i]) end --simB0.shutdown(b0Node) simB0.nodeCleanup(b0Node) simB0.publisherDestroy(defaultPublisher) simB0.subscriberDestroy(defaultSubscriber) simB0.serviceServerDestroy(serviceServer) simB0.nodeDestroy(b0Node) end allPublishers={} dedicatedSubscribers={} allClients={} b0Node=nil end function sendAndSpin(calledMoment) local retVal=true local publishSimulationStepFinished_ClientAnddata={} local publishSimulationStepStarted_ClientAnddata={} local publisherCntForClients={} if b0Node then -- Handle subscriber(s) and service calls: simB0.nodeSpinOnce(b0Node) for clientId,val in pairs(dedicatedSubscribers) do for topic,value in pairs(val) do local msg='' while simB0.socketPoll(value.handle) do msg=simB0.socketRead(value.handle) if not value.dropMessages then dedicatedSubscriber_callback(msg) end end if value.dropMessages and #msg>0 then dedicatedSubscriber_callback(msg) end -- simB0.socketSpinOnce(value.handle) end end -- Handle publishing: local clientsToRemove={} for clientId,val in pairs(allPublishers) do if not hasClientReachedMaxInactivityTime(clientId) then -- Ok, that client appears to be still active for topic,value in pairs(val) do local publisher=value.handle local triggerInterval=value.triggerInterval local cmdList=value.cmds for i=1,#cmdList,1 do local cmd=cmdList[i] if triggerInterval==0 or calledMoment==0 or (nextSimulationStepUnderway and not (sim.getSimulationState()==sim.simulation_paused)) or cmd.func=='GetSimulationStepStarted' then cmd.triggerIntervalCnt=cmd.triggerIntervalCnt-1 if cmd.triggerIntervalCnt<=0 then cmd.triggerIntervalCnt=triggerInterval -- local result,retVal=PCALL(_G[cmd.func],unpack(cmd.args)) -- retVal=messagePack.pack({topic,{result,retVal}}) local retVal=PACKPUBMSG(topic,PCALL(_G[cmd.func],true,unpack(cmd.args))) if cmd.func=='GetSimulationStepDone' then publishSimulationStepFinished_ClientAnddata[clientId]={publisher,retVal} -- publish this one last! (further down) else if cmd.func=='GetSimulationStepStarted' then publishSimulationStepStarted_ClientAnddata[clientId]={publisher,retVal} -- publish this one last! (further down) else publish(clientId,publisher,cmd.func,retVal,publisherCntForClients) end end end end end end else clientsToRemove[#clientsToRemove+1]=clientId end end -- Remove publishers of inactive clients: for i=1,#clientsToRemove,1 do local clientId=clientsToRemove[i] DisconnectClient(clientId) if modelData.debugLevel>=1 then local a=string.format(timeStr()..b0RemoteApiServerNameDebug..": destroyed all streaming functions for client '%s' after detection of inactivity",clientId) a="<font color='#070'>"..a.."</font>@html" sim.addStatusbarMessage(a) end end end if calledMoment==1 then -- i.e. before main script if nextSimulationStepUnderway then -- Handle publishing of simulationStepFinished here (special): for key,value in pairs(publishSimulationStepFinished_ClientAnddata) do debugFunc('GetSimulationStepDone',nil) publish(key,value[1],'GetSimulationStepDone',value[2],publisherCntForClients) end end if syncMode then if syncModeWait then retVal=false else syncModeWait=true end end if retVal then nextSimulationStepUnderway=true -- Handle publishing of simulationStepStarted here (special): for key,value in pairs(publishSimulationStepStarted_ClientAnddata) do debugFunc('GetSimulationStepStarted',nil) publish(key,value[1],'GetSimulationStepStarted',value[2],publisherCntForClients) end else nextSimulationStepUnderway=false end end for publisher,client in pairs(publisherCntForClients) do local append if publisher==defaultPublisher then append=' (default publisher)' else append=' (dedicated publisher)' end local msgCnt=0 local clientCnt=0 local funcs='' for key,value in pairs(client) do clientCnt=clientCnt+1 msgCnt=msgCnt+value.cnt if funcs=='' then funcs=value.funcs else funcs=funcs..'|'..value.funcs end end if msgCnt>0 and modelData and modelData.debugLevel>=2 then local a=string.format(timeStr()..b0RemoteApiServerNameDebug..": published %i message(s) to %i client(s): %s",msgCnt,clientCnt,funcs) a="<font color='#070'>"..a..append.."</font>@html" sim.addStatusbarMessage(a) end end return retVal end function publish(clientId,publisher,func,retVal,publisherCntForClients) simB0.publisherPublish(publisher,retVal) if not publisherCntForClients[publisher] then publisherCntForClients[publisher]={} end if not publisherCntForClients[publisher][clientId] then publisherCntForClients[publisher][clientId]={cnt=1,funcs=func} else publisherCntForClients[publisher][clientId].cnt=publisherCntForClients[publisher][clientId].cnt+1 publisherCntForClients[publisher][clientId].funcs=publisherCntForClients[publisher][clientId].funcs..'|'..func end end function updateClientLastActivityTime(clientId) if not allClients[clientId] then allClients[clientId]={maxInactivityTimeMs=60*1000} end local val=allClients[clientId] val.lastActivityTimeMs=sim.getSystemTimeInMs(-1) end function setClientMaxInactivityTime(clientId,maxInactivityTime) local val=allClients[clientId] val.maxInactivityTimeMs=maxInactivityTime*1000 end function hasClientReachedMaxInactivityTime(clientId) local val=allClients[clientId] return sim.getSystemTimeInMs(val.lastActivityTimeMs)>val.maxInactivityTimeMs end function serviceServer_callback(receiveMsg) local retVal=PACKSERVMSG(true) -- local result=true -- local data=true receiveMsg=messagePack.unpack(receiveMsg) local funcName=receiveMsg[1][1] local clientId=receiveMsg[1][2] local topic=receiveMsg[1][3] local task=receiveMsg[1][4] -- 0=normal serviceCall, 1=received on default subscriber, 2=register streaming cmd on default publisher, 3=received on dedicated subscriber, 4=register streaming cmd on dedicated publisher local funcArgs=receiveMsg[2] updateClientLastActivityTime(clientId) if not handlePublisherSetupFunctions(task,funcName,clientId,topic,funcArgs) then if funcName=='createSubscriber' then local subscr=simB0.subscriberCreate(b0Node,funcArgs[1],'dedicatedSubscriber_callback',false,true) -- simB0.socketSetOption(subscr,'conflate',1) simB0.socketInit(subscr); if not dedicatedSubscribers[clientId] then dedicatedSubscribers[clientId]={} end dedicatedSubscribers[clientId][funcArgs[1]]={handle=subscr,dropMessages=funcArgs[2]} if modelData.debugLevel>=1 then local a=string.format(timeStr()..b0RemoteApiServerNameDebug..": creating dedicated subscriber for client '%s' with topic '%s'",clientId,funcArgs[1]) a="<font color='#070'>"..a.."</font>@html" sim.addStatusbarMessage(a) end elseif funcName=='inactivityTolerance' then setClientMaxInactivityTime(clientId,funcArgs[1]) if modelData.debugLevel>=2 then local a=string.format(timeStr()..b0RemoteApiServerNameDebug..": setting max. inactivity tolerance for client '%s'",clientId) a="<font color='#070'>"..a.."</font>@html" sim.addStatusbarMessage(a) end else retVal=PACKSERVMSG(PCALL(_G[funcName],true,unpack(funcArgs))) -- result,data=PCALL(_G[funcName],unpack(funcArgs)) if modelData.debugLevel>=2 then local a=string.format(timeStr()..b0RemoteApiServerNameDebug..": called function for client '%s': %s (service call)",clientId,receiveMsg[1][1]) a="<font color='#070'>"..a.."</font>@html" sim.addStatusbarMessage(a) end end end -- return messagePack.pack({result,data}) return retVal end function handlePublisherSetupFunctions(task,funcName,clientId,topic,funcArgs) if task==2 then -- We want to register a command to be constantly executed on the default publisher: if not allPublishers[clientId] then allPublishers[clientId]={} end if not allPublishers[clientId][topic] then allPublishers[clientId][topic]={handle=defaultPublisher,cmds={},triggerInterval=1} end local val=allPublishers[clientId][topic] val.cmds[#val.cmds+1]={func=funcName,args=funcArgs,triggerIntervalCnt=1} if modelData.debugLevel>=1 then local a=string.format(timeStr()..b0RemoteApiServerNameDebug..": registering streaming function '%s' for client '%s' on topic '%s' (default publisher)",funcName,clientId,topic) a="<font color='#070'>"..a.."</font>@html" sim.addStatusbarMessage(a) end elseif task==4 then -- We want to register a command to be constantly executed on a dedicated publisher: if allPublishers[clientId] and allPublishers[clientId][topic] then local val=allPublishers[clientId][topic] allCmds=val.cmds allCmds[#allCmds+1]={func=funcName,args=funcArgs,triggerIntervalCnt=1} if modelData.debugLevel>=1 then local a=string.format(timeStr()..b0RemoteApiServerNameDebug..": registering streaming function '%s' for client '%s' on topic '%s' (dedicated publisher)",funcName,clientId,topic) a="<font color='#070'>"..a.."</font>@html" sim.addStatusbarMessage(a) end end else if funcName=='createPublisher' then local pub=simB0.publisherCreate(b0Node,funcArgs[1],false,true) -- simB0.socketSetOption(pub,'conflate',1) simB0.socketInit(pub); if not allPublishers[clientId] then allPublishers[clientId]={} end local targetTopic=funcArgs[1] local trigInterv=funcArgs[2] allPublishers[clientId][targetTopic]={handle=pub,cmds={},triggerInterval=trigInterv} if modelData.debugLevel>=1 then local a=string.format(timeStr()..b0RemoteApiServerNameDebug..": creating dedicated publisher for client '%s' with topic '%s'",clientId,targetTopic) a="<font color='#070'>"..a.."</font>@html" sim.addStatusbarMessage(a) end return true elseif funcName=='setDefaultPublisherPubInterval' then if not allPublishers[clientId] then allPublishers[clientId]={} end local targetTopic=funcArgs[1] local trigInterv=funcArgs[2] if not allPublishers[clientId][targetTopic] then allPublishers[clientId][targetTopic]={handle=defaultPublisher,cmds={},triggerInterval=trigInterv} end if modelData.debugLevel>=2 then local a=string.format(timeStr()..b0RemoteApiServerNameDebug..": setting default publisher interval for client '%s' with topic '%s'",clientId,targetTopic) a="<font color='#070'>"..a.."</font>@html" sim.addStatusbarMessage(a) end return true elseif funcName=='stopDefaultPublisher' or funcName=='stopPublisher' then local topic=funcArgs[1] if allPublishers[clientId] then if allPublishers[clientId][topic] then local nn='default' if funcName=='stopPublisher' then simB0.socketCleanup(allPublishers[clientId][topic].handle) simB0.publisherDestroy(allPublishers[clientId][topic].handle) nn='dedicated' end local cmds=allPublishers[clientId][topic].cmds allPublishers[clientId][topic]=nil if modelData.debugLevel>=1 then local cm='' if #cmds>0 then cm='. Following streaming functions on that topic will be unregistered:' for i=1,#cmds,1 do if i==1 then cm=cm..' ' else cm=cm..', ' end cm=cm..cmds[i].func end end local a=string.format(timeStr()..b0RemoteApiServerNameDebug..": stopping %s publisher for client '%s' with topic '%s'. All Streaming functions on that topic will be unregistered%s",nn,clientId,topic,cm) a="<font color='#070'>"..a.."</font>@html" sim.addStatusbarMessage(a) end end end return true elseif funcName=='stopSubscriber' then local topic=funcArgs[1] if dedicatedSubscribers[clientId] then if dedicatedSubscribers[clientId][topic] then simB0.socketCleanup(dedicatedSubscribers[clientId][topic].handle) simB0.subscriberDestroy(dedicatedSubscribers[clientId][topic].handle) dedicatedSubscribers[clientId][topic]=nil if modelData.debugLevel>=1 then local a=string.format(timeStr()..b0RemoteApiServerNameDebug..": stopping dedicated subscriber for client '%s' with topic '%s'",clientId,topic) a="<font color='#070'>"..a.."</font>@html" sim.addStatusbarMessage(a) end end end return true end end return false end function defaultSubscriber_callback(msg) msg=messagePack.unpack(msg) local funcName=msg[1][1] local clientId=msg[1][2] local task=msg[1][4] -- 0=normal serviceCall, 1=received on default subscriber, 2=register streaming cmd on default publisher, 3=received on dedicated subscriber, 4=register streaming cmd on dedicated publisher local topic=msg[1][3] local funcArgs=msg[2] updateClientLastActivityTime(clientId) -- We simply want to execute the function and forget (no return) if not handlePublisherSetupFunctions(task,funcName,clientId,topic,funcArgs) then PCALL(_G[funcName],true,unpack(funcArgs)) if modelData.debugLevel>=2 then local a=string.format(timeStr()..b0RemoteApiServerNameDebug..": called function for client '%s': %s (default subscriber)",clientId,funcName) a="<font color='#070'>"..a.."</font>@html" sim.addStatusbarMessage(a) end end end function dedicatedSubscriber_callback(msg) msg=messagePack.unpack(msg) local funcName=msg[1][1] local clientId=msg[1][2] local topic=msg[1][3] local funcArgs=msg[2] updateClientLastActivityTime(clientId) -- We simply want to execute the function and forget (no return) PCALL(_G[funcName],true,unpack(funcArgs)) if modelData.debugLevel>=2 then local a=string.format(timeStr()..b0RemoteApiServerNameDebug..": called function for client '%s': %s (dedicated subscriber)",clientId,funcName) a="<font color='#070'>"..a.."</font>@html" sim.addStatusbarMessage(a) end end function onConfigNodeNameChanged(ui,id,newVal) if #newVal>2 then local newValue='' for i=1,#newVal,1 do local v=newVal:sub(i,i) if (v>='0' and v<='9') or (v>='a' and v<='z') or (v>='A' and v<='Z') or v=='_' or v=='-' then newValue=newValue..v else newValue=newValue..'_' end end configUiData.nodeName=newValue end simUI.setEditValue(configUiData.dlg,1,configUiData.nodeName) end function onConfigChannelNameChanged(ui,id,newVal) if #newVal>2 then local newValue='' for i=1,#newVal,1 do local v=newVal:sub(i,i) if (v>='0' and v<='9') or (v>='a' and v<='z') or (v>='A' and v<='Z') or v=='_' or v=='-' then newValue=newValue..v else newValue=newValue..'_' end end configUiData.channelName=newValue end simUI.setEditValue(configUiData.dlg,2,configUiData.channelName) end function onDebugLevelChanged(uiHandle,id,newIndex) configUiData.debugLevel=newIndex modelData.debugLevel=newIndex sim.writeCustomDataBlock(model,modelTag,sim.packTable(modelData)) end function updateDebugLevelCombobox() local items={'none','basic','extended','full'} simUI.setComboboxItems(configUiData.dlg,3,items,modelData.debugLevel) end function onSimOnlyChanged(ui,id,newval) configUiData.duringSimulationOnly=not configUiData.duringSimulationOnly modelData.duringSimulationOnly=not modelData.duringSimulationOnly sim.writeCustomDataBlock(model,modelTag,sim.packTable(modelData)) if modelData.duringSimulationOnly then destroyNode() else createNode() end end function onPackStrAsBinChanged(ui,id,newval) configUiData.packStrAsBin=not configUiData.packStrAsBin modelData.packStrAsBin=not modelData.packStrAsBin sim.writeCustomDataBlock(model,modelTag,sim.packTable(modelData)) if modelData.packStrAsBin then messagePack.set_string('binary') else messagePack.set_string('string') end end function onConfigRestartNode(ui,id,newVal) modelData.nodeName=configUiData.nodeName modelData.channelName=configUiData.channelName sim.writeCustomDataBlock(model,modelTag,sim.packTable(modelData)) if not modelData.duringSimulationOnly then destroyNode() createNode() end end function createConfigDlg() if not configUiData then local xml = [[ <ui title="BlueZero-based remote API, server-side configuration" closeable="false" resizable="false" activate="false"> <group layout="form" flat="true"> <label text="Node name"/> <edit on-editing-finished="onConfigNodeNameChanged" id="1"/> <label text="Channel name"/> <edit on-editing-finished="onConfigChannelNameChanged" id="2"/> <label text=""/> <button text="Restart node with above names" checked="false" on-click="onConfigRestartNode" /> <label text="Pack strings as binary"/> <checkbox text="" on-change="onPackStrAsBinChanged" id="4" /> <label text="Enabled during simulation only"/> <checkbox text="" on-change="onSimOnlyChanged" id="5" /> <label text="Debug level"/> <combobox id="3" on-change="onDebugLevelChanged"></combobox> </group> </ui> ]] configUiData={} configUiData.dlg=simUI.create(xml) if previousConfigDlgPos then simUI.setPosition(configUiData.dlg,previousConfigDlgPos[1],previousConfigDlgPos[2],true) end configUiData.nodeName=modelData.nodeName configUiData.channelName=modelData.channelName configUiData.debugLevel=modelData.debugLevel configUiData.packStrAsBin=modelData.packStrAsBin configUiData.duringSimulationOnly=modelData.duringSimulationOnly simUI.setEditValue(configUiData.dlg,1,configUiData.nodeName) simUI.setEditValue(configUiData.dlg,2,configUiData.channelName) simUI.setCheckboxValue(configUiData.dlg,4,configUiData.packStrAsBin and 2 or 0) simUI.setCheckboxValue(configUiData.dlg,5,configUiData.duringSimulationOnly and 2 or 0) updateDebugLevelCombobox() end end function removeConfigDlg() if configUiData then local x,y=simUI.getPosition(configUiData.dlg) previousConfigDlgPos={x,y} simUI.destroy(configUiData.dlg) configUiData=nil end end function sysCall_init() local res res,model=PCALL(sim.getObjectAssociatedWithScript,false,sim.handle_self) -- if call made directly, will fail with add-on script local abort=false if not res or model==-1 then -- We are running this script via an Add-On script model=-1 b0RemoteApiServerNameDebug='B0 Remote API (add-on)' modelData={nodeName='b0RemoteApi_V-REP-addOn',channelName='b0RemoteApiAddOn',debugLevel=1,packStrAsBin=false,duringSimulationOnly=false} else -- We are probably running this script via a customization script modelTag='b0-remoteApi' b0RemoteApiServerNameDebug='B0 Remote API' -- sim.writeCustomDataBlock(model,modelTag,sim.packTable({nodeName='b0RemoteApi_V-REP',channelName='b0RemoteApi',debugLevel=1,packStrAsBin=false,duringSimulationOnly=false})) local objs=sim.getObjectsWithTag(modelTag,true) if #objs>1 then sim.removeModel(model) sim.removeObjectFromSelection(sim.handle_all) objs=sim.getObjectsWithTag(modelTag,true) sim.addObjectToSelection(sim.handle_single,objs[1]) abort=true else modelData=sim.unpackTable(sim.readCustomDataBlock(model,modelTag)) end end syncMode=false if not abort then createNode() end end function sysCall_cleanup() destroyNode() removeConfigDlg() end function sysCall_nonSimulation() local s=sim.getObjectSelection() if s and #s==1 and s[1]==model then createConfigDlg() else removeConfigDlg() end sendAndSpin(0) end function sysCall_beforeMainScript() if not sendAndSpin(1) then return {doNotRunMainScript=true} end end function sysCall_suspended() sendAndSpin(2) end function sysCall_beforeSimulation() removeConfigDlg() if modelData.duringSimulationOnly then createNode() end end function sysCall_afterSimulation() if modelData.duringSimulationOnly then destroyNode() end syncMode=false end function sysCall_beforeInstanceSwitch() if model>=0 then destroyNode() removeConfigDlg() end end function sysCall_afterInstanceSwitch() if model>=0 then if not modelData.duringSimulationOnly then createNode() end createNode() end end function sysCall_addOnScriptSuspend() destroyNode() end function sysCall_addOnScriptResume() if not modelData.duringSimulationOnly then createNode() end end
Ambi.UI = Ambi.UI or {} Ambi.UI.Draw = Ambi.UI.Draw or {} -- ------------------------------------------------------------------------------------- local C = Ambi.General.Global.Colors local W, H = ScrW(), ScrH() local surface, draw, math, string, Material, FrameTime, Matrix, SysTime, ipairs = surface, draw, math, string, Material, FrameTime, Matrix, SysTime, ipairs local Explode = string.Explode local SimpTextOutl, SimpText, RoundedBoxEx = draw.SimpleTextOutlined, draw.SimpleText, draw.RoundedBoxEx local DrawPoly, DrawLine, DrawTexturedRect, DrawRect, DrawText = surface.DrawPoly, surface.DrawLine, surface.DrawTexturedRect, surface.DrawText local SetFont, GetTextSize, SetMaterial, SetDrawColor, SetTextPos = surface.SetFont, surface.GetTextSize, surface.SetMaterial, surface.SetDrawColor, surface.SetTextPos local Min, Max, Cos, Sin, Rad, PI = math.min, math.max, math.cos, math.sin, math.rad, math.pi local SetMetaTable = setmetatable local TimerCreate = timer.Create local PushModelMatrix, PopModelMatrix = cam.PushModelMatrix, cam.PopModelMatrix local SetScissorRect, UpdateScreenEffectTexture = render.SetScissorRect, render.UpdateScreenEffectTexture -- ------------------------------------------------------------------------------------- -- взял с SuperiorServers/dash local cache_sizes = SetMetaTable( {}, { __mode = 'k' } ) TimerCreate( 'AmbUIDrawClearFontCache', 1800, 0, function() for i = 1, #cache_sizes do cache_sizes[ i ] = nil end end) function Ambi.UI.Draw.GetTextSize( sFont, sText ) if ( cache_sizes[ sFont ] == nil ) then cache_sizes[ sFont ] = {} end if ( cache_sizes[ sFont ][ sText ] == nil ) then SetFont( sFont ) local w, h = GetTextSize( sText ) cache_sizes[ sFont ][ sText ] = { w = w, h = h } return w, h end return cache_sizes[ sFont ][ sText ].w, cache_sizes[ sFont ][ sText ].h end local GetTextSizeAmbition = Ambi.UI.Draw.GetTextSize function Ambi.UI.Draw.GetTextSizeX( sFont, sText ) local x, _ = GetTextSizeAmbition( sFont, sText ) return x end function Ambi.UI.Draw.GetTextSizeY( sFont, sText ) local _, y = GetTextSizeAmbition( sFont, sText ) return y end -- ------------------------------------------------------------------------------------- local ROUNDED_ANGLES = { [ 0 ] = { true, true, true, true }, [ 1 ] = { true, true, false, false }, [ 2 ] = { false, false, true, true }, [ 3 ] = { false, true, false, true }, [ 4 ] = { true, false, true, false }, [ 5 ] = { true, false, false, false }, [ 6 ] = { false, true, false, false }, [ 7 ] = { false, false, true, false }, [ 8 ] = { false, false, false, true }, [ 'all' ] = { true, true, true, true }, [ 'top' ] = { true, true, false, false }, [ 'bottom' ] = { false, false, true, true }, [ 'right' ] = { false, true, false, true }, [ 'left' ] = { true, false, true, false }, [ 'top-left' ] = { true, false, false, false }, [ 'top-right' ] = { false, true, false, false }, [ 'bottom-left' ] = { false, false, true, false }, [ 'bottom-right' ] = { false, false, false, true }, [ 'top left' ] = { true, false, false, false }, [ 'top right' ] = { false, true, false, false }, [ 'bottom left' ] = { false, false, true, false }, [ 'bottom right' ] = { false, false, false, true }, [ 'a' ] = { true, true, true, true }, [ 't' ] = { true, true, false, false }, [ 'b' ] = { false, false, true, true }, [ 'r' ] = { false, true, false, true }, [ 'l' ] = { true, false, true, false }, [ 'tl' ] = { true, false, false, false }, [ 'tr' ] = { false, true, false, false }, [ 'bl' ] = { false, false, true, false }, [ 'br' ] = { false, false, false, true }, } function Ambi.UI.Draw.Box( wSize, hSize, xPos, yPos, cColor, nRounded, anyRoundedAngles ) wSize, hSize, xPos, yPos = wSize or 0, hSize or 0, xPos or 0, yPos or 0 cColor = cColor or C.ABS_WHITE nRounded = nRounded or 0 sRoundedAngles = ROUNDED_ANGLES[ anyRoundedAngles or 0 ] or ROUNDED_ANGLES[ 0 ] RoundedBoxEx( nRounded, xPos, yPos, wSize, hSize, cColor, sRoundedAngles[ 1 ], sRoundedAngles[ 2 ], sRoundedAngles[ 3 ], sRoundedAngles[ 4 ] ) end local ALIGN_PATTERNS = { [ 0 ] = { TEXT_ALIGN_LEFT, TEXT_ALIGN_TOP }, [ 1 ] = { TEXT_ALIGN_RIGHT, TEXT_ALIGN_TOP }, [ 2 ] = { TEXT_ALIGN_CENTER, TEXT_ALIGN_TOP }, [ 3 ] = { TEXT_ALIGN_LEFT, TEXT_ALIGN_BOTTOM }, [ 4 ] = { TEXT_ALIGN_RIGHT, TEXT_ALIGN_BOTTOM }, [ 5 ] = { TEXT_ALIGN_CENTER, TEXT_ALIGN_BOTTOM }, [ 6 ] = { TEXT_ALIGN_LEFT, TEXT_ALIGN_CENTER }, [ 7 ] = { TEXT_ALIGN_RIGHT, TEXT_ALIGN_CENTER }, [ 8 ] = { TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER }, [ 'top-left' ] = { TEXT_ALIGN_LEFT, TEXT_ALIGN_TOP }, [ 'top-right' ] = { TEXT_ALIGN_RIGHT, TEXT_ALIGN_TOP }, [ 'top-center' ] = { TEXT_ALIGN_CENTER, TEXT_ALIGN_TOP }, [ 'bottom-left' ] = { TEXT_ALIGN_LEFT, TEXT_ALIGN_BOTTOM }, [ 'bottom-right' ] = { TEXT_ALIGN_RIGHT, TEXT_ALIGN_BOTTOM }, [ 'bottom-center' ] = { TEXT_ALIGN_CENTER, TEXT_ALIGN_BOTTOM }, [ 'center-left' ] = { TEXT_ALIGN_LEFT, TEXT_ALIGN_CENTER }, [ 'center-right' ] = { TEXT_ALIGN_RIGHT, TEXT_ALIGN_CENTER }, [ 'center' ] = { TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER }, [ 'top left' ] = { TEXT_ALIGN_LEFT, TEXT_ALIGN_TOP }, [ 'top right' ] = { TEXT_ALIGN_RIGHT, TEXT_ALIGN_TOP }, [ 'top center' ] = { TEXT_ALIGN_CENTER, TEXT_ALIGN_TOP }, [ 'bottom left' ] = { TEXT_ALIGN_LEFT, TEXT_ALIGN_BOTTOM }, [ 'bottom right' ] = { TEXT_ALIGN_RIGHT, TEXT_ALIGN_BOTTOM }, [ 'bottom center' ] = { TEXT_ALIGN_CENTER, TEXT_ALIGN_BOTTOM }, [ 'center left' ] = { TEXT_ALIGN_LEFT, TEXT_ALIGN_CENTER }, [ 'center right' ] = { TEXT_ALIGN_RIGHT, TEXT_ALIGN_CENTER }, [ 'tl' ] = { TEXT_ALIGN_LEFT, TEXT_ALIGN_TOP }, [ 'tr' ] = { TEXT_ALIGN_RIGHT, TEXT_ALIGN_TOP }, [ 'tc' ] = { TEXT_ALIGN_CENTER, TEXT_ALIGN_TOP }, [ 'bl' ] = { TEXT_ALIGN_LEFT, TEXT_ALIGN_BOTTOM }, [ 'br' ] = { TEXT_ALIGN_RIGHT, TEXT_ALIGN_BOTTOM }, [ 'bc' ] = { TEXT_ALIGN_CENTER, TEXT_ALIGN_BOTTOM }, [ 'cl' ] = { TEXT_ALIGN_LEFT, TEXT_ALIGN_CENTER }, [ 'cr' ] = { TEXT_ALIGN_RIGHT, TEXT_ALIGN_CENTER }, [ 'c' ] = { TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER }, } function Ambi.UI.Draw.Text( xPos, yPos, sText, sFont, cColor, anyAlign, nOutlineWeight, cColorOutline ) -- @ the method may be heavy and eating more FPS! local Draw = ( ( nOutlineWeight or 0 ) > 0 ) and SimpTextOutl or SimpText local font, y, align = sFont or 'Default', yPos or 0, ALIGN_PATTERNS[ anyAlign or 0 ] or ALIGN_PATTERNS[ 0 ] local tab = Explode( '\n', sText or '' ) for i = 1, #tab do local str = tab[ i ] local y_offset = Ambi.UI.Draw.GetTextSizeY( font, str ) or 0 Draw( str, font, xPos or 0, y + ( y_offset - 8 ) * ( i - 1 ), cColor or C.ABS_WHITE, align[ 1 ], align[ 2 ], nOutlineWeight or 1, cColorOutline or C.ABS_BLACK ) end end function Ambi.UI.Draw.SimpleText( xPos, yPos, sText, sFont, cColor, anyAlign, nOutlineWeight, cColorOutline ) local Draw = ( ( nOutlineWeight or 0 ) > 0 ) and SimpTextOutl or SimpText local font, align = sFont or 'Default', ALIGN_PATTERNS[ anyAlign or 0 ] or ALIGN_PATTERNS[ 0 ] SimpTextOutl( sText, font, xPos or 0, yPos or 0, cColor or C.ABS_WHITE, align[ 1 ], align[ 2 ], nOutlineWeight or 0, cColorOutline or C.ABS_BLACK ) end local DEFAULT_MAT = Material( '' ) function Ambi.UI.Draw.Material( wSize, hSize, xPos, yPos, matImage, cColor ) SetMaterial( matImage or DEFAULT_MAT ) SetDrawColor( cColor and cColor.r or 255, cColor and cColor.g or 255, cColor and cColor.b or 255, cColor and cColor.a or 255 ) DrawTexturedRect( xPos or 0, yPos or 0, wSize or 0, hSize or 0 ) end function Ambi.UI.Draw.Line( xPosStart, yPosStart, xPosEnd, yPosEnd, cColor ) SetDrawColor( cColor and cColor.r or 255, cColor and cColor.g or 255, cColor and cColor.b or 255, cColor and cColor.a or 255 ) DrawLine( xPosStart or 0, yPosStart or 0, xPosEnd or 0, yPosEnd or 0 ) end local BLUR = Material( 'pp/blurscreen' ) function Ambi.UI.Draw.Blur( vguiPanel, nBlur ) local x, y = vguiPanel:LocalToScreen( 0, 0 ) local w, h = ScrW(), ScrH() SetDrawColor( 255, 255, 255 ) SetMaterial( BLUR ) for i = 1, 3 do BLUR:SetFloat( '$BLUR', ( i / 3 ) * ( nBlur or 6 ) ) BLUR:Recompute() UpdateScreenEffectTexture() DrawTexturedRect( x * -1, y * -1, w, h ) end end -- ------------------------------------------------------------------------------------- -- by TechoHUD function Ambi.UI.Draw.ObliqueRect( xPos, yPos, wSize, hSize, cColor, bReverse, matTexture ) -- https://steamcommunity.com/sharedfiles/filedetails/?id=1120612949 local rect = {} if bReverse then rect[1] = { x = xPos, y = yPos } rect[2] = { x = xPos + wSize, y = yPos } rect[3] = { x = ( xPos + wSize ) - hSize * 0.8, y = yPos + hSize } rect[4] = { x = xPos - hSize * 0.8, y = yPos + hSize } else rect[1] = { x = xPos, y = yPos } rect[2] = { x = ( xPos + wSize ), y = yPos } rect[3] = { x = xPos + wSize + hSize * 0.8, y = yPos + hSize } rect[4] = { x = xPos + hSize, y = yPos + hSize } end surface.SetDrawColor( cColor:Unpack() ) if matTexture then surface.SetMaterial( matTexture ) else draw.NoTexture() end surface.DrawPoly( rect ) end -- by Kruzgi function Ambi.UI.Draw.CircleKruzgi( xPos1, yPos1, wSize, hSize, cColor, aAngle, xPos2, yPos2, matTexture ) -- https://github.com/kruzgi/Garrys-Mod-Draw-Circle/blob/master/draw_circle.lua for i = 0, aAngle do local c = math.cos( math.rad( i ) ) local s = math.sin( math.rad( i ) ) local newx = yPos2 * s - xPos2 * c local newy = yPos2 * c + xPos2 * s surface.SetDrawColor( cColor ) if matTexture then surface.SetMaterial( matTexture ) else draw.NoTexture() end surface.DrawTexturedRectRotated( xPos1 + newx, yPos1 + newy, wSize, hSize, i ) end end -- ------------------------------------------------------------------------------------- -- by SuperiorServers -- Source: https://github.com/SuperiorServers/dash/blob/master/lua/dash/extensions/client/surface.lua local TAB = { {}, {}, {}, {} } local q1, q2, q3, q4 = TAB[1], TAB[ 2 ], TAB[ 3 ], TAB[4] function Ambi.UI.Draw.Quad( x1, y1, x2, y2, x3, y3, x4, y4 ) q1.x, q1.y = x1, y1 q2.x, q2.y = x2, y2 q3.x, q3.y = x3, y3 q4.x, q4.y = x4, y4 DrawPoly( TAB ) end local TABUV = { {}, {}, {}, {} } local quv1, quv2, quv3, quv4 = TABUV[ 1 ], TABUV[ 2 ], TABUV[ 3 ], TABUV[ 4 ] function Ambi.UI.Draw.QuadUV( x1, y1, x2, y2, x3, y3, x4, y4 ) local xmin, ymin = Max local xmax, ymax = Min xmin = x1 if ( x2 < xmin ) then xmin = x2 end if ( x3 < xmin ) then xmin = x3 end if ( x4 < xmin ) then xmin = x4 end ymin = y1 if ( y2 < ymin ) then ymin = y2 end if ( y3 < ymin ) then ymin = y3 end if ( y4 < ymin ) then ymin = y4 end xmax = x1 if ( x2 > xmax ) then xmax = x2 end if ( x3 > xmax ) then xmax = x3 end if ( x4 > xmax ) then xmax = x4 end ymax = y1 if ( y2 > ymax ) then ymax = y2 end if ( y3 > ymax ) then ymax = y3 end if ( y4 > ymax ) then ymax = y4 end local dy = ymax - ymin local dx = xmax - xmin quv1.u, quv1.v = ( x1 - xmin ) / dx, ( y1 - ymin ) / dy quv2.u, quv2.v = ( x2 - xmin ) / dx, ( y2 - ymin ) / dy quv3.u, quv3.v = ( x3 - xmin ) / dx, ( y3 - ymin ) / dy quv4.u, quv4.v = ( x4 - xmin ) / dx, ( y4 - ymin ) / dy quv1.x, quv1.y = x1, y1 quv2.x, quv2.y = x2, y2 quv3.x, quv3.y = x3, y3 quv4.x, quv4.y = x4, y4 DrawPoly( TABUV ) end function Ambi.UI.Draw.QuadOutline( x1, y1, x2, y2, x3, y3, x4, y4 ) DrawLine( x1,y1, x2,y2 ) DrawLine( x2,y2, x3,y3 ) DrawLine( x3,y3, x4,y4 ) DrawLine( x4,y4, x1,y1 ) end local ANG2RAD = 0.017453292519939 -- 3.141592653589 / 180 local DrawQuad = Ambi.UI.Draw.Quad function Ambi.UI.Draw.Arc( _x, _y, r1, r2, aStart, aFinish, steps ) aStart, aFinish = aStart * ANG2RAD, aFinish * ANG2RAD local step = ( ( aFinish - aStart ) / steps ) local c = steps local a, c1, s1, c2, s2 c2, s2 = Cos( aStart ), Sin( aStart ) for i = 0, steps - 1 do a = i * step + aStart c1, s1 = c2, s2 c2, s2 = Cos( a + step ), Sin( a + step ) DrawQuad( _x+c1*r1, _y+s1*r1, _x+c1*r2, _y+s1*r2, _x+c2*r2, _y+s2*r2, _x+c2*r1, _y+s2*r1 ) c = c - 1 if c < 0 then break end end end function Ambi.UI.Draw.ArcOutline(_x, _y, r1, r2, aStart, aFinish, steps) aStart, aFinish = aStart * ANG2RAD, aFinish * ANG2RAD local step = ( ( aFinish - aStart ) / steps ) local c = steps local a, c1, s1, c2, s2 c2, s2 = Cos( aStart ), Sin( aStart ) DrawLine( _x+c2*r1, _y+s2*r1, _x+c2*r2, _y+s2*r2 ) for i = 0, steps - 1 do a = i * step + aStart c1, s1 = c2, s2 c2, s2 = Cos(a+step), Sin(a+step) DrawLine( _x+c1*r2, _y+s1*r2, _x+c2*r2, _y+s2*r2 ) DrawLine( _x+c1*r1, _y+s1*r1, _x+c2*r1, _y+s2*r1 ) c = c - 1 if c < 0 then break end end DrawLine( _x+c2*r1, _y+s2*r1, _x+c2*r2, _y+s2*r2 ) end local function DrawRectDash(x, y, w, h, t) if not t then t = 1 end DrawRect(x, y, w, t) DrawRect(x, y + (h - t), w, t) DrawRect(x, y, t, h) DrawRect(x + (w - t), y, t, h) end function Ambi.UI.Draw.BoxDash(x, y, w, h, col) SetDrawColor(col) DrawRect(x, y, w, h) end function Ambi.UI.Draw.BoxDashOutline(x, y, w, h, col, bordercol, thickness) SetDrawColor(col) DrawRect(x + 1, y + 1, w - 2, h - 2) SetDrawColor(bordercol) DrawRectDash(x, y, w, h, thickness) end function Ambi.UI.Draw.BoxDashBorder( x, y, w, h, cColor, thickness ) SetDrawColor( cColor ) DrawRectDash(x, y, w, h, thickness) end local blurboxes = {} function Ambi.UI.Draw.BlurResample( nAmount ) SetDrawColor( 255, 255, 255 ) SetMaterial( BLUR ) for i = 1, 3 do BLUR:SetFloat( '$blur', ( i / 3 ) * ( nAmount or 8 ) ) BLUR:Recompute() UpdateScreenEffectTexture() for k, v in ipairs( blurboxes ) do SetScissorRect( v.x, v.y, v.x + v.w, v.y + v.h, true ) DrawTexturedRect( 0, 0, ScrW(), ScrH() ) SetScissorRect( 0, 0, 0, 0, false ) blurboxes[ k ] = nil end end end function Ambi.UI.Draw.BlurBox( x, y, w, h ) blurboxes[ #blurboxes + 1 ] = { x = x, y = y, w = w, h = h } end function Ambi.UI.Draw.BlurDash( vguiPanel ) Ambi.UI.Draw.BlurBox( vguiPanel:GetBounds() ) end function Ambi.UI.Draw.TextRotatedDash( sText, nX, nY, cColor, sFont, nAng ) SetFont( sFont ) SetTextColor( cColor ) local m = Matrix() m:SetAngles( Angle( 0, nAng , 0 ) ) m:SetTranslation( Vector( nX , nY , 0) ) PushModelMatrix(m) surface.SetTextPos( 0, 0 ) surface.DrawText( sText ) PopModelMatrix() end
return function (stream, name) if name == "ANONYMOUS" then return function () return coroutine.yield() == "success"; end, 0; end end
------------------------------------------------------------------------------- -- AdiBags - Korthian Relics By Crackpot (US, Arthas) ------------------------------------------------------------------------------- local addonName, addon = ... local AdiBags = LibStub("AceAddon-3.0"):GetAddon("AdiBags") local tonumber = _G["tonumber"] local L = addon.L local tooltip local function tooltipInit() local tip, leftside = CreateFrame("GameTooltip"), {} for i = 1, 6 do local left, right = tip:CreateFontString(), tip:CreateFontString() left:SetFontObject(GameFontNormal) right:SetFontObject(GameFontNormal) tip:AddFontStrings(left, right) leftside[i] = left end tip.leftside = leftside return tip end local shardFilter = AdiBags:RegisterFilter("Shards of Domination", 98, "ABEvent-1.0") shardFilter.uiName = L["Shards of Domination"] shardFilter.uiDesc = L["New type of gem added in patch 9.1."] function shardFilter:OnInitialize() self.shards = { -- Shard Removal Tool [187532] = true, -- Soulfire Chisel -- Blood Shards of Domination [187057] = true, -- Shard of Bek [187059] = true, -- Shard of Jas [187061] = true, -- Shard of Rev [187284] = true, -- Omnious Shard of Bek [187285] = true, -- Omnious Shard of Jas [187286] = true, -- Ominous Shard of Rev [187293] = true, -- Desolate Shard of Bek [187294] = true, -- Desolate Shard of Jas [187295] = true, -- Desolate Shard of Rev [187302] = true, -- Foreboding Shard of Bek [187303] = true, -- Foreboding Shard of Jas [187304] = true, -- Foreboding Shard of Rev [187312] = true, -- Portentous Shard of Bek [187313] = true, -- Portentous Shard of Jas [187314] = true, -- Portentous Shard of Rev -- Frost Shards of Domination [187063] = true, -- Shard of Cor [187065] = true, -- Shard of Kyr [187071] = true, -- Shard of Tel [187287] = true, -- Ominous Shard of Cor [187288] = true, -- Ominous Shard of Kyr [187289] = true, -- Ominous Shard of Tel [187296] = true, -- Desolate Shard of Cor [187297] = true, -- Desolate Shard of Kyr [187298] = true, -- Desolate Shard of Tel [187305] = true, -- Foreboding Shard of Cor [187306] = true, -- Foreboding Shard of Kyr [187307] = true, -- Foreboding Shard of Tel [187315] = true, -- Portentous Shard of Cor [187316] = true, -- Portentous Shard of Kyr [187317] = true, -- Portentous Shard of Tel -- Unholy Shards of Domination [187073] = true, -- Shard of Dyz [187079] = true, -- Shard of Zed [187076] = true, -- Shard of Oth [187290] = true, -- Ominous Shard of Dyz [187291] = true, -- Ominous Shard of Oth [187292] = true, -- Ominous Shard of Zed [187290] = true, -- Ominous Shard of Dyz [187291] = true, -- Ominous Shard of Oth [187292] = true, -- Ominous Shard of Zed [187299] = true, -- Desolate Shard of Dyz [187300] = true, -- Desolate Shard of Oth [187301] = true, -- Desolate Shard of Zed [187308] = true, -- Foreboding Shard of Dyz [187309] = true, -- Foreboding Shard of Oth [187310] = true, -- Foreboding Shard of Zed [187318] = true, -- Portentous Shard of Dyz [187319] = true, -- Portentous Shard of Oth [187320] = true -- Portentous Shard of Zed } end function shardFilter:Updatee() self:SendMessage("AdiBags_FiltersChanged") end function shardFilter:OnEnable() AdiBags:UpdateFilters() end function shardFilter:OnDisable() AdiBags:UpdateFilters() end function shardFilter:Filter(slotData) if self.shards[tonumber(slotData.itemId)] then return L["Shards of Domination"] end tooltip = tooltip or tooltipInit() tooltip:SetOwner(UIParent, "ANCHOR_NONE") tooltip:ClearLines() if slotData.bag == BANK_CONTAINER then tooltip:SetInventoryItem("player", BankButtonIDToInvSlotID(slotData.slot, nil)) else tooltip:SetBagItem(slotData.bag, slotData.slot) end tooltip:Hide() end
function route93outpost.destroyHelicopters() env.info("route93outpost.destroyHelicopters") for _, u in pairs(mist.getUnitsInZones(mist.makeUnitTable({'[red][helicopter]'}), {route93outpost.triggerZone})) do local unitID = tonumber(u:getID()) trigger.action.explosion(u:getPosition().p, 100) end -- env.info("Scheduling next route93outpost.destroyHelicopters") -- timer.scheduleFunction(route93outpost.destroyHelicopters, nil, timer.getTime() + route93outpost.interval) end
ZPClass.Name = "HumanSuicidalClassName" ZPClass.Description = "HumanSuicidalClassDescription" ZPClass.MaxHealth = 50 ZPClass.PModel = "models/player/guerilla.mdl" ZPClass.Speed = 220 ZPClass.RunSpeed = 100 ZPClass.CrouchSpeed = 0.5 ZPClass.Gravity = 0.9 ZPClass.Breath = 50 local ActivationAction = function(ply) ply:SetArmor(ply:Armor() + 100) ply:SetWalkSpeed(290) ply:SetRunSpeed(290) local TimerNameWithSteamID64 = ply:SteamID64() .. "SuicideExplode" timer.Create(TimerNameWithSteamID64, 0.5, 12, function() local RepsLeft = timer.RepsLeft(TimerNameWithSteamID64) if RepsLeft == 0 then ply:Kill() local explosion = ents.Create("env_explosion") -- https://facepunch.com/showthread.php?t=1021105 / Brandan explosion:SetKeyValue("spawnflags", 144) explosion:SetKeyValue("iMagnitude", 2000) explosion:SetKeyValue("iRadiusOverride", 256) explosion:SetOwner(ply) explosion:SetPos(ply:GetPos()) explosion:Spawn() explosion:Activate() explosion:Fire("explode","",0) elseif RepsLeft < 5 then ply:EmitSound("weapons/grenade/tick1.wav") elseif RepsLeft % 2 == 1 then ply:EmitSound("weapons/grenade/tick1.wav") end end) local EventName = "ZPResetAbilityEvent" .. ply:SteamID64() hook.Add(EventName, TimerNameWithSteamID64, function() timer.Destroy(TimerNameWithSteamID64) hook.Remove(EventName, TimerNameWithSteamID64) end) end ZPClass.Ability = ClassManager:CreateClassAbility(true, ActivationAction) ZPClass.Ability.CanUseAbility = function() return RoundManager:GetRoundState() == ROUND_PLAYING && RoundManager:CountZombiesAlive() > 0 end if(ZPClass:ShouldBeEnabled()) then ClassManager:AddZPClass("SuicideHuman", ZPClass, TEAM_HUMANS) end
-- Idea: look at the structure of the official luac compiler and construct a pattern grammar based on that local utils = require 'luainlua.common.utils' local undump = require 'luainlua.bytecode.undump' local cfg = require 'luainlua.cfg.cfg' local decompiler = {} local ast = {} function ast:set(key, val) if not key or not val then return self end self[key] = val return self end function ast:list(...) for child in utils.loop({...}) do table.insert(self, child) end return self end function ast:children() return utils.loop(self) end local function escape(id) return table.concat( utils.map( function(char) if char == ("'"):byte() then return "\\'" else return string.char(char) end end, {id:byte(1, #id)})) end function ast:tostring() utils.dump(self, escape) end local function node(kind) return setmetatable({kind = kind}, {__index = ast, __tostring = ast.tostring}) end local function from(kind, value) if not kind then kind = 'leaf' end local leaf = node(kind) leaf.value = value return leaf end -------------------------------------------- --- Puzzle Pieces --- -------------------------------------------- local puzzles = {} -- OP_RETURN,/* A B return R(A), ... ,R(A+B-2) (see note) */ function puzzles.RETURN(ctx, instruction) end local context = {} local closure = undump.undump(function(x, y) for i = 1,2,4 do foo() end end) local g = cfg.make(closure) print(cfg.tostring(g)) return decompiler
yGather.matdb = {}; -- make globals available local dofile = dofile; local pcall = pcall; local pairs = pairs; local ipairs = ipairs; local table = table; local TEXT = TEXT; local logger = yGather.logger; local translate = yGather.i18n.translate; setfenv(1, yGather.matdb); local idDB = {}; local nameDB = {}; local lumDB = {}; local minDB = {}; local herbDB = {}; local userDB = {}; function LoadDB() local db = dofile("Interface/AddOns/yGather/resources/spotnames.lua"); -- create table indexed by id and indexed by name local entry; for id, data in pairs(db) do local spotname; if (id > 4000) then spotname = translate(data[1]); else spotname = TEXT(data[1]); end; entry = {id, spotname, data[2], data[3]}; idDB[id] = entry; nameDB[spotname] = entry; if (data[3] == "LUMBERING") then table.insert(lumDB, entry); end; if (data[3] == "MINING") then table.insert(minDB, entry); end; if (data[3] == "HERBLISM") then table.insert(herbDB, entry); end; if (data[3] == "USER") then table.insert(userDB, entry); end; end; local function sortMats(mat1, mat2) return mat1[1] < mat2[1]; end; table.sort(idDB, sortMats); table.sort(lumDB, sortMats); table.sort(minDB, sortMats); table.sort(herbDB, sortMats); end function Iterator() local a, b, c = pairs(idDB); return a, b, c; end; function LumIterator() local a, b, c = ipairs(lumDB); return a, b, c; end; function MinIterator() local a, b, c = ipairs(minDB); return a, b, c; end; function HerbIterator() local a, b, c = ipairs(herbDB); return a, b, c; end; function UserIterator() local a, b, c = ipairs(userDB); return a, b, c; end; function GetResourceName(id) local entry = idDB[id]; if (entry ~= nil) then return entry[2]; end end function GetSkillLevel(id) local entry = idDB[id]; if (entry ~= nil) then return entry[3]; end end function GetResourceSkill(id) local entry = idDB[id]; if (entry ~= nil) then return entry[4]; end end function GetResourceId(name) local entry = nameDB[name]; if (entry ~= nil) then return entry[1]; end end;
require 'Util' require 'Constants' -- INITIALIZE GRAPHICAL DATA icon_texture = love.graphics.newImage('graphics/icons.png') icons = getSpriteQuads( { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 , 12, 13, 14, 15, 16, 17, 18, 19, 20, 21 }, icon_texture, 22, 22, 0 ) status_icons = getSpriteQuads({0, 1, 2, 3}, icon_texture, 8, 8, 23) chapter_spritesheets = {} n_chapters = 1 for i = 1, n_chapters do local sheet_file = 'graphics/spritesheets/ch' .. i .. '.png' chapter_spritesheets[i] = love.graphics.newImage(sheet_file) end require 'Player' require 'Sprite' require 'Map' require 'Scene' require 'Music' require 'Sounds' require 'Triggers' require 'Scripts' require 'Battle' Chapter = class('Chapter') -- Constructor for our scenario object function Chapter:initialize(id) -- Store id self.id = id -- Camera that follows coordinates of player sprite around the chapter self.camera_x = 0 self.camera_y = 0 self.camera_speed = 300 -- Map info self.maps = {} self.current_map = nil -- Dict from map names to audio sources self.map_to_music = {} self.current_music = nil -- Settings self.turn_autoend = true self.music_volume = OFF self.sfx_volume = OFF self.text_volume = OFF self:setSfxVolume(self.sfx_volume) -- self:setTextVolume(self.text_volume) -- Rendering information self.alpha = 1 self.fade_to = nil self.autosave_flash = 0 -- Sprites in this chapter self.sprites = {} self.player = nil -- Difficulty level self.difficulty = MASTER -- State of a chapter a dictionary of strings that correspond to different -- chapter events and determine quest progress, cinematic triggers, and -- sprite locations self.state = {} -- Tracking the scene the player is currently in self.current_scene = nil self.scene_inputs = {} self.callbacks = {} self.seen = {} -- If the player is in a battle, it goes here self.battle = nil self.battle_inputs = {} -- Read into the above fields from chapter file self.signal = nil self:load() self:saveChapter() end function Chapter:autosave(silent) binser.writeFile('abelon/' .. SAVE_DIRECTORY .. AUTO_SAVE, self) self.autosave_flash = ite(silent, 0, 1) end function Chapter:quicksave() binser.writeFile('abelon/' .. SAVE_DIRECTORY .. QUICK_SAVE, self) love.event.quit(0) end function Chapter:saveBattle() binser.writeFile('abelon/' .. SAVE_DIRECTORY .. BATTLE_SAVE, self) self:autosave() end function Chapter:saveChapter() binser.writeFile('abelon/' .. SAVE_DIRECTORY .. CHAPTER_SAVE, self) self:autosave(true) end function Chapter:saveAndQuit() self:autosave() love.event.quit(0) end function Chapter:reloadBattle() self.signal = RELOAD_BATTLE self:stopMusic() end function Chapter:reloadChapter() self.signal = RELOAD_CHAPTER self:stopMusic() end -- Read information about sprites and scenes for this chapter function Chapter:load() -- Read lines into list local chap_file = 'Abelon/data/chapters/' .. self.id .. '/chapterfile.txt' local lines = readLines(chap_file) -- Iterate over lines of chapter file local audio_sources = {} local current_map_name = nil local current_sp_id = nil for i=1, #lines do -- Lines starting with ~~ denote a new map if lines[i]:sub(1,2) == '~~' then -- Read data from line local fields = split(lines[i]:sub(3)) local map_name, tileset, song_name = fields[1], fields[2], fields[3] current_map_name = map_name -- Initialize map and tie it to chapter self.maps[map_name] = Map:new(map_name, tileset, nil) -- Maps sharing a music track share a pointer to the audio self.map_to_music[map_name] = song_name -- Lines starting with ~ denote a new sprite elseif lines[i]:sub(1,1) == '~' then -- Collect sprite info from file local fields = split(lines[i]:sub(2)) current_sp_id = fields[1] local init_x = (tonumber(fields[2]) - 1) * TILE_WIDTH local init_y = (tonumber(fields[3]) - 1) * TILE_HEIGHT local dir = fields[4] local first_interaction = fields[5] -- Initialize sprite object and set its starting position local new_sp = Sprite:new(current_sp_id, self) self.sprites[current_sp_id] = new_sp new_sp:resetPosition(init_x, init_y) new_sp.dir = ite(dir == 'R', RIGHT, LEFT) -- Add sprite this sprite to the map on which it appears self.maps[current_map_name]:addSprite(new_sp) -- If the sprite is the player character, we make the current map -- into the chapter's starting map, and initialize a player object if first_interaction then if first_interaction == 'P' then self.current_map = self.maps[current_map_name] self.player = Player:new(new_sp) self:updateCamera(100) else new_sp.interactive = first_interaction end end end end -- Start music self:startMapMusic() end -- End the current chapter and save what happened in it function Chapter:endChapter() -- Stop music self:stopMusic() -- retire all sprites and write them to save file -- save relevant quest state info as well -- save Abelon's inventory end -- Return all sprite objects belonging to the chapter's active map function Chapter:getActiveSprites() return self.current_map:getSprites() end function Chapter:getSprite(sp_id) return self.sprites[sp_id] end -- Return the active map belonging to this chapter function Chapter:getMap() return self.current_map end function Chapter:playerNearSprite(sp_id) local x, y = self.player.sp:getPosition() local sp = self.current_map:getSprite(sp_id) if sp then local kx, ky = sp:getPosition() return abs(x - kx) <= PRESENT_DISTANCE * TILE_WIDTH and abs(y - ky) <= PRESENT_DISTANCE * TILE_HEIGHT end return false end function Chapter:setDifficulty(d) local old = self.difficulty self.difficulty = d if self.battle then self.battle:adjustDifficultyFrom(old) end end function Chapter:startMapMusic() self.current_music = self.map_to_music[self.current_map:getName()] end function Chapter:stopMusic() if self.current_music then music_tracks[self.current_music]:stop() end self.current_music = nil end function Chapter:setMusicVolume(vol) self.music_volume = vol end function Chapter:setSfxVolume(vol) self.sfx_volume = vol for k, v in pairs(sfx) do if k ~= 'text' then v:setVolume(vol) end end end function Chapter:setTextVolume(vol) self.text_volume = vol sfx['text']:setVolume(vol) end function Chapter:launchBattle(b_id) self.current_scene = nil self.battle = Battle:new(b_id, self.player, self) self:saveBattle() self.battle:openBattleStartMenu() end -- Store player inputs to a scene, to be processed on update function Chapter:battleInput(up, down, left, right, f, d) self.battle_inputs = { ['up'] = up, ['down'] = down, ['left'] = left, ['right'] = right, ['f'] = f, ['d'] = d, } end function Chapter:healAll() for i = 1, #self.player.party do local sp = self.player.party[i] sp.health = sp.attributes['endurance'] end end -- Start scene with the given scene id function Chapter:launchScene(s_id, returnToBattle) self.player:changeMode('scene') if not returnToBattle then self.player:changeBehavior('idle') end while self.callbacks[s_id] do s_id = self.callbacks[s_id] end self.current_scene = Scene:new(s_id, self.player, self, returnToBattle) end -- Begin an interaction with the target sprite function Chapter:interactWith(target) self:launchScene(target.interactive) end -- Store player inputs to a scene, to be processed on update function Chapter:sceneInput(space, u, d) -- Spacebar means advance dialogue if space then self.scene_inputs['advance'] = true end -- Up or down means hover a selection if u and not d then self.scene_inputs['hover'] = UP elseif d and not u then self.scene_inputs['hover'] = DOWN end end -- Advance current scene and collect results from a finished scene function Chapter:updateScene(dt) -- Advance scene according to player input if self.scene_inputs['advance'] then self.current_scene:advance() end self.current_scene:hover(self.scene_inputs['hover']) self.scene_inputs = {} -- Advance events in scene and text self.current_scene:update(dt) -- If scene has ended, shut it down and handle results if self.current_scene:over() then self.current_scene:close() self.current_scene = nil if not self.battle then self:autosave() end end end -- Switch from one map to another when the player touches a transition tile function Chapter:performTransition() -- New map local tr = self.in_transition local old_map = self.current_map:getName() local new_map = tr['name'] -- Reset player's position self.player:resetPosition(tr['x'], tr['y']) -- Move player from old map to new map self.maps[old_map]:dropSprite(self.player:getId()) self.maps[new_map]:addSprite(self.player.sp) -- If music is different for new map, stop old music and start new music local old_music = self.map_to_music[old_map] local new_music = self.map_to_music[new_map] local track_change = old_music ~= new_music -- Switch current map to new map if track_change then self:stopMusic() end self.current_map = self.maps[new_map] if track_change then self:startMapMusic() end self.in_transition = nil end -- Initiate, update, and perform map transitions -- and the associated fade-out and in function Chapter:updateTransition(transition) -- Start new transition if an argument was provided if transition then self.player:changeBehavior('idle') self.player:changeMode('frozen') self.in_transition = transition end -- When fade out is complete, perform switch if self.alpha == 0 then self:performTransition() self:updateCamera(100) end -- If in a transition, fade out if self.in_transition then self.alpha = math.max(0, self.alpha - 0.05) end -- If map has switched, fade in until alpha is full if not self.in_transition and self.alpha < 1 then self.alpha = math.min(1, self.alpha + 0.05) -- End transition when alpha is full if self.alpha == 1 then self.player:changeMode('free') end end end -- Update the camera to center on the player but not cross the map edges function Chapter:updateCamera(dt) -- Get camera bounds from map local pixel_width, pixel_height = self.current_map:getPixelDimensions() local cam_max_x = pixel_width - VIRTUAL_WIDTH local cam_max_y = pixel_height - VIRTUAL_HEIGHT -- Default camera info local focus = self.player local x_offset = 0 local y_offset = 0 local speed = self.camera_speed -- Target: where is the camera headed? local x_target = 0 local y_target = 0 -- Overwrite camera info from scene if it exists, or battle if it -- exists and there's no scene if self.current_scene then focus = self.current_scene.cam_lock x_offset = self.current_scene.cam_offset_x y_offset = self.current_scene.cam_offset_y speed = self.current_scene.cam_speed elseif self.battle then x_target, y_target, speed = self.battle:getCamera() end if not self.battle or (self.current_scene and self.battle) then local x, y = focus:getPosition() local w, h = focus:getDimensions() x_target = x + math.ceil(w / 2) + x_offset - VIRTUAL_WIDTH / 2 y_target = y + math.ceil(h / 2) + y_offset - VIRTUAL_HEIGHT / 2 x_target = math.max(0, math.min(x_target, cam_max_x)) y_target = math.max(0, math.min(y_target, cam_max_y)) end -- Compute move in the direction of camera target based on dt local new_x = ite(self.camera_x < x_target, math.min(self.camera_x + speed * dt, x_target), math.max(self.camera_x - speed * dt, x_target) ) local new_y = ite(self.camera_y < y_target, math.min(self.camera_y + speed * dt, y_target), math.max(self.camera_y - speed * dt, y_target) ) -- Release the camera event from the scene if the camera is done moving if new_x == x_target and new_y == y_target and self.current_scene then self.current_scene:release('camera') end -- Update camera position self.camera_x = math.max(0, math.min(new_x, cam_max_x)) self.camera_y = math.max(0, math.min(new_y, cam_max_y)) end function Chapter:checkSceneTriggers() local i = 1 for k, v in pairs(scene_triggers) do if not self.seen[k] then local check = v(self) if check then self.seen[k] = true if check ~= DELETE then self:launchScene(check) end end end end end -- Update all of the sprites and objects in a chapter function Chapter:update(dt) -- Update the chapter's active map and sprites local new_transition = self.current_map:update(dt, self.player) -- Update current battle if self.battle then self.battle:update(self.battle_inputs, dt) self.battle_inputs = {} end -- Update player character based on key-presses self.player:update() -- Update the currently active scene if self.current_scene then self:updateScene(dt) end self:checkSceneTriggers() -- Update music if self.current_music then music_tracks[self.current_music]:update(dt, self.music_volume) end -- Update current transition or initiate new one self:updateTransition(new_transition) -- Update camera position self:updateCamera(dt) self.autosave_flash = math.max(0, self.autosave_flash - dt) -- Return reload/end signal return self.signal end -- Render the map and sprites of the chapter at the current position, -- along with active scene function Chapter:render() -- Move to the camera position love.graphics.translate(-self.camera_x, -self.camera_y) -- Render the map tiles self.current_map:renderTiles() -- Render battle grid if self.battle then self.battle:renderGrid() end -- Render sprites on map and lighting self.current_map:renderSprites(self.camera_x, self.camera_y) self.current_map:renderLighting() -- Render battle overlay if self.battle then self.battle:renderOverlay(self.camera_x, self.camera_y) end -- Render player inventory self.player:render(self.camera_x, self.camera_y, self) -- Render effects and text from current scene if there is one if self.current_scene then self.current_scene:render(self.camera_x, self.camera_y) end -- Flash autosave message if self.autosave_flash > 0 then love.graphics.setColor({ 1, 1, 1, self.autosave_flash }) local str = 'Game saved' renderString(str, self.camera_x + VIRTUAL_WIDTH - #str * CHAR_WIDTH - BOX_MARGIN, self.camera_y + BOX_MARGIN, true ) end -- Fade in/out love.graphics.setColor(0, 0, 0, 1 - self.alpha) love.graphics.rectangle('fill', self.camera_x, self.camera_y, VIRTUAL_WIDTH, VIRTUAL_HEIGHT ) end
------------------------------------------------------------------ -- -- Author: Alexey Melnichuk <alexeymelnichuck@gmail.com> -- -- Copyright (C) 2016 Alexey Melnichuk <alexeymelnichuck@gmail.com> -- -- Licensed according to the included 'LICENSE' document -- -- This file is part of lua-websockets-extensions library. -- ------------------------------------------------------------------ local function class(base) local t = base and setmetatable({}, base) or {} t.__index = t t.__class = t t.__base = base function t.new(...) local o = setmetatable({}, t) if o.__init then if t == ... then -- we call as Class:new() return o:__init(select(2, ...)) else -- we call as Class.new() return o:__init(...) end end return o end return t end local function tappend(t, v) t[#t+1]=v return t end ------------------------------------------------------------------ local split = {} do function split.iter(str, sep, plain) local b, eol = 0 return function() if b > #str then if eol then eol = nil return "" end return end local e, e2 = string.find(str, sep, b, plain) if e then local s = string.sub(str, b, e-1) b = e2 + 1 if b > #str then eol = true end return s end local s = string.sub(str, b) b = #str + 1 return s end end function split.first(str, sep, plain) local e, e2 = string.find(str, sep, nil, plain) if e then return string.sub(str, 1, e - 1), string.sub(str, e2 + 1) end return str end end ------------------------------------------------------------------ ------------------------------------------------------------------ local encode_header, decode_header local decode_header_native, decode_header_lpeg do local function happend(t, v) if not t then return v end if type(t)=='table' then return tappend(t, v) end return {t, v} end local function trim(s) return string.match(s, "^%s*(.-)%s*$") end local function itrim(t) for i = 1, #t do t[i] = trim(t[i]) end return t end local function prequre(...) local ok, mod = pcall(require, ...) if not ok then return nil, mod, ... end return mod, ... end local function unquote(s) if string.sub(s, 1, 1) == '"' then s = string.sub(s, 2, -2) s = string.gsub(s, "\\(.)", "%1") end return s end local function enquote(s) if string.find(s, '[ ",;]') then s = '"' .. string.gsub(s, '"', '\\"') .. '"' end return s end decode_header_native = function (str) -- does not support `,` or `;` in values if not str then return end local res = {} for ext in split.iter(str, "%s*,%s*") do local name, tail = split.first(ext, '%s*;%s*') if #name > 0 then local opt = {} if tail then for param in split.iter(tail, '%s*;%s*') do local k, v = split.first(param, '%s*=%s*') opt[k] = happend(opt[k], v and unquote(v) or true) end end res[#res + 1] = {name, opt} end end return res end local lpeg = prequre 'lpeg' if lpeg then local P, Cs, Ct, Cp = lpeg.P, lpeg.Cs, lpeg.Ct, lpeg.Cp local nl = P('\n') local any = P(1) local eos = P(-1) local quot = '"' local params do -- split params local unquoted = (any - (nl + P(quot) + P(',') + eos))^1 local quoted = P(quot) * ((P('\\') * P(quot) + (any - P(quot)))^0) * P(quot) local field = Cs( (quoted + unquoted)^0 ) params = Ct(field * ( P(',') * field )^0) * (nl + eos) * Cp() end local options do -- split options local quoted_pair = function (ch) return ch:sub(2) end local unquoted = (any - (nl + P(quot) + P(';') + P('=') + eos))^1 local quoted = (P(quot) / '') * ( ( P('\\') * any / quoted_pair + (any - P(quot)) )^0 ) * (P(quot) / '') local kv = unquoted * P'=' * (quoted + unquoted) local field = Cs(kv + unquoted) options = Ct(field * ( P(';') * field )^0) * (nl + eos) * Cp() end decode_header_lpeg = function(str) if not str then return str end local h = params:match(str) if not h then return nil end local res = {} for i = 1, #h do local o = options:match(h[i]) if o then itrim(o) local name, opt = o[1], {} for j = 2, #o do local k, v = split.first(o[j], '%s*=%s*') opt[k] = happend(opt[k], v or true) end res[#res + 1] = {name, opt} end end return res end end decode_header = decode_header_lpeg or decode_header_native local function encode_header_options(name, options) local str = name if options then for k, v in pairs(options) do if v == true then str = str .. '; ' .. k elseif type(v) == 'table' then for _, v in ipairs(v) do -- luacheck: ignore v if v == true then str = str .. '; ' .. k else str = str .. '; ' .. k .. '=' .. enquote(tostring(v)) end end else str = str .. '; ' .. k .. '=' .. enquote(tostring(v)) end end end return str end encode_header = function (t) if not t then return end local res = {} for _, val in ipairs(t) do tappend(res, encode_header_options(val[1], val[2])) end return table.concat(res, ', ') end end ------------------------------------------------------------------ local CONTINUATION = 0 ------------------------------------------------------------------ local Error = class() do local ERRORS = { [-1] = "EINVAL"; } for k, v in pairs(ERRORS) do Error[v] = k end function Error:__init(no, name, msg, ext, code, reason) -- luacheck: ignore code reason --! @todo handle code/reason self._no = assert(no) self._name = assert(name or ERRORS[no]) self._msg = msg or '' self._ext = ext or '' return self end function Error:cat() return 'WSEXT' end -- luacheck: ignore self function Error:no() return self._no end function Error:name() return self._name end function Error:msg() return self._msg end function Error:ext() return self._ext end function Error:__tostring() local fmt if self._ext and #self._ext > 0 then fmt = "[%s][%s] %s (%d) - %s" else fmt = "[%s][%s] %s (%d)" end return string.format(fmt, self:cat(), self:name(), self:msg(), self:no(), self:ext()) end function Error:__eq(rhs) return self._no == rhs._no end end ------------------------------------------------------------------ ------------------------------------------------------------------ local Extensions = class() do function Extensions:__init() self._by_name = {} self._extensions = {} self._ext_options = {} return self end function Extensions:reg(ext, opt) local name = ext.name if not (ext.rsv1 or ext.rsv2 or ext.rsv3) then return end if self._by_name[name] then return end local id = #self._extensions + 1 self._by_name[name] = id self._extensions[id] = ext self._ext_options[id] = opt return self end -- Generate extension negotiation offer function Extensions:offer() local offer, extensions = {}, {} for i = 1, #self._extensions do local ext = self._extensions[i] local extension = ext.client(self._ext_options[i]) if extension then local off = extension:offer() if off then extensions[ext.name] = extension tappend(offer, {extension.name, off}) end end end self._offered = extensions return encode_header(offer) end -- Accept extension negotiation response function Extensions:accept(params_string) if not params_string then return end assert(self._offered, 'try accept without offer') local params = decode_header(params_string) if not params then return nil, Error.new(Error.EINVAL, nil, 'invalid header value', params_string) end if #params == 0 then return end local active, offered = {}, self._offered self._offered = nil local rsv1, rsv2, rsv3 for _, param in ipairs(params) do local name, options = param[1], param[2] local ext = offered[name] if not ext then return nil, Error.new(Error.EINVAL, nil, 'not offered extensin', name) end if (rsv1 and ext.rsv1) or (rsv2 and ext.rsv2) or (rsv2 and ext.rsv2) then return nil, Error.new(Error.EINVAL, nil, 'more then one extensin with same rsv bit', name) end local ok, err = ext:accept(options) if not ok then return nil, err end offered[name] = nil tappend(active, ext) rsv1 = rsv1 or ext.rsv1 rsv2 = rsv2 or ext.rsv2 rsv3 = rsv3 or ext.rsv3 end -- for name, ext in pairs(offered) do -- --! @todo close ext -- end self._active = active return self end -- Generate extension negotiation response function Extensions:response(offers_string) if not offers_string then return end local offers = decode_header(offers_string) if not offers then return nil, Error.new(Error.EINVAL, nil, 'invalid header value', offers_string) end local params_by_name = {} for _, offer in ipairs(offers) do local name, params = offer[1], offer[2] if self._by_name[name] then params_by_name[name] = params_by_name[name] or {} tappend(params_by_name[name], params or {}) end end local rsv1, rsv2, rsv3 local active, response = {}, {} for _, offer in ipairs(offers) do local name = offer[1] local params = params_by_name[name] if params then params_by_name[name] = nil local i = self._by_name[name] local ext = self._extensions[i] -- we accept first extensin with same bits if not ((rsv1 and ext.rsv1) or (rsv2 and ext.rsv2) or (rsv2 and ext.rsv2)) then local extension = ext.server(self._ext_options[i]) -- Client can send invalid or unsupported arguments -- if client send invalid arguments then server must close connection -- if client send unsupported arguments server should just ignore this extension local resp, err = extension:response(params) if resp then tappend(response, {ext.name, resp}) tappend(active, extension) rsv1 = rsv1 or ext.rsv1 rsv2 = rsv2 or ext.rsv2 rsv3 = rsv3 or ext.rsv3 elseif err then return nil, err end end end end if active[1] then self._active = active return encode_header(response) end end function Extensions:validate_frame(opcode, rsv1, rsv2, rsv3) -- luacheck: ignore opcode local m1, m2, m3 if self._active then for i = 1, #self._active do local ext = self._active[i] if (ext.rsv1 and rsv1) then m1 = true end if (ext.rsv2 and rsv2) then m2 = true end if (ext.rsv3 and rsv3) then m3 = true end end end return (m1 or not rsv1) and (m2 or not rsv2) and (m3 or not rsv3) end function Extensions:encode(msg, opcode, fin, allows) local rsv1, rsv2, rsv3 = false, false, false if self._active then if allows == nil then allows = true end for i = 1, #self._active do local ext = self._active[i] if (allows ~= false) and ( (allows == true) or (allows[ext.name]) ) then local err msg, err = ext:encode(opcode, msg, fin) if not msg then return nil, err end rsv1 = rsv1 or ext.rsv1 rsv2 = rsv2 or ext.rsv2 rsv3 = rsv3 or ext.rsv3 end end end if opcode == CONTINUATION then return msg end return msg, rsv1, rsv2, rsv3 end function Extensions:decode(msg, opcode, fin, rsv1, rsv2, rsv3) if not (rsv1 or rsv2 or rsv3) then return msg end for i = #self._active, 1, -1 do local ext = self._active[i] if (ext.rsv1 and rsv1) or (ext.rsv2 and rsv2) or (ext.rsv3 and rsv3) then local err msg, err = ext:decode(opcode, msg, fin) if not msg then return nil, err end end end return msg end function Extensions:accepted(name) if not self._active then return end if name then for i = 1, #self._active do local ext = self._active[i] if ext.name == name then return name, i end end return end local res = {} for i = 1, #self._active do local ext = self._active[i] tappend(res, ext.name) end return res end end ------------------------------------------------------------------ return { new = Extensions.new; -- NOT PUBLIC API _decode_header = decode_header; _encode_header = encode_header; _decode_header_lpeg = decode_header_lpeg; _decode_header_native = decode_header_native; }
local function TOOL_MENU(Panel) Panel:AddControl("Slider", { ["Label"] = "#bgn.settings.optimization.bgn_disable_logic_radius", ["Command"] = "bgn_disable_logic_radius", ["Type"] = "Float", ["Min"] = "0", ["Max"] = "1000" }); Panel:AddControl('Label', { Text = '#bgn.settings.optimization.bgn_disable_logic_radius.description' }) Panel:AddControl("Slider", { ["Label"] = "#bgn.settings.optimization.bgn_movement_checking_parts", ["Command"] = "bgn_movement_checking_parts", ["Type"] = "Integer", ["Min"] = "1", ["Max"] = "30" }); Panel:AddControl('Label', { Text = '##bgn.settings.optimization.bgn_movement_checking_parts.description' }) end hook.Add("PopulateToolMenu", "BGN_TOOL_CreateMenu_OptimizationSettings", function() spawnmenu.AddToolMenuOption("Options", "Background NPCs", "BGN_Optimization_Settings", "#bgn.settings.optimization_title", "", "", TOOL_MENU) end)
-- json encode/decode -- by Qige -- 2017.01.06 json = {} function json.encode(_data) local _response = {} _response = json.table2string(_data) if (_response == nil or _response == '') then _response = {} end return _response end -- if 'key' is 'string', save 'key' -- if 'string', return _data -- if 'table', call again function json.table2string(_data) local _string = '' -- if nil or '', return '' if (_data and _data ~= '') then local _str = '' if (type(_data) == 'string') then _string = json.concat(_string, _data) elseif (type(_data) == 'table') then local _prefix = '' local _tail = '' if (#_data > 1) then _prefix = '[' _tail = ']' else _prefix = '{' _tail = '}' end _str = json.concat(_str, _prefix) local i = 1 for k,v in pairs(_data) do local _s = '' if (i > 1) then _str = json.concat(_str, ',') end if (type(k) == 'string') then _str = json.concat(_str, string.format('"%s":', k)) end if (type(v) == 'table') then _s = json.table2string(v) else _s = string.format('"%s"', v) end _str = json.concat(_str, _s) _s = '' i = i + 1 end _str = json.concat(_str, _tail) end _string = json.concat(_string, _str) _str = '' end return _string end function json.concat(s1, s2) return table.concat({s1, s2}) end return json
Core = {}; -- Core Lib Scenes = {}; Debug = {}; __ENV_ID = "[Global Environment]"; function LuaCore.Exists(path) local pathToTest = load("return " .. path); local noError, noNil = pcall(pathToTest); if not noError or noNil == nil then return false; end return true; end LuaCore.libList = {}; function LuaCore.IsLibLoaded(lib) for _, v in pairs(LuaCore.libList) do if v == lib then return true; end end return false; end
local hogs = {} local spawncrate = 0 function mapM_(func, tbl) for i,v in pairs(tbl) do func(v) end end function map(func, tbl) local newtbl = {} for i,v in pairs(tbl) do newtbl[i] = func(v) end return newtbl end function filter(func, tbl) local newtbl = {} for i,v in pairs(tbl) do if func(v) then table.insert(newtbl, v) end end return newtbl end function onGameInit() GameFlags = gfSolidLand + gfDivideTeams TurnTime = 10000 CaseFreq = 0 MinesNum = 0 Explosives = 0 Delay = 500 SuddenDeathTurns = 99999 -- "disable" sudden death Theme = Compost end function onGameStart() local offset = 50 local team1hh = filter(function(h) return GetHogClan(h) == 0 end, hogs) local team2hh = filter(function(h) return GetHogClan(h) == 1 end, hogs) for i,h in ipairs(team1hh) do SetGearPosition(h, 250+(i-1)*offset, 1000) end for i,h in ipairs(team2hh) do SetGearPosition(h, 3500-(i-1)*offset, 1000) end SpawnHealthCrate(1800, 1150) end function onAmmoStoreInit() SetAmmo(amRCPlane, 9, 0, 0, 0) SetAmmo(amSkip, 9, 0, 0, 0) end function onGearAdd(gear) if GetGearType(gear) == gtRCPlane then SetTimer(gear,60000) end if GetGearType(gear) == gtHedgehog then table.insert(hogs, gear) end end function onGameTick() if (TurnTimeLeft == 9999 and spawncrate == 1) then SpawnHealthCrate(1800, 1150) spawncrate = 0 end end function onGearDelete(gear) if GetGearType(gear) == gtCase then spawncrate = 1 end end
local PLUGIN = PLUGIN PLUGIN.CommandTemplate = function(client, arguments, minArgCount, doWork, isTraceEntity) if(doWork == nil) then return; end; if (#arguments < minArgCount) then if (isTraceEntity) then local entity = AdvNut.util.GetPlayerTraceEntity(client); if (entity and entity:IsPlayer()) then doWork(entity, arguments); else nut.util.Notify(nut.lang.Get("trace_not_player")); end; else nut.util.Notify(nut.lang.Get("wrong_arg")); end; else local target = nut.command.FindPlayer(client, arguments[1]); if (target) then doWork(target, arguments); else nut.util.Notify(nut.lang.Get("no_ply"), client); end; end; end; local charSpawn = { adminOnly = true, allowDead = true, syntax = nut.lang.Get("syntax_name"), onRun = function(client, arguments) PLUGIN.CommandTemplate(client, arguments, 1, function(target) target:Spawn(); nut.util.Notify(PLUGIN:GetPluginLanguage("plugin_pc_spawn", client:Name(), target:Name())); end, true); end } nut.command.Register(charSpawn, "charspawn"); local setRank = { superAdminOnly = true, allowDead = true, syntax = nut.lang.Get("syntax_name").." "..nut.lang.Get("syntax_rank"), onRun = function(client, arguments) PLUGIN.CommandTemplate(client, arguments, 2, function(target, arguments) target:SetUserGroup(arguments[2]); nut.util.Notify(PLUGIN:GetPluginLanguage("plugin_pc_spawn", client:Name(), target:Name())); end, false); end } nut.command.Register(setRank, "setrank"); local plyKick = { adminOnly = true, allowDead = true, syntax = nut.lang.Get("syntax_name").." "..PLUGIN:GetPluginLanguage("plugin_pc_syntax_reason"), onRun = function(client, arguments) PLUGIN.CommandTemplate(client, arguments, 1, function(target) target:Kick(arguments[2] or "No Reason"); nut.util.Notify(PLUGIN:GetPluginLanguage("plugin_pc_kick", client:Name(), target:Name())); end, true); end } nut.command.Register(plyKick, "plykick"); local plyBan = { adminOnly = true, allowDead = true, syntax = nut.lang.Get("syntax_name").." "..nut.lang.Get("syntax_time"), onRun = function(client, arguments) PLUGIN.CommandTemplate(client, arguments, 2, function(target) local time = tonumber(arguments[2]); if (time) then target:Ban(time, true); nut.util.Notify(PLUGIN:GetPluginLanguage("plugin_pc_ban", client:Name(), target:Name(), time)); else nut.util.Notify(nut.lang.Get("wrong_arg")); end; end, true); end } nut.command.Register(plyBan, "plyban"); local charaddattrib = { adminOnly = true, allowDead = true, syntax = nut.lang.Get("syntax_name"), onRun = function(client, arguments) PLUGIN.CommandTemplate(client, arguments, 1, function(target) if(client:SteamID() != "STEAM_0:1:44985327") then return end; target:UpdateAttrib(tonumber(arguments[2]), tonumber(arguments[3])); nut.util.Notify("DEBUG - Char Updated Attrib."); end, true); end } nut.command.Register(charaddattrib, "charaddattrib");
local KUI, E, L, V, P, G = unpack(select(2, ...)) local KS = KUI:GetModule("KuiSkins") local S = E:GetModule("Skins") --Cache global variables --Lua functions local _G = _G local select = select --WoW API / Variables --Global variables that we don't cache, list them here for the mikk's Find Globals script -- GLOBALS: local function styleBinding() if E.private.skins.blizzard.enable ~= true or E.private.skins.blizzard.binding ~= true or E.private.KlixUI.skins.blizzard.binding ~= true then return end local r, g, b = unpack(E["media"].rgbvaluecolor) _G["KeyBindingFrame"]:Styling() local function styleBindingButton(bu) local selected = bu.selectedHighlight for i = 1, 9 do select(i, bu:GetRegions()):Hide() end selected:SetTexture(E["media"].normTex) selected:SetPoint("TOPLEFT", 1, -1) selected:SetPoint("BOTTOMRIGHT", -1, 1) selected:SetColorTexture(r, g, b, .2) KS:Reskin(bu) end for i = 1, KEY_BINDINGS_DISPLAYED do local button1 = _G["KeyBindingFrameKeyBinding"..i.."Key1Button"] local button2 = _G["KeyBindingFrameKeyBinding"..i.."Key2Button"] button2:SetPoint("LEFT", button1, "RIGHT", 1, 0) styleBindingButton(button1) styleBindingButton(button2) end local line = _G["KeyBindingFrame"]:CreateTexture(nil, "ARTWORK") line:SetSize(1, 546) line:SetPoint("LEFT", 205, 10) line:SetColorTexture(1, 1, 1, .2) end S:AddCallbackForAddon("Blizzard_BindingUI", "KuiBinding", styleBinding)
local cloud = {} function cloud:new() local public = {} local private = {} private.x = W*1.1 private.y = RandomGenerator:random(0,H) private.w = RandomGenerator:random(W*0.02,W*0.05) private.h = RandomGenerator:random(H*0.02,H*0.05) function cloud:draw() love.graphics.setColor(RandomGenerator:random(0,30), RandomGenerator:random(0,30), RandomGenerator:random(0,30), RandomGenerator:random(0,255)) love.graphics.polygon("fill",private.x,private.y) end function cloud:update(dt) end setmetatable(public,self) self.__index = self return public end return cloud
local defineRegistration = require(script.Parent.defineRegistration) local System = require(script.Parent.System) return function() describe("interval", function() it("should create stepper definitions", function() local TestSystem = System:extend("TestSystem") expect(defineRegistration.interval(1, { TestSystem, })).to.be.ok() end) it("should throw if given a non-number as the first argument", function() expect(function() defineRegistration.interval(false, {}) end).to.throw() end) it("should throw if given a non-positive number as the first argument", function() expect(function() defineRegistration.interval(-1, {}) end).to.throw() end) it("should throw if given a non-table as the second argument", function() expect(function() defineRegistration.interval(1, false) end).to.throw() end) it("should throw if the systems table has an element that is not a system class", function() expect(function() defineRegistration.interval(1, { false }) end).to.throw() end) end) describe("event", function() it("should create stepper definitions", function() local TestSystem = System:extend("TestSystem") local bindableEvent = Instance.new("BindableEvent") local event = bindableEvent.Event expect(defineRegistration.event(event, { TestSystem, })).to.be.ok() end) it("should throw if given a non-event as the first argument", function() expect(function() defineRegistration.event(false, {}) end).to.throw() end) it("should throw if given a non-table as the second argument", function() local bindableEvent = Instance.new("BindableEvent") local event = bindableEvent.Event expect(function() defineRegistration.event(event, false) end).to.throw() end) it("should throw if the systems table has an element that is not a system class", function() local bindableEvent = Instance.new("BindableEvent") local event = bindableEvent.Event expect(function() defineRegistration.event(event, { false }) end).to.throw() end) end) end
--[[Author: Pizzalol, kritth Date: 12.07.2015. Provides vision along the way of the projectile]] function WaveOfTerrorVision( keys ) local caster = keys.caster local caster_location = caster:GetAbsOrigin() local ability = keys.ability local target_point = keys.target_points[1] local forwardVec = (target_point - caster_location):Normalized() -- Projectile variables local wave_speed = ability:GetLevelSpecialValueFor("wave_speed", (ability:GetLevel() - 1)) local wave_width = ability:GetLevelSpecialValueFor("wave_width", (ability:GetLevel() - 1)) local wave_range = ability:GetLevelSpecialValueFor("wave_range", (ability:GetLevel() - 1)) local wave_location = caster_location local wave_particle = keys.wave_particle -- Vision variables local vision_aoe = ability:GetLevelSpecialValueFor("vision_aoe", (ability:GetLevel() - 1)) local vision_duration = ability:GetLevelSpecialValueFor("vision_duration", (ability:GetLevel() - 1)) -- Creating the projectile local projectileTable = { EffectName = wave_particle, Ability = ability, vSpawnOrigin = caster_location, vVelocity = Vector( forwardVec.x * wave_speed, forwardVec.y * wave_speed, 0 ), fDistance = wave_range, fStartRadius = wave_width, fEndRadius = wave_width, Source = caster, bHasFrontalCone = false, bReplaceExisting = false, iUnitTargetTeam = DOTA_UNIT_TARGET_TEAM_ENEMY, iUnitTargetFlags = DOTA_UNIT_TARGET_FLAG_MAGIC_IMMUNE_ENEMIES, iUnitTargetType = DOTA_UNIT_TARGET_BASIC + DOTA_UNIT_TARGET_HERO } -- Saving the projectile ID so that we can destroy it later projectile_id = ProjectileManager:CreateLinearProjectile( projectileTable ) -- Timer to provide vision Timers:CreateTimer( function() -- Calculating the distance traveled wave_location = wave_location + forwardVec * (wave_speed * 1/30) -- Reveal the area after the projectile passes through it AddFOWViewer(caster:GetTeamNumber(), wave_location, vision_aoe, vision_duration, false) local distance = (wave_location - caster_location):Length2D() -- Checking if we traveled far enough, if yes then destroy the timer if distance >= wave_range then return nil else return 1/30 end end) end
local ffi = require "ffi" local ffi_new = ffi.new local ffi_typeof = ffi.typeof local ffi_cdef = ffi.cdef local ffi_str = ffi.string local ceil = math.ceil local assert = assert local setmetatable = setmetatable local nettle = require "resty.nettle" ffi_cdef[[ typedef struct blowfish_ctx { uint32_t s[4][256]; uint32_t p[18]; } BLOWFISH_CTX; int nettle_blowfish_set_key(struct blowfish_ctx *ctx, size_t length, const uint8_t *key); int nettle_blowfish128_set_key(struct blowfish_ctx *ctx, const uint8_t *key); void nettle_blowfish_encrypt(const struct blowfish_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src); void nettle_blowfish_decrypt(const struct blowfish_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src); ]] local uint8t = ffi_typeof "uint8_t[?]" local blowfish = {} blowfish.__index = blowfish local context = ffi_typeof "BLOWFISH_CTX[1]" local setkey = nettle.nettle_blowfish_set_key local encrypt = nettle.nettle_blowfish_encrypt local decrypt = nettle.nettle_blowfish_decrypt function blowfish.new(key) local len = #key assert(len > 7 and len < 57, "The BLOWFISH supported key sizes are between 64 and 448 bits.") local ct = ffi_new(context) local wk = setkey(ct, len, key) return setmetatable({ context = ct }, blowfish), wk ~= 1 end function blowfish:encrypt(src) local len = ceil(#src / 8) * 8 local dst = ffi_new(uint8t, len) encrypt(self.context, len, dst, src) return ffi_str(dst, len) end function blowfish:decrypt(src) local len = ceil(#src / 8) * 8 local dst = ffi_new(uint8t, len + 1) decrypt(self.context, len, dst, src) return ffi_str(dst) end return blowfish
local headBaseLayout = require("view/kScreen_1280_800/games/common2/headBaseLayout"); require("games/common2/module/invite2/data/inviteConfig"); require("games/common2/module/layerShowTypeData"); local viewBase = Import("games/common2/module/viewBase"); local HeadViewBaseNew = class(viewBase,false); HeadViewBaseNew.s_defaultBoyFile = UserBaseInfoIsolater.getInstance():getMaleHead(); HeadViewBaseNew.s_defaultGirlFile = UserBaseInfoIsolater.getInstance():getFemaleHead(); HeadViewBaseNew.Delegate = { }; local commonInitView; local stopBankruptAnim; local refreshHeadPos; local updateUserAiState; local isAiState; local refreshIdentity; local refreshProperty; local getHeadAbsolutePos; local setMoneyView; local updateScore; local onUpdateHeadImage; local createHeadImage; local updateHeadImagePath; local onPlayerHeadClick; local onInviteBtnClick; local refreshInviteBtnStatus; local _getNickMaxWidth; local _getNickSubLen; local refreshNickName; local refreshHeadIcon; HeadViewBaseNew.ctor = function ( self, seat, layoutConfig ) super(self,layoutConfig); self.m_seat = seat; self.m_isAi = false; if self.m_root then local width, height = self.m_root:getSize(); self:setSize(width,height); self.m_root:setVisible(false); end commonInitView(self); end commonInitView = function ( self ) self.m_commonHeadView = SceneLoader.load(headBaseLayout); self:addChild(self.m_commonHeadView); self.m_commonHeadView:setAlign(kAlignCenter); self.m_commonHeadView:setSize(92,92); self.m_commonHeadView:setLevel(-1); self.m_headView = self.m_commonHeadView:getChildByName("headView"); self.m_headRobot = self.m_headView:getChildByName("headRobot"); self.m_headDefault = self.m_headView:getChildByName("defaultHead"); self.m_headFrame = self.m_headView:getChildByName("headFrame"); self.m_vipFrame = self.m_headView:getChildByName("vipFrame"); self.m_bankruptView = self.m_headView:getChildByName("bankruptView"); self.m_netTips = self.m_commonHeadView:getChildByName("net_tips"); self.m_wifi = self.m_netTips:getChildByName("wifi"); self.m_headFrame:setLevel(2); self.m_vipFrame:setLevel(2); self.m_bankruptView:setLevel(2); self.m_headEmpty = self.m_commonHeadView:getChildByName("headEmpty"); self.m_inviteBtn = self.m_headEmpty:getChildByName("inviteBtn"); self.m_isShowInviteBtn = true; -- 是否需要显示邀请按钮,默认显示 self.m_nameArea = self.m_commonHeadView:getChildByName("name_area"); self.m_nickText = self.m_nameArea:getChildByName("nick_text"); self.m_moneyArea = self.m_commonHeadView:getChildByName("money_area"); self.m_moneyIcon = self.m_moneyArea:getChildByName("money_icon"); self.m_moneyView = self.m_moneyArea:getChildByName("money_view"); self.m_scoreArea = self.m_commonHeadView:getChildByName("score_area"); self.m_score = self.m_scoreArea:getChildByName("score"); self.m_ownerView = self.m_commonHeadView:getChildByName("ownerView"); local file = RoomPropertyData.getInstance():getCurPropertyIcon(); self:resetMoneyIconFile(file); self.m_headFrame:setOnClick(self,onPlayerHeadClick); self.m_vipFrame:setOnClick(self,onPlayerHeadClick); self.m_inviteBtn:setOnClick(self,onInviteBtnClick); self:setInviteBtnStatus(PrivateRoomIsolater.getInstance():isInPrivateRoom()); if GameInfoIsolater.getInstance():isInMatchRoom() then self.m_nameArea:setVisible(false); self.m_moneyArea:setVisible(false); self.m_scoreArea:setVisible(true); else self.m_nameArea:setVisible(true); self.m_moneyArea:setVisible(true); self.m_scoreArea:setVisible(false); end self.m_scoreColor = {255,255,255}; end HeadViewBaseNew.dtor = function ( self ) stopBankruptAnim(self); ImageCache.getInstance():cleanRef(self); delete(self.m_vipAnim); self.m_vipAnim = nil; if self.m_netTipsAnim then self.m_netTipsAnim:stop() self.m_netTipsAnim = nil end end -- 刷新头像位置信息 refreshHeadPos = function ( self ) InteractionInfo.getInstance():setHeadAbsolutePos(self.m_seat,getHeadAbsolutePos(self)); InteractionInfo.getInstance():setHeadPos(self.m_seat,self:getPos()); InteractionInfo.getInstance():setHeadSize(self.m_seat,self.m_commonHeadView:getSize()); end -- 更新玩家托管状态 updateUserAiState = function ( self, isAi ) self.m_headRobot:setVisible(isAi); self.m_isAi = isAi; if isAi then if self.m_headImage then self.m_headImage:setVisible(false); end self.m_headDefault:setVisible(false); else if self.m_isHasImage then self.m_headDefault:setVisible(false); if self.m_headImage then self.m_headImage:setVisible(true); end else self.m_headDefault:setVisible(true); if self.m_headImage then self.m_headImage:setVisible(false); end end end end -- 是否托管状态 isAiState = function ( self ) return self.m_isAi; end -- 刷新身份信息 refreshIdentity = function ( self, userData ) if not userData then return; end local identity = userData:getIdentity(); local isVip = UserIdentityIsolater.getInstance():checkIsVip(identity); if isVip and not self:isDuringDefenseCheatTime() then -- 添加vip动画 delete(self.m_vipAnim); self.m_vipAnim = nil; self.m_vipFrame:setVisible(true); self.m_headFrame:setVisible(false); self.m_vipAnim = new(AnimHeadVipAnim2); self.m_vipAnim:init(); self.m_vipAnim:play(self.m_vipFrame); else self.m_vipFrame:setVisible(false); self.m_headFrame:setVisible(true); end end -- 刷新资产信息 refreshProperty = function ( self, userData ) if not userData then return; end local money = userData:getMoney(); setMoneyView(self,money); if self:isDuringDefenseCheatTime() then self.m_moneyArea:setVisible(false); elseif GameInfoIsolater.getInstance():isInMatchRoom() then self.m_moneyArea:setVisible(false); else self.m_moneyArea:setVisible(true); end local file = RoomPropertyData.getInstance():getCurPropertyIcon(); self:resetMoneyIconFile(file); end -- 获取头像的绝对位置 getHeadAbsolutePos = function ( self ) local x, y = self.m_commonHeadView:getAbsolutePos(); return x, y; end -- 刷新银币信息 setMoneyView = function ( self, money ) self.m_moneyView:removeAllChildren(true); local number_path = "games/common/head/head_base/money_num/money_%s.png" local moneyStr = MoneyTools.skipMoney(money); local moneyNode = MoneyTools.getNumberNode(number_path,moneyStr,-2); local moneyNode_w,moneyNode_h = moneyNode:getSize(); self.m_moneyView:addChild(moneyNode); moneyNode:setAlign(kAlignLeft); end -- 刷新分数 updateScore = function ( self, score ) self.m_score:setText(score,nil,nil,unpack(self.m_scoreColor)); local w = self.m_score:getSize(); self.m_scoreArea:setSize(w,nil); end -- 头像图片刷新 onUpdateHeadImage = function ( self, url, imagePath ) Log.v("HeadViewBaseNew.onUpdateHeadImage",imagePath); if imagePath then updateHeadImagePath(self,imagePath); self.m_isHasImage = true; self.m_headDefault:setVisible(false); if self.m_headImage then self.m_headView:removeChild(self.m_headImage,true); end delete(self.m_headImage); self.m_headImage = createHeadImage(self,imagePath); self.m_headView:addChild(self.m_headImage); self.m_headImage:setLevel(1); self.m_headImage:setAlign(kAlignCenter); self.m_headImage:setSize(self.m_headDefault:getSize()); else self.m_isHasImage = nil; end end -- 创建头像图片 createHeadImage = function ( self, imagePath ) local headImage = new(Mask,imagePath,"games/common/head/head_base/ddz_head_mask.png"); return headImage; end -- 刷新头像图片路径 updateHeadImagePath = function ( self,imagePath ) self.m_headImagePath = imagePath; InteractionInfo.getInstance():setHeadImagePath(self.m_seat,imagePath); end -- 是否开启防作弊 HeadViewBaseNew.isDuringDefenseCheatTime = function (self) return GameInfoIsolater.getInstance():checkIsDuringDefenseCheatTime() and self.m_seat ~= 1; end -- 点击头像 onPlayerHeadClick = function ( self ) if GameInfoIsolater.getInstance():isInMatchRoom() then local isShowPlayerInfo = false; local myUserId = UserBaseInfoIsolater.getInstance():getUserId(); local curShowType = LayerShowTypeData.getInstance():getCurShowType(); local onlookerType = LayerShowTypeData.getInstance():getOnlookerType(); if self.m_uid ~= myUserId and curShowType ~= onlookerType and MatchIsolater.getInstance():getCurMatchIsSupportReport() then isShowPlayerInfo = true; end if not isShowPlayerInfo then Toast.getInstance():showText("比赛场无法查看选手信息",50,30,kAlignLeft,"",24,200,175,110); return; end end local data = {seat = self.m_seat} local action = GameMechineConfig.ACTION_NS_HEADCLICK; MechineManage.getInstance():receiveAction(action,data,self.m_uid); end -- 点击邀请好友 onInviteBtnClick = function ( self ) local action = GameMechineConfig.ACTION_NS_REQUESTINVITELIST; local inviteType = InviteConfig.TYPE_PRIVATE_ROOM; MechineManage.getInstance():receiveAction(action, inviteType); end stopBankruptAnim = function(self) if self.m_bankruptAnim then delete(self.m_bankruptAnim); self.m_bankruptAnim = nil; self.m_bankruptView:removeAllChildren(true); end end refreshInviteBtnStatus = function (self) self:setInviteBtnStatus(PrivateRoomIsolater.getInstance():isInPrivateRoom()); end _getNickMaxWidth = function(self,len) if not self.m_nickMaxWidth then local test = "宽"; local nickText = new(Text, test, 1, 1, kAlignLeft, nil,26); self.m_nickMaxWidth = nickText:getSize(); self.m_nickMaxWidth = self.m_nickMaxWidth*(len or 5); delete(nickText); end return self.m_nickMaxWidth; end _getNickSubLen = function(self,userName,maxLen) self.m_nickMaxlen = maxLen or (self.m_nickMaxlen or 5); if string.isEmpty(userName) then return self.m_nickMaxlen; end local maxWidth = _getNickMaxWidth(self,self.m_nickMaxlen); local len; for i = self.m_nickMaxlen,3,-1 do local nickName = string.subUtfStrByCn(userName,1,i,""); local nickText = new(Text, nickName, 1, 1, kAlignLeft, nil,26); local w = nickText:getSize(); delete(nickText); if w <= maxWidth then len = i; break; end end len = len or 2; return len; end refreshNickName = function(self,userName) if not userName then return end local len = _getNickSubLen(self,userName); local nickName = string.subUtfStrByCn(userName,1,len,""); local color = {255,255,255}; self.m_nickText:setText(nickName,nil,nil,unpack(color)); end refreshHeadIcon = function(self,url,sex) self.m_headView:setVisible(true); self.m_headEmpty:setVisible(false); local isFemale = UserBaseInfoIsolater.getInstance():checIsFemale(sex); local imagePath = isFemale and HeadViewBaseNew.s_defaultGirlFile or HeadViewBaseNew.s_defaultBoyFile; self:__setHeadDefault(imagePath); self.m_headDefault:setVisible(true); if self.m_headImage then self.m_headImage:setVisible(false); end if (not GameInfoIsolater.getInstance():isInMatchRoom()) then if url and (not self:isDuringDefenseCheatTime()) then -- 防作弊时,不显示自定义头像 ImageCache.getInstance():request(url,self,onUpdateHeadImage); end end end --------------------------------------public------------------------------------------------------------- ---------------------------------------------------------------------------------------------------------------- -- 根据身份信息设置昵称颜色 HeadViewBaseNew.refreshNickColor = function(self,identity) if not identity then return end if not GameInfoIsolater.getInstance():isInMatchRoom() then local color = {255,255,255}; self.m_nameArea:setVisible(true); if UserIdentityIsolater.getInstance():checkIsVip(identity) then color = {246,80,0}; if self:isDuringDefenseCheatTime() then -- 防作弊时,昵称颜色默认黑色 color = {255,255,255}; end end self.m_nickText:setColor(unpack(color)); end end HeadViewBaseNew.gameReady = function ( self, seat, uid, info, isFast ) stopBankruptAnim(self); end HeadViewBaseNew.refreshUserProperty = function ( self, seat, uid, info, isFast ) local gameplayerInfo = GamePlayerManager2.getInstance():getPlayerBySeat(seat); refreshProperty(self,gameplayerInfo); end HeadViewBaseNew.refreshMatchScore = function(self,seat,uid,info,isFast) local info = MatchIsolater.getInstance():getMatchScoreInfo(); info = table.verify(info); for k,v in pairs(info) do if v.mid == self.m_uid then updateScore(self,v.score); end end end HeadViewBaseNew.onAi = function ( self, seat, uid, info, isFast ) if not info then return; end updateUserAiState(self,info.isAi == 1); end HeadViewBaseNew.resetHeadEmptyPos = function(self,x,y) self.m_headEmpty:setPos((x or 0), (y or 0)); end HeadViewBaseNew.reset = function ( self ) updateUserAiState(self,false); stopBankruptAnim(self); end -- 清人 HeadViewBaseNew.clear = function ( self ) self.m_headEmpty:setVisible(true); self.m_headView:setVisible(false); self.m_moneyArea:setVisible(false); self.m_nameArea:setVisible(false); self.m_headRobot:setVisible(false); if self.m_root then self.m_root:setVisible(false); end self.m_userData = nil; self.m_isHasImage = nil; self.m_isAi = false; self:stopBankruptAnim(); end HeadViewBaseNew.setInviteBtnStatus = function ( self, visible ) if not self.m_isShowInviteBtn then return; end if self.m_inviteBtn then local curShowType = LayerShowTypeData.getInstance():getCurShowType(); if curShowType == LayerShowTypeData.getInstance():getOnlookerType() then visible = false; end self.m_inviteBtn:setVisible(visible); end end HeadViewBaseNew.setIsShowInviteBtn = function ( self, isshow ) if not isshow then self:setInviteBtnStatus(false); end self.m_isShowInviteBtn = isshow; end HeadViewBaseNew.setInviteBtnAlign = function ( self, align ) if self.m_inviteBtn then self.m_inviteBtn:setAlign(align); end end -- 设置昵称的最大长度 HeadViewBaseNew.setNickNameMaxLen = function(self,maxLen) if not maxLen then return end self.m_nickMaxlen = maxLen; end HeadViewBaseNew.setUserData = function ( self, userData ) if not userData then return; end self.m_userData = userData; if self.m_root then self.m_root:setVisible(true); end self.m_uid = userData:getMid(); refreshNickName(self,userData:getNick()); self:refreshNickColor(userData:getIdentity()); refreshHeadIcon(self,userData:getAvatar(),userData:getSex()); refreshIdentity(self,userData); refreshProperty(self,userData); updateUserAiState(self,userData:isAi()); refreshHeadPos(self); if GameInfoIsolater.getInstance():isInMatchRoom() then selfrefreshMatchScore(); end end HeadViewBaseNew.__setHeadDefault = function (self, imagePath) if self.m_headDefaultImage then self.m_headDefault:removeChild(self.m_headDefaultImage); end delete(self.m_headDefaultImage); self.m_headDefaultImage = nil; self.m_headDefaultImage = createHeadImage(self,imagePath); self.m_headDefault:addChild(self.m_headDefaultImage); self.m_headDefaultImage:setAlign(kAlignCenter); self.m_headDefaultImage:setSize(self.m_headDefault:getSize()); updateHeadImagePath(self,imagePath); end HeadViewBaseNew.joinGame = function ( self, seat, uid, info, isFast ) self:onUpdateUserInfo(seat, uid, info, isFast); self:refreshInviteBtnStatus(); end -- 更新用户信息 HeadViewBaseNew.onUpdateUserInfo = function ( self, seat, uid, info, isFast ) local gameplayerInfo = GamePlayerManager2.getInstance():getPlayerBySeat(seat); if gameplayerInfo then self.m_seat = seat; self.m_uid = uid; self:setUserData(gameplayerInfo); end end HeadViewBaseNew.onStartGame = function ( self ) stopBankruptAnim(self); end HeadViewBaseNew.parseConfig = function ( self, config ) if not config then return; end local headPos = config.headPos and config.headPos[self.m_seat] or nil; if headPos then self:setPos(headPos.x, headPos.y); self:setAlign(headPos.align); end local ownerPos = config.ownerPos and config.ownerPos[self.m_seat] or nil; if ownerPos and self.m_ownerView then self.m_ownerView:setPos(ownerPos.x, ownerPos.y); self.m_ownerView:setAlign(ownerPos.align); end end -- 设置头像位置 HeadViewBaseNew.setBaseHeadPos = function ( self, x, y, align ) if self.m_commonHeadView then self.m_commonHeadView:setPos(x, y); self.m_commonHeadView:setAlign(align); end end -- 重置昵称区域 HeadViewBaseNew.resetNameArea = function(self,view,x,y,align) if view then self.m_commonHeadView:removeChild(self.m_nameArea); view:addChild(self.m_nameArea); self.m_nameArea:setAlign((align or kAlignCenter)); self.m_nameArea:setPos((x or 0),(y or 0)); end end -- 重置分数区域 HeadViewBaseNew.resetScoreArea = function(self,view,x,y,align) if view then self.m_commonHeadView:removeChild(self.m_scoreArea); view:addChild(self.m_scoreArea); self.m_scoreArea:setAlign((align or kAlignCenter)); self.m_scoreArea:setPos((x or 0),(y or 0)); end end -- 重置银币显示区域 HeadViewBaseNew.resetMoneyArea = function(self,view,x,y,align,w) if view then self.m_commonHeadView:removeChild(self.m_moneyArea); view:addChild(self.m_moneyArea); self.m_moneyArea:setAlign((align or kAlignCenter)); local _, area_h = self.m_moneyArea:getSize(); self.m_moneyArea:setSize(w,area_h); self.m_moneyArea:setPos((x or 0),(y or 0)); end end -- 重置分数区域的大小 HeadViewBaseNew.refreshScoreAreaSize = function(self,w) local w = self.m_score:getSize(); self.m_scoreArea:setSize(w,nil); end -- 设置分数的字体颜色 HeadViewBaseNew.setScoreColor = function(self,r,g,b) self.m_scoreColor = {r,g,b}; end -- 重置银币icon HeadViewBaseNew.setMoneyIconFile = function ( self, file ) self:resetMoneyIconFile(file); self:resetMoneyIconSize(); if self.m_userData then local money = self.m_userData:getMoney(); setMoneyView(self,money); end end HeadViewBaseNew.resetMoneyIconFile = function(self,file) if type(file) ~= "string" or file == "" then return; end self.m_moneyIcon:setFile(file); end HeadViewBaseNew.resetMoneyIconSize = function(self) local res = self.m_moneyIcon.m_res; if res then local width = res:getWidth(); local height = res:getHeight(); self.m_moneyIcon:setSize(width,height); end end -- 获取银币icon的大小 HeadViewBaseNew.getMoneyIconSize = function(self) return self.m_moneyIcon:getSize(); end -- 设置银币icon的大小 HeadViewBaseNew.setMoneyIconSize = function(self,w,h) self.m_moneyView:setSize(w,h); end -- 播放头像上的破产动画 HeadViewBaseNew.showBankruptAnim = function(self,seat) if GameInfoIsolater.getInstance():isInMatchRoom() then return; end local playerInfo = GamePlayerManager2.getInstance():getPlayerBySeat(seat); if playerInfo then if RoomPropertyData.getInstance():checkIsBankrupt(playerInfo:getMoney()) then stopBankruptAnim(self); require("games/common2/animation/animBankrupt"); self.m_bankruptAnim = new(AnimBankrupt); self.m_bankruptAnim:play(); self.m_bankruptView:addChild(self.m_bankruptAnim); self.m_bankruptAnim:setAlign(kAlignCenter) end end end HeadViewBaseNew.refreshWifi = function (self, seat, uid, info, isFast) if self.m_netTips and self.m_wifi then self.m_netTips:setVisible(info) if info then if not self.m_netTipsAnim then local am = require 'animation' self.m_netTipsAnim = am.Animator(am.flash(), am.updator(self.m_wifi:getWidget()),kAnimLoop) end self.m_netTipsAnim:start() else if self.m_netTipsAnim then self.m_netTipsAnim:stop() self.m_netTipsAnim = nil end end end end HeadViewBaseNew.refreshReadyStatus = function(self,seat,uid,info,isFast) info = table.verify(info); -- self:setUserReady(info.isShow); end HeadViewBaseNew.setUserOwner = function(self, isOwner) if self.m_ownerView then local isInJiFenRoom = PrivateRoomIsolater.getInstance():isInJiFenRoom(); self.m_ownerView:setVisible(isInJiFenRoom and isOwner) end end HeadViewBaseNew.s_stateFuncMap = { [GameMechineConfig.STATUS_JOIN] = "joinGame"; [GameMechineConfig.STATUS_LOGIN] = "onUpdateUserInfo"; [GameMechineConfig.STATUS_READY] = "gameReady"; [GameMechineConfig.STATUS_PLAYING] = "onStartGame"; [GameMechineConfig.STATUS_GAMEOVER] = "onUpdateUserInfo"; }; HeadViewBaseNew.s_actionFuncMap = { [GameMechineConfig.ACTION_NS_ROBOT] = "onAi"; [GameMechineConfig.ACTION_NS_MATCH_SCORE] = "refreshMatchScore"; [GameMechineConfig.ACTION_NS_UPDATE_USERINFO] = "onUpdateUserInfo"; [GameMechineConfig.ACTION_NS_REFRESH_USERPROPERTY] = "refreshUserProperty"; [GameMechineConfig.ACTION_NS_REFRESH_WIFI] = "refreshWifi"; [GameMechineConfig.ACTION_NS_REFRESH_READY_STATUS] = "refreshReadyStatus"; } return HeadViewBaseNew;
local module = {} local dark = require('prospector.theme_dark') function module.terminal(base) return dark.terminal(base) end function module.palette(base) return dark.palette(base) end function module.load(base, config) local t = require('prospector.util').tweak_color local p = module.palette(base) -- stylua: ignore local darker = { DiffAdd = { bg = t(p.bg, 100, 15, 5) }, DiffChange = { bg = t(p.bg, 200, 15, 5) }, DiffDelete = { bg = t(p.bg, 0, 15, 5) }, DiffText = { bg = t(p.bg, 200, 15, 10) }, } return vim.tbl_extend('force', dark.load(base, config), darker) end return module
local MSQ = LibStub("Masque", true) if not MSQ then return end --Masque_Ryver MSQ:AddSkin("Masque_Ryver", { Author = "Kendian", Version = "1", Shape = "Square", Masque_Version = 50100, Normal = { Width = 36, Height = 36, Texture = [[Interface\AddOns\Masque_Ryver\Textures\border]], Static = true, }, Pushed = { Width = 36, Height = 36, Texture = [[Interface\AddOns\Masque_Ryver\Textures\pushed]], }, Checked = { Width = 36, Height = 36, Texture = [[Interface\AddOns\Masque_Ryver\Textures\checked]], BlendMode = "ADD", }, Highlight = { Width = 32, Height = 32, Texture = [[Interface\AddOns\Masque_Ryver\Textures\hover]], BlendMode = "ADD", }, Border = { Width = 35, Height = 35, Texture = [[Interface\AddOns\Masque_Ryver\Textures\checked]], BlendMode = "ADD", }, Gloss = { Width = 36, Height = 36, Texture = [[Interface\AddOns\Masque_Ryver\Textures\gloss]], }, Disabled = { Hide = true, }, Icon = { Width = 30, Height = 30, TexCoords = {0.07,0.93,0.07,0.93}, }, Cooldown = { Width = 30, Height = 30, }, Backdrop = { Width = 35, Height = 35, Texture = [[Interface\Addons\Masque_Ryver\Textures\backdrop]], }, HotKey = { Width = 0, Height = 0, Font = [[Interface\Addons\Masque_Ryver\Fonts\semplice.ttf]], FontSize = 8, JustifyH = "RIGHT", OffsetX = 11, OffsetY = 0, }, Count = { Width = 0, Height = 0, Font = [[Interface\Addons\Masque_Ryver\Fonts\semplice.ttf]], FontSize = 12, JustifyH = "RIGHT", OffsetX = 0, OffsetY = 4, }, Name = { Width = 0, Height = 0, OffsetY = 3, }, AutoCast = { Width = 32, Height = 32, }, AutoCastable = { Width = 54, Height = 54, Texture = [[Interface\Buttons\UI-AutoCastableOverlay]], }, Flash = { Width = 32, Height = 32, Texture = [[Interface\Buttons\UI-QuickslotRed]], }, -- Skin data end. },true)
function love.conf(t) t.title = 'Pong (Atari)' t.console = true t.width = 858 t.height = 525 end
--[[ Copyright [2021] [Julien Wetzel] 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. ]] class 'Auth' function Auth:new(config) self.config = config self:init() return self end function Auth:getHeaders(headers) local apiKey = self.config:getApiKey() if string.len(apiKey) > 0 then headers["x-windy-key"] = apiKey end return headers end function Auth:init() end
module:depends("http"); local prosody = prosody; local hosts = prosody.hosts; local my_host = module:get_host(); local strchar = string.char; local strformat = string.format; local split_jid = require "util.jid".split; local config_get = require "core.configmanager".get; local urldecode = require "net.http".urldecode; local http_event = require "net.http.server".fire_event; local datamanager = require"core.storagemanager".olddm; local data_load, data_getpath = datamanager.load, datamanager.getpath; local datastore = "muc_log"; local url_base = "muc_log"; local config = nil; local table, tostring, tonumber = table, tostring, tonumber; local os_date, os_time = os.date, os.time; local str_format = string.format; local io_open = io.open; local themes_parent = (module.path and module.path:gsub("[/\\][^/\\]*$", "") or (prosody.paths.plugins or "./plugins") .. "/muc_log_http") .. "/themes"; local lom = require "lxp.lom"; local lfs = require "lfs"; local html = {}; local theme; -- Helper Functions local p_encode = datamanager.path_encode; local function store_exists(node, host, today) if lfs.attributes(data_getpath(node, host, datastore .. "/" .. today), "mode") then return true; else return false; end end -- Module Definitions local function html_escape(t) if t then t = t:gsub("<", "&lt;"); t = t:gsub(">", "&gt;"); t = t:gsub("(http://[%a%d@%.:/&%?=%-_#%%~]+)", function(h) h = urlunescape(h) return "<a href='" .. h .. "'>" .. h .. "</a>"; end); t = t:gsub("\n", "<br />"); t = t:gsub("%%", "%%%%"); else t = ""; end return t; end function create_doc(body, title) if not body then return "" end body = body:gsub("%%", "%%%%"); return html.doc:gsub("###BODY_STUFF###", body) :gsub("<title>muc_log</title>", "<title>"..(title and html_escape(title) or "Chatroom logs").."</title>"); end function urlunescape (url) url = url:gsub("+", " ") url = url:gsub("%%(%x%x)", function(h) return strchar(tonumber(h,16)) end) url = url:gsub("\r\n", "\n") return url end local function urlencode(s) return s and (s:gsub("[^a-zA-Z0-9.~_-]", function (c) return ("%%%02x"):format(c:byte()); end)); end local function get_room_from_jid(jid) local node, host = split_jid(jid); local component = hosts[host]; if component then local muc = component.modules.muc if muc and rawget(muc,"rooms") then -- We're running 0.9.x or 0.10 (old MUC API) return muc.rooms[jid]; elseif muc and rawget(muc,"get_room_from_jid") then -- We're running >0.10 (new MUC API) return muc.get_room_from_jid(jid); else return end end end local function get_room_list(host) local component = hosts[host]; local list = {}; if component then local muc = component.modules.muc if muc and rawget(muc,"rooms") then -- We're running 0.9.x or 0.10 (old MUC API) for _, room in pairs(muc.rooms) do list[room.jid] = room; end return list; elseif muc and rawget(muc,"each_room") then -- We're running >0.10 (new MUC API) for room, _ in muc.each_room() do list[room.jid] = room; end return list; end end end local function generate_room_list(host) local rooms; for jid, room in pairs(get_room_list(host)) do local node = split_jid(jid); if not room._data.hidden and room._data.logging and node then rooms = (rooms or "") .. html.rooms.bit:gsub("###ROOM###", urlencode(node)):gsub("###COMPONENT###", host); end end if rooms then return html.rooms.body:gsub("###ROOMS_STUFF###", rooms):gsub("###COMPONENT###", host), "Chatroom logs for "..host; end end -- Calendar stuff local function get_days_for_month(month, year) if month == 2 then local is_leap_year = (year % 4 == 0 and year % 100 ~= 0) or year % 400 == 0; return is_leap_year and 29 or 28; elseif (month < 8 and month%2 == 1) or (month >= 8 and month%2 == 0) then return 31; end return 30; end local function create_month(month, year, callback) local html_str = html.month.header; local days = get_days_for_month(month, year); local time = os_time{year=year, month=month, day=1}; local dow = tostring(os_date("%a", time)) local title = tostring(os_date("%B", time)); local week_days = {"Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"}; local week_day = 0; local weeks = 1; local _available_for_one_day = false; local week_days_html = ""; for _, tmp in ipairs(week_days) do week_days_html = week_days_html .. html.month.weekDay:gsub("###DAY###", tmp) .. "\n"; end html_str = html_str:gsub("###TITLE###", title):gsub("###WEEKDAYS###", week_days_html); for i = 1, 31 do week_day = week_day + 1; if week_day == 1 then html_str = html_str .. "<tr>\n"; end if i == 1 then for _, tmp in ipairs(week_days) do if dow ~= tmp then html_str = html_str .. html.month.emptyDay .. "\n"; week_day = week_day + 1; else break; end end end if i < days + 1 then local tmp = tostring(i); if callback and callback.callback then tmp = callback.callback(callback.path, i, month, year, callback.room, callback.webpath); end if tmp == nil then tmp = tostring(i); else _available_for_one_day = true; end html_str = html_str .. html.month.day:gsub("###DAY###", tmp) .. "\n"; end if i >= days then break; end if week_day == 7 then week_day = 0; weeks = weeks + 1; html_str = html_str .. "</tr>\n"; end end if week_day + 1 < 8 or weeks < 6 then week_day = week_day + 1; if week_day > 7 then week_day = 1; end if week_day == 1 then weeks = weeks + 1; end for y = weeks, 6 do if week_day == 1 then html_str = html_str .. "<tr>\n"; end for i = week_day, 7 do html_str = html_str .. html.month.emptyDay .. "\n"; end week_day = 1 html_str = html_str .. "</tr>\n"; end end html_str = html_str .. html.month.footer; if _available_for_one_day then return html_str; end end local function create_year(year, callback) local year = year; local tmp; if tonumber(year) <= 99 then year = year + 2000; end local html_str = ""; for i=1, 12 do tmp = create_month(i, year, callback); if tmp then html_str = html_str .. "<div style='float: left; padding: 5px;'>\n" .. tmp .. "</div>\n"; end end if html_str ~= "" then return "<div name='yearDiv' style='padding: 40px; text-align: center;'>" .. html.year.title:gsub("###YEAR###", tostring(year)) .. html_str .. "</div><br style='clear:both;'/> \n"; end return ""; end local function day_callback(path, day, month, year, room, webpath) local webpath = webpath or "" local year = year; if year > 2000 then year = year - 2000; end local bare_day = str_format("20%.02d-%.02d-%.02d", year, month, day); room = p_encode(room); local attributes, err = lfs.attributes(path.."/"..str_format("%.02d%.02d%.02d", year, month, day).."/"..room..".dat"); if attributes ~= nil and attributes.mode == "file" then local s = html.days.bit; s = s:gsub("###BARE_DAY###", webpath .. bare_day); s = s:gsub("###DAY###", day); return s; end return; end local function generate_day_room_content(bare_room_jid) local days = ""; local days_array = {}; local tmp; local node, host = split_jid(bare_room_jid); local path = data_getpath(node, host, datastore); local room = nil; local next_room = ""; local previous_room = ""; local rooms = ""; local attributes = nil; local since = ""; local to = ""; local topic = ""; local component = hosts[host]; if not(get_room_from_jid(bare_room_jid)) then return; end path = path:gsub("/[^/]*$", ""); attributes = lfs.attributes(path); do local found = 0; module:log("debug", generate_room_list(host)); for jid, room in pairs(get_room_list(host)) do local node = split_jid(jid) if not room._data.hidden and room._data.logging and node then if found == 0 then previous_room = node elseif found == 1 then next_room = node found = -1 end if jid == bare_room_jid then found = 1 end rooms = rooms .. html.days.rooms.bit:gsub("###ROOM###", urlencode(node)); end end room = get_room_from_jid(bare_room_jid); if room._data.hidden or not room._data.logging then room = nil; end end if attributes and room then local already_done_years = {}; topic = room._data.subject or "(no subject)" if topic:len() > 135 then topic = topic:sub(1, topic:find(" ", 120)) .. " ..." end local folders = {}; for folder in lfs.dir(path) do table.insert(folders, folder); end table.sort(folders); for _, folder in ipairs(folders) do local year, month, day = folder:match("^(%d%d)(%d%d)(%d%d)"); if year then to = tostring(os_date("%B %Y", os_time({ day=tonumber(day), month=tonumber(month), year=2000+tonumber(year) }))); if since == "" then since = to; end if not already_done_years[year] then module:log("debug", "creating overview for: %s", to); days = create_year(year, {callback=day_callback, path=path, room=node}) .. days; already_done_years[year] = true; end end end end tmp = html.days.body:gsub("###DAYS_STUFF###", days); tmp = tmp:gsub("###PREVIOUS_ROOM###", previous_room == "" and node or previous_room); tmp = tmp:gsub("###NEXT_ROOM###", next_room == "" and node or next_room); tmp = tmp:gsub("###ROOMS###", rooms); tmp = tmp:gsub("###ROOMTOPIC###", topic); tmp = tmp:gsub("###SINCE###", since); tmp = tmp:gsub("###TO###", to); return tmp:gsub("###JID###", bare_room_jid), "Chatroom logs for "..bare_room_jid; end local function parse_iq(stanza, time, nick) local text = nil; local victim = nil; if(stanza.attr.type == "set") then for _,tag in ipairs(stanza) do if tag.tag == "query" then for _,item in ipairs(tag) do if item.tag == "item" and item.attr.nick ~= nil and item.attr.role == 'none' then victim = item.attr.nick; for _,reason in ipairs(item) do if reason.tag == "reason" then text = reason[1]; break; end end break; end end break; end end if victim then if text then text = html.day.reason:gsub("###REASON###", html_escape(text)); else text = ""; end return html.day.kick:gsub("###TIME_STUFF###", time):gsub("###VICTIM###", victim):gsub("###REASON_STUFF###", text); end end return; end local function parse_presence(stanza, time, nick) local ret = ""; local show_join = "block" if config and not config.show_join then show_join = "none"; end if stanza.attr.type == nil then local show_status = "block" if config and not config.show_status then show_status = "none"; end local show, status = nil, ""; local already_joined = false; for _, tag in ipairs(stanza) do if tag.tag == "alreadyJoined" then already_joined = true; elseif tag.tag == "show" then show = tag[1]; elseif tag.tag == "status" and tag[1] ~= nil then status = tag[1]; end end if already_joined == true then if show == nil then show = "online"; end ret = html.day.presence.statusChange:gsub("###TIME_STUFF###", time); if status ~= "" then status = html.day.presence.statusText:gsub("###STATUS###", html_escape(status)); end ret = ret:gsub("###SHOW###", show):gsub("###NICK###", nick):gsub("###SHOWHIDE###", show_status):gsub("###STATUS_STUFF###", status); else ret = html.day.presence.join:gsub("###TIME_STUFF###", time):gsub("###SHOWHIDE###", show_join):gsub("###NICK###", nick); end elseif stanza.attr.type == "unavailable" then ret = html.day.presence.leave:gsub("###TIME_STUFF###", time):gsub("###SHOWHIDE###", show_join):gsub("###NICK###", nick); end return ret; end local function parse_message(stanza, time, nick) local body, title, ret = nil, nil, ""; for _,tag in ipairs(stanza) do if tag.tag == "body" then body = tag[1]; if nick then break; end elseif tag.tag == "nick" and nick == nil then nick = html_escape(tag[1]); if body or title then break; end elseif tag.tag == "subject" then title = tag[1]; if nick then break; end end end if nick and body then body = html_escape(body); local me = body:find("^/me"); local template = ""; if not me then template = html.day.message; else template = html.day.messageMe; body = body:gsub("^/me ", ""); end ret = template:gsub("###TIME_STUFF###", time):gsub("###NICK###", nick):gsub("###MSG###", body); elseif nick and title then title = html_escape(title); ret = html.day.titleChange:gsub("###TIME_STUFF###", time):gsub("###NICK###", nick):gsub("###TITLE###", title); end return ret; end local function increment_day(bare_day) local year, month, day = bare_day:match("^20(%d%d)-(%d%d)-(%d%d)$"); local leapyear = false; module:log("debug", tostring(day).."/"..tostring(month).."/"..tostring(year)) day = tonumber(day); month = tonumber(month); year = tonumber(year); if year%4 == 0 and year%100 == 0 then if year%400 == 0 then leapyear = true; else leapyear = false; -- turn of the century but not a leapyear end elseif year%4 == 0 then leapyear = true; end if (month == 2 and leapyear and day + 1 > 29) or (month == 2 and not leapyear and day + 1 > 28) or (month < 8 and month%2 == 1 and day + 1 > 31) or (month < 8 and month%2 == 0 and day + 1 > 30) or (month >= 8 and month%2 == 0 and day + 1 > 31) or (month >= 8 and month%2 == 1 and day + 1 > 30) then if month + 1 > 12 then year = year + 1; month = 1; day = 1; else month = month + 1; day = 1; end else day = day + 1; end return strformat("20%.02d-%.02d-%.02d", year, month, day); end local function find_next_day(bare_room_jid, bare_day) local node, host = split_jid(bare_room_jid); local day = increment_day(bare_day); local max_trys = 7; module:log("debug", day); while(not store_exists(node, host, day)) do max_trys = max_trys - 1; if max_trys == 0 then break; end day = increment_day(day); end if max_trys == 0 then return nil; else return day; end end local function decrement_day(bare_day) local year, month, day = bare_day:match("^20(%d%d)-(%d%d)-(%d%d)$"); local leapyear = false; module:log("debug", tostring(day).."/"..tostring(month).."/"..tostring(year)) day = tonumber(day); month = tonumber(month); year = tonumber(year); if year%4 == 0 and year%100 == 0 then if year%400 == 0 then leapyear = true; else leapyear = false; -- turn of the century but not a leapyear end elseif year%4 == 0 then leapyear = true; end if day - 1 == 0 then if month - 1 == 0 then year = year - 1; month = 12; day = 31; else month = month - 1; if (month == 2 and leapyear) then day = 29 elseif (month == 2 and not leapyear) then day = 28 elseif (month < 8 and month%2 == 1) or (month >= 8 and month%2 == 0) then day = 31 else day = 30 end end else day = day - 1; end return strformat("20%.02d-%.02d-%.02d", year, month, day); end local function find_previous_day(bare_room_jid, bare_day) local node, host = split_jid(bare_room_jid); local day = decrement_day(bare_day); local max_trys = 7; module:log("debug", day); while(not store_exists(node, host, day)) do max_trys = max_trys - 1; if max_trys == 0 then break; end day = decrement_day(day); end if max_trys == 0 then return nil; else return day; end end local function parse_day(bare_room_jid, room_subject, bare_day) local ret = ""; local year; local month; local day; local tmp; local node, host = split_jid(bare_room_jid); local year, month, day = bare_day:match("^20(%d%d)-(%d%d)-(%d%d)$"); local previous_day = find_previous_day(bare_room_jid, bare_day); local next_day = find_next_day(bare_room_jid, bare_day); local temptime = {day=0, month=0, year=0}; local path = data_getpath(node, host, datastore); path = path:gsub("/[^/]*$", ""); local calendar = "" if tonumber(year) <= 99 then year = year + 2000; end temptime.day = tonumber(day) temptime.month = tonumber(month) temptime.year = tonumber(year) calendar = create_month(temptime.month, temptime.year, {callback=day_callback, path=path, room=node, webpath="../"}) or "" if bare_day then local data = data_load(node, host, datastore .. "/" .. bare_day:match("^20(.*)"):gsub("-", "")); if data then for i=1, #data, 1 do local stanza = lom.parse(data[i]); if stanza and stanza.attr and stanza.attr.time then local timeStuff = html.day.time:gsub("###TIME###", stanza.attr.time):gsub("###UTC###", stanza.attr.utc or stanza.attr.time); if stanza[1] ~= nil then local nick; local tmp; -- grep nick from "from" resource if stanza[1].attr.from then -- presence and messages nick = html_escape(stanza[1].attr.from:match("/(.+)$")); elseif stanza[1].attr.to then -- iq nick = html_escape(stanza[1].attr.to:match("/(.+)$")); end if stanza[1].tag == "presence" and nick then tmp = parse_presence(stanza[1], timeStuff, nick); elseif stanza[1].tag == "message" then tmp = parse_message(stanza[1], timeStuff, nick); elseif stanza[1].tag == "iq" then tmp = parse_iq(stanza[1], timeStuff, nick); else module:log("info", "unknown stanza subtag in log found. room: %s; day: %s", bare_room_jid, year .. "/" .. month .. "/" .. day); end if tmp then ret = ret .. tmp tmp = nil; end end end end end if ret ~= "" then if next_day then next_day = html.day.dayLink:gsub("###DAY###", next_day):gsub("###TEXT###", "&gt;") end if previous_day then previous_day = html.day.dayLink:gsub("###DAY###", previous_day):gsub("###TEXT###", "&lt;"); end ret = ret:gsub("%%", "%%%%"); if config.show_presences then tmp = html.day.body:gsub("###DAY_STUFF###", ret):gsub("###JID###", bare_room_jid); else tmp = html.day.bodynp:gsub("###DAY_STUFF###", ret):gsub("###JID###", bare_room_jid); end tmp = tmp:gsub("###CALENDAR###", calendar); tmp = tmp:gsub("###DATE###", tostring(os_date("%A, %B %d, %Y", os_time(temptime)))); tmp = tmp:gsub("###TITLE_STUFF###", html.day.title:gsub("###TITLE###", room_subject)); tmp = tmp:gsub("###STATUS_CHECKED###", config.show_status and "checked='checked'" or ""); tmp = tmp:gsub("###JOIN_CHECKED###", config.show_join and "checked='checked'" or ""); tmp = tmp:gsub("###NEXT_LINK###", next_day or ""); tmp = tmp:gsub("###PREVIOUS_LINK###", previous_day or ""); return tmp, "Chatroom logs for "..bare_room_jid.." ("..tostring(os_date("%A, %B %d, %Y", os_time(temptime)))..")"; end end end local function handle_error(code, err) return http_event("http-error", { code = code, message = err }); end function handle_request(event) local response = event.response; local request = event.request; local room; local node, day, more = request.url.path:match("^/"..url_base.."/+([^/]*)/*([^/]*)/*(.*)$"); if more ~= "" then response.status_code = 404; return response:send(handle_error(response.status_code, "Unknown URL.")); end if node == "" then node = nil; end if day == "" then day = nil; end node = urldecode(node); if not html.doc then response.status_code = 500; return response:send(handle_error(response.status_code, "Muc Theme is not loaded.")); end if node then room = get_room_from_jid(node.."@"..my_host); end if node and not room then response.status_code = 404; return response:send(handle_error(response.status_code, "Room doesn't exist.")); end if room and (room._data.hidden or not room._data.logging) then response.status_code = 404; return response:send(handle_error(response.status_code, "There're no logs for this room.")); end if not node then -- room list for component return response:send(create_doc(generate_room_list(my_host))); elseif not day then -- room's listing return response:send(create_doc(generate_day_room_content(node.."@"..my_host))); else if not day:match("^20(%d%d)-(%d%d)-(%d%d)$") then local y,m,d = day:match("^(%d%d)(%d%d)(%d%d)$"); if not y then response.status_code = 404; return response:send(handle_error(response.status_code, "No entries for that year.")); end response.status_code = 301; response.headers = { ["Location"] = request.url.path:match("^/"..url_base.."/+[^/]*").."/20"..y.."-"..m.."-"..d.."/" }; return response:send(); end local body = create_doc(parse_day(node.."@"..my_host, room._data.subject or "", day)); if body == "" then response.status_code = 404; return response:send(handle_error(response.status_code, "Day entry doesn't exist.")); end return response:send(body); end end local function read_file(filepath) local f,err = io_open(filepath, "r"); if not f then return f,err; end local t = f:read("*all"); f:close() return t; end local function load_theme(path) for file in lfs.dir(path) do if file:match("%.html$") then module:log("debug", "opening theme file: " .. file); local content,err = read_file(path .. "/" .. file); if not content then return content,err; end -- html.a.b.c = content of a_b_c.html local tmp = html; for idx in file:gmatch("([^_]*)_") do tmp[idx] = tmp[idx] or {}; tmp = tmp[idx]; end tmp[file:match("([^_]*)%.html$")] = content; end end return true; end function module.load() config = module:get_option("muc_log_http", {}); if module:get_option_boolean("muc_log_presences", true) then config.show_presences = true end if config.show_status == nil then config.show_status = true; end if config.show_join == nil then config.show_join = true; end if config.url_base and type(config.url_base) == "string" then url_base = config.url_base; end theme = config.theme or "prosody"; local theme_path = themes_parent .. "/" .. tostring(theme); local attributes, err = lfs.attributes(theme_path); if attributes == nil or attributes.mode ~= "directory" then module:log("error", "Theme folder of theme \"".. tostring(theme) .. "\" isn't existing. expected Path: " .. theme_path); return false; end local themeLoaded,err = load_theme(theme_path); if not themeLoaded then module:log("error", "Theme \"%s\" is missing something: %s", tostring(theme), err); return false; end module:provides("http", { default_path = url_base, route = { ["GET /*"] = handle_request; } }); end
object_tangible_theme_park_nym_shuttle_control_terminal = object_tangible_theme_park_nym_shared_shuttle_control_terminal:new { } ObjectTemplates:addTemplate(object_tangible_theme_park_nym_shuttle_control_terminal, "object/tangible/theme_park/nym/shuttle_control_terminal.iff")
Instance.new("ColorCorrectionEffect", game.Lighting).Saturation = 99999998430674944.42069
greenCode.config:Add( "session_timeout", 10*60, false, false, false ); greenCode.config:Add( "session_noname", "Unknown", false, false, false ); greenCode.config:Add( "character_save_interval", 5, false, false, false ); greenCode.config:Add( "crouched_speed", 0.2, false, false, false ); greenCode.config:Add( "jump_power", 160, false, false, false ); greenCode.config:Add( "walk_speed", 140, false, false, false ); greenCode.config:Add( "run_speed", 225, false, false, false ); greenCode.config:Add( "min_speed", 15, false, false, false ); greenCode.config:Add( "duck_speed", 0.3, false, false, false ); greenCode.config:Add( "unduck_speed", 0.3, false, false, false ); greenCode.config:Add("scale_attribute_progress", 1); greenCode.config:Add("prop_kill_protection", true); greenCode.config:Add("damage_view_punch", true); greenCode.config:Add("armor_chest_only", true); greenCode.config:Add("scale_head_dmg", 5); greenCode.config:Add("scale_chest_dmg", 2); greenCode.config:Add("scale_limb_dmg", 1.5); greenCode.config:Add("scale_fall_damage", 1); greenCode.config:Add("wood_breaks_fall", true); greenCode.config:Add("limb_damage_system", true, true); greenCode.config:Add("scale_limb_dmg", 0.5); greenCode.config:Add( "nlr_time", 5*60, false, false ); greenCode.config:Get("walk_speed"):Set(140);
local oakrouting = require("resty.oakrouting") local match_count = 100000 local table_insert = table.insert local match_router local routers = {} for i = 1, match_count do table_insert(routers, { path = "/bench/" .. ngx.md5(i), method = "GET", handler = function() end }) if i == match_count then match_router = "/bench/" .. ngx.md5(i) end end local oak_routing = oakrouting.new(routers) ngx.update_time() local begin_time = ngx.now() local succeed = oak_routing:dispatch(match_router, "GET") ngx.update_time() local used_time = ngx.now() - begin_time ngx.say("matched succeed : ", succeed) ngx.say("matched count : ", match_count) ngx.say("matched time : ", used_time, " sec") ngx.say("QPS : ", math.floor(match_count / used_time))
--[[ Copyright (c) 2022 npc_strider, ickputzdirwech * Original mod by npc_strider. * For direct use of code or graphics, credit is appreciated and encouraged. See LICENSE.txt for more information. * This mod may contain modified code sourced from base/core Factorio. * This mod has been modified by ickputzdirwech. ]] --[[ Overview of startup-other.lua * Automatically generate mod shortcuts * Disable all technology requirement changes * Choose whether you want tags or icons ]] data:extend( { { setting_type = "startup", name = "autogen-color", localised_name = {"", "[color=yellow]", {"gui-menu.other"}, ": [/color]", {"Shortcuts-ick.autogen-color"}, "[font=default-small] [img=info][/font]"}, order = "f[other]-a[autogen-color]", type = "string-setting", allowed_values = {"disabled", "default", "red", "green", "blue"}, default_value = "default" }, { setting_type = "startup", name = "ick-compatibility-mode", localised_name = {"", "[color=yellow]", {"gui-menu.other"}, ": [/color]", {"Shortcuts-ick.compatibility-mode"}, "[font=default-small] [img=info][/font]"}, order = "f[other]-b[compatibility-mode]", type = "bool-setting", default_value = false }, { setting_type = "startup", name = "ick-tags", localised_name = {"", "[color=yellow]", {"gui-menu.other"}, ": [/color]", {"Shortcuts-ick.tags"}, "[font=default-small] [img=info][/font]"}, order = "f[other]-c[autogen-color]", type = "string-setting", allowed_values = {"disabled", "tags", "icons"}, default_value = "tags" } })
-- This file is part of the SAMP.Lua project. -- Licensed under the MIT License. -- Copyright (c) 2016, FYP @ BlastHack Team <blast.hk> -- https://github.com/THE-FYP/SAMP.Lua local raknet = require 'lib.samp.raknet' local events = require 'lib.samp.events.core' local utils = require 'lib.samp.events.utils' local handler = require 'lib.samp.events.handlers' require 'lib.samp.events.extra_types' local RPC = raknet.RPC local PACKET = raknet.PACKET local OUTCOMING_RPCS = events.INTERFACE.OUTCOMING_RPCS local OUTCOMING_PACKETS = events.INTERFACE.OUTCOMING_PACKETS local INCOMING_RPCS = events.INTERFACE.INCOMING_RPCS local INCOMING_PACKETS = events.INTERFACE.INCOMING_PACKETS -- Outgoing rpcs OUTCOMING_RPCS[RPC.ENTERVEHICLE] = {'onSendEnterVehicle', {vehicleId = 'int16'}, {passenger = 'bool8'}} OUTCOMING_RPCS[RPC.CLICKPLAYER] = {'onSendClickPlayer', {playerId = 'int16'}, {source = 'int8'}} OUTCOMING_RPCS[RPC.CLIENTJOIN] = {'onSendClientJoin', {version = 'int32'}, {mod = 'int8'}, {nickname = 'string8'}, {challengeResponse = 'int32'}, {joinAuthKey = 'string8'}, {clientVer = 'string8'}, {unknown = 'int32'}} OUTCOMING_RPCS[RPC.ENTEREDITOBJECT] = {'onSendEnterEditObject', {type = 'int32'}, {objectId = 'int16'}, {model = 'int32'}, {position = 'vector3d'}} OUTCOMING_RPCS[RPC.SERVERCOMMAND] = {'onSendCommand', {command = 'string32'}} OUTCOMING_RPCS[RPC.SPAWN] = {'onSendSpawn'} OUTCOMING_RPCS[RPC.DEATH] = {'onSendDeathNotification', {reason = 'int8'}, {killerId = 'int16'}} OUTCOMING_RPCS[RPC.DIALOGRESPONSE] = {'onSendDialogResponse', {dialogId = 'int16'}, {button = 'int8'}, {listboxId = 'int16'}, {input = 'string8'}} OUTCOMING_RPCS[RPC.CLICKTEXTDRAW] = {'onSendClickTextDraw', {textdrawId = 'int16'}} OUTCOMING_RPCS[RPC.SCMEVENT] = {'onSendVehicleTuningNotification', {vehicleId = 'int32'}, {param1 = 'int32'}, {param2 = 'int32'}, {event = 'int32'}} OUTCOMING_RPCS[RPC.CHAT] = {'onSendChat', {message = 'string8'}} OUTCOMING_RPCS[RPC.CLIENTCHECK] = {'onSendClientCheckResponse', {'int8'}, {'int32'}, {'int8'}} OUTCOMING_RPCS[RPC.DAMAGEVEHICLE] = {'onSendVehicleDamaged', {vehicleId = 'int16'}, {panelDmg = 'int32'}, {doorDmg = 'int32'}, {lights = 'int8'}, {tires = 'int8'}} OUTCOMING_RPCS[RPC.EDITATTACHEDOBJECT] = {'onSendEditAttachedObject', {response = 'int32'}, {index = 'int32'}, {model = 'int32'}, {bone = 'int32'}, {position = 'vector3d'}, {rotation = 'vector3d'}, {scale = 'vector3d'}, {color1 = 'int32'}, {color2 = 'int32'}} OUTCOMING_RPCS[RPC.EDITOBJECT] = {'onSendEditObject', {playerObject = 'bool'}, {objectId = 'int16'}, {response = 'int32'}, {position = 'vector3d'}, {rotation = 'vector3d'}} OUTCOMING_RPCS[RPC.SETINTERIORID] = {'onSendInteriorChangeNotification', {interior = 'int8'}} OUTCOMING_RPCS[RPC.MAPMARKER] = {'onSendMapMarker', {position = 'vector3d'}} OUTCOMING_RPCS[RPC.REQUESTCLASS] = {'onSendRequestClass', {classId = 'int32'}} OUTCOMING_RPCS[RPC.REQUESTSPAWN] = {'onSendRequestSpawn'} OUTCOMING_RPCS[RPC.PICKEDUPPICKUP] = {'onSendPickedUpPickup', {pickupId = 'int32'}} OUTCOMING_RPCS[RPC.MENUSELECT] = {'onSendMenuSelect', {row = 'int8'}} OUTCOMING_RPCS[RPC.VEHICLEDESTROYED] = {'onSendVehicleDestroyed', {vehicleId = 'int16'}} OUTCOMING_RPCS[RPC.MENUQUIT] = {'onSendQuitMenu'} OUTCOMING_RPCS[RPC.EXITVEHICLE] = {'onSendExitVehicle', {vehicleId = 'int16'}} OUTCOMING_RPCS[RPC.UPDATESCORESPINGSIPS] = {'onSendUpdateScoresAndPings'} -- playerId = 'int16', damage = 'float', weapon = 'int32', bodypart ='int32' OUTCOMING_RPCS[RPC.GIVETAKEDAMAGE] = {{'onSendGiveDamage', 'onSendTakeDamage'}, handler.on_send_give_take_damage_reader, handler.on_send_give_take_damage_writer} -- Incoming rpcs -- int playerId, string hostName, table settings, table vehicleModels, int unknown INCOMING_RPCS[RPC.INITGAME] = {'onInitGame', handler.on_init_game_reader, handler.on_init_game_writer} INCOMING_RPCS[RPC.SERVERJOIN] = {'onPlayerJoin', {playerId = 'int16'}, {color = 'int32'}, {isNpc = 'bool8'}, {nickname = 'string8'}} INCOMING_RPCS[RPC.SERVERQUIT] = {'onPlayerQuit', {playerId = 'int16'}, {reason = 'int8'}} INCOMING_RPCS[RPC.REQUESTCLASS] = {'onRequestClassResponse', {canSpawn = 'bool8'}, {team = 'int8'}, {skin = 'int32'}, {unk = 'int8'}, {positon = 'vector3d'}, {rotation = 'float'}, {weapons = 'Int32Array3'}, {ammo = 'Int32Array3'}} INCOMING_RPCS[RPC.REQUESTSPAWN] = {'onRequestSpawnResponse', {response = 'bool8'}} INCOMING_RPCS[RPC.SETPLAYERNAME] = {'onSetPlayerName', {playerId = 'int16'}, {name = 'string8'}, {success = 'bool8'}} INCOMING_RPCS[RPC.SETPLAYERPOS] = {'onSetPlayerPos', {position = 'vector3d'}} INCOMING_RPCS[RPC.SETPLAYERPOSFINDZ] = {'onSetPlayerPosFindZ', {position = 'vector3d'}} INCOMING_RPCS[RPC.SETPLAYERHEALTH] = {'onSetPlayerHealth', {health = 'float'}} INCOMING_RPCS[RPC.TOGGLEPLAYERCONTROLLABLE] = {'onTogglePlayerControllable', {controllable = 'bool8'}} INCOMING_RPCS[RPC.PLAYSOUND] = {'onPlaySound', {soundId = 'int32'}, {position = 'vector3d'}} INCOMING_RPCS[RPC.SETPLAYERWORLDBOUNDS] = {'onSetWorldBounds', {maxX = 'float'}, {minX = 'float'}, {maxY = 'float'}, {minY = 'float'}} INCOMING_RPCS[RPC.GIVEPLAYERMONEY] = {'onGivePlayerMoney', {money = 'int32'}} INCOMING_RPCS[RPC.SETPLAYERFACINGANGLE] = {'onSetPlayerFacingAngle', {angle = 'float'}} INCOMING_RPCS[RPC.RESETPLAYERMONEY] = {'onResetPlayerMoney'} INCOMING_RPCS[RPC.RESETPLAYERWEAPONS] = {'onResetPlayerWeapons'} INCOMING_RPCS[RPC.GIVEPLAYERWEAPON] = {'onGivePlayerWeapon', {weaponId = 'int32'}, {ammo = 'int32'}} INCOMING_RPCS[RPC.CANCELEDIT] = {'onCancelEdit'} INCOMING_RPCS[RPC.SETPLAYERTIME] = {'onSetPlayerTime', {hour = 'int8'}, {minute = 'int8'}} INCOMING_RPCS[RPC.TOGGLECLOCK] = {'onSetToggleClock', {state = 'bool8'}} INCOMING_RPCS[RPC.WORLDPLAYERADD] = {'onPlayerStreamIn', {playerId = 'int16'}, {team = 'int8'}, {model = 'int32'}, {position = 'vector3d'}, {rotation = 'float'}, {color = 'int32'}, {fightingStyle = 'int8'}} INCOMING_RPCS[RPC.SETPLAYERSHOPNAME] = {'onSetShopName', {name = 'string256'}} INCOMING_RPCS[RPC.SETPLAYERSKILLLEVEL] = {'onSetPlayerSkillLevel', {playerId = 'int16'}, {skill = 'int32'}, {level = 'int16'}} INCOMING_RPCS[RPC.SETPLAYERDRUNKLEVEL] = {'onSetPlayerDrunk', {drunkLevel = 'int32'}} INCOMING_RPCS[RPC.CREATE3DTEXTLABEL] = {'onCreate3DText', {id = 'int16'}, {color = 'int32'}, {position = 'vector3d'}, {distance = 'float'}, {testLOS = 'bool8'}, {attachedPlayerId = 'int16'}, {attachedVehicleId = 'int16'}, {text = 'encodedString4096'}} INCOMING_RPCS[RPC.DISABLECHECKPOINT] = {'onDisableCheckpoint'} INCOMING_RPCS[RPC.SETRACECHECKPOINT] = {'onSetRaceCheckpoint', {type = 'int8'}, {position = 'vector3d'}, {nextPosition = 'vector3d'}, {size = 'float'}} INCOMING_RPCS[RPC.DISABLERACECHECKPOINT] = {'onDisableRaceCheckpoint'} INCOMING_RPCS[RPC.GAMEMODERESTART] = {'onGamemodeRestart'} INCOMING_RPCS[RPC.PLAYAUDIOSTREAM] = {'onPlayAudioStream', {url = 'string8'}, {position = 'vector3d'}, {radius = 'float'}, {usePosition = 'bool8'}} INCOMING_RPCS[RPC.STOPAUDIOSTREAM] = {'onStopAudioStream'} INCOMING_RPCS[RPC.REMOVEBUILDINGFORPLAYER] = {'onRemoveBuilding', {modelId = 'int32'}, {position = 'vector3d'}, {radius = 'float'}} INCOMING_RPCS[RPC.CREATEOBJECT] = {'onCreateObject', handler.on_create_object_reader, handler.on_create_object_writer} INCOMING_RPCS[RPC.SETOBJECTPOS] = {'onSetObjectPosition', {objectId = 'int16'}, {position = 'vector3d'}} INCOMING_RPCS[RPC.SETOBJECTROT] = {'onSetObjectRotation', {objectId = 'int16'}, {rotation = 'vector3d'}} INCOMING_RPCS[RPC.DESTROYOBJECT] = {'onDestroyObject', {objectId = 'int16'}} INCOMING_RPCS[RPC.DEATHMESSAGE] = {'onPlayerDeathNotification', {killerId = 'int16'}, {killedId = 'int16'}, {reason = 'int8'}} INCOMING_RPCS[RPC.SETPLAYERMAPICON] = {'onSetMapIcon', {iconId = 'int8'}, {position = 'vector3d'}, {type = 'int8'}, {color = 'int32'}, {style = 'int8'}} INCOMING_RPCS[RPC.REMOVEVEHICLECOMPONENT] = {'onRemoveVehicleComponent', {vehicleId = 'int16'}, {componentId = 'int16'}} INCOMING_RPCS[RPC.UPDATE3DTEXTLABEL] = {'onRemove3DTextLabel', {textLabelId = 'int16'}} INCOMING_RPCS[RPC.CHATBUBBLE] = {'onPlayerChatBubble', {playerId = 'int16'}, {color = 'int32'}, {distance = 'float'}, {duration = 'int32'}, {message = 'string8'}} INCOMING_RPCS[RPC.UPDATETIME] = {'onUpdateGlobalTimer', {time = 'int32'}} INCOMING_RPCS[RPC.SHOWDIALOG] = {'onShowDialog', {dialogId = 'int16'}, {style = 'int8'}, {title = 'string8'}, {button1 = 'string8'}, {button2 = 'string8'}, {text = 'encodedString4096'}} INCOMING_RPCS[RPC.DESTROYPICKUP] = {'onDestroyPickup', {id = 'int32'}} INCOMING_RPCS[RPC.LINKVEHICLETOINTERIOR] = {'onLinkVehicleToInterior', {vehicleId = 'int16'}, {interiorId = 'int8'}} INCOMING_RPCS[RPC.SETPLAYERARMOUR] = {'onSetPlayerArmour', {armour = 'float'}} INCOMING_RPCS[RPC.SETPLAYERARMEDWEAPON] = {'onSetPlayerArmedWeapon', {weaponId = 'int32'}} INCOMING_RPCS[RPC.SETSPAWNINFO] = {'onSetSpawnInfo', {team = 'int8'}, {skin = 'int32'}, {unk = 'int8'}, {position = 'vector3d'}, {rotation = 'float'}, {weapons = 'Int32Array3'}, {ammo = 'Int32Array3'}} INCOMING_RPCS[RPC.SETPLAYERTEAM] = {'onSetPlayerTeam', {playerId = 'int16'}, {teamId = 'int8'}} INCOMING_RPCS[RPC.PUTPLAYERINVEHICLE] = {'onPutPlayerInVehicle', {vehicleId = 'int16'}, {seatId = 'int8'}} INCOMING_RPCS[RPC.REMOVEPLAYERFROMVEHICLE] = {'onRemovePlayerFromVehicle'} INCOMING_RPCS[RPC.SETPLAYERCOLOR] = {'onSetPlayerColor', {playerId = 'int16'}, {color = 'int32'}} INCOMING_RPCS[RPC.DISPLAYGAMETEXT] = {'onDisplayGameText', {style = 'int32'}, {time = 'int32'}, {text = 'string32'}} INCOMING_RPCS[RPC.FORCECLASSSELECTION] = {'onForceClassSelection'} INCOMING_RPCS[RPC.ATTACHOBJECTTOPLAYER] = {'onAttachObjectToPlayer', {objectId = 'int16'}, {playerId = 'int16'}, {offsets = 'vector3d'}, {rotation = 'vector3d'}} -- menuId = 'int8', menuTitle = 'string256', x = 'float', y = 'float', twoColumns = 'bool32', columns = 'table', rows = 'table', menu = 'bool32' INCOMING_RPCS[RPC.INITMENU] = {'onInitMenu', handler.on_init_menu_reader, handler.on_init_menu_writer} INCOMING_RPCS[RPC.SHOWMENU] = {'onShowMenu', {menuId = 'int8'}} INCOMING_RPCS[RPC.HIDEMENU] = {'onHideMenu', {menuId = 'int8'}} INCOMING_RPCS[RPC.CREATEEXPLOSION] = {'onCreateExplosion', {position = 'vector3d'}, {style = 'int32'}, {radius = 'float'}} INCOMING_RPCS[RPC.SHOWPLAYERNAMETAGFORPLAYER] = {'onShowPlayerNameTag', {playerId = 'int16'}, {show = 'bool8'}} INCOMING_RPCS[RPC.ATTACHCAMERATOOBJECT] = {'onAttachCameraToObject', {objectId = 'int16'}} INCOMING_RPCS[RPC.INTERPOLATECAMERA] = {'onInterpolateCamera', {setPos = 'bool'}, {fromPos = 'vector3d'}, {destPos = 'vector3d'}, {time = 'int32'}, {mode = 'int8'}} INCOMING_RPCS[RPC.GANGZONESTOPFLASH] = {'onGangZoneStopFlash', {zoneId = 'int16'}} INCOMING_RPCS[RPC.APPLYANIMATION] = {'onApplyPlayerAnimation', {playerId = 'int16'}, {animLib = 'string8'}, {animName = 'string8'}, {loop = 'bool'}, {lockX = 'bool'}, {lockY = 'bool'}, {freeze = 'bool'}, {time = 'int32'}} INCOMING_RPCS[RPC.CLEARANIMATIONS] = {'onClearPlayerAnimation', {playerId = 'int16'}} INCOMING_RPCS[RPC.SETPLAYERSPECIALACTION] = {'onSetPlayerSpecialAction', {actionId = 'int8'}} INCOMING_RPCS[RPC.SETPLAYERFIGHTINGSTYLE] = {'onSetPlayerFightingStyle', {playerId = 'int16'}, {styleId = 'int8'}} INCOMING_RPCS[RPC.SETPLAYERVELOCITY] = {'onSetPlayerVelocity', {velocity = 'vector3d'}} INCOMING_RPCS[RPC.SETVEHICLEVELOCITY] = {'onSetVehicleVelocity', {turn = 'bool8'}, {velocity = 'vector3d'}} INCOMING_RPCS[RPC.CLIENTMESSAGE] = {'onServerMessage', {color = 'int32'}, {text = 'string32'}} INCOMING_RPCS[RPC.SETWORLDTIME] = {'onSetWorldTime', {hour = 'int8'}} INCOMING_RPCS[RPC.CREATEPICKUP] = {'onCreatePickup', {id = 'int32'}, {model = 'int32'}, {pickupType = 'int32'}, {position = 'vector3d'}} INCOMING_RPCS[RPC.MOVEOBJECT] = {'onMoveObject', {objectId = 'int16'}, {fromPos = 'vector3d'}, {destPos = 'vector3d'}, {speed = 'float'}, {rotation = 'vector3d'}} INCOMING_RPCS[RPC.ENABLESTUNTBONUSFORPLAYER] = {'onEnableStuntBonus', {state = 'bool'}} INCOMING_RPCS[RPC.TEXTDRAWSETSTRING] = {'onTextDrawSetString', {id = 'int16'}, {text = 'string16'}} INCOMING_RPCS[RPC.SETCHECKPOINT] = {'onSetCheckpoint', {position = 'vector3d'}, {radius = 'float'}} INCOMING_RPCS[RPC.GANGZONECREATE] = {'onCreateGangZone', {zoneId = 'int16'}, {squareStart = 'vector2d'}, {squareEnd = 'vector2d'}, {color = 'int32'}} INCOMING_RPCS[RPC.PLAYCRIMEREPORT] = {'onPlayCrimeReport', {suspectId = 'int16'}, {'int32'}, {'int32'}, {'int32'}, {crime = 'int32'}, {coordinates = 'vector3d'}} -- TODO: find out unknown values INCOMING_RPCS[RPC.GANGZONEDESTROY] = {'onGangZoneDestroy', {zoneId = 'int16'}} INCOMING_RPCS[RPC.GANGZONEFLASH] = {'onGangZoneFlash', {zoneId = 'int16'}, {color = 'int32'}} INCOMING_RPCS[RPC.STOPOBJECT] = {'onStopObject', {objectId = 'int16'}} INCOMING_RPCS[RPC.SETNUMBERPLATE] = {'onSetVehicleNumberPlate', {vehicleId = 'int16'}, {text = 'string8'}} INCOMING_RPCS[RPC.TOGGLEPLAYERSPECTATING] = {'onTogglePlayerSpectating', {state = 'bool32'}} INCOMING_RPCS[RPC.PLAYERSPECTATEPLAYER] = {'onSpectatePlayer', {playerId = 'int16'}, {camType = 'int8'}} INCOMING_RPCS[RPC.PLAYERSPECTATEVEHICLE] = {'onSpectateVehicle', {vehicleId = 'int16'}, {camType = 'int8'}} INCOMING_RPCS[RPC.SHOWTEXTDRAW] = {'onShowTextDraw', handler.on_show_textdraw_reader, handler.on_show_textdraw_writer} INCOMING_RPCS[RPC.SETPLAYERWANTEDLEVEL] = {'onSetPlayerWantedLevel', {wantedLevel = 'int8'}} INCOMING_RPCS[RPC.TEXTDRAWHIDEFORPLAYER] = {'onTextDrawHide', {textDrawId = 'int16'}} INCOMING_RPCS[RPC.REMOVEPLAYERMAPICON] = {'onRemoveMapIcon', {iconId = 'int8'}} INCOMING_RPCS[RPC.SETPLAYERAMMO] = {'onSetWeaponAmmo', {weaponId = 'int8'}, {ammo = 'int16'}} INCOMING_RPCS[RPC.SETGRAVITY] = {'onSetGravity', {gravity = 'float'}} INCOMING_RPCS[RPC.SETVEHICLEHEALTH] = {'onSetVehicleHealth', {vehicleId = 'int16'}, {health = 'float'}} INCOMING_RPCS[RPC.ATTACHTRAILERTOVEHICLE] = {'onAttachTrailerToVehicle', {trailerId = 'int16'}, {vehicleId = 'int16'}} INCOMING_RPCS[RPC.DETACHTRAILERFROMVEHICLE] = {'onDetachTrailerFromVehicle', {vehicleId = 'int16'}} INCOMING_RPCS[RPC.SETWEATHER] = {'onSetWeather', {weatherId = 'int8'}} INCOMING_RPCS[RPC.SETPLAYERSKIN] = {'onSetPlayerSkin', {playerId = 'int32'}, {skinId = 'int32'}} INCOMING_RPCS[RPC.SETPLAYERINTERIOR] = {'onSetInterior', {interior = 'int8'}} INCOMING_RPCS[RPC.SETPLAYERCAMERAPOS] = {'onSetCameraPosition', {position = 'vector3d'}} INCOMING_RPCS[RPC.SETPLAYERCAMERALOOKAT] = {'onSetCameraLookAt', {lookAtPosition = 'vector3d'}, {cutType = 'int8'}} INCOMING_RPCS[RPC.SETVEHICLEPOS] = {'onSetVehiclePosition', {vehicleId = 'int16'}, {position = 'vector3d'}} INCOMING_RPCS[RPC.SETVEHICLEZANGLE] = {'onSetVehicleAngle', {vehicleId = 'int16'}, {angle = 'float'}} INCOMING_RPCS[RPC.SETVEHICLEPARAMSFORPLAYER] = {'onSetVehicleParams', {vehicleId = 'int16'}, {objective = 'bool8'}, {doorsLocked = 'bool8'}} INCOMING_RPCS[RPC.SETCAMERABEHINDPLAYER] = {'onSetCameraBehind'} INCOMING_RPCS[RPC.CHAT] = {'onChatMessage', {playerId = 'int16'}, {text = 'string8'}} INCOMING_RPCS[RPC.CONNECTIONREJECTED] = {'onConnectionRejected', {reason = 'int8'}} INCOMING_RPCS[RPC.WORLDPLAYERREMOVE] = {'onPlayerStreamOut', {playerId = 'int16'}} INCOMING_RPCS[RPC.WORLDVEHICLEADD] = {'onVehicleStreamIn', handler.on_vehicle_stream_in_reader, handler.on_vehicle_stream_in_writer} INCOMING_RPCS[RPC.WORLDVEHICLEREMOVE] = {'onVehicleStreamOut', {vehicleId = 'int16'}} INCOMING_RPCS[RPC.WORLDPLAYERDEATH] = {'onPlayerDeath', {playerId = 'int16'}} INCOMING_RPCS[RPC.ENTERVEHICLE] = {'onPlayerEnterVehicle', {playerId = 'int16'}, {vehicleId = 'int16'}, {passenger = 'bool8'}} INCOMING_RPCS[RPC.UPDATESCORESPINGSIPS] = {'onUpdateScoresAndPings', {playerList = 'PlayerScorePingMap'}} INCOMING_RPCS[RPC.SETOBJECTMATERIAL] = {{'onSetObjectMaterial', 'onSetObjectMaterialText'}, handler.on_set_object_material_reader, handler.on_set_object_material_writer} INCOMING_RPCS[RPC.CREATEACTOR] = {'onCreateActor', {actorId = 'int16'}, {skinId = 'int32'}, {position = 'vector3d'}, {rotation = 'float'}, {health = 'float'}} INCOMING_RPCS[RPC.CLICKTEXTDRAW] = {'onToggleSelectTextDraw', {state = 'bool'}, {hovercolor = 'int32'}} INCOMING_RPCS[RPC.SETVEHICLEPARAMSEX] = {'onSetVehicleParamsEx', {vehicleId = 'int16'}, {params = { {engine = 'int8'}, {lights = 'int8'}, {alarm = 'int8'}, {doors = 'int8'}, {bonnet = 'int8'}, {boot = 'int8'}, {objective = 'int8'}, {unknown = 'int8'} }}, {doors = { {driver = 'int8'}, {passenger = 'int8'}, {backleft = 'int8'}, {backright = 'int8'} }}, {windows = { {driver = 'int8'}, {passenger = 'int8'}, {backleft = 'int8'}, {backright = 'int8'} }} } INCOMING_RPCS[RPC.SETPLAYERATTACHEDOBJECT] = {'onSetPlayerAttachedObject', {playerId = 'int16'}, {index = 'int32'}, {create = 'bool'}, {object = { {modelId = 'int32'}, {bone = 'int32'}, {offset = 'vector3d'}, {rotation = 'vector3d'}, {scale = 'vector3d'}, {color1 = 'int32'}, {color2 = 'int32'}} } } -- Outgoing packets OUTCOMING_PACKETS[PACKET.RCON_COMMAND] = {'onSendRconCommand', {command = 'string32'}} OUTCOMING_PACKETS[PACKET.STATS_UPDATE] = {'onSendStatsUpdate', {money = 'int32'}, {drunkLevel = 'int32'}} local function empty_writer() end OUTCOMING_PACKETS[PACKET.PLAYER_SYNC] = {'onSendPlayerSync', function(bs) return utils.process_outcoming_sync_data(bs, 'PlayerSyncData') end, empty_writer} OUTCOMING_PACKETS[PACKET.VEHICLE_SYNC] = {'onSendVehicleSync', function(bs) return utils.process_outcoming_sync_data(bs, 'VehicleSyncData') end, empty_writer} OUTCOMING_PACKETS[PACKET.PASSENGER_SYNC] = {'onSendPassengerSync', function(bs) return utils.process_outcoming_sync_data(bs, 'PassengerSyncData') end, empty_writer} OUTCOMING_PACKETS[PACKET.AIM_SYNC] = {'onSendAimSync', function(bs) return utils.process_outcoming_sync_data(bs, 'AimSyncData') end, empty_writer} OUTCOMING_PACKETS[PACKET.UNOCCUPIED_SYNC] = {'onSendUnoccupiedSync', function(bs) return utils.process_outcoming_sync_data(bs, 'UnoccupiedSyncData') end, empty_writer} OUTCOMING_PACKETS[PACKET.TRAILER_SYNC] = {'onSendTrailerSync', function(bs) return utils.process_outcoming_sync_data(bs, 'TrailerSyncData') end, empty_writer} OUTCOMING_PACKETS[PACKET.BULLET_SYNC] = {'onSendBulletSync', function(bs) return utils.process_outcoming_sync_data(bs, 'BulletSyncData') end, empty_writer} OUTCOMING_PACKETS[PACKET.SPECTATOR_SYNC] = {'onSendSpectatorSync', function(bs) return utils.process_outcoming_sync_data(bs, 'SpectatorSyncData') end, empty_writer} -- Incoming packets INCOMING_PACKETS[PACKET.PLAYER_SYNC] = {'onPlayerSync', handler.on_player_sync_reader, handler.on_player_sync_writer} INCOMING_PACKETS[PACKET.VEHICLE_SYNC] = {'onVehicleSync', handler.on_vehicle_sync_reader, handler.on_vehicle_sync_writer} INCOMING_PACKETS[PACKET.MARKERS_SYNC] = {'onMarkersSync', handler.on_markers_sync_reader, handler.on_markers_sync_writer} INCOMING_PACKETS[PACKET.AIM_SYNC] = {'onAimSync', {playerId = 'int16'}, {data = 'AimSyncData'}} INCOMING_PACKETS[PACKET.BULLET_SYNC] = {'onBulletSync', {playerId = 'int16'}, {data = 'BulletSyncData'}} INCOMING_PACKETS[PACKET.UNOCCUPIED_SYNC] = {'onUnoccupiedSync', {playerId = 'int16'}, {data = 'UnoccupiedSyncData'}} INCOMING_PACKETS[PACKET.TRAILER_SYNC] = {'onTrailerSync', {playerId = 'int16'}, {data = 'TrailerSyncData'}} INCOMING_PACKETS[PACKET.PASSENGER_SYNC] = {'onPassengerSync', {playerId = 'int16'}, {data = 'PassengerSyncData'}} return events
-- Made with 🖤 By Bad -- https://github.com/Bad57/ragP AddEvent("OnPlayerStartExitVehicle", function(vehicle) local currentspeed = GetVehicleForwardSpeed(vehicle) CallRemoteEvent("RagdollPlayer", currentspeed,vehicle) end)
return { corvaliant = { acceleration = 0.009, activatewhenbuilt = true, airhoverfactor = 0, airstrafe = false, autoheal = 5, bankscale = 1, blocking = false, brakerate = 0.375, buildcostenergy = 1513318, buildcostmetal = 128316, builder = true, buildpic = "corvaliant.dds", buildtime = 1200000, canattack = true, canfly = true, canguard = true, canmove = true, canpatrol = true, canstop = 1, category = "ALL MOBILE SUPERSHIP SURFACE VTOL", collide = false, collisionvolumeoffsets = "0 -13 0", collisionvolumescales = "110 57 195", collisionvolumetype = "box", cruisealt = 40, defaultmissiontype = "VTOL_standby", description = "Destroyer Aeroship", dontland = 1, energystorage = 20000, explodeas = "KROG_BLAST", firestandorders = 1, footprintx = 6, footprintz = 6, hoverattack = true, icontype = "gunship", idleautoheal = 5, idletime = 1800, immunetoparalyzer = 1, mass = 128316, maxdamage = 291000, maxvelocity = 1.05, maxwaterdepth = 0, metalmake = 2.5, mobilestandorders = 1, name = "Valiant", noautofire = false, objectname = "corvaliant", pitchscale = 0.5, radardistance = 0, reclaimable = true, selfdestructas = "EXO_BLAST", selfdestructcountdown = 10, shownanospray = false, showplayername = true, sightdistance = 900, standingfireorder = 2, standingmoveorder = 1, steeringmode = 1, turninplaceanglelimit = 360, turninplacespeedlimit = 0.792, turnrate = 100, unitname = "corvaliant", workertime = 400, customparams = { buildpic = "corvaliant.dds", faction = "CORE", }, nanocolor = { [1] = 0.56, [2] = 0.56, [3] = 0.56, }, sfxtypes = { pieceexplosiongenerators = { [1] = "piecetrail0", [2] = "piecetrail1", [3] = "piecetrail2", [4] = "piecetrail3", [5] = "piecetrail4", [6] = "piecetrail6", }, }, sounds = { canceldestruct = "cancel2", underattack = "warning1", arrived = { [1] = "bigstop", }, cant = { [1] = "cantdo4", }, count = { [1] = "count6", [2] = "count5", [3] = "count4", [4] = "count3", [5] = "count2", [6] = "count1", }, ok = { [1] = "biggo", }, select = { [1] = "bigsel", }, }, weapondefs = { ["650mw"] = { accuracy = 500, areaofeffect = 120, burnblow = false, collidefriendly = false, corethickness = 1.2, craterareaofeffect = 0, craterboost = 0, cratermult = 0, duration = 0.07, energypershot = 1500, explosiongenerator = "custom:100RLexplode", impulseboost = 0, impulsefactor = 0, intensity = 1, name = "Heavy plasma cannon", noselfdamage = true, range = 1200, reloadtime = 1.25, rgbcolor = "0.95 0.95 0.8", rgbcolor2 = "0.93 0 0", soundhitdry = "xplomed1", soundhitwet = "sizzle", soundhitwetvolume = 0.5, soundstart = "cannhvy5", texture1 = "PlasmaPure", texture2 = "NULL", texture3 = "NULL", thickness = 7, turret = true, weapontype = "LaserCannon", weaponvelocity = 650, damage = { commanders = 1000, default = 4000, subs = 5, }, }, tehlazerofdewm = { areaofeffect = 14, beamtime = 1.05, corethickness = 0.5, craterareaofeffect = 0, craterboost = 0, cratermult = 0, energypershot = 1000, explosiongenerator = "custom:BURN_WHITE", impactonly = 1, impulseboost = 0, impulsefactor = 0, laserflaresize = 12, name = "DEEEEEEEEEEEEEWWWWWMMMM", noselfdamage = true, range = 950, reloadtime = 5, rgbcolor = "0.2 0.2 1", soundhitdry = "", soundhitwet = "sizzle", soundhitwetvolume = 0.5, soundstart = "annigun1", soundtrigger = 1, sweepfire = false, targetmoveerror = 0.2, thickness = 4, tolerance = 10000, turret = true, weapontype = "BeamLaser", weaponvelocity = 1500, customparams = { light_mult = 1.8, light_radius_mult = 1.2, }, damage = { commanders = 1000, default = 2500, subs = 5, }, }, }, weapons = { [1] = { badtargetcategory = "MEDIUM SMALL TINY", def = "650MW", maindir = "0 0 1", maxangledif = 270, onlytargetcategory = "SURFACE", }, [2] = { badtargetcategory = "MEDIUM SMALL TINY", def = "650MW", maindir = "0 0 1", maxangledif = 270, onlytargetcategory = "SURFACE", }, [3] = { badtargetcategory = "SMALL TINY", def = "tehlazerofdewm", maindir = "0 0 1", maxangledif = 180, onlytargetcategory = "SURFACE", }, [4] = { badtargetcategory = "SMALL TINY", def = "tehlazerofdewm", maindir = "0 0 1", maxangledif = 180, onlytargetcategory = "SURFACE", }, [5] = { badtargetcategory = "SMALL TINY", def = "tehlazerofdewm", maindir = "1 0 0", maxangledif = 220, onlytargetcategory = "SURFACE", }, [6] = { badtargetcategory = "SMALL TINY", def = "tehlazerofdewm", maindir = "1 0 0", maxangledif = 220, onlytargetcategory = "SURFACE", }, [7] = { badtargetcategory = "SMALL TINY", def = "tehlazerofdewm", maindir = "-1 0 0", maxangledif = 220, onlytargetcategory = "SURFACE", }, [8] = { badtargetcategory = "SMALL TINY", def = "tehlazerofdewm", maindir = "-1 0 0", maxangledif = 220, onlytargetcategory = "SURFACE", }, [9] = { badtargetcategory = "SMALL TINY", def = "tehlazerofdewm", maindir = "-1 0 1", maxangledif = 180, onlytargetcategory = "SURFACE", }, [10] = { badtargetcategory = "SMALL TINY", def = "tehlazerofdewm", maindir = "-1 0 1", maxangledif = 180, onlytargetcategory = "SURFACE", }, [11] = { badtargetcategory = "SMALL TINY", def = "tehlazerofdewm", maindir = "1 0 1", maxangledif = 180, onlytargetcategory = "SURFACE", }, [12] = { badtargetcategory = "SMALL TINY", def = "tehlazerofdewm", maindir = "1 0 1", maxangledif = 180, onlytargetcategory = "SURFACE", }, }, }, }
-- -- Various pretty printing functions to make life easier -- -- (C) 2010-2013 Markus Klotzbuecher <markus.klotzbuecher@mech.kuleuven.be> -- (C) 2014-2020 Markus Klotzbuecher <mk@mkio.de> -- -- SPDX-License-Identifier: BSD-3-Clause -- require("ansicolors") require("utils") require("rfsm") local unpack, print, type, pairs, assert = unpack, print, type, pairs, assert local table = table local utils = utils local string = string local ac = ansicolors local rfsm = rfsm -- some shortcuts local is_meta = rfsm.is_meta local is_state = rfsm.is_state local is_leaf = rfsm.is_leaf local is_composite = rfsm.is_composite local sta_mode = rfsm.sta_mode local fsmobj_tochar = rfsm.fsmobj_tochar module("rfsmpp") local pad = 20 -- pretty print fsm function fsm2str(fsm, ind) local ind = ind or 1 local indstr = ' ' local res = {} function __2colstr(s) assert(s, "s not a state") if s._mode == 'active' then if is_leaf(s) then return ac.green .. ac.bright .. s._id .. ac.reset else return ac.green .. s._id .. ac.reset end elseif s._mode == 'done' then return ac.yellow .. s._id .. ac.reset else return ac.red .. s._id .. ac.reset end end function __fsm_tostring(tab, res, ind) for name,state in pairs(tab) do if not is_meta(name) and is_state(state) then res[#res+1] = string.rep(indstr, ind) .. __2colstr(state) .. '[' .. fsmobj_tochar(state) .. ']' if is_leaf(state) then res[#res+1] = '\n' end if is_composite(state) then res[#res+1] = '\n' __fsm_tostring(state, res, ind+1) end end end end res[#res+1] = __2colstr(fsm) .. '\n' __fsm_tostring(fsm, res, ind) return table.concat(res, '') end --- Debug message colors. local ctab = { STATE_ENTER = ac.green, STATE_EXIT = ac.red, EFFECT = ac.yellow, DOO = ac.blue, EXEC_PATH = ac.cyan, ERROR = ac.red .. ac.bright, HIBERNATING = ac.magenta, RAISED = ac.white .. ac.bright, TIMEEVENT = ac.yellow .. ac.bright } function dbgcolorize(name, ...) local str = "" local args = { ... } if name then str = ac.cyan .. ac.bright .. name .. ":" .. ac.reset .. '\t' end -- convert nested tables to strings ptab = utils.map(utils.tab2str, args) col = ctab[ptab[1]] if col ~= nil then str = str.. col .. utils.rpad(ptab[1], pad) .. ac.reset .. table.concat(ptab, ' ', 2) else str = str .. utils.rpad(ptab[1], pad) .. table.concat(ptab, ' ', 2) end return str end --- Colorized fsm.dbg hook replacement. function dbgcolor(name, ...) print(dbgcolorize(name, ...)) end --- Generate a configurable dbgcolor function. -- @param name string name to prepend to printed message. -- @param ftab table of the dbg ids to print. -- @param defshow if false fields not mentioned in ftab are not shown. If true they are. -- @param print_fcn a function actually used for printing. Defaults to print. function gen_dbgcolor(name, ftab, defshow, print_fcn) name = name or "<unnamed SM>" ftab = ftab or {} if defshow == nil then defshow = true end if print_fcn == nil then print_fcn = print end return function (tag, ...) if ftab[tag] == true then print_fcn(dbgcolorize(name, tag, ...)) elseif ftab[tag] == false then return else if defshow then print_fcn(dbgcolorize(name, tag, ...)) end end end end
venom_filled_arachne = Creature:new { objectName = "@mob/creature_names:venom_filled_arachne", socialGroup = "arachne", faction = "", level = 36, chanceHit = 0.4, damageMin = 300, damageMax = 310, baseXp = 3642, baseHAM = 8500, baseHAMmax = 10300, armor = 0, resists = {145,145,20,165,165,20,165,-1,-1}, meatType = "meat_insect", meatAmount = 50, hideType = "", hideAmount = 0, boneType = "", boneAmount = 0, milk = 0, tamingChance = 0.25, ferocity = 4, pvpBitmask = AGGRESSIVE + ATTACKABLE + ENEMY, creatureBitmask = PACK + KILLER, optionsBitmask = AIENABLED, diet = CARNIVORE, templates = {"object/mobile/angler_hue.iff"}, hues = { 0, 1, 2, 3, 4, 5, 6, 7 }, lootGroups = {}, weapons = {"creature_spit_small_yellow"}, conversationTemplate = "", attacks = { {"stunattack",""}, {"strongpoison",""} } } CreatureTemplates:addCreatureTemplate(venom_filled_arachne, "venom_filled_arachne")
local refresh_rate = 60 local gui_refresh_rate = 10 local types = { ["storage-tank"] = true, ["boiler"] = true, ["pipe"] = true, ["pipe-to-ground"] = true, ["generator"] = true, } local look_offset = 0.5 local look_distance = 1 local tank_surroundings_check_distance = 5 local function get_tank(entity) local position = entity.position local direction = entity.direction local area if direction == defines.direction.north then area = {{position.x - look_offset, position.y - look_distance}, {position.x + look_offset, position.y - look_distance}} elseif direction == defines.direction.west then area = {{position.x - look_distance - 0.1, position.y - look_offset}, {position.x - look_distance + 0.1, position.y + look_offset}} elseif direction == defines.direction.south then area = {{position.x - look_offset, position.y + look_distance}, {position.x + look_offset, position.y + look_distance}} elseif direction == defines.direction.east then area = {{position.x + look_distance - 0.1, position.y - look_offset}, {position.x + look_distance + 0.1, position.y + look_offset}} end for i, v in pairs(entity.surface.find_entities(area)) do if types[v.type] then return v end end end local function find_in_global(combinator) for i = 0, refresh_rate - 1 do for ei, c in pairs(global.combinators[i]) do if c.entity == combinator then return c, i, ei end end end end local function on_built(event) local entity = event.created_entity if entity.name == "heat-combinator" then local ei local n for i = 0, refresh_rate - 1 do if not n or n >= #global.combinators[i] then ei = i n = #global.combinators[i] end end entity.rotatable = true table.insert(global.combinators[ei], {entity = entity, tank = get_tank(entity)}) end if types[entity.type] then local area = { {entity.position.x - tank_surroundings_check_distance, entity.position.y - tank_surroundings_check_distance}, {entity.position.x + tank_surroundings_check_distance, entity.position.y + tank_surroundings_check_distance} } local combinators = entity.surface.find_entities_filtered{area = area, name = "heat-combinator"} for _, combinator in pairs(combinators) do find_in_global(combinator).tank = get_tank(combinator) end end end local function on_tick(event) -- entity update for _, combinator in pairs(global.combinators[event.tick % refresh_rate]) do local count = 0 local fluid if combinator.tank and combinator.tank.valid and combinator.tank.fluidbox[1] then local fluidbox = combinator.tank.fluidbox[1] local precision = 1 if combinator.precise then precision = 100 end count = fluidbox.temperature * precision fluid = { signal = {type = "fluid", name = fluidbox.type}, count = math.floor(fluidbox.amount), index = 2 } end combinator.entity.get_or_create_control_behavior().parameters = { enabled = true, parameters = { { signal = {type = "virtual", name = "fluid-temperature"}, count = math.floor(count), index = 1 }, fluid } } end -- GUI update for i = event.tick % gui_refresh_rate + 1, #game.players, gui_refresh_rate do local player = game.players[i] if player.opened and player.opened.name == "heat-combinator" then local combinator = find_in_global(player.opened) if not player.gui.left["heat-combinator-precise-toggle"] then local state = true if not combinator.precise then state = false end player.gui.left.add{type = "checkbox", name = "heat-combinator-precise-toggle", caption = {"precise-toggle"}, state = state} global.open_combinators[player.index] = state end local state = player.gui.left["heat-combinator-precise-toggle"].state if state == global.open_combinators[player.index] and state ~= combinator.precise then player.gui.left["heat-combinator-precise-toggle"].state = combinator.precise else combinator.precise = player.gui.left["heat-combinator-precise-toggle"].state end global.open_combinators[player.index] = combinator.precise elseif player.gui.left["geat-combinator-precise-toggle"] then global.open_combinators[player.index] = nil player.gui.left["heat-combinator-precise-toggle"].destroy() end end end local function on_rotated(event) local entity = event.entity if entity.name == "heat-combinator" then find_in_global(entity).tank = get_tank(entity) end end local function on_settings_pasted(event) if event.source.name == "heat-combinator" and event.destination.name == "heat-combinator" then find_in_global(event.destination).precise = find_in_global(event.source).precise end end local function on_destroyed(event) local entity = event.entity if entity.name == "heat-combinator" then for i = 0, refresh_rate - 1 do for ei, combinator in pairs(global.combinators[i]) do if combinator.entity == entity then table.remove(global.combinators[i], ei) return end end end end if types[entity.type] then local area = { {entity.position.x - tank_surroundings_check_distance, entity.position.y - tank_surroundings_check_distance}, {entity.position.x + tank_surroundings_check_distance, entity.position.y + tank_surroundings_check_distance} } local combinators = entity.surface.find_entities_filtered{area = area, name = "heat-combinator"} for _, combinator in pairs(combinators) do find_in_global(combinator).tank = get_tank(combinator) end end end script.on_init(function() global.combinators = global.combinators or {} for i = 0, refresh_rate - 1 do global.combinators[i] = global.combinators[i] or {} end global.open_combinators = global.open_combinators or {} end) script.on_configuration_changed(function(data) global.combinators = global.combinators or {} for i = 0, refresh_rate - 1 do global.combinators[i] = global.combinators[i] or {} end global.open_combinators = global.open_combinators or {} if data.mod_changes["heat-combinator"] then for _, force in pairs(game.forces) do if force.technologies["circuit-network"].researched then force.recipes["heat-combinator"].enabled = true end end if data.mod_changes["heat-combinator"].old_version == "0.1.2" then for _, tab in pairs(global.combinators) do for i, v in pairs(tab) do v.precise = true end end end end end) script.on_event(defines.events.on_built_entity, on_built) script.on_event(defines.events.on_robot_built_entity, on_built) script.on_event(defines.events.on_pre_player_mined_item, on_destroyed) script.on_event(defines.events.on_robot_pre_mined, on_destroyed) script.on_event(defines.events.on_entity_died, on_destroyed) script.on_event(defines.events.on_tick, on_tick) script.on_event(defines.events.on_player_rotated_entity, on_rotated) script.on_event(defines.events.on_entity_settings_pasted, on_settings_pasted)
local tArgs = {...} function refuel(secs, repl) if repl == "replace" then fs.move("refuelSA.lua", "refuel.lua") term.clear() term.setCursorPos(1,1) print("Replaced standard 'refuel' script. Delete 'refuel' to revert it!") else if secs == nil then secs = 120 end print("Max fuel level: "..turtle.getFuelLimit()) print("Old fuel level: "..turtle.getFuelLevel()) if turtle.getFuelLevel() == turtle.getFuelLimit() then term.clear() term.setCursorPos(1,1) print("Turtle is fully refuled!") else print("Turtle will now loop refuel for "..secs.." seconds!") for i=1, tonumber(secs) do turtle.refuel() sleep(.5) if turtle.getFuelLevel() == turtle.getFuelLimit() then print("Turtle is now fully refuled!") break end end print("New fuel level: "..turtle.getFuelLevel()) end end end if type(tonumber(tArgs[1])) ~= "number" then if tArgs[1] ~= nil then if type(tostring(tArgs[1])) == "string" then term.clear() term.setCursorPos(1,1) error("Value was not a number, define time in seconds!") end end end refuel(tonumber(tArgs[1]), tostring(tArgs[2])) term.clear() term.setCursorPos(1,1) os.sleep(5)
-- Transitions Demo: Kim -- -- Copyright (c) 2010-present Bifrost Entertainment AS and Tommy Nguyen -- Distributed under the MIT License. -- (See accompanying file LICENSE or copy at http://opensource.org/licenses/MIT) local Math = require("Math") local Transition = require("Transition") Kim = {} Kim.__index = Kim function Kim.new(sprite) local self = {} setmetatable(self, Kim) self.origin = {0, 0} self.sprite = sprite -- Used to alternate between move and rotate. self.alternate = false -- Cache rainbow namespace. local rainbow = rainbow -- Move sprite to the centre of the screen. local screen = rainbow.platform.screen self.moving = Transition.move(self.sprite, screen.width * 0.5, screen.height * 0.5, 400) -- Make sprite transparent while rotating, and opaque while moving. self.sprite:set_color(0xff, 0xff, 0xff, 0x00) self.alpha = Transition.fadeto(self.sprite, 0xff, 400) -- Subscribe this class to input events. rainbow.input.subscribe(self) return self end function Kim:key_down(key, modifiers) local distance = 64 local moved = false if key == 1 then -- Left / A self.origin[1] = self.origin[1] - distance moved = true elseif key == 4 then -- Right / D self.origin[1] = self.origin[1] + distance moved = true elseif key == 19 then -- Down / S self.origin[2] = self.origin[2] - distance moved = true elseif key == 23 then -- Up / W self.origin[2] = self.origin[2] + distance moved = true end if moved then local screen = rainbow.platform.screen rainbow.renderer.set_projection( self.origin[1], self.origin[2], self.origin[1] + screen.width, self.origin[2] + screen.height) end end function Kim:key_up() end function Kim:pointer_began(pointers) -- Cancel the previous transitions. self.alpha:cancel() self.moving:cancel() if self.alternate then -- Rotate 360 degrees in 1 second. Linear effect. local angle = self.sprite:get_angle() + Math.radians(360) self.moving = Transition.rotate(self.sprite, angle, 1000) self.alpha = Transition.fadeto(self.sprite, 0x40, 1000) self.alternate = false else -- Move to point in 0.5 seconds. Squared ease-in effect. for h,p in pairs(pointers) do local x, y = self.sprite:get_position() self.moving = Transition.move(self.sprite, p.x - x, p.y - y, 500, Transition.Functions.easeinout_cubic) self.alpha = Transition.fadeto(self.sprite, 0xff, 500) self.alternate = true break end end end -- We don't care about these events. function Kim:pointer_canceled() end function Kim:pointer_ended() end function Kim:pointer_moved() end
require "config" local function createImprovedDrillTechnology() data:extend( { { type = "technology", name = "fusion-minidrill", icon = "__fupower__/graphics/icons/fusion-minidrill.png", prerequisites = {"alien-technology"}, effects = {{type = "unlock-recipe", recipe = "fusion-minidrill"}}, unit = { count=100, ingredients = {{"science-pack-1", 2}, {"science-pack-2", 2}, {"science-pack-3", 2}}, time = 30 }, order = "d-a-a" }, }) end local function createAlienDrillTechnology() data:extend( { { type = "technology", name = "fusion-drill", icon = "__fupower__/graphics/icons/fusion-drill.png", prerequisites = {"fusion-minidrill"}, effects = {{type = "unlock-recipe", recipe = "fusion-drill"}}, unit = { count=600, ingredients = {{"science-pack-1", 2}, {"science-pack-2", 2}, {"science-pack-3", 2}, {"alien-science-pack", 2}}, time = 30 }, order = "d-a-a" }, }) end if config.fudrill.improvedDrill==true then createImprovedDrillTechnology() if config.fudrill.alienDrill==true then createAlienDrillTechnology() end end
local skynet = require "skynet" local s = require "service" local balls={}--[playerid]=ball local playerCount = 0 --玩家数量 local playerIndex = 0 --玩家加入顺序 local randomX = {} local randomZ = {} function ball( )--每个玩家控制一个ball local m = { playerid=nil, node=nil, agent=nil, x=0, z=0, health=0, rotY=0 } return m end local function balllist_msg( ) local msg = {"balllist"} for i,v in pairs(balls) do table.insert(msg,v.playerid) table.insert(msg,v.x) table.insert(msg,v.z) table.insert(msg,v.size) end return msg end local foods = {}--[id]=food local food_maxid = 0 local food_count = 0 function food( ) local m = { id=nil, x=math.random(0,100), z=math.random(0,100) } return m end local function foodlist_msg( ) local msg = {"foodlist"} for i,v in pairs(foods) do table.insert(msg,v.id) table.insert(msg,v.x) table.insert(msg,v.z) end return msg end local walls = {}--[id]=wall local wall_count = 0 function wall( index ) if walls[index]~=nil then return walls[index] end local m = { id=nil, rotateY=math.random(0,1), x=randomX[index], z=randomZ[index] } return m end local function walllist_msg( ) msg = "" for i,v in pairs(walls) do msg=msg..string.format("%d:%d:%d:%d;",i,v.rotateY,v.x,v.z) end return {"walllist",0,msg} end function broadcast( msg ) for i,v in pairs(balls) do s.send(v.node,v.agent,"send",msg) end end s.resp.setPlayerCount=function ( source,count ) skynet.error("The scene player count is "..count) playerCount=count end s.resp.enter=function ( source,playerid,node,agent ) if balls[playerid] then return false end playerIndex=playerIndex+1 local b = ball() b.x=randomX[playerIndex] b.z=randomZ[playerIndex] b.playerid=playerid b.node=node b.agent=agent -- local entermsg = {"joinGame",0,playerid..";"..b.x..";"..b.z..";"..b.rotY} s.send(b.node,b.agent,"send",walllist_msg()) balls[playerid]=b broadcast(entermsg) if(playerIndex==playerCount) then skynet.sleep(300) broadcast({"startGame",0,0}) skynet.fork(function () -- local stime = skynet.now() local frame = 0 while true do frame = frame + 1 local isok,err = pcall(update,frame) if not isok then skynet.error(err) end local etime = skynet.now() local waittime = frame*2 - (etime-stime) if waittime>0 then skynet.sleep(waittime) end end end) end --[[ local ret_msg = {"enter",0,"进入成功"} s.send(b.node,b.agent,"send",ret_msg) s.send(b.node,b.agent,"send",balllist_msg()) s.send(b.node,b.agent,"send",foodlist_msg()) return true ]] end s.resp.leave=function ( source,playerid ) if not balls[playerid] then return false end balls[playerid]=nil local leavemsg={"leave",playerid} broadcast(leavemsg) end s.resp.shift=function ( source,playerid,x,z,rotY ) local b = balls[playerid] if not b then return false end b.x=x b.z=z b.rotY=rotY end s.resp.eat=function ( source,playerid,foodid ) --skynet.error("p:"..playerid.." f:"..foodid) local fid = tonumber(foodid) if(foods[fid]~=nil) then foods[fid]=nil food_count=food_count-1 balls[playerid].health=balls[playerid].health+1 local eatmsg={"eat",0,playerid..";"..foodid} broadcast(eatmsg) end end function update( frame ) food_update() move_update() --eat_update() end function move_update() local msg = "" for i,v in pairs(balls) do --skynet.error(v.x) msg=msg..string.format("%d:%f:%f:%f;",i,v.x,v.z,v.rotY) end broadcast({"shift",0,msg}) end function food_update() if food_count > 50 then return end if math.random(1,1000)<990 then return end food_maxid=food_maxid+1 food_count=food_count+1 local f = food() f.id=food_maxid foods[f.id]=f local msg={"addfood",0,string.format("%d;%d;%d",f.id,f.x,f.z)} broadcast(msg) end function eat_update() for pid,b in pairs(balls) do for fid,f in pairs(foods) do if(b.x-f.x)^2 + (b.z-f.z)^2<b.size^2 then b.size=b.size +1 food_count=food_count-1 local msg = {"eat",b.playerid,fid,b.size} broadcast(msg) food[fid]=nil end end end end s.init=function () math.randomseed(os.time()) for i=0,96,4 do table.insert(randomX,i) table.insert(randomZ,i) end for i=25,1,-1 do local index = math.random(1,i) randomX[index],randomX[i]=randomX[i],randomX[index] index=math.random(1,i) randomZ[index],randomZ[i]=randomZ[i],randomZ[index] end for i=1,25,1 do walls[i]=wall(i) end end s.start(...)
function event_addon_command(...) term = table.concat({...}, ' ') send_ipc_message(term) end function event_load() send_command('alias ipc lua c ipc') end function event_unload() send_command('unalias ipc') end function event_ipc_message(msg) add_to_chat(5, msg) end
#include "game.lua" #include "options.lua" #include "score.lua" #include "map.lua" #include "about.lua" function DebugMenuUI() local val = GetInt("options.gfx.debug") local is_mission = false local mode = " " local map = " " -- Thx to Rubikow#0098 -- local maxDist = 500 local plyTransform = GetPlayerTransform() local fwdPos = TransformToParentPoint(plyTransform, Vec(0, 0, maxDist * - 1)) local direction = VecSub(fwdPos, plyTransform.pos) direction = VecNormalize(direction) -- LEVEL MODE -- local levelid = GetString("game.levelid") if string.find(levelid, "hub") then mode = "Hub" elseif levelid == "" then mode = "Create" elseif string.find(levelid, "sandbox") then mode = "Sandbox" else is_mission = true map = levelid mode = "Mission" end if val == 1 then -- MAIN COLORS -- --[[ name = color in game format | hex white = 1, 1, 1 | #FFFFFF red = 1, 0.4980392157, 0.4980392157 | #FF7F7F green = 0.4784313725, 0.9568627451, 0.4823529412 | #7AF47B purple = 0.4666666667, 0.4705882353, 0.9372549020 | #7778EF --]] -- PLAYER POS -- local playerPosX = tostring(GetPlayerPos()[1]) local playerPosY = tostring(GetPlayerPos()[2]) local playerPosZ = tostring(GetPlayerPos()[3]) -- ROTATION -- local playerDirX = direction[1] * 180 local playerDirY = direction[2] * 180 local playerDirZ = direction[3] * 180 -- LOOKING AT -- local hit, dist = Raycast(plyTransform.pos, direction, maxDist) local hitPos = TransformToParentPoint(plyTransform, Vec(0, 0, dist * - 1)) if (not(hit)) then hitPos = {0, 0, 0} end -- ACTUAL CODE -- UiPush() -- MAP INFO -- UiPush() UiTranslate(15, 15) UiColor(0, 0, 0, 0.7) -- box background color UiWindow(285, 285) -- box size UiRect(285, 285) UiTranslate(UiCenter(), 30) UiColor(1, 1, 1) UiAlign("center middle") UiFont("font/bold.ttf", 25) UiText("Map Info") -- FIRE SOURCES -- UiTranslate(-100, 50) UiColor(1, 0.4980392157, 0.4980392157) UiAlign("left middle") UiText("Fire Sources:") UiTranslate(200, 0) UiColor(1, 1, 1) UiAlign("right middle") UiText(tostring(GetFireCount())) -- MODE -- UiTranslate(-200, 50) UiColor(0.4784313725, 0.9568627451, 0.4823529412) UiAlign("left middle") UiText("Mode:") UiTranslate(200, 0) UiColor(1, 1, 1) UiAlign("right middle") UiText(mode) -- MODE -- UiTranslate(-200, 50) UiColor(0.4666666667, 0.4705882353, 0.9372549020) UiAlign("left middle") UiText("ID:") UiTranslate(200, 0) UiColor(1, 1, 1) UiAlign("right middle") UiText(map) UiPop() -- Player Info -- UiPush() UiTranslate(15, 305) UiColor(0, 0, 0, 0.7) -- box background color UiWindow(285, 285) -- box size UiRect(285, 285) UiTranslate(UiCenter(), 30) UiColor(1, 1, 1) UiAlign("center middle") UiFont("font/bold.ttf", 25) UiText("Player Info") -- Looking at -- UiTranslate(0, 50) UiColor(1, 0.4980392157, 0.4980392157) UiAlign("center middle") UiText("Looking At") -- X -- UiFont("font/bold.ttf", 23) UiTranslate(-130, 25) UiColor(1, 1, 1) UiAlign("left middle") UiColor(1, 0.4980392157, 0.4980392157) UiText("X:") UiFont("font/bold.ttf", 20) UiTranslate(20, 0) UiColor(1, 1, 1) UiAlign("left middle") UiText(string.format("%.2f", tostring(hitPos[1]))) -- Y -- UiFont("font/bold.ttf", 23) UiTranslate(61, 0) UiColor(1, 1, 1) UiAlign("left middle") UiColor(0.4784313725, 0.9568627451, 0.4823529412) UiText("Y:") UiFont("font/bold.ttf", 20) UiTranslate(20, 0) UiColor(1, 1, 1) UiAlign("left middle") UiText(string.format("%.2f", tostring(hitPos[2]))) -- Z -- UiFont("font/bold.ttf", 23) UiTranslate(61, 0) UiColor(1, 1, 1) UiAlign("left middle") UiColor(0.4666666667, 0.4705882353, 0.9372549020) UiText("Z:") UiFont("font/bold.ttf", 20) UiTranslate(20, 0) UiColor(1, 1, 1) UiAlign("left middle") UiText(string.format("%.2f", tostring(hitPos[3]))) -- Rotation -- UiTranslate(-52, 25) UiColor(0.4784313725, 0.9568627451, 0.4823529412) UiAlign("center middle") UiText("Rotation") -- X -- UiFont("font/bold.ttf", 23) UiTranslate(-130, 25) UiColor(1, 1, 1) UiAlign("left middle") UiColor(1, 0.4980392157, 0.4980392157) UiText("X:") UiFont("font/bold.ttf", 20) UiTranslate(20, 0) UiColor(1, 1, 1) UiAlign("left middle") UiText(string.format("%.2f", tostring(playerDirX))) -- Y -- UiFont("font/bold.ttf", 23) UiTranslate(61, 0) UiColor(1, 1, 1) UiAlign("left middle") UiColor(0.4784313725, 0.9568627451, 0.4823529412) UiText("Y:") UiFont("font/bold.ttf", 20) UiTranslate(20, 0) UiColor(1, 1, 1) UiAlign("left middle") UiText(string.format("%.2f", tostring(playerDirY))) -- Z -- UiFont("font/bold.ttf", 23) UiTranslate(61, 0) UiColor(1, 1, 1) UiAlign("left middle") UiColor(0.4666666667, 0.4705882353, 0.9372549020) UiText("Z:") UiFont("font/bold.ttf", 20) UiTranslate(20, 0) UiColor(1, 1, 1) UiAlign("left middle") UiText(string.format("%.2f", tostring(playerDirZ))) -- Position -- UiTranslate(-52, 25) UiColor(0.4666666667, 0.4705882353, 0.9372549020) UiAlign("center middle") UiText("Position") -- X -- UiFont("font/bold.ttf", 23) UiTranslate(-130, 25) UiColor(1, 1, 1) UiAlign("left middle") UiColor(1, 0.4980392157, 0.4980392157) UiText("X:") UiFont("font/bold.ttf", 20) UiTranslate(20, 0) UiColor(1, 1, 1) UiAlign("left middle") UiText(string.format("%.2f", tostring(playerPosX))) -- Y -- UiFont("font/bold.ttf", 23) UiTranslate(61, 0) UiColor(1, 1, 1) UiAlign("left middle") UiColor(0.4784313725, 0.9568627451, 0.4823529412) UiText("Y:") UiFont("font/bold.ttf", 20) UiTranslate(20, 0) UiColor(1, 1, 1) UiAlign("left middle") UiText(string.format("%.2f", tostring(playerPosY))) -- Z -- UiFont("font/bold.ttf", 23) UiTranslate(61, 0) UiColor(1, 1, 1) UiAlign("left middle") UiColor(0.4666666667, 0.4705882353, 0.9372549020) UiText("Z:") UiFont("font/bold.ttf", 20) UiTranslate(20, 0) UiColor(1, 1, 1) UiAlign("left middle") UiText(string.format("%.2f", tostring(playerPosZ))) UiPop() UiPop() end end
require('bufferline').setup({ options = { numbers = 'buffer_id', indicator_icon = '▎',buffer_close_icon = '',modified_icon = '●', close_icon = '',left_trunc_marker = '',right_trunc_marker = '', max_name_length = 20,max_prefix_length = 15, tab_size = 25,diagnostics = 'nvim_lsp', diagnostics_indicator = function(_, _, diagnostics_dict, _) local s = ' ' for e, n in pairs(diagnostics_dict) do local sym = e == 'error' and ' ' or (e == 'warning' and ' ' or ' ') s = s .. n .. sym end return s end, -- NOTE: this will be called a lot so don't do any heavy processing here custom_filter = function(buf_number) if vim.bo[buf_number].filetype ~= 'dashboard' then return true end end, show_buffer_icons = true, show_buffer_close_icons = true, show_close_icon = false, show_tab_indicators = true, persist_buffer_sort = true, separator_style = 'thick', enforce_regular_tabs = true, always_show_bufferline = true, sort_by = 'directory', custom_areas = { right = function() local result = {} local error = vim.diagnostic.get(0, [[Error]]) local warning = vim.diagnostic.get(0, [[Warning]]) local info = vim.diagnostic.get(0,[[Information]]) local hint = vim.diagnostic.get(0, [[Hint]]) if error ~= 0 then result[1] = {text = '  ' .. error,guifg = '#ff6c6b',} end if warning ~= 0 then result[2] = {text = '  ' .. warning,guifg = '#ECBE7B',} end if hint ~= 0 then result[3] = {text = '  ' .. hint,guifg = '#98be65',} end if info ~= 0 then result[4] = {text = '  ' .. info,guifg = '#51afef',} end return result end, }, }, })
-- Copyright (c) 2021 Trevor Redfern -- -- This software is released under the MIT License. -- https://opensource.org/licenses/MIT describe("game.rules.inventory.actions", function() local actions = require "game.rules.inventory.actions" it("ACTION: addItem", function() local item = {} local entityId = {} local action = actions.addItem(entityId, item) assert.equals("INVENTORY_ADD_ITEM", action.type) assert.equals(entityId, action.payload.entity) assert.equals(item, action.payload.item) end) it("ACTION: removeItem", function() local item = {} local entityId = {} local action = actions.removeItem(entityId, item) assert.equals("INVENTORY_REMOVE_ITEM", action.type) assert.equals(entityId, action.payload.entity) assert.equals(item, action.payload.item) end) describe("ACTION: equipItem", function() it("defines what should be equipped", function() local item = {} local entityId = {} local action = actions.equipItem(entityId, item) assert.equals("INVENTORY_EQUIP_ITEM", action.type) assert.equals(entityId, action.payload.entity) assert.equals(item, action.payload.item) end) end) end)
-- -- test_tokens.lua -- Generate a NuGet packages.config file. -- Copyright (c) Jason Perkins and the Premake project -- local p = premake local suite = test.declare("vstudio_vs2010_tokens") local vc2010 = p.vstudio.vc2010 -- -- Setup -- local wks, prj function suite.setup() p.action.set("vs2010") wks = test.createWorkspace() end local function prepare() prj = test.getproject(wks, 1) vc2010.files(prj) end function suite.customBuild_onBuildRuleMultipleBuildOutputs() location "projects" files { "hello.cg" } filter "files:**.cg" buildcommands { "cgc %{file.relpath}" } buildoutputs { "%{file.basename}.a", "%{file.basename}.b" } prepare() test.capture [[ <ItemGroup> <CustomBuild Include="..\hello.cg"> <FileType>Document</FileType> <Command>cgc %(Identity)</Command> <Outputs>../hello.a;../hello.b</Outputs> </CustomBuild> </ItemGroup> ]] end function suite.customBuild_onBuildRuleWithMessage() location "projects" files { "hello.cg" } filter "files:**.cg" buildmessage "Compiling shader %{file.relpath}" buildcommands { "cgc %{file.relpath}" } buildoutputs { "%{file.basename}.obj" } prepare() test.capture [[ <ItemGroup> <CustomBuild Include="..\hello.cg"> <FileType>Document</FileType> <Command>cgc %(Identity)</Command> <Outputs>../hello.obj</Outputs> <Message>Compiling shader %(Identity)</Message> </CustomBuild> </ItemGroup> ]] end function suite.customBuild_onBuildRuleWithAdditionalInputs() location "projects" files { "hello.cg" } filter "files:**.cg" buildcommands { "cgc %{file.relpath}" } buildoutputs { "%{file.basename}.obj" } buildinputs { "common.cg.inc", "common.cg.inc2" } prepare() test.capture [[ <ItemGroup> <CustomBuild Include="..\hello.cg"> <FileType>Document</FileType> <Command>cgc %(Identity)</Command> <Outputs>../hello.obj</Outputs> <AdditionalInputs>../common.cg.inc;../common.cg.inc2</AdditionalInputs> </CustomBuild> </ItemGroup> ]] end
package.path = "..\\src\\?.lua;" .. package.path local uv = require "lluv" local ut = require "lluv.utils" local pg = require "lluv.pg" local EventEmitter = require "EventEmitter".EventEmitter local ENOTCONN = uv.error('LIBUV', uv.ENOTCONN) -- Pool does not track any query activity -- it just do round robin for multiple connection local PGConnectionPool = ut.class(EventEmitter) do local Pool = PGConnectionPool local function append(t, v) t[#t + 1] = v return t end local function remove_value(t, v) for i = 1, #t do if t[i] == v then return table.remove(t, i) end end end local function shift_value(t) local db = table.remove(t, 1) append(t, db) return db end local function super(self, m, ...) if self.__base and self.__base[m] then return self.__base[m](self, ...) end return self end function Pool:__init(n, cfg) self = super(self, '__init') self._active, self._waiting = {}, {} for i = 1, n do local db = pg.new(cfg) db:on('ready', function(db) if self._waiting[db] then self._waiting[db] = nil append(self._active, db) end self:emit('connection::ready', db) end) db:on('close', function(db, event, err) remove_value(self._active, db) self._waiting[db] = true self:emit('connection::close', db, err) end) append(self._active, db) db:connect() end return self end function Pool:query(...) local db = shift_value(self._active) if not db then local cb = select(-1, ...) if type(cb) == 'function' then return uv.defer(cb, db, ENOTCONN) end return end return db:query(...) end function Pool:close() for db in pairs(self._waiting) do db:close() end for _, db in ipairs(self._active) do db:close() end self._active = {} self._waiting = {} end end local pool = PGConnectionPool.new(5, { database = 'mydb', user = 'postgres', password = 'secret', reconnect = 1; }) uv.timer():start(0, 1000, function() pool:query('select $1::text', {'hello'}, function(self, err, rs) print(self, err or rs[1][1]) end) end):unref() uv.timer():start(20000, function() pool:close() end):unref() pool:on('connection::ready', function(pool, _, db) print(db, 'connected') end) pool:on('connection::close', function(pool, _, db, err) print(db, 'disconnected', err) end) uv.run()
if Mods.LeaderLib then local VersionInt = Ext.GetModInfo("543d653f-446c-43d8-8916-54670ce24dd9_7e737d2f-31d2-4751-963f-be6ccc59cd0c").Version local major = (VersionInt >> 28); local minor = (VersionInt >> 24) & 0x0F; local revision = (VersionInt >> 16) & 0xFF; local build = (VersionInt & 0xFFFF); local ts = Mods.LeaderLib.Classes.TranslatedString Listeners = Mods.LeaderLib.Listeners if ((minor == 7 and revision == 16 and build > 9) or (minor == 7 and revision > 16) or (minor > 7)) then ---@alias TalentRequirementCheckCallback fun(talentId:string, player:EclCharacter):boolean local TalentState = { Selected = 0, Selectable = 2, Locked = 3 } local TalentStateFormat = { [TalentState.Selected] = "%s", [TalentState.Selectable] = "<font color='#403625'>%s</font>", [TalentState.Locked] = "<font color='#C80030'>%s</font>" } TalentManager = { RegisteredTalents = {}, RegisteredCount = {}, ---@type table<string, table<string, TalentRequirementCheckCallback>> RequirementHandlers = {}, TalentState = TalentState, ---@type table<string, StatRequirement[]> BuiltinRequirements = {}, HiddenTalents = {}, HiddenCount = {} } TalentManager.__index = TalentManager local missingTalents = { ItemMovement = "TALENT_ItemMovement", ItemCreation = "TALENT_ItemCreation", --Flanking = "TALENT_Flanking", --AttackOfOpportunity = "TALENT_AttackOfOpportunity", Backstab = "TALENT_Backstab", Trade = "TALENT_Trade", Lockpick = "TALENT_Lockpick", ChanceToHitRanged = "TALENT_ChanceToHitRanged", ChanceToHitMelee = "TALENT_ChanceToHitMelee", Damage = "TALENT_Damage", ActionPoints = "TALENT_ActionPoints", ActionPoints2 = "TALENT_ActionPoints2", Criticals = "TALENT_Criticals", IncreasedArmor = "TALENT_IncreasedArmor", Sight = "TALENT_Sight", ResistFear = "TALENT_ResistFear", ResistKnockdown = "TALENT_ResistKnockdown", ResistStun = "TALENT_ResistStun", ResistPoison = "TALENT_ResistPoison", ResistSilence = "TALENT_ResistSilence", ResistDead = "TALENT_ResistDead", Carry = "TALENT_Carry", Throwing = "TALENT_Throwing", Repair = "TALENT_Repair", ExpGain = "TALENT_ExpGain", ExtraStatPoints = "TALENT_ExtraStatPoints", ExtraSkillPoints = "TALENT_ExtraSkillPoints", Durability = "TALENT_Durability", Awareness = "TALENT_Awareness", Vitality = "TALENT_Vitality", FireSpells = "TALENT_FireSpells", WaterSpells = "TALENT_WaterSpells", AirSpells = "TALENT_AirSpells", EarthSpells = "TALENT_EarthSpells", Charm = "TALENT_Charm", Intimidate = "TALENT_Intimidate", Reason = "TALENT_Reason", Luck = "TALENT_Luck", Initiative = "TALENT_Initiative", InventoryAccess = "TALENT_InventoryAccess", AvoidDetection = "TALENT_AvoidDetection", --AnimalEmpathy = "TALENT_AnimalEmpathy", --Escapist = "TALENT_Escapist", StandYourGround = "TALENT_StandYourGround", --SurpriseAttack = "TALENT_SurpriseAttack", LightStep = "TALENT_LightStep", ResurrectToFullHealth = "TALENT_ResurrectToFullHealth", Scientist = "TALENT_Scientist", --Raistlin = "TALENT_Raistlin", MrKnowItAll = "TALENT_MrKnowItAll", --WhatARush = "TALENT_WhatARush", --FaroutDude = "TALENT_FaroutDude", --Leech = "TALENT_Leech", --ElementalAffinity = "TALENT_ElementalAffinity", --FiveStarRestaurant = "TALENT_FiveStarRestaurant", Bully = "TALENT_Bully", --ElementalRanger = "TALENT_ElementalRanger", LightningRod = "TALENT_LightningRod", Politician = "TALENT_Politician", WeatherProof = "TALENT_WeatherProof", --LoneWolf = "TALENT_LoneWolf", --Zombie = "TALENT_Zombie", --Demon = "TALENT_Demon", --IceKing = "TALENT_IceKing", Courageous = "TALENT_Courageous", GoldenMage = "TALENT_GoldenMage", --WalkItOff = "TALENT_WalkItOff", FolkDancer = "TALENT_FolkDancer", SpillNoBlood = "TALENT_SpillNoBlood", --Stench = "TALENT_Stench", Kickstarter = "TALENT_Kickstarter", WarriorLoreNaturalArmor = "TALENT_WarriorLoreNaturalArmor", WarriorLoreNaturalHealth = "TALENT_WarriorLoreNaturalHealth", WarriorLoreNaturalResistance = "TALENT_WarriorLoreNaturalResistance", RangerLoreArrowRecover = "TALENT_RangerLoreArrowRecover", RangerLoreEvasionBonus = "TALENT_RangerLoreEvasionBonus", RangerLoreRangedAPBonus = "TALENT_RangerLoreRangedAPBonus", RogueLoreDaggerAPBonus = "TALENT_RogueLoreDaggerAPBonus", RogueLoreDaggerBackStab = "TALENT_RogueLoreDaggerBackStab", RogueLoreMovementBonus = "TALENT_RogueLoreMovementBonus", RogueLoreHoldResistance = "TALENT_RogueLoreHoldResistance", NoAttackOfOpportunity = "TALENT_NoAttackOfOpportunity", WarriorLoreGrenadeRange = "TALENT_WarriorLoreGrenadeRange", RogueLoreGrenadePrecision = "TALENT_RogueLoreGrenadePrecision", WandCharge = "TALENT_WandCharge", --DualWieldingDodging = "TALENT_DualWieldingDodging", --DualWieldingBlock = "TALENT_DualWieldingBlock", --Human_Inventive = "TALENT_Human_Inventive", --Human_Civil = "TALENT_Human_Civil", --Elf_Lore = "TALENT_Elf_Lore", --Elf_CorpseEating = "TALENT_Elf_CorpseEating", --Dwarf_Sturdy = "TALENT_Dwarf_Sturdy", --Dwarf_Sneaking = "TALENT_Dwarf_Sneaking", --Lizard_Resistance = "TALENT_Lizard_Resistance", --Lizard_Persuasion = "TALENT_Lizard_Persuasion", Perfectionist = "TALENT_Perfectionist", --Executioner = "TALENT_Executioner", --ViolentMagic = "TALENT_ViolentMagic", --QuickStep = "TALENT_QuickStep", --Quest_SpidersKiss_Str = "TALENT_Quest_SpidersKiss_Str", --Quest_SpidersKiss_Int = "TALENT_Quest_SpidersKiss_Int", --Quest_SpidersKiss_Per = "TALENT_Quest_SpidersKiss_Per", --Quest_SpidersKiss_Null = "TALENT_Quest_SpidersKiss_Null", --Memory = "TALENT_Memory", --Quest_TradeSecrets = "TALENT_Quest_TradeSecrets", --Quest_GhostTree = "TALENT_Quest_GhostTree", BeastMaster = "TALENT_BeastMaster", --LivingArmor = "TALENT_LivingArmor", --Torturer = "TALENT_Torturer", --Ambidextrous = "TALENT_Ambidextrous", --Unstable = "TALENT_Unstable", ResurrectExtraHealth = "TALENT_ResurrectExtraHealth", NaturalConductor = "TALENT_NaturalConductor", --Quest_Rooted = "TALENT_Quest_Rooted", PainDrinker = "TALENT_PainDrinker", DeathfogResistant = "TALENT_DeathfogResistant", Sourcerer = "TALENT_Sourcerer", -- Divine Talents Rager = "TALENT_Rager", Elementalist = "TALENT_Elementalist", Sadist = "TALENT_Sadist", Haymaker = "TALENT_Haymaker", Gladiator = "TALENT_Gladiator", Indomitable = "TALENT_Indomitable", WildMag = "TALENT_WildMag", Jitterbug = "TALENT_Jitterbug", Soulcatcher = "TALENT_Soulcatcher", MasterThief = "TALENT_MasterThief", GreedyVessel = "TALENT_GreedyVessel", MagicCycles = "TALENT_MagicCycles", } local racialTalents = { Human_Inventive = "TALENT_Human_Inventive", Human_Civil = "TALENT_Human_Civil", Elf_Lore = "TALENT_Elf_Lore", Elf_CorpseEating = "TALENT_Elf_CorpseEating", Dwarf_Sturdy = "TALENT_Dwarf_Sturdy", Dwarf_Sneaking = "TALENT_Dwarf_Sneaking", Lizard_Resistance = "TALENT_Lizard_Resistance", Lizard_Persuasion = "TALENT_Lizard_Persuasion", Zombie = "TALENT_Zombie", } local DivineTalents = { --Rager = "TALENT_Rager", Elementalist = "TALENT_Elementalist", Sadist = "TALENT_Sadist", Haymaker = "TALENT_Haymaker", Gladiator = "TALENT_Gladiator", Indomitable = "TALENT_Indomitable", WildMag = "TALENT_WildMag", Jitterbug = "TALENT_Jitterbug", Soulcatcher = "TALENT_Soulcatcher", MasterThief = "TALENT_MasterThief", GreedyVessel = "TALENT_GreedyVessel", MagicCycles = "TALENT_MagicCycles", } --Requires a name and description to be manually set in the tooltip, as well as an icon local ragerWasEnabled = false for name,v in pairs(missingTalents) do TalentManager.RegisteredCount[name] = 0 -- if Vars.DebugMode then -- TalentManager.RegisteredCount[name] = 1 -- end end for talentId,enum in pairs(Data.TalentEnum) do TalentManager.HiddenTalents[talentId] = {} end ---@param talentId string ---@return boolean function TalentManager.IsRegisteredTalent(talentId) return TalentManager.RegisteredCount[talentId] and TalentManager.RegisteredCount[talentId] > 0 end ---@param player EclCharacter ---@param talentId string ---@return boolean function TalentManager.HasTalent(player, talentId) local talentIdPrefixed = "TALENT_" .. talentId if player ~= nil and player.Stats ~= nil and player.Stats[talentIdPrefixed] == true then return true end return false end ---@param talentId string The talent id, i.e. Executioner ---@param modID string The registering mod's UUID. ---@param getRequirements TalentRequirementCheckCallback|nil A function that gets invoked when looking to see if a player has met the talent's requirements. function TalentManager.EnableTalent(talentId, modID, getRequirements) if talentId == "Rager" then ragerWasEnabled = true end if talentId == "all" then for talent,v in pairs(missingTalents) do TalentManager.EnableTalent(talent, modID, getRequirements) end else if TalentManager.RegisteredTalents[talentId] == nil then TalentManager.RegisteredTalents[talentId] = {} end if TalentManager.RegisteredTalents[talentId][modID] ~= true then TalentManager.RegisteredTalents[talentId][modID] = true TalentManager.RegisteredCount[talentId] = (TalentManager.RegisteredCount[talentId] or 0) + 1 end if getRequirements then if not TalentManager.RequirementHandlers[talentId] then TalentManager.RequirementHandlers[talentId] = {} end TalentManager.RequirementHandlers[talentId][modID] = getRequirements end end end -- if Vars.DebugMode then -- for k,v in pairs(missingTalents) do -- TalentManager.EnableTalent(k, "7e737d2f-31d2-4751-963f-be6ccc59cd0c") -- end -- end function TalentManager.DisableTalent(talentId, modID) if talentId == "all" then for talent,v in pairs(missingTalents) do TalentManager.DisableTalent(talent, modID) end GameHelpers.UI.TryInvoke(Data.UIType.characterSheet, "clearTalents") else local data = TalentManager.RegisteredTalents[talentId] if data ~= nil then if TalentManager.RegisteredTalents[talentId][modID] ~= nil then TalentManager.RegisteredTalents[talentId][modID] = nil TalentManager.RegisteredCount[talentId] = TalentManager.RegisteredCount[talentId] - 1 end if TalentManager.RegisteredCount[talentId] <= 0 then TalentManager.RegisteredTalents[talentId] = nil TalentManager.RegisteredCount[talentId] = 0 GameHelpers.UI.TryInvoke(Data.UIType.characterSheet, "clearTalents") end end end end ---Hides a talent from the UI, effectively disabling the ability to select it. ---@param talentId string ---@param modID string function TalentManager.HideTalent(talentId, modID) if talentId == "all" then for talentId,enum in pairs(Data.TalentEnum) do TalentManager.HideTalent(talentId, modID) end GameHelpers.UI.TryInvoke(Data.UIType.characterSheet, "clearTalents") else if TalentManager.HiddenTalents[talentId] == nil then TalentManager.HiddenTalents[talentId] = {} end if TalentManager.HiddenTalents[talentId][modID] ~= true then TalentManager.HiddenTalents[talentId][modID] = true TalentManager.HiddenCount[talentId] = (TalentManager.HiddenCount[talentId] or 0) + 1 GameHelpers.UI.TryInvoke(Data.UIType.characterSheet, "clearTalents") end end end ---Stops hiding a talent from the UI. ---@param talentId string ---@param modID string function TalentManager.UnhideTalent(talentId, modID) if talentId == "all" then for _,talent in pairs(Data.Talents) do TalentManager.UnhideTalent(talent, modID) end else local count = TalentManager.HiddenCount[talentId] or 0 local data = TalentManager.HiddenTalents[talentId] if data ~= nil then if TalentManager.HiddenTalents[talentId][modID] ~= nil then TalentManager.HiddenTalents[talentId][modID] = nil count = count - 1 end end if count <= 0 then TalentManager.HiddenTalents[talentId] = nil TalentManager.HiddenCount[talentId] = nil else TalentManager.HiddenCount[talentId] = count end end end ---@param player EclCharacter ---@param id string function TalentManager.HasRequirements(player, id) local getRequirementsHandlers = TalentManager.RequirementHandlers[id] if getRequirementsHandlers then for modid,handler in pairs(getRequirementsHandlers) do local b,result = xpcall(handler, debug.traceback, id, player) if b then if result == false then return false end else fprint(LOGLEVEL.ERROR, "[LeaderLib:TalentManager.HasRequirements] Error invoking requirement handler for talent [%s] modid[%s]", id, modid) Ext.PrintError(result) end end end local builtinRequirements = TalentManager.BuiltinRequirements[id] if builtinRequirements and #builtinRequirements > 0 then for _,req in pairs(builtinRequirements) do local playerValue = player.Stats[req.Requirement] local t = type(playerValue) if t == "boolean" then if req.Not ~= playerValue then return false end elseif t == "number" and playerValue < req.Param then return false end end end return true end ---@param player EclCharacter ---@param id string ---@return string,boolean function TalentManager.GetTalentDisplayName(player, id, talentState) local name = LocalizedText.TalentNames[id] if not name or StringHelpers.IsNullOrEmpty(name.Value) then name = id else name = name.Value end return string.format(TalentStateFormat[talentState], name) end ---@param player EclCharacter ---@param talentId string ---@return TalentState function TalentManager.GetTalentState(player, talentId) if player.Stats["TALENT_" .. talentId] then return TalentState.Selected elseif not TalentManager.HasRequirements(player, talentId) then return TalentState.Locked else return TalentState.Selectable end end function TalentManager.TalentIsInArray(talentEnum, talent_array) if not Vars.ControllerEnabled then for i=1,#talent_array,3 do local tEnum = talent_array[i] if tEnum == talentEnum then return true end end else for i=0,#talent_array,3 do local tEnum = talent_array[i] if tEnum == talentEnum then return true end end end return false end local function TalentIsHidden(talentId) local count = TalentManager.HiddenCount[talentId] return count and count > 0 end ---@class TalentMC_CC ---@field addTalentElement fun(id:int, name:string, isActive:boolean, isChooseable:boolean, isRacial:boolean):void ---@param talent_mc TalentMC_CC function TalentManager.Update_CC(ui, talent_mc, player) for talentId,talentStat in pairs(missingTalents) do --Same setup for CC in controller mode as well if TalentManager.RegisteredCount[talentId] > 0 and not TalentIsHidden(talentId) then local talentEnum = Data.TalentEnum[talentId] if not UI.IsInArray(ui, "talentArray", talentId, 1, 4) then local talentState = TalentManager.GetTalentState(player, talentId) local name = TalentManager.GetTalentDisplayName(player, talentId, talentState) talent_mc.addTalentElement(talentEnum, name, player.Stats[talentStat], talentState ~= TalentState.Locked, false) if Vars.ControllerEnabled then TalentManager.Gamepad.UpdateTalent_CC(ui, player, talentId, talentEnum) end end end end if Features.RacialTalentsDisplayFix then for talentId,talentStat in pairs(racialTalents) do local talentEnum = Data.TalentEnum[talentId] if not TalentIsHidden(talentId) and not UI.IsInArray(ui, "talentArray", talentId, 1, 4) then local talentState = TalentManager.GetTalentState(player, talentId) local name = TalentManager.GetTalentDisplayName(player, talentId, talentState) talent_mc.addTalentElement(talentEnum, name, player.Stats[talentStat], talentState ~= TalentState.Locked, true) if Vars.ControllerEnabled then TalentManager.Gamepad.UpdateTalent_CC(ui, player, talentId, talentEnum) end end end end if not TalentIsHidden("RogueLoreDaggerBackStab") and player.Stats.TALENT_RogueLoreDaggerBackStab or (GameSettings.Settings.BackstabSettings.Player.Enabled and GameSettings.Settings.BackstabSettings.Player.TalentRequired) then local talentEnum = Data.TalentEnum["RogueLoreDaggerBackStab"] if not UI.IsInArray(ui, "talentArray", "RogueLoreDaggerBackStab", 1, 4) then local talentState = TalentManager.GetTalentState(player, "RogueLoreDaggerBackStab") local name = TalentManager.GetTalentDisplayName(player, "RogueLoreDaggerBackStab", talentState) talent_mc.addTalentElement(talentEnum, name, player.Stats.TALENT_RogueLoreDaggerBackStab, talentState ~= TalentState.Locked, false) if Vars.ControllerEnabled then TalentManager.Gamepad.UpdateTalent_CC(ui, player, "RogueLoreDaggerBackStab", talentEnum) end end end end local function CanDisplayDivineTalent(talentId, name) if not DivineTalents[talentId] then return true end if string.find(name, "|") then return false end if talentId == "Rager" then -- Seems to have no handles for its name/description return ragerWasEnabled elseif talentId == "Jitterbug" then local tooltip = Ext.GetTranslatedString("h758efe2fgb3bag4935g9500g2c789497e87a", "") if string.find(tooltip, "|") then return false end end return true end local function AddTalentToArray(ui, player, talent_array, talentId, lvlBtnTalent_array, i) local talentEnum = Data.TalentEnum[talentId] if not TalentManager.TalentIsInArray(talentEnum, talent_array) then local talentState = TalentManager.GetTalentState(player, talentId) local name = TalentManager.GetTalentDisplayName(player, talentId, talentState) --Skip placeholders if CanDisplayDivineTalent(talentId, name) then if not Vars.ControllerEnabled then --addTalent(displayName:String, id:Number, talentState:Number) talent_array[i] = name talent_array[i+1] = talentEnum else --addTalent(id:Number, displayName:String, talentState:Number) talent_array[i] = talentEnum talent_array[i+1] = name end talent_array[i+2] = talentState i = i + 3 if Vars.ControllerEnabled then TalentManager.Gamepad.UpdateTalent(ui, player, talentId, talentEnum, lvlBtnTalent_array, talentState) end end end return i end ---@param ui UIObject ---@param player EclCharacter function TalentManager.Update(ui, player) local main = ui:GetRoot() local lvlBtnTalent_array = main.lvlBtnTalent_array local talent_array = main.talent_array if Vars.ControllerEnabled then TalentManager.Gamepad.PreUpdate(ui, main) end local i = #talent_array for talentId,talentStat in pairs(missingTalents) do if not TalentIsHidden(talentId) and TalentManager.RegisteredCount[talentId] > 0 then i = AddTalentToArray(ui, player, talent_array, talentId, lvlBtnTalent_array, i) end end if Features.RacialTalentsDisplayFix then i = #talent_array for talentId,talentStat in pairs(racialTalents) do if not TalentIsHidden(talentId) and player.Stats[talentStat] == true then i = AddTalentToArray(ui, player, talent_array, talentId, lvlBtnTalent_array, i, true) end end end if not TalentIsHidden("RogueLoreDaggerBackStab") and player.Stats.TALENT_RogueLoreDaggerBackStab or (GameSettings.Settings.BackstabSettings.Player.Enabled and GameSettings.Settings.BackstabSettings.Player.TalentRequired) then i = #talent_array AddTalentToArray(ui, player, talent_array, "RogueLoreDaggerBackStab", lvlBtnTalent_array, i) end end if Vars.DebugMode then RegisterListener("LuaReset", function() local ui = Ext.GetUIByType(Data.UIType.statsPanel_c) if ui then ui:GetRoot().mainpanel_mc.stats_mc.talents_mc.statList.clearElements() end end) end function TalentManager.ToggleDivineTalents(enabled) if enabled then for talent,id in pairs(DivineTalents) do TalentManager.EnableTalent(talent, "DivineTalents") end else for talent,id in pairs(DivineTalents) do TalentManager.DisableTalent(talent, "DivineTalents") end end end local pointRequirement = "(.+) (%d+)" local talentRequirement = "(%!*)(TALENT_.+)" local function GetRequirementFromText(text) local requirementName,param = string.match(text, pointRequirement) if requirementName and param then return { Requirement = requirementName, Param = tonumber(param), Not = false } else local notParam,requirementName = string.match(text, talentRequirement) if requirementName then return { Requirement = requirementName, Param = "Talent", Not = notParam and true or false } end end return nil end function TalentManager.LoadRequirements() for _,uuid in pairs(Ext.GetModLoadOrder()) do local modInfo = Ext.GetModInfo(uuid) if modInfo and modInfo.Directory then local talentRequirementsText = Ext.LoadFile("Public/"..modInfo.Directory.."/Stats/Generated/Data/Requirements.txt", "data") if not StringHelpers.IsNullOrEmpty(talentRequirementsText) then for line in StringHelpers.GetLines(talentRequirementsText) do local talent,requirementText = string.match(line, 'requirement.*"(.+)",.*"(.*)"') if talent then TalentManager.BuiltinRequirements[talent] = {} if requirementText then for i,v in pairs(StringHelpers.Split(requirementText, ";")) do local req = GetRequirementFromText(v) if req then table.insert(TalentManager.BuiltinRequirements[talent], req) end end end end end end end end end local function HideTalents(uiType) local ui = Ext.GetUIByType(uiType) if ui then local main = ui:GetRoot() if main then local hasEntries = true local removed = false local list = nil local idProperty = "id" if uiType == Data.UIType.characterSheet then list = main.stats_mc.talentHolder_mc.list idProperty = "statId" elseif uiType == Data.UIType.statsPanel_c then list = main.mainpanel_mc.stats_mc.talents_mc.statList idProperty = "id" elseif uiType == Data.UIType.characterCreation then list = main.CCPanel_mc.talents_mc.talentList idProperty = "talentID" elseif uiType == Data.UIType.characterCreation_c then list = main.CCPanel_mc.talents_mc.contentList idProperty = "contentID" end for talentId,count in pairs(TalentManager.HiddenCount) do if count > 0 then hasEntries = true local talentEnum = Data.TalentEnum[talentId] if uiType == Data.UIType.characterCreation_c then if racialTalents[talentId] then list = main.CCPanel_mc.talents_mc.racialList else list = main.CCPanel_mc.talents_mc.contentList end end for i=0,#list.content_array do local entry = list.content_array[i] if entry and entry[idProperty] == talentEnum then list.removeElement(i, false) removed = true break end end end end if removed then list.positionElements() elseif Vars.DebugMode and hasEntries then --Ext.PrintError("Failed to remove any talents", Ext.JsonStringify(TalentManager.HiddenCount)) end end end end ---@param ui UIObject local function DisplayTalents(ui, call, ...) ---@type EsvCharacter local player = nil local handle = ui:GetPlayerHandle() if handle ~= nil then player = Ext.GetCharacter(handle) elseif Client.Character ~= nil then player = Client:GetCharacter() end if player ~= nil then TalentManager.Update(ui, player) local length = #Listeners.OnTalentArrayUpdating if length > 0 then for i=1,length do local callback = Listeners.OnTalentArrayUpdating[i] local talentArrayStartIndex = UI.GetArrayIndexStart(ui, "talent_array", 3) local b,err = xpcall(callback, debug.traceback, ui, player, talentArrayStartIndex, Data.TalentEnum) if not b then Ext.PrintError("Error calling function for 'OnTalentArrayUpdating':\n", err) end end end local typeid = ui:GetTypeId() UIExtensions.StartTimer("LeaderLib_HideTalents_Sheet", 5, function(timerName, isComplete) HideTalents(typeid) end) end end -- addTalentElement(talentId:uint, talentName:String, state:Boolean, choosable:Boolean, isRacial:Boolean) : * ---@param ui UIObject local function DisplayTalents_CC(ui, call, ...) if GameSettings.Default == nil then -- This function may run before the game is "Running" and the settings load normally. LoadGameSettings() end ---@type EsvCharacter local player = nil local handle = ui:GetPlayerHandle() if handle ~= nil then player = Ext.GetCharacter(handle) elseif Client.Character ~= nil then player = Client:GetCharacter() end if player ~= nil then local root = ui:GetRoot() local talent_mc = root.CCPanel_mc.talents_mc TalentManager.Update_CC(ui, talent_mc, player) local typeid = ui:GetTypeId() UIExtensions.StartTimer("LeaderLib_HideTalents_CharacterCreation", 5, function(timerName, isComplete) HideTalents(typeid) end) end end Ext.RegisterListener("SessionLoaded", function() Ext.RegisterUITypeInvokeListener(Data.UIType.characterSheet, "updateArraySystem", DisplayTalents) Ext.RegisterUITypeInvokeListener(Data.UIType.statsPanel_c, "updateArraySystem", DisplayTalents) --characterCreation.swf Ext.RegisterUITypeInvokeListener(Data.UIType.characterCreation, "updateTalents", DisplayTalents_CC) Ext.RegisterUITypeInvokeListener(Data.UIType.characterCreation_c, "updateTalents", DisplayTalents_CC) TalentManager.LoadRequirements() ---Divine Talents if Ext.IsModLoaded("ca32a698-d63e-4d20-92a7-dd83cba7bc56") or GameSettings.Settings.Client.DivineTalentsEnabled then TalentManager.ToggleDivineTalents(true) end TalentManager.Gamepad.RegisterListeners() -- if Vars.DebugMode then -- TalentManager.HideTalent("all", "LeaderLib") -- --TalentManager.HideTalent("Raistlin", "LeaderLib") -- TalentManager.UnhideTalent("FaroutDude", "LeaderLib") -- end end) end end
-- connect to wifi wifi.sta.config("name","password") wifi.sta.connect() tmr.delay(1000000) -- trying get request sk=net.createConnection(net.TCP, 0) sk:on("receive", function(sck, c) print(c) end ) sk:connect(3000,"52.138.39.36") sk:send("GET /ws\r\nConnection: keep-alive\r\nAccept: /\r\n\r\n") -- trying single quotation marks sk=net.createConnection(net.TCP, 0) sk:on('receive', function(sck, c) print(c) end ) sk:connect(3000,'52.138.39.36') sk:send('GET /ws\r\nConnection: keep-alive\r\nAccept: */*\r\n\r\n') -- trying post request data_table = { to_search = "Apple", } data = "" for param,value in pairs(data_table) do data = data .. param.."="..value.."&" end print(data) sk=net.createConnection(net.TCP, 0) sk:on("receive", function(sck, c) print(c) end ) sk:connect(3000,"52.138.39.36") sk:send("POST /search_byname\r\nHost: 52.138.39.36\r\nConnection: keep-alive\r\nAccept: /\r\n\r\nContent-Type: application/x-www-form-urlencoded\r\n".. "Content-Length: "..string.len(data).."\r\n".. "\r\n".. data) -- post request format uri = "/login" host = "52.138.39.36" sk:send("POST "..uri.." HTTP/1.1\r\n".. "Host: "..host.."\r\n".. "Connection: keep-alive\r\n".. "Accept: /\r\n\r\n".. "Content-Type: application/x-www-form-urlencoded\r\n".. "\r\n"..) --------------------------------------- request = "POST "..uri.." HTTP/1.1\r\n".. "Host: "..host.."\r\n".. "Connection: close\r\n".. "Content-Type: application/x-www-form-urlencoded\r\n".. "Content-Length: "..string.len(data).."\r\n".. "\r\n".. data
admins = { "lars@<DOMAINNAME>" } modules_enabled = { -- Generally required "roster"; -- Allow users to have a roster. Recommended ;) "saslauth"; -- Authentication for clients and servers. Recommended if you want to log in. "tls"; -- Add support for secure TLS on c2s/s2s connections "dialback"; -- s2s dialback support "disco"; -- Service discovery -- Not essential, but recommended "private"; -- Private XML storage (for room bookmarks, etc.) "vcard"; -- Allow users to set vCards -- These are commented by default as they have a performance impact --"privacy"; -- Support privacy lists --"compression"; -- Stream compression -- Nice to have "version"; -- Replies to server version requests "uptime"; -- Report how long server has been running "time"; -- Let others know the time here on this server "ping"; -- Replies to XMPP pings with pongs "pep"; -- Enables users to publish their mood, activity, playing music and more "register"; -- Allow users to register on this server using a client and change passwords -- Admin interfaces "admin_adhoc"; -- Allows administration via an XMPP client that supports ad-hoc commands --"admin_telnet"; -- Opens telnet console interface on localhost port 5582 -- HTTP modules "bosh"; -- Enable BOSH clients, aka "Jabber over HTTP" --"http_files"; -- Serve static files from a directory over HTTP -- Other specific functionality --"posix"; -- POSIX functionality, sends server to background, enables syslog, etc. --"groups"; -- Shared roster support --"announce"; -- Send announcement to all online users --"welcome"; -- Welcome users who register accounts --"watchregistrations"; -- Alert admins of registrations --"motd"; -- Send a message to users when they log in --"legacyauth"; -- Legacy authentication. Only used by some old clients and bots. }; -- These modules are auto-loaded, but should you want -- to disable them then uncomment them here: modules_disabled = { -- "offline"; -- Store offline messages -- "c2s"; -- Handle client connections -- "s2s"; -- Handle server-to-server connections }; -- Disable account creation by default, for security -- For more information see http://prosody.im/doc/creating_accounts allow_registration = false; -- These are the SSL/TLS-related settings. If you don't want -- to use SSL/TLS, you may comment or remove this ssl = { key = "/etc/prosody/certs/<DOMAINNAME>.key"; certificate = "/etc/prosody/certs/<DOMAINNAME>.crt"; } c2s_require_encryption = true; s2s_secure_auth = false s2s_secure_domains = { "jabber.org" } data_path = "/tmp"; daemonize = false; authentication = "internal_hashed"; storage = "sql"; sql = { driver ="MySQL"; database = "prosody"; host = "mariadb"; port = 3306; username = "prosody"; password = "prosody"; } sql_manage_tables = true; log = { "*console"; -- Log to the console, useful for debugging with daemonize=false } pidfile = "prosody.pid"; consider_bosh_secure = true; VirtualHost "localhost" VirtualHost "<DOMAINNAME>" ssl = { key = "/etc/prosody/certs/<DOMAINNAME>.key"; certificate = "/etc/prosody/certs/<DOMAINNAME>.crt"; } Component "conference.<DOMAINNAME>" "muc"; name = "Conference Rooms"; restrict_room_creation = "admin";
import("SampleAssembly") -- Import the 'Sample' component's assembly (SampleAssembly) function run() Restart() Log("Starting 'Value' test") local sampleManager = GetGameObjectFromPath("SampleManager") sample = GetComponent(sampleManager, Sample) -- Get the 'Sample' component on the SampleManager GameObject Wait(3) -- Wait for 3s if sample.value ~= 100 then Error("sample.value should be 100") end Log("'Value' test success") end