content
stringlengths
5
1.05M
local widgetType, widgetVersion = 'Slider', 1 local Wasabi = LibStub and LibStub('Wasabi', true) if(not Wasabi or (Wasabi:GetWidgetVersion(widgetType) or 0) >= widgetVersion) then return end local methods = {} function methods:SetRange(min, max) self:SetMinMaxValues(min, max) self.Min:SetText(min) self.Max:SetText(max) end function methods:SetStep(step) assert(tonumber(step), 'Step must be a number') step = tonumber(step) self:SetValueStep(step) local _, decimals = string.split('.', step) self.decimals = decimals and #decimals or 0 self.decimalFormat = string.format('%%.%df', self.decimals) end function methods:Update(value) value = tonumber(string.format(self.decimalFormat, value)) local min, max = self:GetMinMaxValues() value = math.min(math.max(value, min), max) self:SetValue(value) self.EditBox:SetText(value) self.panel:SetVariable(self.key, value) self:Fire('Update', value) end local function OnEnable(self) self.EditBox:Enable() self.EditBox:SetTextColor(1, 1, 1) self.Thumb:SetVertexColor(1, 1, 1) end local function OnDisable(self) self.EditBox:Disable() self.EditBox:SetTextColor(1/2, 1/2, 1/2) self.Thumb:SetVertexColor(1/2, 1/2, 1/2) end local function OnMouseWheel(self, direction) self:Update(self:GetValue() + direction * self:GetValueStep()) end local function OnValueChanged(self, value) self:Update(value) end local function OnEscapePressed(self) self:GetParent():Update(self:GetParent():GetValue()) self:ClearFocus() end local function OnEnterPressed(self) local value = tonumber((self:GetText():gsub(',', '.'))) self:GetParent():Update(value or self:GetParent():GetValue()) self:ClearFocus() end local TestString = UIParent:CreateFontString(nil, nil, 'GameFontHighlightSmall') local function OnTextChanged(self, ...) local Slider = self:GetParent() local _, max = Slider:GetMinMaxValues() TestString:SetFormattedText(Slider.decimalFormat, max .. '.' .. 2e9) self:SetWidth(TestString:GetStringWidth() * 3) self:SetText(self:GetText()) self:SetScript('OnTextChanged', nil) end Wasabi:RegisterWidget(widgetType, widgetVersion, function(panel, key) local _NAME = panel:GetName() .. key:gsub('^%l', string.upper) .. widgetType local Slider = CreateFrame('Slider', _NAME, panel, 'OptionsSliderTemplate') Slider:SetScript('OnMouseWheel', OnMouseWheel) Slider:SetScript('OnValueChanged', OnValueChanged) Slider:SetScript('OnEnable', OnEnable) Slider:SetScript('OnDisable', OnDisable) Slider:SetObeyStepOnDrag(true) Slider.Min = _G[_NAME .. 'Low'] Slider.Max = _G[_NAME .. 'High'] Slider.Thumb = _G[_NAME .. 'Thumb'] Slider.panel = panel Slider.key = key local EditBox = CreateFrame('EditBox', nil, Slider) EditBox:SetPoint('TOP', Slider, 'BOTTOM', 0, 3) EditBox:SetSize(100, 18) EditBox:SetJustifyH('CENTER') EditBox:SetFontObject('GameFontHighlightSmall') EditBox:SetAutoFocus(false) EditBox:SetScript('OnEnterPressed', OnEnterPressed) EditBox:SetScript('OnEscapePressed', OnEscapePressed) EditBox:SetScript('OnTextChanged', OnTextChanged) Slider.EditBox = EditBox for method, func in next, methods do Slider[method] = func end Wasabi:InjectBaseWidget(Slider, 'Text') Wasabi:InjectBaseWidget(Slider, 'Events') -- Defaults Slider:SetStep(1) panel:AddObject(key, Slider) return Slider end)
-- ---------------------------------- -- -- Rolling Cubes vs Spinning Hexagons -- -- --------- by: Tasty Kiwi --------- -- -- ---------------------------------- -- -- Import helpers local angle_helpers = require("/dynamic/helpers/angle_helpers.lua") local player_helpers = require("/dynamic/helpers/player_helpers.lua") local floating_message = require("/dynamic/helpers/floating_message.lua") local shield_box = require("/dynamic/helpers/boxes/shield_box.lua") local cannon_box = require("/dynamic/helpers/boxes/cannon_box.lua") -- Set level size local width = 500fx local height = 300fx pewpew.set_level_size(width, height) -- Make fury-like background local background = pewpew.new_customizable_entity(0fx, 0fx) pewpew.customizable_entity_set_mesh(background, "/dynamic/assets/background.lua", 0) pewpew.customizable_entity_start_spawning(background, 120) pewpew.customizable_entity_configure_music_response(background, {color_start = 0xffffff66, color_end = 0xffffffff, scale_z_start = 1fx, scale_z_end = 2fx}) -- Create player local weapon_config = {frequency = pewpew.CannonFrequency.FREQ_7_5, cannon = pewpew.CannonType.TRIPLE, duration=999999999} local ship = player_helpers.new_player_ship(width / 2fx, height / 2fx, 0) pewpew.configure_player(0, {camera_distance = 50fx, shield = 6}) pewpew.configure_player_ship_weapon(ship, weapon_config) -- Functions for making random positions local function random_position_rewards() return fmath.random_fixedpoint(50fx, width-50fx), fmath.random_fixedpoint(50fx, height-50fx) end local function random_position_enemies() return fmath.random_fixedpoint(25fx, width-25fx), fmath.random_fixedpoint(25fx, height-25fx) end local time = 0 pewpew.add_update_callback( function() time = time + 1 -- Make cycle for enemies and powerups local modulo = time % 100 local modulo2 = time % 1100 if modulo2 == 111 or modulo2 == 666 then local x,y = random_position_rewards() shield_box.new(x, y, weapon_config) end if modulo2 == 999 or modulo2 == 333 then local x,y = random_position_rewards() cannon_box.new(x, y, fmath.random_int(0, 3)) end if modulo2 == 777 then local x,y = random_position_rewards() pewpew.new_bomb(x, y, pewpew.BombType.SMALL_ATOMIZE) end if modulo2 == 444 then local x,y = random_position_rewards() pewpew.new_bomb(x, y, pewpew.BombType.FREEZE) end if modulo2 == 1099 then local x,y = random_position_rewards() pewpew.new_bomb(x, y, pewpew.BombType.REPULSIVE) end if modulo == 66 then pewpew.new_rolling_cube(25fx, 25fx) pewpew.new_rolling_cube(25fx, 275fx) pewpew.new_rolling_cube(475fx, 25fx) pewpew.new_rolling_cube(475fx, 275fx) end if modulo == 77 then pewpew.new_wary(125fx, 150fx) pewpew.new_wary(375fx, 150fx) end if modulo2 == 555 then local x,y = random_position_enemies() pewpew.new_inertiac(x, y, 1fx, fmath.tau() / 4fx) end if pewpew.get_player_configuration(0)["has_lost"] == true then pewpew.stop_game() end end)
ITEM.name = "Cat Meat" ITEM.description = "Uncooked meat from a Cat." ITEM.longdesc = "The texture of the flesh is very smooth compared to other types of mutant meat. This type of meat is not very popular within the zone, as it is said to make you feel nauseous for a few hours while digesting it." ITEM.model = "models/lostsignalproject/items/consumable/raw_pseudodog.mdl" ITEM.price = 280 ITEM.width = 1 ITEM.height = 1 ITEM.WeightPerHunger = 0.070 ITEM.BaseWeight = 1.125 ITEM.WeightPerLevel = 0.628 ITEM.meal = "meal_cat" ITEM.img = ix.util.GetMaterial("cotz/ui/icons/food_16.png") ITEM.sound = "stalkersound/inv_eat_mutant_food.mp3" ITEM:Hook("use", function(item) item.player:EmitSound(item.sound or "items/battery_pickup.wav") item.player:AddBuff("debuff_radiation", 10, { amount = 22/20 }) ix.chat.Send(item.player, "iteminternal", "eats a bit of their "..item.name..".", false) end) function ITEM:PopulateTooltipIndividual(tooltip) if !self.entity then ix.util.PropertyDesc(tooltip, "Low Tier Mutant Meat", Color(0, 255, 0)) ix.util.PropertyDesc(tooltip, "Toxic Food", Color(255, 0, 0)) end end
local calc_util = require("scripts.calc.util") --- @param entity LuaEntity return function(rates, entity, emissions_per_second, prototypes) local entity_prototype = entity.prototype local fluidbox = entity.fluidbox for i, fluidbox_prototype in ipairs(entity_prototype.fluidbox_prototypes) do local fluid if fluidbox_prototype.filter then fluid = fluidbox_prototype.filter.name elseif fluidbox[i] then fluid = fluidbox[i].name end if fluid then --- @type LuaFluidPrototype local fluid_prototype = prototypes.fluid[fluid] local fluid_usage = entity_prototype.fluid_usage_per_tick * 60 calc_util.add_rate(rates.materials, "input", "fluid", fluid, fluid_prototype.localised_name, fluid_usage) local added_emissions = entity_prototype.electric_energy_source_prototype.emissions * entity_prototype.max_energy_production * 60 * fluid_prototype.emissions_multiplier emissions_per_second = emissions_per_second + added_emissions end end return emissions_per_second end
ENT.Base = "base_nextbot" ENT.Author = "MetaMan" ENT.PrintName = "Ghost" ENT.Spawnable = false ENT.AdminSpawnable = false ENT.AutomaticFrameAdvance = true ENT.PhysgunDisabled = true ENT.m_tblToolsAllowed = {} local boo = "vo/halloween_boo%i.mp3" -- 1 to 7 local haunted = "vo/halloween_haunted%i.mp3" -- 1 to 5 local moan = "vo/halloween_moan%i.mp3" -- 1 to 4 function ENT:CanConstruct() return false end function ENT:CanTool() return false end function ENT:StartTouch(ent) if ent:IsPlayer() and not ent:IsScared() then if SERVER then self:EmitSound(string.format(boo, math.random(1, 7)), 511) end ent:SetScared(true, 5) end end function ENT:Think() if SERVER and self:Health() > 0 and CurTime() > self.__sound then self:EmitSound(string.format(moan, math.random(1, 4))) self.__sound = CurTime() + math.random(15, 45) end local min, max = self:WorldSpaceAABB() local plys = ents.FindInBox(min, max) for i = 1, #plys do if plys[i]:IsPlayer() then self:StartTouch(plys[i]) end end end
#!/usr/bin/env lua Spore = require 'Spore' require 'Test.More' plan(6) error_like( [[Spore.new_from_lua(true)]], "bad argument #1 to new_from_lua %(table expected, got boolean%)" ) error_like( [[Spore.new_from_lua({}, true)]], "bad argument #2 to new_from_lua %(table expected, got boolean%)" ) local client = Spore.new_from_lua{ base_url = 'http://services.org/restapi/', methods = { get_info = { path = '/show', method = 'GET', }, }, } type_ok( client, 'table' ) type_ok( client.enable, 'function' ) type_ok( client.reset_middlewares, 'function' ) type_ok( client.get_info, 'function' )
--[[ MIT License Copyright (c) 2019-2021 Love2D Community <love2d.org> 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 Cursor = require(SLAB_PATH .. '.Internal.Core.Cursor') local DrawCommands = require(SLAB_PATH .. '.Internal.Core.DrawCommands') local LayoutManager = require(SLAB_PATH .. '.Internal.UI.LayoutManager') local Mouse = require(SLAB_PATH .. '.Internal.Input.Mouse') local Region = require(SLAB_PATH .. '.Internal.UI.Region') local Stats = require(SLAB_PATH .. '.Internal.Core.Stats') local Style = require(SLAB_PATH .. '.Style') local Text = require(SLAB_PATH .. '.Internal.UI.Text') local Window = require(SLAB_PATH .. '.Internal.UI.Window') local ListBox = {} local Instances = {} local ActiveInstance = nil local EMPTY = {} local IGNORE = { Ignore = true } local function GetItemInstance(instance, id) if not instance then return end if instance.Items[id] == nil then instance.Items[id] = { Id = id, X = 0, Y = 0, W = 0, H = 0, } end return instance.Items[id] end local function GetInstance(id) if Instances[id] == nil then Instances[id] = { Id = id, X = 0, Y = 0, W = 0, H = 0, Items = {}, ActiveItem = nil, HotItem = nil, Selected = false, StatHandle = nil, Region = { AutoSizeContent = true, NoBackground = true, Intersect = true, }, } end return Instances[id] end function ListBox.Begin(id, options) local statHandle = Stats.Begin('ListBox', 'Slab') options = options or EMPTY local w = options.W or 150 local h = options.H or 150 local rounding = options.Rounding or Style.WindowRounding local instance = GetInstance(Window.GetItemId(id)) if options.Clear then for i = 1, #instance.Items do instance.Items[i] = nil end end w, h = LayoutManager.ComputeSize(w, h) LayoutManager.AddControl(w, h, 'ListBox') do local remainingW, remainingH = Window.GetRemainingSize() if options.StretchW then w = remainingW end if options.StretchH then h = remainingH end end local x, y = Cursor.GetPosition() instance.X = x instance.Y = y instance.W = w instance.H = h instance.StatHandle = statHandle ActiveInstance = instance Cursor.SetItemBounds(x, y, w, h) Cursor.AdvanceY(0) Window.AddItem(x, y, w, h, instance.Id) local isObstructed = Window.IsObstructedAtMouse() local mouseX, mouseY = Window.GetMousePosition() do local tx, ty = Window.TransformPoint(x, y) local region = instance.Region region.X = x region.Y = y region.W = w region.H = h region.SX = tx region.SY = ty region.MouseX = mouseX region.MouseY = mouseY region.ResetContent = Window.HasResized() region.IsObstructed = isObstructed region.Rounding = rounding Region.Begin(instance.Id, region) end instance.HotItem = nil mouseX, mouseY = Region.InverseTransform(instance.Id, mouseX, mouseY) for k, v in pairs(instance.Items) do if not isObstructed and not Region.IsHoverScrollBar(instance.Id) and v.X <= mouseX and mouseX <= v.X + instance.W and v.Y <= mouseY and mouseY <= v.Y + v.H and Region.Contains(mouseX, mouseY) then instance.HotItem = v end if instance.HotItem == v or v.Selected then DrawCommands.Rectangle('fill', v.X, v.Y, instance.W, v.H, Style.TextHoverBgColor) end end LayoutManager.Begin('Ignore', IGNORE) end function ListBox.BeginItem(id, options) options = options or EMPTY assert(ActiveInstance ~= nil, "Trying to call BeginListBoxItem outside of BeginListBox.") if ActiveInstance.ActiveItem ~= nil then error(("BeginListBoxItem was called for item '%s' without a call to EndListBoxItem."):format( ActiveInstance.ActiveItem.Id or "nil" )) end local item = GetItemInstance(ActiveInstance, id) item.X = ActiveInstance.X item.Y = Cursor.GetY() Cursor.SetX(item.X) Cursor.AdvanceX(0) ActiveInstance.ActiveItem = item ActiveInstance.ActiveItem.Selected = options.Selected end function ListBox.IsItemClicked(button, isDoubleClick) assert(ActiveInstance ~= nil, "Trying to call IsItemClicked outside of BeginListBox.") assert(ActiveInstance.ActiveItem ~= nil, "IsItemClicked was called outside of BeginListBoxItem.") if ActiveInstance.HotItem ~= ActiveInstance.ActiveItem then return false end button = button or 1 if isDoubleClick then return Mouse.IsDoubleClicked(button) else return Mouse.IsClicked(button) end end function ListBox.EndItem() assert(ActiveInstance ~= nil, "Trying to call BeginListBoxItem outside of BeginListBox.") assert(ActiveInstance.ActiveItem ~= nil, "Trying to call EndListBoxItem without calling BeginListBoxItem.") local itemX, itemY, itemW, itemH = Cursor.GetItemBounds() ActiveInstance.ActiveItem.W = itemW ActiveInstance.ActiveItem.H = Cursor.GetLineHeight() Cursor.SetY(ActiveInstance.ActiveItem.Y + ActiveInstance.ActiveItem.H) Cursor.AdvanceY(0) ActiveInstance.ActiveItem = nil end function ListBox.End() assert(ActiveInstance ~= nil, "EndListBox was called without calling BeginListBox.") Region.End() Region.ApplyScissor() Cursor.SetItemBounds(ActiveInstance.X, ActiveInstance.Y, ActiveInstance.W, ActiveInstance.H) Cursor.SetPosition(ActiveInstance.X, ActiveInstance.Y) Cursor.AdvanceY(ActiveInstance.H) LayoutManager.End() Stats.End(ActiveInstance.StatHandle) ActiveInstance = nil end return ListBox
local Promise = require(script.Parent.Promise) -- constants local TYPE_NIL = "nil" local TYPE_STRING = "string" local TYPE_TABLE = "table" local TYPE_USERDATA = "userdata" local TYPE_FUNCTION = "function" local TYPE_INSTANCE = "Instance" local TS = {} -- runtime classes TS.Promise = Promise local Symbol do Symbol = {} Symbol.__index = Symbol setmetatable(Symbol, { __call = function(_, description) local self = setmetatable({}, Symbol) self.description = description or "" return self end }) local symbolRegistry = setmetatable({}, { __index = function(self, k) self[k] = Symbol(k) return self[k] end }) function Symbol:__tostring() return "Symbol(" .. self.description .. ")" end function Symbol:toString() return tostring(self) end -- Symbol.for function Symbol.getFor(key) return symbolRegistry[key] end function Symbol.keyFor(goalSymbol) for key, symbol in pairs(symbolRegistry) do if symbol == goalSymbol then return key end end end end TS.Symbol = Symbol -- module resolution local globalModules = script.Parent.Parent:FindFirstChild("Modules") function TS.getModule(moduleName, object) if not globalModules then error("Could not find any modules!", 2) end if object:IsDescendantOf(globalModules) then while object.Parent do local modules = object == globalModules and object or object:FindFirstChild("node_modules") if modules then local module = modules:FindFirstChild(moduleName) if module then return module end end object = object.Parent end else local module = globalModules:FindFirstChild(moduleName) if module then return module end end error("Could not find module: " .. moduleName, 2) end function TS.import(root, ...) local currentInstance = typeof(root) == TYPE_INSTANCE and root or game:GetService(root) if not currentInstance then error("Failed to find root in which to search for ModuleScripts, got " .. typeof(root) .. " " .. tostring(root), 2) end for i = 1, select("#", ...) do currentInstance = currentInstance:WaitForChild((select(i, ...))) end if currentInstance.ClassName == "ModuleScript" then return require(currentInstance) else error("Failed to import! Expected ModuleScript, got " .. currentInstance.ClassName, 2) end end function TS.exportNamespace(module, ancestor) for key, value in pairs(module) do ancestor[key] = value end end -- general utility functions function TS.typeof(value) local type = typeof(value) if type == TYPE_TABLE or type == TYPE_USERDATA then return "object" elseif type == TYPE_NIL then return "undefined" else return type end end function TS.typeIs(value, typeName) return typeof(value) == typeName end function TS.instanceof(obj, class) -- custom Class.instanceof() check if typeof(class) == TYPE_TABLE and typeof(class.instanceof) == TYPE_FUNCTION then return class.instanceof(obj) end -- metatable check while obj ~= nil do if obj == class then return true end obj = getmetatable(obj) end return false end function TS.async(callback) return function(...) local args = { ... } return Promise.new(function(resolve, reject) coroutine.wrap(function() local ok, result = pcall(callback, unpack(args)) if ok then resolve(result) else reject(result) end end)() end) end end function TS.await(promise) if not Promise.is(promise) then return promise end local ok, result = promise:await() if ok then return result else TS.throw(ok == nil and "The awaited Promise was cancelled" or result) end end function TS.add(a, b) if typeof(a) == TYPE_STRING or typeof(b) == TYPE_STRING then return a .. b else return a + b end end function TS.round(a) if a < 0 then return math.ceil(a) else return math.floor(a) end end -- bitwise operations local function bitop(a, b, oper) local r, m, s = 0, 2^52 repeat s, a, b = a + b + m, a % m, b % m r, m = r + m * oper % (s - a - b), m / 2 until m < 1 return r end function TS.bor(a, b) a = TS.round(tonumber(a)) b = TS.round(tonumber(b)) return bitop(a, b, 1) end function TS.band(a, b) a = TS.round(tonumber(a)) b = TS.round(tonumber(b)) return bitop(a, b, 4) end function TS.bxor(a, b) a = TS.round(tonumber(a)) b = TS.round(tonumber(b)) return bitop(a, b, 3) end function TS.blsh(a, b) a = TS.round(tonumber(a)) b = TS.round(tonumber(b)) return a * 2 ^ b end function TS.brsh(a, b) a = TS.round(tonumber(a)) b = TS.round(tonumber(b)) return TS.round(a / 2 ^ b) end -- array macro functions function TS.array_forEach(list, callback) for i = 1, #list do callback(list[i], i - 1, list) end end function TS.array_map(list, callback) local result = {} for i = 1, #list do result[i] = callback(list[i], i - 1, list) end return result end function TS.array_filter(list, callback) local result = {} for i = 1, #list do local v = list[i] if callback(v, i - 1, list) == true then result[#result + 1] = v end end return result end function TS.array_slice(list, startI, endI) local length = #list if not startI then startI = 0 end if not endI then endI = length end if startI < 0 then startI = length + startI end if endI < 0 then endI = length + endI end startI = startI + 1 endI = endI + 1 local result = {} for i = startI, endI - 1 do result[i - startI + 1] = list[i] end return result end function TS.array_splice(list, start, deleteCount, ...) local len = #list local actualStart if start < 0 then actualStart = math.max(len + start, 0) else actualStart = math.min(start, len) end local items = { ... } local itemCount = #items local actualDeleteCount if not start then actualDeleteCount = 0 elseif not deleteCount then actualDeleteCount = len - actualStart else actualDeleteCount = math.min(math.max(deleteCount, 0), len - actualStart) end local out = {} local k = 0 while k < actualDeleteCount do local from = actualStart + k if list[from + 1] then out[k + 1] = list[from + 1] end k = k + 1 end if itemCount < actualDeleteCount then k = actualStart while k < len - actualDeleteCount do local from = k + actualDeleteCount local to = k + itemCount if list[from + 1] then list[to + 1] = list[from + 1] else list[to + 1] = nil end k = k + 1 end k = len while k > len - actualDeleteCount + itemCount do list[k] = nil k = k - 1 end elseif itemCount > actualDeleteCount then k = len - actualDeleteCount while k > actualStart do local from = k + actualDeleteCount local to = k + itemCount if list[from] then list[to] = list[from] else list[to] = nil end k = k - 1 end end k = actualStart for i = 1, #items do list[k + 1] = items[i] k = k + 1 end k = #list while k > len - actualDeleteCount + itemCount do list[k] = nil k = k - 1 end return out end function TS.array_some(list, callback) for i = 1, #list do if callback(list[i], i - 1, list) == true then return true end end return false end function TS.array_every(list, callback) for i = 1, #list do if callback(list[i], i - 1, list) == false then return false end end return true end function TS.array_indexOf(list, value, fromIndex) if fromIndex == nil then fromIndex = 0 end fromIndex = fromIndex + 1 for i = fromIndex, #list do if value == list[i] then return i - 1 end end return -1 end function TS.array_lastIndexOf(list, value, fromIndex) if fromIndex == nil then fromIndex = #list - 1 end fromIndex = fromIndex + 1 for i = fromIndex, 1, -1 do if value == list[i] then return i - 1 end end return -1 end function TS.array_reverse(list) local result = {} local length = #list for i = 1, length do result[i] = list[length - i + 1] end return result end function TS.array_reduce(list, callback, initialValue) local start = 1 if not initialValue then initialValue = list[start] start = start + 1 end local accumulator = initialValue for i = start, #list do accumulator = callback(accumulator, list[i], i) end return accumulator end function TS.array_reduceRight(list, callback, initialValue) local start = #list if not initialValue then initialValue = list[start] start = start - 1 end local accumulator = initialValue for i = start, 1, -1 do accumulator = callback(accumulator, list[i], i) end return accumulator end function TS.array_shift(list) return table.remove(list, 1) end function TS.array_unshift(list, ...) local args = { ... } local argsLength = #args for i = #list, 1, -1 do list[i + argsLength] = list[i] end for i = 1, argsLength do list[i] = args[i] end return #list end function TS.array_concat(list, ...) local args = { ... } local result = {} for i = 1, #list do result[i] = list[i] end for i = 1, #args do local value = args[i] for j = 1, #value do result[#result + 1] = value[j] end end return result end function TS.array_push(list, ...) local args = { ... } for i = 1, #args do list[#list + 1] = args[i] end return #list end function TS.array_pop(list) local length = #list local lastValue = list[length] list[length] = nil return lastValue end function TS.array_join(list, separator) if #list == 0 then return "" end if not separator then separator = ", " end local result = tostring(list[1]) for i = 2, #list do result = result .. separator .. tostring(list[i]) end return result end function TS.array_find(list, callback) for i = 1, #list do if callback(list[i], i - 1, list) == true then return list[i] end end end -- map macro functions function TS.map_new(value) local result = {} for _, pair in pairs(value) do result[pair[1]] = pair[2] end return result end function TS.map_clear(map) for key in pairs(map) do map[key] = nil end end function TS.map_delete(map, key) local has = TS.map_has(map, key) if has then map[key] = nil end return has end function TS.map_size(map) local result = 0 for _ in pairs(map) do result = result + 1 end return result end function TS.map_entries(map) local result = {} for key, value in pairs(map) do table.insert(result, {key, value}) end return result end function TS.map_forEach(map, callback) for key, value in pairs(map) do callback(value, key, map) end end function TS.map_get(map, key) return map[key] end function TS.map_has(map, key) return map[key] ~= nil end function TS.map_keys(map) local result = {} for key in pairs(map) do table.insert(result, key) end return result end function TS.map_set(map, key, value) map[key] = value return map end function TS.map_values(map) local result = {} for _, value in pairs(map) do table.insert(result, value) end return result end -- set macro functions function TS.set_new(value) local result = {} for _, v in pairs(value) do result[v] = true end return result end function TS.set_add(set, value) set[value] = true return set end TS.set_clear = TS.map_clear function TS.set_delete(set, value) local result = TS.set_has(set, value) set[value] = nil return result end function TS.set_forEach(set, callback) for key in pairs(set) do callback(key, key, set) end end TS.set_has = TS.map_has function TS.set_entries(map) local result = {} for key in pairs(map) do table.insert(result, {key, key}) end return result end TS.set_values = TS.map_keys TS.set_keys = TS.map_keys TS.set_size = TS.map_size -- string macro functions function TS.string_split(input, sep) local result = {} local count = 0 for str in input:gmatch(sep == "" and "." or "[^" .. sep .. "]+") do count = count + 1 result[count] = str end return result end -- Object static functions function TS.Object_keys(object) local result = {} for key in pairs(object) do result[#result + 1] = key end return result end function TS.Object_values(object) local result = {} for _, value in pairs(object) do result[#result + 1] = value end return result end function TS.Object_entries(object) local result = {} for key, value in pairs(object) do result[#result + 1] = {key, value} end return result end function TS.Object_assign(toObj, ...) local args = { ... } for i = 1, #args do for key, value in pairs(args[i]) do toObj[key] = value end end return toObj end function TS.Roact_combine(...) local args = {...} local result = {} for i = 1, #args do for key, value in pairs(args[i]) do if (type(key) == "number") then table.insert(result, value) else result[key] = value end end end return result end -- try catch utilities local function pack(...) local result = { ... } result.size = select("#", ...) return result end local throwStack = {} function TS.throw(value) if #throwStack > 0 then throwStack[#throwStack](value) else error("Uncaught " .. tostring(value), 2) end end function TS.try(tryCallback, catchCallback) local done = false local yielded = false local popped = false local resumeThread = coroutine.running() local returns local function pop() if not popped then popped = true throwStack[#throwStack] = nil end end local function resume() if yielded then local success, errorMsg = coroutine.resume(resumeThread) if not success then warn(errorMsg) end else done = true end end local function throw(value) pop() if catchCallback then returns = pack(catchCallback(value)) end resume() coroutine.yield() end throwStack[#throwStack + 1] = throw coroutine.wrap(function() returns = pack(tryCallback()) resume() end)() if not done then yielded = true coroutine.yield() end pop() return returns end return TS
-------------------------------------------------------------------------------- -- Analyze the initial Hamiltonian. -------------------------------------------------------------------------------- Temperature = Temperature * EnergyUnits.Kelvin.value Sk = DotProduct(WaveVector, {Sx, Sy, Sz}) Lk = DotProduct(WaveVector, {Lx, Ly, Lz}) Jk = DotProduct(WaveVector, {Jx, Jy, Jz}) Tk = DotProduct(WaveVector, {Tx, Ty, Tz}) Operators = {H_i, Ssqr, Lsqr, Jsqr, Sk, Lk, Jk, Tk, ldots_#f, N_#i, N_#f, "dZ"} Header = "Analysis of the %s Hamiltonian:\n" Header = Header .. "=================================================================================================================================\n" Header = Header .. "State E <S^2> <L^2> <J^2> <Sk> <Lk> <Jk> <Tk> <l.s> <N_#i> <N_#f> dZ\n" Header = Header .. "=================================================================================================================================\n" Footer = "=================================================================================================================================\n" if LmctLigandsHybridizationTerm then Operators = {H_i, Ssqr, Lsqr, Jsqr, Sk, Lk, Jk, Tk, ldots_#f, N_#i, N_#f, N_L1, "dZ"} Header = "Analysis of the %s Hamiltonian:\n" Header = Header .. "===========================================================================================================================================\n" Header = Header .. "State E <S^2> <L^2> <J^2> <Sk> <Lk> <Jk> <Tk> <l.s> <N_#i> <N_#f> <N_L1> dZ\n" Header = Header .. "===========================================================================================================================================\n" Footer = "===========================================================================================================================================\n" end local Psis_i, dZ_i = WavefunctionsAndBoltzmannFactors(H_i, NPsis, NPsisAuto, Temperature, nil, InitialRestrictions, CalculationRestrictions) PrintHamiltonianAnalysis(Psis_i, Operators, dZ_i, string.format(Header, "initial"), Footer) -- Stop the calculation if no spectra need to be calculated. if next(SpectraToCalculate) == nil then return end -------------------------------------------------------------------------------- -- Calculate the energy required to shift the spectrum to approximately zero. -------------------------------------------------------------------------------- ZeroShift = 0.0 if ShiftToZero == true then ZeroShift = CalculateEnergyDifference(HAtomic_i, InitialRestrictions, HAtomic_f, FinalRestrictions) end -------------------------------------------------------------------------------- -- Calculate and save the spectra. -------------------------------------------------------------------------------- local t = math.sqrt(1 / 2) Txy_#i_#f = NewOperator("CF", NFermions, IndexUp_#f, IndexDn_#f, IndexUp_#i, IndexDn_#i, {{2, -2, t * I}, {2, 2, -t * I}}) Txz_#i_#f = NewOperator("CF", NFermions, IndexUp_#f, IndexDn_#f, IndexUp_#i, IndexDn_#i, {{2, -1, t }, {2, 1, -t }}) Tyz_#i_#f = NewOperator("CF", NFermions, IndexUp_#f, IndexDn_#f, IndexUp_#i, IndexDn_#i, {{2, -1, t * I}, {2, 1, t * I}}) Tx2y2_#i_#f = NewOperator("CF", NFermions, IndexUp_#f, IndexDn_#f, IndexUp_#i, IndexDn_#i, {{2, -2, t }, {2, 2, t }}) Tz2_#i_#f = NewOperator("CF", NFermions, IndexUp_#f, IndexDn_#f, IndexUp_#i, IndexDn_#i, {{2, 0, 1 } }) Er = {t * (Eh[1] - I * Ev[1]), t * (Eh[2] - I * Ev[2]), t * (Eh[3] - I * Ev[3])} El = {-t * (Eh[1] + I * Ev[1]), -t * (Eh[2] + I * Ev[2]), -t * (Eh[3] + I * Ev[3])} local T = {Txy_#i_#f, Txz_#i_#f, Tyz_#i_#f, Tx2y2_#i_#f, Tz2_#i_#f} Tv_#i_#f = CalculateT(T, Ev, WaveVector) Th_#i_#f = CalculateT(T, Eh, WaveVector) Tr_#i_#f = CalculateT(T, Er, WaveVector) Tl_#i_#f = CalculateT(T, El, WaveVector) Tk_#i_#f = CalculateT(T, WaveVector, WaveVector) -- Initialize a table with the available spectra and the required operators. SpectraAndOperators = { ["Isotropic Absorption"] = {Txy_#i_#f, Txz_#i_#f, Tyz_#i_#f, Tx2y2_#i_#f, Tz2_#i_#f}, ["Absorption"] = {Tk_#i_#f,}, ["Circular Dichroic"] = {Tr_#i_#f, Tl_#i_#f}, ["Linear Dichroic"] = {Tv_#i_#f, Th_#i_#f}, } -- Create an unordered set with the required operators. local T_#i_#f = {} for Spectrum, Operators in pairs(SpectraAndOperators) do if ValueInTable(Spectrum, SpectraToCalculate) then for _, Operator in pairs(Operators) do T_#i_#f[Operator] = true end end end -- Give the operators table the form required by Quanty's functions. local T = {} for Operator, _ in pairs(T_#i_#f) do table.insert(T, Operator) end T_#i_#f = T Emin = Emin - (ZeroShift + ExperimentalShift) Emax = Emax - (ZeroShift + ExperimentalShift) if CalculationRestrictions == nil then G_#i_#f = CreateSpectra(H_f, T_#i_#f, Psis_i, {{"Emin", Emin}, {"Emax", Emax}, {"NE", NPoints}, {"Gamma", Gamma}, {"DenseBorder", DenseBorder}}) else G_#i_#f = CreateSpectra(H_f, T_#i_#f, Psis_i, {{"Emin", Emin}, {"Emax", Emax}, {"NE", NPoints}, {"Gamma", Gamma}, {"Restrictions", CalculationRestrictions}, {"DenseBorder", DenseBorder}}) end -- Shift the calculated spectra. G_#i_#f.Shift(ZeroShift + ExperimentalShift) -- Create a list with the Boltzmann probabilities for a given operator and wavefunction. local dZ_#i_#f = {} for _ in ipairs(T_#i_#f) do for j in ipairs(Psis_i) do table.insert(dZ_#i_#f, dZ_i[j]) end end local Ids = {} for k, v in pairs(T_#i_#f) do Ids[v] = k end -- Subtract the broadening used in the spectra calculations from the Lorentzian table. for i, _ in ipairs(Lorentzian) do -- The FWHM is the second value in each pair. Lorentzian[i][2] = Lorentzian[i][2] - Gamma end Pcl_#i_#f = 9 / 5 for Spectrum, Operators in pairs(SpectraAndOperators) do if ValueInTable(Spectrum, SpectraToCalculate) then -- Find the indices of the spectrum's operators in the table used during the -- calculation (this is unsorted). SpectrumIds = {} for _, Operator in pairs(Operators) do table.insert(SpectrumIds, Ids[Operator]) end if Spectrum == "Isotropic Absorption" then Giso = GetSpectrum(G_#i_#f, SpectrumIds, dZ_#i_#f, #T_#i_#f, #Psis_i) Giso = Giso / 15 SaveSpectrum(Giso, Prefix .. "_iso", Gaussian, Lorentzian, Pcl_#i_#f) end if Spectrum == "Absorption" then Gk = GetSpectrum(G_#i_#f, SpectrumIds, dZ_#i_#f, #T_#i_#f, #Psis_i) SaveSpectrum(Gk, Prefix .. "_k", Gaussian, Lorentzian, Pcl_#i_#f) end if Spectrum == "Circular Dichroic" then Gr = GetSpectrum(G_#i_#f, SpectrumIds[1], dZ_#i_#f, #T_#i_#f, #Psis_i) Gl = GetSpectrum(G_#i_#f, SpectrumIds[2], dZ_#i_#f, #T_#i_#f, #Psis_i) SaveSpectrum(Gr, Prefix .. "_r", Gaussian, Lorentzian, Pcl_#i_#f) SaveSpectrum(Gl, Prefix .. "_l", Gaussian, Lorentzian, Pcl_#i_#f) SaveSpectrum(Gr - Gl, Prefix .. "_cd", Gaussian, Lorentzian) end if Spectrum == "Linear Dichroic" then Gv = GetSpectrum(G_#i_#f, SpectrumIds[1], dZ_#i_#f, #T_#i_#f, #Psis_i) Gh = GetSpectrum(G_#i_#f, SpectrumIds[2], dZ_#i_#f, #T_#i_#f, #Psis_i) SaveSpectrum(Gv, Prefix .. "_v", Gaussian, Lorentzian, Pcl_#i_#f) SaveSpectrum(Gh, Prefix .. "_h", Gaussian, Lorentzian, Pcl_#i_#f) SaveSpectrum(Gv - Gh, Prefix .. "_ld", Gaussian, Lorentzian) end end end
local api = vim.api local Path = require("plenary.path") local M = {} -- Checks to see if an executable is present for single or list of executables -- Note that give a list, if any is not found, this will return false Also, this -- is stolen from the nvim/nvim-lspconfig utils. M.has_bins = function(...) for i = 1, select("#", ...) do if 0 == vim.fn.executable((select(i, ...))) then return false end end return true end -- Checks to see if a user given table is defined. If so, merge it with a default. -- If not, just return the default table. This function favors the userTable on merge. -- @param defaultTable The default table to return or merge -- @param userTable The user defined table to check if exists and then merge -- @return a new table that is either the default or merged with the user one. M.check_exists_and_merge = function(defaultTable, userTable) -- TODO should we add another check in here to ensure that a key that a user -- is trying to set actually exists in the default table? if not userTable then return defaultTable else return vim.tbl_extend("force", defaultTable, userTable) end end M.metals_status = function(text) if text then api.nvim_set_var("metals_status", text) else api.nvim_set_var("metals_status", "") end end -- Location of any files or executables that nvim-metals will create on your system M.nvim_metals_cache_dir = Path.new(vim.fn.stdpath("cache"), "nvim-metals") --- Strip the leading and trailing spaces of a string --- @param s string the string you want to trim. M.full_trim = function(s) return (s:gsub("^%s*(.-)%s*$", "%1")) end --- Strip trailing whites and trailing empty lines --- @param s string the string you want to trim. M.trim_end = function(s) return string.gsub(s, "[ \t]+%f[\r\n%z]", "") end M.split_on = function(s, delimiter) local result = {} local from = 1 local delim_from, delim_to = string.find(s, delimiter, from) while delim_from do table.insert(result, string.sub(s, from, delim_from - 1)) from = delim_to + 1 delim_from, delim_to = string.find(s, delimiter, from) end table.insert(result, string.sub(s, from)) return result end M.reverse = function(t) for i = 1, math.floor(#t / 2) do local j = #t - i + 1 t[i], t[j] = t[j], t[i] end end M.title_case = function(first, rest) return first:upper() .. rest:lower() end M.camel_to_pascal = function(s) local parts = M.split_on(s, "_") local pascal_string = "" for _, part in pairs(parts) do local capitalized_part = string.gsub(part, "(%a)([%w_']*)", M.title_case) pascal_string = pascal_string .. capitalized_part end return pascal_string end M.merge_lists = function(a, b) if b == nil then if a == nil then return {} else return a end else local merged = vim.deepcopy(a) for _, v in ipairs(b) do if type(v) == "string" then table.insert(merged, v) end end return merged end end M.starts_with = function(text, prefix) return text:find(prefix, 1, true) == 1 end return M
slot0 = class("ChallengeFleet", import(".ChapterFleet")) slot0.Ctor = function (slot0) slot0.id = 1 slot0[TeamType.Vanguard] = {} slot0[TeamType.Main] = {} slot0.ships = {} slot0.stgPicked = {} slot0.stgId = 0 slot0.mirrors = nil end slot0.fetchShipVO = function (slot0, slot1) if slot0.mirrors then return Clone(slot0.mirrors[slot1]) else return getProxy(BayProxy):getShipById(slot1) end end slot0.updateShipMirrors = function (slot0, slot1) slot0.mirrors = slot1 end slot0.update = function (slot0, slot1) _.each(slot1.strategy_list, function (slot0) slot0[slot0.id] = slot0.count end) slot0.stgPicked = {} slot0.stgId = (slot1.strategy_id == 0 and 1) or slot1.strategy_id slot0.updateShips(slot0, slot1.ship_list) end slot0.updateShips = function (slot0, slot1) slot0[TeamType.Vanguard] = {} slot0[TeamType.Main] = {} slot0.ships = {} _.each(slot1 or {}, function (slot0) if slot0:fetchShipVO(slot0.id) then slot1.hpRant = slot0.hp_rant slot1.strategies = Clone(slot0.strategies) slot0.ships[slot1.id] = slot1 table.insert(slot0[slot1:getTeamType()], slot1) end end) end slot0.retreat = function (slot0) for slot4, slot5 in pairs(slot0.ships) do slot5.hpRant = 10000 slot5.strategies = {} end slot0.mirrors = nil end slot0.flushShips = function (slot0) for slot5, slot6 in ipairs(slot1) do if slot0:fetchShipVO(slot6) then slot7.hpRant = slot0.ships[slot6].hpRant slot7.strategies = slot0.ships[slot6].strategies end slot0.ships[slot6] = slot7 end _.each(slot0[TeamType.Vanguard], function (slot0) if slot0.ships[slot0.id] then table.insert(table.insert, slot0.ships[slot0.id]) end end) slot0[TeamType.Vanguard] = {} _.each(slot0[TeamType.Main], function (slot0) if slot0.ships[slot0.id] then table.insert(table.insert, slot0.ships[slot0.id]) end end) slot0[TeamType.Main] = {} end slot0.getStrategies = function (slot0) return {} end slot0.updateShipStg = function (slot0, slot1, slot2, slot3) if slot0.ships[slot1] then _.each(slot4.strategies, function (slot0) if slot0.id == slot0 then slot0.count = slot1 end end) end end return slot0
------------------------------------------------------------------------------ -- IMPORTANT: DO NOT EDIT THIS FILE!!! -- ------------------------------------------------------------------------------ -- This file relies on other versions of itself being the same. -- -- If you need something in this file changed, please let the creator know! -- ------------------------------------------------------------------------------ -- CODE STARTS BELOW -- ------------- -- version -- ------------- local fileVersion = 3 local CustomCallbackHelper = CustomCallbackHelper or (ModConfigMenu and ModConfigMenu.PureMode and ModConfigMenu.PureMode.CustomCallbackHelper) --prevent older/same version versions of this script from loading if CustomCallbackHelper and CustomCallbackHelper.Version >= fileVersion then return CustomCallbackHelper end if not CustomCallbackHelper then CustomCallbackHelper = {} CustomCallbackHelper.Version = fileVersion if ModConfigMenu and ModConfigMenu.PureMode then ModConfigMenu.PureMode.CustomCallbackHelper = CustomCallbackHelper else _G.CustomCallbackHelper = CustomCallbackHelper end elseif CustomCallbackHelper.Version < fileVersion then local oldVersion = CustomCallbackHelper.Version -- handle old versions if CustomCallbackHelper.HandleGameStartedCallback then CustomCallbackHelper.Mod:RemoveCallback(ModCallbacks.MC_POST_PLAYER_INIT, CustomCallbackHelper.HandleGameStartedCallback) end if CustomCallbackHelper.ResetPlayerInited then CustomCallbackHelper.Mod:RemoveCallback(ModCallbacks.MC_POST_GAME_END, CustomCallbackHelper.ResetPlayerInited) CustomCallbackHelper.Mod:RemoveCallback(ModCallbacks.MC_PRE_GAME_EXIT, CustomCallbackHelper.ResetPlayerInited) end if CustomCallbackHelper.HandleModsLoadedCallback then CustomCallbackHelper.Mod:RemoveCallback(ModCallbacks.MC_INPUT_ACTION, CustomCallbackHelper.HandleModsLoadedCallback) end CustomCallbackHelper.Version = fileVersion end ----------- -- setup -- ----------- CustomCallbackHelper.Mod = CustomCallbackHelper.Mod or RegisterMod("Custom Callback Helper", 1) -------------------------- -- custom callback enum -- -------------------------- --use these callbacks with CustomCallbackHelper.AddCallback(modRef, callbackID, callbackFunction, extraVar1, extraVar2, etc) CustomCallbacks = CustomCallbacks or {} --PRE/POST ADD CUSTOM CALLBACK --custom callback functions that run when a callback gets added through callback helper's custom callback function (crazy huh?) --specify a callback id to make your code trigger for only that specific callback --in PRE you can return false to prevent the callback from being added --function(modRef, callbackID, callbackFunction, extraVarTable) CustomCallbacks.CCH_PRE_ADD_CUSTOM_CALLBACK = 1 CustomCallbacks.CCH_POST_ADD_CUSTOM_CALLBACK = 2 --GAME START --meant to be used in favor of MC_POST_GAME_STARTED, because that callback isnt the first callback to be triggered --triggers on the first instance of MC_POST_PLAYER_INIT, the first callback to be called when a game starts --makes sure to not trigger on further instances of MC_POST_PLAYER_INIT --checks the run counter for if the game is a continued game, if it is a continued game then isSaveGame will be true --function(player, isSaveGame) CustomCallbacks.CCH_GAME_STARTED = 3 --MODS LOADED --triggered on the first call to MC_INPUT_ACTION, which can trigger in the main menu --use this to have code that runs after all mod init code has ran, to handle mod intercompatibility --function() CustomCallbacks.CCH_MODS_LOADED = 4 ----------------------------- -- call callbacks function -- ----------------------------- --functionToHandleCallbacks is a function that takes what the mod's callback function has returned --return true within the functionToHandleCallbacks callback to cancel all future functions --this function returns true if the callbacks were cancelled, otherwise it returns nothing function CustomCallbackHelper.CallCallbacks(callbackId, functionToHandleCallbacks, args, extraArgs) if type(args) ~= "table" then args = {args} end if type(extraArgs) ~= "table" then extraArgs = {extraArgs} end if CustomCallbackHelper.Callbacks[callbackId] then for _, callbackData in ipairs(CustomCallbackHelper.Callbacks[callbackId]) do local extraVarsMatch = false if not callbackData.extraVariables or #callbackData.extraVariables == 0 then extraVarsMatch = true elseif #extraArgs > 0 then for extraVarIndex, extraVar in ipairs(callbackData.extraVariables) do if extraVar == extraArgs[extraVarIndex] then extraVarsMatch = true else extraVarsMatch = false break end end end if extraVarsMatch then local returned = callbackData.functionToCall(callbackData.modReference, table.unpack(args)) local handlerReturned = nil if type(functionToHandleCallbacks) == "function" then handlerReturned = functionToHandleCallbacks(returned) end if handlerReturned then return true end end end end end --------------------------- -- add callback function -- --------------------------- CustomCallbackHelper.RegisteredMods = CustomCallbackHelper.RegisteredMods or {} CustomCallbackHelper.Callbacks = CustomCallbackHelper.Callbacks or {} function CustomCallbackHelper.AddCallback(mod, callbackId, fn, ...) if type(mod) ~= "table" then error("CustomCallbackHelper.AddCallback Error: No valid mod reference provided", 3) end if type(callbackId) ~= "number" then error("CustomCallbackHelper.AddCallback Error: No valid callback ID provided", 3) end if type(fn) ~= "function" then error("CustomCallbackHelper.AddCallback Error: No valid callback function provided", 3) end local args = {...} --CCH_PRE_ADD_CUSTOM_CALLBACK local cancelCallback = nil CustomCallbackHelper.CallCallbacks ( CustomCallbacks.CCH_PRE_ADD_CUSTOM_CALLBACK, --callback id function(returned) --function to handle it if returned == false then cancelCallback = true return true end end, {mod, callbackId, fn, args}, --args to send callbackId --extra variable ) if cancelCallback then return end CustomCallbackHelper.Callbacks[callbackId] = CustomCallbackHelper.Callbacks[callbackId] or {} CustomCallbackHelper.Callbacks[callbackId][#CustomCallbackHelper.Callbacks[callbackId]+1] = {modReference = mod, functionToCall = fn, extraVariables = args} --CCH_POST_ADD_CUSTOM_CALLBACK CustomCallbackHelper.CallCallbacks ( CustomCallbacks.CCH_POST_ADD_CUSTOM_CALLBACK, --callback id nil, --function to handle it {mod, callbackId, fn, args}, --args to send callbackId --extra variable ) end ------------------------------ -- remove callback function -- ------------------------------ function CustomCallbackHelper.RemoveCallback(mod, callbackId, fn) if type(mod) ~= "table" then error("CustomCallbackHelper.RemoveCallback Error: No valid mod reference provided", 3) end if type(callbackId) ~= "number" then error("CustomCallbackHelper.RemoveCallback Error: No valid callback ID provided", 3) end if type(fn) ~= "function" then error("CustomCallbackHelper.RemoveCallback Error: No valid callback function provided", 3) end --extend the mod CustomCallbackHelper.ExtendMod(mod) --remove the callback from the callbacks table if CustomCallbackHelper.Callbacks[callbackId] then for i=#CustomCallbackHelper.Callbacks[callbackId], 1, -1 do local callbackData = CustomCallbackHelper.Callbacks[callbackId][i] if callbackData[1] == mod and callbackData[2] == fn then table.remove(CustomCallbackHelper.Callbacks[callbackId], i) end end end end ----------------------------------- -- remove all callbacks function -- ----------------------------------- function CustomCallbackHelper.RemoveAllCallbacks(mod) if type(mod) ~= "table" then error("CustomCallbackHelper.RemoveAllCallbacks Error: No valid mod reference provided", 2) end --extend the mod CustomCallbackHelper.ExtendMod(mod) --remove the callback from the callbacks table for _,callbacks in pairs(CustomCallbackHelper.Callbacks) do if type(callbacks) == "table" then for i=#callbacks, 1, -1 do local callbackData = callbacks[i] if callbackData[1] == mod then table.remove(callbacks, i) end end end end end ---------------- -- extend mod -- ---------------- function CustomCallbackHelper.ExtendMod(mod) --check if the mod is already in the table local modAlreadyRegistered = false for i=1, #CustomCallbackHelper.RegisteredMods do if CustomCallbackHelper.RegisteredMods[i] == mod then modAlreadyRegistered = true break end end --add mod to registered mods table if not modAlreadyRegistered then CustomCallbackHelper.RegisteredMods[#CustomCallbackHelper.RegisteredMods+1] = mod end if not mod.CustomCallbackHelperExtended or mod.CustomCallbackHelperExtended < fileVersion then mod.CustomCallbackHelperExtended = fileVersion --AddCustomCallback mod.AddCustomCallback = function(self, callbackId, fn, ...) CustomCallbackHelper.AddCallback(self, callbackId, fn, ...) end --RemoveCustomCallback mod.RemoveCustomCallback = function(self, callbackId, fn) CustomCallbackHelper.RemoveCallback(self, callbackId, fn) end end end --override RegisterMod to add AddCustomCallback function CustomCallbackHelper.OldRegisterMod = CustomCallbackHelper.OldRegisterMod or Isaac.RegisterMod function CustomCallbackHelper.RegisterMod(mod, modname, apiversion) --check if a mod that shares this mod's name is already in the table, and remove all of its callbacks if it is --helps handle luamod better for i=#CustomCallbackHelper.RegisteredMods, 1, -1 do if CustomCallbackHelper.RegisteredMods[i].Name == mod.Name then CustomCallbackHelper.RemoveAllCallbacks(CustomCallbackHelper.RegisteredMods[i]) table.remove(CustomCallbackHelper.RegisteredMods, i) end end --call the old register mod function --pcall to catch any errors local modRegistered, returned = pcall(CustomCallbackHelper.OldRegisterMod, mod, modname, apiversion) --erroring if not modRegistered then returned = string.gsub(returned, "customcallbackhelper.OldRegisterMod", "RegisterMod") error(returned, 2) end if type(mod) == "table" then --extend the mod CustomCallbackHelper.ExtendMod(mod) end end if not (ModConfigMenu and ModConfigMenu.PureMode) then Isaac.RegisterMod = CustomCallbackHelper.RegisterMod end ------------------ -- game started -- ------------------ local firstPlayerInited = false function CustomCallbackHelper.HandleGameStartedCallback(_, player) if not firstPlayerInited then firstPlayerInited = true local game = Game() local isSaveGame = false if game.TimeCounter > 0 then isSaveGame = true end --CCH_GAME_STARTED CustomCallbackHelper.CallCallbacks ( CustomCallbacks.CCH_GAME_STARTED, --callback id nil, --function to handle it {player, isSaveGame} --args to send ) end end CustomCallbackHelper.Mod:AddCallback(ModCallbacks.MC_POST_PLAYER_INIT, CustomCallbackHelper.HandleGameStartedCallback) --player init is the first callback to trigger, before game started, new level, new room, etc function CustomCallbackHelper.ResetPlayerInited() firstPlayerInited = false end CustomCallbackHelper.Mod:AddCallback(ModCallbacks.MC_POST_GAME_END, CustomCallbackHelper.ResetPlayerInited) CustomCallbackHelper.Mod:AddCallback(ModCallbacks.MC_PRE_GAME_EXIT, CustomCallbackHelper.ResetPlayerInited) ----------------- -- mods loaded -- ----------------- local firstCallbackTriggered = false function CustomCallbackHelper.HandleModsLoadedCallback() if not firstCallbackTriggered then firstCallbackTriggered = true --CCH_MODS_LOADED CustomCallbackHelper.CallCallbacks(CustomCallbacks.CCH_MODS_LOADED) end end CustomCallbackHelper.Mod:AddCallback(ModCallbacks.MC_INPUT_ACTION, CustomCallbackHelper.HandleModsLoadedCallback) --input action can trigger on the main menu, before a run starts return CustomCallbackHelper
--[[ ####################################### ####################################### ###########Erstellt von Dawi########### ##########github.com/yourdawi########## ##############yourdawi.de############## ####################################### ####################################### ]] --functions.lua Beinhalten Funktionen von https://wiki.multitheftauto.com/wiki/Useful_Functions function isLeapYear(year) if year then year = math.floor(year) else year = getRealTime().year + 1900 end return ((year % 4 == 0 and year % 100 ~= 0) or year % 400 == 0) end function getTimestamp(year, month, day, hour, minute, second) -- initiate variables local monthseconds = { 2678400, 2419200, 2678400, 2592000, 2678400, 2592000, 2678400, 2678400, 2592000, 2678400, 2592000, 2678400 } local timestamp = 0 local datetime = getRealTime() year, month, day = year or datetime.year + 1900, month or datetime.month + 1, day or datetime.monthday hour, minute, second = hour or datetime.hour, minute or datetime.minute, second or datetime.second -- calculate timestamp for i=1970, year-1 do timestamp = timestamp + (isLeapYear(i) and 31622400 or 31536000) end for i=1, month-1 do timestamp = timestamp + ((isLeapYear(year) and i == 2) and 2505600 or monthseconds[i]) end timestamp = timestamp + 86400 * (day - 1) + 3600 * hour + 60 * minute + second timestamp = timestamp - 3600 --GMT+1 compensation if datetime.isdst then timestamp = timestamp - 3600 end return timestamp end function getElementSpeed(theElement, unit) -- Check arguments for errors assert(isElement(theElement), "Bad argument 1 @ getElementSpeed (element expected, got " .. type(theElement) .. ")") assert(getElementType(theElement) == "player" or getElementType(theElement) == "ped" or getElementType(theElement) == "object" or getElementType(theElement) == "vehicle", "Invalid element type @ getElementSpeed (player/ped/object/vehicle expected, got " .. getElementType(theElement) .. ")") assert((unit == nil or type(unit) == "string" or type(unit) == "number") and (unit == nil or (tonumber(unit) and (tonumber(unit) == 0 or tonumber(unit) == 1 or tonumber(unit) == 2)) or unit == "m/s" or unit == "km/h" or unit == "mph"), "Bad argument 2 @ getElementSpeed (invalid speed unit)") -- Default to m/s if no unit specified and 'ignore' argument type if the string contains a number unit = unit == nil and 0 or ((not tonumber(unit)) and unit or tonumber(unit)) -- Setup our multiplier to convert the velocity to the specified unit local mult = (unit == 0 or unit == "m/s") and 50 or ((unit == 1 or unit == "km/h") and 180 or 111.84681456) -- Return the speed by calculating the length of the velocity vector, after converting the velocity to the specified unit return (Vector3(getElementVelocity(theElement)) * mult).length end function math.round(number, decimals, method) decimals = decimals or 0 local factor = 10 ^ decimals if (method == "ceil" or method == "floor") then return math[method](number * factor) / factor else return tonumber(("%."..decimals.."f"):format(number)) end end
-- Natural Selection 2 Competitive Mod -- Source located at - https://github.com/xToken/CompMod -- lua\CompMod\TechTreeConstants\post.lua -- - Dragon Script.Load("lua/CompMod/Utilities/Elixer/shared.lua") Elixer.UseVersion( 1.8 ) -- Load the file with our new tech names Script.Load("lua/CompMod/TechTreeConstants/NewTechTreeConstants.lua") -- Table for new tech names local newTechNames = BuildCompModTechTreeConstantUpdates() -- Grab existing list of techID names local gTechIdToString = GetUpValue( StringToTechId, "gTechIdToString", { LocateRecurse = true } ) -- Add new techs to string table, with index for i = 1, #newTechNames do gTechIdToString[newTechNames[i]] = kTechIdMax + i - 1 end -- Push out max index accordingly gTechIdToString['Max'] = kTechIdMax + #newTechNames -- Rebuild table to create enum from local kTechIdTable = { } for k, _ in pairs(gTechIdToString) do table.insert(kTechIdTable, k) end -- Sort table.sort(kTechIdTable, function(a, b) return gTechIdToString[a] < gTechIdToString[b] end) -- Update global kTechId enum kTechId = enum(kTechIdTable) -- Reset Max kTechIdMax = kTechId.Max
if not luasocket then luasocket = require('socket') end function sleep(ms) luasocket.select(nil, nil, ms / 1000) end return sleep
-- LUALOCALS < --------------------------------------------------------- local minetest, nodecore = minetest, nodecore -- LUALOCALS > --------------------------------------------------------- local modname = minetest.get_current_modname() local checkdirs = nodecore.dirs() local breathable = { airlike = true, allfaces = true, allfaces_optional = true, torchlike = true, signlike = true, plantlike = true, firelike = true, raillike = true, nodebox = true, mesh = true, plantlike_rooted = true, liquid = true, flowingliquid = true } ---------------------------------------- ---------------MUSHROOMS---------------- minetest.register_node(modname .. ":mushroom", { description = "Mushroom", drawtype = 'plantlike', waving = 1, tiles = {modname .. "_mushroom.png"}, sunlight_propagates = true, paramtype = 'light', walkable = false, -- silktouch = false, groups = { snappy = 1, fungi = 1, flammable = 1, attached_node = 1, natdecay = 1}, sounds = nodecore.sounds("nc_terrain_swishy"), buildable_to = true, -- drop = modname .. ":plant_fibers", selection_box = { type = "fixed", fixed = {-6 / 16, -0.5, -6 / 16, 6 / 16, 4 / 16, 6 / 16}, }, }) minetest.register_node(modname .. ":mushroom_glow", { description = "Glowing Mushroom", drawtype = 'plantlike', waving = 1, tiles = {modname .. "_mushroom_glow.png"}, sunlight_propagates = true, paramtype = 'light', walkable = false, -- silktouch = false, light_source = 2, groups = { snappy = 1, fungi = 1, flammable = 1, attached_node = 1, natdecay = 1}, sounds = nodecore.sounds("nc_terrain_swishy"), buildable_to = true, -- drop = modname .. ":plant_fibers", selection_box = { type = "fixed", fixed = {-6 / 16, -0.5, -6 / 16, 6 / 16, 4 / 16, 6 / 16}, }, }) minetest.register_node(modname .. ":mushroom_lux", { description = "Luxaeterna", drawtype = 'plantlike', waving = 1, tiles = {modname .. "_mushroom_lux.png"}, sunlight_propagates = true, paramtype = 'light', walkable = false, -- silktouch = false, light_source = 4, groups = { snappy = 1, fungi = 1, flammable = 1, attached_node = 1, natdecay = 1}, sounds = nodecore.sounds("nc_terrain_swishy"), buildable_to = true, -- drop = modname .. ":plant_fibers", selection_box = { type = "fixed", fixed = {-6 / 16, -0.5, -6 / 16, 6 / 16, 4 / 16, 6 / 16}, }, })
local version = { major = 0, minor = 0, patch = 0 } function love.conf(t) t.title = "TCG-Player v"..version.major..'.'..version.minor..'.'..version.patch t.author = "USPGameDev" t.url = "uspgamedev.org" t.identity = "tcg-player" t.version = "0.8.0" t.console = false t.release = false t.screen.width = 1024 t.screen.height = 768 t.screen.fullscreen = false t.screen.vsync = true t.screen.fsaa = 0 t.modules.joystick = true t.modules.audio = true t.modules.keyboard = true t.modules.event = true t.modules.image = true t.modules.graphics = true t.modules.timer = true t.modules.mouse = true t.modules.sound = true t.modules.physics = true end
object_static_particle_pt_sparks_small_no_wind = object_static_particle_shared_pt_sparks_small_no_wind:new { } ObjectTemplates:addTemplate(object_static_particle_pt_sparks_small_no_wind, "object/static/particle/pt_sparks_small_no_wind.iff")
require('hw.i386.luaqemu.core') json = require('hw.i386.luaqemu.json') machine_cpu = 'qemu32' firmware_path = '../firmware/test.bin' memory_regions = { region_rom = { name = 'mem_rom', start = 0x08000000, size = 0x1000 }, region_ram = { name = 'mem_ram', start = 0x20000000, size = 0x100000 } } file_mappings = { main_rom = { name = firmware_path, start = 0x08000000, size = 0x100 } } cpu = { env = { } } function bp_init() print "Init" local stack_pointer = 0x20001000 lua_set_register(4, stack_pointer) lua_set_pc(0x0800007a) local seed = read_file(fuzz_parameters.path_to_input) local fuzz_buffer = 0x20002000 lua_write_memory(fuzz_buffer, seed, #seed) lua_continue() end function bp_end() print "Stop emulate" os.exit() end breakpoints = { [0x08000000] = bp_init, [0x0800008a] = bp_end } function post_init(config) fuzz_parameters = json.read_json(config) lua_continue() end
package.path = package.path .. ";../?.lua;?.lua;lib/?.lua" local Object = require( "lib.object" ) local Event = Object:extend{ className = "Event", eventType = nil, mouseDown = false, mouseX = 0, mouseY = 0, mouseButton = 0, keyEntered = 0, keyChar = 0, keyMod = false } return Event
print('testing tables, next, and for') local a = {} -- make sure table has lots of space in hash part for i=1,100 do a[i.."+"] = true end for i=1,100 do a[i.."+"] = nil end -- fill hash part with numeric indices testing size operator for i=1,100 do a[i] = true assert(#a == i) end -- test size operation on empty tables assert(#{} == 0) assert(#{nil} == 0) assert(#{nil, nil} == 0) assert(#{nil, nil, nil} == 0) assert(#{nil, nil, nil, nil} == 0) print'+' local nofind = {} a,b,c = 1,2,3 a,b,c = nil local function find (name) local n,v while 1 do n,v = next(_G, n) if not n then return nofind end assert(v ~= nil) if n == name then return v end end end local function find1 (name) for n,v in pairs(_G) do if n==name then return v end end return nil -- not found end do -- create 100 new global variables for i=1,100 do _G[i] = i end end assert(print==find("print") and print == find1("print")) assert(_G["print"]==find("print")) assert(assert==find1("assert")) assert(nofind==find("return")) assert(not find1("return")) _G["ret" .. "urn"] = nil assert(nofind==find("return")) _G["xxx"] = 1 assert(xxx==find("xxx")) print('+') -- remove those 100 new global variables for i=1,100 do _G[i] = nil end do -- clear global table local a = {} local preserve = {io = 1, string = 1, table = 1} for n,v in pairs(_G) do a[n]=v end for n,v in pairs(a) do if not preserve[n] and type(v) ~= "function" and not string.find(n, "^[%u_]") then _G[n] = nil end collectgarbage() end end print'+' assert(#{} == 0) assert(#{[-1] = 2} == 0) assert(#{1,2,3,nil,nil} == 3) for i=0,40 do local a = {} for j=1,i do a[j]=j end assert(#(a) == i) end print("+") -- erasing values local t = {[{1}] = 1, [{2}] = 2, [string.rep("x ", 4)] = 3, [100.3] = 4, [4] = 5} local n = 0 for k, v in pairs( t ) do n = n+1 assert(t[k] == v) t[k] = nil collectgarbage() assert(t[k] == nil) end assert(n == 5) local function test (a) table.insert(a, 10); table.insert(a, 2, 20); table.insert(a, 1, -1); table.insert(a, 40); table.insert(a, #(a)+1, 50) table.insert(a, 2, -2) assert(table.remove(a,1) == -1) assert(table.remove(a,1) == -2) assert(table.remove(a,1) == 10) assert(table.remove(a,1) == 20) assert(table.remove(a,1) == 40) assert(table.remove(a,1) == 50) assert(table.remove(a,1) == nil) end a = {n=0, [-7] = "ban"} test(a) assert(a.n == 0 and a[-7] == "ban") a = {[-7] = "ban"}; test(a) assert(a.n == nil and #(a) == 0 and a[-7] == "ban") table.insert(a, 1, 10); table.insert(a, 1, 20); table.insert(a, 1, -1) assert(table.remove(a) == 10) assert(table.remove(a) == 20) assert(table.remove(a) == -1) a = {'c', 'd'} table.insert(a, 3, 'a') table.insert(a, 'b') assert(table.remove(a, 1) == 'c') assert(table.remove(a, 1) == 'd') assert(table.remove(a, 1) == 'a') assert(table.remove(a, 1) == 'b') assert(#(a) == 0 and a.n == nil) print("+") a = {} for i=1,1000 do a[i] = i; a[i-1] = nil end assert(next(a,nil) == 1000 and next(a,1000) == nil) assert(next({}) == nil) assert(next({}, nil) == nil) for a,b in pairs{} do error"not here" end for i=1,0 do error'not here' end for i=0,1,-1 do error'not here' end a = nil; for i=1,1 do assert(not a); a=1 end; assert(a) a = nil; for i=1,1,-1 do assert(not a); a=1 end; assert(a) a = 0; for i=0, 1, 0.1 do a=a+1 end; assert(a==10) -- precision problems a = 0; for i=1, 0, -0.01 do a=a+1 end; assert(a==101) a = 0; for i=0, 0.999999999, 0.1 do a=a+1 end; assert(a==10) a = 0; for i=1, 1, 1 do a=a+1 end; assert(a==1) a = 0; for i=1, 0.99999, 1 do a=a+1 end; assert(a==0) a = 0; for i=99999, 1e5, -1 do a=a+1 end; assert(a==0) a = 0; for i=1, 0.99999, -1 do a=a+1 end; assert(a==1) -- conversion a = 0; for i="10","1","-2" do a=a+1 end; assert(a==5) collectgarbage() -- testing generic 'for' local function f (n, p) local t = {}; for i=1,p do t[i] = i*10 end return function (_,n) if n > 0 then n = n-1 return n, unpack(t) end end, nil, n end local x = 0 for n,a,b,c,d in f(5,3) do x = x+1 assert(a == 10 and b == 20 and c == 30 and d == nil) end assert(x == 5) print(" OK")
-- V12 engines -- Petrol ACF_DefineEngine( "4.6-V12", { name = "4.6L V12 Petrol", desc = "An elderly racecar engine; low on torque, but plenty of power", model = "models/engines/v12s.mdl", sound = "acf_base/engines/v12_petrolsmall.wav", category = "V12", fuel = "Petrol", enginetype = "GenericPetrol", weight = 188, torque = 235, flywheelmass = 0.2, idlerpm = 1000, peakminrpm = 4500, peakmaxrpm = 7500, limitrpm = 8000 } ) ACF_DefineEngine( "7.0-V12", { name = "7.0L V12 Petrol", desc = "A high end V12; primarily found in very expensive cars", model = "models/engines/v12m.mdl", sound = "acf_base/engines/v12_petrolmedium.wav", category = "V12", fuel = "Petrol", enginetype = "GenericPetrol", weight = 360, torque = 500, flywheelmass = 0.45, idlerpm = 800, peakminrpm = 3600, peakmaxrpm = 6000, limitrpm = 7500 } ) ACF_DefineEngine( "23.0-V12", { name = "23.0L V12 Petrol", desc = "A large, thirsty gasoline V12, found in early cold war tanks", model = "models/engines/v12l.mdl", sound = "acf_base/engines/v12_petrollarge.wav", category = "V12", fuel = "Petrol", enginetype = "GenericPetrol", weight = 1350, torque = 1925, flywheelmass = 5, idlerpm = 600, peakminrpm = 1500, peakmaxrpm = 3000, limitrpm = 3250 } ) -- Diesel ACF_DefineEngine( "4.0-V12", { name = "4.0L V12 Diesel", desc = "Reliable truck-duty diesel; a lot of smooth torque", model = "models/engines/v12s.mdl", sound = "acf_base/engines/v12_dieselsmall.wav", category = "V12", fuel = "Diesel", enginetype = "GenericDiesel", weight = 305, torque = 375, flywheelmass = 0.475, idlerpm = 650, peakminrpm = 1200, peakmaxrpm = 3800, limitrpm = 4000 } ) ACF_DefineEngine( "9.2-V12", { name = "9.2L V12 Diesel", desc = "High torque light-tank V12, used mainly for vehicles that require balls", model = "models/engines/v12m.mdl", sound = "acf_base/engines/v12_dieselmedium.wav", category = "V12", fuel = "Diesel", enginetype = "GenericDiesel", weight = 600, torque = 750, flywheelmass = 2.5, idlerpm = 675, peakminrpm = 1100, peakmaxrpm = 3300, limitrpm = 3500 } ) ACF_DefineEngine( "21.0-V12", { name = "21.0L V12 Diesel", desc = "AVDS-1790-2 tank engine; massively powerful, but enormous and heavy", model = "models/engines/v12l.mdl", sound = "acf_base/engines/v12_diesellarge.wav", category = "V12", fuel = "Diesel", enginetype = "GenericDiesel", weight = 1800, torque = 3560, flywheelmass = 7, idlerpm = 400, peakminrpm = 500, peakmaxrpm = 1500, limitrpm = 2500 } ) ACF_DefineEngine( "13.0-V12", { name = "13.0L V12 Petrol", desc = "Thirsty gasoline v12, good torque and power for medium applications.", model = "models/engines/v12m.mdl", sound = "acf_base/engines/v12_special.wav", category = "V12", fuel = "Petrol", enginetype = "GenericPetrol", weight = 520, torque = 660, flywheelmass = 1, idlerpm = 700, peakminrpm = 2500, peakmaxrpm = 4000, limitrpm = 4250 } )
local K, C = unpack(select(2, ...)) if C["DataText"].System ~= true then return end local _G = _G local math_floor = math.floor local select = select local PlayerColorStr = _G.RAID_CLASS_COLORS[K.Class].colorStr local FPS_ABBR = "|c" .. PlayerColorStr .. _G.FPS_ABBR .. "|r" local MILLISECONDS_ABBR = "|c" .. PlayerColorStr .. _G.MILLISECONDS_ABBR .. "|r" local performance_font = K.GetFont(C["DataText"].Font) local performance_hz = 1 local performance_string = "%d%s - %d%s" local PerformanceFrame = CreateFrame("Frame", "SystemInfo", Minimap) PerformanceFrame:SetPoint("TOP", Minimap, "TOP", 0, -4) PerformanceFrame:SetSize(Minimap:GetWidth() - 2, 14) PerformanceFrame:Show() PerformanceFrame.Text = PerformanceFrame:CreateFontString(nil, "OVERLAY") PerformanceFrame.Text:SetFontObject(performance_font) PerformanceFrame.Text:SetFont(select(1, PerformanceFrame.Text:GetFont()), 13, select(3, PerformanceFrame.Text:GetFont())) PerformanceFrame.Text:SetAllPoints(PerformanceFrame) PerformanceFrame.Performance = PerformanceFrame.Text PerformanceFrame:SetScript("OnUpdate", function(self, elapsed) self.elapsed = (self.elapsed or 0) + elapsed if self.elapsed > performance_hz then local _, _, chat_latency, cast_latency = _G.GetNetStats() local fps = math_floor(_G.GetFramerate()) if not cast_latency or cast_latency == 0 then cast_latency = chat_latency end self.Performance:SetFormattedText(performance_string, cast_latency, MILLISECONDS_ABBR, fps, FPS_ABBR) self.elapsed = 0 end end) K.PerformanceFrame = PerformanceFrame
--[[ A library to make the manipulation of the action packet easier. The primary functionality provided here are iterators which allow for easy traversal of the sub-tables within the packet. Example: ======================================================================================= require 'actions' function event_action(act) action = Action(act) -- constructor -- print out all melee hits to the console if action:get_category_string() == 'melee' then for target in action:get_targets() do -- target iterator for subaction in target:get_actions() do -- subaction iterator if subaction.message == 1 then -- 1 is the code for messages print(string.format("%s hit %s for %d damage", action:get_actor_name(), target:get_name(), subaction.param)) end end end end end ======================================================================================= ]] _libs = _libs or {} _libs.actions = true local category_strings = { 'melee', 'ranged_finish', 'weaponskill_finish', 'spell_finish', 'item_finish', 'job_ability', 'weaponskill_begin', 'casting_begin', 'item_begin', 'unknown', 'mob_tp_finish', 'ranged_begin', 'avatar_tp_finish', 'job_ability_unblinkable' } local action = {} -- Constructor for Actions. -- Usage: action = Action(raw_action) function Action(a) if a == nil then return end local new_instance = {} new_instance.raw = a return setmetatable(new_instance, {__index = function(t, k) if rawget(t, k) ~= nil then return t[k] else return action[k] end end}) end function action.get_category_string(self) return category_strings[self.raw['category']] end -- Returns the name of this actor if there is one function action.get_actor_name(self) local mob = windower.ffxi.get_mob_by_id(self.raw['actor_id']) if mob then return mob['name'] else return nil end end -- Returns an iterator for this action's targets function action.get_targets(self) local targets = self.raw['targets'] local target_count = self.raw['target_count'] local i = 0 return function () i = i + 1 if i <= target_count then return Target(targets[i]) end end end local target = {} -- Constructor for target wrapper function Target(t) if t == nil then return end local new_instance = {} new_instance.raw = t return setmetatable(new_instance, {__index = target}) end -- Returns an iterator for this target's subactions function target.get_actions(self) local subactions = self.raw['actions'] local action_count = self.raw['action_count'] local i = 0 return function () i = i + 1 if i <= action_count then return subactions[i] end end end -- Returns the name of this target if there is one function target.get_name(self) local mob = windower.ffxi.get_mob_by_id(self.raw['id']) if mob then return mob['name'] else return nil end end --[[ Copyright (c) 2013, Suji All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of actions nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUJI BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ]]
ITEM.name = "Old Ceramic Plate" ITEM.description = "An old ceramic plate, could absorb some impacts against a body armor." ITEM.model = "models/lostsignalproject/items/outfit_parts/ballistic8.mdl" ITEM.category = "Attachments" ITEM.width = 1 ITEM.height = 1 ITEM.upgradeIcon = Material("materials/vgui/ui/stalker/weaponupgrades/grip.png") ITEM.price = 10000 ITEM.attachName = "ceramicplate_1" ITEM.weight = 1.400
--[[ Project: SA Memory (Available from https://blast.hk/) Developers: LUCHARE, FYP Special thanks: plugin-sdk (https://github.com/DK22Pac/plugin-sdk) for the structures and addresses. Copyright (c) 2018 BlastHack. ]] local shared = require 'SAMemory.shared' shared.require 'RenderWare' shared.require 'CVehicle' shared.require 'CColPoint' shared.require 'CEntity' shared.require 'CRideAnimData' shared.require 'matrix' shared.require 'vector3d' shared.ffi.cdef[[ typedef enum eBikeNodes { BIKE_NODE_NONE = 0, BIKE_CHASSIS = 1, BIKE_FORKS_FRONT = 2, BIKE_FORKS_REAR = 3, BIKE_WHEEL_FRONT = 4, BIKE_WHEEL_REAR = 5, BIKE_MUDGUARD = 6, BIKE_HANDLEBARS = 7, BIKE_MISC_A = 8, BIKE_MISC_B = 9, BIKE_NUNODES } eBikeNodes; typedef struct CBike : CVehicle { RwFrame *pBikeNodes[BIKE_NUNODES]; bool bLeanMatrixCalculated; char _pad0[3]; matrix mLeanMatrix; unsigned char nDamageFlags; char field_615[27]; vector3d field_630; void *pBikeHandlingData; CRideAnimData rideAnimData; unsigned char anWheelDamageState[2]; char field_65E; char field_65F; CColPoint anWheelColPoint[4]; float field_710[4]; float field_720[4]; float field_730[4]; float field_740; int anWheelSurfaceType[2]; char field_74C[2]; char field_74E[2]; float afWheelRotationX[2]; float fWheelSpeed[2]; float field_760; float field_764; float field_768; float field_76C; float field_770[4]; float field_780[4]; float fHeightAboveRoad; float fCarTraction; float field_798; float field_79C; float field_7A0; float field_7A4; short field_7A8; char field_7AA[2]; int field_7AC; int field_7B0; bool bPedLeftHandFixed; bool bPedRightHandFixed; char field_7B6[2]; int field_7B8; int field_7BC; CEntity *apWheelCollisionEntity[4]; vector3d avTouchPointsLocalSpace[4]; CEntity *pDamager; unsigned char nNumContactWheels; unsigned char nNumWheelsOnGround; char field_806; char field_807; int field_808; unsigned int anWheelState[2]; } CBike; ]] shared.validate_size('CBike', 0x814)
local t = Def.ActorFrame { InitCommand=function(self) state = 1; end }; --HAS THIS GUY EVER HEARD OF METRICS??? -- Chart info helpers local infy = 160 --Chart info Y axis position (both players, includes black quad alt) local infx = 0 --Chart info X DIFFERENCE FROM DISC --quad stuff local infft = 0.125*0.75 --Chart info quad fade top local inffb = infft --Chart info quad fade bottom local redu = 0 --Chart info vertical reduction value for black quad (pixels) local bqwid = _screen.cx --Chart info quad width local bqalt = 244-20 --Chart info black quad height local bqalph = 0.9 --Chart info black quad diffusealpha value local wqwid = _screen.cx -- local npsxz = _screen.cx*0.5 --next/previous song X zoom local npsyz = _screen.cy --*0.75 --next/previous song Y zoom -- --local css1 = STATSMAN:GetCurStageStats():GetPlayerStageStats(PLAYER_1); --local css2 = STATSMAN:GetCurStageStats():GetPlayerStageStats(PLAYER_2); local newranktext = "NEW CHALLENGER" --text replacing #P1# when someone does a new record local bpmalt = _screen.cy+55 --Y value for BPM Display below banner if IsUsingWideScreen() then defaultzoom = 0.8; else defaultzoom = 0.65; end; ---DECORATIONS IN GENERAL t[#t+1] = Def.ActorFrame { --MSG INFO LoadActor(THEME:GetPathB("ScreenSelectMusic" ,"overlay/help_info/txt_box"))..{ InitCommand=cmd(x,_screen.cx;y,SCREEN_BOTTOM-50;zoomx,0.9;zoomy,0.65); }; Def.Sprite{ --Yeah I dunno why I have to specify the full path Texture=THEME:GetPathB("ScreenSelectMusic","overlay/help_info/messages 1x4.png"); InitCommand=function(self) (cmd(x,_screen.cx;y,SCREEN_BOTTOM-50;zoom,.6;animate,false;setstate,0))(self); if getenv("PlayMode") == "Easy" then self:Load(THEME:GetPathB("ScreenSelectMusic","overlay/help_info/easymessages 1x4.png")); end; end; OnCommand=cmd(queuecommand,"Set"); SetCommand=function(self) --I know hard coding stuff is bad, but there will only ever be 4 states... --And also, hide the setlist prompt if we're in Special mode, since there are no folders --in special mode. if self:GetState()+1 >= 4 or (getenv("PlayMode") == "Special" and self:GetState() == 2) then self:setstate(0); else self:setstate(self:GetState()+1); end; self:linear(0.2); self:diffusealpha(1); self:sleep(2); self:linear(0.2) self:diffusealpha(0); self:queuecommand("Set"); end; TwoPartConfirmCanceledMessageCommand=cmd(playcommand,"PickingSong"); SongUnchosenMessageCommand=cmd(playcommand,"PickingSong"); PickingSongCommand=cmd(stoptweening;linear,.2;diffusealpha,1;sleep,2;linear,.2;diffusealpha,0;queuecommand,"Set"); SongChosenMessageCommand=cmd(stoptweening;linear,.2;diffusealpha,0); }; Def.Sprite{ Texture=THEME:GetPathB("ScreenSelectMusic","overlay/help_info/difficulty_messages 1x4.png"); InitCommand=cmd(x,_screen.cx;y,SCREEN_BOTTOM-50;zoom,.6;animate,false;setstate,0;diffusealpha,0); SetCommand=function(self) --I know hard coding stuff is bad, but there will only ever be 4 states... --And also, hide the command window info if we're in Easy mode. if self:GetState()+1 >= 4 or (getenv("PlayMode") == "Easy" and self:GetState() == 2) then self:setstate(0); else self:setstate(self:GetState()+1); end; self:linear(0.2); self:diffusealpha(1); self:sleep(2); self:linear(0.2) self:diffusealpha(0); self:queuecommand("Set"); end; TwoPartConfirmCanceledMessageCommand=cmd(playcommand,"PickingSong"); SongUnchosenMessageCommand=cmd(playcommand,"PickingSong"); PickingSongCommand=cmd(stoptweening;linear,.2;diffusealpha,0); SongChosenMessageCommand=cmd(stoptweening;linear,.2;diffusealpha,1;sleep,2;linear,.2;diffusealpha,0;queuecommand,"Set"); }; --TIME LoadFont("monsterrat/_montserrat light 60px")..{ Text="TIME"; InitCommand=cmd(x,SCREEN_CENTER_X-25;y,SCREEN_BOTTOM-92;zoom,0.6;skewx,-0.2); }; }; t[#t+1] = Def.ActorFrame{ --[[LoadFont("Common normal")..{ --formatted stage display InitCommand=cmd(xy,_screen.cx,_screen.cy-190;zoomx,0.75;zoomy,0.65); Text=ToEnumShortString(GAMESTATE:GetCurrentStage()).." Stage"; };]] --[[LoadFont("monsterrat/_montserrat semi bold 60px")..{ InitCommand=cmd(horizalign,right;x,SCREEN_RIGHT-16;y,SCREEN_TOP+23;zoom,0.6;skewx,-0.25;); Text=string.upper(ToEnumShortString(GAMESTATE:GetCurrentStage()).." Stage"); };]] --Left side background Def.ActorFrame{ InitCommand=cmd(x,SCREEN_LEFT;y,_screen.cy+110;vertalign,middle,horizalign,right); SongChosenMessageCommand=cmd(stoptweening;decelerate,0.125;x,SCREEN_CENTER_X); SongUnchosenMessageCommand=cmd(stoptweening;accelerate,0.125*1.5;x,SCREEN_LEFT;); Def.Quad{ --white quad for Difficulties InitCommand=cmd(horizalign,right;zoomto,_screen.cx,35;diffuse,1,1,1,0.75;x,0;y,-3;fadeleft,1;); }; Def.Quad{ --Black quad for Chart info P1 InitCommand=cmd(horizalign,right;fadetop,infft;fadebottom,inffb;xy,-infx,-infy+20;zoomto,bqwid*2,bqalt+50;diffuse,0,0,0,bqalph;); --InitCommand=cmd(diffuse,color("0,0,0,"..bqalph);xy,0,SCREEN_CENTER_Y;horizalign,right;setsize,bqwid*2,bqalt+50;); }; LoadFont("bebas/_bebas neue bold 90px")..{ Text="NOT PRESENT"; Condition=not GAMESTATE:IsHumanPlayer(PLAYER_1); InitCommand=cmd(x,-_screen.cx*0.7;y,-infy;zoom,0.3;skewx,-0.2); --PlayerJoinedMessageCommand=cmd(visible,not GAMESTATE:IsHumanPlayer(PLAYER_1)); }; Def.Sprite{ Condition=GAMESTATE:IsHumanPlayer(PLAYER_1); Texture=THEME:GetPathB("ScreenSelectMusic","overlay/p1_info"); --PLAYER INFO InitCommand=cmd(zoomto,250,45;horizalign,left;xy,-SCREEN_CENTER_X,-_screen.cy); }; }; --Right side background Def.ActorFrame{ InitCommand=cmd(x,SCREEN_RIGHT;y,_screen.cy+110;vertalign,middle,horizalign,left); SongChosenMessageCommand=cmd(stoptweening;decelerate,0.125;x,SCREEN_CENTER_X); SongUnchosenMessageCommand=cmd(stoptweening;accelerate,0.125*1.5;x,SCREEN_RIGHT;); Def.Quad{ --white quad for Difficulties InitCommand=cmd(horizalign,left;zoomto,_screen.cx,35;diffuse,1,1,1,0.75;x,0;y,-3;faderight,1;); }; Def.Quad{ --Black quad for Chart info P1 InitCommand=cmd(horizalign,left;fadetop,infft;fadebottom,inffb;xy,-infx,-infy+20;zoomto,bqwid*2,bqalt+50;diffuse,0,0,0,bqalph;); --InitCommand=cmd(diffuse,color("0,0,0,"..bqalph);xy,0,SCREEN_CENTER_Y;horizalign,right;setsize,bqwid*2,bqalt+50;); }; LoadFont("bebas/_bebas neue bold 90px")..{ Condition=not GAMESTATE:IsHumanPlayer(PLAYER_2); Text="NOT PRESENT"; InitCommand=cmd(x,_screen.cx*0.7;y,-infy;zoom,0.3;skewx,-0.2); --PlayerJoinedMessageCommand=cmd(visible,not GAMESTATE:IsHumanPlayer(PLAYER_2)); }; Def.Sprite{ Condition=GAMESTATE:IsHumanPlayer(PLAYER_2); Texture=THEME:GetPathB("ScreenSelectMusic","overlay/p2_info"); --PLAYER INFO InitCommand=cmd(zoomto,250,45;horizalign,right;xy,SCREEN_CENTER_X,-_screen.cy); }; }; Def.Quad{ --White for Chart info P1 EFFECT JOINED InitCommand=function(self) self:visible(GAMESTATE:IsHumanPlayer(PLAYER_2)); (cmd(horizalign,right;fadetop,infft;fadebottom,inffb;x,-infx;y,-infy; zoomto,bqwid,bqalt-redu;diffuse,1,1,1,0;blend,'BlendMode_Add';))(self) end; PlayerJoinedMessageCommand=function(self) (cmd(zoomy,(bqalt-redu)*1.25;diffuse,1,1,1,1;decelerate,0.75;zoomy,(bqalt-redu)*0.925;diffuse,1,1,1,0))(self) end; }; Def.Quad{ --White for Chart info P2 EFFECT JOINED InitCommand=function(self) self:visible(GAMESTATE:IsHumanPlayer(PLAYER_1)); (cmd(horizalign,left;fadetop,infft;fadebottom,inffb;x,infx;y,-infy; zoomto,bqwid,bqalt-redu;diffuse,1,1,1,0;blend,'BlendMode_Add';))(self) end; PlayerJoinedMessageCommand=function(self) (cmd(zoomy,(bqalt-redu)*1.25;diffuse,1,1,1,1;decelerate,0.75;zoomy,(bqalt-redu)*0.925;diffuse,1,1,1,0))(self) end; }; }; t[#t+1] = Def.ActorFrame{ LoadActor(THEME:GetPathB("ScreenSelectMusic" ,"overlay/judge_back"))..{ --This is my big surprise secret remodel lmfao -Gio InitCommand=cmd(zoom,0.35;x,SCREEN_CENTER_X;y,SCREEN_CENTER_Y-124;diffusealpha,0); SongChosenMessageCommand=cmd(linear,0.1;diffusealpha,1); SongUnchosenMessageCommand=cmd(linear,0.1;diffusealpha,0); }; LoadFont("facu/_zona pro bold 40px")..{ Text="MIXTAPE INFO"; InitCommand=cmd(zoom,0.35;x,SCREEN_CENTER_X;y,SCREEN_CENTER_Y-125;diffusealpha,0); SongChosenMessageCommand=cmd(linear,0.1;diffusealpha,1); SongUnchosenMessageCommand=cmd(linear,0.1;diffusealpha,0); }; --[[LoadActor(THEME:GetPathB("ScreenSelectMusic" ,"overlay/tab-speed"))..{ --Fancy, eh? InitCommand=cmd(zoom,0.35;x,SCREEN_CENTER_X;y,SCREEN_CENTER_Y-70;diffusealpha,0); SongChosenMessageCommand=cmd(linear,0.1;diffusealpha,1); SongUnchosenMessageCommand=cmd(linear,0.1;diffusealpha,0); };]] LoadActor(THEME:GetPathB("ScreenSelectMusic" ,"overlay/tab-score"))..{ --I hope people like it! InitCommand=cmd(zoom,0.35;x,SCREEN_CENTER_X;y,SCREEN_CENTER_Y+20;diffusealpha,0); SongChosenMessageCommand=cmd(linear,0.1;diffusealpha,1); SongUnchosenMessageCommand=cmd(linear,0.1;diffusealpha,0); }; } local j = Def.ActorFrame{ InitCommand=cmd(xy,SCREEN_CENTER_X,140;diffusealpha,0); SongChosenMessageCommand=cmd(linear,0.1;diffusealpha,1); SongUnchosenMessageCommand=cmd(linear,0.1;diffusealpha,0); }; --I don't expect there to be more than 4 songs. local OBJECT_WIDTH = 300; for i = 1,4 do j[i] = Def.ActorFrame{ InitCommand=function(self) self:addy(30*(i-1)); --[[if i < 3 then self:x(-OBJECT_WIDTH*.65); else self:x(OBJECT_WIDTH*.65); end;]] end; CurrentCourseChangedMessageCommand=function(self) self:stoptweening():diffusealpha(0); --if not GAMESTATE:GetCurrentCourse() then return end; local trailEntries = getenv("TrailCache"):GetTrailEntries(); if i <= #trailEntries then self:GetChild("SongName"):settext(trailEntries[i]:GetSong():GetDisplayFullTitle()); if true then local steps = trailEntries[i]:GetSteps() local meter = steps:GetMeter(); if meter >= 99 then self:GetChild("Label"):settext("??"); else self:GetChild("Label"):settextf("%02d",meter); end; local StepsType = steps:GetStepsType(); local labelBG = self:GetChild("LabelBG"); if StepsType then sString = THEME:GetString("StepsDisplay StepsType",ToEnumShortString(StepsType)); if sString == "Single" then --There is no way to designate a single trail as DANGER, unfortunately. if meter >= 99 then labelBG:setstate(4); else labelBG:setstate(0); end elseif sString == "Double" then labelBG:setstate(1); elseif sString == "SinglePerformance" or sString == "Half-Double" then labelBG:setstate(2); elseif sString == "DoublePerformance" or sString == "Routine" then labelBG:setstate(3); else labelBG:setstate(5); end; end; end; self:diffusealpha(1); else --Do nothing. end; end; --[[Def.Quad{ InitCommand=cmd(setsize,OBJECT_WIDTH,10); };]] LoadActor(THEME:GetPathG("StepsDisplayListRow","frame/_icon"))..{ Name="LabelBG"; InitCommand=cmd(zoom,0.3;addx,-OBJECT_WIDTH/2;addy,2;animate,false);--draworder,140;); }; LoadFont("monsterrat/_montserrat semi bold 60px")..{ Name="Label"; InitCommand=cmd(zoom,0.25;skewx,-0.15;addx,-OBJECT_WIDTH/2;y,0.5); }; -- NEW LABEL --[[LoadActor(THEME:GetPathG("StepsDisplayListRow","frame/danger"))..{ InitCommand=cmd(zoom,0.5;y,22); OnCommand=cmd(diffuseshift; effectoffset,1; effectperiod, 0.5; effectcolor1, 1,1,0,1; effectcolor2, 1,1,1,1;); SetMessageCommand=function(self,param) profile = PROFILEMAN:GetMachineProfile(); scorelist = profile:GetHighScoreList(GAMESTATE:GetCurrentSong(),param.Steps); scores = scorelist:GetHighScores(); topscore = scores[1]; local descrp = param.Steps:GetDescription(); if descrp == "DANGER!" then self:visible(true); else self:visible(false); end; end; };]] LoadFont("facu/_zona pro bold 40px")..{ Name="SongName"; Text="Song names here"; InitCommand=cmd(horizalign,left;zoom,.5;addx,-OBJECT_WIDTH/2+15;maxwidth,OBJECT_WIDTH*2); }; }; end; t[#t+1] = j; for pn in ivalues(GAMESTATE:GetEnabledPlayers()) do local alignment = (pn == PLAYER_1) and right or left; local negativeOffset = (pn == PLAYER_1) and 1 or -1; local start = (pn == PLAYER_1) and SCREEN_LEFT or SCREEN_RIGHT; t[#t+1] = Def.ActorFrame{ Condition=PROFILEMAN:IsPersistentProfile(pn); --Don't show scores for players without profiles. Or maybe MACHINE BEST could be shown instead? InitCommand=cmd(x,start;y,SCREEN_CENTER_Y+50;vertalign,middle,horizalign,alignment); SongChosenMessageCommand=cmd(stoptweening;decelerate,0.125;x,SCREEN_CENTER_X); SongUnchosenMessageCommand=cmd(stoptweening;accelerate,0.125*1.5;x,start;); LoadFont("monsterrat/_montserrat semi bold 60px")..{ Text="YOUR BEST:"; InitCommand=cmd(x,-60*negativeOffset;y,-8;zoom,0.25;skewx,-0.25;horizalign,alignment;); }; LoadFont("monsterrat/_montserrat semi bold 60px")..{--Player Top Score (numbers) InitCommand=cmd(x,-60*negativeOffset;y,8;zoom,0.25;skewx,-0.25;horizalign,alignment;); SongChosenMessageCommand=cmd(queuecommand,"Set"); SetCommand=function(self) -- ROAD24: and more checks -- TODO: decide what to do when no song is selected local cursong = GAMESTATE:GetCurrentCourse() if cursong then profile = PROFILEMAN:GetProfile(pn); scorelist = profile:GetHighScoreList(cursong,GAMESTATE:GetCurrentTrail(pn)); local scores = scorelist:GetHighScores(); local topscore = scores[1]; if topscore then -- if topscore >= stagemaxscore then --temporary workaround -- pscore = stagemaxscore -- else pscore = topscore:GetScore(); -- end else pscore = "0"; end --local percen = tonumber(string.format("%.03f",((pscore/stagemaxscore)*100))); if topscore then --self:settext(pscore.." - "..percen.."%"); self:settext(pscore); else self:settext("0"); end; end; end; }; Def.Sprite { InitCommand=cmd(x,-15*negativeOffset;zoom,0.15;horizalign,alignment;); SongChosenMessageCommand=cmd(queuecommand,"Set"); SetCommand=function(self) local song = GAMESTATE:GetCurrentCourse(); if song then self:diffusealpha(1); profile = PROFILEMAN:GetProfile(pn); scorelist = profile:GetHighScoreList(song,GAMESTATE:GetCurrentTrail(pn)); assert(scorelist); local scores = scorelist:GetHighScores(); local topscore = scores[1]; if topscore then local grade = getGradeFromScore(topscore) self:Load(THEME:GetPathG("","GradeDisplayEval/"..grade)); else --if no score self:diffusealpha(0); end else --if no song self:diffusealpha(0); end; end; }; }; end; t[#t+1] = LoadActor(THEME:GetPathG("","USB_stuff"))..{}; --[[t[#t+1] = LoadActor("ready")..{ -- 1 PLAYER JOINED READY InitCommand=cmd(visible,false;horizalign,center;x,SCREEN_CENTER_X;y,SCREEN_CENTER_Y;zoom,2;); WaitingConfirmMessageCommand=cmd(playcommand,"Ready";); StepsChosenMessageCommand=cmd(playcommand,"Ready";); ReadyCommand=function(self) if GAMESTATE:GetNumSidesJoined() == 1 and state > 1 then self:stoptweening(); self:visible(false); self:zoom(1); self:linear(0.3); self:zoom(2); self:visible(true); end; end; CurrentSongChangedMessageCommand=cmd(visible,false); StepsUnchosenMessageCommand=cmd(visible,false); SongUnchosenMessageCommand=cmd(visible,false); };]] return t
--[[ --MIT License -- --Copyright (c) 2019 manilarome --Copyright (c) 2020 Tom Meyers -- --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 translations = {} translations["+10%"] = "+10%" translations["-10%"] = "-10%" translations["About"] = "Over" translations[ "A break timer gets triggered every hour, this is intended to give you some time to stretch, take a break etc" ] = "Een pauze timer word elk uur geactiveerd, de bedoeling hiervan is om u tijd te geven voor te stretchen en een pauze te pakken" translations["Action Center"] = "Actie Centrum" translations["arandr"] = "arandr" translations["Area"] = "Gedeeltelijke foto van het scherm" translations["area/selected screenshot"] = "gedeeltelijke foto van het scherm" translations["Audio popup"] = "Indicatief Geluidje" translations["awesome"] = "awesome" translations["Background"] = "Achtergrond" translations["Back"] = "Terug" translations["Bluetooth Connection"] = "Bluetooth Connectie" translations["Bluetooth is off"] = "Bluetooth is uitgeschakeld" translations["Bluetooth is on"] = "Bluetooth staat aan" translations["Break timer"] = "Pauze timer" translations["Brightness"] = "Helderheid" translations["Can't retreive deaths."] = "Kan doden aantal niet opvragen" translations["Change Application Scaling"] = "Verander applicatie schaling" translations["Clear All Notifications"] = "Verwijder alle notificaties" translations["client"] = "klient" translations["close"] = "sluit" translations["Connected to "] = "Verbonden met " translations["Connections"] = "Connecties" translations["Connect to a wireless network"] = "Verbind met een draadloos netwerk" translations["Covid-19 cases in "] = "Covid-19 gevallen in " translations["Covid-19 cases in your country"] = "Covid-19 gevallen in uw land" translations["CPU"] = "CPU" translations["custom"] = "Op maat" translations["Deaths: "] = "Doden: " translations["decrease master width factor"] = "Verlaag master breedte factor" translations["decrease the number of columns"] = "Verlaag het aantal colommen" translations["decrease the number of master clients"] = "Verlaag het aantal master applicaties" translations["Delay by 5 minutes"] = "Vertraag met 5 minuten" translations["Device name"] = "Apparaat naam" translations["Disable Desktop"] = "Schakel desktop uit" translations["Disable for this session"] = "Schakel uit voor deze sessie" translations["disable sticky mode"] = "Stop plak modus" translations["Disconnected"] = "Losgekoppeld" translations["Disk capacity"] = "Schijfcapaciteit" translations["Disk"] = "Schijf" translations["Display"] = "Scherm" translations["Display refresh rate"] = "Scherm vernieuwingsfrequentie" translations["Documents"] = "Documenten" translations["Do Not Disturb"] = "Niet storen" translations["don't keep above other windows"] = "Hou het niet boven andere schermen" translations["Downloads"] = "Downloads" translations["Draw the tagbar either on all screens, the main screen or don't draw it at all"] = "Teken het labelbar op elk scherm, enkel het hoofdscherm of nergens" translations["Draw the titlebar above every application"] = "Teken de titelbar boven elke applicatie" translations["Draw the topbar either on all screens, the main screen or don't draw it at all"] = "Teken het topbar op elk scherm, enkel het hoofdscherm of nergens" translations["dropdown terminal"] = "dropdown terminal" translations["Edit config"] = "Bewerk configuratie" translations["enable floating mode"] = "schakel zwevende modus in" translations["enable sticky mode"] = "schakel plak modus in" translations["Enable the 'pop' sound when changing the audio"] = "Schakel het 'pop' geluidje in wanneer het volume veranderd" translations["enable tiling mode"] = "Schakel tegel modus in" translations["End Session"] = "Beëinding sessie" translations["End work session"] = "Beëinding werk sessie" translations["Error data opt out"] = "Error data afmelden" translations["File Manager"] = "File beheerder" translations["focus next by index"] = "focus volgende op basis van index" translations["focus previous by index"] = "focus vorige op basis van index" translations["FPS"] = "FPS" translations["fullscreen screenshot"] = "fullscreen foto" translations["Full settings application"] = "Volledige settings applicatie" translations["Full"] = "Volledig" translations["General"] = "Algemeen" translations["Global search"] = "Globale zoek" translations["go back"] = "ga terug" translations["Goodbye "] = "Vaarwel " translations["go to the next song"] = "ga naar het volgend liedje" translations["go to the previous song"] = "ga naar het vorig liedje" translations["Graphics"] = "Grafisch" translations["hardware"] = "hardware" translations["Hardware monitor"] = "Hardware monitor" translations["home"] = "huis" translations["Home"] = "Huis" translations["Hostname: "] = "Hostnaam: " translations["hotkeys"] = "sneltoetsen" translations["Hotkeys"] = "Sneltoetsen" translations["increase master width factor"] = "Verhoog master breedte factor" translations["increase the number of columns"] = "Verhoog het aantal colommen" translations["increase the number of master clients"] = "Verhoog het aantal master applicaties" translations["Infected: "] = "Geinfecteerde: " translations["keep above other windows"] = "Hou boven andere applicaties" translations["Kernel: "] = "Kernel: " translations["label"] = "label" translations["launcher"] = "lanceerder" translations["Launcher"] = "Lanceerder" translations["Launch screen layout mode"] = "Lanceer scherm layout mode" translations["layout"] = "indeling" translations["lock the screen"] = "vergrendel het scherm" translations["Lock"] = "Vergrendel" translations["Logout"] = "Log uit" translations["maximize"] = "maximaliseren" translations["Media"] = "Media" translations["Mouse"] = "Muis" translations["Mouse Settings"] = "Muis Settings" translations["Mouse Speed"] = "Muis snelheid" translations["Mouse Acceleration"] = "Muis versnelling" translations["Memory"] = "Geheugen" translations["minimize"] = "minimalizeren" translations["move focused client to tag #"] = "verplaats applicatie naar label #" translations["Natural Scrolling"] = "Natuurlijk scrollen" translations["Network list"] = "Netwerk lijst" translations["Network Settings"] = "Netwerk Settings" translations["No active music player found."] = "Geen active muziekspeler gevonden." translations["No internet connection..."] = "Geen internet connectie..." translations["None available"] = "Niet beschikbaar" translations["Notifications"] = "Notificaties" translations["Offset"] = "compensatie" translations["Of which "] = "Waarvan " translations["OLED brightness mode"] = "OLED helderheid modus" translations["Open a Window Switcher"] = "Verander tussen applicaties" translations["Open Browser"] = "Open Browser" translations["Open Control panel"] = "Open Controle paneel" translations["Open file manager"] = "Open bestandsbeheerder" translations["Open Notification Center"] = "Open notificatie centrum" translations["Open Rofi"] = "Open Rofi" translations["Open Rofi"] = "Open Rofi" translations["Open settings application"] = "Toon settings applicatie" translations["Open system monitor"] = "Open systeembeheerder" translations["Open Terminal"] = "Open Terminal" translations["OS Name"] = "OS Naam" translations["OS: "] = "OS: " translations["OS Type"] = "OS Type" translations["Packages to update: "] = "Pakketjes om te updaten: " translations["Primary"] = "Primair" translations["Processor"] = "Processor" translations["Processor Core Count"] = "Aantal processorkernen" translations["Plugin System"] = "Plugin Systeem" translations["Put the system in sleep mode after a period of inactivity"] = "Zet het systeem in slaap modus na een periode van inactiviteit" translations["Quick settings"] = "Snelle settings" translations["quit awesome"] = "stop tde" translations["Quit"] = "Stop" translations["RAM"] = "RAM" translations["reload awesome"] = "herlaad tde" translations["Resolution"] = "Resolution" translations["Restart"] = "Herstart" translations["Restart"] = "Herstart" translations["restore minimized"] = "herstel geminimaliseert" translations["Save"] = "Slaag op" translations["Screen on time"] = "Scherm tijd" translations["Screen Settings"] = "Scherm Settings" translations["Screen System"] = "Scherm Systeem" translations["Screenshot"] = "Screenshot" translations["Screen timeout"] = "Scherm slaapstand" translations[" security vulnerabilities. Please try and update the system to prevent risks."] = " Beveiligingsproblemen gevonden. Probeer het systeem bij te werken om risico's te voorkomen." translations[" security vulnerability. Please try and update the system to prevent risks."] = " beveiligingsprobleem gevonden. Probeer het systeem bij te werken om risico's te voorkomen." translations["select next"] = "selecteer het volgende" translations["select previous"] = " selecteer het vorige" translations["Send error messages to the developers, this is useful for debugging and reducing errors/bugs"] = "Verzend error berichten naar de ontwikelaars, dit helpt met het oplossen van foutjes en errors" translations["Settings application"] = "Settings applicatie" translations["Show clipboard history"] = "Toon klembord verleden" translations["Show emoji selector"] = "Toon emoji's" translations["show help"] = "toon hulp" translations["Shutdown"] = "Schakel uit" translations["Skip break"] = "Pauze overslaan" translations["Sleep"] = "Slaap" translations["Social Media"] = "Sociale Media" translations["Spooky..."] = "Eng..." translations["System Notification"] = "Systeem Notificaties" translations["System"] = "Systeem" translations["System Updates"] = "Systeem Updates" translations["Tagbar anchor location"] = "Labelbar anker locatie" translations["Tagbar bar draw location"] = "Labelbar bar teken locatie" translations["tag"] = "label" translations["TDE Version"] = "TDE Versie" translations["Terminal"] = "Terminal" translations["test"] = "test" translations["Text Editor"] = "Textverwerker" translations["Thanks for using our product"] = "Bedankt om ons product te gebruiken" translations["The location where you want the tagbar to appear (default bottom)"] = "De plaat waar u het labelbar wilt laten verschijnen (standaard op de bodem)" translations["Theme"] = "Thema" translations["There is "] = "Er zijn" translations["There's nothing in here... Come back later."] = "Er is niets hier te vinden... Kom op een later moment terug" translations["Titlebar drawing"] = "Titlebar schrijven" translations["toggle exit screen"] = "schakel sluit scherm" translations["toggle floating"] = "Schakel zwevend applicaties" translations["toggle focused client on tag #"] = "schakel focus van applicatie op label #" translations["toggle fullscreen"] = "schakel fullscreen" translations["toggle music"] = "schakel muziek" translations["toggle mute"] = "schakel geluid dempen" translations["Toggle systray visibility"] = "Schakel systeem dienblad zichtbaarheid" translations["toggle tag #"] = "schakel tag #" translations["Topbar draw location"] = "Topbar schrijf locatie" translations["Trash contains:"] = "Vuilbak bevat:" translations["Trash"] = "Vuilbak" translations["Try again later."] = "Probeer later opnieuw." translations["Try and play some music :)"] = "Probeer wat muziek te spelen :)" translations["unmaximize"] = "minimalizeer" translations[" update is available!"] = " update is beschikbaar!" translations[" updates are available!"] = " updates zijn beschikbaar!" translations["Update"] = "Update" translations["Uptime: unknown"] = "Uptime: unknown" translations["Uptime: "] = "Uptime: " translations["user!"] = "gebruiken!" translations["Utility"] = "Nut" translations["view next"] = "bekijk volgende" translations["view previous"] = "bekijk vorige" translations["view tag #"] = "toon label #" translations["volume down"] = "volume omlaag" translations["volume up"] = "volume omhoog" translations["Volume"] = "Volume" translations["We are up-to-date!"] = "We zijn up to date!" translations["Weather & Temperature"] = "Weer & Temperatuur" translations["Web browser"] = "Web browser" translations["When enabled we don't draw icons or anything on the desktop"] = "Indien ingeschakeld, tekenen we geen icoontjes (of iets anders) op uw bureaublad" translations[ "when making a screenshot of a window, you can either show the screenshot or make a pretty version with some shadows, and your theme color" ] = "wanneer u een schermafbeelding van een venster maakt, kunt u de schermafbeelding laten zien of een mooie versie maken met een schaduw en uw themakleur" translations["Widgets"] = "Widgets" translations["Window Effects"] = "Scherm effecten" translations["Windowing system"] = "Windowing systeem" translations["window screenshot"] = "foto van een applicatie" translations["Window screenshot mode"] = "Schermafbeelding modus" translations["wired"] = "bedraad" translations["Wireless connection"] = "Draadloze verbinding" translations["Wireless Connection"] = "Draadloze Verbinding" translations["wireless"] = "draadloos" translations["Weak Hardware"] = "Zwakke hardware" translations["Disable a lot of the 'nice' features in order to reduce hardware consumption"] = "Schakel een hoop features uit om zodat zwakke hardware TDE ook kan draaien" translations[" before sleeping"] = " voor we in sluimermodus gaan" translations["Autofocus"] = "Autofocus" translations["Automatically make the focus follow the mouse without clicking"] = "De focus volgt uw muis, zelfs wanneer je niet klikt." translations["Tab between applications"] = "Tab tussen verschillende applicaties" translations["Tab between applications in reverse order"] = "Tab tussen verschillende applicaties in tegengestelde richting" translations["Tutorial"] = "Tutorial" return translations
surveytrigger = { Properties = { }, } function surveytrigger:OnActivate() -- For handling tick events. self.tickBusHandler = TickBus.Connect(self,self.entityId); self.activeSurveysList = {} self.currentSurvey = {} self.currentQuestionIndex = 0 self.displayTimer = 0.0 self.currentQuestionEntityID = EntityId() self.canvasEntityId = UiCanvasManagerBus.Broadcast.LoadCanvas("Levels/InGameSurveySample/UI/InGameSurveyMenu.uicanvas") --UiCanvasBus.Event.SetEnabled(self.canvasEntityId, false) self.notificationHandler = CloudGemInGameSurveyNotificationBus.Connect(self, self.entityId) local emptyString = "" --CloudGemInGameSurveyRequestBus.Event.GetActiveSurvey_metadata(self.entityId, 10, emptyString, emptyString, nil) end function surveytrigger:OnTick(deltaTime,timePoint) end function surveytrigger:OnDeactivate() self.notificationHandler:Disconnect(); self.tickBusHandler:Disconnect(); self.buttonHandler:Disconnect() end -- STEP ONE SURVEY METADATA function surveytrigger:OnGetActiveSurvey_metadataRequestSuccess(response) Debug.Log("OnGetActiveSurvey_metadataRequestSuccess succeeded") --self.activeSurveysList = {} Debug.Log("Response survey metadatalist: "..tostring(#response.metadata_list)); if #response.metadata_list >= 1 then UiCanvasBus.Event.SetEnabled(self.canvasEntityId, true) -- Listen for action strings broadcast by the canvas self.buttonHandler = UiCanvasNotificationBus.Connect(self, self.canvasEntityId) end end function surveytrigger:OnGetActiveSurvey_metadataRequestError(errorMsg) Debug.Log("GetActiveSurveys Error") end function surveytrigger:OnAction(entityId, actionName) Debug.Log(tostring(entityId) .. ": " .. actionName) if actionName == "SubmitResults" then UiCanvasBus.Event.SetEnabled(self.canvasEntityId, false) end end return surveytrigger
require "lunit" local testcase = lunit.TestCase("Test library loading doesn't affect globals") function testcase:test_no_global_clobbering () local globals = {} for key in pairs(_G) do globals[key] = true end -- Load all the modules for the different types of URIs, in case any one -- of those treads on a global. I keep them around in a table to make -- sure they're all loaded at the same time, just in case that does -- anything interesting. local schemes = { "_login", "_relative", "_util", "data", "file", "file.unix", "file.win32", "ftp", "http", "https", "pop", "rtsp", "rtspu", "telnet", "urn", "urn.isbn", "urn.issn", "urn.oid" } local loaded = {} local URI = require "uri" for _, name in ipairs(schemes) do loaded[name] = require("uri." .. name) end for key in pairs(_G) do lunit.assert_not_nil(globals[key], "global '" .. key .. "' created by lib") end for key in pairs(globals) do lunit.assert_not_nil(_G[key], "global '" .. key .. "' destroyed by lib") end end lunit.run() -- vi:ts=4 sw=4 expandtab
-- -- Copyright (c) 2016, Facebook, Inc. -- All rights reserved. -- -- This source code is licensed under the BSD-style license found in the -- LICENSE file in the root directory of this source tree. An additional grant -- of patent rights can be found in the PATENTS file in the same directory. -- -- The training loop and learning rate schedule -- local optim = require 'optim' local M = {} local Trainer = torch.class('LSTM.Trainer', M) function Trainer:__init(model, criterion, opt, optimState) self.model = model self.criterion = criterion self.optimState = optimState or { learningRate = opt.LR, learningRateDecay = 0.0, momentum = opt.momentum, nesterov = true, dampening = 0.0, weightDecay = opt.weightDecay, --SOS use 0.0 in this experiment to leave fronetend and ResNet unaltered } self.opt = opt self.params, self.gradParams = model:getParameters() end function Trainer:runningmean(xn,T) table.remove(T,1) table.insert(T,xn) local m = torch.Tensor(T):mean() return m,T end function Trainer:train(epoch, dataloader) -- Trains the model for a single epoch self.optimState.learningRate = self:learningRate(epoch) local timer = torch.Timer() local dataTimer = torch.Timer() local function feval() return self.criterion.output, self.gradParams end local trainSize = dataloader:size() local top1Sum, top5Sum, lossSum = 0.0, 0.0, 0.0 local N = 0 print('=> Training epoch # ' .. epoch) -- set the batch norm to training mode self.model:training() local nmean = 100 local Terr = torch.FloatTensor(nmean):fill(0):totable() local Ttop1 = torch.FloatTensor(nmean):fill(0):totable() local rerr = 0 local rtop1 = 0 local fake_examples = torch.IntTensor() for n, sample in dataloader:run() do local dataTime = dataTimer:time().real local loss = 0.0 local top1 = 0.0 local top5 = 0.0 fake_examples = self:copyInputs(sample) if fake_examples:sum() == 0 then local output = self.model:forward(self.input):float() local batchSize = output:size(1) local loss = self.criterion:forward(self.model.output, self.target) self.model:zeroGradParameters() self.criterion:backward(self.model.output, self.target) self.model:backward(self.input, self.criterion.gradInput) optim.adam(feval, self.params, self.optimState) -- I use adam in my latest experiments local top1, top5 = self:computeScore(output, sample.target, 1) top1Sum = top1Sum + top1*batchSize top5Sum = top5Sum + top5*batchSize lossSum = lossSum + loss*batchSize N = N + batchSize rerr, Terr = self:runningmean(loss,Terr) rtop1, Ttop1 = self:runningmean(top1,Ttop1) print((' | Epoch: [%d][%d/%d] Time %.3f Data %.3f Err %1.4f (%1.4f) top1 %7.3f (%7.3f) top5 %7.3f'):format( epoch, n, trainSize, timer:time().real, dataTime, loss, rerr, top1, rtop1, top5)) -- check that the storage didn't get changed do to an unfortunate getParameters call assert(self.params:storage() == self.model:parameters()[1]:storage()) timer:reset() dataTimer:reset() end end return top1Sum / N, top5Sum / N, lossSum / N end function Trainer:test(epoch, dataloader) -- Computes the top-1 and top-5 err on the validation set local timer = torch.Timer() local dataTimer = torch.Timer() local size = dataloader:size() local nCrops = self.opt.tenCrop and 10 or 1 local top1Sum, top5Sum, top10Sum = 0.0, 0.0, 0.0 local N = 0 self.model:evaluate() local fake_examples = torch.IntTensor() for n, sample in dataloader:run() do local dataTime = dataTimer:time().real -- Copy input and target to the GPU fake_examples = self:copyInputs(sample) local output = self.model:forward(self.input):float() local batchSize = output:size(1)/nCrops - fake_examples:sum() local loss = self.criterion:forward(self.model.output, self.target) local top1, top5, top10 = self:computeScore(output[{{1,batchSize}}], sample.target[{{1,batchSize}}], nCrops) top1Sum = top1Sum + top1*batchSize top5Sum = top5Sum + top5*batchSize top10Sum = top10Sum + top10*batchSize N = N + batchSize print((' | Test: [%d][%d/%d] Time %.3f Data %.3f top1 %7.3f (%7.3f) top5 %7.3f (%7.3f) top10 %7.3f (%7.3f)'):format( epoch, n, size, timer:time().real, dataTime, top1, top1Sum / N, top5, top5Sum / N, top10, top10Sum / N)) timer:reset() dataTimer:reset() end self.model:training() print((' * Finished epoch # %d top1: %7.3f top5: %7.3f top10: %7.3f\n'):format( epoch, top1Sum / N, top5Sum / N, top10Sum / N)) return top1Sum / N, top5Sum / N, top10Sum / N end function Trainer:computeScore(output, target, nCrops) if output:dim() == 3 then output = torch.sum(output,2):squeeze(2) -- sum over all outputs (for LSTM, that has one logsoftmax per frame) end if nCrops > 1 then -- Sum over crops output = output:view(output:size(1) / nCrops, nCrops, output:size(2)) --:exp() :sum(2):squeeze(2) end -- Computes the top1 and top5 error rate local batchSize = output:size(1) local _ , predictions = output:float():sort(2, true) -- descending -- Find which predictions match the target local correct = predictions:eq( target:long():view(batchSize, 1):expandAs(output)) -- Top-1 score local top1 = 1.0 - (correct:narrow(2, 1, 1):sum() / batchSize) -- Top-5 score, if there are at least 5 classes local len = math.min(5, correct:size(2)) local top5 = 1.0 - (correct:narrow(2, 1, len):sum() / batchSize) -- Top-10 score, if there are at least 10 classes local len = math.min(10, correct:size(2)) local top10 = 1.0 - (correct:narrow(2, 1, len):sum() / batchSize) return top1 * 100, top5 * 100, top10 * 100 end function Trainer:copyInputs(sample) -- To have a fixed number of examples per minibatch I add some fake examples in the last minibatch of each epoch, which are not used in training or in testing self.input = self.input or (self.opt.nGPU == 1 and torch.CudaTensor() or torch.CudaTensor()) self.target = self.target or (torch.CudaLongTensor and torch.CudaLongTensor() or torch.CudaTensor()) local fake_examples = torch.IntTensor(self.opt.batchSize):fill(0) if sample.input:size(1)<self.opt.batchSize then fake_examples[{{sample.input:size(1)+1,-1}}]:fill(1) --video: local P = torch.FloatTensor(self.opt.batchSize - sample.input:size(1),sample.input:size(2),sample.input:size(3),sample.input:size(4),sample.input:size(5)):normal(0,1) sample.input = torch.cat(sample.input,P:typeAs(sample.input),1) --target: local O = torch.LongTensor(self.opt.batchSize - sample.target:size(1)):random(1,500) sample.target = torch.cat(sample.target,O:typeAs(sample.target),1) end self.input:resize(sample.input:size()):copy(sample.input) target_rep = torch.repeatTensor(sample.target,self.opt.Nw,1):transpose(1,2) self.target:resize(target_rep:size()):copy(target_rep) return fake_examples end function Trainer:learningRate(epoch) -- Training schedule local decay = 0 if self.opt.dataset == 'imagenet' then decay = math.floor((epoch - 1) / 30) elseif self.opt.dataset == 'BBCnet' then decay = math.floor((epoch - 1) / 5) -- I drop it by half every 5 epochs elseif self.opt.dataset == 'cifar10' then decay = epoch >= 122 and 2 or epoch >= 81 and 1 or 0 elseif self.opt.dataset == 'cifar100' then decay = epoch >= 122 and 2 or epoch >= 81 and 1 or 0 end return self.opt.LR * math.pow(0.5, decay) end return M.Trainer
local templates = require('custom.MWS-Templates.main') local sine = templates.mimics.sine local cosine = templates.mimics.cosine local decoratorConfig = { showMessages = false, localization = { EnableMessage = color.Green .. "Decorator enabled, activate again for options.", DisableMessage = color.Green .. "Decorator disabled.", Label = "Decorator Menu", PositionButton = "Position 3d", RotateXButton = "Yaw", RotateYButton = "Pitch", RotateZButton = "Roll", PauseButton = "Pause", ManualButton = "Manual", PlaceButton = "Place", DisableButton = "Disable" }, defaultMode = "position", position = { height = 125, distance = 75, feedback = true }, rotation = { sensitivity = 10, feedback = true }, defaultMarker = { baseId = "misc_dwrv_artifact60" } } local modes = { { name = "pause", value = -1 }, { name = "position", value = 0 }, { name = "rotatex", value = 1, axis = "x", inverse = "u" }, { name = "rotatey", value = 2, axis = "y", inverse = "v" }, { name = "rotatez", value = 3, axis = "z", inverse = "w" } } local scripts = { script_decorator_position = templates.process([[ begin script_decorator_position float px float py float pz float sx float sz float cz float r float r0 short mode ``SINE`` ``COSINE`` if (script_decorator_globals.mode != mode) set r0 to 0 endif if (script_decorator_globals.mode == 0) set px to ( player->GetAngle X ) set pz to ( player->GetAngle Z ) set SINE_in to px `SINE` set sx to SINE_out set SINE_in to pz `SINE` set sz to SINE_out set COSINE_in to pz `COSINE` set cz to COSINE_out set px to ( {{position.distance}} * sz + player->GetPos X ) set py to ( {{position.distance}} * cz + player->GetPos Y ) set pz to ( {{position.height}} * (1 - sx) + player->GetPos Z ) {{#position.feedback}} MessageBox "%.3f %.3f %.3f", px, py, pz {{/position.feedback}} SetPos X px SetPos Y py SetPos Z pz endif {{#modes}} {{#axis}} if (script_decorator_globals.mode == {{value}}) ;set px to GetAngle x ;set py to GetAngle y ;set pz to GetAngle z set r to ( player->GetAngle Z ) set r to ( r * {{rotation.sensitivity}} ) ;set p{{axis}} to (r - r0) / GetSecondsPassed ;set r0 to r ;RotateWorld {{axis}} p{{axis}} SetAngle {{axis}} r ;set p{{axis}} to r ;SetAngle x px ;SetAngle y py ;SetAngle z pz {{#rotation.feedback}} set r to (r * `PI` / 180) MessageBox "%.3f", r {{/rotation.feedback}} endif {{/axis}} {{/modes}} set mode to script_decorator_globals.mode ` set px to GetAngle x set py to GetAngle y set pz to GetAngle z set px to px * `PI` / 180 set py to py * `PI` / 180 set pz to pz * `PI` / 180 MessageBox "%.3f %.3f %.3f", px, py, pz `noPickUp` end script_decorator_position ]], { position = decoratorConfig.position, rotation = decoratorConfig.rotation, modes = modes }), script_decorator_globals = [[ begin script_decorator_globals short mode end script_decorator_globals ]], script_decorator_menu = templates.process([[ begin script_decorator_menu `noPickUp` end script_decorator_menu ]]) } for _, mode in pairs(modes) do scripts["script_decorator_switch_" .. mode.name] = templates.process( [[ begin script_decorator_switch_{{name}} set script_decorator_globals.mode to {{value}} stopscript script_decorator_switch_{{name}} end script_decorator_switch_{{name}} ]], mode) end --[[for _, script in pairs(scripts) do print(script) end]] local MENU_REF_ID = "decorator_menu" local MARKER_REF_ID = "decorator_marker" local GHOST_RECORD_STORE = nil local enabled = {} local placingItems = {} local originals = {} local activeMode = {} local function CalculatePosition(pid, objectLoc) Players[pid]:SaveCell() local playerLoc = Players[pid].data.location objectLoc.posX = playerLoc.posX + decoratorConfig.position.distance * sine(playerLoc.rotZ) objectLoc.posY = playerLoc.posY + decoratorConfig.position.distance * cosine(playerLoc.rotZ) objectLoc.posZ = playerLoc.posZ + decoratorConfig.position.height * (1 - sine(playerLoc.rotX)) return objectLoc end local function CalculateRotation(pid, objectLoc, axis) Players[pid]:SaveCell() local playerLoc = Players[pid].data.location local rotate = (playerLoc.rotZ) * decoratorConfig.rotation.sensitivity-- % (math.pi * 2) --[[if rotate > math.pi then rotate = math.pi - rotate end]] objectLoc[axis] = rotate tes3mp.SendMessage(pid, "ROTATE " .. rotate .. "\n") return objectLoc end local function PlaceAtLocationForPlayer(pid, cellDescription, location, refId) local uniqueIndex = WorldInstance:GenerateUniqueIndex() local item = { uniqueIndex = uniqueIndex, refId = refId, location = location } LoadedCells[cellDescription]:LoadObjectsPlaced( pid, { [item.uniqueIndex] = { location = item.location, refId = item.refId, packetType = "place" } }, { item.uniqueIndex }, false ) return item end local function DeleteForPlayer(pid, cellDescription, uniqueIndex, refId) LoadedCells[cellDescription]:LoadObjectsDeleted( pid, { [uniqueIndex] = { refId = refId } }, { uniqueIndex }, false ) end local function UpdatePlacingLocationForPlayer(pid) local cellDescription = tes3mp.GetCell(pid) local item = placingItems[pid] tableHelper.print(item) placingItems[pid] = PlaceAtLocationForPlayer(pid, cellDescription, item.location, item.refId) DeleteForPlayer(pid, cellDescription, item.uniqueIndex, item.refId) end local function RotateForPlayer(pid, index, delta) local location = placingItems[pid].location location[index] = location[index] + delta UpdatePlacingLocationForPlayer(pid) end local function AddDecoratorMenu(pid, limit) local inventory = Players[pid].data.inventory limit = limit or 1 local load = false local index if not inventoryHelper.containsItem(inventory, MENU_REF_ID) then inventoryHelper.addItem(inventory, MENU_REF_ID, 1, -1, -1, "") load = true index = #inventory tableHelper.print(inventory[index]) else index = inventoryHelper.getItemIndex(inventory, MENU_REF_ID, -1, -1, "") if inventory[index].count < limit then load = true end end if load then tes3mp.ClearInventoryChanges(pid) tes3mp.SetInventoryChangesAction(pid, enumerations.inventory.ADD) packetBuilder.AddPlayerInventoryItemChange(pid, inventory[index]) tes3mp.SendInventoryChanges(pid) end end local function ReturnOriginal(pid, cellDescription) local uniqueIndex = next(originals[pid]) local original = originals[pid][uniqueIndex] inventoryHelper.addItem( Players[pid].data.inventory, original.refId, original.count or 1, original.charge or -1, original.enchantmentCharge or -1, original.soul or '' ) local item = placingItems[pid] DeleteForPlayer(pid, cellDescription, item.uniqueIndex, item.refId) tes3mp.ClearInventoryChanges(pid) tes3mp.SetInventoryChangesAction(pid, enumerations.inventory.ADD) packetBuilder.AddPlayerInventoryItemChange(pid, original) tes3mp.SendInventoryChanges(pid) placingItems[pid] = nil originals[pid] = nil end local function CalculatePlacingLocation(pid) local aMode = activeMode[pid] local item = placingItems[pid] if aMode == "position" then CalculatePosition(pid, item.location) elseif aMode == "rotatex" then CalculateRotation(pid, item.location, "rotX") elseif aMode == "rotatey" then CalculateRotation(pid, item.location, "rotY") elseif aMode == "rotatez" then CalculateRotation(pid, item.location, "rotZ") else return false end return true end local function SwitchMode(pid, mode) logicHandler.RunConsoleCommandOnPlayer(pid, "StartScript script_decorator_switch_" .. mode) if placingItems[pid] then CalculatePlacingLocation(pid) --UpdatePlacingLocationForPlayer(pid) end activeMode[pid] = mode end local function PlaceOriginal(pid) if placingItems[pid] then CalculatePlacingLocation(pid) local item = placingItems[pid] local originalObjects = originals[pid] local originalObject = originalObjects[next(originalObjects)] originalObject.location = item.location local cellDescription = tes3mp.GetCell(pid) local eventStatus = customEventHooks.triggerValidators("OnObjectPlace", { pid, cellDescription, originalObjects, {} }) if eventStatus.validDefaultHandler then LoadedCells[cellDescription]:SaveObjectsPlaced(originalObjects) LoadedCells[cellDescription]:LoadObjectsPlaced(pid, originalObjects, tableHelper.getArrayFromIndexes(originalObjects), true) end customEventHooks.triggerHandlers("OnObjectPlace", eventStatus, {pid, cellDescription, originalObjects, {}}) DeleteForPlayer(pid, cellDescription, item.uniqueIndex, item.refId) originals[pid] = nil placingItems[pid] = nil return customEventHooks.makeEventStatus(false, false) end end local ShowDecoratorMenu = nil local function ShowManualMenu(pid) async.Wrap(function() local buttons = {} local buttonsMap = {} table.insert(buttons, "RX+") table.insert(buttonsMap, 'RX+') table.insert(buttons, "RX-") table.insert(buttonsMap, 'RX-') table.insert(buttons, "RY+") table.insert(buttonsMap, 'RY+') table.insert(buttons, "RY-") table.insert(buttonsMap, 'RY-') table.insert(buttons, "RZ+") table.insert(buttonsMap, 'RZ+') table.insert(buttons, "RZ-") table.insert(buttonsMap, 'RZ-') table.insert(buttons, "Back") table.insert(buttonsMap, 'back') local buttonNumber = guiHelper.CustomMessageBoxAsync(pid, buttons, decoratorConfig.localization.Label) if buttonNumber == nil then return end local result = buttonsMap[buttonNumber] if result == 'back' then ShowDecoratorMenu(pid) else local command = string.sub(result, 1, 1) local axis = string.sub(result, 2, 2) local direction = string.sub(result, 3, 3) == '+' and 1 or -1 if command == "R" then RotateForPlayer(pid, "rot" .. string.upper(axis), direction * 5 * 2 * math.pi / 360) end ShowManualMenu(pid) end end) end local function ShowAxisMenu(pid, axis) async.Wrap(function() end) end local function ShowDecoratorMenu(pid) if not enabled[pid] then enabled[pid] = true if decoratorConfig.showMessages then tes3mp.SendMessage(pid, decoratorConfig.localization.EnableMessage .. "\n") end end async.Wrap(function() local buttons = {} local buttonsMap = {} table.insert(buttons, decoratorConfig.localization.PositionButton) table.insert(buttonsMap, 'position') table.insert(buttons, decoratorConfig.localization.RotateXButton) table.insert(buttonsMap, 'rotatex') table.insert(buttons, decoratorConfig.localization.RotateYButton) table.insert(buttonsMap, 'rotatey') table.insert(buttons, decoratorConfig.localization.RotateZButton) table.insert(buttonsMap, 'rotatez') table.insert(buttons, decoratorConfig.localization.PauseButton) table.insert(buttonsMap, 'pause') if not placingItems[pid] then table.insert(buttons, decoratorConfig.localization.DisableButton) table.insert(buttonsMap, 'disable') else table.insert(buttons, decoratorConfig.localization.ManualButton) table.insert(buttonsMap, 'manual') table.insert(buttons, decoratorConfig.localization.PlaceButton) table.insert(buttonsMap, 'place') end local buttonNumber = guiHelper.CustomMessageBoxAsync(pid, buttons, decoratorConfig.localization.Label) if buttonNumber == nil then return end local result = buttonsMap[buttonNumber] if result == 'disable' then enabled[pid] = false PlaceOriginal(pid) if decoratorConfig.showMessages then tes3mp.SendMessage(pid, decoratorConfig.localization.DisableMessage .. "\n") end elseif result == 'place' then PlaceOriginal(pid) elseif result == 'manual' then SwitchMode(pid, 'pause') async.Wrap(function() ShowManualMenu(pid) end) else SwitchMode(pid, result) end end) end customEventHooks.registerHandler('OnServerPostInit', function(eventStatus) if eventStatus.validCustomHandlers then GHOST_RECORD_STORE = RecordStores.miscellaneous for refId, text in pairs(scripts) do RecordStores.script.data.permanentRecords[refId] = { scriptText = text } end RecordStores.miscellaneous.data.permanentRecords[MARKER_REF_ID] = decoratorConfig.defaultMarker RecordStores.miscellaneous.data.permanentRecords[MENU_REF_ID] = { name = "Decorator Menu", model = "m/misc_dwrv_gear00.nif", icon = "m/misc_dwrv_gear00.dds", weight = 0, value = 0, script = "script_decorator_menu" } end end) customEventHooks.registerHandler('OnPlayerAuthentified', function(eventStatus, pid) if eventStatus.validCustomHandlers then AddDecoratorMenu(pid) SwitchMode(pid, decoratorConfig.defaultMode) end end) customEventHooks.registerHandler('OnPlayerItemUse', function(eventStatus, pid, refId) if eventStatus.validCustomHandlers then if refId == MENU_REF_ID then ShowDecoratorMenu(pid) end end end) customEventHooks.registerValidator('OnCellUnload', function(eventStatus, pid, cellDescription) if eventStatus.validCustomHandlers then if placingItems[pid] then ReturnOriginal(pid, cellDescription) end end end) --[[customEventHooks.registerValidator('OnPlayerCellChange', function(eventStatus, pid, cellDescription) if eventStatus.validCustomHandlers then if placingItems[pid] then if LoadedCells[cellDescription] and not LoadedCells[cellDescription].isExterior then ReturnOriginal(pid, cellDescription) end end end end)]] customEventHooks.registerValidator('OnPlayerDisconnect', function(eventStatus, pid) if eventStatus.validCustomHandlers then if placingItems[pid] then ReturnOriginal(pid, tes3mp.GetCell(pid)) end enabled[pid] = nil activeMode[pid] = nil end end) customEventHooks.registerValidator('OnObjectPlace', function(eventStatus, pid, cellDescription, objects) if not eventStatus.validCustomHandlers or #objects > 1 then return end for uniqueIndex, object in pairs(objects) do if object.refId == MENU_REF_ID then AddDecoratorMenu(pid, 2) DeleteForPlayer(pid, cellDescription, uniqueIndex, MENU_REF_ID) return customEventHooks.makeEventStatus(false, false) elseif enabled[pid] and not placingItems[pid] then local decoratorEventStatus = customEventHooks.triggerValidators("Decorator_OnActivate", { pid, cellDescription, object }) if not decoratorEventStatus.validDefaultHandler then return end local refId = GHOST_RECORD_STORE:GenerateRecordId() local records = { [refId] = { baseId = object.refId, script = "script_decorator_position" } } GHOST_RECORD_STORE:LoadRecords(pid, records, {refId}, false) placingItems[pid] = PlaceAtLocationForPlayer(pid, cellDescription, object.location, refId) DeleteForPlayer(pid, cellDescription, uniqueIndex, object.refId) originals[pid] = objects customEventHooks.triggerHandlers("Decorator_OnActivate", decoratorEventStatus, { pid, cellDescription, object }) return customEventHooks.makeEventStatus(false, false) end end end)
local energy_10kw = 166.666666666666 local energy_cooldown = 0.98 local current_cranks = {} script.on_event(defines.events.on_tick, function() local new_cranks = {} for _, crank in pairs(current_cranks) do if crank.valid then crank.power_production = crank.power_production * energy_cooldown - (1 - energy_cooldown) if crank.power_production <= 0.05 then crank.power_production = 0 else new_cranks[crank.unit_number] = crank end end end current_cranks = new_cranks for _, player in pairs(game.players) do if player.walking_state.walking and player.walking_state.direction == defines.direction.north then local position = player.position position.y = position.y - 1.0 local crank = player.surface.find_entity('hand-crank', position) if crank then crank.power_production = energy_10kw current_cranks[crank.unit_number] = crank end end end end)
----------------------------------------------------- PLUGIN.name = "Papers, Please" PLUGIN.author = "RobertLP" PLUGIN.desc = "Let's players give their papers" --Includes nut.util.include("cl_openpapers.lua", "client") if (SERVER) then hook.Add("PlayerSpawn", "papers_init_spawn", function(ply) local item = nut.item.list["papers"] local inv = ply:getChar():getInv() if not inv:hasItem(item.uniqueID, item:getData()) then local x,y = inv:findEmptySlot(item.width, item.height, true) inv:add(item.uniqueID, 1, item:getData(), x, y) end end) end
local kAddonName, addon = ... addon.guiutils = {} local L = LibStub('AceLocale-3.0'):GetLocale(kAddonName) _G.StaticPopupDialogs[kAddonName .. '_CONFIRM_DELETE'] = { text = L['Really delete this?'], button1 = _G.ACCEPT, button2 = _G.CANCEL, timeout = 0, showAlert = true, exclusive = true, hideOnEscape = true, } _G.StaticPopupDialogs[kAddonName .. '_EXPORT_ENTRY'] = { text = L['Copy the text below. This text can be imported.'], button1 = _G.DONE, OnShow = function(self) self.editBox:SetText(self.data) self.editBox:SetFocus() self.editBox:HighlightText() end, timeout = 0, wide = true, hasEditBox = true, editBoxWidth = 250, exclusive = true, hideOnEscape = true, } _G.StaticPopupDialogs[kAddonName .. '_IMPORT_ENTRY'] = { text = L['Paste the entry text to import below.'], button1 = _G.ACCEPT, button2 = _G.CANCEL, timeout = 0, wide = true, hasEditBox = true, editBoxWidth = 250, exclusive = true, hideOnEscape = true, } function addon.guiutils.confirmDelete(callback) local function onAccept() callback() end _G.StaticPopupDialogs[kAddonName .. '_CONFIRM_DELETE'].OnAccept = onAccept _G.StaticPopup_Show(kAddonName .. '_CONFIRM_DELETE') end function addon.guiutils.promptExport(entryText) _G.StaticPopup_Show(kAddonName .. '_EXPORT_ENTRY', nil, nil, entryText) end function addon.guiutils.promptImport(callback) local function onAccept(self) callback(self.editBox:GetText()) end _G.StaticPopupDialogs[kAddonName .. '_IMPORT_ENTRY'].OnAccept = onAccept _G.StaticPopup_Show(kAddonName .. '_IMPORT_ENTRY') end function addon.guiutils.closePrompts() _G.StaticPopup_Hide(kAddonName .. '_CONFIRM_DELETE') _G.StaticPopup_Hide(kAddonName .. '_EXPORT_ENTRY') _G.StaticPopup_Hide(kAddonName .. '_IMPORT_ENTRY') end function addon.guiutils.compareByName(left, right) return left.name < right.name end function addon.guiutils.isValidCooldown(text) return (pcall(addon.utils.parseCooldown, text)) end function addon.guiutils.onCooldownTextChanged(self) if addon.guiutils.isValidCooldown(self:GetText()) then self:SetTextColor(1.0, 1.0, 1.0) else self:SetTextColor(0.8, 0.1, 0.1) end end function addon.guiutils.getSelectedEntryIndex() local state = addon.store.getState() return state.selectedEntryIndex end local function updateScrollerList(scroller, items, updateLine) local totalCount = #items local shownCount = math.min(#scroller.buttons, totalCount) local offset = _G.HybridScrollFrame_GetOffset(scroller) for i, line in ipairs(scroller.buttons) do local index = i + offset line:SetID(index) line.item = nil if index > totalCount then line:Hide() else line:Show() line.item = items[index] updateLine(line, line.item) end end local totalHeight = totalCount * scroller.buttonHeight local shownHeight = shownCount * scroller.buttonHeight _G.HybridScrollFrame_Update(scroller, totalHeight, shownHeight) end function addon.guiutils.updateScroller(scroller, items, updateLine) local function updateAfterScroll() updateScrollerList(scroller, items, updateLine) end scroller.update = updateAfterScroll updateAfterScroll() end function addon.guiutils.setupTooltip(frame, title, text, disabledText) local function onEnter(self) _G.GameTooltip:SetOwner(self, 'ANCHOR_RIGHT') _G.GameTooltip:SetText(title) local textToShow = text if self.extraTooltipText then textToShow = textToShow .. '\n\n' .. self.extraTooltipText end if disabledText and not self:IsEnabled() then textToShow = textToShow .. '\n\n|cffcc2525' .. disabledText .. '|r' end _G.GameTooltip:AddLine(textToShow, 1.0, 1.0, 1.0, true) _G.GameTooltip:Show() end frame:SetScript('OnEnter', onEnter) frame:SetScript('OnLeave', _G.GameTooltip_Hide) if disabledText then frame:SetMotionScriptsWhileDisabled(true) end end function addon.guiutils.create(frameType, name, parent, inherits) assert(name and parent) local frame = _G.CreateFrame(frameType, '$parent' .. name, parent, inherits) parent[name:sub(1, 1):lower() .. name:sub(2)] = frame return frame end function addon.guiutils.createButton(name, parent, inherits, onClick) assert(onClick) local button = addon.guiutils.create('Button', name, parent, inherits) button:SetScript('OnClick', onClick) return button end function addon.guiutils.createTextButton(name, parent, text, onClick) local button = addon.guiutils.createButton(name, parent, 'GameMenuButtonTemplate', onClick) button:SetText(text) button:SetWidth(100) return button end function addon.guiutils.createSelect(name, parent, width, init) local frame = addon.guiutils.create('Frame', name, parent, 'UIDropDownMenuTemplate') _G.UIDropDownMenu_SetInitializeFunction(frame, init) if width == 'MENU' then frame:Hide() _G.UIDropDownMenu_SetDisplayMode(frame, 'MENU') else _G.UIDropDownMenu_SetWidth(frame, width, 20) end return frame end local function createHelp(parent, tooltipTitle, tooltipText, initDropdown) local dropdown local function toggleDropdown() _G.ToggleDropDownMenu(1, nil, dropdown) end local button = addon.guiutils.createButton('Help', parent, nil, toggleDropdown) button:SetNormalTexture('Interface/Common/help-i') button:SetHighlightTexture('Interface/Buttons/ButtonHilight-Square', 'ADD') button:SetSize(24, 24) -- The (i) icon is too small when set with :SetNormalTexture(). Make it bigger. local icon = button:GetNormalTexture() icon:ClearAllPoints() icon:SetPoint('CENTER') icon:SetSize(40, 40) addon.guiutils.setupTooltip(button, tooltipTitle, tooltipText) dropdown = addon.guiutils.createSelect('HelpSelect', parent, 'MENU', initDropdown) dropdown:Hide() dropdown:SetPoint('TOPLEFT', button, 'TOPLEFT') return button end local function createTitle(parent, titleText, subtitleText, helpText, initHelpDropdown) local helpButton = createHelp(parent, titleText, helpText, initHelpDropdown) helpButton:SetPoint('TOPLEFT', 0, 3) local title = parent:CreateFontString('$parentTitle', 'ARTWORK', 'GameFontNormalLarge') title:SetText(titleText) title:SetPoint('TOPLEFT', 30, 0) local subtitle = parent:CreateFontString('$parentSubtitle', 'ARTWORK', 'GameFontNormalSmall') subtitle:SetText(subtitleText) subtitle:SetPoint('BOTTOMLEFT', title, 'BOTTOMRIGHT', 15, 2) return helpButton, title, subtitle end local function createContent(parent, lineCount, createLine) local frame = addon.guiutils.create('Frame', 'Content', parent) frame:SetBackdrop({ bgFile = 'Interface/Tooltips/UI-Tooltip-Background', edgeFile = 'Interface/Tooltips/UI-Tooltip-Border', tile = true, tileSize = 16, edgeSize = 16, insets = { left = 3, right = 3, top = 3, bottom = 3 }, }) frame:SetBackdropColor(0.0, 0.0, 0.0) frame:SetPoint('TOPLEFT', 0, -20) frame:SetPoint('BOTTOMRIGHT', 0, 0) local scroller = addon.guiutils.create( 'ScrollFrame', 'Scroller', frame, 'MinimalHybridScrollFrameTemplate') scroller:SetPoint('TOPLEFT', 10, -5) scroller:SetPoint('BOTTOMRIGHT', -28, 5) scroller:SetWidth(525) scroller.buttons = {} for i = 1, lineCount do local line = createLine(scroller.scrollChild, i) if i == 1 then line:SetPoint('TOPLEFT') else line:SetPoint('TOPLEFT', scroller.buttons[i - 1], 'BOTTOMLEFT') end scroller.buttons[i] = line end _G.HybridScrollFrame_CreateButtons(scroller) return frame end function addon.guiutils.createSection(spec) local frame = addon.guiutils.create('Frame', spec.name, spec.parent) frame:SetHeight(spec.height) createTitle(frame, spec.title, spec.subtitle, spec.help, spec.initHelpDropdown) createContent(frame, spec.lineCount, spec.createLine) return frame end
--==================================================================================== -- #Author: Jonathan D @ Gannon -- -- Développée pour la communauté n3mtv -- https://www.twitch.tv/n3mtv -- https://twitter.com/n3m_tv -- https://www.facebook.com/lan3mtv --==================================================================================== -- Configuration local KeyToucheClose = 177 local distMaxCheck = 3 -- Variable | 0 close | 1 Identity | 2 register local menuIsOpen = 0 --==================================================================================== -- TEMPORAIRE thead interaction --==================================================================================== Citizen.CreateThread(function() while true do Citizen.Wait(0) if menuIsOpen ~= 0 then if IsControlJustPressed(1, KeyToucheClose) then closeGui() elseif menuIsOpen == 2 then local ply = GetPlayerPed(-1) DisableControlAction(0, 1, true) DisableControlAction(0, 2, true) DisablePlayerFiring(ply, true) DisableControlAction(0, 142, true) DisableControlAction(0, 106, true) if IsDisabledControlJustReleased(0, 142) then SendNUIMessage({method = "clickGui"}) end end end end end) --==================================================================================== -- User Event --==================================================================================== RegisterNetEvent("gcl:showItentity") AddEventHandler("gcl:showItentity", function() local p , dist = GetClosestPlayer(distMaxCheck) if p ~= -1 then TriggerServerEvent('gc:openIdentity', GetPlayerServerId(p)) end end) RegisterNetEvent("gcl:openMeIdentity") AddEventHandler("gcl:openMeIdentity", function() TriggerServerEvent('gc:openMeIdentity') end) --==================================================================================== -- Gestion des evenements Server --==================================================================================== RegisterNetEvent("gc:showItentity") AddEventHandler("gc:showItentity", function(data) openGuiIdentity(data) end) RegisterNetEvent("gc:showRegisterItentity") AddEventHandler("gc:showRegisterItentity", function() openGuiRegisterIdentity() end) RegisterNUICallback('register', function(data, cb) closeGui() TriggerServerEvent('gc:setIdentity', data) cb() end) --==================================================================================== -- Gestion UI --==================================================================================== function openGuiIdentity(data) --SetNuiFocus(true) SendNUIMessage({method = 'openGuiIdentity', data = data}) menuIsOpen = 1 end function openGuiRegisterIdentity() SetNuiFocus(true) SendNUIMessage({method = 'openGuiRegisterIdentity'}) menuIsOpen = 2 end function closeGui() SetNuiFocus(false) SendNUIMessage({method = 'closeGui'}) menuIsOpen = 0 end --==================================================================================== -- Utils function --==================================================================================== function GetClosestPlayer(distmax) local players = GetPlayers() local closestDistance = distmax or -1 local closestPlayer = -1 local ply = GetPlayerPed(-1) local plyCoords = GetEntityCoords(ply, 0) for _ ,value in ipairs(players) do local target = GetPlayerPed(value) if(target ~= ply) then local targetCoords = GetEntityCoords(GetPlayerPed(value), 0) local distance = GetDistanceBetweenCoords(targetCoords["x"], targetCoords["y"], targetCoords["z"], plyCoords["x"], plyCoords["y"], plyCoords["z"], true) if(closestDistance == -1 or closestDistance > distance) then closestPlayer = value closestDistance = distance end end end return closestPlayer, closestDistance end function GetPlayers() local players = {} for i = 0, 31 do if NetworkIsPlayerActive(i) then table.insert(players, i) end end return players end
--ZFUNC-asciichunks-v1 local function asciichunks( str, length ) --> chunks length = length or 1 local chunks = {} local i = 1 local last = string.len( str ) while i <= last do local j = i + length - 1 table.insert( chunks, str:sub( i, j ) ) i = i + length end return chunks end return asciichunks
local function parse_diff(output) local header = {} local hunks = {} local is_header = true for i=1,#output do if is_header and output[i]:match('^@@.*@@') then is_header = false end if is_header then table.insert(header, output[i]) else table.insert(hunks, output[i]) end end local diff = { lines = hunks, hunks = {} } local len = #hunks local hunk = nil for i=1,len do local line = hunks[i] if not vim.startswith(line, "+++") then local index_from, index_len, disk_from, disk_len = line:match('@@ %-(%d+),?(%d*) %+(%d+),?(%d*) @@') if index_from then if hunk ~= nil then table.insert(diff.hunks, hunk) end hunk = { index_from = tonumber(index_from), index_len = tonumber(index_len) or 1, disk_from = tonumber(disk_from), disk_len = tonumber(disk_len) or 1, first = i, last = i } else hunk.last = hunk.last + 1 end end end table.insert(diff.hunks, hunk) return diff end local diff = { parse = parse_diff } return diff
local keywordHandler = KeywordHandler:new() local npcHandler = NpcHandler:new(keywordHandler) NpcSystem.parseParameters(npcHandler) function onCreatureAppear(cid) npcHandler:onCreatureAppear(cid) end function onCreatureDisappear(cid) npcHandler:onCreatureDisappear(cid) end function onCreatureSay(cid, type, msg) npcHandler:onCreatureSay(cid, type, msg) end function onThink() npcHandler:onThink() end -- Spark of the Phoenix local blessKeyword = keywordHandler:addKeyword({'phoenix'}, StdModule.say, {npcHandler = npcHandler, text = 'The Spark of the Phoenix is given by me and by the great geomancer of the local earth temple. Do you wish to receive my part of the Spark of the Phoenix for |BLESSCOST| gold?'}) blessKeyword:addChildKeyword({'yes'}, StdModule.bless, {npcHandler = npcHandler, text = 'So receive the spark of the phoenix, pilgrim.', cost = '|BLESSCOST|', bless = 4}) blessKeyword:addChildKeyword({''}, StdModule.say, {npcHandler = npcHandler, text = 'Maybe another time.', reset = true}) keywordHandler:addAliasKeyword({'spark'}) -- Basic keywordHandler:addKeyword({'gods'}, StdModule.say, {npcHandler = npcHandler, text = 'The ways of the gods are imprehensible to mortals. On the other hand, the elements are raw forces and can be understood and tamed.'}) keywordHandler:addKeyword({'job'}, StdModule.say, {npcHandler = npcHandler, text = 'I am the head pyromancer of Kazordoon.'}) keywordHandler:addKeyword({'name'}, StdModule.say, {npcHandler = npcHandler, text = 'My name is Pydar Firefist, Son of Fire, from the Savage Axes.'}) keywordHandler:addKeyword({'quest'}, StdModule.say, {npcHandler = npcHandler, text = 'Ask around. There\'s a lot to do, jawoll.'}) keywordHandler:addKeyword({'tibia'}, StdModule.say, {npcHandler = npcHandler, text = 'That is our world.'}) keywordHandler:addKeyword({'time'}, StdModule.say, {npcHandler = npcHandler, text = 'It\'s the fourth age of the yellow flame.'}) keywordHandler:addKeyword({'monsters'}, StdModule.say, {npcHandler = npcHandler, text = 'May the great flame devour them all!'}) keywordHandler:addKeyword({'life'}, StdModule.say, {npcHandler = npcHandler, text = 'Life feeds on fire and ultimately fire will feed on life.'}) keywordHandler:addKeyword({'excalibug'}, StdModule.say, {npcHandler = npcHandler, text = 'A weapon too powerful to be wielded by mortals. It has to be returned to the fire which gave birth to it.'}) keywordHandler:addKeyword({'ferumbras'}, StdModule.say, {npcHandler = npcHandler, text = 'If he ever dares enter Kazordoon I will gladly dump him into the lava. Tthe sacred flame shall bring justice upon him.'}) keywordHandler:addKeyword({'kazordoon'}, StdModule.say, {npcHandler = npcHandler, text = 'Our city was founded in ancient times. Abandoned by the gods we once fought for, we created a secure haven for our people.'}) keywordHandler:addKeyword({'the big old one'}, StdModule.say, {npcHandler = npcHandler, text = 'This mountain is said to be the oldest in the world. It is the place where fire and earth meet and separate at the same time.'}) keywordHandler:addKeyword({'bezil'}, StdModule.say, {npcHandler = npcHandler, text = 'Bezil and Nezil are buying and selling equipment of all kinds.'}) keywordHandler:addKeyword({'nezil'}, StdModule.say, {npcHandler = npcHandler, text = 'Bezil and Nezil are buying and selling equipment of all kinds.'}) keywordHandler:addKeyword({'duria'}, StdModule.say, {npcHandler = npcHandler, text = 'She is the first knight of Kazordoon. She is responsible for teaching our young warriors how to handle an axe.'}) keywordHandler:addKeyword({'etzel'}, StdModule.say, {npcHandler = npcHandler, text = 'Etzel is a true master of the elements. He is a role-model for our youngsters, jawoll.'}) keywordHandler:addKeyword({'jimbin'}, StdModule.say, {npcHandler = npcHandler, text = 'He and his wife are running the Jolly Axeman tavern.'}) keywordHandler:addKeyword({'kroox'}, StdModule.say, {npcHandler = npcHandler, text = 'He is a smith. If you are looking for exquisite weapons and armour just talk to him.'}) keywordHandler:addKeyword({'maryza'}, StdModule.say, {npcHandler = npcHandler, text = 'She and her husband are running the Jolly Axeman tavern.'}) keywordHandler:addKeyword({'uzgod'}, StdModule.say, {npcHandler = npcHandler, text = 'Uzgod is a weaponsmith just like those in the old legends.'}) keywordHandler:addKeyword({'durin'}, StdModule.say, {npcHandler = npcHandler, text = 'Though we are through with the so-called gods, Durin, the first dwarf to aquire divine powers of his own, is considered a protector of our race.'}) keywordHandler:addKeyword({'fire'}, StdModule.say, {npcHandler = npcHandler, text = 'Unlike the gods, the elements don\'t use mortals as toys, A skilled mind can understand and even control them to some extent.'}) keywordHandler:addKeyword({'keeper'}, StdModule.say, {npcHandler = npcHandler, text = 'The ways of the gods are imprehensible to mortals. On the other hand, the elements are raw forces and can be understood and tamed.'}) keywordHandler:addKeyword({'spiritual'}, StdModule.say, {npcHandler = npcHandler, text = 'You can receive the Spiritual Shielding in the Whiteflower Temple south of Thais.'}) keywordHandler:addKeyword({'suns'}, StdModule.say, {npcHandler = npcHandler, text = 'Ask for the Fire of the Suns in the Suntower near Ab\'Dendriel.'}) keywordHandler:addKeyword({'embrace'}, StdModule.say, {npcHandler = npcHandler, text = 'The druids north of Carlin can provide you with the Embrace of Tibia.'}) keywordHandler:addKeyword({'solitude'}, StdModule.say, {npcHandler = npcHandler, text = 'Talk to the hermit Eremo on the isle of Cormaya about this blessing.'}) keywordHandler:addKeyword({'heal'}, StdModule.say, {npcHandler = npcHandler, text = text}, function(player) return player:getCondition(CONDITION_FIRE) ~= nil end) keywordHandler:addKeyword({'heal'}, StdModule.say, {npcHandler = npcHandler, text = 'You aren\'t looking that bad. Sorry, I can\'t help you. But if you are looking for additional protection you should go on the {pilgrimage} of ashes.'}) keywordHandler:addKeyword({'pilgrimage'}, StdModule.say, {npcHandler = npcHandler, text = 'I\'m the head pyromancer of Kazordoon. I guess you are here for healing or looking for a blessing.'}) keywordHandler:addKeyword({'blessing'}, StdModule.say, {npcHandler = npcHandler, text = 'There are five different blessings available in five sacred places. These blessings are: the {spiritual} shielding, the spark of the {phoenix}, the {embrace} of Tibia, the fire of the {suns} and the wisdom of {solitude}.'}) keywordHandler:addKeyword({'pyromancer'}, StdModule.say, {npcHandler = npcHandler, text = 'We are the keepers and shepherds of the elemental force of {fire}.'}) npcHandler:setMessage(MESSAGE_GREET, 'Be greeted |PLAYERNAME|! I can smell the scent of a phoenix on you!') npcHandler:setMessage(MESSAGE_FAREWELL, 'May the fire in your heart never die, |PLAYERNAME|!') npcHandler:setMessage(MESSAGE_WALKAWAY, 'May the fire in your heart never die.') npcHandler:addModule(FocusModule:new())
local vim = vim or {} local api = vim.api local lsp = vim.lsp local uv = vim.loop local callbacks = require'lsp_ext/callbacks' local util = require'lsp_ext/util' local putil = require'lsp_ext/private/util' local M = { signature_help_debounce_timer = nil; diagnostics_debounce_timer = nil; diagnostics = vim.empty_dict(); } function M.set_signature_help_autocmd(wait) wait = wait or 100 lsp.callbacks['textDocument/signatureHelp'] = callbacks.signature_help api.nvim_command('augroup nvim_lsp_signature_help') api.nvim_command('autocmd!') api.nvim_command(string.format("autocmd CursorMoved,CursorMovedI,VimResized,BufHidden,BufLeave * lua require'lsp_ext'._on_cursor_moved_for_signature_help(%s)", wait)) api.nvim_command('augroup END') end function M.unset_signature_help_autocmd() api.nvim_command('augroup nvim_lsp_signature_help') api.nvim_command('autocmd!') api.nvim_command('augroup END') end function M._on_cursor_moved_for_signature_help(wait) vim.validate{wait={wait,'n'}} local function should_call_signature_help() local chars = vim.tbl_flatten(vim.tbl_map(function(cap) return cap.resolved_capabilities.signature_help_trigger_characters end, util.buf_resolved_capabilities())) if vim.tbl_contains(chars, putil.get_before_char_skip_white()) then return true end return false end if not should_call_signature_help() then return end if M.signature_help_debounce_timer ~= nil then if uv.is_active(M.signature_help_debounce_timer) then putil.clear_timeout(M.signature_help_debounce_timer) end M.signature_help_debounce_timer = nil end M.signature_help_debounce_timer = putil.set_timeout(wait, vim.schedule_wrap(lsp.buf.signature_help)) end function M.set_publish_diagnostics_autocmd(wait) wait = wait or 100 lsp.callbacks['textDocument/publishDiagnostics'] = callbacks.publish_diagnostics api.nvim_command('augroup nvim_lsp_publish_diagnostics') api.nvim_command('autocmd!') api.nvim_command(string.format("autocmd CursorMoved * lua require'lsp_ext'._on_cursor_moved_for_publish_diagnostics(%s)", wait)) api.nvim_command('augroup END') end function M.unset_publish_diagnostics_autocmd() api.nvim_command('augroup nvim_lsp_signature_help') api.nvim_command('autocmd!') api.nvim_command('augroup END') end function M.set_diagnostics(diagnostics_params) if vim.tbl_isempty(diagnostics_params.diagnostics) then M.diagnostics[diagnostics_params.uri] = nil return end M.diagnostics[diagnostics_params.uri] = diagnostics_params.diagnostics end function M._on_cursor_moved_for_publish_diagnostics(wait) vim.validate{wait={wait,'n'}} local function _build_diagnostics_messages(diagnostics) local messages = {} for _, diagnostic in ipairs(diagnostics) do local message = "" local severity = putil.convert_severity(diagnostic.severity) if severity then message = string.format("[%s]", severity) end message = string.format("%s %s", message, diagnostic.message) if diagnostic.code then message = string.format("%s [%s]", message, diagnostic.code) end if diagnostic.source then message = string.format("%s [%s]", message, diagnostic.source) end table.insert(messages, message) end return messages end local function _echo_diagnostic_messages() local current_fname = vim.uri_from_bufnr(vim.fn.bufnr) local diagnostics = M.diagnostics[current_fname] if not diagnostics then return end local line = api.nvim_win_get_cursor(0)[0] local target_diagnostics = {} for _, diagnostic in ipairs(diagnostics) do if putil.is_line_in_range(diagnostic.range, line) then table.insert(target_diagnostics, diagnostic) end end if vim.tbl_isempty(target_diagnostics) then return end local messages = _build_diagnostics_messages(target_diagnostics) local echo_message = "" for _, message in ipairs(messages) do if echo_message ~= "" then echo_message = echo_message.."\n" end echo_message = echo_message..message end api.nvim_command("echo '"..echo_message.."'") end local function _show_publish_diagnostics_floating_window() local function _open_floating_window(contents) local width local height = #contents width = 0 for i, line in ipairs(contents) do line = vim.fn.trim(line) local line_width = vim.fn.strdisplaywidth(line) width = math.max(line_width, width) contents[i] = line end -- Add right padding of 1 each. width = width + 1 local floating_bufnr = api.nvim_create_buf(false, true) local float_option = lsp.util.make_floating_popup_options(width, height) local floating_winnr = vim.api.nvim_open_win(floating_bufnr, false, float_option) api.nvim_buf_set_lines(floating_bufnr, 0, -1, true, contents) api.nvim_buf_set_option(floating_bufnr, 'modifiable', false) lsp.util.close_preview_autocmd({"CursorMoved", "CursorMovedI", "VimResized", "BufHidden", "BufLeave"}, floating_winnr) return floating_bufnr, floating_winnr end local current_fname = vim.uri_from_bufnr(vim.fn.bufnr) local diagnostics = M.diagnostics[current_fname] if not diagnostics then return end local pos = api.nvim_win_get_cursor(0) local target_diagnostics = {} for _, diagnostic in ipairs(diagnostics) do if putil.is_possition_in_range(diagnostic.range, pos) then table.insert(target_diagnostics, diagnostic) end end if vim.tbl_isempty(target_diagnostics) then return end local messages = _build_diagnostics_messages(target_diagnostics) _open_floating_window(messages) end if vim.g["lsp_publish_diagnostics_display_method"] == "echo" then _echo_diagnostic_messages() elseif vim.g["lsp_publish_diagnostics_display_method"] == "float" then if M.diagnostics_debounce_timer ~= nil then if uv.is_active(M.diagnostics_debounce_timer) then putil.clear_timeout(M.diagnostics_debounce_timer) end M.diagnostics_debounce_timer = nil end M.diagnostics_debounce_timer = putil.set_timeout(wait, vim.schedule_wrap(_show_publish_diagnostics_floating_window)) end end return M
function Shadikith_Charge(Unit, event, miscUnit, misc) Unit:FullCastSpellOnTarget(38461, Unit:GetRandomPlayer()) end function Shadikith_Sonic_Burst(Unit, event, miscUnit, misc) Unit:FullCastSpellOnTarget(39052, Unit:GetClosestPlayer()) end function Shadikith_Wing_Buffet(Unit, event, miscUnit, misc) Unit:FullCastSpellOnTarget(38110, Unit:GetClosestPlayer()) end function Shadikith_Knockback(Unit, event, miscUnit, misc) Unit:FullCastSpellOnTarget(37966, Unit:GetRandomPlayer()) end function Shadikith(Unit, event, miscUnit, misc) Unit:RegisterEvent("Shadikith_Charge", 10000, 0) Unit:RegisterEvent("Shadikith_Sonic_Burst", 17000, 0) Unit:RegisterEvent("Shadikith_Wing_Buffet", 27000, 0) Unit:RegisterEvent("Shadikith_Knockback", 33000, 0) end RegisterUnitEvent(16180, 1, "Shadikith")
local Maths = CLRPackage("OpenNefia.Core", "OpenNefia.Core.Maths") local Rendering = CLRPackage("OpenNefia.Core", "OpenNefia.Core.Rendering") local Drawing = CLRPackage("OpenNefia.Core", "OpenNefia.Core.UI.Wisp.Drawing") local Styling = CLRPackage("OpenNefia.Core", "OpenNefia.Core.UI.Wisp.Styling") local Color = Maths.Color local Thickness = Maths.Thickness local FontSpec = Rendering.FontSpec local StyleBoxFlat = Drawing.StyleBoxFlat local Utilities = Styling.StylesheetUtilities local function capitalize(str) return (str:gsub("^%l", string.upper)) end local function setProps(result, t) if type(t) == "table" then for k, v in pairs(t) do k = capitalize(k) if type(v) == "string" then if v:match("^#") then v = Color.FromXaml(v) end end result[k] = v end end end local function styleBoxFlat(t) local result = StyleBoxFlat() setProps(result, t) return result end local function asset(id) return Utilities.GetAssetInstance(id) end local function margin(x, y, z, w) if y == nil then return Thickness(x) elseif z == nil then return Thickness(x, y) else return Thickness(x, y, z, w) end end local function font(t) local result = FontSpec(t.size, t.smallSize or t.size) t.size = nil t.smallSize = nil setProps(result, t) return result end local function font(t) local result = FontSpec(t.size, t.smallSize or t.size) t.size = nil t.smallSize = nil setProps(result, t) return result end ---------------------------------------- -- Fallback ---------------------------------------- defaultFont = font({ size = 14, smallSize = 14, }) defaultStyleBox = styleBoxFlat({ backgroundColor = "#202020" }) _({ font = defaultFont, fontColor = "#FFFFFF", panel = defaultStyleBox, styleBox = defaultStyleBox, texture = asset("Elona.AutoTurnIcon"), modulateSelf = "#FFFFFF", }) defaultGrabberSize = 10 HScrollBar({ grabber = styleBoxFlat({ backgroundColor = "#80808080", contentMarginTopOverride = defaultGrabberSize, }), rule(":hover")({ grabber = styleBoxFlat({ backgroundColor = "#A0A0A080", contentMarginTopOverride = defaultGrabberSize, }), }), rule(":grabbed")({ grabber = styleBoxFlat({ backgroundColor = "#C0C0C080", contentMarginTopOverride = defaultGrabberSize, }), }), }) VScrollBar({ grabber = styleBoxFlat({ backgroundColor = "#80808080", contentMarginLeftOverride = defaultGrabberSize, contentMarginTopOverride = defaultGrabberSize, }), rule(":hover")({ grabber = styleBoxFlat({ backgroundColor = "#A0A0A080", contentMarginLeftOverride = defaultGrabberSize, contentMarginTopOverride = defaultGrabberSize, }), }), rule(":grabbed")({ grabber = styleBoxFlat({ backgroundColor = "#C0C0C080", contentMarginLeftOverride = defaultGrabberSize, contentMarginTopOverride = defaultGrabberSize, }), }), }) ---------------------------------------- -- Custom ---------------------------------------- _({ rule(".windowPanel")({ panel = styleBoxFlat({ backgroundColor = "#202040D0", borderColor = "#80808080", borderThickness = margin(1), }), }), }) PanelContainer(".windowHeader")({ panel = styleBoxFlat({ backgroundColor = "#444488", }), }) PanelContainer(".windowHeaderAlert")({ panel = styleBoxFlat({ backgroundColor = "#884444" }), }) font10 = font({ size = 10, smallSize = 10, }) font12 = font({ size = 12, smallSize = 12, }) fontBold12 = font({ size = 12, smallSize = 12, -- style = { "Bold" } }) colorGold = "#F8ABAE" Label(".windowTitle")({ fontColor = "#FFFFFF", font = fontBold12, }) Label(".windowTitleAlert")({ fontColor = colorGold, font = fontBold12, }) Button({ styleBox = styleBoxFlat({ borderColor = "#446666", backgroundColor = "#447777", borderThickness = margin(2), }), rule(":hover")({ styleBox = styleBoxFlat({ borderColor = "#446666", backgroundColor = "#44AAAA", borderThickness = margin(2), }), }), rule(":pressed")({ styleBox = styleBoxFlat({ borderColor = "#886666", backgroundColor = "#AAAA44", borderThickness = margin(2), }), }), rule(":disabled")({ styleBox = styleBoxFlat({ borderColor = "#444444", backgroundColor = "#666666", borderThickness = margin(2), }), }), }) CheckBox({ styleBox = styleBoxFlat({ backgroundColor = "#00000000", }), }) TextureButton(".windowCloseButton")({ texture = asset("Elona.AutoTurnIcon"), modulateSelf = "#4B596A", }) TextureRect(".checkBox")({ texture = asset("Core.WispCheckboxUnchecked"), rule(".checkBoxChecked")({ texture = asset("Core.WispCheckboxChecked"), }), }) PanelContainer(".designerBackground")({ styleBox = styleBoxFlat({ backgroundColor = "#B0C4DE", }), }) PanelContainer(".designerToolbar")({ styleBox = styleBoxFlat({ backgroundColor = "#223333", }), }) Label(".pointerText")({ fontColor = "#00AAAA", font = font10, }) MeasurementPointer({ rulerColor = "#A0A0A040", }) --[[ ItemList { background = "#334455", itemBackground = "#AABB88", disabledItemBackground = "#888888", selectedItemBackground = "#88BBAA", rule ".transparentItemList" { background = "#FFFFFF00", itemBackground = "#FFFFFF00", disabledItemBackground = "#FFFFFF00", selectedItemBackground = "#FFFFFF00", }, } --]] -- local inspect = require "Lua.Core.Thirdparty.inspect" -- print(inspect(_DeclaredRules))
--[[ LICENSE: BSD Author: CandyMi[https://github.com/candymi] ]] local tcp = require "internal.TCP" local crypt = require "crypt" local hexencode = crypt.hexencode local sys = require "sys" local now = sys.now local new_tab = sys.new_tab local hostname = sys.hostname local null = null local type = type local pcall = pcall local error = error local tostring = tostring local strpack = string.pack local strunpack = string.unpack local strchar = string.char local strbyte = string.byte local fmt = string.format local strgsub = string.gsub local strsub = string.sub local toint = math.tointeger local os_date = os.date local tabinsert = table.insert local tabconcat = table.concat -- TDS公共头部类型 local PTYPE_QUERY = 0x01 -- 回应包类型 local PTYPE_RESPONSE = 0x04 -- 回应包类型 local PTYPE_LOGIN = 0x10 -- TDS-7.0 登录类型 -- TDS控制TOKEN类型 local ORDER_TOKEN = 0xA9 local ERROR_TOKEN = 0xAA local INFO_TOKEN = 0xAB local ACK_TOKEN = 0xAD local ENVCHANGE_TOKEN = 0xE3 local COLMETADATA_TOKEN = 0x81 local COLMETAROW_TOKEN = 0xD1 local COLMETAROW_TOKEN = 0xD1 local DONE_TOKEN = 0xFD -- TDS ENVCHANGE 字段表 local TDS_ENV = { "Database", "Language", "Character_set", "Packet_size", "Unicode_sorting_local_id", "Unicode_sorting_comparison_flags", "SQL_Collation", "Begin_Transaction (described in [MSDN-BEGIN])", "Commit_Transaction (described in [MSDN-COMMIT])", "Rollback_Transaction", "Enlist_DTC_Transaction", "Defect_Transaction", "Real_Time_Log_Shipping", "Promote_Transaction", "Transaction_Manager_Address", "Transaction_ended", "Acknowledgement", "BackInfo", "Routing", } -- TDS字符集之间的转换兼容函数 -- 引入libiconv库实现 USC-2LE 与 UTF8 之间的转换 local liconv, liconv_to, liconv_from local ok, liconv_info = pcall(require, "liconv") if ok then liconv = liconv_info liconv_to, liconv_from = liconv.to, liconv.from end local function iconv_to (str, opcode) return liconv and liconv_to(opcode, str) or str end local function iconv_from (str, opcode) return liconv and liconv_from(opcode, str) or str end local function to_usc2le (s) return strpack("z", s) end local function from_usc2le (s) local tab = new_tab(#s / 2, 0) for index = 1, #s, 2 do tab[#tab+1] = strchar(strbyte(s, index)) end return tabconcat(tab) end local function TO_UCS2LE (s) return liconv and iconv_to(s, "UCS-2LE") or strgsub(s, ".", to_usc2le) end local function FROM_UCS2LE(s) return liconv and iconv_from(s, "UCS-2LE") or from_usc2le(s) end --[[ 加密算法原理: 1. 对每个字符同时进行高/低位位移(4位); 2. 将位移后的结果高位与低位进行"或"运算; 3. 再将之后的运算结果异或0xA5(10100101); 4. 最终的结果按位"与"0xFF取范围0~255; C 函数原型: uint8_t* tds7_crypt_pass(const uint8_t *clear_pass, int len, uint8_t *crypt_pass) { for (int i = 0; i < len; i++) crypt_pass[i] = ((clear_pass[i] << 4) | (clear_pass[i] >> 4)) ^ 0xA5; return crypt_pass; } --]] local function password_encrypt(password) return strgsub(password, ".", function (ch) return strchar(((strbyte(ch) << 4 | strbyte(ch) >> 4) ~ 0xA5 ) & 0xff) end) end -- TDS数据类型(N的位置不固定是因为官方文档命名的问题) local TYPE_BITN = 0x68 -- (104) BITN local TYPE_BIT = 0x32 -- (50) BIT local TYPE_INTN = 0x26 -- (38) INTN local TYPE_INT1 = 0x30 -- (48) INT1 local TYPE_INT2 = 0x34 -- (54) INT2 local TYPE_INT4 = 0x38 -- (56) INT4 local TYPE_INT8 = 0x7F -- (127) INT8 local TYPE_FLOAT32 = 0x3B -- (59) Float32 local TYPE_FLOAT64 = 0x3E -- (62) Float64 local TYPE_DECIMAL = 0x6A -- (106) Decimal local TYPE_NUMERIC = 0x6C -- (108) Numeric local TYPE_FLOATN = 0x6D -- (109) float32/64 local TYPE_MONEY8 = 0x3C -- (60) Money local TYPE_MONEY4 = 0x7A -- (122) SmallMoney local TYPE_MONEYN = 0x6E -- (110) NMoney local TYPE_BIGBIN = 0xAD -- (173) NBINARY local TYPE_CHAR = 0xAF -- (175) Char local TYPE_VARCHAR = 0xA7 -- (167) VarChar local TYPE_NVARCHAR = 0xE7 -- (231) NVarChar local TYPE_NCHAR = 0xEF -- (239) NChar local TYPE_TEXT = 0x23 -- (35) TEXT local TYPE_NTEXT = 0x63 -- (99) NTEXT local TYPE_DATETIMEN = 0x6F -- (111) DATETIME local TYPE_GEO = 0x22 -- (34) GEO local TYPE_GUID = 0x24 -- (36) GUID local TYPE_HIER = 0xA5 -- (165) Hierarchyid -- TDS Field转换方法 local FTYPE_TAB = {} FTYPE_TAB[TYPE_HIER] = function (packet, pos) return pos + 2 end FTYPE_TAB[TYPE_GUID] = function (packet, pos) return pos + 1 end FTYPE_TAB[TYPE_GEO] = function (packet, pos) local large_type_size, table_name_len large_type_size, table_name_len, pos = strunpack("<I4I2", packet, pos) return pos + table_name_len * 2 end FTYPE_TAB[TYPE_BITN] = function (packet, pos) return pos + 1 end FTYPE_TAB[TYPE_BIT] = function (packet, pos) return pos end FTYPE_TAB[TYPE_INTN] = function (packet, pos) return pos + 1 end FTYPE_TAB[TYPE_INT1] = function (packet, pos) return pos end FTYPE_TAB[TYPE_INT2] = function (packet, pos) return pos end FTYPE_TAB[TYPE_INT4] = function (packet, pos) return pos end FTYPE_TAB[TYPE_INT8] = function (packet, pos) return pos end FTYPE_TAB[TYPE_BIGBIN] = function (packet, pos) return pos + 2 end FTYPE_TAB[TYPE_CHAR] = function (packet, pos) -- local large_type_size, collate_codepage, collate_flags, collate_charset_id -- large_type_size, collate_codepage, collate_flags, collate_charset_id, pos = strunpack("<I2I2I2B", packet, pos) -- return pos return pos + 7 end FTYPE_TAB[TYPE_NCHAR] = function (packet, pos) -- local large_type_size, collate_codepage, collate_flags, collate_charset_id -- large_type_size, collate_codepage, collate_flags, collate_charset_id, pos = strunpack("<I2I2I2B", packet, pos) -- return pos return pos + 7 end FTYPE_TAB[TYPE_VARCHAR] = function (packet, pos) -- local large_type_size, collate_codepage, collate_flags, collate_charset_id -- large_type_size, collate_codepage, collate_flags, collate_charset_id, pos = strunpack("<I2I2I2B", packet, pos) -- return pos return pos + 7 end FTYPE_TAB[TYPE_NVARCHAR] = function (packet, pos) -- local large_type_size, collate_codepage, collate_flags, collate_charset_id -- large_type_size, collate_codepage, collate_flags, collate_charset_id, pos = strunpack("<I2I2I2B", packet, pos) -- return pos return pos + 7 end FTYPE_TAB[TYPE_TEXT] = function (packet, pos) local large_type_size, collate_codepage, collate_flags, collate_charset_id, table_name_len large_type_size, collate_codepage, collate_flags, collate_charset_id, pos = strunpack("<I4I2I2B", packet, pos) table_name_len, pos = strunpack("<I2", packet, pos) return pos + table_name_len * 2 end FTYPE_TAB[TYPE_NTEXT] = function (packet, pos) local large_type_size, collate_codepage, collate_flags, collate_charset_id, table_name_len large_type_size, collate_codepage, collate_flags, collate_charset_id, pos = strunpack("<I4I2I2B", packet, pos) table_name_len, pos = strunpack("<I2", packet, pos) return pos + table_name_len * 2 end FTYPE_TAB[TYPE_FLOAT32] = function (packet, pos) return pos end FTYPE_TAB[TYPE_FLOAT64] = function (packet, pos) return pos end FTYPE_TAB[TYPE_DECIMAL] = function (packet, pos) local type_size, precision, scale type_size, precision, scale, pos = strunpack("<BBB", packet, pos) return pos, precision, scale end FTYPE_TAB[TYPE_NUMERIC] = function (packet, pos) local type_size, precision, scale type_size, precision, scale, pos = strunpack("<BBB", packet, pos) return pos, precision, scale end FTYPE_TAB[TYPE_FLOATN] = function (packet, pos) return pos + 1 end FTYPE_TAB[TYPE_MONEYN] = function (packet, pos) return pos + 1 end FTYPE_TAB[TYPE_MONEY4] = function (packet, pos) return pos end FTYPE_TAB[TYPE_MONEY8] = function (packet, pos) return pos end FTYPE_TAB[TYPE_DATETIMEN] = function (packet, pos) return pos + 1 end -- TDS Rows内容转换方法 local RTYPE_TAB = {} RTYPE_TAB[TYPE_HIER] = function (packet, pos) local len len, pos = strunpack("<I2", packet, pos) if len == 0xFFFF then return null, pos end return "0x" .. hexencode(strsub(packet, pos, pos + len - 1):reverse()), pos + len end RTYPE_TAB[TYPE_GEO] = function (packet, pos) local len len, pos = strunpack("<B", packet, pos) if len == 0 then return null, pos end pos = pos + len + 8 len, pos = strunpack("<I4", packet, pos) return "0x" .. hexencode(strsub(packet, pos, pos + len - 1):reverse()), pos + len end RTYPE_TAB[TYPE_GUID] = function (packet, pos) local len len, pos = strunpack("<B", packet, pos) if len == 0 then return null, pos end return tabconcat({ fmt("%02X", strunpack("<I4", packet, pos)), fmt("%02X", strunpack("<I2", packet, pos + 4)), fmt("%02X", strunpack("<I2", packet, pos + 6)), fmt("%02X", strunpack(">I2", packet, pos + 8)), fmt("%02X", strunpack(">I6", packet, pos + 10)) }, "-"), pos + 16 end RTYPE_TAB[TYPE_BIT] = function (packet, pos) local value value, pos = strunpack("<B", packet, pos) return value == 1 and true or false, pos end RTYPE_TAB[TYPE_BITN] = function (packet, pos) local len, value len, pos = strunpack("<B", packet, pos) if len == 0 then return null, pos end value, pos = strunpack("<B", packet, pos) return value == 1 and true or false, pos end RTYPE_TAB[TYPE_INTN] = function (packet, pos) local len, value len, pos = strunpack("<B", packet, pos) if len == 1 then value, pos = strunpack("<i1", packet, pos) elseif len == 2 then value, pos = strunpack("<i2", packet, pos) elseif len == 4 then value, pos = strunpack("<i4", packet, pos) elseif len == 8 then value, pos = strunpack("<i8", packet, pos) else return null, pos end return value, pos end RTYPE_TAB[TYPE_INT1] = function (packet, pos) return strunpack("<i1", packet, pos) end RTYPE_TAB[TYPE_INT2] = function (packet, pos) return strunpack("<i2", packet, pos) end RTYPE_TAB[TYPE_INT4] = function (packet, pos) return strunpack("<i4", packet, pos) end RTYPE_TAB[TYPE_INT8] = function (packet, pos) return strunpack("<i8", packet, pos) end RTYPE_TAB[TYPE_BIGBIN] = function (packet, pos) local len len, pos = strunpack("<i2", packet, pos) if len == 0xFFFF then return null, pos end return strsub(packet, pos, pos + len - 1), pos + len end RTYPE_TAB[TYPE_CHAR] = function (packet, pos) local len len, pos = strunpack("<i2", packet, pos) return iconv_from(strsub(packet, pos, pos + len - 1), "GBK"), pos + len end RTYPE_TAB[TYPE_NCHAR] = function (packet, pos) local len len, pos = strunpack("<i2", packet, pos) return iconv_from(strsub(packet, pos, pos + len - 1), "UCS-2LE"), pos + len end RTYPE_TAB[TYPE_VARCHAR] = function (packet, pos) local len len, pos = strunpack("<i2", packet, pos) return iconv_from(strsub(packet, pos, pos + len - 1), "GBK"), pos + len end RTYPE_TAB[TYPE_NVARCHAR] = function (packet, pos) local len len, pos = strunpack("<i2", packet, pos) return iconv_from(strsub(packet, pos, pos + len - 1), "UCS-2LE"), pos + len end RTYPE_TAB[TYPE_TEXT] = function (packet, pos) local ptr_len, text_len ptr_len, pos = strunpack("<B", packet, pos) text_len, pos = strunpack("<I4", packet, pos + ptr_len + 8) return iconv_from(strsub(packet, pos, pos + text_len - 1), "GBK"), pos + text_len end RTYPE_TAB[TYPE_NTEXT] = function (packet, pos) local ptr_len, text_len ptr_len, pos = strunpack("<B", packet, pos) text_len, pos = strunpack("<I4", packet, pos + ptr_len + 8) return iconv_from(strsub(packet, pos, pos + text_len - 1), "UCS-2LE"), pos + text_len end RTYPE_TAB[TYPE_FLOAT32] = function (packet, pos) -- 精度: 小数点后6位 return strunpack("<f", packet, pos) * 1e6 // 1 * 1e-6, pos + 4 end RTYPE_TAB[TYPE_FLOAT64] = function (packet, pos) -- 精度: 小数点后20位 return strunpack("<n", packet, pos) end RTYPE_TAB[TYPE_DECIMAL] = function (packet, pos, precision, scale) local len, sign, value len, pos = strunpack("<B", packet, pos) if len == 0 then return null, pos end sign, value, pos = strunpack("<Bi4", packet, pos) return value * (0.1 ^ scale) * (sign == 0x00 and -1 or 1), pos end RTYPE_TAB[TYPE_NUMERIC] = function (packet, pos, precision, scale) local len, sign, value len, pos = strunpack("<B", packet, pos) if len == 0 then return null, pos end sign, value, pos = strunpack("<Bi4", packet, pos) return value * (0.1 ^ scale) * (sign == 0x00 and -1 or 1), pos end RTYPE_TAB[TYPE_FLOATN] = function (packet, pos) local len, value len, pos = strunpack("<B", packet, pos) if len == 4 then value, pos = strunpack("<f", packet, pos) value = value * 1e3 // 1 * 1e-3 elseif len == 8 then value, pos = strunpack("<n", packet, pos) else return null, pos end return value, pos end RTYPE_TAB[TYPE_MONEYN] = function (packet, pos) local len, value len, pos = strunpack("<B", packet, pos) if len == 4 then value, pos = strunpack("<i4", packet, pos) value = value * (0.1 ^ 4) elseif len == 8 then -- 请不要使用MONEY类型 value, pos = strunpack("<n", packet, pos) else return null, pos end return value, pos end RTYPE_TAB[TYPE_MONEY4] = function (packet, pos) local value value, pos = strunpack("<i4", packet, pos) return value * (0.1 ^ 4), pos end RTYPE_TAB[TYPE_MONEY8] = function (packet, pos) -- 请不要使用MONEY类型 return strunpack("<n", packet, pos) end -- MSSQL要求起始时间必须为1900-1-1, 所以必须用算法求出当前日期的偏移值(这个偏移值必须再 + 343) -- local DATETIME_OFFSET = os_time { year = 1900, month = 1, day = 1, hour = 0, min = 0, sec = 0 } + 343 local DATETIME_OFFSET = -2209017600 RTYPE_TAB[TYPE_DATETIMEN] = function (packet, pos) local len, value len, pos = strunpack("<B", packet, pos) if len == 4 then local v1, v2 v1, v2, pos = strunpack("<I2I2", packet, pos) value = os_date("%F %X", v1 * 86400 + DATETIME_OFFSET + v2 * 60) elseif len == 8 then local v1, v2 v1, v2, pos = strunpack("<I4I4", packet, pos) value = tabconcat {os_date("%F %X", v1 * 86400 + DATETIME_OFFSET + v2 / 300 // 1), fmt(".%03u", ((v2 / 300 * 1e3 - v2 / 300 // 1 * 1e3 ) + 0.5) // 1)} else return null, pos end return value, pos end --[[ 公共协议头部: OPCODE - 包类型(uint8) STATUS - 包状态(uint8) LENGTH - 包长度(uint16) CHANNEL - 此版本未使用, 所以默认为0(uint16) PACKNO - 包序号(uint8) WINDOW - 此版本未使用, 所以默认为0(uint8) --]] local function tds_pack_header(OP_CODE, STATUS, LENGTH, CHANNEL, PACKNO, WINDOW) return strpack(">BBI2I2BB", OP_CODE, STATUS, LENGTH, CHANNEL, PACKNO, WINDOW) end local function tds_unpack_header(packet) return strunpack(">BBI2I2BB", packet) end local function tds_login7( self ) local HOSTNAME = hostname() -- print(HOSTNAME, #HOSTNAME) local APP_NAME = "cfadmin" -- print(APP_NAME, #APP_NAME) local LOCALE = "us_english" -- print(LOCALE, #LOCALE) local SERVER_NAME = self.host local DATABASE = self.database local USERNAME = self.username local PASSWORD = self.password local msg = { -- LOGIN 7 默认头部信息 strpack("<I4", 0x71000001), -- TDS Version (7.1.1) strpack("<I4", self.max_packet_size ), -- Packet Size (32767) strpack(">BBI2", 7, 1, 1), -- Client Version (7.1.1) strpack("<I4", math.random(100000, now() // 1)), -- Client PID (uint32) strpack("<I4", 0), -- Connection ID, Deafult 0 (uint32) strpack("<BB", 0xE0, 0x03), -- Option Flags 1 And 2. (uint8 And uint8) strpack("<B", self.TSQL, 0), -- SQL Type Flags, 0 = DEFAULT SQL, 1 = T-SQL (uint32) strpack("<B", 0), -- Reserved Flags, Deafult 0 (uint32) strpack("<I4", 0xffffff88), -- Time Zone, Deafult 0xffffff88 (uint32) strpack("<I4", 0x00000436), -- Collation, Deafult 0x00000436 (uint32) } -- LOGIN 7 内容偏移值与长度 local position = 86 -- 客户端主机名 msg[#msg+1] = strpack("<I2I2", position, #HOSTNAME) position = position + #HOSTNAME * 2 -- 客户端登录账户 msg[#msg+1] = strpack("<I2I2", position, #USERNAME) position = position + #USERNAME * 2 -- 客户端登录密码 msg[#msg+1] = strpack("<I2I2", position, #PASSWORD) position = position + #PASSWORD * 2 -- 客户端应用名称 msg[#msg+1] = strpack("<I2I2", position, #APP_NAME) position = position + #APP_NAME * 2 -- 客户端服务名称 msg[#msg+1] = strpack("<I2I2", position, #SERVER_NAME) position = position + #SERVER_NAME * 2 -- 客户端远程账户与密码 msg[#msg+1] = strpack("<I2I2", 0, 0) position = position + 0 -- 客户端链接库名称 msg[#msg+1] = strpack("<I2I2", position, 0) position = position + 0 -- 客户端语言名称 msg[#msg+1] = strpack("<I2I2", position, #LOCALE) position = position + #LOCALE * 2 -- 客户端数据库名称 msg[#msg+1] = strpack("<I2I2", position, #DATABASE) position = position + #DATABASE * 2 -- 客户端MAC地址 msg[#msg+1] = strpack("<BBBBBB", 0, 0, 0, 0, 0, 0) -- position = position + 6 -- 客户端认证部分 msg[#msg+1] = strpack("<I2I2", position, 0) position = position + 0 -- 客户端指定DATA位置 msg[#msg+1] = strpack("<I2I2", position, 0) position = position + 0 msg[#msg+1] = TO_UCS2LE(HOSTNAME) msg[#msg+1] = TO_UCS2LE(USERNAME) msg[#msg+1] = password_encrypt(TO_UCS2LE(PASSWORD)) -- TO_UCS2LE(PASSWORD) msg[#msg+1] = TO_UCS2LE(APP_NAME) msg[#msg+1] = TO_UCS2LE(SERVER_NAME) msg[#msg+1] = TO_UCS2LE(LOCALE) msg[#msg+1] = TO_UCS2LE(DATABASE) local message = tabconcat(msg) return tabconcat { tds_pack_header(PTYPE_LOGIN, 0x1, #message + 12, 0, 0, 0), strpack("<I4", #message + 4), message, } end local function tds_read_head (self) return self:read(8) end local function tds_read_body (self, LENGTH) return self:read(LENGTH - 8) end local function tds_get_errorinfo(packet, p) local pkg_len, errorno, state, severity, pos = strunpack("<I2I4BB", packet, p or 2) local msg_len, pos = strunpack("<I2", packet, pos) -- print(pkg_len, errorno, state, severity, msg_len) local error_msg = FROM_UCS2LE(strsub(packet, pos, pos + msg_len * 2 - 1)) local msg_len, pos = strunpack("<B", packet, pos + msg_len * 2) local server_name = FROM_UCS2LE(strsub(packet, pos, pos + msg_len * 2 - 1)) local _, _, pos = strunpack("<BI2", packet, pos + msg_len * 2) return fmt("ERROR: {server_name = \"%s\", errno = \"%u\", errmsg = \"%s\"}", server_name, errorno, error_msg), pos end local function tds_get_meta_data(packet, length, pos) local fields = new_tab(length, 0) for i = 1, length do -- 字段属性 local field_length, user_type, field_flags, field_type, precision, scale user_type, field_flags, field_type, pos = strunpack("<I2I2B", packet, pos) -- print(user_type, field_flags, field_type, pos) local f = FTYPE_TAB[field_type] if type(f) == 'function' then pos, precision, scale = f(packet, pos) else error("Error: Unknown field type [" .. field_type .. "] ") end local field_name = "?field_" .. i .. "?" field_length, pos = strunpack("<B", packet, pos) if field_length > 0 then field_name = FROM_UCS2LE(strsub(packet, pos, pos + field_length * 2 - 1)) pos = pos + field_length * 2 end fields[#fields+1] = { field_name = field_name, field_type = field_type, precision = precision, scale = scale } end return fields, pos end local function tds_get_row_data (packet, pos, fields) -- var_dump(fields) local rows = new_tab(#fields, 0) local value for index = 1, #fields do local field = fields[index] local f = RTYPE_TAB[field.field_type] -- print(pos) if type(f) == 'function' then value, pos = f(packet, pos, field.precision, field.scale) else error("Error: Unknown data type [" .. field.field_type .. "] ") end -- print(field.field_type, value, pos) rows[#rows+1] = value end return rows, pos end local function tds_done_to_tab(tab, status, operation, row_count) -- 这个值应该被忽略 tab["DONE_OPERATION"] = operation -- 是否是最终的数据包 tab["DONE_FINAL"] = status & 0x01 == 0x00 and true or false -- 是否还有其他数据包 tab["DONE_MORE"] = status & 0x01 == 0x01 and true or false -- 是否是一个错误数据包 tab["DONE_ERROR"] = status & 0x01 == 0x01 and true or false -- 是否正在处理一个事务 tab["DONE_TRANSACTION"] = status & 0x04 == 0x04 and true or false -- TODO tab["DONE_COUNT"] = status & 0x10 == 0x10 and row_count or 0 -- TODO tab["DONE_ATTN"] = status & 0x20 == 0x20 and true or false end local function tds_get_done (packet, pos) return strunpack("<I2I2I4", packet, pos) end local function tds_read_response(self, before_packets) local packet = tds_read_head(self) if not packet then self.state = nil return nil, "The server disconnected before receiving the response header." end local OPCODE, STATUS, LENGTH, CHANNEL, PACKNO, WINDOW = tds_unpack_header(packet) if OPCODE ~= PTYPE_RESPONSE then self.state = nil return nil, "A protocol type not supported by TDS-7.0 was received." end local packet = tds_read_body(self, LENGTH) if not packet then self.state = nil return nil, "The server disconnected before receiving the response data." end -- print(LENGTH, #packet) if before_packets then before_packets[#before_packets+1] = packet if STATUS & 0x1 ~= 0x01 then return tds_read_response(self, before_packets) else packet = tabconcat(before_packets) end else if STATUS & 0x1 ~= 0x01 then return tds_read_response(self, { packet }) end end local result = new_tab(32, 8) local pos = 1 local fields, token_type, order, more_result, meta_field while 1 do token_type, pos = strunpack("<B", packet, pos) if token_type == COLMETADATA_TOKEN then local length length, pos = strunpack("<I2", packet, pos) fields, pos = tds_get_meta_data(packet, length, pos) meta_field = true elseif token_type == ERROR_TOKEN then local error_msg error_msg, pos = tds_get_errorinfo(packet, pos) if strunpack("<B", packet, pos) == INFO_TOKEN then local _, len _, len, pos = strunpack("<BI2", packet, pos) pos = pos + len end if strunpack("<B", packet, pos) == DONE_TOKEN then tds_get_done(packet, pos) end return nil, error_msg elseif token_type == COLMETAROW_TOKEN then local rows local len = #fields local tab = new_tab(0, len) rows, pos = tds_get_row_data(packet, pos, fields) for index = 1, #rows do tab[fields[index].field_name] = rows[index] end result[#result+1] = tab elseif token_type == DONE_TOKEN then local status, operation, row_count status, operation, row_count, pos = tds_get_done(packet, pos) if not meta_field then tds_done_to_tab(result, status, operation, row_count) result["order"] = order end meta_field = false -- 设置MORE_RESULT标志位 if not more_result then more_result = new_tab(3, 0) end more_result[#more_result + 1] = result result = new_tab(32, 8) -- 如果后面还有数据, 则需要改变返回结构 -- print(status & 0x01) if status & 0x01 ~= 0x01 then result = more_result or result -- 如果只有一条数据, 就直接返回那条数据结构 if #result == 1 then result = result[1] end break end elseif token_type == ORDER_TOKEN then local token_len, token_name_index token_len, token_name_index, pos = strunpack("<I2I2", packet, pos) local field = fields[token_name_index] order = { token_len = token_len, token_name = field and field.field_name } -- var_dump(order) end end return result end --[[ TDS 7.1.1支持2种查询格式 1. TDS Header + Raw SQL 2. TDS Header + Data Stream headers + Raw SQL --]] local function tds_query_and_response (self, sql) -- 此处为格式 1 -- local tds_data = TO_UCS2LE(sql) -- 此处为格式 2 local tds_data = strpack("<I4I4I2I4I4I4", 22, 18, 2, 0, 0, 1) .. TO_UCS2LE(sql) -- 支持分包 if self.max_packet_size >= #tds_data then self:write(tds_pack_header(PTYPE_QUERY, 0x01, #tds_data + 8, 0, 1, 0) .. tds_data) else local fin = 0x00 while 1 do local body = strsub(tds_data, 1, self.max_packet_size) if #tds_data <= self.max_packet_size then fin = 0x01 end self:write(tds_pack_header(PTYPE_QUERY, fin, #body + 8, 0, 1, 0) .. body) if fin == 0x01 then break end tds_data = strsub(tds_data, self.max_packet_size + 1, -1) end end return tds_read_response(self) end local class = require "class" local mssql = class("mssql") function mssql:ctor(opt) self.sock = tcp:new() self.host = opt.host or "localhost" self.port = opt.port or 1433 self.unixdomain = opt.unixdomain self.TSQL = opt.TSQL == 1 and 1 or 0 self.max_packet_size = opt.max_packet_size or 10240 self.database = opt.database or "master" self.username = opt.username or "sa" self.password = opt.password -- self.state = "connected" end function mssql:read( bytes ) local sock = self.sock local buffer = sock:recv(bytes) if not buffer then return end if #buffer == bytes then return buffer end bytes = bytes - #buffer local buffers = {buffer} local sock_read = sock.recv while 1 do buffer = sock_read(sock, bytes) if not buffer then return end bytes = bytes - #buffer tabinsert(buffers, buffer) if bytes == 0 then return tabconcat(buffers) end end end function mssql:write(data) return self.sock:send(data) end function mssql:connect( ... ) if not self.sock then return nil, "Connection failed: please recreate the socket object." end if self.unixdomain then if not self.sock:connect_ex(self.unixdomain) then return nil, "MSSQL Server [" .. tostring(self.unixdomain) .. "] Connect failed." end elseif self.host and self.port then if not self.sock:connect(self.host, self.port) then return nil, "MSSQL Server TCP Connect failed." end else return nil, "MSSQL Server driver Invalid Configure." end -- 发送TDS-7.0登录协议 self:write(tds_login7(self)) local packet = tds_read_head(self) if not packet then return nil, "1. After sending the LOGIN data, the server disconnected." end local OPCODE, STATUS, LENGTH, CHANNEL, PACKNO, WINDOW = tds_unpack_header(packet) if OPCODE ~= PTYPE_RESPONSE then return nil, "A protocol type not supported by TDS-7.0 was received." end local packet = tds_read_body(self, LENGTH) if not packet then return nil, "2. After sending the LOGIN data, the server disconnected." end local sever = new_tab(0, 6) local pos = 1 while 1 do local token_type token_type, pos = strunpack("<B", packet, pos) -- 登录失败 if token_type == ERROR_TOKEN then return nil, tds_get_errorinfo(packet) end if token_type ~= INFO_TOKEN and token_type ~= ENVCHANGE_TOKEN and token_type ~= ACK_TOKEN and token_type ~= DONE_TOKEN then return nil, "Unsupported login response type, please check the MSSQL server version." end if token_type == ENVCHANGE_TOKEN then local len, env_type local new_value, new_len, old_value, old_len, collate_codepage, collate_flags, collate_charset_id len, pos = strunpack("<I2", packet, pos) env_type, pos = strunpack("<B", packet, pos) new_len, pos = strunpack("<B", packet, pos) local type_name = TDS_ENV[env_type] or "Unknown Type" if new_len > 0 then if env_type ~= 0x07 then new_value = FROM_UCS2LE(strsub(packet, pos, pos + new_len * 2 - 1)) pos = pos + new_len * 2 else collate_codepage, collate_flags, collate_charset_id, pos = strunpack("<I2I2B", packet, pos) end end old_len, pos = strunpack("<B", packet, pos) if old_len > 0 then old_value = FROM_UCS2LE(strsub(packet, pos, pos + old_len * 2 - 1)) pos = pos + old_len * 2 end sever[type_name] = { new_value = new_value, old_value = old_value, collate_codepage = collate_codepage, collate_flags = collate_flags, collate_charset_id = collate_charset_id } -- return sever elseif token_type == INFO_TOKEN then local info info, pos = tds_get_errorinfo(packet, pos) elseif token_type == ACK_TOKEN then local len, interface, tds_version, server_name_len, server_name, server_version_max1, server_version_max2, server_version_min len, pos = strunpack("<I2", packet, pos) interface, tds_version, server_name_len, pos = strunpack("<BI4B", packet, pos) -- print(len, interface, tds_version) server_name = FROM_UCS2LE(strsub(packet, pos, pos + server_name_len * 2 - 1)) pos = pos + server_name_len * 2 server_version_max1, server_version_max2, server_version_min, pos = strunpack("<BBI2", packet, pos) -- print(server_version_max1, server_version_max2, server_version_min, pos) sever["server_name"] = server_name sever["server_version"] = fmt("%u.%u.%u", server_version_max1, server_version_max2, server_version_min) -- return sever elseif token_type == DONE_TOKEN then local status, operation, count status, operation, count = strunpack("<I2I2I4", packet, pos) sever["status"] = status sever["operation"] = operation sever["row_count"] = count break end -- var_dump(sever) end -- var_dump(sever) self.max_packet_size = (sever.Packet_size and toint(sever.Packet_size.new_value) or toint(self.max_packet_size)) - 8 self.sever = sever self.state = "connected" return true end function mssql:query (sql) if type(sql) ~= 'string' or sql == '' then return nil, "Fatal error: invalid SQL statement or parameter." end return tds_query_and_response(self, sql) end local escape_map = { ['\0'] = "\\0", ['\b'] = "\\b", ['\n'] = "\\n", ['\r'] = "\\r", ['\t'] = "\\t", ['\26'] = "\\Z", ['\\'] = "\\\\", ["'"] = "\\'", ['"'] = '\\"', } function mssql.quote_to_str (sql) return fmt("%s", string.gsub(sql, "[\0\b\n\r\t\26\\\'\"]", escape_map)) end function mssql:set_timeout(timeout) if self.sock and tonumber(timeout) then self.sock._timeout = timeout end end function mssql:close () if self.sock then self.sock:close() self.sock = nil end end return mssql
-- ZUI - Zethirium User Interface Library local zui = { manager = require( "lib.zethirium.zui.manager" ), -- container = require( "lib.zethirium.zui.container" ), -- panel = require( "lib.zethirium.zui.panel" ), -- text = require( "lib.zethirium.zui.text" ), -- button = require( "lib.zethirium.zui.button" ), -- textbutton = require( "lib.zethirium.zui.textbutton" ), -- iconbutton = require( "lib.zethirium.zui.iconbutton" ), } function zui:add( obj ) self.manager:add( obj ) end function zui:remove( obj ) self.manager:remove( obj ) end function zui:update( dt ) self.manager:update( dt ) end function zui:draw( ) self.manager:draw() end local function test( ) zui:useAtlas( "ui" ) local frameIdPrefix = "btn-play--" local frameIdSuffixes = { "normal", "hover" } local btn = zui:newButton( frameIdPrefix, frameIdSuffixes ) :name( "play" ) -- set the humanId property of the button :frame( "normal" ) -- select the "btn-play--normal" atlas frame to represent the button :pivot( 0.5, 0.5 ) -- set the button pivot point to the button's center :anchor( "left", 10 ) -- anchor the left edge of the button to 10 pixels from the left edge of the screen :move( 120, 100 ) -- move the button 120 pixels to the right and 100 pixels down :on( "over", function ( button ) button:frame( "hover" ) end ) -- handle mouse over :on( "out", function ( button ) button:frame( "normal" ) end ) -- handle mouse out :on( "click", function ( button ) print( button.humanId .. " clicked" ) end ) -- handle mouse click zui:add( btn ) end function zui:newContainer( x, y ) end function zui:newPanel( x, y, backgroundImage, backgroundQuad ) end function zui:newText( text, x, y, font, alignment ) end function zui:newButton( x, y, normalImage, hoverState ) end function zui:newTextButton( x, y, normalImage, hoverState ) end function zui:newIconButton( x, y, normalImage, hoverState ) end return zui -- zui.manager -- UI Manager System -- iterates through all ui objects, updating and drawing as necessary -- zui.container -- Hierarchial Container. children are drawn relative to the container -- zui.panel -- serves as a container with a background image -- zui.text -- static/dynamic text display -- zui.button -- clickable image with hover state image -- zui.textbutton -- button with centered text label -- zui.iconbutton -- button with centered icon image
_ENV=namespace "game" using_namespace "luaClass" using_namespace "container" ---@class Time ---@field public day number ---@field public hour number class("Time"){ CLASS_DEBUG(false) } function Time:Time(day,hour) self.day=day self.hour=hour end local tiangan={ ["甲"]=1, ["乙"]=2, ["丙"]=3, ["丁"]=4, ["戊"]=5, ["己"]=6, ["庚"]=7, ["辛"]=8, ["壬"]=9, ["癸"]=10, } local dizhi={ ["子"]=1, ["丑"]=2, ["寅"]=3, ["卯"]=4, ["辰"]=5, ["巳"]=6, ["午"]=7, ["未"]=8, ["申"]=9, ["酉"]=10, ["戌"]=11, ["亥"]=12, } local numTiangan={} for key,num in pairs(tiangan) do numTiangan[num]=key end local numDizhi={} for key,num in pairs(dizhi) do numDizhi[num]=key end local function year2Stirng(year) local r=math.fmod(year,10) r=r==0 and 10 or r local gan=numTiangan[r] local r2=math.fmod(year,12) r2=r2==0 and 12 or r local zhi=numDizhi[r2] return gan,zhi end local function mouth2String(year_gan_num,mouth) -- body local mouth_gan_num=year_gan_num*2+mouth local num=math.fmod(mouth_gan_num,10) num=num==0 and 10 or num local mouth_gan=numTiangan[num] mouth=mouth+2 mouth=math.fmod(mouth,12) mouth=mouth==0 and 12 or mouth local mouth_zhi=numDizhi[mouth] return mouth_gan,mouth_zhi end local function day2Stirng(day) day=math.fmod(day,60) day=day==0 and 60 or day local r=math.fmod(day,10) r=r==0 and 10 or r local gan=numTiangan[r] local r2=math.fmod(day,12) r2=r2==0 and 12 or r local zhi=numDizhi[r2] return gan,zhi end local function hour2String(hour) return numDizhi[hour] or "空" end function Time:toString() local year=math.ceil(self.day/360) local mouth=math.ceil(math.ceil(self.day/30)/12) local year_gan,year_zhi=year2Stirng(year) local mouth_gan,mouth_zhi=mouth2String(tiangan[ year_gan],mouth) local day_gan,day_zhi=day2Stirng(self.day) return "江湖".. year_gan..year_zhi.."年" ..mouth_gan..mouth_zhi.."月" ..day_gan..day_zhi.."日" ..hour2String(self.hour).."时" end function Time:register(time,luaf) if self.eventArray==nil then self.eventArray=set() end local alltime=self.day*12+self.hour+time.day*12+time.hour self.eventArray:insert({time=alltime,callBack=luaf}) end function Time:addTime(time) self.day=self.day+time.day self.hour=self.hour+time.hour local day=math.floor(self.hour/12) self.hour=self.hour-day*12 if self.hour==0 then self.hour=12 day=day-1 end self.day=self.day+day if self.eventArray then local alltime=self.day*12+self.hour local delArray=array() --不要在自己循环的时候删除自己的东西 for event in self.eventArray:iter() do if alltime>event.time then event.callBack() delArray:push_back(event) end end for _,event in delArray:iter() do self.eventArray:del(event) end end end function Time:inTime(timeStr) return numDizhi[self.hour]==timeStr end return Time
-- -- https://github.com/olback/computercraft/blob/master/utils/cat.lua -- local args = { ... } if args[1] == nil then error("No input file specified.") return end if fs.exists(args[1]) then if not fs.isDir(args[1]) then local f = fs.open(args[1], "r") print(f.readAll()) f.close() else error("Cannot open '" .. args[1] .. "'. It's a directory.") end else error("Cannot open '" .. args[1] .. "'. Does it exist?") end
--[[ Copyright 2019 Manticore Games, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. --]] -- Internal custom properties local TARGET = script:GetCustomProperty("Target"):WaitForObject() local SHOW_ON_ZOOM = script:GetCustomProperty("ShowOnZoom") local REVERSE = script:GetCustomProperty("Reverse") local LOCAL_PLAYER = Game.GetLocalPlayer() local handle = nil -- nil UpdateTargetVisibility(player, bool) -- Update TARGET visibility based on the showTarget argument function UpdateTargetVisibility(player, showTarget) if not Object.IsValid(TARGET) and handle then handle:Disconnect() return end if player ~= LOCAL_PLAYER then return end if not SHOW_ON_ZOOM then return end if REVERSE then if showTarget then TARGET.visibility = Visibility.FORCE_OFF else TARGET.visibility = Visibility.INHERIT end else if showTarget then TARGET.visibility = Visibility.INHERIT else TARGET.visibility = Visibility.FORCE_OFF end end end if REVERSE then if SHOW_ON_ZOOM then TARGET.visibility = Visibility.INHERIT end else TARGET.visibility = Visibility.FORCE_OFF end -- Initialize handle = Events.Connect("WeaponZoom", UpdateTargetVisibility)
_G._savedEnv = getfenv() module( "debugging", package.seeall ) local utils = require(GetScriptDirectory() .. "/logic") local gHeroVar = require( GetScriptDirectory().."/global_hero_data" ) local retreatMode = dofile( GetScriptDirectory().."/modes/retreat" ) local last_draw_time = -500 local bot_states = {} local team_states = {} local circles = {} local LINE_HEIGHT = 10 local TITLE_VALUE_DELTA_X = 10 local BOT_STATES_MAX_LINES = 2 local BOT_STATES_X = 1600 local BOT_STATES_Y = 100 local TEAM_STATES_MAX_LINES = 6 local TEAM_STATES_X = 1550 local TEAM_STATES_Y = 400 local function updateBotStates() local listAllies = GetUnitList(UNIT_LIST_ALLIED_HEROES) for _, ally in pairs(listAllies) do if ally:IsBot() and not ally:IsIllusion() and gHeroVar.HasID(ally:GetPlayerID()) then local hMyBot = ally.SelfRef local mode = hMyBot:getCurrentMode() local state = mode:GetName() if state == "laning" then local cLane = hMyBot:getHeroVar("CurLane") state = state .. " Lane: " .. tostring(cLane) .. " Info: " .. hMyBot:getHeroVar("LaningStateInfo") elseif state == "fight" then local target = hMyBot:getHeroVar("Target") if utils.ValidTarget(target) then state = state .. " " .. utils.GetHeroName(target) end elseif state == "roam" then local target = hMyBot:getHeroVar("RoamTarget") if utils.ValidTarget(target) then state = state .. " " .. utils.GetHeroName(target) end elseif state == "retreat" then state = state .. " " .. ally.retreat_desire_debug end SetBotState(hMyBot.Name, 1, state) end end end function draw() if last_draw_time > GameTime() - 0.010 then return end last_draw_time = GameTime() updateBotStates() local y = BOT_STATES_Y for name, v in utils.Spairs(bot_states) do DebugDrawText( BOT_STATES_X, y, name, 255, 0, 0 ) for line,text in pairs(v) do DebugDrawText( BOT_STATES_X + TITLE_VALUE_DELTA_X, y + line * LINE_HEIGHT, text, 255, 0, 0 ) end y = y + (BOT_STATES_MAX_LINES + 1) * LINE_HEIGHT end y = TEAM_STATES_Y for name, v in utils.Spairs(team_states) do DebugDrawText( TEAM_STATES_X, y, name, 255, 0, 0 ) for line,text in pairs(v) do DebugDrawText( TEAM_STATES_X + TITLE_VALUE_DELTA_X, y + line * LINE_HEIGHT, text, 255, 0, 0 ) end y = y + (TEAM_STATES_MAX_LINES + 1) * LINE_HEIGHT end for name, circle in pairs(circles) do DebugDrawCircle( circle.center, circle.radius, circle.r, circle.g, circle.b ) end end function SetBotState(name, line, text) if line < 1 or BOT_STATES_MAX_LINES > 2 then print("SetBotState: line out of bounds!") return end if bot_states[name] == nil then bot_states[name] = {} end bot_states[name][line] = text end function SetTeamState(category, line, text) if line < 1 or line > TEAM_STATES_MAX_LINES then print("SetBotState: line out of bounds!") return end if team_states[category] == nil then team_states[category] = {} end team_states[category][line] = text end function SetCircle(name, center, r, g, b, radius) if radius == nil then radius = 50 end circles[name] = {["center"] = center, ["r"] = r, ["g"] = g, ["b"] = b, ["radius"] = radius} end function DeleteCircle(name) circles[name] = nil end for k,v in pairs( debugging ) do _G._savedEnv[k] = v end
--[[ MIT License Copyright (c) 2019 nasso <nassomails ~ at ~ gmail {dot} com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ]] local cwd = (...):match('(.*lovector).-$') .. "." local PathBuilder = require(cwd .. "pathbuilder") local common = require(cwd .. "svg.common") local renderer = {} function renderer:empty(svg, options) local cx = tonumber(common.get_attr(self, "cx", "0"), 10) local cy = tonumber(common.get_attr(self, "cy", "0"), 10) local r = tonumber(common.get_attr(self, "r", "0"), 10) if r > 0 then local path = PathBuilder(options) path:arc(cx, cy, r, 0, 360) path:close_path() svg.graphics:draw_path(path) end end return renderer
local _={} _[38]={x=27,id=2,y=9,arrangement=0,type=3} _[37]={x=23,id=1,y=7,arrangement=0,type=3} _[36]={x=27,id=0,y=6,arrangement=0,type=3} _[35]={y=7,x=15,id=0} _[34]={y=8,x=0,dest=9,id=3} _[33]={y=7,x=0,dest=9,id=2} _[32]={y=8,x=31,dest=10,id=1} _[31]={y=7,x=31,dest=10,id=0} _[30]={y=0,x=31,target=0,id=3} _[29]={y=0,x=31,target=0,id=2} _[28]={y=0,x=31,target=0,id=1} _[27]={y=0,x=31,target=0,id=0} _[26]={x=31,w=1,y=0,h=1,style=false,id=15} _[25]={x=31,w=1,y=0,h=1,style=false,id=14} _[24]={x=0,w=1,y=9,h=2,style=false,id=13} _[23]={x=0,w=1,y=5,h=2,style=false,id=12} _[22]={x=31,w=1,y=9,h=2,style=false,id=11} _[21]={x=31,w=1,y=5,h=2,style=false,id=10} _[20]={x=23,w=9,y=11,h=1,style=false,id=9} _[19]={x=0,w=8,y=4,h=1,style=false,id=8} _[18]={x=18,w=14,y=4,h=1,style=false,id=7} _[17]={x=0,w=13,y=11,h=1,style=false,id=6} _[16]={x=22,w=1,y=11,h=5,style=false,id=5} _[15]={x=8,w=1,y=0,h=5,style=false,id=4} _[14]={x=13,w=9,y=13,h=1,style=false,id=3} _[13]={x=9,w=9,y=2,h=1,style=false,id=2} _[12]={x=17,w=1,y=3,h=8,style=false,id=1} _[11]={x=13,w=1,y=5,h=8,style=false,id=0} _[10]={y=7,x=8,id=3} _[9]={y=7,x=3,id=2} _[8]={y=9,x=6,id=1} _[7]={y=6,x=6,id=0} _[6]={_[36],_[37],_[38]} _[5]={_[35]} _[4]={_[31],_[32],_[33],_[34]} _[3]={_[27],_[28],_[29],_[30]} _[2]={_[11],_[12],_[13],_[14],_[15],_[16],_[17],_[18],_[19],_[20],_[21],_[22],_[23],_[24],_[25],_[26]} _[1]={_[7],_[8],_[9],_[10]} return {spawners=_[1],walls=_[2],keys=_[3],exits=_[4],starts=_[5],treasures=_[6]}
-- load all otui files, order doesn't matter local configName = modules.game_bot.contentsPanel.config:getCurrentOption().text local configFiles = g_resources.listDirectoryFiles("/bot/" .. configName .."/vBot/", true, false) for i, file in ipairs(configFiles) do local ext = file:split(".") if ext[#ext]:lower() == "ui" or ext[#ext]:lower() == "otui" then g_ui.importStyle(file) end end local function loadScript(name) return dofile("/vBot/" .. name .. ".lua") end -- here you can set manually order of scripts -- libraries should be loaded first local luaFiles = { "main", "vlib", "new_cavebot_lib", "configs", -- do not change this and above "extras", "playerlist", "BotServer", "alarms", "Conditions", "pushmax", "combo", "HealBot", "Sio", "AttackBot", -- last of major modules "ingame_editor", "items_management", "quiver_manager", "tools", "antiRs", "cavebot", "depot_withdraw", "eat_food", "equip", "exeta", "info", "items", "jewellery_equipper", "spy_level", "supplies" } for i, file in ipairs(luaFiles) do loadScript(file) end setDefaultTab("Main") UI.Separator() UI.Label("Private Scripts:") UI.Separator()
function __TS__NumberIsNaN(value) return value ~= value end
local skynet = require "local_skynet" local netpack = require "netpack" local socketdriver = require "socketdriver" local Utils = require "lualib.utils" local Debug = require "lualib.debug" local handlecon = import "lualib/connection" local socket -- listen socket local queue -- message queue local CMD = setmetatable({}, { __gc = function() netpack.clear(queue) end }) function CMD.open(source, conf) local address = conf.address or "0.0.0.0" local port = assert(conf.port) skynet.error(string.format("====Listen on %s:%d start====", address, port)) socket = socketdriver.listen(address, port) socketdriver.start(socket) skynet.error(string.format("====Listen on %s:%d %d end====", address, port,socket)) end function CMD.close() assert(socket) socketdriver.close(socket) end function CMD.loginsuc(source, fd, mArgs) local conn = handlecon.GetConnection(fd) if not conn then print("login error:no conn",fd,Utils.table_str(mArgs)) return end if conn.m_Agent then print("login error:re login",fd,Utils.table_str(mArgs)) return end conn:loginsuc(mArgs.agent, mArgs.pid) skynet.send(conn.m_Agent, "lua", "start", mArgs.pid, mArgs) print("login suc",fd,Utils.table_str(mArgs)) end local MSG = {} local function dispatch_msg(fd, msg, sz) local conn = handlecon.GetConnection(fd) if not conn then return end if conn.m_Agent then skynet.send(conn.m_Agent, "lua", "Unpack", conn.m_Pid, msg, sz) else skynet.send("GAMELOGIN", "lua", "UpackData", fd, msg, sz) end end MSG.data = dispatch_msg local function dispatch_queue() local fd, msg, sz = netpack.pop(queue) if fd then -- may dispatch even the handler.message blocked -- If the handler.message never block, the queue should be empty, so only fork once and then exit. skynet.fork(dispatch_queue) dispatch_msg(fd, msg, sz) for fd, msg, sz in netpack.pop, queue do dispatch_msg(fd, msg, sz) end end end MSG.more = dispatch_queue function MSG.open(fd, msg) socketdriver.start(fd) socketdriver.nodelay(fd) handlecon.NewConnection(fd) end function MSG.close(fd) handlecon.DelConnection(fd) end function MSG.error(fd, msg) handlecon.DelConnection(fd) end skynet.register_protocol { name = "socket", id = skynet.PTYPE_SOCKET, -- PTYPE_SOCKET = 6 unpack = function ( msg, sz ) return netpack.filter( queue, msg, sz) end, dispatch = function (_, _, q, type, ...) queue = q if type then MSG[type](...) end end } skynet.start(function() AddTimer(5*60*100, function () handlecon.CheckConnections() end, "CheckConnections") skynet.dispatch("lua", function (_, address, cmd, ...) local f = CMD[cmd] if f then skynet.ret(skynet.pack(f(address, ...))) end end) skynet.register("GAMEGATE") Debug.print("====service GAMEGATE start====") end)
local utils = {} local memory = require "util.memory" function utils.dist(x1, y1, x2, y2) return math.sqrt(math.pow(x2 - x1, 2) + math.pow(y2 - y1, 2)) end function utils.ingame() return memory.raw(0x020E) > 0 end function utils.each(table, func) for key,val in pairs(table) do func(key.." = "..tostring(val)..",") end end function utils.eachi(table, func) for idx,val in ipairs(table) do if (val) then func(idx.." "..val) else func(idx) end end end function utils.match(needle, haystack) for i,val in ipairs(haystack) do if (needle == val) then return true end end end function utils.key(needle, haystack) for key,val in pairs(haystack) do if (needle == val) then return key end end end function utils.igt() local secs = memory.raw(0xDA44) local mins = memory.raw(0xDA43) local hours = memory.raw(0xDA41) return secs + mins * 60 + hours * 3600 end function utils.onPokemonSelect(battleMenu) return battleMenu == 8 or battleMenu == 48 or battleMenu == 184 or battleMenu == 224 end return utils
AddCSLuaFile("cl_init.lua") AddCSLuaFile("shared.lua") include("shared.lua") function ENT:Initialize() self:SetModel("models/blues-bar/glass.mdl") self:PhysicsInit( SOLID_VPHYSICS ) self:SetMoveType( MOVETYPE_NONE ) self:SetSolid( SOLID_VPHYSICS ) self:SetUseType(SIMPLE_USE) self.isRunning = false self:SetCollisionGroup(COLLISION_GROUP_WEAPON) local t = {} self:SetIngredients(util.TableToJSON(t)) local phys = self:GetPhysicsObject() if (phys:IsValid()) then phys:Wake() end local liquid = ents.Create("blue_liquid") liquid:SetPos(self:GetPos() + (self:GetAngles():Up() * 5)) liquid:SetParent(self) liquid.glass = self liquid:Spawn() self.liquid = liquid end function ENT:AddDrink(drinkName , amount) local tab = util.JSONToTable(self:GetIngredients() , {}) for i = 1 , amount do table.insert(tab , drinkName) end local drinkAmount = #tab tab = util.TableToJSON(tab) self:SetIngredients(tab) self.liquid:SetGlassIngs(tab) self.liquid:SetLiquidAmount(drinkAmount) end
-------------------------------------------------------------------------------- -------------------------------------------------------------------------------- function widget:GetInfo() return { name = "Depth of Field", desc = "f8 toggles on/off, ctrl+] or [ to change intensity, /dofQuality #", author = "jK, Satirik (shortcuts: BD & Floris)", date = "March, 2013", license = "GNU GPL, v2 or later", layer = -10000, enabled = false } end options = { fadeInOut = 2, -- seconds shortcuts = { toggle = 'f8', intensityIncrease = 'Ctrl+]', intensityDecrease = 'Ctrl+[', }, quality = { name = 'Quality', type = 'number', min = 1, max = 30, step = 1, value = 4, }, intensity = { name = 'Intensity', type = 'number', min = 0.05, max = 5., step = 0.05, value = 1.5, }, focusCurveExp = { name = 'Non linear focused area', type = 'number', min = 1., max = 4., step = 0.1, value = 2, }, focusRangeMultiplier = { name = 'Focus range multiplier', type = 'number', min = 0.1, max = 3.0, step = 0.1, value = 0.2, }, } -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- --hardware capability local canRTT = (gl.RenderToTexture ~= nil) local canCTT = (gl.CopyToTexture ~= nil) local canShader = (gl.CreateShader ~= nil) -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- local GL_DEPTH_BITS = 0x0D56 local GL_DEPTH_COMPONENT = 0x1902 local GL_DEPTH_COMPONENT16 = 0x81A5 local GL_DEPTH_COMPONENT24 = 0x81A6 local GL_DEPTH_COMPONENT32 = 0x81A7 -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- local blurShader local dofShader local screencopy local depthcopy local focusLoc local focusRangeLoc local viewXLoc local viewYLoc local qualityLoc local intensityLoc local focusCurveExpLoc local focusRangeMultiplierLoc local focusPtXLoc local focusPtYLoc local oldvs = 0 local vsx, vsy = widgetHandler:GetViewSizes() function widget:ViewResize(viewSizeX, viewSizeY) vsx, vsy = viewSizeX,viewSizeY if (gl.DeleteTextureFBO) then gl.DeleteTexture(depthcopy) gl.DeleteTextureFBO(blurtex) gl.DeleteTextureFBO(blurtex2) gl.DeleteTexture(screencopy) end depthcopy = gl.CreateTexture(vsx,vsy, { border = false, format = GL_DEPTH_COMPONENT24, min_filter = GL.NEAREST, mag_filter = GL.NEAREST, }) screencopy = gl.CreateTexture(vsx, vsy, { border = false, min_filter = GL.NEAREST, mag_filter = GL.NEAREST, }) if (screencopy == nil) then Spring.Echo("Depth of Field: texture error") widgetHandler:RemoveWidget(self) return false end end function widget:GetConfigData() return { quality = options.quality.value, intensity = options.intensity.value, focusCurveExp = options.focusCurveExp.value, focusRangeMultiplier = options.focusRangeMultiplier.value, } end function widget:SetConfigData(data) --options.quality.value = data.quality or 2. --options.intensity.value = data.intensity or 1. --options.focusCurveExp.value = data.focusCurveExp or 2. --options.focusRangeMultiplier.value = data.focusRangeMultiplier or 1. end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- local function CheckHardware() if (not canCTT) then Spring.Echo("Depth of Field: your hardware is missing the necessary CopyToTexture feature") widgetHandler:RemoveWidget(self) return false end if (not canRTT) then Spring.Echo("Depth of Field: your hardware is missing the necessary RenderToTexture feature") widgetHandler:RemoveWidget(self) return false end if (not canShader) then Spring.Echo("Depth of Field: your hardware does not support shaders") widgetHandler:RemoveWidget(self) return false end return true end -- user controls local deactivated = true function dofToggle(cmd, line, words) deactivated = not deactivated if words[1] then deactivated = words[1] == "0" end if not deactivated then widgetHandler:UpdateCallIn('DrawScreenEffects') Spring.Echo("Depth of Field: on") else widgetHandler:RemoveCallIn('DrawScreenEffects') Spring.Echo("Depth of Field: off") end end function dofIntensity(cmd, line, words) options.intensity.value = tonumber(words[1]) --Spring.Echo("Depth of Field: intensity: "..options.intensity.value) return true end function dofIntensityIncrease() options.intensity.value = options.intensity.value + options.intensity.step if (options.intensity.value > options.intensity.max) then options.intensity.value = options.intensity.max end --Spring.Echo("Depth of Field: intensity: "..options.intensity.value) return true end function dofIntensityDecrease() options.intensity.value = options.intensity.value - options.intensity.step if (options.intensity.value < options.intensity.min) then options.intensity.value = options.intensity.min end --Spring.Echo("Depth of Field: intensity: "..options.intensity.value) return true end function dofQuality(cmd, line, words) options.quality.value = tonumber(words[1]) if (options.quality.value > options.quality.max) then options.quality.value = options.quality.max end --Spring.Echo("Depth of Field: quality changed to: "..options.quality.value) return true end function widget:Initialize() if (not CheckHardware()) then return false end -- register user control commands/keys widgetHandler:AddAction("dofToggle", dofToggle, nil, "t") Spring.SendCommands({"bind "..options.shortcuts.toggle.." dofToggle"}) Spring.SendCommands({"dofToggle 0"}) -- toggle off defaultly widgetHandler:AddAction("dofIntensityIncrease", dofIntensityIncrease, nil, "t") Spring.SendCommands({"bind "..options.shortcuts.intensityIncrease.." dofIntensityIncrease"}) widgetHandler:AddAction("dofIntensityDecrease", dofIntensityDecrease, nil, "t") Spring.SendCommands({"bind "..options.shortcuts.intensityDecrease.." dofIntensityDecrease"}) widgetHandler:AddAction("dofQuality", dofQuality, nil, "t") widgetHandler:AddAction("dofIntensity", dofIntensity, nil, "t") WG['dof'] = {} WG['dof'].getIntensity = function() return options.intensity.value end WG['dof'].setIntensity = function(value) options.intensity.value = value end dofShader = gl.CreateShader({ fragment = [[ uniform sampler2D tex0; uniform sampler2D tex1; uniform sampler2D tex2; uniform float focus; uniform float focusRange; uniform float viewX; uniform float viewY; uniform float quality; uniform float intensity; uniform float focusCurveExp; uniform float focusRangeMultiplier; uniform float focusPtX; uniform float focusPtY; void main(void) { vec2 texCoord = vec2(gl_TextureMatrix[0] * gl_TexCoord[0]); gl_FragColor = vec4(0.0,0.0,0.0,1.0); float focus = texture2D(tex2, vec2(focusPtX,focusPtY)).z; int k,l; float zValue = texture2D(tex2, texCoord).z; float dmix = clamp(abs(focus-zValue)*focusRange*focusRangeMultiplier ,0.0,1.0); if(dmix > 0.05 || focus>zValue) { zValue = 0; for(k = -1; k <= 1; k++){ for(l = -1; l <= 1; l++){ zValue += texture2D(tex2, texCoord + vec2(0.005*k,0.005*l)).z/9.; } } dmix = clamp(abs(focus-zValue)*focusRange*focusRangeMultiplier ,0.0,1.0); } if(focusCurveExp>1.){ dmix = (exp(focusCurveExp*dmix)-1.)/exp(focusCurveExp); } float halfSizeKernel = quality; // quality float dy = (8./halfSizeKernel)*dmix/viewY*intensity; float dx = (8./halfSizeKernel)*dmix/viewX*intensity; float i,j; float sumKernel = 0; for(j = -halfSizeKernel; j <= halfSizeKernel; j++) for(i = -halfSizeKernel; i <= halfSizeKernel; i++){ sumKernel += (halfSizeKernel+1-abs(i)+halfSizeKernel+1-abs(j))/2.; } for(j = -halfSizeKernel; j <= halfSizeKernel; j++) for(i = -halfSizeKernel; i <= halfSizeKernel; i++){ gl_FragColor.rgb+= (halfSizeKernel+1-abs(i)+halfSizeKernel+1-abs(j))/(2*sumKernel)*texture2D(tex0, texCoord + vec2(j*dy,i*dx)).rgb; } //gl_FragColor.rgb = vec3(dmix,dmix,dmix); } ]], uniform = { focus = 0.9955, focusRange = 1./0.0005, }, uniformInt = { tex0 = 0, tex1 = 1, tex2 = 2, } }) Spring.Echo('DoF shaderlog:') Spring.Echo(gl.GetShaderLog()) -- create blurtexture depthcopy = gl.CreateTexture(vsx,vsy, { border = false, format = GL_DEPTH_COMPONENT24, min_filter = GL.NEAREST, mag_filter = GL.NEAREST, }) screencopy = gl.CreateTexture(vsx, vsy, { border = false, min_filter = GL.NEAREST, mag_filter = GL.NEAREST, }) -- debug? if (screencopy == nil) then Spring.Echo("Depth of Field: texture error") widgetHandler:RemoveWidget(self) return false end focusLoc = gl.GetUniformLocation(dofShader,"focus") focusRangeLoc = gl.GetUniformLocation(dofShader,"focusRange") viewXLoc = gl.GetUniformLocation(dofShader,"viewX") viewYLoc = gl.GetUniformLocation(dofShader,"viewY") qualityLoc = gl.GetUniformLocation(dofShader,"quality") intensityLoc = gl.GetUniformLocation(dofShader,"intensity") focusCurveExpLoc = gl.GetUniformLocation(dofShader,"focusCurveExp") focusRangeMultiplierLoc = gl.GetUniformLocation(dofShader,"focusRangeMultiplier") focusRangeMultiplierLoc = gl.GetUniformLocation(dofShader,"focusRangeMultiplier") focusPtXLoc = gl.GetUniformLocation(dofShader,"focusPtX") focusPtYLoc = gl.GetUniformLocation(dofShader,"focusPtY") end function widget:Shutdown() WG['dof'] = nil Spring.SendCommands({"DofEnable 0"}) widgetHandler:RemoveAction("DofEnable", DofEnable) if (gl.DeleteTextureFBO) then gl.DeleteTexture(depthcopy) gl.DeleteTexture(screencopy) gl.DeleteTextureFBO(blurtex) gl.DeleteTextureFBO(blurtex2) end if (gl.DeleteShader) then gl.DeleteShader(blurShader or 0) gl.DeleteShader(dofShader or 0) end end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- function widget:DrawScreenEffects() if deactivated then return end local zfocus = 0.9995 local msx,msy = widgetHandler:GetViewSizes() msx,msy = 0.5*msx,0.5*msy local type,mpos = Spring.TraceScreenRay(msx,msy,true) if (type=="ground") then _,_,zfocus = Spring.WorldToScreenCoords(mpos[1],mpos[2],mpos[3]) end viewX,viewY = gl.GetViewSizes() local mouseX,mouseY = Spring.GetMouseState() local focusRange = 0.8*(1-zfocus) -- + ((1-zfocus)*(1-zfocus)*10) --zfocus = zfocus - zfocus^10000 gl.CopyToTexture(depthcopy, 0, 0, 0, 0, vsx, vsy) gl.CopyToTexture(screencopy, 0, 0, 0, 0, vsx, vsy) gl.Texture(screencopy) gl.UseShader(dofShader) gl.Uniform(focusLoc,zfocus) gl.Uniform(focusRangeLoc,1/focusRange) gl.Uniform(viewXLoc,viewX) gl.Uniform(viewYLoc,viewY) gl.Uniform(qualityLoc,options.quality.value) gl.Uniform(intensityLoc,options.intensity.value) gl.Uniform(focusCurveExpLoc,options.focusCurveExp.value) gl.Uniform(focusRangeMultiplierLoc,options.focusRangeMultiplier.value) gl.Uniform(focusPtXLoc,mouseX/viewX) gl.Uniform(focusPtYLoc,mouseY/viewY) gl.Texture(0,screencopy) gl.Texture(2,depthcopy) gl.TexRect(0,vsy,vsx,0) gl.Texture(0,false) gl.Texture(1,false) gl.Texture(2,false) gl.UseShader(0) end -------------------------------------------------------------------------------- --------------------------------------------------------------------------------
-- require 'struct' local yrk = { scheme = "http", host = "localhost", port = nil, method = "GET", path = "/", headers = {}, body = nil, thread = nil, } struct = {} function struct.pack(format, ...) local stream = {} local vars = {...} local endianness = true for i = 1, format:len() do local opt = format:sub(i, i) if opt == '<' then endianness = true elseif opt == '>' then endianness = false elseif opt:find('[bBhHiIlL]') then local n = opt:find('[hH]') and 2 or opt:find('[iI]') and 4 or opt:find('[lL]') and 8 or 1 local val = tonumber(table.remove(vars, 1)) local bytes = {} for j = 1, n do table.insert(bytes, string.char(val % (2 ^ 8))) val = math.floor(val / (2 ^ 8)) end if not endianness then table.insert(stream, string.reverse(table.concat(bytes))) else table.insert(stream, table.concat(bytes)) end elseif opt:find('[fd]') then local val = tonumber(table.remove(vars, 1)) local sign = 0 if val < 0 then sign = 1 val = -val end local mantissa, exponent = math.frexp(val) if val == 0 then mantissa = 0 exponent = 0 else mantissa = (mantissa * 2 - 1) * math.ldexp(0.5, (opt == 'd') and 53 or 24) exponent = exponent + ((opt == 'd') and 1022 or 126) end local bytes = {} if opt == 'd' then val = mantissa for i = 1, 6 do table.insert(bytes, string.char(math.floor(val) % (2 ^ 8))) val = math.floor(val / (2 ^ 8)) end else table.insert(bytes, string.char(math.floor(mantissa) % (2 ^ 8))) val = math.floor(mantissa / (2 ^ 8)) table.insert(bytes, string.char(math.floor(val) % (2 ^ 8))) val = math.floor(val / (2 ^ 8)) end table.insert(bytes, string.char(math.floor(exponent * ((opt == 'd') and 16 or 128) + val) % (2 ^ 8))) val = math.floor((exponent * ((opt == 'd') and 16 or 128) + val) / (2 ^ 8)) table.insert(bytes, string.char(math.floor(sign * 128 + val) % (2 ^ 8))) val = math.floor((sign * 128 + val) / (2 ^ 8)) if not endianness then table.insert(stream, string.reverse(table.concat(bytes))) else table.insert(stream, table.concat(bytes)) end elseif opt == 's' then table.insert(stream, tostring(table.remove(vars, 1))) table.insert(stream, string.char(0)) elseif opt == 'c' then local n = format:sub(i + 1):match('%d+') local length = tonumber(n) if length > 0 then local str = tostring(table.remove(vars, 1)) if length - str:len() > 0 then str = str .. string.rep(' ', length - str:len()) end table.insert(stream, str:sub(1, length)) end i = i + n:len() end end return table.concat(stream) end function struct.unpack(format, stream) local vars = {} local iterator = 1 local endianness = true for i = 1, format:len() do local opt = format:sub(i, i) if opt == '<' then endianness = true elseif opt == '>' then endianness = false elseif opt:find('[bBhHiIlL]') then local n = opt:find('[hH]') and 2 or opt:find('[iI]') and 4 or opt:find('[lL]') and 8 or 1 local signed = opt:lower() == opt local val = 0 for j = 1, n do local byte = string.byte(stream:sub(iterator, iterator)) if endianness then val = val + byte * (2 ^ ((j - 1) * 8)) else val = val + byte * (2 ^ ((n - j) * 8)) end iterator = iterator + 1 end if signed and val >= 2 ^ (n * 8 - 1) then val = val - 2 ^ (n * 8) end table.insert(vars, val) elseif opt:find('[fd]') then local n = (opt == 'd') and 8 or 4 local x = stream:sub(iterator, iterator + n - 1) iterator = iterator + n if not endianness then x = string.reverse(x) end local sign = 1 local mantissa = string.byte(x, (opt == 'd') and 7 or 3) % ((opt == 'd') and 16 or 128) for i = n - 2, 1, -1 do mantissa = mantissa * (2 ^ 8) + string.byte(x, i) end if string.byte(x, n) > 127 then sign = -1 end local exponent = (string.byte(x, n) % 128) * ((opt == 'd') and 16 or 2) + math.floor(string.byte(x, n - 1) / ((opt == 'd') and 16 or 128)) if exponent == 0 then table.insert(vars, 0.0) else mantissa = (math.ldexp(mantissa, (opt == 'd') and -52 or -23) + 1) * sign table.insert(vars, math.ldexp(mantissa, exponent - ((opt == 'd') and 1023 or 127))) end elseif opt == 's' then local bytes = {} for j = iterator, stream:len() do if stream:sub(j, j) == string.char(0) then break end table.insert(bytes, stream:sub(j, j)) end local str = table.concat(bytes) iterator = iterator + str:len() + 1 table.insert(vars, str) elseif opt == 'c' then local n = format:sub(i + 1):match('%d+') table.insert(vars, stream:sub(iterator, iterator + tonumber(n)-1)) iterator = iterator + tonumber(n) i = i + n:len() end end return unpack(vars) end function hex_dump (str) local len = string.len( str ) local dump = "" local hex = "" local asc = "" for i = 1, len do if 1 == i % 8 then dump = dump .. hex .. asc .. "\n" hex = string.format( "%04x: ", i - 1 ) asc = "" end local ord = string.byte( str, i ) hex = hex .. string.format( "%02x ", ord ) if ord >= 32 and ord <= 126 then asc = asc .. string.char( ord ) else asc = asc .. "." end end return dump .. hex .. string.rep( " ", 8 - len % 8 ) .. asc end function dump(o) if type(o) == 'table' then local s = '{ ' for k,v in pairs(o) do if type(k) ~= 'number' then k = '"'..k..'"' end s = s .. '['..k..'] = ' .. dump(v) .. ',' end return s .. '} ' else return tostring(o) end end function yrk.resolve(host, service) local addrs = yrk.lookup(host, service) for i = #addrs, 1, -1 do if not yrk.connect(addrs[i]) then table.remove(addrs, i) end end yrk.addrs = addrs end function yrk.setup(thread) thread.addr = yrk.addrs[1] if type(setup) == "function" then setup(thread) end end function yrk.init(args) if not yrk.headers["Host"] then local host = yrk.host local port = yrk.port host = host:find(":") and ("[" .. host .. "]") or host host = port and (host .. ":" .. port) or host yrk.headers["Host"] = host end if type(init) == "function" then init(args) end local req = yrk.format() yrk.request = function() return req end end function hex_dump (str) local len = string.len( str ) local dump = "" local hex = "" local asc = "" for i = 1, len do if 1 == i % 8 then dump = dump .. hex .. asc .. "\n" hex = string.format( "%04x: ", i - 1 ) asc = "" end local ord = string.byte( str, i ) hex = hex .. string.format( "%02x ", ord ) if ord >= 32 and ord <= 126 then asc = asc .. string.char( ord ) else asc = asc .. "." end end return dump .. hex .. string.rep( " ", 8 - len % 8 ) .. asc end function yrk.format(method, path, headers, body) local method = method or yrk.method local path = path or yrk.path local headers = headers or yrk.headers local body = body or yrk.body local s = {} if not headers['raw'] then if not headers["Host"] then headers["Host"] = yrk.headers["Host"] end headers["Content-Length"] = body and string.len(body) s[1] = string.format("%s %s HTTP/1.1", method, path) for name, value in pairs(headers) do s[#s+1] = string.format("%s: %s", name, value) end s[#s+1] = "" s[#s+1] = body or "" return table.concat(s, "\r\n") else return body end end return yrk
--[[ Copyright 2019-2020 Manticore Games, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. --]] -- Internal custom properties local API_A = require(script:GetCustomProperty("APIAbility")) local API_SE = require(script:GetCustomProperty("APIStatusEffects")) local API_NPC = require(script:GetCustomProperty("API_NPC")) local API_T = require(script:GetCustomProperty("APITargeting")) local API_RE = require(script:GetCustomProperty("APIReliableEvents")) local COMPONENT_ROOT = script:GetCustomProperty("ComponentRoot"):WaitForObject() local NAMEPLATE_TEMPLATE = script:GetCustomProperty("NameplateTemplate") local STATUS_EFFECT_TEMPLATE = script:GetCustomProperty("StatusEffectTemplate") -- User exposed properties local SHOW_NAMES = COMPONENT_ROOT:GetCustomProperty("ShowNames") local SHOW_HEALTHBARS = COMPONENT_ROOT:GetCustomProperty("ShowHealthbars") local SHOW_ON_SELF = COMPONENT_ROOT:GetCustomProperty("ShowOnSelf") local SHOW_ON_TEAMMATES = COMPONENT_ROOT:GetCustomProperty("ShowOnTeammates") local MAX_DISTANCE_ON_TEAMMATES = COMPONENT_ROOT:GetCustomProperty("MaxDistanceOnTeammates") local SHOW_ON_ENEMIES = COMPONENT_ROOT:GetCustomProperty("ShowOnEnemies") local MAX_DISTANCE_ON_ENEMIES = COMPONENT_ROOT:GetCustomProperty("MaxDistanceOnEnemies") local SHOW_ON_DEAD_PLAYERS = COMPONENT_ROOT:GetCustomProperty("ShowOnDeadPlayers") local SCALE = COMPONENT_ROOT:GetCustomProperty("Scale") local TARGET_SCALE_MULTIPLIER = COMPONENT_ROOT:GetCustomProperty("TargetScaleMultiplier") local SHOW_NUMBERS = COMPONENT_ROOT:GetCustomProperty("ShowNumbers") local ANIMATE_CHANGES = COMPONENT_ROOT:GetCustomProperty("AnimateChanges") local CHANGE_ANIMATION_TIME = COMPONENT_ROOT:GetCustomProperty("ChangeAnimationTime") -- User exposed properties (colors) local FRIENDLY_NAME_COLOR = COMPONENT_ROOT:GetCustomProperty("FriendlyNameColor") local ENEMY_NAME_ASLEEP_COLOR = COMPONENT_ROOT:GetCustomProperty("EnemyNameAsleepColor") local ENEMY_NAME_READY_COLOR = COMPONENT_ROOT:GetCustomProperty("EnemyNameReadyColor") local ENEMY_NAME_COMBAT_COLOR = COMPONENT_ROOT:GetCustomProperty("EnemyNameCombatColor") local ENEMY_NAME_AGGRO_COLOR = COMPONENT_ROOT:GetCustomProperty("EnemyNameAggroColor") local BORDER_COLOR = COMPONENT_ROOT:GetCustomProperty("BorderColor") local BORDER_AGGRO_COLOR = COMPONENT_ROOT:GetCustomProperty("BorderAggroColor") local BACKGROUND_COLOR = COMPONENT_ROOT:GetCustomProperty("BackgroundColor") local FRIENDLY_HEALTH_COLOR = COMPONENT_ROOT:GetCustomProperty("FriendlyHealthColor") local ENEMY_HEALTH_ASLEEP_COLOR = COMPONENT_ROOT:GetCustomProperty("EnemyHealthAsleepColor") local ENEMY_HEALTH_READY_COLOR = COMPONENT_ROOT:GetCustomProperty("EnemyHealthReadyColor") local ENEMY_HEALTH_COMBAT_COLOR = COMPONENT_ROOT:GetCustomProperty("EnemyHealthCombatColor") local DAMAGE_CHANGE_COLOR = COMPONENT_ROOT:GetCustomProperty("DamageChangeColor") local HEAL_CHANGE_COLOR = COMPONENT_ROOT:GetCustomProperty("HealChangeColor") local HEALTH_NUMBER_COLOR = COMPONENT_ROOT:GetCustomProperty("HealthNumberColor") -- Check user properties if MAX_DISTANCE_ON_TEAMMATES < 0.0 then warn("MaxDistanceOnTeammates cannot be negative") MAX_DISTANCE_ON_TEAMMATES = 0.0 end if MAX_DISTANCE_ON_ENEMIES < 0.0 then warn("MaxDistanceOnEnemies cannot be negative") MAX_DISTANCE_ON_ENEMIES = 0.0 end if SCALE <= 0.0 then warn("Scale must be positive") SCALE = 1.0 end if CHANGE_ANIMATION_TIME <= 0.0 then warn("ChangeAnimationTime must be positive") CHANGE_ANIMATION_TIME = 1.0 end --Constants -- In units of scale local BORDER_WIDTH = 0.02 local NAMEPLATE_LAYER_THICKNESS = 0.01 -- To force draw order local HEALTHBAR_WIDTH = 1.5 local HEALTHBAR_HEIGHT = 0.14 local STATUS_EFFECT_X_STEP = nil -- Defined when we spawn a panel and see its size local LOCAL_PLAYER = Game.GetLocalPlayer() -- Variables local nameplates = {} function CreateNameplate(character, data) assert(character:IsA("Player") or data) local nameplateRoot = World.SpawnAsset(NAMEPLATE_TEMPLATE) nameplateRoot.visibility = Visibility.FORCE_OFF nameplates[character] = {} nameplates[character].templateRoot = nameplateRoot nameplates[character].borderPiece = nameplateRoot:GetCustomProperty("BorderPiece"):WaitForObject() nameplates[character].backgroundPiece = nameplateRoot:GetCustomProperty("BackgroundPiece"):WaitForObject() nameplates[character].healthPiece = nameplateRoot:GetCustomProperty("HealthPiece"):WaitForObject() nameplates[character].changePiece = nameplateRoot:GetCustomProperty("ChangePiece"):WaitForObject() nameplates[character].levelBackgroundPiece = nameplateRoot:GetCustomProperty("LevelBackgroundPiece"):WaitForObject() nameplates[character].healthText = nameplateRoot:GetCustomProperty("HealthText"):WaitForObject() nameplates[character].nameText = nameplateRoot:GetCustomProperty("NameText"):WaitForObject() nameplates[character].levelText = nameplateRoot:GetCustomProperty("LevelText"):WaitForObject() -- Cast Bar nameplates[character].castBarGroup = nameplateRoot:GetCustomProperty("CastBarGroup"):WaitForObject() nameplates[character].castBorderPiece = nameplateRoot:GetCustomProperty("CastBorderPiece"):WaitForObject() nameplates[character].castBackgroundPiece = nameplateRoot:GetCustomProperty("CastBackgroundPiece"):WaitForObject() nameplates[character].castProgressPiece = nameplateRoot:GetCustomProperty("CastProgressPiece"):WaitForObject() nameplates[character].castNameText = nameplateRoot:GetCustomProperty("CastNameText"):WaitForObject() nameplates[character].castBarGroup.visibility = Visibility.FORCE_OFF nameplates[character].castBorderPiece:SetScale(Vector3.New(NAMEPLATE_LAYER_THICKNESS, HEALTHBAR_WIDTH + 2.0 * BORDER_WIDTH, HEALTHBAR_HEIGHT + 2.0 * BORDER_WIDTH)) nameplates[character].castBorderPiece:SetPosition(Vector3.New(-3.0 * NAMEPLATE_LAYER_THICKNESS, 0.0, -100.0 * (HEALTHBAR_HEIGHT + BORDER_WIDTH))) nameplates[character].castBorderPiece:SetColor(BORDER_COLOR) nameplates[character].castBackgroundPiece:SetScale(Vector3.New(NAMEPLATE_LAYER_THICKNESS, HEALTHBAR_WIDTH, HEALTHBAR_HEIGHT)) nameplates[character].castBackgroundPiece:SetPosition(Vector3.New(-2.0 * NAMEPLATE_LAYER_THICKNESS, 0.0, -100.0 * (HEALTHBAR_HEIGHT + BORDER_WIDTH))) nameplates[character].castBackgroundPiece:SetColor(BACKGROUND_COLOR) nameplates[character].castNameText:SetPosition(Vector3.New(50.0 * NAMEPLATE_LAYER_THICKNESS, 0.0, -100.0 * (HEALTHBAR_HEIGHT + BORDER_WIDTH))) -- Text must be 50 units ahead as it doesn't have thickness nameplates[character].statusEffectIcons = {} nameplates[character].panel = nameplateRoot:GetCustomProperty("Panel"):WaitForObject() nameplates[character].container = nameplateRoot:GetCustomProperty("Container"):WaitForObject() -- UI parented to a player doesn't display, so we stick them in the nameplate folder nameplates[character].container.parent = COMPONENT_ROOT if not STATUS_EFFECT_X_STEP then STATUS_EFFECT_X_STEP = nameplates[character].panel.width / API_SE.MAX_STATUS_EFFECTS end for i = 1, API_SE.MAX_STATUS_EFFECTS do local iconTemplate = World.SpawnAsset(STATUS_EFFECT_TEMPLATE, {parent = nameplates[character].panel}) iconTemplate.visibility = Visibility.FORCE_OFF iconTemplate.x = STATUS_EFFECT_X_STEP * (i - (API_SE.MAX_STATUS_EFFECTS + 1) / 2) iconTemplate.y = 0 nameplates[character].statusEffectIcons[i] = iconTemplate end -- For animating changes. Each change clobbers the previous state. nameplates[character].lastHealthFraction = 1.0 nameplates[character].lastHealthTime = 0.0 nameplates[character].lastFrameHealthFraction = 1.0 -- Setup static properties if character:IsA("Player") then nameplateRoot:AttachToPlayer(character, "nameplate") elseif data then if data.animatedMesh then data.animatedMesh:AttachCoreObject(nameplateRoot, "root") nameplates[character].animatedMesh = data.animatedMesh -- Bigger enemies need a bigger gap before their nameplate nameplateRoot:SetPosition(Vector3.UP * (data.capsuleHeight * 1.1 / data.animatedMesh:GetWorldScale().z + 20.0)) else nameplateRoot.parent = character nameplateRoot:SetPosition(Vector3.UP * (data.capsuleHeight * 1.1 + 20.0)) end end -- Static properties on pieces nameplates[character].borderPiece:SetScale(Vector3.New(NAMEPLATE_LAYER_THICKNESS, HEALTHBAR_WIDTH + 2.0 * BORDER_WIDTH, HEALTHBAR_HEIGHT + 2.0 * BORDER_WIDTH)) nameplates[character].borderPiece:SetPosition(Vector3.New(-3.0 * NAMEPLATE_LAYER_THICKNESS, 0.0, 0.0)) nameplates[character].borderPiece:SetColor(BORDER_COLOR) nameplates[character].backgroundPiece:SetScale(Vector3.New(NAMEPLATE_LAYER_THICKNESS, HEALTHBAR_WIDTH, HEALTHBAR_HEIGHT)) nameplates[character].backgroundPiece:SetPosition(Vector3.New(-2.0 * NAMEPLATE_LAYER_THICKNESS, 0.0, 0.0)) nameplates[character].backgroundPiece:SetColor(BACKGROUND_COLOR) nameplates[character].levelBackgroundPiece:SetScale(Vector3.New(NAMEPLATE_LAYER_THICKNESS, HEALTHBAR_HEIGHT + 2.0 * BORDER_WIDTH, HEALTHBAR_HEIGHT + 2.0 * BORDER_WIDTH)) nameplates[character].levelBackgroundPiece:SetPosition(Vector3.New(-3.0 * NAMEPLATE_LAYER_THICKNESS, 50.0 * (HEALTHBAR_WIDTH + HEALTHBAR_HEIGHT + 4.0 * BORDER_WIDTH), 0.0)) nameplates[character].levelBackgroundPiece:SetColor(BORDER_COLOR) nameplates[character].healthText:SetPosition(Vector3.New(50.0 * NAMEPLATE_LAYER_THICKNESS, 0.0, 0.0)) -- Text must be 50 units ahead as it doesn't have thickness nameplates[character].healthText:SetColor(HEALTH_NUMBER_COLOR) nameplates[character].levelText:SetPosition(Vector3.New(50.0 * NAMEPLATE_LAYER_THICKNESS, 50.0 * (HEALTHBAR_WIDTH + HEALTHBAR_HEIGHT + 4.0 * BORDER_WIDTH), 0.0)) if character:IsA("Player") then nameplates[character].nameText.text = character.name elseif data then nameplates[character].nameText.text = data.name end nameplates[character].borderPiece.visibility = Visibility.FORCE_OFF nameplates[character].backgroundPiece.visibility = Visibility.FORCE_OFF nameplates[character].healthPiece.visibility = Visibility.FORCE_OFF nameplates[character].changePiece.visibility = Visibility.FORCE_OFF nameplates[character].healthText.visibility = Visibility.FORCE_OFF nameplates[character].nameText.visibility = Visibility.FORCE_OFF if SHOW_HEALTHBARS then nameplates[character].borderPiece.visibility = Visibility.INHERIT nameplates[character].backgroundPiece.visibility = Visibility.INHERIT nameplates[character].healthPiece.visibility = Visibility.INHERIT if ANIMATE_CHANGES then nameplates[character].changePiece.visibility = Visibility.INHERIT end if SHOW_NUMBERS then nameplates[character].healthText.visibility = Visibility.INHERIT end end if SHOW_NAMES then nameplates[character].nameText.visibility = Visibility.INHERIT end end -- nil OnPlayerJoined(Player) -- Creates a nameplate for the local player to see the target player's status function OnPlayerJoined(player) CreateNameplate(player) end -- nil OnPlayerLeft(Player) -- Destroy their nameplate function OnPlayerLeft(player) nameplates[player].container:Destroy() nameplates[player].templateRoot:Destroy() nameplates[player] = nil end function OnNPCCreated(npc, data) CreateNameplate(npc, data) end function OnNPCDestroyed(npc) nameplates[npc].container:Destroy() -- AnimatedMeshes destroy their attachments when destroyed, so we don't need to nameplates[npc] = nil end -- bool IsNameplateVisible(Player) -- Can we see this player's nameplate given team and distance properties? function IsNameplateVisible(character) if not SHOW_ON_DEAD_PLAYERS then if character:IsA("Player") and character.isDead then return false end if not character:IsA("Player") and API_NPC.IsDead(character) then return false end end if character == LOCAL_PLAYER then return SHOW_ON_SELF end -- Special casing this for Boss Fight, all NPCs are enemy -- 0 distance is special, and means we always display them if not character:IsA("Player") or Teams.AreTeamsEnemies(character.team, LOCAL_PLAYER.team) then if SHOW_ON_ENEMIES and not API_NPC.IsAsleep(character) then local distance = (character:GetWorldPosition() - LOCAL_PLAYER:GetWorldPosition()).size if MAX_DISTANCE_ON_ENEMIES == 0.0 or distance <= MAX_DISTANCE_ON_ENEMIES then return true end end else if SHOW_ON_TEAMMATES then local distance = (character:GetWorldPosition() - LOCAL_PLAYER:GetWorldPosition()).size if MAX_DISTANCE_ON_TEAMMATES == 0.0 or distance <= MAX_DISTANCE_ON_TEAMMATES then return true end end end return false end -- nil RotateNameplate(CoreObject) -- Called every frame to make nameplates align with the local view function RotateNameplate(nameplate) local quat = Quaternion.New(LOCAL_PLAYER:GetViewWorldRotation()) quat = quat * Quaternion.New(Vector3.UP, 180.0) nameplate.templateRoot:SetWorldRotation(Rotation.New(quat)) end -- nil OnAbilityInterrupted(player) -- Handle interrupted abilities with proper ui function OnAbilityInterrupted(player) local nameplate = nameplates[player] nameplate.castBarGroup.visibility = Visibility.INHERIT nameplate.castProgressPiece:SetColor(Color.RED) nameplate.castNameText.text = "Cast Interrupted" nameplate.interruptTime = os.clock() end -- nil Tick(float) -- Update dynamic properties (ex. team, health, and health animation) of every nameplate function Tick(deltaTime) local npcData = API_NPC.GetAllNPCData() -- Update all nameplates for character, nameplate in pairs(nameplates) do -- We calculate visibility every frame to handle when teams change local visible = IsNameplateVisible(character) if not visible then nameplate.templateRoot.visibility = Visibility.FORCE_OFF nameplate.container.visibility = Visibility.FORCE_OFF else nameplate.templateRoot.visibility = Visibility.FORCE_ON -- Some animated meshes are hidden and replaced by costumes nameplate.container.visibility = Visibility.INHERIT RotateNameplate(nameplate) -- Update cast bar if character:IsA("Player") then nameplate.castBarGroup.visibility = Visibility.FORCE_OFF if nameplate.interruptTime then nameplate.castBarGroup.visibility = Visibility.INHERIT if nameplate.interruptTime + 0.5 < os.clock() then nameplate.interruptTime = nil end else local castData = API_A.GetPlayerCastData(character) if castData then local totalTime = API_A.GetAbilityCastDuration(LOCAL_PLAYER, castData.abilityName) local remainingTime = castData.startTime + totalTime - os.clock() nameplate.castBarGroup.visibility = Visibility.INHERIT local castProgress = CoreMath.Clamp(1.0 - remainingTime / totalTime, 0.0, 1.0) local castProgressPieceOffset = 50.0 * HEALTHBAR_WIDTH * (1.0 - castProgress) nameplate.castProgressPiece:SetScale(Vector3.New(NAMEPLATE_LAYER_THICKNESS, HEALTHBAR_WIDTH * castProgress, HEALTHBAR_HEIGHT)) nameplate.castProgressPiece:SetPosition(Vector3.New(-1.0 * NAMEPLATE_LAYER_THICKNESS, castProgressPieceOffset, -100.0 * (HEALTHBAR_HEIGHT + BORDER_WIDTH))) nameplate.castProgressPiece:SetColor(Color.YELLOW) nameplate.castNameText.text = castData.abilityName end end end -- Update scale for target local scale = SCALE if API_T.GetTarget(LOCAL_PLAYER) == character then scale = scale * TARGET_SCALE_MULTIPLIER end nameplate.templateRoot:SetScale(Vector3.New(scale)) -- Update status effects local nameplatePosition = nameplate.templateRoot:GetWorldPosition() local nameplateUp = nameplate.templateRoot:GetWorldRotation() * Vector3.UP local characterScale = character:GetWorldScale().z if nameplate.animatedMesh then characterScale = nameplate.animatedMesh:GetWorldScale().z end local statusEffectPosition = nameplatePosition + nameplateUp * (BORDER_WIDTH + HEALTHBAR_HEIGHT) * 115.0 * scale * characterScale local screenPosition = UI.GetScreenPosition(statusEffectPosition) local targetDistance = LOCAL_PLAYER:GetViewWorldRotation() * Vector3.FORWARD .. (nameplatePosition - LOCAL_PLAYER:GetViewWorldPosition()) if targetDistance > 0.0 and screenPosition then local statusEffects = API_SE.GetStatusEffectsOnCharacter(character) nameplate.panel.visibility = Visibility.INHERIT nameplate.panel.x = screenPosition.x nameplate.panel.y = screenPosition.y local uiScale = math.min(10.0, 250.0 / targetDistance) * scale * characterScale for i = 1, API_SE.MAX_STATUS_EFFECTS do local data = statusEffects[i] local iconTemplate = nameplate.statusEffectIcons[i] if data then local icon = iconTemplate:GetCustomProperty("Icon"):WaitForObject() local timeText = iconTemplate:GetCustomProperty("TimeText"):WaitForObject() -- Apply scale iconTemplate.x = uiScale * STATUS_EFFECT_X_STEP * (i - (API_SE.MAX_STATUS_EFFECTS + 1) / 2) * 1.5 iconTemplate.y = uiScale * -20.0 iconTemplate.width = math.floor(uiScale * 80.0) iconTemplate.height = math.floor(uiScale * 80.0) timeText.height = math.floor(uiScale * 100.0) timeText.fontSize = uiScale * 50.0 local effectData = API_SE.STATUS_EFFECT_DEFINITIONS[data.name] iconTemplate.visibility = Visibility.INHERIT icon:SetImage(effectData.icon) if effectData.duration then local timeLeft = data.startTime + effectData.duration - time() if timeLeft > 180.0 then timeText.text = string.format("%dm", math.max(0.0, timeLeft // 60.0)) else timeText.text = string.format("%.1f", math.max(0.0, timeLeft)) end else timeText.text = "" end else iconTemplate.visibility = Visibility.FORCE_OFF end end else nameplate.panel.visibility = Visibility.FORCE_OFF end if SHOW_HEALTHBARS then local hitPoints = nil local maxHitPoints = nil if character:IsA("Player") then hitPoints = character.hitPoints maxHitPoints = character.maxHitPoints else hitPoints = API_NPC.GetHitPoints(character) maxHitPoints = API_NPC.GetMaxHitPoints(character) end local healthFraction = hitPoints / maxHitPoints local visibleHealthFraction = healthFraction -- For animating changes -- Set size and position of change piece if ANIMATE_CHANGES then local timeSinceChange = CoreMath.Clamp(os.clock() - nameplate.lastHealthTime, 0.0, CHANGE_ANIMATION_TIME) local timeScale = 1.0 - timeSinceChange / CHANGE_ANIMATION_TIME local changeFraction = timeScale * (nameplate.lastHealthFraction - healthFraction) nameplate.changePiece:SetScale(Vector3.New(NAMEPLATE_LAYER_THICKNESS, HEALTHBAR_WIDTH * math.abs(changeFraction), HEALTHBAR_HEIGHT)) if changeFraction == 0.0 then nameplate.changePiece.visibility = Visibility.FORCE_OFF else nameplate.changePiece.visibility = Visibility.INHERIT if changeFraction > 0.0 then -- Character took damage local changePieceOffset = 50.0 * HEALTHBAR_WIDTH * (1.0 - changeFraction) - 100.0 * HEALTHBAR_WIDTH * healthFraction nameplate.changePiece:SetPosition(Vector3.New(-1.0 * NAMEPLATE_LAYER_THICKNESS, changePieceOffset, 0.0)) nameplate.changePiece:SetColor(DAMAGE_CHANGE_COLOR) else -- Character was healed visibleHealthFraction = visibleHealthFraction + changeFraction local changePieceOffset = 50.0 * HEALTHBAR_WIDTH * (1.0 + changeFraction) - 100.0 * HEALTHBAR_WIDTH * visibleHealthFraction nameplate.changePiece:SetPosition(Vector3.New(-1.0 * NAMEPLATE_LAYER_THICKNESS, changePieceOffset, 0.0)) nameplate.changePiece:SetColor(HEAL_CHANGE_COLOR) end end -- Detect health changes to set the animation state if healthFraction ~= nameplate.lastFrameHealthFraction then -- If you just respawned, don't show it like a big heal if nameplate.lastFrameHealthFraction == 0.0 then nameplate.lastHealthTime = 0.0 nameplate.lastHealthFraction = healthFraction else nameplate.lastHealthTime = os.clock() nameplate.lastHealthFraction = nameplate.lastFrameHealthFraction end nameplate.lastFrameHealthFraction = healthFraction end end -- Set size and position of health bar local healthPieceOffset = 50.0 * HEALTHBAR_WIDTH * (1.0 - visibleHealthFraction) nameplate.healthPiece:SetScale(Vector3.New(NAMEPLATE_LAYER_THICKNESS, HEALTHBAR_WIDTH * visibleHealthFraction, HEALTHBAR_HEIGHT)) nameplate.healthPiece:SetPosition(Vector3.New(-1.0 * NAMEPLATE_LAYER_THICKNESS, healthPieceOffset, 0.0)) -- Update hit point number if SHOW_NUMBERS then nameplate.healthText.text = string.format("%.0f / %.0f", hitPoints, maxHitPoints) end -- Update Level if character:IsA("Player") then if character.clientUserData.statSheet then -- If stats aren't ready, they will be soon nameplate.levelText.text = tostring(character.clientUserData.statSheet:GetLevel()) end else nameplate.levelText.text = tostring(API_NPC.GetAllNPCData()[character].level) end nameplate.borderPiece:SetColor(BORDER_COLOR) -- Do we have aggro if not character:IsA("Player") and API_NPC.GetTarget(character) == LOCAL_PLAYER then nameplate.borderPiece:SetColor(BORDER_AGGRO_COLOR) end end -- Update name and health color based on teams and state if SHOW_NAMES then local nameColor = nil local healthColor = nil if character:IsA("Player") then nameColor = FRIENDLY_NAME_COLOR healthColor = FRIENDLY_HEALTH_COLOR else if API_NPC.IsAsleep(character) then -- Asleep nameColor = ENEMY_NAME_ASLEEP_COLOR healthColor = ENEMY_HEALTH_ASLEEP_COLOR else local target = API_NPC.GetTarget(character) if target then -- Combat if target == LOCAL_PLAYER then nameColor = ENEMY_NAME_AGGRO_COLOR else nameColor = ENEMY_NAME_COMBAT_COLOR end healthColor = ENEMY_HEALTH_COMBAT_COLOR else -- Ready nameColor = ENEMY_NAME_READY_COLOR healthColor = ENEMY_HEALTH_READY_COLOR end end end -- Adjust slightly if it's our target if API_T.GetTarget(LOCAL_PLAYER) == character then nameplate.nameText:SetScale(Vector3.New(1.15)) else nameplate.nameText:SetScale(Vector3.ONE) end nameplate.nameText:SetColor(nameColor) nameplate.healthPiece:SetColor(healthColor) end end end end -- Initialize Game.playerJoinedEvent:Connect(OnPlayerJoined) Game.playerLeftEvent:Connect(OnPlayerLeft) API_RE.Connect("NPC_Created", OnNPCCreated) API_RE.Connect("NPC_Destroyed", OnNPCDestroyed) API_RE.Connect("AI", OnAbilityInterrupted) for npc, data in pairs(API_NPC.GetAllNPCData()) do OnNPCCreated(npc, data) end
DefineClass.SpawnsAnomalyOnGameInit = { __parents = { "Object" }, properties = { { template = true, category = "Anomaly", name = T(1000037, "Name"), id = "anomaly_name", editor = "text", default = "", translate = true}, { template = true, category = "Anomaly", name = T(1000017, "Description"), id = "anomaly_description", editor = "text", default = "", translate = true}, { template = true, category = "Anomaly", name = T(3774, "Generate Breakthrough Tech"), id = "is_breakthrough", editor = "bool", default = false}, { template = true, category = "Anomaly", name = T(13604, "Revealed"), id = "anomaly_revealed", editor = "bool", default = false}, { template = true, category = "Anomaly", name = T(3775, "Sequence List"), id = "sequence_list", default = "", editor = "dropdownlist", items = function() return table.map(DataInstances.Scenario, "name") end, }, { template = true, category = "Anomaly", name = T(5, "Sequence"), id = "sequence", editor = "dropdownlist", items = function(self) return self.sequence_list == "" and {} or table.map(DataInstances.Scenario[self.sequence_list], "name") end, default = "", help = "Sequence to start when the anomaly is scanned" }, { template = true, category = "Anomaly", name = T(8696, "Expiration Time"), id = "expiration_time", editor = "number", default = 0, scale = const.HourDuration, help = "If > 0 the anomaly will expire and disappear in this many hours." }, { template = true, category = "Anomaly", name = T(3940, "Rare"), id = "anomaly_rare", editor = "bool", default = false, help = "Whether we should spawn a rare anomaly" }, }, } function SpawnsAnomalyOnGameInit:SpawnAnomaly() local map_id = self:GetMapID() local pos = self:GetPos() local marker = PlaceObjectIn("SubsurfaceSpecialAnomalyMarker", map_id) marker.display_name = self.anomaly_name ~= "" and self.anomaly_name or nil marker.description = self.anomaly_description ~= "" and self.anomaly_description or nil marker.sequence = self.sequence marker.sequence_list = self.sequence_list ~= "" and self.sequence_list or nil marker.expiration_time = self.expiration_time marker.tech_action = self.is_breakthrough and "breakthrough" marker.revealed = self.anomaly_revealed marker.rare = self.anomaly_rare marker:SetPos(pos) local x, y, unobstructed, obstructed = FindUnobstructedDepositPos(marker) if not obstructed and unobstructed then marker:SetPos(x, y, const.InvalidZ) end local city = GetCity(marker) local sector = GetMapSectorXY(city, x, y) if sector then local status = sector.blocked_status or sector.status if status == "unexplored" then sector:RegisterDeposit(marker) else RevealDeposits({marker}) end end end function SpawnsAnomalyOnGameInit:GameInit() self:SpawnAnomaly() end
-- Instance -- author: @roblox/0a_oq, @github/0aoq local Players = game:GetService("Players") return { name = script.Name, constructor = function(type: string, parent: Instance, next) local self = Instance.new(type, parent); next(self) -- object functions local properties = {} do function properties:Destroy() self:Destroy() end end; return properties end, }
----------------------------------------------- -- cherrypopper.lua -- Represents a cherrypopper that a player can wield or pick up -- Created by NimbusBP1729 ----------------------------------------------- -- -- Creates a new cherrypopper object -- @return the cherrypopper object created return { hand_x = 9, hand_y = 40, frameAmt = 3, width = 50, height = 35, dropWidth = 24, dropHeight = 44, damage = 7, special_damage = {ice = 1}, bbox_width = 22, bbox_height = 30, bbox_offset_x = {0,3,28}, bbox_offset_y = {0,1,28}, animations = { default = {'once', {'1,1'}, 1}, wield = {'once', {'1,1','2,1','3,1'},0.2} }, action = "wieldaction3" }
-- L3M0N Designed local credits="L3M0N" -- DO NOT CHANGE THIS AT ALL -- Chat Command local chat_enabled = true local chat_commands = {"!thirdperson","/thirdperson"} if CLIENT then local enabled=false local speed = 5 local lrp_right = 40 local lrp_forward = 100 local cr = { ["CHudCrosshair"]=true, } hook.Add("HUDShouldDraw", "RemoveCrosshair_", function(name) if cr[name] then return false end end) function ToggleThirdPerson() enabled=!enabled print("Third Person Made By L3M0N") end local myscrw, myscrh = 1768,992 print("Third Person Created By L3M0N\nhttp://steamcommunity.com/id/wwhitehouse") function sw(width) local screenwidth = myscrw return width*ScrW()/screenwidth end function sh(height) local screenheight = myscrh return height*ScrH()/screenheight end local blur = Material("pp/blurscreen") local function b(x, y, w, h) local X, Y = 0,0 surface.SetDrawColor(255,255,255) surface.SetMaterial(blur) for i = 1, 5 do blur:SetFloat("$blur", (i / 3) * (5)) blur:Recompute() render.UpdateScreenEffectTexture() render.SetScissorRect(x, y, x+w, y+h, true) surface.DrawTexturedRect(X * -1, Y * -1, ScrW(), ScrH()) render.SetScissorRect(0, 0, 0, 0, false) end draw.RoundedBox(0,x,y,w,h,Color(0,0,0,205)) surface.SetDrawColor(0,0,0) surface.DrawOutlinedRect(x,y,w,h) end function CreateThirdPersonAdjuster() tpa = vgui.Create("DFrame") tpa:SetTitle("") tpa:SetSize(sw(350),sh(30)) tpa:SetPos(ScrW()/2-sw(175),sh(5)) tpa.Paint = function(self) b(0,0,self:GetWide(),self:GetTall()) end tpa:SetDraggable(false) tpa:ShowCloseButton(false) local b = vgui.Create("DButton",tpa) b:SetSize(tpa:GetWide()/2,sh(20)) b:SetPos( (tpa:GetWide()/2)-((tpa:GetWide()/2)/2),sh(55) ) b:SetText("Toggle Thirdperson") b.DoClick = function() ToggleThirdPerson() end end if credits!="L3M0N" then return end hook.Add("OnContextMenuOpen","tpaopen", CreateThirdPersonAdjuster) hook.Add("OnContextMenuClose","tpaclose",function() if tpa then tpa:Remove() end end) hook.Add( "OnPlayerChat", "tpaopen", function( ply, strText ) if ply == LocalPlayer() and chat_enabled == true then strText = string.lower( strText ) if ( table.HasValue(chat_commands,strText) ) then ToggleThirdPerson() return "" end end end ) if credits!="L3M0N" then return end function CalcView(ply, pos, angles, fov) if enabled == true and !ply:InVehicle() then local view = {} lrp_forward = Lerp(speed*FrameTime(),lrp_forward,100) if enabled!=true then lrp_right = Lerp(speed*FrameTime(),lrp_right,-35) else lrp_right = Lerp(speed*FrameTime(),lrp_right,-20) end if ply:KeyDown(IN_SPEED) then lrp_forward = Lerp(speed*FrameTime(),lrp_forward,150) end if ply:KeyDown(IN_DUCK) then lrp_forward = Lerp(speed*FrameTime(),lrp_forward,50) end if ply:KeyDown(IN_WALK) then lrp_forward = Lerp(speed*FrameTime(),lrp_forward,50) end if ply:KeyDown(IN_ATTACK2) then lrp_forward = Lerp(speed*FrameTime(),lrp_forward,2) end if ply:IsOnGround() == false then lrp_forward = Lerp(speed*FrameTime(),lrp_forward,200) end local _p = LocalPlayer() local TraceData = { } TraceData.start = _p:EyePos() TraceData.endpos = _p:EyePos() + ( _p:GetRight() * -lrp_right ) + ( _p:GetForward() * -lrp_forward ) TraceData.filter = _p TraceData.mask = MASK_SOLID_BRUSHONLY local Trace = util.TraceLine( TraceData ) local v = { } v.origin = Trace.HitPos + _p:GetForward() *10 v.angles = _p:GetAngles() v.fov = _f return v end end hook.Add("CalcView", "hzn_CalcView", CalcView) hook.Add("ShouldDrawLocalPlayer", "hzn_ShouldDrawLocalPlayer", function(ply) return enabled end) local CrosshairS = 5 hook.Add("HUDPaint", "hzn_Crosshair", function() -- Credit For Crosshair: termy58 (I COULDNT FUCKING FIGURE IT OUT - l3m0n) if enabled == true and LocalPlayer():Alive() then local player = LocalPlayer() local t = {} t.start = player:GetShootPos() t.endpos = t.start + player:GetAimVector() * 9000 t.filter = player local tr = util.TraceLine(t) local pos = tr.HitPos:ToScreen() local fraction = math.min((tr.HitPos - t.start):Length(), 1024) / 1024 local size = 10 + 20 * (1.0 - fraction) local offset = size * 0.5 local offset2 = offset - (size * 0.1) t = {} t.start = enabled or player:GetPos() t.endpos = tr.HitPos + tr.HitNormal * 5 t.filter = player local tr = util.TraceLine(t) surface.SetDrawColor(255,255,255,255) CrosshairS = Lerp(speed*FrameTime(),CrosshairS,5) if LocalPlayer():KeyDown(IN_WALK) or LocalPlayer():KeyDown(IN_DUCK) then CrosshairS = Lerp(speed*FrameTime(),CrosshairS,1) end if LocalPlayer():KeyDown(IN_FORWARD) then CrosshairS = Lerp(speed*FrameTime(),CrosshairS,20) end if LocalPlayer():KeyDown(IN_SPEED) then CrosshairS = Lerp(speed*FrameTime(),CrosshairS,40) end if LocalPlayer():KeyDown(IN_ATTACK2) then CrosshairS = Lerp(speed*FrameTime(),CrosshairS,1) end if LocalPlayer():KeyDown(IN_ATTACK) then CrosshairS = Lerp(speed*FrameTime(),CrosshairS,20) end if !LocalPlayer():IsOnGround() then CrosshairS = Lerp(speed*FrameTime(),CrosshairS,40) end else if (LocalPlayer():Alive()) then CrosshairS = Lerp(speed*FrameTime(),CrosshairS,5) if LocalPlayer():KeyDown(IN_WALK) or LocalPlayer():KeyDown(IN_DUCK) then CrosshairS = Lerp(speed*FrameTime(),CrosshairS,1) end if LocalPlayer():KeyDown(IN_FORWARD) then CrosshairS = Lerp(speed*FrameTime(),CrosshairS,20) end if LocalPlayer():KeyDown(IN_SPEED) then CrosshairS = Lerp(speed*FrameTime(),CrosshairS,40) end if LocalPlayer():KeyDown(IN_ATTACK2) then CrosshairS = Lerp(speed*FrameTime(),CrosshairS,1) end if LocalPlayer():KeyDown(IN_ATTACK) then CrosshairS = Lerp(speed*FrameTime(),CrosshairS,20) end if !LocalPlayer():IsOnGround() then CrosshairS = Lerp(speed*FrameTime(),CrosshairS,40) end if !LocalPlayer():InVehicle() and !LocalPlayer():KeyDown(IN_ATTACK2) then surface.DrawCircle(ScrW()/2,ScrH()/2,sw(CrosshairS), 255, 255,255, 10) end end end end) hook.Add( "PostDrawOpaqueRenderables", "hzn_crosshair_", function() local trace = LocalPlayer():GetEyeTrace() local angle = trace.HitNormal:Angle() if (enabled==true) then cam.Start3D2D( trace.HitPos, angle+Angle(90,0,0), 1 ) surface.DrawCircle(0,0,CrosshairS, 255, 255,255, 10) cam.End3D2D() end end ) end
object_intangible_beast_bm_uller = object_intangible_beast_shared_bm_uller:new { } ObjectTemplates:addTemplate(object_intangible_beast_bm_uller, "object/intangible/beast/bm_uller.iff")
require 'p4' p4 = P4.P4() p4:connect() clientspec = p4:fetch_client() clientspec.Description = "Build client 2" p4:save_client( clientspec ) p4:disconnect()
local string = require"luv.string" local table = require"luv.table" local pairs, io, require, os, type, unpack, tostring = pairs, io, require, os, type, unpack, tostring local exceptions = require"luv.exceptions" local Object, Exception, try = require"luv.oop".Object, exceptions.Exception, exceptions.try module(...) local TestCase = Object:extend{ __tag = .....".TestCase"; Exception = Exception:extend{__tag = .....".Exception"}; assertTrue = function (test) if not test then Exception"assertTrue failed" end end; assertFalse = function (test) if test then Exception"assertFalse failed" end end; assertEquals = function (first, second) if first ~= second then Exception"assertEquals failed" end end; assertNotEquals = function (first, second) if first == second then Exception"assertNotEquals failed" end end; assertNil = function (val) if val ~= nil then Exception"assertNil failed" end end; assertNotNil = function (val) if val == nil then Exception"assertNotNil failed" end end; assertThrows = function (func, ...) local args = {...} try(function() func(unpack(args)) end):elseDo(function() Exception"assertThrows failed" end) end; assertNotThrows = function (func, ...) func(...) end; setUp = function () end; tearDown = function () end; run = function (self) local stat = {total = 0, executed = 0, failed = 0, time = os.clock(), methods = {}} local function errorHandler (e) stat.failed = stat.failed+1 io.write("\nException: ", e:msg(), e:trace()) end local function runTest (self, test) --setfenv(test, self) self:setUp() test(self) self:tearDown() stat.executed = stat.executed+1 end local s = self repeat for key, val in pairs(s) do if string.find(key, "test", 1, true) and type(val) == "function" then stat.total = stat.total+1 table.insert(stat.methods, key) io.write(key, ", ") try(runTest, self, s[key]):catch(Exception, errorHandler):throw() end end s = s:parent() until nil == s if stat.total ~= 0 then if stat.failed == 0 then io.write("\n--\nPASS ", stat.total, " tests") else io.write("\n--\nFAIL ", stat.failed, "/", stat.total, " tests") end io.write(" in ", os.clock()-stat.time, " sec") end return stat.total == 0 or (stat.total ~= 0 and stat.failed == 0) end; } local TestSuite = Object:extend{ __tag = .....".TestSuite"; tests = Object.property; init = function (self, tests) self:tests(tests) end; run = function (self) local testModule if not self:tests() then Exception "No tests are defined!" end local total, failed, time = 0, 0, os.clock() local runTest = function (test) local res = test:run() if not res then failed = failed+1 end total = total+1 io.write"\n\n" end for _, test in pairs(self:tests()) do local t = require(test) if t.isA then io.write(test, ": ") runTest(t) else local testCase for k, testCase in pairs(t) do io.write(test, "/", k, ": ") runTest(testCase) end end end io.write"==\n" if 0 == failed then io.write("PASS ", total, " unit tests in ", os.clock()-time, " sec") else io.write("FAIL ", failed, "/", total, " unit tests in ", os.clock()-time, " sec") end end } return { TestCase=TestCase;TestSuite=TestSuite; }
-- Copyright (c) 2021 Kirazy -- Part of Artisanal Reskins: Library -- -- See LICENSE.md in the project directory for license information. -- Core functions require("prototypes.functions.functions") require("prototypes.functions.tints") require("prototypes.functions.entity-rescaling") require("prototypes.functions.icon-handling") require("prototypes.functions.pipe-pictures") require("prototypes.functions.label-items") ---------------------------------------------------------------------------------------------------- -- ENTITIES ---------------------------------------------------------------------------------------------------- -- Base require("prototypes.entity.base.oil-refinery") require("prototypes.entity.base.splitter") require("prototypes.entity.base.transport-belt") require("prototypes.entity.base.underground-belt") ---------------------------------------------------------------------------------------------------- -- TECHNOLOGIES ---------------------------------------------------------------------------------------------------- -- Base require("prototypes.technology.base.logistics")
return function ( material ) function _material_inputs_radio (x, y, ripple, selected, inactive, hover, focused) local _radius = material.inputs.getPixelSize() / 2 -- Background colors local _unselectedBackgroundColor = material.theme.getActiveOnSurface() local _selectedBackgroundColor = material.theme.getSecondary() local _inactiveBackgroundColor = material.theme.getInactiveOnSurface() local _surfaceColor = material.theme.getSurface() -- Ripple colors local _unselectedRippleColor = material.theme.getRippleOnSurface() local _selectedRippleColor = material.theme.getRippleSecondary() local _unselectedHoverColor = material.theme.getRippleOnSurface() local _selectedHoverColor = material.theme.getRippleSecondary() local _unselectedFocusColor = material.theme.getInactiveOnSurface() local _selectedFocusColor = material.theme.getInactiveSecondary() -- Checks optional args ripple = math.min(ripple or 0, 1) selected = selected or false inactive = inactive or false hover = hover or false focused = focused or false local _love_color = { love.graphics.getColor() } -- Draws the focus if focused then if inactive then love.graphics.setColor(_unselectedFocusColor) else love.graphics.setColor(_selectedFocusColor) end love.graphics.circle("fill", x + _radius, y + _radius, _radius) end -- Draws the focus if hover then if inactive then love.graphics.setColor(_unselectedHoverColor) else love.graphics.setColor(_selectedHoverColor) end love.graphics.circle("fill", x + _radius, y + _radius, _radius) end -- Draws the ripple if ripple > 0 then if selected then love.graphics.setColor(_selectedRippleColor) else love.graphics.setColor(_unselectedRippleColor) end love.graphics.circle("fill", x + _radius, y + _radius, ripple * _radius) end -- Draws the background if inactive then love.graphics.setColor(_inactiveBackgroundColor) elseif not selected then love.graphics.setColor(_unselectedBackgroundColor) else love.graphics.setColor(_selectedBackgroundColor) end love.graphics.circle("fill", x + _radius, y + _radius, 10) love.graphics.setColor(_surfaceColor) love.graphics.circle("fill", x + _radius, y + _radius, 8) -- Draws the selection if selected then if inactive then love.graphics.setColor(_inactiveBackgroundColor) else love.graphics.setColor(_selectedBackgroundColor) end love.graphics.circle("fill", x + _radius, y + _radius, 6) end love.graphics.setColor(_love_color) end return _material_inputs_radio end
data:define_type("portrait") data:add_multi( "core.portrait", { { id = "man1", source = { x = 0, y = 0, width = 48, height = 72, } }, { id = "man2", source = { x = 48, y = 0, width = 48, height = 72, } }, { id = "man3", source = { x = 96, y = 0, width = 48, height = 72, } }, { id = "man4", source = { x = 144, y = 0, width = 48, height = 72, } }, { id = "man5", source = { x = 192, y = 0, width = 48, height = 72, } }, { id = "man6", source = { x = 240, y = 0, width = 48, height = 72, } }, { id = "man7", source = { x = 288, y = 0, width = 48, height = 72, } }, { id = "man8", source = { x = 336, y = 0, width = 48, height = 72, } }, { id = "man9", source = { x = 384, y = 0, width = 48, height = 72, } }, { id = "man10", source = { x = 432, y = 0, width = 48, height = 72, } }, { id = "man11", source = { x = 480, y = 0, width = 48, height = 72, } }, { id = "man12", source = { x = 528, y = 0, width = 48, height = 72, } }, { id = "man13", source = { x = 576, y = 0, width = 48, height = 72, } }, { id = "man14", source = { x = 624, y = 0, width = 48, height = 72, } }, { id = "man15", source = { x = 672, y = 0, width = 48, height = 72, } }, { id = "man16", source = { x = 720, y = 0, width = 48, height = 72, } }, { id = "man17", source = { x = 0, y = 72, width = 48, height = 72, } }, { id = "man18", source = { x = 48, y = 72, width = 48, height = 72, } }, { id = "man19", source = { x = 96, y = 72, width = 48, height = 72, } }, { id = "man20", source = { x = 144, y = 72, width = 48, height = 72, } }, { id = "man21", source = { x = 192, y = 72, width = 48, height = 72, } }, { id = "man22", source = { x = 240, y = 72, width = 48, height = 72, } }, { id = "man23", source = { x = 288, y = 72, width = 48, height = 72, } }, { id = "man24", source = { x = 336, y = 72, width = 48, height = 72, } }, { id = "man25", source = { x = 384, y = 72, width = 48, height = 72, } }, { id = "man26", source = { x = 432, y = 72, width = 48, height = 72, } }, { id = "man27", source = { x = 480, y = 72, width = 48, height = 72, } }, { id = "man28", source = { x = 528, y = 72, width = 48, height = 72, } }, { id = "man29", source = { x = 576, y = 72, width = 48, height = 72, } }, { id = "man30", source = { x = 624, y = 72, width = 48, height = 72, } }, { id = "man31", source = { x = 672, y = 72, width = 48, height = 72, } }, { id = "man32", source = { x = 720, y = 72, width = 48, height = 72, } }, { id = "man33", source = { x = 0, y = 144, width = 48, height = 72, } }, { id = "gilbert", source = { x = 48, y = 144, width = 48, height = 72, } }, { id = "man34", source = { x = 96, y = 144, width = 48, height = 72, } }, { id = "man35", source = { x = 144, y = 144, width = 48, height = 72, } }, { id = "arnord", source = { x = 192, y = 144, width = 48, height = 72, } }, { id = "man36", source = { x = 240, y = 144, width = 48, height = 72, } }, { id = "balzak", source = { x = 288, y = 144, width = 48, height = 72, } }, { id = "conery", source = { x = 336, y = 144, width = 48, height = 72, } }, { id = "man39", source = { x = 384, y = 144, width = 48, height = 72, } }, { id = "man40", source = { x = 432, y = 144, width = 48, height = 72, } }, { id = "man41", source = { x = 480, y = 144, width = 48, height = 72, } }, { id = "man42", source = { x = 528, y = 144, width = 48, height = 72, } }, { id = "man43", source = { x = 576, y = 144, width = 48, height = 72, } }, { id = "man44", source = { x = 624, y = 144, width = 48, height = 72, } }, { id = "barius", source = { x = 0, y = 216, width = 48, height = 72, } }, { id = "loyter", source = { x = 48, y = 216, width = 48, height = 72, } }, { id = "bethel", source = { x = 96, y = 216, width = 48, height = 72, } }, { id = "orphe", source = { x = 144, y = 216, width = 48, height = 72, } }, { id = "norne", source = { x = 192, y = 216, width = 48, height = 72, } }, { id = "zeome", source = { x = 240, y = 216, width = 48, height = 72, } }, { id = "saimore", source = { x = 288, y = 216, width = 48, height = 72, } }, { id = "xabi", source = { x = 336, y = 216, width = 48, height = 72, } }, { id = "karam", source = { x = 384, y = 216, width = 48, height = 72, } }, { id = "lomias", source = { x = 432, y = 216, width = 48, height = 72, } }, { id = "man45", source = { x = 480, y = 216, width = 48, height = 72, } }, { id = "sevilis", source = { x = 528, y = 216, width = 48, height = 72, } }, { id = "man46", source = { x = 576, y = 216, width = 48, height = 72, } }, { id = "man47", source = { x = 624, y = 216, width = 48, height = 72, } }, { id = "man48", source = { x = 672, y = 216, width = 48, height = 72, } }, { id = "woman1", source = { x = 0, y = 288, width = 48, height = 72, } }, { id = "woman2", source = { x = 48, y = 288, width = 48, height = 72, } }, { id = "woman3", source = { x = 96, y = 288, width = 48, height = 72, } }, { id = "woman4", source = { x = 144, y = 288, width = 48, height = 72, } }, { id = "woman5", source = { x = 192, y = 288, width = 48, height = 72, } }, { id = "woman6", source = { x = 240, y = 288, width = 48, height = 72, } }, { id = "woman7", source = { x = 288, y = 288, width = 48, height = 72, } }, { id = "woman8", source = { x = 336, y = 288, width = 48, height = 72, } }, { id = "woman9", source = { x = 384, y = 288, width = 48, height = 72, } }, { id = "woman10", source = { x = 432, y = 288, width = 48, height = 72, } }, { id = "woman11", source = { x = 480, y = 288, width = 48, height = 72, } }, { id = "woman12", source = { x = 528, y = 288, width = 48, height = 72, } }, { id = "woman13", source = { x = 576, y = 288, width = 48, height = 72, } }, { id = "woman14", source = { x = 624, y = 288, width = 48, height = 72, } }, { id = "woman15", source = { x = 672, y = 288, width = 48, height = 72, } }, { id = "woman16", source = { x = 720, y = 288, width = 48, height = 72, } }, { id = "woman17", source = { x = 0, y = 360, width = 48, height = 72, } }, { id = "woman18", source = { x = 48, y = 360, width = 48, height = 72, } }, { id = "woman19", source = { x = 96, y = 360, width = 48, height = 72, } }, { id = "woman20", source = { x = 144, y = 360, width = 48, height = 72, } }, { id = "woman21", source = { x = 192, y = 360, width = 48, height = 72, } }, { id = "woman22", source = { x = 240, y = 360, width = 48, height = 72, } }, { id = "woman23", source = { x = 288, y = 360, width = 48, height = 72, } }, { id = "woman24", source = { x = 336, y = 360, width = 48, height = 72, } }, { id = "woman25", source = { x = 384, y = 360, width = 48, height = 72, } }, { id = "woman26", source = { x = 432, y = 360, width = 48, height = 72, } }, { id = "woman27", source = { x = 480, y = 360, width = 48, height = 72, } }, { id = "woman28", source = { x = 528, y = 360, width = 48, height = 72, } }, { id = "woman29", source = { x = 576, y = 360, width = 48, height = 72, } }, { id = "woman30", source = { x = 624, y = 360, width = 48, height = 72, } }, { id = "woman31", source = { x = 672, y = 360, width = 48, height = 72, } }, { id = "woman32", source = { x = 720, y = 360, width = 48, height = 72, } }, { id = "woman34", source = { x = 0, y = 432, width = 48, height = 72, } }, { id = "woman35", source = { x = 48, y = 432, width = 48, height = 72, } }, { id = "mia", source = { x = 96, y = 432, width = 48, height = 72, } }, { id = "woman36", source = { x = 144, y = 432, width = 48, height = 72, } }, { id = "woman37", source = { x = 192, y = 432, width = 48, height = 72, } }, { id = "woman38", source = { x = 240, y = 432, width = 48, height = 72, } }, { id = "woman39", source = { x = 288, y = 432, width = 48, height = 72, } }, { id = "woman40", source = { x = 336, y = 432, width = 48, height = 72, } }, { id = "woman41", source = { x = 384, y = 432, width = 48, height = 72, } }, { id = "woman42", source = { x = 432, y = 432, width = 48, height = 72, } }, { id = "woman43", source = { x = 480, y = 432, width = 48, height = 72, } }, { id = "woman44", source = { x = 528, y = 432, width = 48, height = 72, } }, { id = "woman45", source = { x = 576, y = 432, width = 48, height = 72, } }, { id = "woman46", source = { x = 624, y = 432, width = 48, height = 72, } }, { id = "larnneire", source = { x = 0, y = 504, width = 48, height = 72, } }, { id = "shena", source = { x = 48, y = 504, width = 48, height = 72, } }, { id = "miches", source = { x = 96, y = 504, width = 48, height = 72, } }, { id = "isca", source = { x = 144, y = 504, width = 48, height = 72, } }, { id = "woman47", source = { x = 192, y = 504, width = 48, height = 72, } }, { id = "woman48", source = { x = 240, y = 504, width = 48, height = 72, } }, { id = "stersha", source = { x = 288, y = 504, width = 48, height = 72, } }, { id = "erystia", source = { x = 336, y = 504, width = 48, height = 72, } }, { id = "liana", source = { x = 384, y = 504, width = 48, height = 72, } }, { id = "woman49", source = { x = 432, y = 504, width = 48, height = 72, } }, })
local ttl = function (keys, min, max) local s = 0 for i = 1, table.getn(keys), 1 do s = s + redis.call("ZREMRANGEBYSCORE", keys[i], min, max) end return s end return ttl(redis.call("KEYS", KEYS[1]), ARGV[1], ARGV[2])
-- This table is used by the client to show items in the equipment menu, and by -- the server to check if a certain role is allowed to buy a certain item. -- If you have custom items you want to add, consider using a separate lua -- script that uses table.insert to add an entry to this table. This method -- means you won't have to add your code back in after every TTT update. Just -- make sure the script is also run on the client. -- -- For example: -- table.insert(EquipmentItems[ROLE_DETECTIVE], { id = EQUIP_ARMOR, ... }) -- -- Note that for existing items you can just do: -- table.insert(EquipmentItems[ROLE_DETECTIVE], GetEquipmentItem(ROLE_TRAITOR, EQUIP_ARMOR)) -- Special equipment bitflags. Every unique piece of equipment needs its own -- id. -- -- Use the GenerateNewEquipmentID function (see below) to get a unique ID for -- your equipment. This is guaranteed not to clash with other addons (as long -- as they use the same safe method). -- -- Details you shouldn't need: -- The number should increase by a factor of two for every item (ie. ids -- should be powers of two). EQUIP_NONE = 0 EQUIP_ARMOR = 1 EQUIP_RADAR = 2 EQUIP_DISGUISE = 4 EQUIP_MAX = 4 -- Icon doesn't have to be in this dir, but all default ones are in here local mat_dir = "vgui/ttt/" -- Stick to around 35 characters per description line, and add a "\n" where you -- want a new line to start. EquipmentItems = { [ROLE_DETECTIVE] = { -- body armor { id = EQUIP_ARMOR, loadout = true, -- default equipment for detectives type = "item_passive", material = mat_dir .. "icon_armor", name = "item_armor", desc = "item_armor_desc" }, -- radar { id = EQUIP_RADAR, type = "item_active", material = mat_dir .. "icon_radar", name = "item_radar", desc = "item_radar_desc" } -- The default TTT equipment uses the language system to allow -- translation. Below is an example of how the type, name and desc fields -- would look with explicit non-localized text (which is probably what you -- want when modding). -- { id = EQUIP_ARMOR, -- loadout = true, -- default equipment for detectives -- type = "Passive effect item", -- material = mat_dir .. "icon_armor", -- name = "Body Armor", -- desc = "Reduces bullet damage by 30% when\nyou get hit." -- }, }; [ROLE_TRAITOR] = { -- body armor { id = EQUIP_ARMOR, type = "item_passive", material = mat_dir .. "icon_armor", name = "item_armor", desc = "item_armor_desc" }, -- radar { id = EQUIP_RADAR, type = "item_active", material = mat_dir .. "icon_radar", name = "item_radar", desc = "item_radar_desc" }, -- disguiser { id = EQUIP_DISGUISE, type = "item_active", material = mat_dir .. "icon_disguise", name = "item_disg", desc = "item_disg_desc" } }; }; -- Search if an item is in the equipment table of a given role, and return it if -- it exists, else return nil. function GetEquipmentItem(role, id) local tbl = EquipmentItems[role] if not tbl then return end for k, v in pairs(tbl) do if v and v.id == id then return v end end end -- Utility function to register a new Equipment ID function GenerateNewEquipmentID() EQUIP_MAX = EQUIP_MAX * 2 return EQUIP_MAX end
return {'kiyu'}
ModifyEvent(-2, -2, -2, -2, -1, -1, -1, 2468, 2468, 2468, -2, -2, -2); AddItem(140, 1); AddItem(102, 5); do return end;
function OnPlayerDied() Events.Broadcast("UIUpdateSected",1) Game.GetLocalPlayer().clientUserData.CurrentlySelected = 1 end Events.Connect("LivingStateChange",function(state) OnPlayerDied() end)
local PlayTestSequence = { Properties = { SequenceEntity = {default = EntityId()}, }, } function PlayTestSequence:OnActivate() -- If no sequence entity assigned, use our entity if (not self.Properties.SequenceEntity:IsValid()) then self.Properties.SequenceEntity = self.entityId; end self.tickHandler = TickBus.Connect(self, 0) self.sequenceHandler = SequenceComponentNotificationBus.Connect(self, self.Properties.SequenceEntity); end function PlayTestSequence:OnDeactivate() self.sequenceHandler:Disconnect() self.tickHandler:Disconnect() end function PlayTestSequence:OnTick(deltaTime, timePoint) if (self.counter == nil) then self.counter = 0 end if (self.counter == 0) then SequenceComponentRequestBus.Event.Play(self.Properties.SequenceEntity) end self.counter = self.counter + deltaTime end function PlayTestSequence:OnStop(entityId, stopTime) AutomatedLauncherTestingRequestBus.Broadcast.CompleteTest(true, "Fly over test completed successfully."); end return PlayTestSequence
-- open terminal on ctrl+n vim.api.nvim_exec( [[ function! OpenTerminal() split term://bash resize 10 endfunction ]], true) -- clear all registers vim.api.nvim_exec( [[ fun! EmptyRegisters() let regs=split('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789/-"', '\zs') for r in regs call setreg(r, []) endfor endfun ]], true) -- removes any extraneous whitespace at the end of the lines vim.api.nvim_exec( [[ fun! TrimWhitespace() let l:save = winsaveview() keeppatterns %s/\s\+$//e call winrestview(l:save) endfun ]], true)
#!/usr/bin/env lua -- MIT License -- -- Copyright (c) 2021 Ferhat Geçdoğan All Rights Reserved. -- Distributed under the terms of the MIT License. -- if (#arg < 1) then print('Colocalua - Lua implementation of ColoCat\n'..arg[0]..' {file}') os.exit(1); end local open = io.open local BOLD_RED_COLOR = '\x1b[1;31m' local BOLD_GREEN_COLOR = '\x1b[1;32m' local BOLD_YELLOW_COLOR = '\x1b[1;33m' local BOLD_BLUE_COLOR = '\x1b[1;34m' local BOLD_MAGENTA_COLOR = '\x1b[1;35m' local BOLD_CYAN_COLOR = '\x1b[1;36m' local BOLD_LIGHT_BLACK_COLOR = '\x1b[1;90m' local BOLD_LIGHT_RED_COLOR = '\x1b[1;91m' local BOLD_LIGHT_GREEN_COLOR = '\x1b[1;92m' local BOLD_LIGHT_YELLOW_COLOR = '\x1b[1;93m' local BOLD_LIGHT_BLUE_COLOR = '\x1b[1;94m' local BOLD_LIGHT_MAGENTA_COLOR= '\x1b[1;95m' local BOLD_LIGHT_CYAN_COLOR = '\x1b[1;96m' local BOLD_LIGHT_WHITE_COLOR = '\x1b[1;97m' local RESET = '\x1b[0m' function exists(filename) local f = io.open(filename,'r') if f~=nil then io.close(f) return true else return false end end function print_top_header(length) io.write(BOLD_YELLOW_COLOR..' ╭'); local i = 0 while i ~= length do io.write('───'); i = i + 1; end io.write('╮\n '..' │ '..RESET); end function print_bottom_header(length) io.write(BOLD_LIGHT_CYAN_COLOR..' ╰'); local i = 0 while i ~= length do io.write('───'); i = i + 1; end io.write('╯\n'..RESET); end function header_text(text, language) print('🔒 '..BOLD_LIGHT_MAGENTA_COLOR..text..' | '..BOLD_LIGHT_RED_COLOR..language..RESET); end function regular(line) line = line:gsub('int ', BOLD_BLUE_COLOR..'int '..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('char ', BOLD_BLUE_COLOR..'char '..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('const ', BOLD_LIGHT_BLUE_COLOR..'const '..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('void ', BOLD_RED_COLOR..'void '..BOLD_LIGHT_WHITE_COLOR); print(line); end function c_plus_plus(line) if (string.sub(line, 1, 1) == '/' and string.sub(line, 2, 2) == '/') then line = BOLD_LIGHT_BLACK_COLOR..line..BOLD_LIGHT_WHITE_COLOR; end line = line:gsub('int ', BOLD_BLUE_COLOR..'int '..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('long ', BOLD_BLUE_COLOR..'long '..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('bool ', BOLD_BLUE_COLOR..'bool '..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('char ', BOLD_BLUE_COLOR..'char '..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('auto ', BOLD_BLUE_COLOR..'auto '..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('if', BOLD_LIGHT_RED_COLOR..'if'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('else', BOLD_LIGHT_RED_COLOR..'else'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('for', BOLD_MAGENTA_COLOR..'for'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('do', BOLD_MAGENTA_COLOR..'do'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('while', BOLD_MAGENTA_COLOR..'while'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('void ', BOLD_RED_COLOR..'void '..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('main', BOLD_LIGHT_RED_COLOR..'main'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('asm', BOLD_LIGHT_RED_COLOR..'asm'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('const ', BOLD_LIGHT_BLUE_COLOR..'const '..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('static ', BOLD_LIGHT_BLUE_COLOR..'static '..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('extern ', BOLD_LIGHT_BLUE_COLOR..'extern '..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('inline ', BOLD_LIGHT_BLUE_COLOR..'inline'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('virtual ', BOLD_LIGHT_BLUE_COLOR..'virtual '..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('friend ', BOLD_LIGHT_BLUE_COLOR..'friend '..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('public', BOLD_LIGHT_BLUE_COLOR..'public'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('private', BOLD_LIGHT_BLUE_COLOR..'private'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('protected', BOLD_LIGHT_BLUE_COLOR..'protected'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('#include', BOLD_YELLOW_COLOR..'#include'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('typedef ', BOLD_MAGENTA_COLOR..'typedef '..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('#define ', BOLD_MAGENTA_COLOR..'#define '..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('#ifndef ', BOLD_MAGENTA_COLOR..'#ifndef '..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('#ifdef ', BOLD_MAGENTA_COLOR..'#ifdef '..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('#endif', BOLD_MAGENTA_COLOR..'#endif'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('return ', BOLD_LIGHT_MAGENTA_COLOR..'return '..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('nodiscard', BOLD_LIGHT_BLACK_COLOR..'nodiscard'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('class ', BOLD_LIGHT_YELLOW_COLOR..'class '..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('struct ', BOLD_LIGHT_YELLOW_COLOR..'struct '..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('namespace ', BOLD_LIGHT_YELLOW_COLOR..'namespace '..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('using ', BOLD_GREEN_COLOR..'using '..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('std', BOLD_LIGHT_YELLOW_COLOR..'std'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('iostream', BOLD_LIGHT_MAGENTA_COLOR..'iostream'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('cstring', BOLD_LIGHT_MAGENTA_COLOR..'cstring'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('sstream', BOLD_LIGHT_MAGENTA_COLOR..'sstream'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('fstream', BOLD_LIGHT_MAGENTA_COLOR..'fstream'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('memory', BOLD_LIGHT_MAGENTA_COLOR..'memory'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('cstdlib', BOLD_LIGHT_MAGENTA_COLOR..'cstdlib'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('cstdio', BOLD_LIGHT_MAGENTA_COLOR..'cstdio'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('vector', BOLD_LIGHT_MAGENTA_COLOR..'vector'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('algorithm', BOLD_LIGHT_MAGENTA_COLOR..'algorithm'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('thread', BOLD_LIGHT_MAGENTA_COLOR..'thread'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('array', BOLD_LIGHT_MAGENTA_COLOR..'array'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('bitset', BOLD_LIGHT_MAGENTA_COLOR..'bitset'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('deque', BOLD_LIGHT_MAGENTA_COLOR..'deque'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('map', BOLD_LIGHT_MAGENTA_COLOR..'map'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('stack', BOLD_LIGHT_MAGENTA_COLOR..'stack'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('set', BOLD_LIGHT_MAGENTA_COLOR..'set'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('iterator', BOLD_LIGHT_MAGENTA_COLOR..'iterator'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('tuple', BOLD_LIGHT_MAGENTA_COLOR..'tuple'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('locale', BOLD_LIGHT_MAGENTA_COLOR..'locale'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('regex', BOLD_LIGHT_MAGENTA_COLOR..'regex'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('istream', BOLD_LIGHT_MAGENTA_COLOR..'istream'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('ostream', BOLD_LIGHT_MAGENTA_COLOR..'ostream'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('cout', BOLD_CYAN_COLOR..'cout'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('printf', BOLD_CYAN_COLOR..'printf'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('getline', BOLD_CYAN_COLOR..'getline'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('cin', BOLD_CYAN_COLOR..'cin'..BOLD_LIGHT_WHITE_COLOR); print(line); end function flascript(line) if (string.sub(line, 1, 1) == '/' and string.sub(line, 2, 2) == '/') then line = BOLD_LIGHT_BLACK_COLOR..line..BOLD_LIGHT_WHITE_COLOR; end line = line:gsub('print', BOLD_CYAN_COLOR..'print'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('fprintf', BOLD_CYAN_COLOR..'fprintf'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('@echo', BOLD_CYAN_COLOR..'@echo'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('fprintln', BOLD_CYAN_COLOR..'fprintln'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('@append', BOLD_LIGHT_YELLOW_COLOR..'@append'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('@pop_back', BOLD_LIGHT_YELLOW_COLOR..'@pop_back'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('@between', BOLD_LIGHT_YELLOW_COLOR..'@between'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('@escape_seq', BOLD_LIGHT_YELLOW_COLOR..'@escape_seq'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('@input', BOLD_LIGHT_YELLOW_COLOR..'@input'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('var ', BOLD_BLUE_COLOR..'var '..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('bool', BOLD_LIGHT_BLUE_COLOR..'bool'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('int', BOLD_LIGHT_BLUE_COLOR..'int'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('string', BOLD_LIGHT_BLUE_COLOR..'string'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('put', BOLD_MAGENTA_COLOR..'put'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('if', BOLD_LIGHT_RED_COLOR..'if'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('else', BOLD_LIGHT_RED_COLOR..'else'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('for', BOLD_MAGENTA_COLOR..'for'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('do', BOLD_MAGENTA_COLOR..'do'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('while', BOLD_MAGENTA_COLOR..'while'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('func', BOLD_RED_COLOR..'void'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('main', BOLD_LIGHT_RED_COLOR..'main'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('import', BOLD_YELLOW_COLOR..'import'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('defin', BOLD_MAGENTA_COLOR..'defin'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('#ifdef', BOLD_MAGENTA_COLOR..'#ifdef'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('#endif', BOLD_MAGENTA_COLOR..'#endif'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('return', BOLD_LIGHT_MAGENTA_COLOR..'return'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('SystemInfo', BOLD_LIGHT_MAGENTA_COLOR..'SystemInfo'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('Colorized', BOLD_LIGHT_MAGENTA_COLOR..'Colorized'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('newline', BOLD_LIGHT_BLACK_COLOR..'newline'..BOLD_LIGHT_WHITE_COLOR); print(line) end function python(line) if string.sub(line, 1, 1) == '#' then line = BOLD_LIGHT_BLACK_COLOR..line..BOLD_LIGHT_WHITE_COLOR; end line = line:gsub('if', BOLD_LIGHT_RED_COLOR..'if'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('else', BOLD_LIGHT_RED_COLOR..'else'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('elif', BOLD_LIGHT_RED_COLOR..'elif'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('for', BOLD_MAGENTA_COLOR..'for'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('while', BOLD_MAGENTA_COLOR..'while'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('str', BOLD_BLUE_COLOR..'str'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('bool', BOLD_BLUE_COLOR..'bool'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('float', BOLD_BLUE_COLOR..'float'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('def', BOLD_RED_COLOR..'def'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('lambda', BOLD_RED_COLOR..'lambda'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('import', BOLD_YELLOW_COLOR..'import'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('from', BOLD_LIGHT_YELLOW_COLOR..'from'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('global', BOLD_LIGHT_BLUE_COLOR..'global'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('return', BOLD_LIGHT_MAGENTA_COLOR..'return'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('print', BOLD_CYAN_COLOR..'print'..BOLD_LIGHT_WHITE_COLOR); print(line) end function html(line) line = line:gsub('html', BOLD_CYAN_COLOR..'html'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('!DOCTYPE', BOLD_BLUE_COLOR..'!DOCTYPE'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('abbr', BOLD_CYAN_COLOR..'abbr'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('acronym', BOLD_CYAN_COLOR..'acronym'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('address', BOLD_CYAN_COLOR..'address'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('applet', BOLD_CYAN_COLOR..'applet'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('area', BOLD_CYAN_COLOR..'area'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('article', BOLD_CYAN_COLOR..'article'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('aside', BOLD_CYAN_COLOR..'aside'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('audio', BOLD_CYAN_COLOR..'audio'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('base', BOLD_CYAN_COLOR..'base'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('basefont', BOLD_CYAN_COLOR..'basefont'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('bb', BOLD_CYAN_COLOR..'bb'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('bdo', BOLD_CYAN_COLOR..'bdo'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('big', BOLD_CYAN_COLOR..'big'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('blockquote', BOLD_CYAN_COLOR..'blockquote'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('body', BOLD_CYAN_COLOR..'body'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('br', BOLD_CYAN_COLOR..'br'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('button', BOLD_CYAN_COLOR..'button'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('canvas', BOLD_CYAN_COLOR..'canvas'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('caption', BOLD_CYAN_COLOR..'caption'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('center', BOLD_CYAN_COLOR..'center'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('cite', BOLD_CYAN_COLOR..'cite'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('code', BOLD_CYAN_COLOR..'code'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('col', BOLD_CYAN_COLOR..'col'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('colgroup', BOLD_CYAN_COLOR..'colgroup'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('command', BOLD_CYAN_COLOR..'command'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('datagrid', BOLD_CYAN_COLOR..'datagrid'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('datalist', BOLD_CYAN_COLOR..'datalist'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('dd', BOLD_CYAN_COLOR..'dd'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('del', BOLD_CYAN_COLOR..'del'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('details', BOLD_CYAN_COLOR..'details'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('dfn', BOLD_CYAN_COLOR..'dfn'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('dialog', BOLD_CYAN_COLOR..'dialog'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('dir', BOLD_CYAN_COLOR..'dir'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('div', BOLD_CYAN_COLOR..'div'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('dl', BOLD_CYAN_COLOR..'dl'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('dt', BOLD_CYAN_COLOR..'dt'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('em', BOLD_CYAN_COLOR..'em'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('embed', BOLD_CYAN_COLOR..'embed'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('eventsource', BOLD_CYAN_COLOR..'eventsource'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('fieldset', BOLD_CYAN_COLOR..'fieldset'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('figcaption', BOLD_CYAN_COLOR..'figcaption'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('figure', BOLD_CYAN_COLOR..'figure'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('font', BOLD_CYAN_COLOR..'font'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('footer', BOLD_CYAN_COLOR..'footer'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('form', BOLD_CYAN_COLOR..'form'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('frame', BOLD_CYAN_COLOR..'frame'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('frameset', BOLD_CYAN_COLOR..'frameset'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('h1', BOLD_CYAN_COLOR..'h1'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('h2', BOLD_CYAN_COLOR..'h2'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('h3', BOLD_CYAN_COLOR..'h3'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('h4', BOLD_CYAN_COLOR..'h4'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('h5', BOLD_CYAN_COLOR..'h5'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('h6', BOLD_CYAN_COLOR..'h6'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('head', BOLD_CYAN_COLOR..'head'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('header', BOLD_CYAN_COLOR..'header'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('hgroup', BOLD_CYAN_COLOR..'hgroup'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('hr', BOLD_CYAN_COLOR..'hr'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('iframe', BOLD_CYAN_COLOR..'iframe'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('img', BOLD_CYAN_COLOR..'img'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('input', BOLD_CYAN_COLOR..'input'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('ins', BOLD_CYAN_COLOR..'ins'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('isindex', BOLD_CYAN_COLOR..'isindex'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('kbd', BOLD_CYAN_COLOR..'kbd'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('keygen', BOLD_CYAN_COLOR..'keygen'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('label', BOLD_CYAN_COLOR..'label'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('legend', BOLD_CYAN_COLOR..'legend'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('li', BOLD_CYAN_COLOR..'li'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('link', BOLD_CYAN_COLOR..'link'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('map', BOLD_CYAN_COLOR..'map'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('mark', BOLD_CYAN_COLOR..'mark'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('menu', BOLD_CYAN_COLOR..'menu'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('meta', BOLD_CYAN_COLOR..'meta'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('meter', BOLD_CYAN_COLOR..'meter'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('nav', BOLD_CYAN_COLOR..'nav'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('noframes', BOLD_CYAN_COLOR..'noframes'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('noscript', BOLD_CYAN_COLOR..'noscript'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('object', BOLD_CYAN_COLOR..'object'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('ol', BOLD_CYAN_COLOR..'ol'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('optgroup', BOLD_CYAN_COLOR..'optgroup'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('option', BOLD_CYAN_COLOR..'option'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('output', BOLD_CYAN_COLOR..'output'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('p', BOLD_CYAN_COLOR..'p'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('param', BOLD_CYAN_COLOR..'param'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('pre', BOLD_CYAN_COLOR..'pre'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('progress', BOLD_CYAN_COLOR..'progress'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('q', BOLD_CYAN_COLOR..'q'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('rp', BOLD_CYAN_COLOR..'rp'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('rt', BOLD_CYAN_COLOR..'rt'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('ruby', BOLD_CYAN_COLOR..'ruby'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('script', BOLD_CYAN_COLOR..'script'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('samp', BOLD_CYAN_COLOR..'samp'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('section', BOLD_CYAN_COLOR..'section'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('select', BOLD_CYAN_COLOR..'select'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('small', BOLD_CYAN_COLOR..'small'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('source', BOLD_CYAN_COLOR..'source'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('span', BOLD_CYAN_COLOR..'span'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('strike', BOLD_CYAN_COLOR..'strike'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('strong', BOLD_CYAN_COLOR..'strong'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('style', BOLD_CYAN_COLOR..'style'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('sub', BOLD_CYAN_COLOR..'sub'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('sup', BOLD_CYAN_COLOR..'sup'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('table', BOLD_CYAN_COLOR..'table'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('tbody', BOLD_CYAN_COLOR..'tbody'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('tfoot', BOLD_CYAN_COLOR..'tfoot'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('th', BOLD_CYAN_COLOR..'th'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('thead', BOLD_CYAN_COLOR..'thead'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('time', BOLD_CYAN_COLOR..'time'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('title', BOLD_CYAN_COLOR..'title'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('tr', BOLD_CYAN_COLOR..'tr'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('track', BOLD_CYAN_COLOR..'track'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('tt', BOLD_CYAN_COLOR..'tt'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('u', BOLD_CYAN_COLOR..'u'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('ul', BOLD_CYAN_COLOR..'ul'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('var', BOLD_CYAN_COLOR..'var'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('video', BOLD_CYAN_COLOR..'video'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('wbr', BOLD_CYAN_COLOR..'wbr'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('class', BOLD_CYAN_COLOR..'class'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('/', BOLD_YELLOW_COLOR..'/'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('<', BOLD_YELLOW_COLOR..'<'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('>', BOLD_YELLOW_COLOR..'>'..BOLD_LIGHT_WHITE_COLOR); print(line) end function javascript(filename) if (string.sub(line, 1, 1) == '/' and string.sub(line, 2, 2) == '/') then line = BOLD_LIGHT_BLACK_COLOR..line..BOLD_LIGHT_WHITE_COLOR; end line = line:gsub('var ', BOLD_BLUE_COLOR..'var '..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('const ', BOLD_BLUE_COLOR..'const '..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('let ', BOLD_BLUE_COLOR..'let '..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('new', BOLD_BLUE_COLOR..'new'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('function', BOLD_RED_COLOR..'function'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('for', BOLD_RED_COLOR..'for'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('while', BOLD_RED_COLOR..'while'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('do', BOLD_RED_COLOR..'do'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('break', BOLD_BLUE_COLOR..'break'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('return', BOLD_BLUE_COLOR..'return'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('continue', BOLD_BLUE_COLOR..'continue'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('if', BOLD_CYAN_COLOR..'if'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('else', BOLD_CYAN_COLOR..'else'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('console', BOLD_CYAN_COLOR..'console'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('switch', BOLD_CYAN_COLOR..'switch'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('case', BOLD_CYAN_COLOR..'case'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('try', BOLD_RED_COLOR..'try'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('catch', BOLD_RED_COLOR..'catch'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('throw', BOLD_RED_COLOR..'throw'..BOLD_LIGHT_WHITE_COLOR); line = line:gsub('finally', BOLD_RED_COLOR..'finally'..BOLD_LIGHT_WHITE_COLOR); print(line) end function read_file(filename) extension = filename:match('^.+(%..+)$') if (extension == '.cpp' or extension == '.hpp' or extension == '.cc' or extension == '.hh' or extension == '.hxx' or extension == '.cxx') then for line in io.lines(filename) do c_plus_plus(line); end elseif (extension == '.fls' or extension == '.flsh') then for line in io.lines(filename) do flascript(line); end elseif extension == '.py' then for line in io.lines(filename) do python(line); end elseif (extension == '.htm' or extension == '.html') then for line in io.lines(filename) do html(line); end elseif extension == '.js' then for line in io.lines(filename) do javascript(line); end else for line in io.lines(filename) do regular(line); end end end if exists(arg[1]) == false then os.exit(1); end print_top_header(10); local extension = arg[1]:match('^.+(%..+)$') if (extension == '.cpp' or extension == '.hpp' or extension == '.cc' or extension == '.hh' or extension == '.hxx' or extension == '.cxx') then header_text(arg[1], 'C++'); elseif (extension == '.fls' or extension == '.flsh') then header_text(arg[1], 'FlaScript'); elseif extension == '.py' then header_text(arg[1], 'Python'); elseif (extension == '.htm' or extension == '.html') then header_text(arg[1], 'HTML'); elseif extension == '.js' then header_text(arg[1], 'JavaScript'); else header_text(arg[1], 'Regular'); end print_bottom_header(10); read_file(arg[1]);
-- Copyright (C) Yichun Zhang (agentzh) local ffi = require 'ffi' local ffi_string = ffi.string local C = ffi.C local ngx = ngx local type = type local tostring = tostring local base = require "resty.core.base" local get_string_buf = base.get_string_buf ffi.cdef[[ size_t ngx_http_lua_ffi_uri_escaped_length(const unsigned char *src, size_t len); void ngx_http_lua_ffi_escape_uri(const unsigned char *src, size_t len, unsigned char *dst); size_t ngx_http_lua_ffi_unescape_uri(const unsigned char *src, size_t len, unsigned char *dst); ]] ngx.escape_uri = function (s) if type(s) ~= 'string' then if not s then s = '' else s = tostring(s) end end local slen = #s local dlen = C.ngx_http_lua_ffi_uri_escaped_length(s, slen) -- print("dlen: ", tonumber(dlen)) if dlen == slen then return s end local dst = get_string_buf(dlen) C.ngx_http_lua_ffi_escape_uri(s, slen, dst) return ffi_string(dst, dlen) end ngx.unescape_uri = function (s) if type(s) ~= 'string' then if not s then s = '' else s = tostring(s) end end local slen = #s local dlen = slen local dst = get_string_buf(dlen) dlen = C.ngx_http_lua_ffi_unescape_uri(s, slen, dst) return ffi_string(dst, dlen) end return { version = base.version, }
----------------------------------------- -- ID: 11290 -- Item: tidal talisman -- ----------------------------------------- function onItemCheck(target) local result = 56 local zone = target:getZoneID() if (zone == 238 or zone == 239 or zone == 240 or zone == 241 or zone == 242 or -- Windurst zone == 234 or zone == 235 or zone == 236 or zone == 237 or -- Bastok zone == 230 or zone == 231 or zone == 232 or zone == 233 or -- San d'Oria zone == 243 or zone == 244 or zone == 245 or zone == 246 or -- Jeuno zone == 248 or -- Selbina zone == 249 or -- Mhaura zone == 250 or -- Kazham zone == 50 or -- Aht Urhgan Whitegate zone == 53) -- Nashmau then result = 0 end return result end function onItemUse(target) local zone = target:getZoneID() if (zone == 241 or zone == 242 or zone == 240 or zone == 239 or zone == 238) then -- Item is used in Windurst target:setPos(0, 3, 2, 64, 243) -- Player/s will end up at Ru'Lude Gardens elseif (zone == 237 or zone == 236 or zone == 235 or zone == 234) then -- Item is used in Bastok target:setPos(0, 3, 2, 64, 243) -- Player/s will end up at Ru'Lude Gardens elseif (zone == 233 or zone == 232 or zone == 231 or zone == 230) then -- Item is used in San d'Oria target:setPos(0, 3, 2, 64, 243) -- Player/s will end up at Ru'Lude Gardens elseif (zone == 243 or zone == 245 or zone == 244) then -- Item is used in Jeuno target:setPos(-33, -8, -71, 97, 250) -- player/s end up in Kazham elseif (zone == 250) then -- Item is used in Kazham target:setPos(0, 3, 2, 64, 243) -- Player/s will end up at Ru'Lude Gardens elseif (zone == 248) then -- Item is used in Selbina target:setPos(0, -8, 59, 62, 248) -- player/s end up at Mhaura elseif (zone == 249) then -- Item is used in Mhaura target:setPos(18, -14, 79, 62, 248) -- player/s end up in Selbina elseif (zone == 50) then -- Item is used in Aht Urhgan Whitegate target:setPos(12, -6, 31, 63, 53) -- player/s end up in Nashmau elseif (zone == 53) then -- Item is used in Nashmu target:setPos(-73, 0, 0, 252, 50) -- player/s ends up at Aht Urahgan Whitegate end end
math.randomseed(os.time()) local rand = math.random local tasks = {} local function ghost(t, ...) local g = {} local exc = {...} local check = {} for i = 1, #exc do check[exc[i]] = true end for i = 1, #t do if not check[i] then g[#g + 1] = t[i] end end return g end local printf do local format = string.format printf = function (fstring, ...) print(format(fstring, unpack({...}))) end end local function addtask(task) tasks[#tasks + 1] = {c = coroutine.create(task), events = {}} end local function shuffle(arr) local a, b for i = 1, #arr do a = rand(#arr) b = rand(#arr) arr[a], arr[b] = arr[b], arr[a] end end local function run() local i = 1 local ret while true do i = 1 shuffle(tasks) while i <= #tasks do ret = {coroutine.resume(tasks[i].c)} if not ret[1] then print(err) end if coroutine.status(tasks[i].c) == "dead" then tasks = ghost(tasks, i) end if #tasks == 0 then os.exit(0) end i = i + 1 end end end local function wait() local tick while true do print("tick") tick = os.clock() while os.clock() - tick < 1 do coroutine.yield() end print("tock") end end
local minos = {} -- constants for directions minos.up_ = 0 minos.dwn = 1 minos.rgt = 2 minos.lft = 3 function minos:create_mino(_x,_y,_type,_image) mino={} mino.x=_x mino.y=_y mino.type=_type mino.image=_image end function mino:update(map) --update the mino in the map index if(map[mino.y+1]==0)then local item_up = map[mino.y-1][mino.x] if(item_up~=nil and item_up==0)then map[mino.y][mino.x]=0 end mino.y=mino.y+1;map[mino.y][mino.x]=mino.type return true else return false end end function mino:move(direction,map) local verify_move=false if (direction==minos.up_)then local item_up = map[mino.y-1][mino.x] if(item_up~=nil and item_up==0)then if(map[mino.y+1][mino.x]==0)then map[mino.y][mino.x]=0 end mino.y=mino.y-1;map[mino.y][mino.x]=mino.type end elseif(direction==minos.dwn)then local item_dwn = map[mino.y+1][mino.x] if(item_dwn~=nil and item_dwn==0)then if(map[mino.y-1][mino.x]==0)then map[mino.y][mino.x]=0 end mino.y=mino.y+1;map[mino.y][mino.x]=mino.type end elseif(direction==minos.rgt)then local item_rgt = map[mino.y][mino+1] if(item_rgt~=nil and item_rgt==0)then if(map[mino.y][mino.x-1]==0)then map[mino.y][mino.x]=0 end mino.x = mino.x+1; map[mino.y][mino.x]=mino.type end elseif(direction==minos.lft)then local item_lft = map[mino.y][mino.x-1] if(item_lft~= nil and item_lft==0)then if(map[mino.y][mino.x+1]==0)then map[mino.y][mino.x]=0 end mino.x = mino.x-1; map[mino.y][mino.x]=mino.type end end end function mino:draw(size) love.graphics.draw(mino.image,mino.x*size,mino.y*size,0,1,1,0,0,1,1); end return minos
bc.util = bc.util or {} -- Can a player run a command on a person (via ULX) function bc.util.canRunULX( cmd, target, ply ) if not ULib then return false end local ply = ply or LocalPlayer() if ply:SteamID() == "STEAM_0:0:0" or ply:SteamID() == "STEAM_0:0:00000000" then return true end local canRun, tag = ULib.ucl.query( ply, cmd ) --Get global can run if not canRun then return false end --If they cant, return no if not target then return true end --If no target specified, just return if they can run the func at all if not tag then success, tag = pcall( function() return ULib.ucl.getGroupCanTarget( ply:GetUserGroup() ) end ) --if no player specific tag, get tag from their rank end if not success then return false end -- Edge case when rank doesnt exist but previous had permissions (e.g. SA -> unassigned) if not tag then return true end --if still no tag, player has no restriction, return yes local users = ULib.getUsers( tag, true, ply ) --get users our player can target return table.HasValue( users or {}, target ) end if SERVER then function bc.util.getRunnableULXCommands( ply ) local sayCmds = ULib.sayCmds local allCmds = {} for cmd, data in pairs( sayCmds ) do if data.__cmd and bc.util.canRunULX( data.__cmd, nil, ply ) and cmd[1] == "!" then table.insert( allCmds, string.sub( cmd, 0, #cmd - 1 ) ) end end return allCmds end end function bc.util.isLetter( char ) return string.byte( char ) >= string.byte( "A" ) and string.byte( char ) <= string.byte( "z" ) end -- Length treating tabs as 4 spaces function bc.util.getChatTextLength( txt ) local _, count = string.gsub( txt, "\t", "" ) return #txt + count * 3 end function bc.util.shortenChatText( txt, len ) local a = 1000 while bc.util.getChatTextLength( txt ) > len and a > 0 do a = a - 1 txt = string.sub( txt, 1, -2 ) end if a == 0 then print( "Shouldn't happen, pls message BetterChat creator if you see this :)" ) end return txt end -- Url finding (https://stackoverflow.com/questions/23590304/finding-a-url-in-a-string-lua-pattern) -- all characters allowed to be inside URL according to RFC 3986 but without -- comma, semicolon, apostrophe, equal, brackets and parentheses -- (as they are used frequently as URL separators) local domains = [[.ac.ad.ae.aero.af.ag.ai.al.am.an.ao.aq.ar.arpa.as.asia.at.au .aw.ax.az.ba.bb.bd.be.bf.bg.bh.bi.biz.bj.bm.bn.bo.br.bs.bt.bv.bw.by.bz.ca .cat.cc.cd.cf.cg.ch.ci.ck.cl.cm.cn.co.com.coop.cr.cs.cu.cv.cx.cy.cz.dd.de .dj.dk.dm.do.dz.ec.edu.ee.eg.eh.er.es.et.eu.fi.firm.fj.fk.fm.fo.fr.fx.ga .gb.gd.ge.gf.gh.gi.gl.gm.gn.gov.gp.gq.gr.gs.gt.gu.gw.gy.hk.hm.hn.hr.ht.hu .id.ie.il.im.in.info.int.io.iq.ir.is.it.je.jm.jo.jobs.jp.ke.kg.kh.ki.km.kn .kp.kr.kw.ky.kz.la.lb.lc.li.lk.lr.ls.lt.lu.lv.ly.ma.mc.md.me.mg.mh.mil.mk .ml.mm.mn.mo.mobi.mp.mq.mr.ms.mt.mu.museum.mv.mw.mx.my.mz.na.name.nato.nc .ne.net.nf.ng.ni.nl.no.nom.np.nr.nt.nu.nz.om.org.pa.pe.pf.pg.ph.pk.pl.pm .pn.post.pr.pro.ps.pt.pw.py.qa.re.ro.ru.rw.sa.sb.sc.sd.se.sg.sh.si.sj.sk .sl.sm.sn.so.sr.ss.st.store.su.sv.sy.sz.tc.td.tel.tf.tg.th.tj.tk.tl.tm.tn .to.tp.tr.travel.tt.tv.tw.tz.ua.ug.uk.um.us.uy.va.vc.ve.vg.vi.vn.vu.web.wf .ws.xxx.ye.yt.yu.za.zm.zr.zw]] local tlds = {} for tld in string.gmatch( domains, "%w+" ) do tlds[tld] = true end local function max4( a, b, c, d ) return math.max( a + 0, b + 0, c + 0, d + 0 ) end local protocols = { [""] = 0, ["http://"] = 0, ["https://"] = 0, ["ftp://"] = 0 } function bc.util.getNextUrl( inputStr ) local pos_start, pos_end, url, prot, subd, tld, colon, port, slash, path = string.find( inputStr, "(([%w_.~!*:@&+$/?%%#-]-)(%w[-.%w]*%.)(%w+)(:?)(%d*)(/?)([%w_.~!*:@&+$/?%%#=-]*))" ) if pos_start and protocols[prot:lower()] == ( 1 - #slash ) * #path and not string.find( subd, "%W%W" ) and ( colon == "" or port ~= "" and port + 0 < 65536 ) and ( tlds[tld:lower()] or string.find( tld, "^%d+$" ) and string.find( subd, "^%d+%.%d+%.%d+%.$" ) and max4( tld, string.match( subd, "^(%d+)%.(%d+)%.(%d+)%.$" ) ) < 256 ) then return pos_start, pos_end, string.sub( inputStr, pos_start, pos_end ) end pos_start, pos_end, url, prot, dom, colon, port, slash, path = string.find( inputStr, "((%f[%w]%a+://)(%w[-.%w]*)(:?)(%d*)(/?)([%w_.~!*:@&+$/?%%#=-]*))" ) if pos_start and not string.find( dom .. ".", "%W%W" ) and protocols[prot:lower()] == ( 1 - #slash ) * #path and ( colon == "" or port ~= "" and port + 0 < 65536 ) then return pos_start, pos_end, string.sub( inputStr, pos_start, pos_end ) end return nil end -- End urlFinding -- Different to IsColor, as doesn't require mt to be set function bc.util.isColor( tab ) return type( tab ) == "table" and type( tab.r ) == "number" and type( tab.g ) == "number" and type( tab.b ) == "number" and type( tab.a ) == "number" and #table.GetKeys( tab ) == 4 end if CLIENT then local function makeFonts( name, data ) name = "BC_" .. name data.antialias = false data.shadow = true data.extended = true for boldI = 0, 1 do local bold = boldI == 1 for italicsI = 0, 1 do local italics = italicsI == 1 local newName = name local newData = table.Copy( data ) if bold then newName = newName .. "_bold" newData.weight = newData.weight + 200 end if italics then newName = newName .. "_italics" newData.italic = true end surface.CreateFont( newName, newData ) end end end makeFonts( "default", { font = system.IsLinux() and "DejaVu Sans" or "Tahoma", size = 21, weight = 500, } ) makeFonts( "defaultLarge", { font = system.IsLinux() and "DejaVu Sans" or "Tahoma", size = 26, weight = 500, } ) makeFonts( "monospace", { font = "Lucida Console", size = 15, weight = 500, } ) makeFonts( "monospaceLarge", { font = "Lucida Console", size = 22, weight = 500, } ) makeFonts( "monospaceSmall", { font = "Lucida Console", size = 10, weight = 300, } ) local blur = Material( "pp/blurscreen" ) function bc.util.blur( panel, layers, density, alpha, w, h ) local x, y = panel:LocalToScreen( 0, 0 ) if not w then w, h = panel:GetSize() end surface.SetDrawColor( 255, 255, 255, alpha ) surface.SetMaterial( blur ) for i = 1, 3 do blur:SetFloat( "$blur", ( i / layers ) * density ) blur:Recompute() render.UpdateScreenEffectTexture() surface.DrawTexturedRectUV( 0, 0, w, h, x / ScrW(), y / ScrH(), ( x + w ) / ScrW(), ( y + h ) / ScrH() ) end end function bc.util.msgC( ... ) local data = { ... } data = bc.channels.preProcess( data ) local lastCol = bc.defines.colors.white local k = 1 while k <= #data do local v = data[k] if type( v ) == "Player" then table.remove( data, k ) table.insertMany( data, k, { team.GetColor( v:Team() ), v:Nick(), lastCol } ) k = k + 2 elseif type( v ) == "table" then if v.formatter or v.controller then if v.formatter and ( v.type == "image" or v.type == "clickable" or v.type == "text" ) then if v.colour then v.color = v.colour end data[k] = v.text if ( v.type == "clickable" or v.type == "text" ) and v.color then table.insert( data, k, v.color ) table.insert( data, k + 2, lastCol ) k = k + 2 end else table.remove( data, k ) k = k - 1 end elseif v.isConsole then table.remove( data, k ) table.insert( data, k, lastCol ) table.insert( data, k, "Console" ) table.insert( data, k, bc.defines.colors.printBlue ) k = k + 2 else lastCol = v end end k = k + 1 end data[#data + 1] = "\n" MsgC( unpack( data ) ) end end bc.util.hooks = bc.util.hooks or {} bc.util.HOOK_ALTER = 0 bc.util.HOOK_RETURN = 1 local function makeHookWrapper( event ) return { BC_GlobalHookManager = { isstring = true, fn = function( ... ) local data = { ... } local preRes = { hook.Run( "BC_Pre_" .. event, unpack( data ) ) } if #preRes > 0 then local returnType = table.remove( preRes, 1 ) if returnType == bc.util.HOOK_ALTER then data = preRes elseif returnType == bc.util.HOOK_RETURN then return unpack( preRes ) else return returnType, unpack( preRes ) end end local res = { bc.util.runReplacedHook( event, unpack( data ) ) } local postRes = { hook.Run( "BC_Post_" .. event, data, res ) } if #postRes > 0 then res = postRes end return unpack( res ) end } } end function bc.util.replaceHookTable( event ) if bc.util.hooks[event] then return end print( "[BetterChat] Overloading " .. event .. " hook table" ) local uLibHookTbl = hook.GetULibTable() -- Forces tables to exist if not uLibHookTbl[event] then hook.Add( event, "bc_TempHook", function() end ) hook.Remove( event, "bc_TempHook" ) end local wrapper = makeHookWrapper( event ) bc.util.hooks[event] = uLibHookTbl[event] uLibHookTbl[event] = { [ -2] = {}, [ -1] = {}, [0] = wrapper, [1] = {}, [2] = {} } for i = -2, 2 do local mt = {} function mt:__index( k ) return bc.util.hooks[event][i][k] end function mt:__newindex( k, v ) bc.util.hooks[event][i][k] = v end setmetatable( uLibHookTbl[event][i], mt ) end end function bc.util.undoReplaceHookTable( event ) if not bc.util.hooks[event] then return end -- Not replaced print( "[BetterChat] Undoing " .. event .. " hook table overload" ) local uLibHookTbl = hook.GetULibTable() uLibHookTbl[event] = bc.util.hooks[event] bc.util.hooks[event] = nil end -- Code from https://github.com/TeamUlysses/ulib/blob/master/lua/ulib/shared/hook.lua function bc.util.runReplacedHook( event, ... ) local hookTbl = bc.util.hooks[event] if hookTbl then for i = -2, 2 do for k, v in pairs( hookTbl[i] ) do if ( v.isstring ) then local success, a, b, c, d, e, f = xpcall( v.fn, function( e ) print( "Error in " .. event .. ", " .. k .. ": " .. tostring( a ) ) print( debug.traceback() ) end, ... ) if success and a ~= nil and i > -2 and i < 2 then return a, b, c, d, e, f end else if ( IsValid( k ) ) then local success, a, b, c, d, e, f = xpcall( v.fn, function( e ) print( "Error in " .. event .. ", " .. k .. ": " .. tostring( a ) ) print( debug.traceback() ) end, ... ) if success and a ~= nil and i > -2 and i < 2 then return a, b, c, d, e, f end else hookTbl[i][k] = nil end end end end end if GAMEMODE and GAMEMODE[event] then return GAMEMODE[event]( GAMEMODE, ... ) end end function bc.util.you( ply ) ply = ply or LocalPlayer() return { formatter = true, type = "clickable", signal = "Player-" .. ply:SteamID(), text = "You", color = bc.defines.colors.ulxYou } end
----------------------------------------------------------------------------- -- Tab completion for the Cloud Foundry CLI (cf) on Windows -- for use with clink (https://github.com/mridgers/clink) -- -- Copyright (c) 2017 Dies Koper -- -- License: MIT, see https://opensource.org/licenses/MIT ----------------------------------------------------------------------------- local parser = clink.arg.new_parser -- execute cf with goflags env var to retrieve newline delimited completions local function list_cf_completions() local cur_line = rl_state.line_buffer local exec_cmd = 'set GO_FLAGS_COMPLETION=1 && '..cur_line..' 2>nul' for candidate in io.popen(exec_cmd):lines() do -- print('[m:'..candidate..']') -- goflags sometimes returns previous arg/opt, so detect and skip -- (coz space after last arg/opt is not propagated to goflags?) local i, _ = string.find(cur_line, candidate, -2 - #candidate, true) if not i then clink.add_match(candidate) end end return {} end local completions = function (token) -- luacheck: no unused args return list_cf_completions() end -- 6 levels deep: e.g. `cf set-space-role user org space role -v` local cf_parser = parser( {completions}, {completions}, {completions}, {completions}, {completions}, {completions} ) clink.arg.register_parser("cf", cf_parser)
local utils = require 'utils' local Dialog = require 'dialog' local app = require 'app' return { width = 32, height = 48, run_speed = 50, run_offsets = {{x=5, y=0}, {x=-1000, y=0}, {x=-990, y=0}}, animations = { default = { 'loop',{'1,1','11,1'},.5, }, walking = { 'loop',{'1,1','2,1','3,1'},.2, }, }, walking = true, --walk_speed = 36, enter = function(npc, previous) local show = npc.db:get('acornKingVisible', false) local acornDead = npc.db:get("bosstriggers.acorn", true) local bldgburned = npc.db:get('house_building_burned', false ) if show == true and not npc.hidden then npc.state = 'walking' npc.collider:setGhost(npc.bb) npc.run_offsets = {{x=5, y=0}, {x=-1000, y=0}, {x=-990, y=0}} npc.flee = true npc.hidden = true elseif bldgburned == true then npc.flee = false npc.state = 'hidden' npc.collider:setGhost(npc.bb) end end, talk_items = { { ['text']='i am done with you' }, { ['text']='What are you carrying?'}, { ['text']='This town is in ruins!' }, { ['text']='Talk about the Acorn King'}, }, talk_commands = { ['Talk about the Acorn King'] = function (npc, player) npc.walking = false local check = app.gamesaves:active():get("bosstriggers.acorn", false) if check ~= false then Dialog.new("You saved us from the Acorn King! Thank you so much, adventurer!", function() npc.menu:close(player) npc.walking = true end) else Dialog.new("The Acorn King? He's a monster! It's because of the acorn infestation that we had to close the mines, it got too dangerous!", function() npc.menu:close(player) npc.walking = true end) end end, }, talk_responses = { ["This town is in ruins!"]={ "Ever since that tyrant {{grey}}Hawkthorne{{white}} started ruling,", "our town started falling apart into pieces. If only he were overthrown!", }, ["What are you carrying?"]={ "It's a piece of wood. The town {{green_light}}blacksmith{{white}} needs it to make his weapons.", "You can find him at the last house on the street.", }, }, update = function(dt, npc, player) if npc.flee then npc:run(dt, player) end end, }
--ロード・ウォリアー function c2322421.initial_effect(c) aux.AddMaterialCodeList(c,71971554) --synchro summon aux.AddSynchroProcedure(c,c2322421.tfilter,aux.NonTuner(nil),2) c:EnableReviveLimit() --spsummon local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(2322421,0)) e1:SetCategory(CATEGORY_SPECIAL_SUMMON) e1:SetType(EFFECT_TYPE_IGNITION) e1:SetCountLimit(1) e1:SetRange(LOCATION_MZONE) e1:SetTarget(c2322421.tg) e1:SetOperation(c2322421.op) c:RegisterEffect(e1) end c2322421.material_setcode=0x1017 function c2322421.tfilter(c) return c:IsCode(71971554) or c:IsHasEffect(20932152) end function c2322421.filter(c,e,tp) return c:IsLevelBelow(2) and c:IsRace(RACE_WARRIOR+RACE_MACHINE) and c:IsCanBeSpecialSummoned(e,0,tp,false,false) end function c2322421.tg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and Duel.IsExistingMatchingCard(c2322421.filter,tp,LOCATION_DECK,0,1,nil,e,tp) end Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_DECK) end function c2322421.op(e,tp,eg,ep,ev,re,r,rp) if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local g=Duel.SelectMatchingCard(tp,c2322421.filter,tp,LOCATION_DECK,0,1,1,nil,e,tp) if g:GetCount()>0 then Duel.SpecialSummon(g,0,tp,tp,false,false,POS_FACEUP) end end
local config = { cmd = { "DiffviewOpen", "DiffviewFocusFiles", "DiffviewToggleFiles", "DiffviewClose", "DiffviewRefresh", }, config = function() require "plug-config.diffview.settings" end, } return config
local Promise = require(script.Parent.Promise) -- constants local TYPE_STRING = "string" local TS = {} -- runtime classes TS.Promise = Promise local Symbol do Symbol = {} Symbol.__index = Symbol setmetatable(Symbol, { __call = function(_, description) local self = setmetatable({}, Symbol) self.description = description or "" return self end }) function Symbol:__tostring() return "Symbol(" .. self.description .. ")" end function Symbol:toString() return tostring(self) end end TS.Symbol = Symbol -- module resolution local globalModules = script.Parent.Parent:FindFirstChild("Modules") function TS.getModule(moduleName, object) if not globalModules then error("Could not find any modules!", 2) end if object:IsDescendantOf(globalModules) then while object.Parent do local modules = object == globalModules and object or object:FindFirstChild("node_modules") if modules then local module = modules:FindFirstChild(moduleName) if module then return module end end object = object.Parent end else local module = globalModules:FindFirstChild(moduleName) if module then return module end end error("Could not find module: " .. moduleName, 2) end function TS.import(root, ...) local currentInstance = typeof(root) == "Instance" and root or game:GetService(root) local path = { ... } if currentInstance then for _, part in pairs(path) do currentInstance = currentInstance and currentInstance:WaitForChild(part) end end if currentInstance and currentInstance:IsA("ModuleScript") then return require(currentInstance) else error("Failed to import!", 2) end end function TS.exportNamespace(module, ancestor) for key, value in pairs(module) do ancestor[key] = value end end -- general utility functions function TS.typeof(value) local type = typeof(value) if type == "table" then return "object" elseif type == "nil" then return "undefined" else return type end end function TS.instanceof(obj, class) while obj ~= nil do if obj == class then return true end obj = getmetatable(obj) end return false end function TS.isA(instance, className) return typeof(instance) == "Instance" and instance:IsA(className) end function TS.async(callback) return function(...) local args = { ... } return Promise.new(function(resolve, reject) coroutine.wrap(function() local ok, result = pcall(callback, unpack(args)) if ok then resolve(result) else reject(result) end end)() end) end end function TS.await(promise) if not Promise.is(promise) then return promise end local ok, result = promise:await() if ok then return result else error(ok == nil and "The awaited Promise was cancelled" or result, 2) end end function TS.add(a, b) if typeof(a) == TYPE_STRING or typeof(b) == TYPE_STRING then return a .. b else return a + b end end -- array macro functions function TS.array_forEach(list, callback) for i = 1, #list do callback(list[i], i - 1, list) end end function TS.array_map(list, callback) local result = {} for i = 1, #list do result[i] = callback(list[i], i - 1, list) end return result end function TS.array_filter(list, callback) local result = {} for i = 1, #list do local v = list[i] if callback(v, i - 1, list) == true then result[#result + 1] = v end end return result end function TS.array_slice(list, startI, endI) local length = #list if not startI then startI = 0 end if not endI then endI = length end if startI < 0 then startI = length + startI end if endI < 0 then endI = length + endI end startI = startI + 1 endI = endI + 1 local result = {} for i = startI, endI - 1 do result[i - startI + 1] = list[i] end return result end function TS.array_splice(list, start, deleteCount, ...) local len = #list local actualStart if start < 0 then actualStart = math.max(len + start, 0) else actualStart = math.min(start, len) end local items = { ... } local itemCount = #items local actualDeleteCount if not start then actualDeleteCount = 0 elseif not deleteCount then actualDeleteCount = len - actualStart else actualDeleteCount = math.min(math.max(deleteCount, 0), len - actualStart) end local out = {} local k = 0 while k < actualDeleteCount do local from = actualStart + k if list[from + 1] then out[k + 1] = list[from + 1] end k = k + 1 end if itemCount < actualDeleteCount then k = actualStart while k < len - actualDeleteCount do local from = k + actualDeleteCount local to = k + itemCount if list[from + 1] then list[to + 1] = list[from + 1] else list[to + 1] = nil end k = k + 1 end k = len while k > len - actualDeleteCount + itemCount do list[k] = nil k = k - 1 end elseif itemCount > actualDeleteCount then k = len - actualDeleteCount while k > actualStart do local from = k + actualDeleteCount local to = k + itemCount if list[from] then list[to] = list[from] else list[to] = nil end k = k - 1 end end k = actualStart for i = 1, #items do list[k + 1] = items[i] k = k + 1 end k = #list while k > len - actualDeleteCount + itemCount do list[k] = nil k = k - 1 end return out end function TS.array_some(list, callback) for i = 1, #list do if callback(list[i], i - 1, list) == true then return true end end return false end function TS.array_every(list, callback) for i = 1, #list do if callback(list[i], i - 1, list) == false then return false end end return true end function TS.array_indexOf(list, value, fromIndex) if fromIndex == nil then fromIndex = 0 end fromIndex = fromIndex + 1 for i = fromIndex, #list do if value == list[i] then return i - 1 end end return -1 end function TS.array_lastIndexOf(list, value, fromIndex) if fromIndex == nil then fromIndex = #list - 1 end fromIndex = fromIndex + 1 for i = fromIndex, 1, -1 do if value == list[i] then return i - 1 end end return -1 end function TS.array_reverse(list) local result = {} for i = 1, #list do result[i] = list[#list - i + 1] end return result end function TS.array_reduce(list, callback, initialValue) local start = 1 if not initialValue then initialValue = list[start] start = start + 1 end local accumulator = initialValue for i = start, #list do accumulator = callback(accumulator, list[i], i) end return accumulator end function TS.array_reduceRight(list, callback, initialValue) local start = #list if not initialValue then initialValue = list[start] start = start - 1 end local accumulator = initialValue for i = start, 1, -1 do accumulator = callback(accumulator, list[i], i) end return accumulator end function TS.array_shift(list) return table.remove(list, 1) end function TS.array_unshift(list, ...) local args = { ... } for i = #list, 1, -1 do list[i + #args] = list[i] end for i = 1, #args do list[i] = args[i] end return #list end function TS.array_concat(list, ...) local args = { ... } local result = {} for i = 1, #list do result[i] = list[i] end for i = 1, #args do local value = args[i] for j = 1, #value do result[#result + 1] = value[j] end end return result end function TS.array_push(list, ...) local args = { ... } for i = 1, #args do list[#list + 1] = args[i] end end function TS.array_pop(list) local length = #list; local lastValue = list[length] list[length] = nil return lastValue end function TS.array_join(list, separator) if #list == 0 then return "" end if not separator then separator = ", " end local result = tostring(list[1]) for i = 2, #list do result = result .. separator .. tostring(list[i]) end return result end function TS.array_find(list, callback) for i = 1, #list do if callback(list[i], i - 1, list) == true then return list[i] end end end -- map macro functions function TS.map_new(value) local result = {} for _, pair in pairs(value) do result[pair[1]] = pair[2] end return result end function TS.map_clear(map) for key in pairs(map) do map[key] = nil end end function TS.map_delete(map, key) local has = TS.map_has(map, key) if has then map[key] = nil end return has end function TS.map_size(map) local result = 0 for _ in pairs(map) do result = result + 1 end return result end function TS.map_entries(map) local result = {} for key, value in pairs(map) do table.insert(result, {key, value}) end return result end function TS.map_forEach(map, callback) for key, value in pairs(map) do callback(value, key, map) end end function TS.map_get(map, key) return map[key] end function TS.map_has(map, key) return map[key] ~= nil end function TS.map_keys(map) local result = {} for key in pairs(map) do table.insert(result, key) end return result end function TS.map_set(map, key, value) map[key] = value return map end function TS.map_values(map) local result = {} for _, value in pairs(map) do table.insert(result, value) end return result end -- set macro functions function TS.set_new(value) local result = {} for _, v in pairs(value) do result[v] = true end return result end function TS.set_add(set, value) set[value] = true return set end TS.set_clear = TS.map_clear function TS.set_delete(set, value) local result = TS.set_has(set, value) set[value] = nil return result end function TS.set_forEach(set, callback) for key in pairs(set) do callback(key, key, set) end end TS.set_has = TS.map_has function TS.set_entries(map) local result = {} for key in pairs(map) do table.insert(result, {key, key}) end return result end TS.set_values = TS.map_keys TS.set_keys = TS.map_keys TS.set_size = TS.map_size -- string macro functions function TS.string_split(input, sep) local result = {} local count = 0 for str in input:gmatch(sep == "" and "." or "[^" .. sep .. "]+") do count = count + 1 result[count] = str end return result end -- Object static functions function TS.Object_keys(object) local result = {} for key in pairs(object) do result[#result + 1] = key end return result end function TS.Object_values(object) local result = {} for _, value in pairs(object) do result[#result + 1] = value end return result end function TS.Object_entries(object) local result = {} for key, value in pairs(object) do result[#result + 1] = {key, value} end return result end function TS.Object_assign(toObj, ...) local args = { ... } for i = 1, #args do for key, value in pairs(args[i]) do toObj[key] = value end end return toObj end return TS
local utf8 = require "utf8" local Timer = require "hump.timer" local class = require "class" local Word = class() --- Create a new Word instance. -- @param font the font used to display the word -- @param text the rendered text function Word:initialize(font, text) self.font = font self.chars = {utf8.codepoint(text, 1, #text)} self.cursor = 1 self.x = 0 self.y = 0 self.a = 1 end --- Get the next letter, pointed by the cursor. -- @return the letter function Word:get_letter() return utf8.char(self.chars[self.cursor]) end --- Set the next letter as consumed. -- @return whether the word is finished or not function Word:consume_letter() self.cursor = self.cursor + 1 return self.cursor > #self.chars end --- Display the word on screen. function Word:draw() local y = self.y + (love.graphics.getHeight() - self.font:getHeight()) / 2 local w = love.graphics.getWidth() love.graphics.setColor(1, 1, 1, self.a) love.graphics.printf({ {1, 1, 1}, utf8.char(unpack(self.chars, 1, self.cursor - 1)), {1, 1, 1, 0.5}, utf8.char(unpack(self.chars, self.cursor)) }, self.x, y, w, "center") end --- Tween the word attributes. -- @see hump.timer function Word:tween(duration, ...) Timer.tween(duration, self, ...) end return Word
pcl = require 'pcl' v = pcl.CloudViewer() s = pcl.OpenNI2Stream() s:start() while true do local c = s:read() v:showCloud(c) collectgarbage() end
local client = getLocalPlayer() local trucks = {[515]=true, [514]=true, [403]=true} local assignmentSet = false function enterTruck(thePlayer, Xdel, Ydel, Zdel) if (assignmentSet) then return end if (Xdel and Ydel and Zdel) then truckerMarker = createMarker(Xdel, Ydel, Zdel, "cylinder", 5, 200, 200, 100, 150) truckerBlip = createBlip(Xdel, Ydel, Zdel, 51) local zone = getZoneName(Xdel, Ydel, Zdel) outputChatBox("#d9534f[CAMINHONEIRO] #FFFFFFLeve a carga até o comprador, no local indicado no seu mini-mapa: "..zone..".",255, 255, 255, true ) addEventHandler("onClientMarkerHit", truckerMarker, truckerHitsMarker) local Xp, Yp, Zp = getElementPosition(client) assignmentSet = true else triggerServerEvent("trucker:getPoint", client, client) end end addEvent("trucker:sendPoint", true) addEventHandler("trucker:sendPoint", client, enterTruck) function newTruckerAssignment() local theVehicle = getPedOccupiedVehicle(client) if (not theVehicle) then return end local model = getElementModel(theVehicle) if (not trucks[model]) then outputChatBox("#d9534f[CAMINHONEIRO] #FFFFFFVocê precisa estar usando o caminhão da empresa para concluir o trampo.",255, 255, 255, true ) return end local theDriver = getVehicleController(theVehicle) if (theDriver ~= client) then return end enterTruck() end function truckerHitsMarker(hitPlayer,source) if (hitPlayer ~= client) then return end local theVehicle = getPedOccupiedVehicle(hitPlayer) local model = getElementModel(theVehicle) if (not theVehicle) then return end if (not trucks[model]) then outputChatBox("#d9534f[CAMINHONEIRO] #FFFFFFVocê precisa estar usando o caminhão da empresa para receber o pagamento.",255, 255, 255, true ) return end if (getVehicleController(theVehicle) ~= client) then return end triggerServerEvent("trucker:giveMoney", client) endJob() setTimer(fadeOut, 2000, 1) setTimer(newTruckerAssignment, 5000, 1) fadeCamera(false, 1) end function onExitTruckDestroyMarker(thePlayer) if (thePlayer ~= client) then return end local model = getElementModel(source) if (trucks[model] and assignmentSet) then if isElement(truckerMarker) then destroyElement(truckerMarker) end if isElement(truckerBlip) then destroyElement(truckerBlip) end assignmentSet = false end end addEventHandler("onClientVehicleExit",getRootElement(),onExitTruckDestroyMarker) function fadeOut() fadeCamera(true, 1) end function endJob() if (assignmentSet == false) then return end assignmentSet = false if (isElement(truckerMarker)) then removeEventHandler("onClientMarkerHit", truckerMarker, truckerHitsMarker) destroyElement(truckerMarker) end if (isElement(truckerBlip)) then destroyElement(truckerBlip) end end addEvent("endJob",true) addEventHandler("endJob",getRootElement(),endJob)
--[[ © CloudSixteen.com do not share, re-distribute or modify without permission of its author (kurozael@gmail.com). Clockwork was created by Conna Wiles (also known as kurozael.) http://cloudsixteen.com/license/clockwork.html --]] CW_ENGLISH = Clockwork.lang:GetTable("English"); CW_ENGLISH["ObserverReset"] = "Observer Reset"; CW_ENGLISH["ObserverResetDesc"] = "Whether or not observer mode resets the player's position to where they were originally.";
-- This file is subject to copyright - contact swampservers@gmail.com for more information. local Entity = FindMetaTable("Entity")
modifier_creature_techies_land_mine = class({}) -------------------------------------------------------------------------------- function modifier_creature_techies_land_mine:OnCreated( kv ) if IsServer() then self.radius = self:GetAbility():GetSpecialValueFor( "radius" ) self.activation_delay = self:GetAbility():GetSpecialValueFor( "activation_delay" ) self.damage = self:GetAbility():GetSpecialValueFor( "damage" ) --self.proximity_threshold = self:GetAbility():GetSpecialValueFor( "proximity_threshold" ) self:StartIntervalThink( self.activation_delay ) end end -------------------------------------------------------------------------------- function modifier_creature_techies_land_mine:CheckState() local state = {} if IsServer() then state[MODIFIER_STATE_ROOTED] = true state[MODIFIER_STATE_MAGIC_IMMUNE] = true state[MODIFIER_STATE_INVULNERABLE] = true state[MODIFIER_STATE_ATTACK_IMMUNE] = true state[MODIFIER_STATE_NO_HEALTH_BAR] = true state[MODIFIER_STATE_UNSELECTABLE] = true state[MODIFIER_STATE_NO_UNIT_COLLISION] = true end return state end -------------------------------------------------------------------------------- function modifier_creature_techies_land_mine:OnIntervalThink() if IsServer() then local enemies = FindUnitsInRadius( self:GetParent():GetTeamNumber(), self:GetParent():GetOrigin(), self:GetCaster(), self.radius, DOTA_UNIT_TARGET_TEAM_ENEMY, DOTA_UNIT_TARGET_HERO + DOTA_UNIT_TARGET_BASIC, DOTA_UNIT_TARGET_FLAG_NOT_ANCIENTS, 0, false ) if #enemies > 0 then for _, enemy in pairs( enemies ) do if enemy ~= nil and ( not enemy:IsMagicImmune() ) and ( not enemy:IsInvulnerable() ) then local DamageInfo = { victim = enemy, attacker = self:GetParent(), ability = self:GetAbility(), damage = self.damage, damage_type = DAMAGE_TYPE_MAGICAL, } ApplyDamage( DamageInfo ) end end end local nFXIndex = ParticleManager:CreateParticle( "particles/units/heroes/hero_techies/techies_land_mine_explode.vpcf", PATTACH_CUSTOMORIGIN, nil ) ParticleManager:SetParticleControl( nFXIndex, 0, self:GetParent():GetOrigin() ) ParticleManager:SetParticleControl( nFXIndex, 1, Vector( 1.0, 1.0, radius ) ) ParticleManager:SetParticleControl( nFXIndex, 2, Vector( 1.0, 1.0, radius ) ) ParticleManager:ReleaseParticleIndex( nFXIndex ) EmitSoundOn( "TreasureChest.MineTrap.Detonate", self:GetParent() ) self:GetParent():ForceKill( false ) end end
defaultProfile = { ["sound_alert"] = false, ["show_player_messages"] = true, ["show_player_mentions"] = true, ["channels"] = {"world","LookingForGroup"}, ["banned"] = {}, ["dungeons"] = {}, ["dungeons_roles"] = {}, ["dungeons_types"] = {}, ["raids"] = {}, ["raids_roles"] = {}, ["other"] = {}, } exampleProfie = { ["sound_alert"] = false, ["show_player_messages"] = true, ["show_player_mentions"] = true, ["channels"] = { "world", -- [1] "LookingForGroup", -- [2] }, ["banned"] = { "WTS", -- [1] "wtb", -- [2] "www", -- [3] }, ["dungeons"] = { "scholo", -- [1] "strat", -- [2] }, ["dungeons_roles"] = { "tank", -- [1] }, ["dungeons_types"] = { "nm", -- [1] "hc", -- [2] }, ["raids"] = { "mc", -- [1] "molten core", -- [2] "onyxia", -- [3] }, ["raids_roles"] = { "tank", -- [1] "dps", -- [2] }, ["other"] = { "thunderfury", -- [1] "help", -- [2] }, } globalSettingsDefault = { ["profiles"] = { ["Default"] = defaultProfile, ["Example"] = exampleProfie, }, } CharSettingsDefault = { ["enabled"] = true, ["profile"] = "Default" } local version = "1.1.0" local addonStr = "|cff009674ClassicChatFilter|cffffffff" local LibDropDown = LibStub:GetLibrary("LibUIDropDownMenu-4.0") local ccf = CreateFrame("Frame", addonName); local pname, pserver = UnitName("player"); local totalelapsed = 0 ccf:RegisterEvent("VARIABLES_LOADED"); ccf:RegisterEvent("ADDON_LOADED"); ccf:SetScript("OnEvent", function(self, event, arg1) self[event](self, arg1) end); function SlashHandler(arg) if(arg == "help") then print(addonStr.." available commands :") print("/ccf or /classicchatfilter to open the configuration panel.") print("/ccf disable to temporarily disable the addon.") print("/ccf enable to re-enable the addon.") print("/ccf toggle to toggle between enable and disable (useful for macros).") print("/ccf sound to toggle current profile's sound alert option.") elseif(arg == "enable") then CharSettings.enabled = true RefreshValues() print(addonStr.." has been re-enabled.") elseif(arg == "disable") then CharSettings.enabled = true RefreshValues() print(addonStr.." has been temporarily disabled.") elseif(arg == "toggle") then CharSettings.enabled = not CharSettings.enabled RefreshValues() print(addonStr.." has been toggled "..((CharSettings.enabled and "ON") or "OFF")) elseif(arg == "sound") then SetCurrentValue("sound_alert", not GetCurrentValue("sound_alert")) print(addonStr.." sound alert toggled "..((GetCurrentValue("sound_alert") and "ON") or "OFF")) else InterfaceOptionsFrame_OpenToCategory("ClassicChatFilter") InterfaceOptionsFrame_OpenToCategory("ClassicChatFilter") InterfaceOptionsFrame_OpenToCategory("ClassicChatFilter") end end function ccf:VARIABLES_LOADED() --RefreshValues() end function ccf:ADDON_LOADED(addon) if(addon == "ClassicChatFilter") then SlashCmdList["CLASSICCHATFILTER"] = SlashHandler; SLASH_CLASSICCHATFILTER1 = "/classicchatfilter"; SLASH_CLASSICCHATFILTER2 = "/ccf"; InitGlobalSettings() InitCharSettings() CheckDefault() CheckProfile() RenderOptions() print("|cff009674ClassicChatFilter v"..version.." loaded. |cffffffffType /ccf to configure.") end end function CheckProfile() if(not GlobalSettings["profiles"][CharSettings["profile"]]) then CharSettings["profile"] = "Default" end end function CheckDefault() if(not GlobalSettings["profiles"]["Default"]) then GlobalSettings["profiles"]["Default"] = DeepCopy(defaultProfile) end end function InitGlobalSettings() if(not GlobalSettings) then GlobalSettings = DeepCopy(globalSettingsDefault) else -- copy defaults to conf if key not exists for k, v in pairs(globalSettingsDefault) do if(GlobalSettings[k] == nil) then GlobalSettings[k] = DeepCopy(globalSettingsDefault[k]); end end -- remove keys not in defaults anymore for k, v in pairs(GlobalSettings) do if(globalSettingsDefault[k] == nil) then GlobalSettings[k] = nil; end end end end function InitCharSettings() if (not CharSettings) then CharSettings = DeepCopy(CharSettingsDefault) else -- copy defaults to conf if key not exists for k, v in pairs(CharSettingsDefault) do if (CharSettings[k] == nil) then CharSettings[k] = DeepCopy(CharSettingsDefault[k]); end end -- remove keys not in defaults anymore for k, v in pairs(CharSettings) do if (CharSettingsDefault[k] == nill) then CharSettings[k] = nil; end end end end StaticPopupDialogs["CCF_PROFILE_RENAME"] = { text = "Rename profile", button1 = OKAY, button2 = CANCEL, OnShow = function(self) self.editBox:SetScript("OnEnterPressed", function() RenameProfile(self.editBox:GetText()) StaticPopup_Hide("CCF_PROFILE_RENAME") end) self.editBox:SetScript("OnEscapePressed", function() StaticPopup_Hide("CCF_PROFILE_RENAME") end) end, OnAccept = function(self) RenameProfile(self.editBox:GetText()) StaticPopup_Hide("CCF_PROFILE_RENAME") end, hasEditBox = true, timeout = 0, exclusive = 0, showAlert = 1, whileDead = 1, hideOnEscape = 1 } StaticPopupDialogs["CCF_PROFILE_COPY"] = { text = "New copied profile", button1 = OKAY, button2 = CANCEL, OnShow = function(self) self.editBox:SetScript("OnEnterPressed", function() CopyProfile(self.editBox:GetText()) StaticPopup_Hide("CCF_PROFILE_COPY") end) self.editBox:SetScript("OnEscapePressed", function() StaticPopup_Hide("CCF_PROFILE_COPY") end) end, OnAccept = function(self) CopyProfile(self.editBox:GetText()) StaticPopup_Hide("CCF_PROFILE_COPY") end, hasEditBox = true, timeout = 0, exclusive = 0, showAlert = 1, whileDead = 1, hideOnEscape = 1 } StaticPopupDialogs["CCF_PROFILE_ADD"] = { text = "New profile", button1 = OKAY, button2 = CANCEL, OnShow = function(self) self.editBox:SetScript("OnEnterPressed", function() CreateProfile(self.editBox:GetText()) StaticPopup_Hide("CCF_PROFILE_ADD") end) self.editBox:SetScript("OnEscapePressed", function() StaticPopup_Hide("CCF_PROFILE_ADD") end) end, OnAccept = function(self) CreateProfile(self.editBox:GetText()) StaticPopup_Hide("CCF_PROFILE_ADD") end, hasEditBox = true, timeout = 0, exclusive = 0, showAlert = 1, whileDead = 1, hideOnEscape = 1 } StaticPopupDialogs["CCF_PROFILE_DELETE"] = { text = "Delete profile ?", button1 = DELETE, button2 = CANCEL, OnAccept = function(self) DeleteCurrentProfile() StaticPopup_Hide("CCF_PROFILE_DELETE") end, timeout = 0, exclusive = 0, showAlert = 1, whileDead = 1, hideOnEscape = 1 } function RenderOptions() local leftMargin = 20 local topMargin = -20 local options = CreateFrame("FRAME","ccf_options"); options.name = "ClassicChatFilter"; InterfaceOptions_AddCategory(options); local header = options:CreateFontString(nil, "ARTWORK","GameFontNormalLarge"); header:SetPoint("TOPLEFT", leftMargin, topMargin); header:SetText("ClassicChatFilter"); local ver=options:CreateFontString(nil,"ARTWORK","GameFontNormalSmall"); ver:SetPoint("BOTTOMLEFT",header,"BOTTOMRIGHT",1,0); ver:SetTextColor(0.7,0.7,0.7); ver:SetText("v"..version); enabledButton = CreateFrame("CheckButton", "ccf_enabledButton", options, "ChatConfigCheckButtonTemplate"); enabledButton:SetPoint("LEFT", ver, "RIGHT", 5, 0) enabledButton.tooltip = "Enable the ClassicChatFilter addon."; _G[enabledButton:GetName().."Text"]:SetText("Enabled"); enabledButton:SetScript("OnClick", function(self) CharSettings.enabled = self:GetChecked(); end) local welcomeText=options:CreateFontString(nil,"ARTWORK","GameFontNormalSmall"); welcomeText:SetPoint("TOPLEFT", header, "BOTTOMLEFT", 0, -5); welcomeText:SetTextColor(0.7,0.7,0.7); welcomeText:SetJustifyH("LEFT"); welcomeText:SetWidth(590); welcomeText:SetText("|cffb3b3b3Welcome to ClassicChatFilter!" .."\n\nHere you can setup whitelisted and blacklisted keywords, separated by a |cffb3ffb3comma|cffb3b3b3 (|cffb3ffb3,|cffb3b3b3)." .."\nThey are case insensitive and can contain spaces (or other special characters)." .."\n\nSpecial |cffffffffDungeons|cffb3b3b3 and |cffffffffRaids|cffb3b3b3 whitelists can be |cffffb3b3combinated|cffb3b3b3 with their respective |cffffffffRoles|cffb3b3b3 for more accurate filtering." .."\nExample : |cffb3b3ffscholo,strat|cffb3b3b3 |cffffb3b3combinated|cffb3b3b3 with |cffb3b3fftank|cffb3b3b3 would only show messages containing |cffb3b3fftank|cffb3b3b3 |cffffb3b3and|cffb3b3b3 (|cffb3b3ffscholo|cffb3b3b3 |cffb3ffb3or|cffb3b3b3 |cffb3b3ffstrat|cffb3b3b3)." .."\n\n|cffb3b3b3An example setup is available by selecting the |cffffffffExample|cffb3b3b3 profile.") local profilesDropDownText = options:CreateFontString(nil, "ARTWORK","GameFontNormal"); profilesDropDownText:SetPoint("TOPLEFT", welcomeText, "BOTTOMLEFT", 0, -20); profilesDropDownText:SetText("Profile selection"); profilesDropDown = LibDropDown:Create_UIDropDownMenu("ccf_profilesDropdown", options); profilesDropDown:SetPoint("LEFT", profilesDropDownText, "RIGHT", 5, -4) LibDropDown:UIDropDownMenu_SetWidth(profilesDropDown, 150); LibDropDown:UIDropDownMenu_SetButtonWidth(profilesDropDown, 124); LibDropDown:UIDropDownMenu_JustifyText(profilesDropDown, "LEFT"); profilesDropDownText.tooltip = "Select the profile to use on this character." renameProfileButton = CreateFrame("Button", "ccf_renameProfileButton", options, "OptionsButtonTemplate"); renameProfileButton:SetWidth(25) renameProfileButton:SetPoint("LEFT", profilesDropDown, "RIGHT", 0, 2); renameProfileButton.tooltipText = "Rename this profile."; renameProfileButton:SetScript("OnClick", function(self) StaticPopup_Show("CCF_PROFILE_RENAME") end); _G[renameProfileButton:GetName().."Text"]:SetText("R"); renameProfileButton.alwaysShowTooltip = true renameProfileButton.tooltipText = "Rename this profile." renameProfileButton:SetScript("OnEnter", function(self) GameTooltip:SetOwner(renameProfileButton, "ANCHOR_TOPLEFT") GameTooltip:ClearLines() GameTooltip:AddLine(self.tooltipText) GameTooltip:Show() end); copyProfileButton = CreateFrame("Button", "ccf_copyProfileButton", options, "OptionsButtonTemplate"); copyProfileButton:SetWidth(25) copyProfileButton:SetPoint("LEFT", renameProfileButton, "RIGHT", 2, 0); copyProfileButton.tooltipText = "Rename this profile."; copyProfileButton:SetScript("OnClick", function(self) StaticPopup_Show("CCF_PROFILE_COPY") end); _G[copyProfileButton:GetName().."Text"]:SetText("C"); copyProfileButton.alwaysShowTooltip = true copyProfileButton.tooltipText = "Copy this profile to a new one." copyProfileButton:SetScript("OnEnter", function(self) GameTooltip:SetOwner(copyProfileButton, "ANCHOR_TOPLEFT") GameTooltip:ClearLines() GameTooltip:AddLine(self.tooltipText) GameTooltip:Show() end); newProfileButton = CreateFrame("Button", "ccf_newProfileButton", options, "OptionsButtonTemplate"); newProfileButton:SetWidth(25) newProfileButton:SetPoint("LEFT", copyProfileButton, "RIGHT", 2, 0); newProfileButton:SetScript("OnClick", function(self) StaticPopup_Show("CCF_PROFILE_ADD") end); _G[newProfileButton:GetName().."Text"]:SetText("+"); newProfileButton.alwaysShowTooltip = true newProfileButton.tooltipText = "Create a new profile." newProfileButton:SetScript("OnEnter", function(self) GameTooltip:SetOwner(newProfileButton, "ANCHOR_TOPLEFT") GameTooltip:ClearLines() GameTooltip:AddLine(self.tooltipText) GameTooltip:Show() end); deleteProfileButton = CreateFrame("Button", "ccf_deleteProfileButton", options, "OptionsButtonTemplate"); deleteProfileButton:SetWidth(25) deleteProfileButton:SetPoint("LEFT", newProfileButton, "RIGHT", 2, 0); deleteProfileButton:SetScript("OnClick", function(self) StaticPopup_Show("CCF_PROFILE_DELETE") end); _G[deleteProfileButton:GetName().."Text"]:SetText("-"); deleteProfileButton.tooltipText = "Delete this profile." deleteProfileButton:SetScript("OnEnter", function(self) GameTooltip:SetOwner(deleteProfileButton, "ANCHOR_TOPLEFT") GameTooltip:ClearLines() GameTooltip:AddLine(self.tooltipText) GameTooltip:Show() end); soundalertbutton = CreateFrame("CheckButton", "ccf_soundalertbutton", options, "ChatConfigCheckButtonTemplate"); soundalertbutton:SetPoint("TOPLEFT", profilesDropDownText, "BOTTOMLEFT", 0, -20) soundalertbutton.tooltip = "Play a sound alert when a message goes through the filter"; _G[soundalertbutton:GetName().."Text"]:SetText("Play a sound alert when a message goes through the filter"); soundalertbutton:SetScript("OnClick", function(self) SetCurrentValue("sound_alert", self:GetChecked()); end) pmessagesButton = CreateFrame("CheckButton", "ccf_pmessagesButton", options, "ChatConfigCheckButtonTemplate"); pmessagesButton:SetPoint("TOPLEFT", soundalertbutton, "BOTTOMLEFT", 0, 0) pmessagesButton.tooltip = "Always show your own messages."; _G[pmessagesButton:GetName().."Text"]:SetText("Always show player's messages"); pmessagesButton:SetScript("OnClick", function(self) SetCurrentValue("show_player_messages", self:GetChecked()); end) pmentionsButton = CreateFrame("CheckButton", "ccf_pmentionsButton", options, "ChatConfigCheckButtonTemplate"); pmentionsButton:SetPoint("TOPLEFT", pmessagesButton, "BOTTOMLEFT", 0, 0) pmentionsButton.tooltip = "Always show messages containing your character's name."; _G[pmentionsButton:GetName().."Text"]:SetText("Always show player mentions"); pmentionsButton:SetScript("OnClick", function(self) SetCurrentValue("show_player_mentions", self:GetChecked()); end) local channelsBoxText = options:CreateFontString(nil, "ARTWORK","GameFontWhite"); channelsBoxText:SetPoint("TOPLEFT", pmentionsButton, "BOTTOMLEFT", 0, -10); channelsBoxText:SetText("Channels :"); channelsCount=options:CreateFontString(nil,"ARTWORK","GameFontNormalSmall"); channelsCount:SetPoint("BOTTOMLEFT", channelsBoxText,"BOTTOMRIGHT", 4, 0); channelsCount:SetTextColor(0.7,1,0.7) channelsBox = CreateFrame("editbox", "ccf_channelsBox", options, "InputBoxTemplate") channelsBox:SetPoint("TOPLEFT", channelsBoxText, "BOTTOMLEFT", 0, 0); channelsBox:SetPoint("RIGHT", options, "RIGHT", -10, 0) channelsBox:SetHeight(25) channelsBox:SetAutoFocus(false) channelsBox:ClearFocus() channelsBox:SetScript("OnEscapePressed", function(self) SetCurrentValue("channels", StringToTable(self:GetText())) self:SetAutoFocus(false) self:ClearFocus() end) channelsBox:SetScript("OnEnterPressed", function(self) SetCurrentValue("channels", StringToTable(self:GetText())) self:SetAutoFocus(false) self:ClearFocus() end) channelsBox:SetScript("OnEditFocusLost", function(self) SetCurrentValue("channels", StringToTable(self:GetText())) self:SetAutoFocus(false) self:ClearFocus() end) channelsBox:SetScript("OnEditFocusGained", function(self) self:SetAutoFocus(true) end) local channelsHelp=options:CreateFontString(nil,"ARTWORK","GameFontNormalSmall"); channelsHelp:SetPoint("BOTTOMRIGHT", channelsBox,"TOPRIGHT",0,0); channelsHelp:SetTextColor(0.7,0.7,0.7); channelsHelp:SetText("Channels affected by the filters"); local channelsTip=options:CreateFontString(nil,"ARTWORK","GameFontNormal"); channelsTip:SetPoint("LEFT", channelsBox,"LEFT",0,0); channelsTip:SetTextColor(1,1,1); local bannedBoxText = options:CreateFontString(nil, "ARTWORK","GameFontWhite"); bannedBoxText:SetPoint("TOPLEFT", channelsBox, "BOTTOMLEFT", 0, -5); bannedBoxText:SetText("Blacklisted keywords :"); bannedCount=options:CreateFontString(nil,"ARTWORK","GameFontNormalSmall"); bannedCount:SetPoint("BOTTOMLEFT", bannedBoxText,"BOTTOMRIGHT", 4, 0); bannedCount:SetTextColor(0.7,1,0.7) bannedBox = CreateFrame("editbox", "ccf_bannedBox", options, "InputBoxTemplate") bannedBox:SetPoint("TOPLEFT", bannedBoxText, "BOTTOMLEFT", 0, 0); bannedBox:SetPoint("RIGHT", options, "RIGHT", -10, 0) bannedBox:SetHeight(25) bannedBox:SetAutoFocus(false) bannedBox:ClearFocus() bannedBox:SetScript("OnEscapePressed", function(self) SetCurrentValue("banned", StringToTable(self:GetText())) self:SetAutoFocus(false) self:ClearFocus() end) bannedBox:SetScript("OnEnterPressed", function(self) SetCurrentValue("banned", StringToTable(self:GetText())) self:SetAutoFocus(false) self:ClearFocus() end) bannedBox:SetScript("OnEditFocusLost", function(self) SetCurrentValue("banned", StringToTable(self:GetText())) self:SetAutoFocus(false) self:ClearFocus() end) bannedBox:SetScript("OnEditFocusGained", function(self) self:SetAutoFocus(true) end) local bannedHelp=options:CreateFontString(nil,"ARTWORK","GameFontNormalSmall"); bannedHelp:SetPoint("BOTTOMRIGHT", bannedBox,"TOPRIGHT",0,0); bannedHelp:SetTextColor(0.7,0.7,0.7); bannedHelp:SetText("Messages with blacklisted keywords will be hidden"); local bannedTip=options:CreateFontString(nil,"ARTWORK","GameFontNormal"); bannedTip:SetPoint("LEFT", bannedBox,"LEFT",0,0); bannedTip:SetTextColor(1,1,1); local dungeonsBoxText = options:CreateFontString(nil, "ARTWORK","GameFontWhite"); dungeonsBoxText:SetPoint("TOPLEFT", bannedBox, "BOTTOMLEFT", 0, -5); dungeonsBoxText:SetText("Dungeons whitelist :"); dungeonsCount=options:CreateFontString(nil,"ARTWORK","GameFontNormalSmall"); dungeonsCount:SetPoint("BOTTOMLEFT", dungeonsBoxText,"BOTTOMRIGHT", 4, 0); dungeonsCount:SetTextColor(0.7,1,0.7) dungeonsBox = CreateFrame("editbox", "ccf_dungeonsBox", options, "InputBoxTemplate") dungeonsBox:SetPoint("TOPLEFT", dungeonsBoxText, "BOTTOMLEFT", 0, 0); dungeonsBox:SetHeight(25) dungeonsBox:SetWidth(200) dungeonsBox:SetAutoFocus(false) dungeonsBox:ClearFocus() dungeonsBox:SetScript("OnEscapePressed", function(self) SetCurrentValue("dungeons", StringToTable(self:GetText())) self:SetAutoFocus(false) self:ClearFocus() end) dungeonsBox:SetScript("OnEnterPressed", function(self) SetCurrentValue("dungeons", StringToTable(self:GetText())) self:SetAutoFocus(false) self:ClearFocus() end) dungeonsBox:SetScript("OnEditFocusLost", function(self) SetCurrentValue("dungeons", StringToTable(self:GetText())) self:SetAutoFocus(false) self:ClearFocus() end) dungeonsBox:SetScript("OnEditFocusGained", function(self) self:SetAutoFocus(true) end) local dungeonsHelp=options:CreateFontString(nil,"ARTWORK","GameFontNormalSmall"); dungeonsHelp:SetPoint("BOTTOMRIGHT", dungeonsBox,"TOPRIGHT",0,0); dungeonsHelp:SetTextColor(0.7,0.7,0.7); dungeonsHelp:SetText(""); local dungeonsTip=options:CreateFontString(nil,"ARTWORK","GameFontNormal"); dungeonsTip:SetPoint("LEFT", dungeonsBox,"LEFT",0,0); dungeonsTip:SetTextColor(1,1,1); local dungeonsAnd=options:CreateFontString(nil,"ARTWORK","GameFontNormalSmall"); dungeonsAnd:SetPoint("LEFT", dungeonsBox,"RIGHT", 2, 0); dungeonsAnd:SetTextColor(0.7,0.7,0.7); dungeonsAnd:SetText("|cffff9393and|cff939393"); local dungeonsRolesBoxText = options:CreateFontString(nil, "ARTWORK","GameFontWhite"); dungeonsRolesBoxText:SetPoint("BOTTOMLEFT", dungeonsBox, "TOPRIGHT", 30, 0); dungeonsRolesBoxText:SetText("Dungeon roles :"); dungeonsRolesCount=options:CreateFontString(nil,"ARTWORK","GameFontNormalSmall"); dungeonsRolesCount:SetPoint("BOTTOMLEFT", dungeonsRolesBoxText,"BOTTOMRIGHT", 4, 0); dungeonsRolesCount:SetTextColor(0.7,1,0.7) dungeonsRolesBox = CreateFrame("editbox", "ccf_dungeonsRolesBox", options, "InputBoxTemplate") dungeonsRolesBox:SetPoint("TOPLEFT", dungeonsRolesBoxText, "BOTTOMLEFT", 0, 0); --dungeonsRolesBox:SetPoint("RIGHT", options, "RIGHT", -10, 0) dungeonsRolesBox:SetHeight(25) dungeonsRolesBox:SetWidth(200) dungeonsRolesBox:SetAutoFocus(false) dungeonsRolesBox:ClearFocus() dungeonsRolesBox:SetScript("OnEscapePressed", function(self) SetCurrentValue("dungeons_roles", StringToTable(self:GetText())) self:SetAutoFocus(false) self:ClearFocus() end) dungeonsRolesBox:SetScript("OnEnterPressed", function(self) SetCurrentValue("dungeons_roles", StringToTable(self:GetText())) self:SetAutoFocus(false) self:ClearFocus() end) dungeonsRolesBox:SetScript("OnEditFocusLost", function(self) SetCurrentValue("dungeons_roles", StringToTable(self:GetText())) self:SetAutoFocus(false) self:ClearFocus() end) dungeonsRolesBox:SetScript("OnEditFocusGained", function(self) self:SetAutoFocus(true) end) local dungeonsRolesHelp=options:CreateFontString(nil,"ARTWORK","GameFontNormalSmall"); dungeonsRolesHelp:SetPoint("BOTTOMRIGHT", dungeonsRolesBox,"TOPRIGHT",0,0); dungeonsRolesHelp:SetTextColor(0.7,0.7,0.7); dungeonsRolesHelp:SetText(""); local dungeonsRolesTip=options:CreateFontString(nil,"ARTWORK","GameFontNormal"); dungeonsRolesTip:SetPoint("LEFT", dungeonsRolesBox,"LEFT",0,0); dungeonsRolesTip:SetTextColor(1,1,1); local dungeonsRolesAnd=options:CreateFontString(nil,"ARTWORK","GameFontNormalSmall"); dungeonsRolesAnd:SetPoint("LEFT", dungeonsRolesBox,"RIGHT", 2, 0); dungeonsRolesAnd:SetTextColor(0.7,0.7,0.7); dungeonsRolesAnd:SetText("|cffff9393and|cff939393"); local dungeonsTypesBoxText = options:CreateFontString(nil, "ARTWORK","GameFontWhite"); dungeonsTypesBoxText:SetPoint("BOTTOMLEFT", dungeonsRolesBox, "TOPRIGHT", 30, 0); dungeonsTypesBoxText:SetText("Dungeon types :"); dungeonsTypesCount=options:CreateFontString(nil,"ARTWORK","GameFontNormalSmall"); dungeonsTypesCount:SetPoint("BOTTOMLEFT", dungeonsTypesBoxText,"BOTTOMRIGHT", 4, 0); dungeonsTypesCount:SetTextColor(0.7,1,0.7) dungeonsTypesBox = CreateFrame("editbox", "ccf_dungeonsTypeBox", options, "InputBoxTemplate") dungeonsTypesBox:SetPoint("TOPLEFT", dungeonsTypesBoxText, "BOTTOMLEFT", 0, 0); dungeonsTypesBox:SetHeight(25) dungeonsTypesBox:SetPoint("RIGHT", options, "RIGHT", -10, 0) dungeonsTypesBox:SetAutoFocus(false) dungeonsTypesBox:ClearFocus() dungeonsTypesBox:SetScript("OnEscapePressed", function(self) SetCurrentValue("dungeons_types", StringToTable(self:GetText())) self:SetAutoFocus(false) self:ClearFocus() end) dungeonsTypesBox:SetScript("OnEnterPressed", function(self) SetCurrentValue("dungeons_types", StringToTable(self:GetText())) self:SetAutoFocus(false) self:ClearFocus() end) dungeonsTypesBox:SetScript("OnEditFocusLost", function(self) SetCurrentValue("dungeons_types", StringToTable(self:GetText())) self:SetAutoFocus(false) self:ClearFocus() end) dungeonsTypesBox:SetScript("OnEditFocusGained", function(self) self:SetAutoFocus(true) end) local dungeonsTypesHelp=options:CreateFontString(nil,"ARTWORK","GameFontNormalSmall"); dungeonsTypesHelp:SetPoint("BOTTOMRIGHT", dungeonsTypesBox,"TOPRIGHT",0,0); dungeonsTypesHelp:SetTextColor(0.7,0.7,0.7); dungeonsTypesHelp:SetText(""); local dungeonsTypesTip=options:CreateFontString(nil,"ARTWORK","GameFontNormal"); dungeonsTypesTip:SetPoint("LEFT", dungeonsTypesBox,"LEFT",0,0); dungeonsTypesTip:SetTextColor(1,1,1); local raidsBoxText = options:CreateFontString(nil, "ARTWORK","GameFontWhite"); raidsBoxText:SetPoint("TOPLEFT", dungeonsBox, "BOTTOMLEFT", 0, -5); raidsBoxText:SetText("Raids whitelist :"); raidsCount=options:CreateFontString(nil,"ARTWORK","GameFontNormalSmall"); raidsCount:SetPoint("BOTTOMLEFT", raidsBoxText,"BOTTOMRIGHT", 4, 0); raidsCount:SetTextColor(0.7,1,0.7) raidsBox = CreateFrame("editbox", "ccf_raidsBox", options, "InputBoxTemplate") raidsBox:SetPoint("TOPLEFT", raidsBoxText, "BOTTOMLEFT", 0, 0); raidsBox:SetHeight(25) raidsBox:SetWidth(250) raidsBox:SetAutoFocus(false) raidsBox:ClearFocus() raidsBox:SetScript("OnEscapePressed", function(self) SetCurrentValue("raids", StringToTable(self:GetText())) self:SetAutoFocus(false) self:ClearFocus() end) raidsBox:SetScript("OnEnterPressed", function(self) SetCurrentValue("raids", StringToTable(self:GetText())) self:SetAutoFocus(false) self:ClearFocus() end) raidsBox:SetScript("OnEditFocusLost", function(self) SetCurrentValue("raids", StringToTable(self:GetText())) self:SetAutoFocus(false) self:ClearFocus() end) raidsBox:SetScript("OnEditFocusGained", function(self) self:SetAutoFocus(true) end) local raidsHelp=options:CreateFontString(nil,"ARTWORK","GameFontNormalSmall"); raidsHelp:SetPoint("BOTTOMRIGHT", raidsBox,"TOPRIGHT",0,0); raidsHelp:SetTextColor(0.7,0.7,0.7); raidsHelp:SetText(""); local raidsTip=options:CreateFontString(nil,"ARTWORK","GameFontNormal"); raidsTip:SetPoint("LEFT", raidsBox,"LEFT",0,0); raidsTip:SetTextColor(1,1,1); local raidsAnd=options:CreateFontString(nil,"ARTWORK","GameFontNormalSmall"); raidsAnd:SetPoint("LEFT", raidsBox,"RIGHT", 2, 0); raidsAnd:SetTextColor(0.7,0.7,0.7); raidsAnd:SetText("|cffff9393and|cff939393"); local raidsRolesBoxText = options:CreateFontString(nil, "ARTWORK","GameFontWhite"); raidsRolesBoxText:SetPoint("BOTTOMLEFT", raidsBox, "TOPRIGHT", 30, 0); raidsRolesBoxText:SetText("Raid roles whitelist :"); raidsRolesCount=options:CreateFontString(nil,"ARTWORK","GameFontNormalSmall"); raidsRolesCount:SetPoint("BOTTOMLEFT", raidsRolesBoxText,"BOTTOMRIGHT", 4, 0); raidsRolesCount:SetTextColor(0.7,1,0.7) raidsRolesBox = CreateFrame("editbox", "ccf_raidsRolesBox", options, "InputBoxTemplate") raidsRolesBox:SetPoint("TOPLEFT", raidsRolesBoxText, "BOTTOMLEFT", 0, 0); raidsRolesBox:SetPoint("RIGHT", options, "RIGHT", -10, 0) raidsRolesBox:SetHeight(25) raidsRolesBox:SetAutoFocus(false) raidsRolesBox:ClearFocus() raidsRolesBox:SetScript("OnEscapePressed", function(self) SetCurrentValue("raids_roles", StringToTable(self:GetText())) self:SetAutoFocus(false) self:ClearFocus() end) raidsRolesBox:SetScript("OnEnterPressed", function(self) SetCurrentValue("raids_roles", StringToTable(self:GetText())) self:SetAutoFocus(false) self:ClearFocus() end) raidsRolesBox:SetScript("OnEditFocusLost", function(self) SetCurrentValue("raids_roles", StringToTable(self:GetText())) self:SetAutoFocus(false) self:ClearFocus() end) raidsRolesBox:SetScript("OnEditFocusGained", function(self) self:SetAutoFocus(true) end) local raidsRolesHelp=options:CreateFontString(nil,"ARTWORK","GameFontNormalSmall"); raidsRolesHelp:SetPoint("BOTTOMRIGHT", raidsRolesBox,"TOPRIGHT",0,0); raidsRolesHelp:SetTextColor(0.7,0.7,0.7); raidsRolesHelp:SetText(""); local raidsRolesTip=options:CreateFontString(nil,"ARTWORK","GameFontNormal"); raidsRolesTip:SetPoint("LEFT", raidsRolesBox,"LEFT",0,0); raidsRolesTip:SetTextColor(1,1,1); local otherBoxText = options:CreateFontString(nil, "ARTWORK","GameFontWhite"); otherBoxText:SetPoint("TOPLEFT", raidsBox, "BOTTOMLEFT", 0, -5); otherBoxText:SetText("Other whitelisted keywords :"); otherCount=options:CreateFontString(nil,"ARTWORK","GameFontNormalSmall"); otherCount:SetPoint("BOTTOMLEFT", otherBoxText,"BOTTOMRIGHT", 4, 0); otherCount:SetTextColor(0.7,1,0.7) otherBox = CreateFrame("editbox", "ccf_otherBox", options, "InputBoxTemplate") otherBox:SetPoint("TOPLEFT", otherBoxText, "BOTTOMLEFT", 0, 0); otherBox:SetPoint("RIGHT", options, "RIGHT", -10, 0) otherBox:SetHeight(25) otherBox:SetAutoFocus(false) otherBox:ClearFocus() otherBox:SetScript("OnEscapePressed", function(self) SetCurrentValue("other", StringToTable(self:GetText())) self:SetAutoFocus(false) self:ClearFocus() end) otherBox:SetScript("OnEnterPressed", function(self) SetCurrentValue("other", StringToTable(self:GetText())) self:SetAutoFocus(false) self:ClearFocus() end) otherBox:SetScript("OnEditFocusLost", function(self) SetCurrentValue("other", StringToTable(self:GetText())) self:SetAutoFocus(false) self:ClearFocus() end) otherBox:SetScript("OnEditFocusGained", function(self) self:SetAutoFocus(true) end) local otherHelp=options:CreateFontString(nil,"ARTWORK","GameFontNormalSmall"); otherHelp:SetPoint("BOTTOMRIGHT", otherBox,"TOPRIGHT",0,0); otherHelp:SetTextColor(0.7,0.7,0.7); otherHelp:SetText("Messages with whitelisted keywords will be displayed"); local otherTip=options:CreateFontString(nil,"ARTWORK","GameFontNormal"); otherTip:SetPoint("LEFT", otherBox,"LEFT",0,0); otherTip:SetTextColor(1,1,1); local bottomText=options:CreateFontString(nil,"ARTWORK","GameFontNormalSmall"); bottomText:SetPoint("BOTTOMLEFT", options,"BOTTOMLEFT", leftMargin , 20); bottomText:SetTextColor(0.7,0.7,0.7); bottomText:SetJustifyH("LEFT"); bottomText:SetWidth(590); bottomText:SetText("ClassicChatFilter will later be updated to support advanced custom filters.") options:SetScript("OnShow", function(self) RefreshValues() end); channelsBox:SetScript("OnTabPressed", function(self) self:SetAutoFocus(false) self:ClearFocus() if(IsShiftKeyDown()) then otherBox:SetAutoFocus(true) else bannedBox:SetAutoFocus(true) end end) channelsBox:SetScript("OnTextChanged", function(self) channelsCount:SetText(#StringToTable(self:GetText())) if(self:GetText() == "") then channelsTip:SetText("none") else channelsTip:SetText("") end end) bannedBox:SetScript("OnTabPressed", function(self) self:SetAutoFocus(false) self:ClearFocus() if(IsShiftKeyDown()) then channelsBox:SetAutoFocus(true) else dungeonsBox:SetAutoFocus(true) end end) bannedBox:SetScript("OnTextChanged", function(self) bannedCount:SetText(#StringToTable(self:GetText())) if(self:GetText() == "") then bannedTip:SetText("none") else bannedTip:SetText("") end end) dungeonsBox:SetScript("OnTabPressed", function(self) self:SetAutoFocus(false) self:ClearFocus() if(IsShiftKeyDown()) then bannedBox:SetAutoFocus(true) else dungeonsRolesBox:SetAutoFocus(true) end end) dungeonsBox:SetScript("OnTextChanged", function(self) dungeonsCount:SetText(#StringToTable(self:GetText())) if(self:GetText() == "" and dungeonsRolesBox:GetText() == "") then dungeonsTip:SetText("disabled") dungeonsRolesTip:SetText("disabled") dungeonsTypesTip:SetText("disabled") elseif(self:GetText() == "") then dungeonsTip:SetText("any") else dungeonsTip:SetText("") if(dungeonsRolesBox:GetText() == "") then dungeonsRolesTip:SetText("any") end if(dungeonsTypesBox:GetText() == "") then dungeonsTypesTip:SetText("any") end end end) dungeonsRolesBox:SetScript("OnTabPressed", function(self) self:SetAutoFocus(false) self:ClearFocus() if(IsShiftKeyDown()) then dungeonsBox:SetAutoFocus(true) else dungeonsTypesBox:SetAutoFocus(true) end end) dungeonsRolesBox:SetScript("OnTextChanged", function(self) dungeonsRolesCount:SetText(#StringToTable(self:GetText())) if(self:GetText() == "" and dungeonsBox:GetText() == "") then dungeonsTip:SetText("disabled") dungeonsRolesTip:SetText("disabled") dungeonsTypesTip:SetText("disabled") elseif(self:GetText() == "") then dungeonsRolesTip:SetText("any") else dungeonsRolesTip:SetText("") if(dungeonsBox:GetText() == "") then dungeonsTip:SetText("any") end if(dungeonsTypesBox:GetText() == "") then dungeonsTypesTip:SetText("any") end end end) dungeonsTypesBox:SetScript("OnTabPressed", function(self) self:SetAutoFocus(false) self:ClearFocus() if(IsShiftKeyDown()) then dungeonsRolesBox:SetAutoFocus(true) else raidsBox:SetAutoFocus(true) end end) dungeonsTypesBox:SetScript("OnTextChanged", function(self) dungeonsTypesCount:SetText(#StringToTable(self:GetText())) if(self:GetText() == "" and dungeonsBox:GetText() == "") then dungeonsTip:SetText("disabled") dungeonsRolesTip:SetText("disabled") dungeonsTypesTip:SetText("disabled") elseif(self:GetText() == "") then dungeonsTypesTip:SetText("any") else dungeonsTypesTip:SetText("") if(dungeonsBox:GetText() == "") then dungeonsTip:SetText("any") end if(dungeonsRolesBox:GetText() == "") then dungeonsRolesTip:SetText("any") end end end) raidsBox:SetScript("OnTabPressed", function(self) self:SetAutoFocus(false) self:ClearFocus() if(IsShiftKeyDown()) then dungeonsRolesBox:SetAutoFocus(true) else raidsRolesBox:SetAutoFocus(true) end end) raidsBox:SetScript("OnTextChanged", function(self) raidsCount:SetText(#StringToTable(self:GetText())) if(self:GetText() == "" and raidsRolesBox:GetText() == "") then raidsTip:SetText("disabled") raidsRolesTip:SetText("disabled") elseif(self:GetText() == "") then raidsTip:SetText("any") else raidsTip:SetText("") if(raidsRolesBox:GetText() == "") then raidsRolesTip:SetText("any") end end end) raidsRolesBox:SetScript("OnTabPressed", function(self) self:SetAutoFocus(false) self:ClearFocus() if(IsShiftKeyDown()) then raidsBox:SetAutoFocus(true) else otherBox:SetAutoFocus(true) end end) raidsRolesBox:SetScript("OnTextChanged", function(self) raidsRolesCount:SetText(#StringToTable(self:GetText())) if(self:GetText() == "" and raidsBox:GetText() == "") then raidsTip:SetText("disabled") raidsRolesTip:SetText("disabled") elseif(self:GetText() == "") then raidsRolesTip:SetText("any") else raidsRolesTip:SetText("") if(raidsBox:GetText() == "") then raidsTip:SetText("any") end end end) otherBox:SetScript("OnTabPressed", function(self) self:SetAutoFocus(false) self:ClearFocus() if(IsShiftKeyDown()) then raidsRolesBox:SetAutoFocus(true) else channelsBox:SetAutoFocus(true) end end) otherBox:SetScript("OnTextChanged", function(self) otherCount:SetText(#StringToTable(self:GetText())) if(self:GetText() == "") then otherTip:SetText("disabled") else otherTip:SetText("") end end) SetProfile(CharSettings["profile"]) options:Hide() end function RenameProfile(val) if(#val > 0 and not GlobalSettings["profiles"][val]) then GlobalSettings["profiles"][val] = DeepCopy(GlobalSettings["profiles"][CharSettings["profile"]]) GlobalSettings["profiles"][CharSettings["profile"]] = nil SetProfile(val) RefreshValues() else print(addonStr.." : couldn't rename profile") end end function CopyProfile(val) if(#val > 0 and not GlobalSettings["profiles"][val]) then GlobalSettings["profiles"][val] = DeepCopy(GlobalSettings["profiles"][CharSettings["profile"]]) SetProfile(val) RefreshValues() else print(addonStr.." : couldn't copy profile") end end function CreateProfile(val) if(#val > 0 and not GlobalSettings["profiles"][val]) then GlobalSettings["profiles"][val] = DeepCopy(defaultProfile) SetProfile(val) RefreshValues() else print(addonStr.." : couldn't create profile") end end function DeleteCurrentProfile() GlobalSettings["profiles"][CharSettings["profile"]] = nil SetProfile("Default") RefreshValues() end function SetProfile(val,noinit) if(not noinit) then LibDropDown:UIDropDownMenu_Initialize(profilesDropDown, profilesDropdownInit); end CharSettings["profile"] = val; LibDropDown:UIDropDownMenu_SetSelectedValue(profilesDropDown, val); if(val == "Default") then renameProfileButton:Disable() deleteProfileButton:Disable() else renameProfileButton:Enable() deleteProfileButton:Enable() end end function RefreshValues() enabledButton:SetChecked(CharSettings.enabled); soundalertbutton:SetChecked(GetCurrentValue("sound_alert")); pmessagesButton:SetChecked(GetCurrentValue("show_player_messages")); pmentionsButton:SetChecked(GetCurrentValue("show_player_mentions")); channelsBox:SetText(TableToString(GetCurrentValue("channels"))); bannedBox:SetText(TableToString(GetCurrentValue("banned"))); dungeonsBox:SetText(TableToString(GetCurrentValue("dungeons"))); dungeonsRolesBox:SetText(TableToString(GetCurrentValue("dungeons_roles"))); dungeonsTypesBox:SetText(TableToString(GetCurrentValue("dungeons_types"))); raidsBox:SetText(TableToString(GetCurrentValue("raids"))); raidsRolesBox:SetText(TableToString(GetCurrentValue("raids_roles"))); otherBox:SetText(TableToString(GetCurrentValue("other"))); end function profilesDropdownInit(self, level) for key, value in pairs(GlobalSettings["profiles"]) do local info; info = LibDropDown:UIDropDownMenu_CreateInfo(); info.text = key; info.value = key; info.arg1 = key; info.func = function(self, arg1, arg2, checked) SetProfile(self.value, true) RefreshValues() end LibDropDown:UIDropDownMenu_AddButton(info, level); end end function Filter(self,event,msg,author,arg1,arg2,arg3,arg4,arg5,arg6,channel,...) if(CharSettings["enabled"]) then if(CheckChannel(channel)) then if(CheckPlayerAuthor(author)) then return false elseif(CheckPlayerMention(msg)) then PlayAlert() return false elseif(CheckBanned(msg)) then return true elseif(AtLeastOneFilter() and (CheckDungeons(msg) or CheckRaids(msg) or CheckOther(msg))) then PlayAlert() return false else return true end end end return false end function PlayAlert() if(GetCurrentValue("sound_alert")) then PlaySound(12867, "Music") end end function GetCurrentValue(key) local val = GlobalSettings["profiles"][CharSettings["profile"]][key] if val == nil then val = defaultProfile[key] SetCurrentValue(key,val) end return val end function SetCurrentValue(key,val) GlobalSettings["profiles"][CharSettings["profile"]][key] = val end function HasValues(key) return #GetCurrentValue(key) ~= 0 end function CheckPlayerAuthor(author) return GetCurrentValue("show_player_messages") and CheckAuthor(author,pname) end function CheckPlayerMention(msg) return GetCurrentValue("show_player_mentions") and MatchStr(msg, pname) end function CheckAuthor(author,check) ind = string.find(author, "-") if(ind) then author = string.sub(author, 1, ind-1) end return author == check end function AtLeastOneFilter() return HasValues("raids") or HasValues("raids_roles") or HasValues("dungeons") or HasValues("dungeons_roles") or HasValues("dungeons_types") or HasValues("other") end function CheckChannel(channel) return HasValues("channels") and MatchAny(channel, GetCurrentValue("channels")) end function CheckBanned(msg) return HasValues("banned") and MatchAny(msg, GetCurrentValue("banned")) end function CheckDungeons(msg) return (HasValues("dungeons") or HasValues("dungeons_roles") or HasValues("dungeons_types")) and ( (not HasValues("dungeons") or MatchAny(msg, GetCurrentValue("dungeons"))) and (not HasValues("dungeons_roles") or MatchAny(msg, GetCurrentValue("dungeons_roles"))) and (not HasValues("dungeons_types") or MatchAny(msg, GetCurrentValue("dungeons_types"))) ) end function CheckRaids(msg) return (HasValues("raids_roles") or HasValues("raids")) and ((not HasValues("raids_roles") or MatchAny(msg, GetCurrentValue("raids_roles"))) and (not HasValues("raids") or MatchAny(msg, GetCurrentValue("raids")))) end function CheckOther(msg) return HasValues("other") and MatchAny(msg, GetCurrentValue("other")) end function MatchAny(source,testlist) for _,test in pairs(testlist) do if(MatchStr(source,test)) then return true end end return false end function MatchStr(source,test) return string.lower(source):find(string.lower(test)) end function DeepCopy(orig) local copy if(type(orig) == "table") then copy = {} for orig_key, orig_value in next, orig, nil do copy[DeepCopy(orig_key)] = DeepCopy(orig_value) end setmetatable(copy, DeepCopy(getmetatable(orig))) else copy = orig end return copy end function TableToString(val,sep) return table.concat(val, sep or ",") end function StringToTable(val,sep) local sep, fields = sep or ",", {} local pattern = string.format("([^%s]+)", sep) string.gsub(val, pattern, function(c) fields[#fields+1] = c end) return fields end for type in next,getmetatable(ChatTypeInfo).__index do ChatFrame_AddMessageEventFilter("CHAT_MSG_"..type,Filter); end
DefineClass.FuelFactory = { __parents = { "ResourceProducer", "ElectricityConsumer", "LifeSupportConsumer", "OutsideBuildingWithShifts" }, properties = { --{ template = true, category = "Spaceport", name = T{"Food per colonist"}, id = "food_per_colonist", editor = "number", default = 4*const.ResourceScale, min = 1, max = 9999999, scale = const.ResourceScale, help = "The amount of food delivered for each arriving colonist.",}, }, building_update_time = const.HourDuration, exploitation_resource = "Fuel", stockpile_spots1 = { "Resourcepile" }, has_demand_request = false, has_supply_request = true, max_x = 5, max_y = 2, } function FuelFactory:Init() self.parent = self self.max_z = self.max_storage1/(10 * const.ResourceScale) end
aliveai.registered_rndcheck_nodes={} aliveai.register_rndcheck_on_generated=function(def) if not def then return end def.miny=def.miny or -500 def.maxy=def.maxy or 500 def.chance=def.chance or 1 def.mindistance=def.mindistance or 0 if def.node and type(def.node)~="string" then print("failed to add to check random generated node: node aren't a string") elseif def.chance and type(def.chance)~="number" then print("failed to add to check random generated chance aren't a number") elseif def.mindistance and type(def.mindistance)~="number" then print("failed to add to check random generated mindistance aren't a number") elseif def.group and type(def.group)~="string" then print("failed to add to check random generated node:group aren't a string") elseif type(def.run)~="function" then print("failed to add to check random generated node: no run function") return elseif not (def.node or def.group) then print("failed to add to check random generated node: choose node or group or both") return end table.insert(aliveai.registered_rndcheck_nodes,{ func=def.run, miny=def.miny, maxy=def.maxy, group=def.group, node=def.node, first_only=def.first_only, chance=def.chance, mindistance=def.mindistance }) end minetest.register_on_generated(function(minp, maxp, seed) local nodes={} for _, f in pairs(aliveai.registered_rndcheck_nodes) do if f.miny<=minp.y and f.maxy>=maxp.y then f.first=nil table.insert(nodes,f) end end if #nodes==0 then return end local center={x=minp.x+math.floor((maxp.x-minp.x)/2),y=minp.y+math.floor((maxp.y-minp.y)/2),z=minp.z+math.floor((maxp.z-minp.z)/2)} local a for ii=-20,20,1 do a=ii+math.pi local cp={x=center.x+20*math.cos(a),y=center.y+ii,z=center.z+20*math.sin(a)} --minetest.set_node(cp,{name="default:mese"}) local node=minetest.get_node(cp).name for _, f in pairs(nodes) do if not f.first and math.random(1,f.chance)==1 and (f.node and f.node==node) or (f.group and minetest.get_item_group(node,f.group)>0) then if not f.lpos then f.lpos=cp end if f.mindistance<=aliveai.distance(cp,f.lpos) then if f.first_only then f.first=true end f.lpos=cp minetest.after(0, function(f,cp) f.func(cp) end,f,cp) end end end end end)
resource_manifest_version '44febabe-d386-4d18-afbe-5e627f4af937' name 'CO-extended' author 'COKLUK - https://github.com/cokluk' version 'v1.1.0' client_scripts { '@es_extended/locale.lua', 'main.lua', } server_scripts { '@es_extended/locale.lua', '@mysql-async/lib/MySQL.lua', 'server.lua', } exports { 'CoLog', 'comaven', 'arac_gonder', } shared_script 'config.lua' dependency 'es_extended'
require('packer').use { 'nvim-ts-context-commentstring', after = 'nvim-treesitter' }
yatm_packs:require("items/ammo_pack_pouch.lua") yatm_packs:require("items/health_pack_pouch.lua") yatm_packs:require("items/mana_pack_pouch.lua")
--[[----------------------------------------------------------------------------------------------------------------------- Enable speedmode for a player -----------------------------------------------------------------------------------------------------------------------]]-- local PLUGIN = {} PLUGIN.Title = "Speed" PLUGIN.Description = "Enable speedmode for a player." PLUGIN.Author = "Overv" PLUGIN.ChatCommand = "speed" PLUGIN.Usage = "[players] [speed]" PLUGIN.Privileges = { "Speed" } function PLUGIN:Call( ply, args ) if ( ply:EV_HasPrivilege( "Speed" ) ) then local players = evolve:FindPlayer( args, ply, true ) local speed = math.abs( tonumber( args[ #args ] ) or 250 ) for _, pl in ipairs( players ) do GAMEMODE:SetPlayerSpeed( pl, speed, speed * 2 ) end if ( #players > 0 ) then evolve:Notify( evolve.colors.blue, ply:Nick(), evolve.colors.white, " has set the speed of ", evolve.colors.red, evolve:CreatePlayerList( players ), evolve.colors.white, " to " .. speed .. "." ) else evolve:Notify( ply, evolve.colors.red, evolve.constants.noplayers ) end else evolve:Notify( ply, evolve.colors.red, evolve.constants.notallowed ) end end function PLUGIN:Menu( arg, players ) return "Speed", evolve.category.actions, { { "Default", 250 }, { "Double", 500 } } end evolve:RegisterPlugin( PLUGIN )
-- leader 键设置为空格 vim.g.mapleader = " " -- 默认的键位设置函数太长了,所以这里将它们重新引用一下 vim.keybinds = { gmap = vim.api.nvim_set_keymap, bmap = vim.api.nvim_buf_set_keymap, dgmap = vim.api.nvim_del_keymap, dbmap = vim.api.nvim_buf_del_keymap, opts = {noremap = true, silent = true} } local keymap = vim.api.nvim_set_keymap keymap('n', '<c-s>', ':w<CR>', {}) keymap('n', 'W', ':w<CR>', {}) keymap('n', 'Q', ':q<CR>', {}) keymap('n', 'J', '5j', {}) keymap('n', 'K', '5k', {}) keymap('n', 'L', '5l', {}) keymap('n', 'H', '5h', {}) keymap('i', 'jj', '<ESC>', {}) keymap('i', 'jk', '<ESC>', {}) local opts = { noremap = true, silent = true } -- Normal -- -- Better window navigation keymap("n", "<C-h>", "<C-w>h", opts) keymap("n", "<C-j>", "<C-w>j", opts) keymap("n", "<C-k>", "<C-w>k", opts) keymap("n", "<C-l>", "<C-w>l", opts) -- Move text up and down --keymap("n", "<A-j>", "<Esc>:m .+1<CR>==gi", opts) --keymap("n", "<A-k>", "<Esc>:m .-2<CR>==gi", opts) ---- Move text up and down --keymap("v", "<A-j>", ":m .+1<CR>==", opts) --keymap("v", "<A-k>", ":m .-2<CR>==", opts) --keymap("v", "p", '"_dP', opts) -- ---- Visual Block -- ---- Move text up and down --keymap("x", "J", ":move '>+1<CR>gv-gv", opts) --keymap("x", "K", ":move '<-2<CR>gv-gv", opts) --keymap("x", "<A-j>", ":move '>+1<CR>gv-gv", opts) --keymap("x", "<A-k>", ":move '<-2<CR>gv-gv", opts) --local opts = {noremap = true} keymap('n', '<c-j>', '<c-w>j', opts) --keymap('n', '<space>', ':call VSCodeNotify("whichkey.show")', opts) --markdown vim.keybinds.gmap("n", "mv", "<cmd>Glow<CR>", vim.keybinds.opts) -- 设置format timeout 2000 vim.keybinds.gmap("n", "F", "<cmd>lua vim.lsp.buf.formatting_sync(nil, 2000)<CR>", vim.keybinds.opts) -- 插入模下 jj 退出插入模式 vim.keybinds.gmap("i", "jj", "<Esc>", vim.keybinds.opts) vim.keybinds.gmap("c", "<C-j>", "<C-n>", {noremap = false}) vim.keybinds.gmap("c", "<C-k>", "<C-p>", {noremap = false}) -- 用 H 和 L 代替 ^ 与 $ vim.keybinds.gmap("n", "H", "^", vim.keybinds.opts) -- vim.keybinds.gmap("n", "nn", "i<ESC>", vim.keybinds.opts) vim.keybinds.gmap("n", "<CR>", "o<ESC>k", vim.keybinds.opts) vim.keybinds.gmap("n", "N", "J", vim.keybinds.opts) vim.keybinds.gmap("v", "H", "^", vim.keybinds.opts) vim.keybinds.gmap("n", "L", "$", vim.keybinds.opts) vim.keybinds.gmap("v", "L", "$", vim.keybinds.opts) vim.keybinds.gmap("v", "J", "5j", vim.keybinds.opts) vim.keybinds.gmap("v", "K", "5k", vim.keybinds.opts) vim.keybinds.gmap("v", "mm", "<ESC>", vim.keybinds.opts) -- 将 C-u 和 C-d 调整为上下滑动 10 行而不是半页 vim.keybinds.gmap("n", "<C-u>", "10k", vim.keybinds.opts) vim.keybinds.gmap("n", "<C-d>", "10j", vim.keybinds.opts) -- 插入模式下的上下左右移动 vim.keybinds.gmap("i", "<A-k>", "<up>", vim.keybinds.opts) vim.keybinds.gmap("i", "<A-j>", "<down>", vim.keybinds.opts) vim.keybinds.gmap("i", "<A-h>", "<left>", vim.keybinds.opts) vim.keybinds.gmap("i", "<A-l>", "<right>", vim.keybinds.opts) -- 修改分屏大小 vim.keybinds.gmap("n", "<C-up>", "<cmd>res +1<CR>", vim.keybinds.opts) vim.keybinds.gmap("n", "<C-down>", "<cmd>res -1<CR>", vim.keybinds.opts) vim.keybinds.gmap("n", "<C-left>", "<cmd>vertical resize-1<CR>", vim.keybinds.opts) vim.keybinds.gmap("n", "<C-right>", "<cmd>vertical resize+1<CR>", vim.keybinds.opts) -- 正常模式下按 ESC 取消高亮显示 vim.keybinds.gmap("n", "<ESC>", ":nohlsearch<CR>", vim.keybinds.opts) -- 通过 leader cs 切换拼写检查 vim.keybinds.gmap("n", "<leader>cs", "<cmd>set spell!<CR>", vim.keybinds.opts) vim.bo.expandtab = true vim.bo.shiftwidth = 4 vim.bo.softtabstop = 4 vim.wo.number = true vim.wo.relativenumber = true