content
stringlengths
5
1.05M
-- TODO: Get string code for relevant Materials -- TODO: read() for every ore local mine = ("Gold Ore", "Diamond Ore", "Iron Ore") local slotFuel = 1 local slotTorch = 2 local slotChestFuel = 3 local slotChestShit = 4 local torchDistance = 7 write("Tunnel length: ) local tunnelLength = read() write("Spacing between Tunnels: ") local spacing = read() write("Side ajacent tunnels: ") write("1 - Left") write("2 - Right") local side = read() write("Fuel slot: " .. slotFuel) write("Torch slot: " .. slotTorch) write("Enderchest Fuel slot: " .. slotChestFuel) write("Enderchest Shit slot: " .. slotChestShit) write("-----------------------------") write("Press Enter to continue") -- Turtle starting turtle.select(slotFuel) turtle.refuel() print("Turtle ready") -- Starting position: Bottom turtle.up() function place(slot) turtle.turnRight() turtle.turnRight() turtle.select(slot) turtle.place() turtle.turnLeft() turtle.turnLeft() end function store(slot) turtle.select(slotChestShit) turtle.placeDown() turtle.select(slot) turtle.dropDown() turtle.digDown() end function getFuel() turtle.select(slotChestFuel) turtle.placeDown() turtle.select(slotFuel) turtle.suckDown(63) turtle.digDown() end function move(length) for i = 1, length do -- Basic Movement if turtle.detect() == true then turtle.dig() end turtle.forward() if turtle.detectUp() == true then turtle.digUp() end if turtle.detectDown() == true then turtle.digDown() end if turtle.getFuelLevel() == 1 then turtle.select(slotFuel) turtle.refuel() end -- Check if moved torchDistance Blocks -- TODO: move efficient: i is a multiple of torchDistance for a = 0, torchDistance * torchDistance do if i = a * torchDistance then place(slotTorch) end end -- If a slot is full -> store in ender chest for a = 5, 12 do if turtle.getItemSpace(a) == 0 then store(a); end end -- If fuel slot is empty -> refuel if turtle.getItemCount(slotFuel) == 1 then getFuel() end -- TODO: Detect and mine specific ores end end function moveLeft() turtle.turnLeft() turtle.move(spacing + 1) turtle.turnLeft() end function moveRight() turtle.turnRight() move(spacing + 1) turtle.turnRight() end -- TODO: Set slots for torch / Fuel -- TODO: Place torch while true do -- Turtle continue left if side == 1 then move(tunnelLength) moveLeft() move(tunnelLength) moveRight() end -- Turtle continue right if side == 2 then move(tunnelLength) moveRight() move(tunnelLength) moveLeft() end end
SomeName = "Alice" -- single line comment SomeValue = 10.5f [[-- Multi-line comment . . . --]] SomePath = "./this/potato/is/mine.pdf" Potato = { Temp = 260, Color = 'yellow', some_bool = true } some_multiline_string = [[ This is a multiline string ]]
local SyntaxKind = require("lunar.ast.syntax_kind") local SyntaxNode = require("lunar.ast.syntax_node") local PrefixExpression = setmetatable({}, { __index = SyntaxNode, }) PrefixExpression.__index = setmetatable({}, SyntaxNode) function PrefixExpression.new(start_pos, end_pos, expr) return PrefixExpression.constructor(setmetatable({}, PrefixExpression), start_pos, end_pos, expr) end function PrefixExpression.constructor(self, start_pos, end_pos, expr) SyntaxNode.constructor(self, SyntaxKind.prefix_expression, start_pos, end_pos) self.expr = expr return self end return PrefixExpression
--[[ 优点:外观模式的目的不是给子系统添加新的功能接口, 而是为了让外部减少与子系统内多个模块的交互, 松散耦合,从而让外部能够更简单的使用子系统。 当然,这是一把双刃剑 缺点:不能很好的限制客户端直接使用子系统类, 如果对客户端访问子系统类做太多的限制则减少了 可变性和灵活性 下面外部只与Facade交互,而facade与system交互, 从而达到上述优点 ]] System = {} function System:new(o) o = o or {} setmetatable(o, self) self.__index = self return o end SubSystemOne = System:new() function SubSystemOne:Method1() print("SubSystemOne:Method1") end function SubSystemOne:Method2() print("SubSystemOne:Method2") end function SubSystemOne:Method3() print("SubSystemOne:Method3") end SubSystemTwo = System:new() function SubSystemTwo:Method1() print("SubSystemTwo:Method1") end function SubSystemTwo:Method2() print("SubSystemTwo:Method2") end function SubSystemTwo:Method3() print("SubSystemTwo:Method3") end Facade = {} function Facade:new(o) o = o or {} setmetatable(o, self) self.__index = self o.one = SubSystemOne:new() o.two = SubSystemTwo:new() return o end function Facade:Method1() self.one:Method1() self.two:Method1() end function Facade:Method2() self.one:Method2() self.two:Method2() end function Facade:Method3() self.one:Method3() self.two:Method3() end facade = Facade:new() facade:Method1()
local att = {} att.name = "md_fas2_eotech" att.displayName = "EOTech 553 holographic sight" att.displayNameShort = "EoTech" att.aimPos = {"EoTech553Pos", "EoTech553Ang"} att.FOVModifier = 15 att.isSight = true att.colorType = CustomizableWeaponry.colorableParts.COLOR_TYPE_SIGHT att.statModifiers = {OverallMouseSensMult = -0.05} if CLIENT then att.displayIcon = surface.GetTextureID("atts/eotech553") att.description = { [1] = {t = "Provides a bright reticle to ease aiming.", c = CustomizableWeaponry.textColors.POSITIVE}, [2] = {t = "Model taken directly from Firearms: Source.", c = CustomizableWeaponry.textColors.POSITIVE} } att.reticle = "models/qq_rec/fas2_2015/eotech_reticle" att._reticleSize = 5 local glowMat = Material("models/qq_rec/cod4_2014/weapon_holographic_lens_glow_col") local glowCol = Vector(0,0,0) local rc, isAiming, freeze, isScopePos, attachmEnt, EA, retPos, retNorm, retAng function att:elementRender() if not self.ActiveAttachments[att.name] then return end if not self.AttachmentModelsVM[att.name] then return end rc = self:getSightColor(att.name) glowCol.x = rc.r / 255 / 4 glowCol.y = rc.g / 255 / 4 glowCol.z = rc.b / 255 / 4 glowMat:SetVector("$color2", glowCol) isAiming = self:isAiming() freeze = GetConVarNumber("cw_kk_freeze_reticles") != 0 isScopePos = (self.AimPos == self[att.aimPos[1]] and self.AimAng == self[att.aimPos[2]]) attachmEnt = self.AttachmentModelsVM[att.name].ent if isAiming then attachmEnt:SetBodygroup(1, 1) else attachmEnt:SetBodygroup(1, 0) end if not isScopePos then return end if isAiming or self.dt.BipodDeployed then self._stencilTimeChck = CurTime() + 0.1 end if self._stencilTimeChck and self._stencilTimeChck < CurTime() then return end render.ClearStencil() render.SetStencilEnable(true) render.SetStencilWriteMask(1) render.SetStencilTestMask(1) render.SetStencilReferenceValue(1) render.SetStencilCompareFunction(STENCILCOMPARISONFUNCTION_ALWAYS) render.SetStencilPassOperation(STENCILOPERATION_REPLACE) render.SetStencilFailOperation(STENCILOPERATION_KEEP) render.SetStencilZFailOperation(STENCILOPERATION_KEEP) attachmEnt:SetModel("models/c_fas2_eotech_stencil.mdl") attachmEnt:DrawModel() render.SetStencilWriteMask(2) render.SetStencilTestMask(2) render.SetStencilReferenceValue(2) render.SetStencilCompareFunction(STENCILCOMPARISONFUNCTION_EQUAL) render.SetStencilPassOperation(STENCILOPERATION_REPLACE) render.SetStencilWriteMask(1) render.SetStencilTestMask(1) render.SetStencilReferenceValue(1) render.SetMaterial(att._reticle) EA = self:getReticleAngles() retPos = EyePos() + EA:Forward() * 12 *(attachmEnt:GetPos():Distance(EyePos())) retNorm = attachmEnt:GetAngles():Forward() retAng = 180 + attachmEnt:GetAngles().z cam.IgnoreZ(true) render.CullMode(MATERIAL_CULLMODE_CW) render.DrawQuadEasy(retPos, retNorm, att._reticleSize, att._reticleSize, Color(rc.r,rc.g,rc.b,150 + math.random(50)), retAng) render.DrawQuadEasy(retPos, retNorm, att._reticleSize, att._reticleSize, Color(rc.r,rc.g,rc.b,150 + math.random(50)), retAng) render.CullMode(MATERIAL_CULLMODE_CCW) cam.IgnoreZ(false) attachmEnt:SetModel("models/c_fas2_eotech.mdl") render.SetStencilEnable(false) end end CustomizableWeaponry:registerAttachment(att)
local _M = {} _M._VERSION = '1.0' local function split(s, sep) local fields = {} local sep = sep or "," local pattern = string.format("([^%s]+)", sep) string.gsub(s, pattern, function(c) fields[#fields + 1] = c end) return fields end local function cookieFix(source, token) if source == "cookie" and string.find(token,"-") ~= nil then -- cookie 且包含 中划线 return "cookie;"..token; end return source.."_"..string.gsub(token, "-", "_"); end local function validKey(s) -- lua 读取 header cookie 参数 的方式 分别为 http_ cookie_ arg_ if s ~= "cookie" and s ~= "header" and s ~= "arg" then ngx.log(ngx.ERR,"[unit] json rule key err "..s.." should be in (cookie,header,arg)") return nil end if s == "header" then s = "http" end return s end function _M.doParseSource(val) local idSource = nil if val["source"] == nil or val["tokenKey"] == nil then ngx.log(ngx.ERR,"[unit] no source or tokenKey") return idSource end if string.find(val["source"],",") ~= nil then local sourceArray = {} local arr = split(val["source"],",") for i = 1, #arr do local sourceKey = arr[i] sourceKey = validKey(sourceKey) if sourceKey == nil then return end sourceKey = cookieFix(sourceKey,val["tokenKey"]) sourceArray[i] = sourceKey end idSource = sourceArray else local sourceKey = validKey(val["source"]) if sourceKey == nil then return end idSource = cookieFix(sourceKey,val["tokenKey"]) end return idSource end return _M
print('hello') a = safemath.bigint('123') pprint('a=', a) b = safemath.bigint(456) pprint('b=', b) pprint('hex(a)=', safemath.tohex(a)) pprint('int(a)=', safemath.toint(a)) pprint('str(a)=', safemath.tostring(a)) c = safemath.add(a, b) d = safemath.sub(a, b) e = safemath.mul(a, b) f = safemath.div(b, a) g = safemath.pow(a, safemath.bigint(10)) h = safemath.bigint('3333333333333333333333333333333333332') j = safemath.rem(h, safemath.bigint(2)) pprint('c', safemath.tostring(c)) pprint('d', safemath.tostring(d)) pprint('e', safemath.tostring(e)) pprint('f', safemath.tostring(f)) pprint('g', safemath.tostring(g)) pprint('h', safemath.tostring(h)) pprint('j', safemath.tostring(j)) pprint("try parse a1 is:", safemath.bigint('a1')) c1 = safemath.gt(a, b) c2 = safemath.ge(a, b) c3 = safemath.lt(a, b) c4 = safemath.le(a, b) c5 = safemath.eq(a, b) c6 = safemath.ne(a, b) c7 = safemath.eq(a, a) pprint(safemath.tostring(a) .. ' > ' .. safemath.tostring(b) .. '=' .. tostring(c1)) pprint(safemath.tostring(a) .. ' >= ' .. safemath.tostring(b) .. '=' .. tostring(c2)) pprint(safemath.tostring(a) .. ' < ' .. safemath.tostring(b) .. '=' .. tostring(c3)) pprint(safemath.tostring(a) .. ' <= ' .. safemath.tostring(b) .. '=' .. tostring(c4)) pprint(safemath.tostring(a) .. ' == ' .. safemath.tostring(b) .. '=' .. tostring(c5)) pprint(safemath.tostring(a) .. ' != ' .. safemath.tostring(b) .. '=' .. tostring(c6)) pprint(safemath.tostring(a) .. ' == ' .. safemath.tostring(a) .. '=' .. tostring(c7))
CyrodiilAction = CyrodiilAction or {} CyrodiilAction.NotificationManager = CyrodiilAction.NotificationManager or {} CyrodiilAction.Utils = {} ---------------------------------------------- -- Returns smaller keep names. ---------------------------------------------- function CyrodiilAction.Utils:shortenKeepName(str) return str:gsub(",..$", ""):gsub("%^.d$", "") --FR :gsub("avant.poste d[eu] ", "") :gsub("la bastille d[eu]s? ", "") :gsub("de la bastille", "") :gsub("fort de la ", "") :gsub("du château ", "") :gsub("du fort ", "") end ---------------------------------------------- -- Returns keep icon from keepID ---------------------------------------------- function CyrodiilAction.Utils.getKeepIcon(keepId) local keepType = GetKeepType(keepId) if keepType == KEEPTYPE_RESOURCE then local keepResourceType = GetKeepResourceType(keepId) return CyrodiilAction.defaults.icons.keep.resource[keepResourceType] else return CyrodiilAction.defaults.icons.keep[keepType] end end ---------------------------------------------- -- Returns keep icon based on battle context ---------------------------------------------- function CyrodiilAction.Utils.getKeepIconByBattleContext(keepId, battleContext) local keepType = GetKeepType(keepId) local alliance = GetKeepAlliance(keepId, battleContext) if keepType == KEEPTYPE_RESOURCE then local keepResourceType = GetKeepResourceType(keepId) return CyrodiilAction.defaults.icons.ava.keep.resource[keepResourceType][alliance] elseif keepType == KEEPTYPE_BRIDGE then if IsKeepPassable(keepId, battleContext) then return CyrodiilAction.defaults.icons.keep.bridge["PASSABLE"] else return CyrodiilAction.defaults.icons.keep.bridge["NOT_PASSABLE"] end elseif keepType == KEEPTYPE_MILEGATE then if IsKeepPassable(keepId, battleContext) then return CyrodiilAction.defaults.icons.keep.milegate["PASSABLE"] else return CyrodiilAction.defaults.icons.keep.milegate["NOT_PASSABLE"] end else return CyrodiilAction.defaults.icons.ava.keep[keepType][alliance] end end ---------------------------------------------- -- Fake notify command ---------------------------------------------- SLASH_COMMANDS["/notify"] = function (extra) CyrodiilAction.NotificationManager.push({text="New notification !", type="test"}) end ---------------------------------------------- -- Format thousand numbers ---------------------------------------------- function CyrodiilAction.Utils.format_thousand(v) local s = string.format("%d", math.floor(v)) local pos = string.len(s) % 3 local thousandSeparator = " " if pos == 0 then pos = 3 end return string.sub(s, 1, pos) .. string.gsub(string.sub(s, pos+1), "(...)", thousandSeparator.."%1") end ---------------------------------------------- -- Converts seconds to minutes and seconds ---------------------------------------------- function CyrodiilAction.Utils.format_time(delta) local sec = delta % 60 delta = (delta - sec) / 60 local min = delta % 60 local out = min .. "m" out = out .. " " .. sec .. "s" return out end
-- View an animation namespace "standard" local flat = require "engine.flat" local ui2 = require "ent.ui2" local ModelDrawer = require "app.debug.modelView.modelDrawer" local ModelEditAnimationUi = classNamed("ModelEditAnimationUi", ModelDrawer) function ModelEditAnimationUi:onLoad() local function Home() return self.back[1](self.back[2]) end -- Horizontal local ents = { ui2.ButtonEnt{label="<", onButton = function(_self) -- Die self:swap( Home() ) end}, ui2.UiEnt{label=self.target} } local layout = ui2.PileLayout{managed=ents, parent=self} layout:layout() -- Vertical self.duration = self.model:getAnimationDuration(self.target) if self.duration <= 0 then self.duration = 0 end self.timeSlider = ui2.SliderTripletEnt{startLabel="Time", sliderSpec={minRange=0, maxRange=self.duration}} self.mixerSlider = ui2.SliderTripletEnt{startLabel="Mix", sliderSpec={value=1}} ents = { ui2.ButtonEnt{label="Play", onButton = function(_self) self.playing = not self.playing _self.label = self.playing and "Stop" or "Play" end}, self.timeSlider, self.mixerSlider } local layout = ui2.PileLayout{managed=ents, parent=self, face="y", anchor="tr"} layout:layout() end function ModelEditAnimationUi:onUpdate() if self.dead then return end self.model:pose() local time = lovr.timer.getTime() if self.playing then self.timeSlider:setValue(time % self.duration) end self.model:animate(self.target, self.playing and time or self.timeSlider:getValue(), self.mixerSlider:getValue()) end function ModelEditAnimationUi:onBury() self.model:pose() end return ModelEditAnimationUi
function main() uv.resolve4('baidu.com', function (addresses, err) if addresses == nil then print('error', err) return end print(addresses) print('[') for i, v in ipairs(addresses) do print(v) end print(']') end ) uv.resolve4('www.google.com', function (addresses, err) if addresses == nil then print('error', err) return end print(addresses) print('[') for i, v in ipairs(addresses) do print(v) end print(']') end ) uv.resolve4('baidgdsgsdfgu.com', function (addresses, err) if addresses == nil then print('error', err) return end print(addresses) print('[') for i, v in ipairs(addresses) do print(v) end print(']') end ) uv.lookup('baidu.com', function (address, err) if address == nil then print('error', err) return end print(address) end ) uv.lookup('baidsafdsafu.com', function (address, err) if address == nil then print('error', err) return end print(address) end ) uv.lookup('192.168.1.1', function (address, err) if address == nil then print('error', err) return end print(address) end ) uv.loop() end main()
local ELEMENT = Element.New() function ELEMENT:Initialize() self:SetDamageType(DMG_CLUB) self:SetWeakAgainst(ELEMENT_ROCK) self:SetStrongAgainst(ELEMENT_FIRE, ELEMENT_ICE) self:SetImmuneAgainst(ELEMENT_SHOCK) end function ELEMENT:OnInteractWith(target, other, dmg_info) if target:HasDebuff(DEBUFF_FROZEN) then dmg_info:ScaleDamage(2) end end ELEMENT_ROCK = Element.Register(ELEMENT)
require 'nn' require 'image' require 'xlua' local Provider = torch.class 'Provider' function Provider:__init(full) local trsize = 50000 local tesize = 10000 -- download dataset if not paths.dirp('cifar-10-batches-t7') then local www = 'http://torch7.s3-website-us-east-1.amazonaws.com/data/cifar-10-torch.tar.gz' local tar = paths.basename(www) os.execute('wget ' .. www .. '; '.. 'tar xvf ' .. tar) end -- load dataset self.trainData = { data = torch.Tensor(trsize, 3072), labels = torch.Tensor(trsize), size = function() return trsize end } local trainData = self.trainData local groups=trsize/10000 print(groups) for i = 0,groups do local subset = torch.load('cifar-10-batches-t7/data_batch_' .. (i+1) .. '.t7', 'ascii') trainData.data[{ {i*10000+1, (i+1)*10000} }] = subset.data:t() trainData.labels[{ {i*10000+1, (i+1)*10000} }] = subset.labels end trainData.labels = trainData.labels + 1 local subset = torch.load('cifar-10-batches-t7/test_batch.t7', 'ascii') self.testData = { data = subset.data:t():double(), labels = subset.labels[1]:double(), size = function() return tesize end } local testData = self.testData testData.labels = testData.labels + 1 -- resize dataset (if using small version) trainData.data = trainData.data[{ {1,trsize} }] trainData.labels = trainData.labels[{ {1,trsize} }] testData.data = testData.data[{ {1,tesize} }] testData.labels = testData.labels[{ {1,tesize} }] -- reshape data trainData.data = trainData.data:reshape(trsize,3,32,32) testData.data = testData.data:reshape(tesize,3,32,32) end function Provider:normalize() ---------------------------------------------------------------------- -- preprocess/normalize train/test sets -- local trainData = self.trainData local testData = self.testData print '<trainer> preprocessing data (color space + normalization)' collectgarbage() -- preprocess trainSet local normalization = nn.SpatialContrastiveNormalization(1, image.gaussian1D(7)) for i = 1,trainData:size() do xlua.progress(i, trainData:size()) -- rgb -> yuv local rgb = trainData.data[i] local yuv = image.rgb2yuv(rgb) -- normalize y locally: yuv[1] = normalization(yuv[{{1}}]) trainData.data[i] = yuv end -- normalize u globally: local mean_u = trainData.data:select(2,2):mean() local std_u = trainData.data:select(2,2):std() trainData.data:select(2,2):add(-mean_u) trainData.data:select(2,2):div(std_u) -- normalize v globally: local mean_v = trainData.data:select(2,3):mean() local std_v = trainData.data:select(2,3):std() trainData.data:select(2,3):add(-mean_v) trainData.data:select(2,3):div(std_v) trainData.mean_u = mean_u trainData.std_u = std_u trainData.mean_v = mean_v trainData.std_v = std_v -- preprocess testSet for i = 1,testData:size() do xlua.progress(i, testData:size()) -- rgb -> yuv local rgb = testData.data[i] local yuv = image.rgb2yuv(rgb) -- normalize y locally: yuv[{1}] = normalization(yuv[{{1}}]) testData.data[i] = yuv end -- normalize u globally: testData.data:select(2,2):add(-mean_u) testData.data:select(2,2):div(std_u) -- normalize v globally: testData.data:select(2,3):add(-mean_v) testData.data:select(2,3):div(std_v) end
local util = require('radio.core.util') describe("table and array utilities", function () it("table_length()", function () assert.is.equal(0, util.table_length({})) assert.is.equal(3, util.table_length({foo = 'bar', bar = nil, abc = true, def = 1})) assert.is.equal(5, util.table_length({1, 2, 3, 4, 5})) end) it("table_copy()", function () local x = {foo = 'bar', bar = nil, abc = true, def = 1} local y = util.table_copy(x) assert.is_true(x ~= y) assert.is.same(y, x) end) it("array_exists()", function () local x = {'bar', 'foo', 123, true} assert.is_true(util.array_exists(x, 'bar')) assert.is_true(util.array_exists(x, 'foo')) assert.is_true(util.array_exists(x, 123)) assert.is_true(util.array_exists(x, true)) assert.is_false(util.array_exists(x, false)) assert.is_false(util.array_exists(x, 'abc')) end) it("array_search()", function () local x = {} local y = {} local arr = {'bar', 'foo', 123, false, x, y} assert.is.equal('bar', util.array_search(arr, function (x) return x == 'bar' end)) assert.is.equal(123, util.array_search(arr, function (x) return type(x) == 'number' end)) assert.is.equal(nil, util.array_search(arr, function (x) return x == 456 end)) assert.is.equal(x, util.array_search(arr, function (e) return e == x end)) end) it("array_all()", function () local x = {1, 2, 3, 4, 5} local y = {2, 4, 6, 8, 10} local z = {1, 3, 5, 7, 9} assert.is_true(util.array_all(x, function (e) return type(e) == 'number' end)) assert.is_false(util.array_all(x, function (e) return (e % 2) == 0 end)) assert.is_true(util.array_all(y, function (e) return (e % 2) == 0 end)) assert.is_false(util.array_all(z, function (e) return (e % 2) == 0 end)) assert.is_false(util.array_all(x, function (e) return (e % 2) == 1 end)) assert.is_false(util.array_all(y, function (e) return (e % 2) == 1 end)) assert.is_true(util.array_all(z, function (e) return (e % 2) == 1 end)) end) it("array_equals()", function () local x = {1, 2, 3, 4, 5} local y = {1, 2, 3, 4} local z = {1, 2, 3, 4, 5} local w = {1, 2, 3, 4, 6} assert.is_false(util.array_equals(x, y)) assert.is_false(util.array_equals(x, w)) assert.is_true(util.array_equals(x, z)) end) it("array_find()", function () local x = {5, 4, 3, 2, 1} assert.is.equal(1, util.array_find(x, 5)) assert.is.equal(2, util.array_find(x, 4)) assert.is.equal(3, util.array_find(x, 3)) assert.is.equal(4, util.array_find(x, 2)) assert.is.equal(5, util.array_find(x, 1)) assert.is.equal(nil, util.array_find(x, 0)) assert.is.equal(nil, util.array_find(x, 6)) end) end)
local libgen = require 'libgen' local config = assert(arg[1]) local T = require (config) assert(type(T) == "table") use_lua = false libgen(T, use_lua)
-------------------------------- -- @module Animate3D -- @extend ActionInterval -- @parent_module cc -------------------------------- -- @function [parent=#Animate3D] getSpeed -- @param self -- @return float#float ret (return value: float) -------------------------------- -- @function [parent=#Animate3D] setWeight -- @param self -- @param #float float -------------------------------- -- @function [parent=#Animate3D] getPlayBack -- @param self -- @return bool#bool ret (return value: bool) -------------------------------- -- @function [parent=#Animate3D] setPlayBack -- @param self -- @param #bool bool -------------------------------- -- @function [parent=#Animate3D] setSpeed -- @param self -- @param #float float -------------------------------- -- @function [parent=#Animate3D] getWeight -- @param self -- @return float#float ret (return value: float) -------------------------------- -- overload function: create(cc.Animation3D, float, float) -- -- overload function: create(cc.Animation3D) -- -- @function [parent=#Animate3D] create -- @param self -- @param #cc.Animation3D animation3d -- @param #float float -- @param #float float -- @return Animate3D#Animate3D ret (retunr value: cc.Animate3D) -------------------------------- -- @function [parent=#Animate3D] startWithTarget -- @param self -- @param #cc.Node node -------------------------------- -- @function [parent=#Animate3D] step -- @param self -- @param #float float -------------------------------- -- @function [parent=#Animate3D] clone -- @param self -- @return Animate3D#Animate3D ret (return value: cc.Animate3D) -------------------------------- -- @function [parent=#Animate3D] reverse -- @param self -- @return Animate3D#Animate3D ret (return value: cc.Animate3D) -------------------------------- -- @function [parent=#Animate3D] update -- @param self -- @param #float float return nil
--呪詛返しのヒトガタ --id:Ruby QQ:917770701 function c100290023.initial_effect(c) --reflect local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_CHAINING) e1:SetCondition(c100290023.condition) e1:SetOperation(c100290023.refop) c:RegisterEffect(e1) --set local e2=Effect.CreateEffect(c) e2:SetCategory(CATEGORY_LEAVE_GRAVE) e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O) e2:SetCode(EVENT_BATTLE_DAMAGE) e2:SetRange(LOCATION_GRAVE) e2:SetCountLimit(1,100290023) e2:SetCondition(c100290023.setcon) e2:SetTarget(c100290023.settg) e2:SetOperation(c100290023.setop) c:RegisterEffect(e2) end function c100290023.condition(e,tp,eg,ep,ev,re,r,rp) return aux.damcon1(e,tp,eg,ep,ev,re,r,rp) and re:IsActiveType(TYPE_MONSTER) end function c100290023.refop(e,tp,eg,ep,ev,re,r,rp) local cid=Duel.GetChainInfo(ev,CHAININFO_CHAIN_ID) local e1=Effect.CreateEffect(e:GetHandler()) e1:SetType(EFFECT_TYPE_FIELD) e1:SetCode(EFFECT_REFLECT_DAMAGE) e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET) e1:SetTargetRange(1,0) e1:SetLabel(cid) e1:SetValue(c100290023.refcon) e1:SetReset(RESET_CHAIN) Duel.RegisterEffect(e1,tp) end function c100290023.refcon(e,re,val,r,rp,rc) local cc=Duel.GetCurrentChain() if cc==0 or bit.band(r,REASON_EFFECT)==0 then return end local cid=Duel.GetChainInfo(0,CHAININFO_CHAIN_ID) return cid==e:GetLabel() end function c100290023.setcon(e,tp,eg,ep,ev,re,r,rp) return ep==tp end function c100290023.settg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return e:GetHandler():IsSSetable() end Duel.SetOperationInfo(0,CATEGORY_LEAVE_GRAVE,e:GetHandler(),1,0,0) end function c100290023.setop(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() if c:IsRelateToEffect(e) then Duel.SSet(tp,c) end end
-- file: runme.lua -- This file illustrates class C++ interface generated -- by SWIG. ---- importing ---- if string.sub(_VERSION,1,7)=='Lua 5.0' then -- lua5.0 doesnt have a nice way to do this lib=loadlib('example.dll','luaopen_example') or loadlib('example.so','luaopen_example') assert(lib)() else -- lua 5.1 does require('example') end ----- Object creation ----- print("Creating some objects:") c = example.Circle(10) print(" Created circle", c) s = example.Square(10) print(" Created square", s) ----- Access a static member ----- print("\nA total of",example.Shape_nshapes,"shapes were created") ----- Member data access ----- -- Set the location of the object c.x = 20 c.y = 30 s.x = -10 s.y = 5 print("\nHere is their current position:") print(string.format(" Circle = (%f, %f)",c.x,c.y)) print(string.format(" Square = (%f, %f)",s.x,s.y)) ----- Call some methods ----- print("\nHere are some properties of the shapes:") for _,o in pairs({c,s}) do print(" ", o) print(" area = ", o:area()) print(" perimeter = ", o:perimeter()) end print("\nGuess I'll clean up now") -- Note: this invokes the virtual destructor c=nil s=nil -- call gc to make sure they are collected collectgarbage() print(example.Shape_nshapes,"shapes remain") print "Goodbye"
local file = require 'pl.file' local textx = require 'pl.text' local stringx = require 'pl.stringx' local tablex = require 'pl.tablex' local path = require 'pl.path' local dir = require 'pl.dir' --[[ Return a table describing the .dokx config format Table entries are themselves tables, with keys 'key', 'description' and 'default' ]] function dokx.configSpecification() return { { key = "filter", description = "pattern or table of patterns; file paths to include", default = 'nil' }, { key = "exclude", description = "pattern or table of patterns; file paths to exclude", default = "{ 'test', 'build' }" }, { key = "tocLevel", description = "string; level of detail for table of contents for inline docs: 'class', 'function' or 'none'", default = "'function'" }, { key = "tocLevelTopSection", description = "integer; max depth of table of contents for standalone .md docs", default = "nil" }, { key = "sectionOrder", description = "table; paths of .md files in order of priority", default = "nil" }, { key = "tocIncludeFilenames", description = "boolean; whether to include filenames as a top level in the table of contents", default = "false" }, { key = "mathematics", description = "boolean; whether to process mathematics blocks", default = "true" }, { key = "packageName", description = "string; override the inferred package namespace", default = "nil" }, { key = "githubURL", description = "string; $githubUser/$githubProject - used for generating links, if present", default = "nil" }, { key = "includeLocal", description = "boolean; whether to include local functions", default = "false" }, { key = "includePrivate", description = "boolean; whether to include private functions (i.e. those that begin with an underscore)", default = "false" }, { key = "section", description = "string; name of the section under which this package should be grouped in the main menu", default = "Miscellaneous" } } end -- Calling this puts dokx into debug mode. function dokx.debugMode() dokx.logger.level = logroll.DEBUG dokx._inDebugMode = true end -- Return true if dokx is in debug mode. function dokx.inDebugMode() return dokx._inDebugMode end --[[ Return true if x is an instance of the given class ]] function dokx._is_a(x, className) return torch.typename(x) == className end --[[ Create a temporary directory and return its path ]] function dokx._mkTemp() local file = io.popen("mktemp -d -t dokx_XXXXXX") local name = stringx.strip(file:read("*all")) file:close() return name end function dokx._withTmpDir(func) local tmpDir = dokx._mkTemp() func(tmpDir) dir.rmtree(tmpDir) end --[[ Read the whole of the given file's contents, and return it as a string. Args: * `inputPath` - path to a file Returns: string containing the contents of the file --]] function dokx._readFile(inputPath) if not path.isfile(inputPath) then error("Not a file: " .. tostring(inputPath)) end dokx.logger.debug("Opening " .. tostring(inputPath)) local inputFile = io.open(inputPath, "rb") if not inputFile then error("Could not open: " .. tostring(inputPath)) end local content = inputFile:read("*all") inputFile:close() return content end --[[ Given the path to a directory, return the name of the last component ]] function dokx._getLastDirName(dirPath) local split = tablex.filter(stringx.split(path.normpath(path.abspath(dirPath)), "/"), function(x) return x ~= '' end) local packageName = split[#split] if stringx.strip(packageName) == '' then error("malformed package name for " .. dirPath) end return packageName end --[[ Given a path to a file, an expected extension, and a new extension, return the path to a file with the same name but the new extension. Throws an error if the file does not have the expected extension. --]] function dokx._convertExtension(extension, newExtension, filePath) if not stringx.endswith(filePath, "." .. extension) then error("Expected ." .. extension .. " file") end return filePath:sub(1, -string.len(extension) - 1) .. newExtension end function dokx._searchDBPath(docRoot) return path.join(docRoot, "_search.sqlite3") end function dokx._markdownPath(docRoot) return path.join(docRoot, "_markdown") end --[[ Create a function that will prepend the given path prefix onto its argument. Example: > f = dokx._prependPath("/usr/local") > print(f("bin")) "/usr/local/bin" --]] function dokx._prependPath(prefix) return function(suffix) return path.join(prefix, suffix) end end --[[ Given a comment string, remove extraneous symbols and spacing ]] function dokx._normalizeComment(text) text = stringx.strip(tostring(text)) local lines = stringx.splitlines(text) tablex.transform(function(line) line = line:gsub("^%[=*%[", "") line = line:gsub("%]=*%]$", "") if stringx.startswith(line, "--") then local chopIndex = 3 if stringx.startswith(line, "-- ") then chopIndex = 4 end line = line:sub(chopIndex) end if stringx.endswith(line, "--") then line = line:sub(1, -3) end line = line:gsub("^%[=*%[", "") line = line:gsub("%]=*%]$", "") return line end, lines) text = stringx.join("\n", lines) -- Ensure we end with a new line if text[#text] ~= '\n' then text = text .. "\n" end return text end function dokx._loadConfig(packagePath) local configPath if packagePath then if path.isfile(packagePath) then configPath = packagePath else configPath = path.join(packagePath, ".dokx") end end local configTable = {} -- If config file exists, try to load it if configPath and path.isfile(configPath) then local configFunc, err = loadfile(configPath) if err then error("dokx._loadConfig: error loading dokx config " .. configPath .. ": " .. err) end configTable = configFunc() if not configTable or type(configTable) ~= 'table' then error("dokx._loadConfig: dokx config file must return a lua table! " .. configPath) end end local configSpec = dokx.configSpecification() local allowedKeys = {} local defaultValues = {} for _, configEntry in pairs(configSpec) do allowedKeys[configEntry.key] = true defaultValues[configEntry.key] = configEntry.default end -- Check for unknown keys for key, value in pairs(configTable) do if not allowedKeys[key] then error("dokx._loadConfig: unknown key '" .. key .. "' in dokx config file " .. configPath) end end -- Assign defaults, where value was not specified for key, _ in pairs(allowedKeys) do if configTable[key] == nil then local default = loadstring("return " .. defaultValues[key])() dokx.logger.info("dokx._loadConfig: no value specified for key '" .. key .. "' - using default: " .. tostring(default)) configTable[key] = default end end return configTable end function dokx._filterFiles(files, pattern, invert) if not pattern then return files end if type(pattern) == 'string' then pattern = { pattern } end for _, patternString in ipairs(pattern) do files = tablex.filter(files, function(x) local admit = string.find(x, patternString) if invert then admit = not admit end if not admit then dokx.logger.info("dokx.buildPackageDocs: skipping file excluded by filter: " .. x) end return admit end) end return files end function dokx._getDokxDir() return path.dirname(debug.getinfo(1, 'S').source:gsub('^[@=]', '')) end function dokx._getTemplate(templateFile) local dokxDir = dokx._getDokxDir() local templateDir = path.join(dokxDir, "templates") return path.join(templateDir, templateFile) end function dokx._getTemplateContents(templateFile) return textx.Template(dokx._readFile(dokx._getTemplate(templateFile))) end function dokx._sanitizePath(pathString) local sanitized = path.normpath(path.abspath(pathString)) if stringx.endswith(sanitized, "/.") then sanitized = sanitized:sub(1, -3) end return sanitized end function dokx._which(command) local cmd = io.popen("which " .. command) local result = stringx.strip(cmd:read("*all")) cmd:close() if result == '' then return nil end return result end --[[ Given a table of possible commands, return the path for the first one that exists, or nil if none do. Example: dokx._chooseCommand { 'open', 'xdg-open' } --]] function dokx._chooseCommand(commands) for _, command in ipairs(commands) do local result = dokx._which(command) if result then return result end end return nil end function dokx._urlEncode(str) if (str) then str = string.gsub (str, "\n", "\r\n") str = string.gsub (str, "([^%w %-%_%.%~])", function (c) return string.format ("%%%02X", string.byte(c)) end) str = string.gsub (str, " ", "+") end return str end function dokx._openBrowser(url) local browser = dokx._chooseCommand { "open", "xdg-open", "firefox" } if not browser then dokx.logger.error("dokx.browse: could not find a browser") return end os.execute(browser .. " " .. url) end function dokx._copyFilesToDir(files, dirPath, copyFunc) local outputs = {} copyFunc = copyFunc or file.copy tablex.foreach(files, function(filePath) local dest = path.join(dirPath, path.basename(filePath)) if path.isfile(dest) then dokx.logger.warn("*** Overwriting markdown file " .. dest .. " ***") end copyFunc(filePath, dest) table.insert(outputs, dest) end) return outputs end function dokx._pruneFunctions(config, documentedFunctions, undocumentedFunctions) if not config or not config.includeLocal then local function notLocal(x) if x:isLocal() then dokx.logger.info("Excluding local function " .. x:fullname()) return false end return true end documentedFunctions = tablex.filter(documentedFunctions, notLocal) undocumentedFunctions = tablex.filter(undocumentedFunctions, notLocal) end if not config or not config.includePrivate then local function notPrivate(x) if x:isPrivate() then dokx.logger.info("Excluding private function " .. x:fullname()) return false end return true end documentedFunctions = tablex.filter(documentedFunctions, notPrivate) undocumentedFunctions = tablex.filter(undocumentedFunctions, notPrivate) end return documentedFunctions, undocumentedFunctions end
return { plan = function(char, state) for _,task in ipairs(state) do char:push_task(task.name, task.state) end end, perform = function(char, state) return true end }
local jua = nil local idPatt = "#R%d+" if not ((socket and socket.websocket) or http.websocketAsync) then error("You do not have CC:Tweaked/CCTweaks installed or you are not on the latest version.") end local newws = socket and socket.websocket or http.websocketAsync local async if socket and socket.websocket then async = false else async = true end local callbackRegistry = {} wsRegistry = {} local function gfind(str, patt) local t = {} for found in str:gmatch(patt) do table.insert(t, found) end if #t > 0 then return t else return nil end end local function findID(url) local found = gfind(url, idPatt) return tonumber(found[#found]:sub(found[#found]:find("%d+"))) end local function newID() return #callbackRegistry + 1 end local function trimID(url) local found = gfind(url, idPatt) local s, e = url:find(found[#found]) return url:sub(1, s-1) end function open(callback, url, headers) local id if async then id = newID() end local newUrl if async then newUrl = url .. "#R" .. id newws(newUrl, headers) else if headers then error("Websocket headers not supported under CCTweaks") end local ws = newws(url) ws.send = ws.write id = ws.id() wsRegistry[id] = ws end callbackRegistry[id] = callback return id end function init(jua) jua = jua if async then jua.on("websocket_success", function(event, url, handle) local id = findID(url) if type(callbackRegistry[id]) == "table" and callbackRegistry[id].success then callbackRegistry[id].success(findID(url), handle) end end) jua.on("websocket_failure", function(event, url) local id = findID(url) if type(callbackRegistry[id]) == "table" and callbackRegistry[id].failure then callbackRegistry[id].failure(findID(url)) end table.remove(callbackRegistry, id) end) jua.on("websocket_message", function(event, url, data) local id = findID(url) if type(callbackRegistry[id]) == "table" and callbackRegistry[id].message then callbackRegistry[id].message(findID(url), data) end end) jua.on("websocket_closed", function(event, url) local id = findID(url) if type(callbackRegistry[id]) == "table" and callbackRegistry[id].closed then callbackRegistry[id].closed(findID(url)) end table.remove(callbackRegistry, id) end) else jua.on("socket_connect", function(event, id) if type(callbackRegistry[id]) == "table" and callbackRegistry[id].success then callbackRegistry[id].success(id, wsRegistry[id]) end end) jua.on("socket_error", function(event, id, msg) if type(callbackRegistry[id]) == "table" and callbackRegistry[id].failure then callbackRegistry[id].failure(id, msg) end table.remove(callbackRegistry, id) end) jua.on("socket_message", function(event, id) if type(callbackRegistry[id]) == "table" and callbackRegistry[id].message then local data = wsRegistry[id].read() callbackRegistry[id].message(id, data) end end) jua.on("socket_closed", function(event, id) if type(callbackRegistry[id]) == "table" and callbackRegistry[id].closed then callbackRegistry[id].closed(id) end table.remove(callbackRegistry, id) end) end end return { open = open, init = init }
-- `--::-.` -- ./shddddddddhs+. -- :yddddddddddddddddy: -- `sdddddddddddddddddddds` -- ydddh+sdddddddddy+ydddds M-Like:main -- /ddddy:oddddddddds:sddddd/ By adebray - adebray -- sdddddddddddddddddddddddds -- sdddddddddddddddddddddddds Created: 2015-10-26 21:10:55 -- :ddddddddddhyyddddddddddd: Modified: 2015-12-01 04:57:35 -- odddddddd/`:-`sdddddddds -- +ddddddh`+dh +dddddddo -- -sdddddh///sdddddds- -- .+ydddddddddhs/. -- .-::::-` Lib = require 'libs.Lib' Box = require 'libs.Box' UI = require 'libs.loveframes' Event = require 'libs.Event' Meshes = require 'libs.Meshes' Quadlist = require 'libs.Quadlist' Point = require 'libs.Point' Vertice = require 'libs.Vertice' Entity = require 'libs.Entity' inspect = require 'libs.inspect' print(inspect(_G._VERSION)) Modes = { 'none', -- 'editor', 'debug' } love.mode = Modes[2] function love.load() face = love.graphics.newImage('assets/image.bmp') image = love.graphics.newImage('assets/tile.png') player_image = love.graphics.newImage('assets/PlayerLeft.png') player_image:setFilter('nearest', 'nearest') player_quad = Quadlist.new({image = player_image, width = 8, height = 8}) tiles_image = love.graphics.newImage('assets/Tiles_Basic.png') tiles_image:setFilter('nearest', 'nearest') tiles_quad = Quadlist.new({image = tiles_image, width = 8, height = 8}) local size = 42 for i=love.window.getWidth() - (size * 10), love.window.getWidth() ,size do local v = Vertice.newFromCenter(i, love.window.getHeight() - size / 2 , size / 2) Meshes:add(v, tiles_quad.images[3]) end local size = 42 for i=0, size * 5 ,size do local v = Vertice.newFromCenter(i, love.window.getHeight() - (size + 10) * 2 , size / 2) Meshes:add(v, tiles_quad.images[3]) end local size = 42 for i=love.window.getWidth() - (size * 10), love.window.getWidth() ,size do local v = Vertice.newFromCenter(i, love.window.getHeight() - size * 4 , size / 2) Meshes:add(v, tiles_quad.images[3]) end local size = 42 for i=love.window.getHeight() - (size * 10), love.window.getHeight() ,size do local v = Vertice.newFromCenter(love.window.getWidth() - size / 2, i , size / 2) Meshes:add(v, tiles_quad.images[3]) end player = Entity.player(player_quad) local slider_speed_mul = UI.Create("slider") slider_speed_mul:SetPos(42, 50) slider_speed_mul:SetWidth(100) slider_speed_mul:SetMinMax(0, 1000) slider_speed_mul.value = player.speed_mul slider_speed_mul.Update = function (object, dt) player.speed_mul = math.floor(object.value) end local slider_gravity = UI.Create("slider") slider_gravity:SetPos(42, 100) slider_gravity:SetWidth(100) slider_gravity:SetMinMax(0, 100) slider_gravity.value = player.mass slider_gravity.Update = function (object, dt) player.mass = math.floor(object.value) end local slider_speed_max = UI.Create("slider") slider_speed_max:SetPos(42, 150) slider_speed_max:SetWidth(100) slider_speed_max:SetMinMax(0, 100) slider_speed_max.value = player.speed_max slider_speed_max.Update = function (object, dt) player.speed_max = math.floor(object.value) end local slider_jump = UI.Create("slider") slider_jump:SetPos(42, 200) slider_jump:SetWidth(100) slider_jump:SetMinMax(0, 100) slider_jump.value = player.jump slider_jump.Update = function (object, dt) player.jump = math.floor(object.value) end local button_mode = UI.Create("button") button_mode:SetText(love.mode) button_mode:SetPos(700, 10) button_mode.OnClick = function (object, x, y) for i,v in ipairs(Modes) do if v == love.mode then if i ~= #Modes then love.mode = Modes[i + 1] else love.mode = Modes[1] end object:SetText(love.mode) return end end end end function love.update(dt) love.last_dt = dt local x, y = player.position.x, player.position.y player:update(dt) local newx, newy = player.position.x, player.position.y Meshes:move(Point.new(x - newx, y - newy)) UI.update(dt) end function love.draw() Meshes:draw() player:draw() love.graphics.print('Speed Mul', 5, 30) love.graphics.print(player.speed_mul, 150, 30) love.graphics.print('Mass', 5, 80) love.graphics.print(player.mass, 50, 80) love.graphics.print('Speed Max', 5, 130) love.graphics.print(player.speed_max, 100, 130) love.graphics.print('Jump Str', 5, 180) love.graphics.print(player.jump, 100, 180) UI:draw() end
require "behaviours/standstill" require "behaviours/runaway" require "behaviours/doaction" require "behaviours/panic" require "behaviours/wander" require "behaviours/chaseandattack" local MAX_CHASE_TIME = 60 local MAX_CHASE_DIST = 40 local BatBrain = Class(Brain, function(self, inst) Brain._ctor(self, inst) end) local function GoHomeAction(inst) if inst.components.homeseeker and inst.components.homeseeker.home and inst.components.homeseeker.home:IsValid() and inst.components.homeseeker.home.components.childspawner and not inst.components.teamattacker.inteam then return BufferedAction(inst, inst.components.homeseeker.home, ACTIONS.GOHOME) end end local function EatFoodAction(inst) local target = nil if inst.sg:HasStateTag("busy") then return end if inst.components.inventory and inst.components.eater then target = inst.components.inventory:FindItem(function(item) return inst.components.eater:CanEat(item) end) if target then return BufferedAction(inst,target,ACTIONS.EAT) end end if not target then target = FindEntity(inst, 30, function(item) if item:GetTimeAlive() < 8 then return false end if not item:IsOnValidGround() then return false end return inst.components.eater:CanEat(item) end) end if target then return BufferedAction(inst,target,ACTIONS.PICKUP) end -- local target = FindEntity(inst, 30, function(item) return inst.components.eater:CanEat(item) and not (item.components.inventoryitem and item.components.inventoryitem:IsHeld()) end) -- if target then -- local act = BufferedAction(inst, target, ACTIONS.EAT) -- act.validfn = function() return not (target.components.inventoryitem and target.components.inventoryitem:IsHeld()) end -- return act -- end end function BatBrain:OnStart() local root = PriorityNode( { WhileNode( function() return self.inst.components.health.takingfiredamage and not self.inst.components.teamattacker.inteam end, "OnFire", Panic(self.inst)), AttackWall(self.inst), ChaseAndAttack(self.inst, MAX_CHASE_TIME, MAX_CHASE_DIST), WhileNode(function() return GetClock():IsDay() end, "IsDay", DoAction(self.inst, function() return GoHomeAction(self.inst) end ) ), WhileNode(function() return self.inst.components.teamattacker.teamleader == nil end, "No Leader Eat Action", DoAction(self.inst, EatFoodAction)), WhileNode(function() return self.inst.components.teamattacker.teamleader == nil end, "No Leader Wander Action", Wander(self.inst, function() return self.inst.components.knownlocations:GetLocation("home") end, 40)), }, .25) self.bt = BT(self.inst, root) end return BatBrain
module 'mock_edit' -------------------------------------------------------------------- local handleSize = 80 local handleArrowSize = 12 local handlePad = 15 -------------------------------------------------------------------- ---Handles -------------------------------------------------------------------- CLASS: TranslationHandle( CanvasItem ) function TranslationHandle:__init( option ) self.option = option self.activeAxis = false end function TranslationHandle:onLoad() local option = self.option self:attach( mock.DrawScript() ) end function TranslationHandle:onDraw() applyColor 'handle-all' MOAIDraw.fillRect( 0,0, handleArrowSize, handleArrowSize ) --x axis applyColor 'handle-x' MOAIDraw.drawLine( 0,0, handleSize, 0 ) MOAIDraw.fillFan( handleSize, handleArrowSize/3, handleSize + handleArrowSize, 0, handleSize, -handleArrowSize/3 -- handleSize, handleArrowSize/3 ) -- MOAIDraw.fillFan( 0,0, handleSize / 5, handleSize / 5 ) --y axis applyColor 'handle-y' MOAIDraw.drawLine( 0,0, 0, handleSize ) MOAIDraw.fillFan( handleArrowSize/3, handleSize, 0, handleSize + handleArrowSize, -handleArrowSize/3, handleSize -- handleArrowSize/3, handleSize, ) end function TranslationHandle:wndToTarget( x, y ) local x, y = self:wndToWorld( x, y ) if self.target then local parent = self.target.parent if parent then return parent:worldToModel( x, y ) end end return x, y end function TranslationHandle:setTarget( target ) self.target = target target:setUpdateMasks( true, false, false ) inheritLoc( self:getProp(), target:getProp() ) end function TranslationHandle:inside( x, y ) return self:calcActiveAxis( x, y ) ~= false end function TranslationHandle:calcActiveAxis( x, y ) x, y = self:wndToModel( x, y ) if x >= 0 and y >= 0 and x <= handleArrowSize + handlePad and y <= handleArrowSize + handlePad then return 'all' elseif math.abs( y ) < handlePad and x <= handleSize + handleArrowSize and x > -handlePad then return 'x' elseif math.abs( x ) < handlePad and y <= handleSize + handleArrowSize and y > -handlePad then return 'y' end return false end function TranslationHandle:onMouseDown( btn, x, y ) if btn~='left' then return end self.activeAxis = false self.x0, self.y0 = self:wndToWorld( x, y ) target = self.target target:forceUpdate() local tx, ty = self.target:getLoc() self.tx0, self.ty0 = tx, ty self.activeAxis = self:calcActiveAxis( x, y ) if self.activeAxis then self.target:preTransform() return true end end function TranslationHandle:onMouseUp( btn, x, y ) if btn~='left' then return end if not self.activeAxis then return end self.activeAxis = false return true end function TranslationHandle:onDrag( btn, x, y ) if not self.activeAxis then return end local target = self.target target:forceUpdate() self:forceUpdate() x, y = self:wndToWorld( x, y ) local dx = x - self.x0 local dy = y - self.y0 local tx0, ty0 = self.tx0, self.ty0 local tx, ty = tx0 + dx, ty0 + dy -- local mode = 'global' -- local parent = target.parent -- if parent and mode == 'global' then -- local wx, wy = target:getWorldLoc() -- local wx1, wy1 = parent:modelToWorld( tx + dx, ty + dy ) -- wx1, wy1 = self:getView():snapLoc( wx1, wy1 ) -- if self.activeAxis == 'all' then -- --pass -- elseif self.activeAxis == 'x' then -- wy1 = wy -- elseif self.activeAxis == 'y' then -- wx1 = wx -- end -- tx, ty = parent:worldToModel( wx1, wy1 ) -- else -- local wx1, wy1 = tx + dx, ty + dy -- wx1, wy1 = self:getView():snapLoc( wx1, wy1 ) -- if self.activeAxis == 'all' then -- --pass -- elseif self.activeAxis == 'x' then -- wy1 = ty -- elseif self.activeAxis == 'y' then -- wx1 = tx -- end -- tx, ty = wx1, wy1 -- end tx, ty = self:getView():snapLoc( tx, ty, nil, self.activeAxis ) if self.activeAxis == 'all' then --pass elseif self.activeAxis == 'x' then ty = ty0 elseif self.activeAxis == 'y' then tx = tx0 end target:setLoc( tx, ty ) self.tool:updateCanvas() return true end -------------------------------------------------------------------- ---ROTATION -------------------------------------------------------------------- CLASS: RotationHandle( CanvasItem ) function RotationHandle:__init( option ) self.option = option self.align = false self.active = false self.size = handleSize end function RotationHandle:onLoad() self:attach( mock.DrawScript() ) end function RotationHandle:setTarget( target ) self.target = target inheritLoc( self:getProp(), target:getProp() ) self.r0 = target:getRotZ() end function RotationHandle:inside( x, y ) local x1, y1 = self:wndToModel( x, y ) local r = distance( 0,0, x1,y1 ) return r <= self.size end function RotationHandle:onDraw() if self.active then applyColor 'handle-active' else applyColor 'handle-z' end MOAIDraw.fillCircle( 0, 0, 5 ) MOAIDraw.drawCircle( 0, 0, self.size ) local r = self.target:getRotZ() MOAIDraw.drawLine( 0,0, vecAngle( r, self.size ) ) if self.active then applyColor 'handle-previous' MOAIDraw.drawLine( 0,0, vecAngle( self.r0, self.size ) ) end end function RotationHandle:onMouseDown( btn, x, y ) if btn~='left' then return end local x1, y1 = self:wndToModel( x, y ) local rx,ry,rz = self.target:getRot() self.rot0 = rz self.dir0 = direction( 0,0, x1,y1 ) self.active = true self.target:preTransform() self.r0 = self.target:getRotZ() self.tool:updateCanvas() return true end function RotationHandle:onDrag( btn, x, y ) if not self.active then return end local x1, y1 = self:wndToModel( x, y ) local r = distance( 0,0, x1,y1 ) if r>5 then local dir = direction( 0,0, x1,y1) local ddir = dir - self.dir0 local rx,ry,rz = self.target:getRot() rz = self.rot0 + ddir * 180/math.pi self.target:setRot( rx, ry, rz ) gii.emitPythonSignal( 'entity.modified', self.target, 'view' ) self.tool:updateCanvas() end return true end function RotationHandle:onMouseUp( btn, x, y ) if btn~='left' then return end if not self.active then return end self.active = false self.tool:updateCanvas() return true end -------------------------------------------------------------------- ---SCALE Handle -------------------------------------------------------------------- CLASS: ScaleHandle( CanvasItem ) function ScaleHandle:__init( option ) self.option = option self.activeAxis = false end function ScaleHandle:onLoad() local option = self.option self:attach( mock.DrawScript() ) end function ScaleHandle:onDraw() applyColor 'handle-all' MOAIDraw.fillRect( 0, 0, handleArrowSize, handleArrowSize ) --x axis applyColor 'handle-x' MOAIDraw.drawLine( 0, 0, handleSize, 0 ) MOAIDraw.fillRect( handleSize,0, handleSize + handleArrowSize, handleArrowSize ) --y axis applyColor 'handle-y' MOAIDraw.drawLine( 0, 0, 0, handleSize ) MOAIDraw.fillRect( 0, handleSize, handleArrowSize, handleSize + handleArrowSize ) end function ScaleHandle:setTarget( target ) self.target = target inheritLoc( self:getProp(), target:getProp() ) end function ScaleHandle:inside( x, y ) return self:calcActiveAxis( x, y ) ~= false end function ScaleHandle:calcActiveAxis( x, y ) x, y = self:wndToModel( x, y ) if x >= 0 and y >= 0 and x <= handleArrowSize + handlePad and y <= handleArrowSize + handlePad then return 'all' elseif math.abs( y ) < handlePad and x <= handleSize + handleArrowSize and x > -handlePad then return 'x' elseif math.abs( x ) < handlePad and y <= handleSize + handleArrowSize and y > -handlePad then return 'y' end return false end function ScaleHandle:onMouseDown( btn, x, y ) if btn~='left' then return end self.x0 = x self.y0 = y self.activeAxis = self:calcActiveAxis( x, y ) self.sx, self.sy, self.sz = self.target:getScl() if self.activeAxis then self.target:preTransform() return true end end function ScaleHandle:onMouseUp( btn, x, y ) if btn~='left' then return end if not self.activeAxis then return end self.activeAxis = false return true end function ScaleHandle:onDrag( btn, x, y ) if not self.activeAxis then return end local target = self.target target:forceUpdate() self:forceUpdate() local dx = x - self.x0 local dy = y - self.y0 local mode = 'global' local parent = target.parent -- if parent and mode == 'global' then if self.activeAxis == 'all' then local k = 1 + math.magnitude( dx, dy ) / 100 * math.sign(dx) self.target:setScl( self.sx * k, self.sy * k, self.sz * 1 ) elseif self.activeAxis == 'x' then local k = 1 + math.magnitude( dx, 0 ) / 100 * math.sign(dx) self.target:setScl( self.sx * k, self.sy * 1, self.sz * 1 ) elseif self.activeAxis == 'y' then local k = 1 - math.magnitude( dy, 0 ) / 100 * math.sign(dy) self.target:setScl( self.sx * 1, self.sy * k, self.sz * 1 ) end -- else -- local k = 1 + math.magnitude( dx, dy ) / 100 * math.sign(dx) -- self.target:setScl( -- self.sx * k, -- self.sy * k, -- self.sz * 1 ) -- end self.tool:updateCanvas() return true end -------------------------------------------------------------------- ---Transform Tool -------------------------------------------------------------------- CLASS: TransformTool ( SelectionTool ) function TransformTool:__init() self.handle = false end function TransformTool:onLoad() TransformTool.__super.onLoad( self ) self:updateSelection() end function TransformTool:onSelectionChanged( selection ) self:updateSelection() end function TransformTool:updateSelection() local selection = self:getSelection() local entities = {} for i, e in ipairs( selection ) do if isInstance( e, mock.Entity ) then entities[ e ] = true end end if self.handle then self:removeCanvasItem( self.handle ) end self.handle = false self.target = false local topEntities = self:findTopLevelEntities( entities ) if topEntities then local target = mock_edit.TransformToolHelper() target:setTargets( topEntities ) self.target = target self.handle = self:createHandle( target ) self:addCanvasItem( self.handle ) end self:updateCanvas() end function TransformTool:createHandle( target ) --Abstract end -------------------------------------------------------------------- CLASS: TranslationTool ( TransformTool ) :MODEL{} function TranslationTool:createHandle( target ) local handle = TranslationHandle() handle:setTarget( target ) return handle end -------------------------------------------------------------------- CLASS: RotationTool ( TransformTool ) :MODEL{} function RotationTool:createHandle( target ) local handle = RotationHandle() handle:setTarget( target ) if target.targetCount > 1 then target:setUpdateMasks( true, true, false ) else target:setUpdateMasks( false, true, false ) end return handle end -------------------------------------------------------------------- CLASS: ScaleTool ( TransformTool ) :MODEL{} function ScaleTool:createHandle( target ) local handle = ScaleHandle() handle:setTarget( target ) if target.targetCount > 1 then target:setUpdateMasks( false, true, true ) else target:setUpdateMasks( false, false, true ) end return handle end -------------------------------------------------------------------- registerCanvasTool( 'translation', TranslationTool ) registerCanvasTool( 'rotation', RotationTool ) registerCanvasTool( 'scale', ScaleTool )
object_tangible_food_generic_drink_breath_of_heaven = object_tangible_food_generic_shared_drink_breath_of_heaven:new { } ObjectTemplates:addTemplate(object_tangible_food_generic_drink_breath_of_heaven, "object/tangible/food/generic/drink_breath_of_heaven.iff")
--[[ ByteStorage, CharStorage, ShortStorage, IntStorage, LongStorage, FloatStorage, DoubleStorage. ]]-- require 'torch' x = torch.IntStorage(10):fill(1) --print("IntStorage default:",torch.IntStorage(10)) --random value print("IntStorage:",x) print(x[5]) -- convert int to double y = torch.DoubleStorage(10):copy(x) print("DoubleStorage",y) x = torch.IntStorage({1,2,3,4}); print("IntStorage with table:", x) -- create with size 10 x = torch.DoubleStorage(10); -- create storage from x , and start offset(index = 2) = 3, size = 5. change y will effect x y = torch.DoubleStorage(x, 3, 5) y = y:fill(1) print("with offset x: ", x) print("with offset y: ", y) -- create storage with share memory or not x = torch.CharStorage('hello.txt') -- read only print("hello:",x) print("hello:",x:string()) -- create storage of shared memeory with size = 10. x = torch.CharStorage('hello2.txt', true, 10) x:fill(42); print("hello2:", x) --[[ func: #self self[index] [self] copy(storage) [self] fill(value) [self] resize(size) [number] size() [self] string(str) * This function is available only on ByteStorage and CharStorage.* This method resizes the storage to the length of the provided string str, and copy the contents of str into the storage. The NULL terminating character is not copied, but str might contain NULL characters. The method returns the Storage. [string] string() * This function is available only on ByteStorage and CharStorage.* retain() increare reference free() decrease reference. free if 0. ]]--
--[[/* * (C) 2012-2013 Marmalade. * * 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. */--]] -------------------------------------------------------------------------------- -- Labels -------------------------------------------------------------------------------- QLabel = {} QLabel.__index = QNode -------------------------------------------------------------------------------- -- Private API -------------------------------------------------------------------------------- QLabel.serialize = function(o) local obj = serializeTLMT(getmetatable(o), o) table.setValuesFromTable(obj, serializeTLMT(getmetatable(quick.QLabel), o)) return obj end --[[ /* Initialise the peer table for the C++ class QNode. This must be called immediately after the QNode() constructor. */ --]] function QLabel:initLabel(l) local lp = {} setmetatable(lp, QLabel) tolua.setpeer(l, lp) local mt = getmetatable(n) mt.__serialize = QLabel.serialize end -------------------------------------------------------------------------------- -- Public API -------------------------------------------------------------------------------- --[[ /** Create a label node, specifying arbitrary input values. @param values Lua table specifying name/value pairs. @return The created label. */ --]] function director:createLabel(values) end --[[ /** Create a label node, at the specified screen position, with the specified text string. @param x X coordinate of label origin. @param y Y coordinate of label origin. @param text Text string. @param font a string or QFont defining the font to use. @return The created label. */ --]] function director:createLabel(x, y, text, font) local n = quick.QLabel() QNode:initNode(n) if (type(x) == "table") then -- Remove 'font' key from table, place in local variable font = x["font"] -- could be nil x["font"] = nil table.setValuesFromTable(n, x) else dbg.assertFuncVarTypes({"number", "number", "string"}, x, y, text) dbg.assertFuncVarTypes({"string", "userdata", "nil"}, font) n.x = x n.y = y n.text = text end if font == nil then -- Specify the default font if self.defaultFont == nil then dbg.print("Creating default font") self.defaultFont = self:createFont("fonts/Default.fnt") end font = self.defaultFont elseif type(font) == "string" then -- This version creates a font object from the string first font = self:createFont(font) n.fontlock = font end n.font = font n:init() self:addNodeToLists(n) -- Force a sync to allow changed parentage to take effect n:sync() return n end
local sWidth,sHeight = guiGetScreenSize() -- The variables -- add blips and convert to dxDrawImage function showMap() if map_window and guiGetVisible ( map_window ) == false then guiSetVisible( map_window, true) centerWindow(map_window) addEventHandler ( "onClientGUIClick", root, onMapClick ) addEventHandler ( "onClientRender", root, drawAllBlips ) showCursor(true) elseif not map_window then map_window = guiCreateWindow(365,71,705,735,"GPS: Pick a location on the map.",false) centerWindow(map_window) local windowX, windowY = guiGetPosition(map_window,false) local windowWidth, windowHeight = guiGetSize ( map_window, false ) map_image = guiCreateStaticImage(5, 20,windowWidth-5, windowHeight-60,":CSGmods/Mods/map.png",false,map_window) map_button_close = guiCreateButton(301,695,112,36,"Close",false,map_window) showCursor(true) addEventHandler ( "onClientGUIClick", root, onMapClick ) --addPlayerBlip() --drawAllBlips() addEventHandler ( "onClientRender", root, drawAllBlips ) elseif map_window and guiGetVisible ( map_window ) then centerWindow(map_window) end end function drawPlayerBlip () local px, py, pz = getElementPosition ( localPlayer ) local prz = getPedRotation ( localPlayer ) local imagePosX, imagePosY = guiGetPosition(map_image,false) local windowX, windowY = guiGetPosition(map_window,false) local windowWidth, windowHeight = guiGetSize ( map_window, false ) local iWidth, iHeight = guiGetSize ( map_image, false ) local worldPercX = ((px+3000) / 6000)-0.03 local worldPercY = ((3000+py) / 6000)+0.03 local imageX = worldPercX * iWidth local imageY = ( 1 - worldPercY ) * iHeight local screenX = imageX+windowX+5 local screenY = imageY+windowY+20 if screenX and screenY then --map_playerBlip = guiCreateStaticImage(screenX, screenY,32, 32,"blips/player.png",false,map_image) --guiBringToFront(map_playerBlip) dxDrawImage ( screenX, screenY, 32, 32, "blips/player.png", prz-30, 0, 0, tocolor(255,255,255), true ) end end function drawAllBlips() -- draw player blip drawPlayerBlip () -- draw other blips local players = getElementsByType ( "player" ) for i, player in ipairs(players) do if player ~= localPlayer then local px, py, pz = getElementPosition ( player ) local imagePosX, imagePosY = guiGetPosition(map_image,false) local windowX, windowY = guiGetPosition(map_window,false) local windowWidth, windowHeight = guiGetSize ( map_window, false ) local iWidth, iHeight = guiGetSize ( map_image, false ) local worldPercX = ((px+3000) / 6000)-0.03 local worldPercY = ((3000+py) / 6000)+0.03 local imageX = worldPercX * iWidth local imageY = ( 1 - worldPercY ) * iHeight local screenX = imageX+windowX+5 local screenY = imageY+windowY+20 if screenX and screenY then local color = tocolor(getPlayerBlipColor(player)) dxDrawImage ( screenX, screenY, 8, 8, "blips/playerBlip.png", 0, 0, 0, color, true ) end end end end local blipsForPlayers= {} function getPlayerBlipColor(player) if not blipsForPlayers[player] then local r = math.random(100,255) local g = math.random(100,255) local b = math.random(100,255) blipsForPlayers[player] = { r, g, b } end local playerTable = blipsForPlayers[player] local r, g, b = playerTable[1], playerTable[2], playerTable[3] return r, g, b end function closeMap() if isElement( map_window ) then guiSetVisible( map_window, false ) --destroyElement( map_playerBlip ) removeEventHandler ( "onClientGUIClick", root, onMapClick ) removeEventHandler ( "onClientRender", root, drawAllBlips ) end showCursor(false) end addCommandHandler ( 'gpsmap', showMap ) onMarkerHitCheckZ = false function onMapClick(btn, state, screenX, screenY) if source == map_image or source == map_playerBlip then local imagePosX, imagePosY = guiGetPosition(map_image,false) local windowX, windowY = guiGetPosition(map_window,false) local windowWidth, windowHeight = guiGetSize ( map_window, false ) local iWidth, iHeight = guiGetSize ( map_image, false ) local posX, posY = windowX+imagePosX, windowY+imagePosY local worldX = ((((screenX-posX)/(iWidth)))*6000)-3000 local worldY = (3000-(((screenY-posY)/(iHeight)))*6000) if worldX and worldY then local worldZ = getGroundPosition( worldX, worldY, 500 ) if onMarkerHitCheckZ == true then removeEventHandler( "onClientColShapeHit", checkForZCuboid, targetStreamedIn, false ) if isElement(checkForZMarker) then destroyElement(checkForZMarker) end if isElement(checkForZCuboid) then destroyElement(checkForZCuboid) end onMarkerHitCheckZ = false end checkForZMarker = createMarker ( worldX, worldY, worldZ, "cylinder", 100, 0, 0, 0, 0 ) checkForZCuboid = createColCuboid ( worldX - 60, worldY - 60, worldZ, 120, 120, 80 ) if worldZ == 0 and not isMarkerInWater(checkForZMarker) then addEventHandler( "onClientColShapeHit", checkForZCuboid, targetStreamedIn, false ) onMarkerHitCheckZ = true elseif isMarkerInWater(checkForZMarker) then local waterLevel = getWaterLevel ( worldX, worldY, 5 ) if waterLevel then worldZ = waterLevel end end if onMarkerHitCheckZ == false then if isElement(checkForZMarker) then destroyElement(checkForZMarker) end if isElement(checkForZCuboid) then destroyElement(checkForZCuboid) end end setDestination ( worldX, worldY, worldZ, "Map Destination" ) closeMap() return else exports.DENhelp:createNewHelpMessage("Could not find location!", 255, 0, 0) end elseif source == map_button_close then closeMap() end end function isMarkerInWater(marker) if isElement(marker) then local x,y,z = getElementPosition(marker) local waterHeight = getWaterLevel(x,y,5) if waterHeight and z < waterHeight then return true end end return false end function targetStreamedIn (hitElement) if hitElement == localPlayer then local x,y,z,desc = getDestination () local px, py, pz = getElementPosition ( localPlayer ) local z = getGroundPosition( x, y, pz ) if z and ( z ~= 0 or isMarkerInWater(destinationMarker) ) then if isMarkerInWater(destinationMarker) then local waterLevel = getWaterLevel ( x, y, 5 ) if waterLevel then z = waterLevel end end removeEventHandler( "onClientColShapeHit", checkForZCuboid, targetStreamedIn, false ) destroyElement(checkForZMarker) destroyElement(source) onMarkerHitCheckZ = false setDestination ( x, y, z, "Map Destination", oldBlip ) elseif z == 0 then local testZ = pz while z == 0 and testZ < 500 do z = getGroundPosition( x, y, testZ+20 ) end if z ~= 0 or isMarkerInWater(destinationMarker) then if isMarkerInWater(destinationMarker) then local waterLevel = getWaterLevel ( x, y, 5 ) if waterLevel then z = waterLevel end end removeEventHandler( "onClientColShapeHit", checkForZCuboid, targetStreamedIn, false ) destroyElement(checkForZMarker) destroyElement(source) onMarkerHitCheckZ = false setDestination ( x, y, z, "Map Destination", oldBlip ) end end end end
-------------------ModuleInfo------------------- --- Author : jxy --- Date : 2020/02/15 23:58 --- Description : 所有类的基类 --- https://github.com/JomiXedYu/JxCode.LuaSharp ------------------------------------------------ ---@class SysLib.Object ---@field New fun() local Object = class.extends("SysLib.Object") --为了更好的智能提示,在Object中添加了New,但会覆盖原有的New方法 --所以先保存起来,然后在调用,本方法仅有在执行Object.New时才会执行,尽管这没有意义 local _new = Object.New ---@return self function Object.New() return _new() end function Object:constructor() end function Object:Dispose() end --virtual function Object:Equals(target) return self == target end ---@return Type function Object:GetType() ---元数据时存在元表当中的,所以要获取元表 local meta = getmetatable(self) assert(meta.__classType == class.ClassType.Instance , "该方法为实例方法") --返回类型对象指针 return meta.__type end function Object:ToString() return "<class: "..self:GetType():GetName()..">" end return Object
---@class CS.UnityEngine.WaitForSeconds : CS.UnityEngine.YieldInstruction ---@type CS.UnityEngine.WaitForSeconds CS.UnityEngine.WaitForSeconds = { } ---@return CS.UnityEngine.WaitForSeconds ---@param seconds number function CS.UnityEngine.WaitForSeconds.New(seconds) end return CS.UnityEngine.WaitForSeconds
-- pretty much stolen from https://learnopengl.com/Advanced-Lighting/Bloom -- i can't figure out who wrote that though so uh thanks whoever local bloom = {} if not OS_MOBILE then local blur = love.graphics.newShader [[ float weight[6] = float[] (0.13298,0.125858,0.106701,0.081029,0.055119,0.033585); float size_x = 1 / love_ScreenSize.x; float size_y = 1 / love_ScreenSize.y; extern bool x; vec4 effect(vec4 color, Image tex, vec2 coords, vec2 _) { vec3 c = Texel(tex, coords).rgb * weight[0]; if (x) { for (int i=0; i<6; ++i) { c += Texel(tex, coords + vec2(i*size_x, 0.0)).rgb * weight[i]; c += Texel(tex, coords - vec2(i*size_x, 0.0)).rgb * weight[i]; } } else { for (int i=0; i<6; ++i) { c += Texel(tex, coords + vec2(0.0, i*size_y)).rgb * weight[i]; c += Texel(tex, coords - vec2(0.0, i*size_y)).rgb * weight[i]; } } return vec4(c, 1.0) * color; } ]] local can = love.graphics.newCanvas() local can_blury = love.graphics.newCanvas() function bloom.preDraw() love.graphics.setCanvas(can) love.graphics.clear() end function bloom.postDraw() love.graphics.setCanvas(can_blury) love.graphics.setShader(blur) blur:send('x', true) love.graphics.setColor(1,1,1) love.graphics.draw(can, 0,0) love.graphics.setCanvas() blur:send('x', false) love.graphics.draw(can_blury, 0,0) love.graphics.setShader() love.graphics.draw(can, 0,0) end else -- if OS_MOBILE function bloom.preDraw() end function bloom.postDraw() end end return bloom
--@name moneydb DEMO --@shared --@include casino/moneydb/sv_lib.lua if SERVER then dofile('casino/moneydb/sv_lib.lua') moneydb.init() local fetching = {} net.receive('getBalance', function(_, ply) if fetching[ply] then return end fetching[ply] = true moneydb.getBalance(ply, function(success, balance) net.start('getBalance') net.writeInt(balance, 64) net.send(ply) fetching[ply] = false end) end) return end net.receive('getBalance', function() balance = net.readInt(64) end) hook.add('render', '', function() render.setFont('DermaLarge') render.drawText(10, 10, (balance and "Your balance is: "..balance or "Press E to get balance")) end) local usable = {[chip()] = true} for _, ent in pairs(chip():getLinkedComponents()) do usable[ent] = true end hook.add('starfallused', '', function(user, ent) if user == player() and usable[ent] then net.start('getBalance') net.send() end end)
ENT.Base = "dronesrewrite_base" ENT.Type = "anim" ENT.PrintName = "Ambulance" ENT.Spawnable = true ENT.AdminSpawnable = true ENT.Category = "Drones Rewrite" ENT.UNIT = "AMB" ENT.Weight = 250 ENT.Model = "models/dronesrewrite/medic/medic.mdl" ENT.FirstPersonCam_pos = Vector(13, 0, -10) ENT.RenderCam = false ENT.ExplosionForce = 16 ENT.ExplosionAngForce = 1.7 ENT.Alignment = 0 --1.6 ENT.AlignmentRoll = 0.7 ENT.AlignmentPitch = 1.6 ENT.NoiseCoefficient = 0.4 ENT.AngOffset = 4 ENT.Speed = 4800 ENT.UpSpeed = 24000 ENT.RotateSpeed = 7 ENT.HackValue = 2 ENT.Fuel = 100 ENT.MaxFuel = 100 ENT.FuelReduction = 0.3 ENT.PitchOffset = 0.8 ENT.AllowYawRestrictions = true ENT.YawMin = -60 ENT.YawMax = 60 ENT.PitchMin = -40 ENT.PitchMax = 64 ENT.KeysFuncs = DRONES_REWRITE.DefaultKeys() ENT.HealthAmount = 250 ENT.DefaultHealth = 250 ENT.AI_ReverseCheck = true ENT.AI_CustomEnemyChecker = function(drone, v) return (not v.IS_DRR and not v.IS_DRONE) and v:Health() < v:GetMaxHealth() end ENT.Sounds = { PropellerSound = { Name = "npc/manhack/mh_engine_loop1.wav", Pitch = 120, Level = 71, Volume = 0.75 }, ExplosionSound = { Name = "ambient/explosions/explode_7.wav", Level = 85 } } ENT.Propellers = { Damage = 1, Health = 50, HitRange = 12, Model = "models/dronesrewrite/rotor_smb/rotor_smb.mdl", Info = { Vector(-18, 41, 11), Vector(-18, -41, 11), Vector(36.5, 0, 11) } } ENT.Attachments = { ["Healer"] = { Pos = Vector(-10, 0, -6) } } ENT.Weapons = { ["Healer"] = { Name = "Healer", Attachment = "Healer" } } ENT.Modules = DRONES_REWRITE.GetBaseModules()
-- P51 - [练习 1.40] function fixed_point(f, first_guess) function close_enough(x, y) local abs = math.abs local tolerance = 0.00001 return abs(x - y) < tolerance end function try(guess) local next_guess = f(guess) if close_enough(guess, next_guess) then return next_guess else return try(next_guess) end end return try(first_guess) end function newton_transform(g) function deriv(g) local dx = 0.00001 return function (x) return (g(x + dx) - g(x)) / dx end end return function (x) return x - g(x) / deriv(g)(x) end end function newtons_method(g, guess) return fixed_point(newton_transform(g), guess) end function cubic(a, b, c) function cube(x) return x * x * x end function square(x) return x * x end return function (x) return cube(x) + a * square(x) + b * x + c end end print(newtons_method(cubic(3, 2, 1), 1.0)) print(newtons_method(cubic(3, 4, 5), 1.0)) print(newtons_method(cubic(6, 7, 8), 1.0)) --[[ 输出 -2.3247179572447 -2.2134116627622 -4.9054740060655 ]]
slot0 = class("BundleLoaderPort") slot0.Ctor = function (slot0, slot1) slot0.pool = slot1 or BundlePool.New() slot0.pool:Bind(slot0) slot0._returnRequest = {} end slot0.GetPrefab = function (slot0, slot1, slot2, slot3, slot4) slot2 = slot2 or "" if slot4 and slot0._returnRequest[slot4] then slot0:ClearRequest(slot4) end slot5 = slot0.pool:GetPrefab(slot1, slot2, true, function (slot0) if slot0 then slot1._returnRequest[slot0] = nil end if slot2 then slot2(slot0) end end) if slot4 then slot0._returnRequest[slot4] = slot5 end end slot0.ReturnPrefab = function (slot0, slot1, slot2, slot3, slot4) slot0.pool:ReturnPrefab(slot1, slot2, slot3, slot4) end slot0.GetSpine = function (slot0, slot1, slot2, slot3) if not slot1 or #slot1 < 0 then return end if slot3 and slot0._returnRequest[slot3] then slot0:ClearRequest(slot3) end slot4 = slot0.pool:GetSpineChar(slot1, true, function (slot0) if slot0 then slot1._returnRequest[slot0] = nil end if slot2 then slot2(slot0) end end) if slot3 then slot0._returnRequest[slot3] = slot4 end end slot0.ReturnSpine = function (slot0, slot1, slot2) slot0.pool:ReturnSpineChar(slot1, go(slot2)) end slot0.GetPainting = function (slot0, slot1, slot2, slot3) if not slot1 or #slot1 < 0 then return end if slot3 and slot0._returnRequest[slot3] then slot0:ClearRequest(slot3) end slot4 = slot0.pool:GetPainting(slot1, true, function (slot0) if slot0 then slot1._returnRequest[slot0] = nil end if slot2 then slot2(slot0) end end) if slot3 then slot0._returnRequest[slot3] = slot4 end end slot0.ReturnPainting = function (slot0, slot1, slot2) slot0.pool:ReturnPainting(slot1, go(slot2)) end slot0.GetSprite = function (slot0, slot1, slot2, slot3, slot4) slot3:GetComponent(typeof(Image)).enabled = false slot2 = slot2 or "" if slot0._returnRequest[tf(slot3)] then slot0:ClearRequest(slot6) end slot0._returnRequest[slot6] = slot0.pool:GetSprite(slot1, slot2, true, function (slot0) slot0._returnRequest[] = nil slot0._returnRequest.enabled = true slot2.sprite = slot0 if nil then slot2:SetNativeSize() end end) end slot0.DestroyPlural = function (slot0, slot1, slot2) slot0.pool:DestroyPlural(slot1, slot2) end slot0.DestroyAtlas = function (slot0, slot1) slot0.pool:DestroyPack(slot1) end slot0.GetOffSpriteRequest = function (slot0, slot1) slot0:ClearRequest(tf(slot1)) end slot1 = ResourceMgr.Inst slot0.LoadPrefab = function (slot0, slot1, slot2, slot3, slot4) slot2 = slot2 or "" slot5 = false if slot3 then if slot0._returnRequest[slot3] then slot0:ClearRequest(slot3) end slot0._returnRequest[slot3] = function () slot0 = true end end slot0.getAssetAsync(slot6, slot1, slot2, UnityEngine.Events.UnityAction_UnityEngine_Object(function (slot0) if slot0 then return end Object.Instantiate(slot0)(Object.Instantiate(slot0)) end), true, false) end slot0.LoadSprite = function (slot0, slot1, slot2, slot3, slot4) slot3:GetComponent(typeof(Image)).enabled = false slot2 = slot2 or "" if slot0._returnRequest[tf(slot3)] then slot0:ClearRequest(slot6) end slot7 = false slot0._returnRequest[slot6] = function () slot0 = true end slot0.getAssetAsync(slot8, slot1, slot2, typeof(Sprite), UnityEngine.Events.UnityAction_UnityEngine_Object(function (slot0) if slot0 then return end slot1._returnRequest[slot2] = nil slot3.enabled = true slot3.sprite = slot0 if slot4 then slot3:SetNativeSize() end end), true, false) end slot0.ClearRequest = function (slot0, slot1) if slot0._returnRequest[slot1] then slot0._returnRequest[slot1]() slot0._returnRequest[slot1] = nil end end slot0.ClearRequests = function (slot0) for slot4, slot5 in pairs(slot0._returnRequest) do slot5() slot0._returnRequest[slot4] = nil end end slot0.Clear = function (slot0) slot0:ClearRequests() slot0.pool:UnBind() table.clear(slot0) end return slot0
solution "IOCP_01" configurations { "Debug", "Release" } platforms { "Win64" } -- A project defines one build target project "IOCP_01" kind "ConsoleApp" language "C++" files { "**.h", "**.cpp" } configuration "Debug" defines { "DEBUG" } flags { "Symbols" } platforms { "Win64" } configuration "Release" defines { "NDEBUG" } flags { "Optimize" } filter { "platforms:Win64" } architecture "x64" targetdir("../bin")
Object = require "classic" require "dungeon/dungeon" local width = 100 local height = 100 local rooms = 22 local display = { tri = false, tile = true, mst = false } function love.load() dungeon = Dungeon(width,height,rooms) dungeon:generateMap() end function love.update(dt) end function love.draw() dungeon:draw(display) love.graphics.setColor(255,255,255,255) love.graphics.print('Rooms:'..rooms,520,20) love.graphics.print('+ or - to Add/Delete Rooms', 520,60) love.graphics.print('t - toggle show trangulation',520, 80) love.graphics.print('g - toggle show tile view/drawn room view',520,100) love.graphics.print('m - toggle show MST',520,120) love.graphics.print('r - regenerate dungeon',520, 180) end function love.keyreleased(key) if key == '+' or key == '=' then rooms = rooms + 1 end if key == '-' or key == '_' then rooms = rooms - 1 if rooms == 0 then rooms = 1 end end if key == 'r' then dungeon = Dungeon(width, height, rooms) dungeon:generateMap() end if key == 't' then display.tri = not display.tri end if key == 'm' then display.mst = not display.mst end if key == 'g' then display.tile = not display.tile end end
require 'lush'(require 'gruvbox') -- nvim-treesitter if not pcall(require, 'nvim-treesitter') then return end local parser_config = require('nvim-treesitter.parsers').get_parser_configs() parser_config.org = { install_info = { url = '~/Projects/tree-sitter-org', files = { 'src/parser.c', 'src/scanner.cc' }, }, filetype = 'org', } require('nvim-treesitter.configs').setup { -- one of "all", "maintained" (parsers with maintainers), or a list of languages ensure_installed = { 'bash', 'cpp', 'lua', 'python', 'c', 'javascript' }, highlight = { enable = true, -- false will disable the whole extension disable = { 'org' }, -- list of language that will be disabled -- custom_captures = { -- -- Highlight the @foo.bar capture group with the "Identifier" highlight group. -- ["foo.bar"] = "Identifier", }, indent = { enable = false, disable = { 'org' }, }, incremental_selection = { enable = true, keymaps = { init_selection = 'gnn', node_incremental = 'grn', scope_incremental = 'grc', node_decremental = 'grm', }, }, } require('nvim-treesitter.configs').setup { textobjects = { swap = { enable = true, swap_next = { ['<leader>a'] = '@parameter.inner', }, swap_previous = { ['<leader>A'] = '@parameter.inner', }, }, move = { enable = true, set_jumps = true, -- whether to set jumps in the jumplist goto_next_start = { [']m'] = '@function.outer', [']]'] = '@class.outer', }, goto_next_end = { [']M'] = '@function.outer', [']['] = '@class.outer', }, goto_previous_start = { ['[m'] = '@function.outer', ['[['] = '@class.outer', }, goto_previous_end = { ['[M'] = '@function.outer', ['[]'] = '@class.outer', }, }, select = { enable = true, -- Automatically jump forward to textobj, similar to targets.vim lookahead = true, keymaps = { -- You can use the capture groups defined in textobjects.scm ['af'] = '@function.outer', ['if'] = '@function.inner', ['ac'] = '@class.outer', ['ic'] = '@class.inner', -- Or you can define your own textobjects like this ['iF'] = { python = '(function_definition) @function', cpp = '(function_definition) @function', c = '(function_definition) @function', java = '(method_declaration) @function', }, }, }, }, }
TIMERS_VERSION = "1.06" --[[ 1.06 modified by Celireor (now uses binary heap priority queue instead of iteration to determine timer of shortest duration) DO NOT MODIFY A REALTIME TIMER TO USE GAMETIME OR VICE VERSA MIDWAY WITHOUT FIRST REMOVING AND RE-ADDING THE TIMER -- A timer running every second that starts immediately on the next frame, respects pauses Timers:CreateTimer(function() print ("Hello. I'm running immediately and then every second thereafter.") return 1.0 end ) -- The same timer as above with a shorthand call Timers(function() print ("Hello. I'm running immediately and then every second thereafter.") return 1.0 end) -- A timer which calls a function with a table context Timers:CreateTimer(GameMode.someFunction, GameMode) -- A timer running every second that starts 5 seconds in the future, respects pauses Timers:CreateTimer(5, function() print ("Hello. I'm running 5 seconds after you called me and then every second thereafter.") return 1.0 end ) -- 10 second delayed, run once using gametime (respect pauses) Timers:CreateTimer({ endTime = 10, -- when this timer should first execute, you can omit this if you want it to run first on the next frame callback = function() print ("Hello. I'm running 10 seconds after when I was started.") end }) -- 10 second delayed, run once regardless of pauses Timers:CreateTimer({ useGameTime = false, endTime = 10, -- when this timer should first execute, you can omit this if you want it to run first on the next frame callback = function() print ("Hello. I'm running 10 seconds after I was started even if someone paused the game.") end }) -- A timer running every second that starts after 2 minutes regardless of pauses Timers:CreateTimer("uniqueTimerString3", { useGameTime = false, endTime = 120, callback = function() print ("Hello. I'm running after 2 minutes and then every second thereafter.") return 1 end }) ]] -- Binary Heap implementation copy-pasted from https://gist.github.com/starwing/1757443a1bd295653c39 -- BinaryHeap[1] always points to the element with the lowest "key" variable -- API -- BinaryHeap(key) - Creates a new BinaryHeap with key. The key is the name of the integer variable used to sort objects. -- BinaryHeap:Insert - Inserts an object into BinaryHeap -- BinaryHeap:Remove - Removes an object from BinaryHeap BinaryHeap = BinaryHeap or {} BinaryHeap.__index = BinaryHeap function BinaryHeap:Insert(item) local index = #self + 1 local key = self.key item.index = index self[index] = item while index > 1 do local parent = math.floor(index/2) if self[parent][key] <= item[key] then break end self[index], self[parent] = self[parent], self[index] self[index].index = index self[parent].index = parent index = parent end return item end function BinaryHeap:Remove(item) local index = item.index if self[index] ~= item then return end local key = self.key local heap_size = #self if index == heap_size then self[heap_size] = nil return end self[index] = self[heap_size] self[index].index = index self[heap_size] = nil while true do local left = index*2 local right = left + 1 if not self[left] then break end local newindex = right if self[index][key] >= self[left][key] then if not self[right] or self[left][key] < self[right][key] then newindex = left end elseif not self[right] or self[index][key] <= self[right][key] then break end self[index], self[newindex] = self[newindex], self[index] self[index].index = index self[newindex].index = newindex index = newindex end end setmetatable(BinaryHeap, {__call = function(self, key) return setmetatable({key=key}, self) end}) function table.merge(input1, input2) for i,v in pairs(input2) do input1[i] = v end return input1 end TIMERS_THINK = 0.01 if Timers == nil then print ( '[Timers] creating Timers' ) Timers = {} setmetatable(Timers, { __call = function(t, ...) return t:CreateTimer(...) end }) --Timers.__index = Timers end function Timers:start() self.started = true Timers = self self:InitializeTimers() self.nextTickCallbacks = {} local ent = SpawnEntityFromTableSynchronous("info_target", {targetname="timers_lua_thinker"}) ent:SetThink("Think", self, "timers", TIMERS_THINK) end function Timers:Think() local nextTickCallbacks = table.merge({}, Timers.nextTickCallbacks) Timers.nextTickCallbacks = {} for _, cb in ipairs(nextTickCallbacks) do local status, result = xpcall(cb, debug.traceback) if not status then Timers:HandleEventError(result) end end if GameRules:State_Get() >= DOTA_GAMERULES_STATE_POST_GAME then return end -- Track game time, since the dt passed in to think is actually wall-clock time not simulation time. local now = GameRules:GetGameTime() -- Process timers self:ExecuteTimers(self.realTimeHeap, Time()) self:ExecuteTimers(self.gameTimeHeap, GameRules:GetGameTime()) return TIMERS_THINK end function Timers:ExecuteTimers(timerList, now) --Empty timer, ignore if not timerList[1] then return end --Timers are alr. sorted by end time upon insertion local currentTimer = timerList[1] currentTimer.endTime = currentTimer.endTime or now --Check if timer has finished if now >= currentTimer.endTime then -- Remove from timers list timerList:Remove(currentTimer) Timers.runningTimer = k Timers.removeSelf = false -- Run the callback local status, timerResult if currentTimer.context then status, timerResult = xpcall(function() return currentTimer.callback(currentTimer.context, currentTimer) end, debug.traceback) else status, timerResult = xpcall(function() return currentTimer.callback(currentTimer) end, debug.traceback) end Timers.runningTimer = nil -- Make sure it worked if status then -- Check if it needs to loop if timerResult and not Timers.removeSelf then -- Change its end time currentTimer.endTime = currentTimer.endTime + timerResult timerList:Insert(currentTimer) end -- Update timer data --self:UpdateTimerData() else -- Nope, handle the error Timers:HandleEventError(timerResult) end --run again! self:ExecuteTimers(timerList, now) end end function Timers:HandleEventError(err) if IsInToolsMode() then print(err) else StatsClient:HandleError(err) end end function Timers:CreateTimer(arg1, arg2, context) local timer if type(arg1) == "function" then if arg2 ~= nil then context = arg2 end timer = {callback = arg1} elseif type(arg1) == "table" then timer = arg1 elseif type(arg1) == "number" then timer = {endTime = arg1, callback = arg2} end if not timer.callback then print("Invalid timer created") return end local now = GameRules:GetGameTime() local timerHeap = self.gameTimeHeap if timer.useGameTime ~= nil and timer.useGameTime == false then now = Time() timerHeap = self.realTimeHeap end if timer.endTime == nil then timer.endTime = now else timer.endTime = now + timer.endTime end timer.context = context timerHeap:Insert(timer) return timer end function Timers:NextTick(callback) table.insert(Timers.nextTickCallbacks, callback) end function Timers:RemoveTimer(name) local timerHeap = self.gameTimeHeap if name.useGameTime ~= nil and name.useGameTime == false then timerHeap = self.realTimeHeap end timerHeap:Remove(name) if Timers.runningTimer == name then Timers.removeSelf = true end end function Timers:InitializeTimers() self.realTimeHeap = BinaryHeap("endTime") self.gameTimeHeap = BinaryHeap("endTime") end if not Timers.started then Timers:start() end GameRules.Timers = Timers
local cwd = (...):gsub("%.[^%.]+$", "") .. "." local cfg_mgzjh_robot = require(cwd .. "config_mgzjh_robot") --[[ { id = 1001, type = 1, -- 'upstream type : 1 = game, 2 = chat', name = '游戏服务器1', -- '名称', host = '127.0.0.1', port = 8861, visibility = 1, -- '可见性,1=正式服,2=测试服,3=审核服', white_peerip = '', -- '白名单peer ip,服务器强制可见 -- "ip : mask | ..."', enable = 1 -- '是否启用,0 = 禁用, 1 = 启用', }, ]] local _M = { servers = { { id = 1000, type = 1, name = "Zjh服务器1", host = "127.0.0.1", port = 8860, visibility = 1, white_peerip = "", enable = true } }, -- robots = {} } -- init and sort robots local __tmp_tbl__ = cfg_mgzjh_robot.ConfigRobot for _, v in pairs(__tmp_tbl__) do table.insert(_M.robots, v) end table.sort( _M.robots, function(a, b) return a.userid < b.userid end ) return _M
local TreeSitter = require("refactoring.treesitter.treesitter") local Typescript = require("refactoring.treesitter.langs.typescript") local Cpp = require("refactoring.treesitter.langs.cpp") local go = require("refactoring.treesitter.langs.go") local Lua = require("refactoring.treesitter.langs.lua") local Python = require("refactoring.treesitter.langs.python") local JavaScript = require("refactoring.treesitter.langs.javascript") local M = { TreeSitter = TreeSitter, javascript = JavaScript, typescript = Typescript, python = Python, go = go, lua = Lua, -- Why so many... cc = Cpp, cxx = Cpp, cpp = Cpp, h = Cpp, hpp = Cpp, c = Cpp, } local DefaultSitter = {} function DefaultSitter.new(bufnr, ft) return TreeSitter:new({ version = 0, filetype = ft, bufnr = bufnr, }, bufnr) end local function get_bufrn(bufnr) return bufnr or vim.api.nvim_get_current_buf() end function M.get_treesitter(bufnr) bufnr = get_bufrn(bufnr) local ft = vim.bo[bufnr].ft return M[ft] and M[ft].new(bufnr, ft) or DefaultSitter.new(bufnr, ft) end return M
-- -- c_water.lua -- local textureVol, textureCube local g_Timer function enableWater () -- Version check if getVersion ().sortable < "1.1.0" then outputChatBox( "Resource is not compatible with this client." ) return end -- Create shader myShader, tec = dxCreateShader ( "water.fx" ) if not myShader then --outputChatBox( "Could not create shader. Please use debugscript 3" ) return false else --outputChatBox( "Using technique " .. tec ) -- Set textures textureVol = dxCreateTexture ( "images/smallnoise3d.dds" ); textureCube = dxCreateTexture ( "images/cube_env256.dds" ); dxSetShaderValue ( myShader, "sRandomTexture", textureVol ); dxSetShaderValue ( myShader, "sReflectionTexture", textureCube ); -- Update water color incase it gets changed by persons unknown g_Timer = setTimer( function() if myShader then local r,g,b,a = getWaterColor() dxSetShaderValue ( myShader, "sWaterColor", r/255, g/255, b/255, a/255 ); end end ,100,0 ) engineApplyShaderToWorldTexture ( myShader, "waterclear256" ) return true end end function disableWater() killTimer(g_Timer) destroyElement(myShader) destroyElement(textureVol) destroyElement(textureCube) end
-- -- Register lua controller and lua tube for Magic pen -- local o2b_lookup = { ['0'] = '000', ['1'] = '001', ['2'] = '010', ['3'] = '011', ['4'] = '100', ['5'] = '101', ['6'] = '110', ['7'] = '111', } local o2b = function(o) return o:gsub('.', o2b_lookup) end local d2b = function(d) return o2b(string.format('%o', d)) end local lpad = function(s, c, n) return c:rep(n - #s) .. s end local lpadcut = function(s, c, n) return lpad(s,c,n):sub(math.max(0, #s - n + 1), #s + 1) end local nodes = {} -- lua controller, 16 different nodes for i=0,15 do table.insert(nodes, "mesecons_luacontroller:luacontroller" .. lpadcut(d2b(i), '0', 4)) end table.insert(nodes, "mesecons_luacontroller:luacontroller_burnt") -- lua tubes, 64 different nodes for i=0,63 do table.insert(nodes, "pipeworks:lua_tube" .. lpad(d2b(i), '0', 6)) end table.insert(nodes, "pipeworks:lua_tube_burnt") local truncate = metatool.ns('magic_pen').truncate local function parse_comments(content) if type(content) ~= "string" then return end local m = content:gmatch("[^\r\n]+") local line = m() local title, author while line and (line:find("^%s*%-%-[%s%p]*[%a%d]") or line:find("^%s*$")) do if not title then title = truncate( line:gmatch("[Dd][Ee][Ss][Cc]%a*[%s]*%p[%s%p]*([%a%d][%a%d%p%s]+)")() or line:gmatch("[Tt][Ii][Tt][Ll][Ee][%s]*%p[%s%p]*([%a%d][%a%d%p%s]+)")(), 80) end if not author then author = truncate(line:gmatch("[Aa][Uu][Tt][Hh][Oo][Rr][%s]*%p[%s%p]*([%a%d][%a%d%p%s]+)")(), 80) end if title and author then break end line = m() end return title, author end local definition = { name = 'luacontroller', nodes = nodes, group = 'text', protection_bypass_read = "interact", } function definition:copy(node, pos, player) local meta = minetest.get_meta(pos) local content = meta:get_string("code") local title, author = parse_comments(content) local nicename = minetest.registered_nodes[node.name].description or node.name local description = title and ("%s: %s"):format(nicename, title) or ("%s at %s"):format(nicename, minetest.pos_to_string(pos)) return { description = description, content = content, title = title, source = author, } end function definition:paste(node, pos, player, data) local content = data.content local title, author = parse_comments(content) if not author and data.source then content = ("-- Author: %s\n%s"):format(data.source, content) end if not title and data.title then content = ("-- Description: %s\n%s"):format(data.title, content) end local fields = { program = 1, code = content, } local nodedef = minetest.registered_nodes[node.name] nodedef.on_receive_fields(pos, "", fields, player) end return definition
--白泽球的增援 function c22221202.initial_effect(c) c:SetUniqueOnField(1,0,22221202) --Activate local e1=Effect.CreateEffect(c) e1:SetCategory(CATEGORY_TOGRAVE+CATEGORY_DRAW) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET) e1:SetCode(EVENT_FREE_CHAIN) e1:SetTarget(c22221202.target) e1:SetOperation(c22221202.activate) c:RegisterEffect(e1) --SpecialSummon local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(22221202, 0)) e2:SetCategory(CATEGORY_SPECIAL_SUMMON) e2:SetType(EFFECT_TYPE_IGNITION) e2:SetRange(LOCATION_SZONE) e2:SetCountLimit(1,EFFECT_COUNT_CODE_SINGLE) e2:SetCost(c22221202.cost2) e2:SetTarget(c22221202.tg) e2:SetOperation(c22221202.op) c:RegisterEffect(e2) --tohand local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(22221202, 1)) e2:SetCategory(CATEGORY_TOHAND) e2:SetType(EFFECT_TYPE_IGNITION) e2:SetRange(LOCATION_SZONE) e2:SetCountLimit(1,EFFECT_COUNT_CODE_SINGLE) e2:SetCost(c22221202.cost2) e2:SetTarget(c22221202.tg3) e2:SetOperation(c22221202.op3) c:RegisterEffect(e2) --todeck local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(22221202, 2)) e2:SetType(EFFECT_TYPE_IGNITION) e2:SetRange(LOCATION_SZONE) e2:SetCountLimit(1,EFFECT_COUNT_CODE_SINGLE) e2:SetCost(c22221202.cost2) e2:SetTarget(c22221202.tg2) e2:SetOperation(c22221202.op2) c:RegisterEffect(e2) --maintain local e5=Effect.CreateEffect(c) e5:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS) e5:SetProperty(EFFECT_FLAG_UNCOPYABLE) e5:SetCode(EVENT_PHASE+PHASE_STANDBY) e5:SetRange(LOCATION_SZONE) e5:SetCountLimit(1) e5:SetOperation(c22221202.mtop) c:RegisterEffect(e5) end c22221202.named_with_Shirasawa_Tama=1 function c22221202.IsShirasawaTama(c) local m=_G["c"..c:GetCode()] return m and m.named_with_Shirasawa_Tama end function c22221202.filter(c) return (c:GetSequence()==6 or c:GetSequence()==7) and c22221202.IsShirasawaTama(c) and c:IsAbleToHand() end function c22221202.target(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return true end local g=Duel.GetMatchingGroup(c22221202.filter,tp,LOCATION_SZONE,0,nil) Duel.SetOperationInfo(0,CATEGORY_TOHAND,g,g:GetCount(),0,0) end function c22221202.activate(e,tp,eg,ep,ev,re,r,rp) if not e:GetHandler():IsRelateToEffect(e) then return end local g=Duel.GetMatchingGroup(c22221202.filter,tp,LOCATION_SZONE,0,nil) if g:GetCount()>0 then Duel.SendtoHand(g,tp,REASON_EFFECT) end end function c22221202.filter2(c) return c22221202.IsShirasawaTama(c) and c:IsAbleToGraveAsCost() and c:IsType(TYPE_MONSTER) and c:IsFaceup() end function c22221202.filter3(c) return c22221202.IsShirasawaTama(c) and c:IsType(TYPE_MONSTER) and c:IsAbleToGraveAsCost() end function c22221202.filter4(c,e,tp) return c22221202.IsShirasawaTama(c) and c:IsType(TYPE_MONSTER) and c:IsCanBeSpecialSummoned(e,0,tp,false,false) end function c22221202.cost2(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and Duel.IsExistingMatchingCard(c22221202.filter2,tp,LOCATION_EXTRA,0,1,nil) and Duel.IsExistingMatchingCard(c22221202.filter3,tp,LOCATION_HAND,0,1,nil) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TOGRAVE) local g1=Duel.SelectMatchingCard(tp,c22221202.filter2,tp,LOCATION_EXTRA,0,1,1,nil) local g2=Duel.SelectMatchingCard(tp,c22221202.filter3,tp,LOCATION_HAND,0,1,1,nil) g1:Merge(g2) Duel.SendtoGrave(g1,REASON_COST) end function c22221202.tg(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsLocation(LOCATION_DECK+LOCATION_GRAVE) and c22221202.filter4(chkc,e,tp) end if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and Duel.IsExistingTarget(c22221202.filter4,tp,LOCATION_DECK+LOCATION_GRAVE,0,1,nil,e,tp) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local g=Duel.SelectTarget(tp,c22221202.filter4,tp,LOCATION_DECK+LOCATION_GRAVE,0,1,1,nil,e,tp) Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,g,1,tp,LOCATION_DECK+LOCATION_GRAVE) end function c22221202.op(e,tp,eg,ep,ev,re,r,rp) local tc=Duel.GetFirstTarget() if tc:IsRelateToEffect(e) and e:GetHandler():IsRelateToEffect(e) then Duel.SpecialSummon(tc,0,tp,tp,false,false,POS_FACEUP) end end function c22221202.filter5(c) return c22221202.IsShirasawaTama(c) and c:IsType(TYPE_MONSTER) end function c22221202.tg2(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsLocation(LOCATION_REMOVED+LOCATION_DECK) and c22221202.filter5(chkc) end if chk==0 then return Duel.IsExistingMatchingCard(c22221202.filter5,tp,LOCATION_REMOVED+LOCATION_DECK,0,2,nil) end end function c22221202.op2(e,tp,eg,ep,ev,re,r,rp) if Duel.IsExistingMatchingCard(c22221202.filter5,tp,LOCATION_REMOVED+LOCATION_DECK,0,2,nil) then local g=Duel.SelectMatchingCard(tp,c22221202.filter5,tp,LOCATION_REMOVED+LOCATION_DECK,0,2,2,nil) if e:GetHandler():IsRelateToEffect(e) then Duel.SendtoExtraP(g,nil,REASON_EFFECT) end end end function c22221202.filter6(c) return c22221202.IsShirasawaTama(c) and c:IsType(TYPE_MONSTER) and c:IsAbleToHand() end function c22221202.tg3(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsLocation(LOCATION_GRAVE+LOCATION_REMOVED) and c22221202.filter6(chkc,e,tp) end if chk==0 then return Duel.IsExistingTarget(c22221202.filter6,tp,LOCATION_GRAVE+LOCATION_REMOVED,0,1,nil) end end function c22221202.op3(e,tp,eg,ep,ev,re,r,rp) if Duel.IsExistingMatchingCard(c22221202.filter6,tp,LOCATION_GRAVE+LOCATION_REMOVED,0,1,nil) then local g=Duel.SelectMatchingCard(tp,c22221202.filter5,tp,LOCATION_GRAVE+LOCATION_REMOVED,0,1,1,nil) local tc=g:GetFirst() if e:GetHandler():IsRelateToEffect(e) then Duel.SendtoHand(tc,nil,REASON_EFFECT) end end end function c22221202.mtfilter(c) return c:IsFaceup() and c22221202.IsShirasawaTama(c) end function c22221202.mtop(e,tp,eg,ep,ev,re,r,rp) if Duel.GetTurnPlayer()~=tp then return end if Duel.IsExistingMatchingCard(c22221202.mtfilter,tp,LOCATION_MZONE,0,1,nil) then local g=Duel.SelectMatchingCard(tp,c22221202.mtfilter,tp,LOCATION_MZONE,0,1,1,nil) Duel.Remove(g,POS_FACEUP,REASON_RULE) else Duel.Remove(e:GetHandler(),POS_FACEUP,REASON_RULE) end end
--[[ EVDevice Represents a single libevdev device You can create a blank one, and fill it in, as if creating one for event injection Or you can create one from a filename Or you can create one from an existing file descriptor --]] local ffi = require("ffi") local bit = require("bit") local band, bor = bit.band, bit.bor local evdev = require("evdev") local libc = require("libc") local input = require("linux_input")(_G) local EVEvent = require("EVEvent") local EVDevice = {} setmetatable(EVDevice, { __call = function(self, ...) return self:new(...) end, }) local EVDevice_mt = { __index = EVDevice, } function EVDevice.init(self, handle, nodename) local obj = { Handle = handle, NodeName = nodename, } setmetatable(obj, EVDevice_mt) return obj end --[[ Can be constructed a couple of different ways EVDevice(fd) - pass in an already opened file handle EVDevice(name, access) - pass in a device name and intended access --]] function EVDevice.new(self, ...) local dev = nil local fd = 0 local nodename = nil if select("#", ...) < 1 then return nil, "not enough arguments specified" end if type(select(1, ...)) == "string" then -- a filename was specified local access = select(2, ...) or bor(libc.O_RDONLY, libc.O_NONBLOCK) nodename = select(1, ...) fd = libc.open(nodename, access) end local dev = ffi.new("struct libevdev *[1]") local rc = evdev.libevdev_new_from_fd(fd, dev) if rc < 0 then return nil, string.format("Failed to init libevdev (%s)\n", libc.strerror(-rc)) end dev = dev[0] ffi.gc(dev, evdev.libevdev_free) return EVDevice:init(dev, nodename) end -- Qualities function EVDevice.hasEventType(self, atype) return evdev.libevdev_has_event_type(self.Handle, atype) == 1 end function EVDevice.hasEventCode(self, eventType, eventCode) return evdev.libevdev_has_event_code(self.Handle, eventType, eventCode) == 1 end function EVDevice.hasProperty(self, prop) local res = evdev.libevdev_has_property(self.Handle, prop) return res == 1 end -- Attributes function EVDevice.busType(self) return tonumber(evdev.libevdev_get_id_bustype(self.Handle)) end function EVDevice.vendorId(self) return tonumber(evdev.libevdev_get_id_vendor(self.Handle)) end function EVDevice.productId(self) return tonumber(evdev.libevdev_get_id_product(self.Handle)) end function EVDevice.name(self, name) local str = evdev.libevdev_get_name(self.Handle) return libc.safeffistring(str) end function EVDevice.physical(self, name) local str = evdev.libevdev_get_phys(self.Handle) return libc.safeffistring(str) end function EVDevice.unique(self, name) local str = evdev.libevdev_get_uniq(self.Handle) return libc.safeffistring(str) end -- Behaviors function EVDevice.isLikeFlightStick(self) return self:hasEventCode(input.Constants.EV_ABS, input.Constants.ABS_X) and self:hasEventCode(input.Constants.EV_ABS, input.Constants.ABS_Y) and self:hasEventCode(input.Constants.EV_ABS, input.Constants.ABS_THROTTLE) end function EVDevice.isLikeKeyboard(self) return self:hasEventCode(input.Constants.EV_KEY, input.Constants.KEY_SPACE) end function EVDevice.isLikeMouse(self) if self:hasEventType(input.Constants.EV_REL) and self:hasEventCode(input.Constants.EV_REL, input.Constants.REL_X) and self:hasEventCode(input.Constants.EV_REL, input.Constants.REL_Y) and self:hasEventCode(input.Constants.EV_KEY, input.Constants.BTN_LEFT) then return true end return false end function EVDevice.isLikeTablet(self) if self:hasEventType(input.Constants.EV_ABS) and self:hasEventCode(input.Constants.EV_KEY, input.Constants.BTN_LEFT) then return true end return false end -- Events function EVDevice.eventIsPending(self) return libevdev.libevdev_has_event_pending(self.Handle) == 1 end -- Iterator of events -- will block until an even comes function EVDevice.events(self, predicate) local function iter_gen(params, flags) local flags = flags or ffi.C.LIBEVDEV_READ_FLAG_NORMAL local ev = ffi.new("struct input_event") local event = EVEvent(ev) local rc = 0 if params.Predicate then repeat rc = evdev.libevdev_next_event(params.Handle, flags, ev) if (rc == ffi.C.LIBEVDEV_READ_STATUS_SUCCESS) or (rc == ffi.C.LIBEVDEV_READ_STATUS_SYNC) then if params.Predicate(event) then return flags, event end end until rc ~= ffi.C.LIBEVDEV_READ_STATUS_SUCCESS and rc ~= LIBEVDEV_READ_STATUS_SYNC and rc ~= -libc.EAGAIN else repeat rc = evdev.libevdev_next_event(params.Handle, flags, ev) until rc ~= -libc.EAGAIN if (rc == ffi.C.LIBEVDEV_READ_STATUS_SUCCESS) or (rc == ffi.C.LIBEVDEV_READ_STATUS_SYNC) then return flags, event end end return nil, rc end return iter_gen, { Handle = self.Handle, Predicate = predicate }, state end function EVDevice.rawEvents(self) local function iter_gen(params, flags) local flags = flags or ffi.C.LIBEVDEV_READ_FLAG_NORMAL local ev = ffi.new("struct input_event") --local event = EVEvent(ev); local rc = 0 repeat rc = evdev.libevdev_next_event(params.Handle, flags, ev) until rc ~= -libc.EAGAIN if (rc == ffi.C.LIBEVDEV_READ_STATUS_SUCCESS) or (rc == ffi.C.LIBEVDEV_READ_STATUS_SYNC) then return flags, ev end return nil, rc end return iter_gen, { Handle = self.Handle }, state end function EVDevice.properties(self) local function prop_gen(param, state) if state > input.Properties.INPUT_PROP_MAX then return nil end repeat if param:hasProperty(state) then return state + 1, state, input.getValueName(state, input.Properties) end state = state + 1 until state > input.Properties.INPUT_PROP_MAX return nil end return prop_gen, self, input.Properties.INPUT_PROP_POINTER end return EVDevice
TLua = { content = nil, data = nil, exportedData = nil, } function TLua.checkContent() if string.sub(TLua.content, -5) == '.tlua' then TLua.content = TLua.getFileContent(TLua.content) end end function TLua.getFileContent(filename) local handler = assert(io.open(filename, 'r')) local content = handler:read('*all') handler:close() -- Trim trailing newline if content:sub(-1) == '\n' then content = content:sub(1, -2) end return content end function TLua.render(content, data) TLua.content = content TLua.data = data or {} TLua.checkContent() TLua.exportData() TLua.replaceCode() TLua.replaceVars() TLua.replaceFiles() return TLua.content end function TLua.replaceVars() for key, value in pairs(TLua.data) do local realValue = '' if type(value) == 'number' or type(value) == 'string' or type(value) == 'boolean' then realValue = value end TLua.content = TLua.content:gsub('{{%s-' .. key .. '%s-}}', TLua.escapePattern(realValue)) end end function TLua.replaceCode() for placeholder, code in TLua.content:gmatch('({{{(.-)}}})') do TLua.content = TLua.content:gsub(TLua.escapePattern(placeholder), TLua.escapePattern(TLua.runCode(code))) end end function TLua.replaceFiles() for placeholder, filename in TLua.content:gmatch('(@include%((.-)%))') do TLua.content = TLua.content:gsub(TLua.escapePattern(placeholder), TLua.escapePattern(TLua.getFileContent(filename))) end end function TLua.runCode(code) code = TLua.exportedData .. '\n' .. 'return ' .. code local func = loadstring(code) return func() end function TLua.exportData() TLua.exportedData = '' if next(TLua.data) ~= nil then local keys, values = {}, {} for key, value in pairs(TLua.data) do table.insert(keys, key) if (type(value) == 'number') then table.insert(values, tostring(value)) elseif (type(value) == 'string') then table.insert(values, string.format('%q', value)) end end TLua.exportedData = 'local ' .. table.concat(keys, ', ') .. ' = ' .. table.concat(values, ', ') end end -- Taken from https://github.com/lua-nucleo/lua-nucleo function TLua.escapePattern(content) local matches = { ["^"] = "%^"; ["$"] = "%$"; ["("] = "%("; [")"] = "%)"; ["%"] = "%%"; ["."] = "%."; ["["] = "%["; ["]"] = "%]"; ["*"] = "%*"; ["+"] = "%+"; ["-"] = "%-"; ["?"] = "%?"; ["\0"] = "%z"; } return (content:gsub(".", matches)) end
local I = require(script.Parent.Parent.Types) local Util = require(script.Parent.Parent.Parent.Shared.Util) local Lens = require(script.Parent.Lens) local Constants = require(script.Parent.Parent.Constants) local LensCollection = {} LensCollection.__index = LensCollection function LensCollection.new(rocs) return setmetatable({ rocs = rocs; _components = {}; _entities = {}; _lenses = {}; }, LensCollection) end local function makeArrayPipelineCheck(array) return function(instance) for _, className in ipairs(array) do if instance:IsA(className) then return true end end return false, ("Instance type %q is not allowed to have this component!") :format(instance.ClassName) end end function LensCollection.runPipelineCheck(staticLens, instance) if staticLens.pipelineCheck == nil then return true end if type(staticLens.pipelineCheck) == "table" then staticLens.pipelineCheck = makeArrayPipelineCheck(staticLens.pipelineCheck) end return staticLens.pipelineCheck(instance) end function LensCollection:register(componentDefinition) assert(I.LayerDefinition(componentDefinition)) assert(self._components[componentDefinition.name] == nil, "A component with this name is already registered!") setmetatable(componentDefinition, Lens) componentDefinition.__index = componentDefinition componentDefinition.__tostring = Lens.__tostring componentDefinition.rocs = self.rocs componentDefinition.new = componentDefinition.new or function() return setmetatable({}, componentDefinition) end self._components[componentDefinition.name] = componentDefinition self._components[componentDefinition] = componentDefinition return componentDefinition end function LensCollection:construct(staticLens, instance) local lens = staticLens.new() assert( getmetatable(lens) == staticLens, "Metatable of constructed component lens must be static component lens" ) lens.components = {} lens.instance = instance self:_dispatchLifecycle(lens, "initialize") return lens end function LensCollection:deconstruct(lens) -- destroy is called in removeLayer for correct timing local staticLens = getmetatable(lens) self._entities[lens.instance][staticLens] = nil local array = self._lenses[staticLens] for i, v in ipairs(array) do if v == lens then table.remove(array, i) break end end if #array == 0 then self._lenses[staticLens] = nil end if next(self._entities[lens.instance]) == nil then self._entities[lens.instance] = nil end self:removeAllLayers(lens) end function LensCollection:addLayer(instance, staticLens, scope, data, metacomponents) if data == nil then return self:removeLayer(instance, staticLens, scope), false end assert(LensCollection.runPipelineCheck(staticLens, instance)) if self._entities[instance] == nil then self._entities[instance] = {} end if self._lenses[staticLens] == nil then self._lenses[staticLens] = {} end local lens = self._entities[instance][staticLens] local isNew = false if lens == nil then isNew = true lens = self:construct(staticLens, instance) self._entities[instance][staticLens] = lens table.insert(self._lenses[staticLens], lens) end lens.components[scope] = data self:_dispatchLayerChange(lens) local pendingParentUpdated = {} if isNew and staticLens.components then for componentResolvable, metacomponentData in pairs(staticLens.components) do local metacomponentstaticLens = self:getStatic(componentResolvable) local metacomponentLens = self:addLayer( lens, metacomponentstaticLens, Constants.SCOPE_BASE, metacomponentData ) pendingParentUpdated[metacomponentLens] = true end end if metacomponents then for componentResolvable, metacomponentData in pairs(metacomponents) do local metacomponentstaticLens = self:getStatic(componentResolvable) local metacomponentLens, wasNew = self:addLayer( lens, metacomponentstaticLens, scope, metacomponentData ) if wasNew then pendingParentUpdated[metacomponentLens] = true end end end -- De-duplicate onParentUpdated calls in case both tables have same for metacomponentLens in pairs(pendingParentUpdated) do self:_dispatchLifecycle( metacomponentLens, Constants.LIFECYCLE_PARENT_UPDATED ) end return lens, isNew end function LensCollection:removeAllLayers(instance) if self._entities[instance] == nil then return end for _, lens in ipairs(self:getAll(instance)) do lens.components = {} self:deconstruct(lens) self:_dispatchLayerChange(lens) self:_dispatchLifecycle(lens, "destroy") end end function LensCollection:removeLayer(instance, staticLens, scope) if self._entities[instance] == nil or self._entities[instance][staticLens] == nil then return end local lens = self._entities[instance][staticLens] lens.components[scope] = nil self:_dispatchLayerChange(lens) local shouldDestroy = next(lens.components) == nil if shouldDestroy then self:deconstruct(lens) end if shouldDestroy then self:_dispatchLifecycle(lens, "destroy") end -- TODO: Should destroy be deffered to end-of-frame? end function LensCollection:getLayer(instance, staticLens, scope) if self._entities[instance] == nil or self._entities[instance][staticLens] == nil then return end return self._entities[instance][staticLens].components[scope] end function LensCollection:getAll(instance) local lenses = {} if self._entities[instance] ~= nil then for _, lens in pairs(self._entities[instance]) do table.insert(lenses, lens) end end return lenses end function LensCollection:get(instance, staticLens) return self._entities[instance] and self._entities[instance][staticLens] end function LensCollection:getStatic(componentResolvable) return self:resolve(componentResolvable) or error(("Cannot resolve component %s"):format(componentResolvable)) end function LensCollection:resolve(componentResolvable) return self._components[componentResolvable] or ( type(componentResolvable) == "table" and getmetatable(componentResolvable) == Lens and componentResolvable ) end function LensCollection:reduce(lens) if next(lens.components) == nil then return end local values = { lens.components[Constants.SCOPE_REMOTE] } table.insert(values, lens.components[Constants.SCOPE_BASE]) for name, component in pairs(lens.components) do if Constants.RESERVED_SCOPES[name] == nil then table.insert(values, component) end end local staticLens = getmetatable(lens) local reducedValue = (staticLens.reducer or self.rocs.reducers.default)(values) local data = reducedValue if staticLens.defaults and type(reducedValue) == "table" then staticLens.defaults.__index = staticLens.defaults data = setmetatable( reducedValue, staticLens.defaults ) end if staticLens.check then assert(staticLens.check(data)) end return data end function LensCollection:_dispatchLifecycle(lens, stage) lens:dispatch(stage) self.rocs:_dispatchLifecycle(lens, stage) end function LensCollection:_dispatchLayerChange(lens) local lastData = lens.data local newData = self:reduce(lens) lens.data = newData lens.lastData = lastData if lastData == nil and newData ~= nil then self:_dispatchLifecycle(lens, Constants.LIFECYCLE_ADDED) end local staticLens = getmetatable(lens) if (staticLens.shouldUpdate or self.rocs.comparators.default)(newData, lastData) then self:_dispatchLifecycle(lens, Constants.LIFECYCLE_UPDATED) local childLenss = self:getAll(lens) for _, childLens in ipairs(childLenss) do self:_dispatchLifecycle( childLens, Constants.LIFECYCLE_PARENT_UPDATED ) end end if newData == nil then self:_dispatchLifecycle(lens, Constants.LIFECYCLE_REMOVED) end lens.lastData = nil end return LensCollection
TOOL.Category = "Construction" TOOL.Name = "#tool.wheel.name" TOOL.Command = nil TOOL.ConfigName = "" TOOL.ClientConVar[ "torque" ] = "3000" TOOL.ClientConVar[ "friction" ] = "1" TOOL.ClientConVar[ "nocollide" ] = "1" TOOL.ClientConVar[ "forcelimit" ] = "0" TOOL.ClientConVar[ "fwd" ] = "8" -- Forward key TOOL.ClientConVar[ "bck" ] = "5" -- Back key TOOL.ClientConVar[ "toggle" ] = "0" -- Togglable TOOL.ClientConVar[ "model" ] = "models/props_vehicles/carparts_wheel01a.mdl" TOOL.ClientConVar[ "rx" ] = "90" TOOL.ClientConVar[ "ry" ] = "0" TOOL.ClientConVar[ "rz" ] = "90" cleanup.Register( "wheels" ) --[[--------------------------------------------------------- Places a wheel -----------------------------------------------------------]] function TOOL:LeftClick( trace ) if ( trace.Entity && trace.Entity:IsPlayer() ) then return false end -- If there's no physics object then we can't constraint it! if ( SERVER && !util.IsValidPhysicsObject( trace.Entity, trace.PhysicsBone ) ) then return false end if (CLIENT) then return true end local ply = self:GetOwner() if ( !self:GetSWEP():CheckLimit( "wheels" ) ) then return false end local targetPhys = trace.Entity:GetPhysicsObjectNum( trace.PhysicsBone ) -- Get client's CVars local torque = self:GetClientNumber( "torque" ) local friction = self:GetClientNumber( "friction" ) local nocollide = self:GetClientNumber( "nocollide" ) local limit = self:GetClientNumber( "forcelimit" ) local toggle = self:GetClientNumber( "toggle" ) != 0 local model = self:GetClientInfo( "model" ) local fwd = self:GetClientNumber( "fwd" ) local bck = self:GetClientNumber( "bck" ) if ( !util.IsValidModel( model ) ) then return false end if ( !util.IsValidProp( model ) ) then return false end -- Create the wheel local wheelEnt = MakeWheel( ply, trace.HitPos, Angle(0,0,0), model, fwd, bck, nil, nil, toggle, torque ) -- Make sure we have our wheel angle self.wheelAngle = Angle( tonumber(self:GetClientInfo( "rx" )), tonumber(self:GetClientInfo( "ry" )), tonumber(self:GetClientInfo( "rz" )) ) local TargetAngle = trace.HitNormal:Angle() + self.wheelAngle wheelEnt:SetAngles( TargetAngle ) local CurPos = wheelEnt:GetPos() local NearestPoint = wheelEnt:NearestPoint( CurPos - (trace.HitNormal * 512) ) local wheelOffset = CurPos - NearestPoint wheelEnt:SetPos( trace.HitPos + wheelOffset + trace.HitNormal ) -- Wake up the physics object so that the entity updates wheelEnt:GetPhysicsObject():Wake() local TargetPos = wheelEnt:GetPos() -- Set the hinge Axis perpendicular to the trace hit surface local LPos1 = wheelEnt:GetPhysicsObject():WorldToLocal( TargetPos + trace.HitNormal ) local LPos2 = targetPhys:WorldToLocal( trace.HitPos ) local constraint, axis = constraint.Motor( wheelEnt, trace.Entity, 0, trace.PhysicsBone, LPos1, LPos2, friction, torque, 0, nocollide, toggle, ply, limit ) undo.Create("Wheel") undo.AddEntity( axis ) undo.AddEntity( constraint ) undo.AddEntity( wheelEnt ) undo.SetPlayer( ply ) undo.Finish() ply:AddCleanup( "wheels", axis ) ply:AddCleanup( "wheels", constraint ) ply:AddCleanup( "wheels", wheelEnt ) wheelEnt:SetMotor( constraint ) wheelEnt:SetDirection( constraint.direction ) wheelEnt:SetAxis( trace.HitNormal ) wheelEnt:SetToggle( toggle ) wheelEnt:DoDirectionEffect() wheelEnt:SetBaseTorque( torque ) return true end --[[--------------------------------------------------------- Apply new values to the wheel -----------------------------------------------------------]] function TOOL:RightClick( trace ) if ( trace.Entity && trace.Entity:GetClass() != "gmod_wheel" ) then return false end if (CLIENT) then return true end local wheelEnt = trace.Entity -- Only change your own wheels.. if ( wheelEnt:GetPlayer():IsValid() && wheelEnt:GetPlayer() != self:GetOwner() ) then return false end -- Get client's CVars local torque = self:GetClientNumber( "torque" ) local toggle = self:GetClientNumber( "toggle" ) != 0 local fwd = self:GetClientNumber( "fwd" ) local bck = self:GetClientNumber( "bck" ) wheelEnt.BaseTorque = torque wheelEnt:SetTorque( torque ) wheelEnt:SetToggle( toggle ) -- Make sure the table exists! wheelEnt.KeyBinds = wheelEnt.KeyBinds or {} wheelEnt.key_f = fwd wheelEnt.key_r = bck -- Remove old binds numpad.Remove( wheelEnt.KeyBinds[1] ) numpad.Remove( wheelEnt.KeyBinds[2] ) numpad.Remove( wheelEnt.KeyBinds[3] ) numpad.Remove( wheelEnt.KeyBinds[4] ) -- Add new binds wheelEnt.KeyBinds[1] = numpad.OnDown( self:GetOwner(), fwd, "WheelForward", wheelEnt, true ) wheelEnt.KeyBinds[2] = numpad.OnUp( self:GetOwner(), fwd, "WheelForward", wheelEnt, false ) wheelEnt.KeyBinds[3] = numpad.OnDown( self:GetOwner(), bck, "WheelReverse", wheelEnt, true ) wheelEnt.KeyBinds[4] = numpad.OnUp( self:GetOwner(), bck, "WheelReverse", wheelEnt, false ) return true end if ( SERVER ) then --[[--------------------------------------------------------- For duplicator, creates the wheel. -----------------------------------------------------------]] function MakeWheel( pl, Pos, Ang, Model, key_f, key_r, axis, direction, toggle, BaseTorque, Data ) if ( IsValid( pl ) ) then if ( !pl:CheckLimit( "wheels" ) ) then return false end end local wheel = ents.Create( "gmod_wheel" ) if ( !wheel:IsValid() ) then return end wheel:SetModel( Model ) wheel:SetPos( Pos ) wheel:SetAngles( Ang ) wheel:Spawn() wheel:SetPlayer( pl ) duplicator.DoGenericPhysics( wheel, pl, Data ) wheel.key_f = key_f wheel.key_r = key_r if ( axis ) then wheel.Axis = axis end direction = direction or 1 wheel:SetDirection( direction ) toggle = toggle or false wheel:SetToggle( toggle ) wheel:SetBaseTorque( BaseTorque ) wheel:UpdateOverlayText() wheel.KeyBinds = {} -- Bind to keypad wheel.KeyBinds[1] = numpad.OnDown( pl, key_f, "WheelForward", wheel, true ) wheel.KeyBinds[2] = numpad.OnUp( pl, key_f, "WheelForward", wheel, false ) wheel.KeyBinds[3] = numpad.OnDown( pl, key_r, "WheelReverse", wheel, true ) wheel.KeyBinds[4] = numpad.OnUp( pl, key_r, "WheelReverse", wheel, false ) if ( IsValid( pl ) ) then pl:AddCount( "wheels", wheel ) end return wheel end duplicator.RegisterEntityClass( "gmod_wheel", MakeWheel, "Pos", "Ang", "Model", "key_f", "key_r", "Axis", "Direction", "Toggle", "BaseTorque", "Data" ) end function TOOL:UpdateGhostWheel( ent, player ) if ( !ent ) then return end if ( !ent:IsValid() ) then return end local tr = util.GetPlayerTrace( player ) local trace = util.TraceLine( tr ) if (!trace.Hit) then return end if ( trace.Entity:IsPlayer() ) then ent:SetNoDraw( true ) return end local Ang = trace.HitNormal:Angle() + self.wheelAngle local CurPos = ent:GetPos() local NearestPoint = ent:NearestPoint( CurPos - (trace.HitNormal * 512) ) local WheelOffset = CurPos - NearestPoint local min = ent:OBBMins() ent:SetPos( trace.HitPos + trace.HitNormal + WheelOffset ) ent:SetAngles( Ang ) ent:SetNoDraw( false ) end --[[--------------------------------------------------------- Maintains the ghost wheel -----------------------------------------------------------]] function TOOL:Think() if (!self.GhostEntity || !self.GhostEntity:IsValid() || self.GhostEntity:GetModel() != self:GetClientInfo( "model" )) then self.wheelAngle = Angle( tonumber(self:GetClientInfo( "rx" )), tonumber(self:GetClientInfo( "ry" )), tonumber(self:GetClientInfo( "rz" )) ) self:MakeGhostEntity( self:GetClientInfo( "model" ), Vector(0,0,0), Angle(0,0,0) ) end self:UpdateGhostWheel( self.GhostEntity, self:GetOwner() ) end function TOOL.BuildCPanel( CPanel ) -- HEADER CPanel:AddControl( "Header", { Text = "#tool.wheel.name", Description = "#tool.wheel.desc" } ) local Options = { Default = { wheel_torque = "3000", wheel_friction = "0", wheel_nocollide = "1", wheel_forcelimit = "0" } } local CVars = { "wheel_torque", "wheel_friction", "wheel_nocollide", "wheel_forcelimit" } CPanel:AddControl( "ComboBox", { Label = "#tool.presets", MenuButton = 1, Folder = "wheel", Options = Options, CVars = CVars } ) CPanel:AddControl( "Numpad", { Label = "#tool.wheel.forward", Label2 = "#tool.wheel.reverse", Command = "wheel_fwd", Command2 = "wheel_bck", ButtonSize = "22" } ) CPanel:AddControl( "PropSelect", { Label = "#tool.wheel.model", ConVar = "wheel_model", Category = "Wheels", Height = 4, Models = list.Get( "WheelModels" ) } ) CPanel:AddControl( "Slider", { Label = "#tool.wheel.torque", Type = "Float", Min = 10, Max = 10000, Command = "wheel_torque" } ) CPanel:AddControl( "Slider", { Label = "#tool.wheel.forcelimit", Type = "Float", Min = 0, Max = 50000, Command = "wheel_forcelimit" } ) CPanel:AddControl( "Slider", { Label = "#tool.wheel.friction", Type = "Float", Min = 0, Max = 100, Command = "wheel_friction" } ) CPanel:AddControl( "CheckBox", { Label = "#tool.wheel.nocollide", Command = "wheel_nocollide" } ) CPanel:AddControl( "CheckBox", { Label = "#tool.wheel.toggle", Description = "#WheelTool_toggle_desc", Command = "wheel_toggle" } ) end list.Set( "WheelModels", "models/props_junk/sawblade001a.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0} ) list.Set( "WheelModels", "models/props_vehicles/carparts_wheel01a.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 90} ) list.Set( "WheelModels", "models/props_vehicles/apc_tire001.mdl", { wheel_rx = 0, wheel_ry = 0, wheel_rz = 0} ) list.Set( "WheelModels", "models/props_vehicles/tire001a_tractor.mdl", { wheel_rx = 0, wheel_ry = 0, wheel_rz = 0} ) list.Set( "WheelModels", "models/props_vehicles/tire001b_truck.mdl", { wheel_rx = 0, wheel_ry = 0, wheel_rz = 0} ) list.Set( "WheelModels", "models/props_vehicles/tire001c_car.mdl", { wheel_rx = 0, wheel_ry = 0, wheel_rz = 0} ) list.Set( "WheelModels", "models/props_wasteland/controlroom_filecabinet002a.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0} ) list.Set( "WheelModels", "models/props_borealis/bluebarrel001.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0} ) list.Set( "WheelModels", "models/props_c17/oildrum001.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0} ) list.Set( "WheelModels", "models/props_c17/playground_carousel01.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0} ) list.Set( "WheelModels", "models/props_c17/chair_office01a.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0} ) list.Set( "WheelModels", "models/props_c17/TrapPropeller_Blade.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0} ) list.Set( "WheelModels", "models/props_wasteland/wheel01.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 90} ) list.Set( "WheelModels", "models/props_trainstation/trainstation_clock001.mdl", { wheel_rx = 0, wheel_ry = 0, wheel_rz = 0} ) list.Set( "WheelModels", "models/props_junk/metal_paintcan001a.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0} ) list.Set( "WheelModels", "models/props_c17/pulleywheels_large01.mdl", { wheel_rx = 0, wheel_ry = 0, wheel_rz = 0} ) list.Set( "WheelModels", "models/props_phx/oildrum001_explosive.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0} ) list.Set( "WheelModels", "models/props_phx/wheels/breakable_tire.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0} ) list.Set( "WheelModels", "models/props_phx/gibs/tire1_gib.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0} ) list.Set( "WheelModels", "models/props_phx/normal_tire.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0} ) list.Set( "WheelModels", "models/props_phx/mechanics/medgear.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0} ) list.Set( "WheelModels", "models/props_phx/mechanics/biggear.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0} ) list.Set( "WheelModels", "models/props_phx/gears/bevel9.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0} ) list.Set( "WheelModels", "models/props_phx/gears/bevel90_24.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0} ) list.Set( "WheelModels", "models/props_phx/gears/bevel12.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0} ) list.Set( "WheelModels", "models/props_phx/gears/bevel24.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0} ) list.Set( "WheelModels", "models/props_phx/gears/bevel36.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0} ) list.Set( "WheelModels", "models/props_phx/gears/spur9.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0} ) list.Set( "WheelModels", "models/props_phx/gears/spur12.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0} ) list.Set( "WheelModels", "models/props_phx/gears/spur24.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0} ) list.Set( "WheelModels", "models/props_phx/gears/spur36.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0} ) list.Set( "WheelModels", "models/props_phx/smallwheel.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0} ) list.Set( "WheelModels", "models/props_phx/wheels/747wheel.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0} ) list.Set( "WheelModels", "models/props_phx/wheels/trucktire.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0} ) list.Set( "WheelModels", "models/props_phx/wheels/trucktire2.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0} ) list.Set( "WheelModels", "models/props_phx/wheels/metal_wheel1.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0} ) list.Set( "WheelModels", "models/props_phx/wheels/metal_wheel2.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0} ) list.Set( "WheelModels", "models/props_phx/wheels/wooden_wheel1.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0} ) list.Set( "WheelModels", "models/props_phx/wheels/wooden_wheel2.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0} ) list.Set( "WheelModels", "models/props_phx/construct/metal_plate_curve360.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0} ) list.Set( "WheelModels", "models/props_phx/construct/metal_plate_curve360x2.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0} ) list.Set( "WheelModels", "models/props_phx/construct/wood/wood_curve360x1.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0} ) list.Set( "WheelModels", "models/props_phx/construct/wood/wood_curve360x2.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0} ) list.Set( "WheelModels", "models/props_phx/construct/windows/window_curve360x1.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0} ) list.Set( "WheelModels", "models/props_phx/construct/windows/window_curve360x2.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0} ) list.Set( "WheelModels", "models/props_phx/trains/wheel_medium.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0} ) list.Set( "WheelModels", "models/props_phx/trains/medium_wheel_2.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0} ) list.Set( "WheelModels", "models/props_phx/trains/double_wheels.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0} ) list.Set( "WheelModels", "models/props_phx/trains/double_wheels2.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0} ) list.Set( "WheelModels", "models/props_phx/wheels/drugster_back.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0} ) list.Set( "WheelModels", "models/props_phx/wheels/drugster_front.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0} ) list.Set( "WheelModels", "models/props_phx/wheels/monster_truck.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0} ) list.Set( "WheelModels", "models/props_phx/misc/propeller2x_small.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0} ) list.Set( "WheelModels", "models/props_phx/misc/propeller3x_small.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0} ) list.Set( "WheelModels", "models/props_phx/misc/paddle_small.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0} ) list.Set( "WheelModels", "models/props_phx/misc/paddle_small2.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0} ) list.Set( "WheelModels", "models/props_phx/wheels/magnetic_small.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0} ) list.Set( "WheelModels", "models/props_phx/wheels/magnetic_small_base.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0} ) list.Set( "WheelModels", "models/props_phx/wheels/magnetic_medium.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0} ) list.Set( "WheelModels", "models/props_phx/wheels/magnetic_med_base.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0} ) list.Set( "WheelModels", "models/props_phx/wheels/magnetic_large.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0} ) list.Set( "WheelModels", "models/props_phx/wheels/magnetic_large_base.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0} ) list.Set( "WheelModels", "models/props_phx/wheels/moped_tire.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0 } ) --Tile Model Pack Wheels list.Set( "WheelModels", "models/hunter/misc/cone1x05.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0 } ) list.Set( "WheelModels", "models/hunter/tubes/circle2x2.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0 } ) list.Set( "WheelModels", "models/hunter/tubes/circle4x4.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0 } ) --Primitive Mechanics list.Set( "WheelModels", "models/mechanics/wheels/bmw.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0 } ) list.Set( "WheelModels", "models/mechanics/wheels/bmwl.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0 } ) list.Set( "WheelModels", "models/mechanics/wheels/rim_1.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0 } ) list.Set( "WheelModels", "models/mechanics/wheels/tractor.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0 } ) list.Set( "WheelModels", "models/mechanics/wheels/wheel_2.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0 } ) list.Set( "WheelModels", "models/mechanics/wheels/wheel_2l.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0 } ) list.Set( "WheelModels", "models/mechanics/wheels/wheel_extruded_48.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0 } ) list.Set( "WheelModels", "models/mechanics/wheels/wheel_race.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0 } ) list.Set( "WheelModels", "models/mechanics/wheels/wheel_smooth2.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0 } ) list.Set( "WheelModels", "models/Mechanics/gears/gear12x12.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0 } ) list.Set( "WheelModels", "models/Mechanics/gears/gear12x12_large.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0 } ) list.Set( "WheelModels", "models/Mechanics/gears/gear12x12_small.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0 } ) list.Set( "WheelModels", "models/Mechanics/gears/gear12x24.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0 } ) list.Set( "WheelModels", "models/Mechanics/gears/gear12x24_large.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0 } ) list.Set( "WheelModels", "models/Mechanics/gears/gear12x24_small.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0 } ) list.Set( "WheelModels", "models/Mechanics/gears/gear12x6.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0 } ) list.Set( "WheelModels", "models/Mechanics/gears/gear12x6_large.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0 } ) list.Set( "WheelModels", "models/Mechanics/gears/gear12x6_small.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0 } ) list.Set( "WheelModels", "models/Mechanics/gears/gear16x12.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0 } ) list.Set( "WheelModels", "models/Mechanics/gears/gear16x12_large.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0 } ) list.Set( "WheelModels", "models/Mechanics/gears/gear16x12_small.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0 } ) list.Set( "WheelModels", "models/Mechanics/gears/gear16x24.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0 } ) list.Set( "WheelModels", "models/Mechanics/gears/gear16x24_large.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0 } ) list.Set( "WheelModels", "models/Mechanics/gears/gear16x24_small.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0 } ) list.Set( "WheelModels", "models/Mechanics/gears/gear16x6.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0 } ) list.Set( "WheelModels", "models/Mechanics/gears/gear16x6_large.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0 } ) list.Set( "WheelModels", "models/Mechanics/gears/gear16x6_small.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0 } ) list.Set( "WheelModels", "models/Mechanics/gears/gear24x12.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0 } ) list.Set( "WheelModels", "models/Mechanics/gears/gear24x12_large.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0 } ) list.Set( "WheelModels", "models/Mechanics/gears/gear24x12_small.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0 } ) list.Set( "WheelModels", "models/Mechanics/gears/gear24x24.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0 } ) list.Set( "WheelModels", "models/Mechanics/gears/gear24x24_large.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0 } ) list.Set( "WheelModels", "models/Mechanics/gears/gear24x24_small.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0 } ) list.Set( "WheelModels", "models/Mechanics/gears/gear24x6.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0 } ) list.Set( "WheelModels", "models/Mechanics/gears/gear24x6_large.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0 } ) list.Set( "WheelModels", "models/Mechanics/gears/gear24x6_small.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0 } ) list.Set( "WheelModels", "models/Mechanics/gears2/gear_12t1.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0 } ) list.Set( "WheelModels", "models/Mechanics/gears2/gear_18t1.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0 } ) list.Set( "WheelModels", "models/Mechanics/gears2/gear_24t1.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0 } ) list.Set( "WheelModels", "models/Mechanics/gears2/gear_36t1.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0 } ) list.Set( "WheelModels", "models/Mechanics/gears2/gear_48t1.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0 } ) list.Set( "WheelModels", "models/Mechanics/gears2/gear_60t1.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0 } ) list.Set( "WheelModels", "models/Mechanics/gears2/gear_12t2.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0 } ) list.Set( "WheelModels", "models/Mechanics/gears2/gear_18t2.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0 } ) list.Set( "WheelModels", "models/Mechanics/gears2/gear_24t2.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0 } ) list.Set( "WheelModels", "models/Mechanics/gears2/gear_36t2.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0 } ) list.Set( "WheelModels", "models/Mechanics/gears2/gear_48t2.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0 } ) list.Set( "WheelModels", "models/Mechanics/gears2/gear_60t2.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0 } ) list.Set( "WheelModels", "models/Mechanics/gears2/gear_12t3.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0 } ) list.Set( "WheelModels", "models/Mechanics/gears2/gear_18t3.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0 } ) list.Set( "WheelModels", "models/Mechanics/gears2/gear_24t3.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0 } ) list.Set( "WheelModels", "models/Mechanics/gears2/gear_36t3.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0 } ) list.Set( "WheelModels", "models/Mechanics/gears2/gear_48t3.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0 } ) list.Set( "WheelModels", "models/Mechanics/gears2/gear_60t3.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0 } ) list.Set( "WheelModels", "models/Mechanics/gears2/bevel_12t1.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0 } ) list.Set( "WheelModels", "models/Mechanics/gears2/bevel_18t1.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0 } ) list.Set( "WheelModels", "models/Mechanics/gears2/bevel_24t1.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0 } ) list.Set( "WheelModels", "models/Mechanics/gears2/bevel_36t1.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0 } ) list.Set( "WheelModels", "models/Mechanics/gears2/bevel_48t1.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0 } ) list.Set( "WheelModels", "models/Mechanics/gears2/bevel_60t1.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0 } ) list.Set( "WheelModels", "models/Mechanics/gears2/vert_12t1.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0 } ) list.Set( "WheelModels", "models/Mechanics/gears2/vert_18t1.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0 } ) list.Set( "WheelModels", "models/Mechanics/gears2/vert_24t1.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0 } ) list.Set( "WheelModels", "models/Mechanics/gears2/vert_36t1.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0 } ) list.Set( "WheelModels", "models/Mechanics/gears2/pinion_20t1.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0 } ) list.Set( "WheelModels", "models/Mechanics/gears2/pinion_40t1.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0 } ) list.Set( "WheelModels", "models/Mechanics/gears2/pinion_80t1.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0 } ) list.Set( "WheelModels", "models/Mechanics/gears2/pinion_20t2.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0 } ) list.Set( "WheelModels", "models/Mechanics/gears2/pinion_40t2.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0 } ) list.Set( "WheelModels", "models/Mechanics/gears2/pinion_80t2.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0 } ) list.Set( "WheelModels", "models/Mechanics/gears2/pinion_20t3.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0 } ) list.Set( "WheelModels", "models/Mechanics/gears2/pinion_40t3.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0 } ) list.Set( "WheelModels", "models/Mechanics/gears2/pinion_80t3.mdl", { wheel_rx = 90, wheel_ry = 0, wheel_rz = 0 } ) --XQM Model Pack Wheels list.Set( "WheelModels", "models/NatesWheel/nateswheel.mdl", { wheel_rx = 0, wheel_ry = 0, wheel_rz = 0} ) list.Set( "WheelModels", "models/NatesWheel/nateswheelwide.mdl", { wheel_rx = 0, wheel_ry = 0, wheel_rz = 0} ) list.Set( "WheelModels", "models/XQM/JetEnginePropeller.mdl", { wheel_rx = 0, wheel_ry = 0, wheel_rz = 0} ) list.Set( "WheelModels", "models/XQM/JetEnginePropellerMedium.mdl", { wheel_rx = 0, wheel_ry = 0, wheel_rz = 0} ) list.Set( "WheelModels", "models/XQM/JetEnginePropellerBig.mdl", { wheel_rx = 0, wheel_ry = 0, wheel_rz = 0} ) list.Set( "WheelModels", "models/XQM/JetEnginePropellerHuge.mdl", { wheel_rx = 0, wheel_ry = 0, wheel_rz = 0} ) list.Set( "WheelModels", "models/XQM/JetEnginePropellerLarge.mdl", { wheel_rx = 0, wheel_ry = 0, wheel_rz = 0} ) list.Set( "WheelModels", "models/XQM/HelicopterRotor.mdl", { wheel_rx = 0, wheel_ry = 0, wheel_rz = 0} ) list.Set( "WheelModels", "models/XQM/HelicopterRotorMedium.mdl", { wheel_rx = 0, wheel_ry = 0, wheel_rz = 0} ) list.Set( "WheelModels", "models/XQM/HelicopterRotorBig.mdl", { wheel_rx = 0, wheel_ry = 0, wheel_rz = 0} ) list.Set( "WheelModels", "models/XQM/HelicopterRotorHuge.mdl", { wheel_rx = 0, wheel_ry = 0, wheel_rz = 0} ) list.Set( "WheelModels", "models/XQM/HelicopterRotorLarge.mdl", { wheel_rx = 0, wheel_ry = 0, wheel_rz = 0} ) list.Set( "WheelModels", "models/XQM/Propeller1.mdl", { wheel_rx = 0, wheel_ry = 0, wheel_rz = 0} ) list.Set( "WheelModels", "models/XQM/Propeller1Medium.mdl", { wheel_rx = 0, wheel_ry = 0, wheel_rz = 0} ) list.Set( "WheelModels", "models/XQM/Propeller1Big.mdl", { wheel_rx = 0, wheel_ry = 0, wheel_rz = 0} ) list.Set( "WheelModels", "models/XQM/Propeller1Huge.mdl", { wheel_rx = 0, wheel_ry = 0, wheel_rz = 0} ) list.Set( "WheelModels", "models/XQM/Propeller1Large.mdl", { wheel_rx = 0, wheel_ry = 0, wheel_rz = 0} ) list.Set( "WheelModels", "models/XQM/AirPlaneWheel1.mdl", { wheel_rx = 0, wheel_ry = 0, wheel_rz = 0} ) list.Set( "WheelModels", "models/XQM/AirPlaneWheel1Medium.mdl", { wheel_rx = 0, wheel_ry = 0, wheel_rz = 0} ) list.Set( "WheelModels", "models/XQM/AirPlaneWheel1Big.mdl", { wheel_rx = 0, wheel_ry = 0, wheel_rz = 0} ) list.Set( "WheelModels", "models/XQM/AirPlaneWheel1Huge.mdl", { wheel_rx = 0, wheel_ry = 0, wheel_rz = 0} ) list.Set( "WheelModels", "models/XQM/AirPlaneWheel1Large.mdl", { wheel_rx = 0, wheel_ry = 0, wheel_rz = 0} ) --Xeon133's Wheels list.Set( "WheelModels", "models/xeon133/offroad/Off-road-20.mdl", { wheel_rx = 0, wheel_ry = 0, wheel_rz = 0} ) list.Set( "WheelModels", "models/xeon133/offroad/Off-road-30.mdl", { wheel_rx = 0, wheel_ry = 0, wheel_rz = 0} ) list.Set( "WheelModels", "models/xeon133/offroad/Off-road-40.mdl", { wheel_rx = 0, wheel_ry = 0, wheel_rz = 0} ) list.Set( "WheelModels", "models/xeon133/offroad/Off-road-50.mdl", { wheel_rx = 0, wheel_ry = 0, wheel_rz = 0} ) list.Set( "WheelModels", "models/xeon133/offroad/Off-road-60.mdl", { wheel_rx = 0, wheel_ry = 0, wheel_rz = 0} ) list.Set( "WheelModels", "models/xeon133/offroad/Off-road-70.mdl", { wheel_rx = 0, wheel_ry = 0, wheel_rz = 0} ) list.Set( "WheelModels", "models/xeon133/offroad/Off-road-80.mdl", { wheel_rx = 0, wheel_ry = 0, wheel_rz = 0} )
-- uncomment to run unit tests -- require 'skeletor.unittests.run' -- load the skeletor module with property adjustments local Skeletor = require('skeletor.skeletor') skeletor = Skeletor({ boundariesCalculate = true, boundariesShow = true, shapeShow = true, shapeMode = "fill" }) opts = { x = 400, y = 200, angle = 0, speed = 100, sx = 1, sy = 1, scaleSpeed = 1, boneArmLeftAngle = 150, boneArmLeftLength = 80 } function love.load() skeletor:newSkeleton('man', {x = opts.x, y = opts.y, angle = opts.angle, sx = opts.sx, sy = opts.sy}) skeletor:newBone('man.head', { length = 50, angle = math.rad(110), -- you can use utils methods when loading skeletor. -- this should be changed as it isn't transparent. -- the shape is modified for a more headlike shape. shapeShape = utils:getEllipseVertices(0, 0, 1, 1, math.rad(0), 30), }) skeletor:newBone('man.head.body', {length = 100, angle = math.rad(90)}) skeletor:newBone('man.head.armRight', {length = 80, angle = math.rad(30)}) skeletor:newBone('man.head.armRight.forearm', {length = 40, angle = math.rad(300)}) skeletor:newBone('man.head.armLeft', {length = opts.boneArmLeftLength, angle = math.rad(opts.boneArmLeftAngle)}) skeletor:newBone('man.head.armLeft.forearm', {length = 40, angle = math.rad(30)}) skeletor:newBone('man.head.body.legRight', {length = 100, angle = math.rad(45)}) skeletor:newBone('man.head.body.legRight.foot', {length = 50, angle = math.rad(120)}) skeletor:newBone('man.head.body.legLeft', {length = 100, angle = math.rad(100)}) skeletor:newBone('man.head.body.legLeft.foot', {length = 50, angle = math.rad(160)}) end function love.update(dt) -- move skeleton sideways if love.keyboard.isDown('left') then opts.x = opts.x - (opts.speed*dt) elseif love.keyboard.isDown('right') then opts.x = opts.x + (opts.speed*dt) end skeletor:editSkeleton('man', {x = opts.x}) -- move skeleton up and down if love.keyboard.isDown('up') then opts.y = opts.y - (opts.speed*dt) elseif love.keyboard.isDown('down') then opts.y = opts.y + (opts.speed*dt) end skeletor:editSkeleton('man', {y = opts.y}) -- rotate skeleton if love.keyboard.isDown('q') then opts.angle = opts.angle + (opts.speed*dt) elseif love.keyboard.isDown('w') then opts.angle = opts.angle - (opts.speed*dt) end skeletor:editSkeleton('man', {angle = math.rad(opts.angle)}) -- mofify x scale if love.keyboard.isDown('a') then opts.sx = opts.sx + (opts.scaleSpeed*dt) elseif love.keyboard.isDown('s') then opts.sx = opts.sx - (opts.scaleSpeed*dt) end skeletor:editSkeleton('man', {sx = opts.sx}) -- mofify y scale if love.keyboard.isDown('z') then opts.sy = opts.sy + (opts.scaleSpeed*dt) elseif love.keyboard.isDown('x') then opts.sy = opts.sy - (opts.scaleSpeed*dt) end skeletor:editSkeleton('man', {sy = opts.sy}) -- rotate arm left bone if love.keyboard.isDown('e') then opts.boneArmLeftAngle = opts.boneArmLeftAngle + (opts.speed*dt) elseif love.keyboard.isDown('r') then opts.boneArmLeftAngle = opts.boneArmLeftAngle - (opts.speed*dt) end skeletor:editBone('man.head.armLeft', {angle = math.rad(opts.boneArmLeftAngle)}) -- mofify left arm's length if love.keyboard.isDown('d') then opts.boneArmLeftLength = opts.boneArmLeftLength - (opts.speed*dt) elseif love.keyboard.isDown('f') then opts.boneArmLeftLength = opts.boneArmLeftLength + (opts.speed*dt) end skeletor:editBone('man.head.armLeft', {length = opts.boneArmLeftLength}) end function love.draw() love.graphics.setColor({255, 255, 255}) love.graphics.print("- use arrows to move skeleton", 10, 10) love.graphics.print("- use q and w to rotate skeleton", 10, 30) love.graphics.print("- use a and s to modify x scaling", 10, 50) love.graphics.print("- use z and x to modify y scaling", 10, 70) love.graphics.print("- use e and r to rotate left arm", 10, 90) love.graphics.print("- use d and f to change the left arm's length", 10, 110) skeletor:draw() end
mapFields = require "lib/mapFields" selection = self.ask_menu("What do you want from me?", { [0] = "Gather up some information on the hideout.", [1] = "Take me to the hideout.", [2] = "Nothing." }) if selection == 0 then self.say("I can take you to the hideout, but the place is infested with thugs looking for trouble. You'll need to be both incredibly strong and brave to enter the premise. At the hideaway, you'll find the Boss that controls all the other bosses around this area. It's easy to get to the hideout, but the room on the top floor of the place can only be entered ONCE a day. The Boss's Room is not a place to mess around. I suggest you don't stay there for too long; you'll need to swiftly take care of the business once inside. The boss himself is a difficult foe, but you'll run into some incredibly powerful enemies on your way to meeting the boss! It ain't going to be easy.") elseif selection == 1 then self.say("Oh, the brave one. I've been awaiting your arrival. If these thugs are left unchecked, there's no telling what going to happen in this neighborhood. Before that happens, I hope you take care of all of them and beat the boss, who resides on the 5th floor. You'll need to be on alert at all times, since the boss is too tough for even the wisemen to handle. Looking at your eyes, however, I can see that eye of the tiger, the eyes that tell me you can do this. Let's go!") target.field = mapFields.getID("NearTheHideout") else self.say("I'm a busy person! Leave me alone if that's all you need!") end
Projectile = GameObject:extend() function Projectile:new(area, x, y, opts) Projectile.super.new(self, area, x, y, opts) self.s = opts.s or 2.5 self.v = opts.v or 200 self.color = attacks[self.attack].color self.collider = self.area.world:newCircleCollider(self.x, self.y, self.s) self.collider:setObject(self) self.collider:setCollisionClass('Projectile') self.collider:setLinearVelocity(self.v*math.cos(self.r), self.v*math.sin(self.r)) end function Projectile:update(dt) Projectile.super.update(self, dt) self.collider:setLinearVelocity(self.v*math.cos(self.r), self.v*math.sin(self.r)) if self.x < 0 then self:die() end if self.y < 0 then self:die() end if self.x > gw then self:die() end if self.y > gh then self:die() end end function Projectile:draw() pushRotate(self.x, self.y, Vector(self.collider:getLinearVelocity()):angle()) love.graphics.setLineWidth(self.s - self.s/4) love.graphics.setColor(self.color) love.graphics.line(self.x - 2*self.s, self.y, self.x, self.y) love.graphics.setColor(default_color) love.graphics.line(self.x, self.y, self.x + 2*self.s, self.y) love.graphics.setLineWidth(1) love.graphics.pop() end function Projectile:destroy() Projectile.super.destroy(self) end function Projectile:die() self.dead = true self.area:addGameObject('ProjectileDeathEffect', self.x, self.y, {color = self.color or default_color, w = 3*self.s}) end
local python = require "dap-python" python.setup "/usr/bin/python3" vim.api.nvim_set_keymap( "n", "<leader>dn", ":lua require('dap-python').test_method()<CR>", { noremap = true, silent = true } ) vim.api.nvim_set_keymap( "n", "<leader>df", ":lua require('dap-python').test_class()<CR>", { noremap = true, silent = true } ) vim.api.nvim_set_keymap( "v", "<leader>ds", "<ESC>:lua require('dap-python').debug_selection()<CR>", { noremap = true, silent = true } )
SILE.registerCommand("xmltricks:ignore", function (_, content) for token in SU.gtoke(content[1]) do if token.string then SILE.call("define", { command = token.string}, function() end) end end end) SILE.registerCommand("xmltricks:passthru", function (_, content) for token in SU.gtoke(content[1]) do if token.string then SILE.registerCommand(token.string, function(_, c) SILE.process(c) end) end end end)
local Beam = {} function Beam.initialize(enemy, props) local game = enemy:get_game() local map = enemy:get_map() local hero = map:get_hero() local sprite local movement -- Event called when the enemy is initialized. function enemy:on_created() -- Initialize the properties of your enemy here, -- like the sprite, the life and the damage. sprite = enemy:create_sprite("enemies/" .. enemy:get_breed()) enemy:set_life(1) enemy:set_damage(1) enemy:set_layer_independent_collisions(true) enemy:set_traversable(true) end function enemy:on_obstacle_reached(enemyMovement) print("Obstacle reached") enemy:remove() end -- Event called when the enemy should start or restart its movements. -- This is called for example after the enemy is created or after -- it was hurt or immobilized. function enemy:on_restarted() movement = sol.movement.create("straight") movement:set_angle(enemy:get_angle(hero)) movement:set_speed(100) movement:set_smooth(false) movement:set_max_distance(props.length) function movement:on_finished() enemy:remove() end movement:start(enemy) end end return Beam
local core = l2df or require((...):match("(.-)[^%.]+$") .. "core") assert(type(core) == "table" and core.version >= 1.0, "UI works only with l2df v1.0 and higher") local i18n = core.import "i18n" local fonts = core.import "fonts" local media = core.import "media" local settings = core.import "settings" local Entity = core.import "core.entities.entity" local fopen = io.open local fs = love and love.filesystem local UI = Entity:extend() function UI.resource(file) local path = settings.global.ui_path .. file if fs and fs.getInfo(path) then return path else local f = fopen(path, "r") if f then f:close() return path end end -- TODO: stuff below is a hardcoded resource == bad, needs refactor return settings.global.ui_path .. "dummy.png" end function UI:init(x, y, childs) self.x = x or 0 self.y = y or 0 self.hidden = false self.active = true self.childs = childs or { } assert(type(self.childs) == "table", "Parameter 'childs' must be a table.") for i = 1, #self.childs do local child = childs[i] assert(child and child:isInstanceOf(UI), "Only UI elements can be a part of UI.") child.x = child.x + self.x child.y = child.y + self.y end end function UI:on(event, callback) assert(type(event) == "string", "Event name must be string") assert(type(callback) == "function", "Callback must be a function") if type(self[event]) == "function" then local old = self[event] self[event] = function (...) old(...) callback(...) end end return self end function UI:hide() self.hidden = true return self end function UI:show() self.hidden = false return self end function UI:toggle() self.hidden = not self.hidden return self end function UI:edit(callback) local x, y = self.x, self.y if type(callback) == "function" then callback(self) elseif type(callback) == "table" then for k, v in pairs(callback) do self[k] = v end end if x ~= self.x or y ~= self.y then for i = 1, #self.childs do local child = self.childs[i] child.x = child.x - x + self.x child.y = child.y - y + self.y end end return self end UI.Image = UI:extend() function UI.Image:init(file, x, y, cutting, sprite, filter) self:super(x, y) self.resource = file and media.Image(file, cutting, nil, filter) self.sprite = sprite or 0 end function UI.Image:draw() self.resource:draw(self.x, self.y) end UI.Video = UI:extend() function UI.Video:init(file, x, y, stretch) self:super(x, y) self.video = media.Video(file) self.stretch = stretch or false self.size = { width = 1, height = 1 } end function UI.Video:resize(w, h) if self.stretch then self.size.width = core.settings.gameWidth / self.video.info.width self.size.height = core.settings.gameHeight / self.video.info.height end end function UI.Video:draw() self.video:draw(self.x, self.y, self.size) end function UI.Video:play() self.video.resource:play() return self end function UI.Video:stop() self.video.resource:pause() self.video.resource:rewind() return self end function UI.Video:pause() self.video.resource:pause() return self end function UI.Video:hide() self.video.resource:pause() self.hidden = true return self end function UI.Video:show() self.video.resource:play() self.hidden = false return self end UI.Animation = UI:extend() function UI.Animation:init(file, x, y, w, h, row, col, frames, wait, looped) self:super(x, y) self.resource = file and media.Image(file, {w = w or 1, h = h or 1, x = row or 1, y = col or 1}) self.frame = 1 self.max_frames = frames self.wait = 0 self.max_wait = wait or 1 self.looped = looped or false end function UI.Animation:update(dt) if self.wait < self.max_wait then self.wait = self.wait + 1 else self.wait = 0 if self.frame < self.max_frames then self.frame = self.frame + 1 elseif self.looped then self.frame = 1 end end end function UI.Animation:draw() self.resource:draw(self.x, self.y, self.frame) end UI.Text = UI:extend() function UI.Text:init(text, fnt, x, y, color, align, stroke) self:super(x, y) self.align = align self.stroke = stroke self.font = fnt or "default" self.color = color or { 0, 0, 0, 1 } self:setText(text) end function UI.Text:roomloaded() self:setText() end function UI.Text:localechanged() self:setText() end function UI.Text:setText(new_text) if type(new_text) == "string" then self.text = new_text elseif type(new_text) == "table" then self.text = new_text.text self.key = new_text.key elseif self.key then local temp = i18n(self.key) self.text = temp and temp.text else self.text = self.text or "" end local font = fonts.list[self.font] if font and self.text then self.width = font:getWidth(self.text) self.height = font:getHeight(self.text) end end function UI.Text:draw() fonts.print(self.text, self.x, self.y, self.align, self.font, self.stroke, self.width, self.color) end UI.Button = UI:extend() function UI.Button:init(text, x, y, w, h, ox, oy, bg, use_mouse) self:setText( type(text) == "string" and UI.Text:new(text) or text ) self:super(x, y, { self.text }) self.ox = ox or 0 self.oy = oy or 0 self.w = w or self.text.width or 1 self.h = h or self.text.height or 1 self.background = type(bg) == "string" and media.Image(bg) or bg self.use_mouse = use_mouse and true or false self.hover = false self.clicked = false end function UI.Button:mousemoved(x, y, dx, dy) if not self.use_mouse then return end local mx = (x + dx - self.ox) / core.scalex local my = (y + dy - self.oy) / core.scaley self.hover = mx > self.x and mx < self.x + self.w and my > self.y and my < self.y + self.h self.clicked = self.clicked and self.hover end function UI.Button:useMouse(value) self.use_mouse = value and true or false return self end function UI.Button:update(dt) -- hook end function UI.Button:click(x, y, button) -- hook end function UI.Button:roomloaded() self.text:localechanged() end function UI.Button:localechanged() self.text:localechanged() end function UI.Button:setText(new_text) if type(new_text) == "string" then self.text:setText(new_text) elseif not self.text and new_text:isTypeOf(UI.Text) then self.text = new_text:on("setText", function (text) self.w = text.width or 1 self.h = text.height or 1 end) end end function UI.Button:mousepressed(x, y, button, istouch, presses) x = (x - self.ox) / core.scalex y = (y - self.oy) / core.scaley self.clicked = self.use_mouse and x > self.x and x < self.x + self.w and y > self.y and y < self.y + self.h if self.clicked then self:click(x, y, button) end end function UI.Button:draw() if self.background then self.background(self.x, self.y,0) end if self.text then self.text.x = self.x + self.ox self.text.y = self.y + self.oy -- self.text:draw() end end UI.List = UI:extend() function UI.List:init(x, y, childs, horizontal) self:super(x, y, childs) self.cursor = 1 self.horizontal = horizontal or false end function UI.List:press(button, player) local size = #self.childs if self.horizontal then if button == "left" then local old = self.childs[self.cursor] self.cursor = self.cursor > 1 and self.cursor - 1 or size return self:change(self.childs[self.cursor], old) elseif button == "right" then local old = self.childs[self.cursor] self.cursor = self.cursor < size and self.cursor + 1 or 1 return self:change(self.childs[self.cursor], old) end else if button == "up" then local old = self.childs[self.cursor] self.cursor = self.cursor > 1 and self.cursor - 1 or size return self:change(self.childs[self.cursor], old) elseif button == "down" then local old = self.childs[self.cursor] self.cursor = self.cursor < size and self.cursor + 1 or 1 return self:change(self.childs[self.cursor], old) end end if button == "attack" and self.childs[self.cursor].click then return self.childs[self.cursor]:click(nil, nil, 1) end end function UI.List:change(new, old) old.hover = false new.hover = true end function UI.List:update(dt) self.childs[self.cursor].hover = true end return UI
local Object = require("lib.classic.main") local private = require("bin.instances") local Stat = Object:extend() local function createEntry(value, action, reason) reason = reason or "None" assert(type(action) == "string", "'" .. tostring(action) .. "' is not a string.") assert(type(reason) == "string", "'" .. tostring(reason) .. "' is not a string.") action = action:upper() assert(Stat.validActions[action], "'" .. action .. "' is not a valid stat change action.") return { timestamp = os.time(os.date("!*t")), value = value, action = action, reason = reason } end Stat.validActions = { INIT = true, LVLUP = true, INCREASE = true, DECREASE = true, CHANGE = true, DEBUG = true, REVERT = true, OBVERT = true } function Stat:new(value, reason) private[self.uuid] = private[self.uuid] or {} private[self.uuid].value = value private[self.uuid].history = { createEntry(value, "INIT", reason) } private[self.uuid].index = 1 end function Stat:get_value() return private[self.uuid].value end function Stat:get_history() return private[self.uuid].history end function Stat:set_value(_) error("Use the 'change' method to update a stat.") end function Stat:set_history(_) error("You may not change the history table directly.") end function Stat:change(val, action, reason) local p = private[self.uuid] local old_val = self.value assert(type(val) == type(old_val), "You have changed your stat's type, which is not allowed. Your previous value's type was '" .. type(old_val) .. "' but the new type is '" .. type(val) .. "'.") p.value = val if self.index then self.index = nil else p.index = #p.history + 1 end p.history[#p.history + 1] = createEntry(val, action, reason) end function Stat:revert(steps, reason) local p = private[self.uuid] steps = steps or 1 assert(p.index ~= 1, "Unable to revert as you as there is nothing to revert to.") assert(type(steps) == "number", "You can only revert a numeric amount.") assert(steps > 0, "You can only revert a positive number of steps. Use obvert if you'd like to 'redo'.") assert(p.index - steps + 1 > 0, "You can only revert to the first entry. (Tried to revert " .. steps .. " times, there are only " .. #p.history .. " entries.)") p.index = p.index - steps self.index = true self:change(p.history[p.index].value, "REVERT", reason or "No reason given.") end function Stat:obvert(steps, reason) local p = private[self.uuid] steps = steps or 1 assert(p.index ~= #p.history, "Unable to obvert as you as there is nothing to obvert to.") assert(type(steps) == "number", "You can only obvert a numeric amount.") assert(steps > 0, "You can only obvert a positive number of steps. Use revert if you'd like to 'undo'.") assert(p.index + steps - 1 < #p.history, "You can only obvert to the last entry. (Tried to obvert " .. steps .. " times, there are only " .. #p.history .. " entries.)") p.index = p.index + steps self.index = true self:change(p.history[p.index].value, "OBVERT", reason or "No reason given.") end Stat.__type = "Stat" function Stat:__tostring() return "s" + private[self.uuid].value end return Stat
hydro = { -- The case prefix and postfixes prefix = "shock_box_3d", postfix = "dat", -- The frequency of outputs output_freq = 1e6, -- The time stepping parameters final_time = 0.2, max_steps = 1e6, CFL = 1./3., -- the mesh mesh = { type = "box", dimensions = {10, 10, 10}, xmin = {-0.5, -0.5, -0.5}, xmax = { 0.5, 0.5, 0.5} }, -- the equation of state eos = { type = "ideal_gas", gas_constant = 1.4, specific_heat = 1.0 }, -- the initial conditions -- return density, velocity, pressure ics = function (x,y,z,t) if x < 0 and y < 0 and z < 0 then return 0.125, {0,0,0}, 0.1 else return 1.0, {0,0,0}, 1.0 end end }
local rnd = math.random local G = require 'geoip' local function time(f, desc) s = os.clock() f() e = os.clock() print("DESC: " .. desc .. '\t' .. e-s .. 's') end time(function() cnt, err = G.load("ipdb.csv") assert(err == nil) end, "DB load") time(function() for i=1,100000 do local ip = string.format("%d.%d.%d.%d", rnd(1,256),rnd(1,256), rnd(1,256),rnd(1,256)) local country,err = G.find(ip,"N/A") end end, "100000 random IPs")
pfUI:RegisterSkin("Options - Video", function () local border = tonumber(pfUI_config.appearance.border.default) local bpad = border > 1 and border - 1 or 1 CreateBackdrop(OptionsFrame, nil, nil, .75) EnableMovable(OptionsFrame) HookScript(OptionsFrame, "OnShow", function() this:ClearAllPoints() this:SetPoint("CENTER", 0, 0) end) OptionsFrameHeader:SetTexture("") local OptionsFrameHeaderText = GetNoNameObject(OptionsFrame, "FontString", "ARTWORK", VIDEOOPTIONS_MENU) OptionsFrameHeaderText:ClearAllPoints() OptionsFrameHeaderText:SetPoint("TOP", OptionsFrame.backdrop, "TOP", 0, -10) SkinButton(OptionsFrameDefaults) SkinButton(OptionsFrameCancel) SkinButton(OptionsFrameOkay) OptionsFrameOkay:ClearAllPoints() OptionsFrameOkay:SetPoint("RIGHT", OptionsFrameCancel, "LEFT", -2*bpad, 0) SkinDropDown(OptionsFrameResolutionDropDown) SkinDropDown(OptionsFrameRefreshDropDown) SkinDropDown(OptionsFrameMultiSampleDropDown) CreateBackdrop(OptionsFrameDisplay, nil, true, .75) CreateBackdrop(OptionsFrameWorldAppearance, nil, true, .75) CreateBackdrop(OptionsFrameBrightness, nil, true, .75) CreateBackdrop(OptionsFramePixelShaders, nil, true, .75) CreateBackdrop(OptionsFrameMiscellaneous, nil, true, .75) for i=1, 9 do local shift = 0 if i == 1 or i == 6 then shift = 4 elseif i == 4 or i == 8 then shift = 10 end SkinSlider(_G["OptionsFrameSlider"..i]) local point, anchor, anchorPoint, x, y = _G["OptionsFrameSlider"..i]:GetPoint() _G["OptionsFrameSlider"..i]:ClearAllPoints() _G["OptionsFrameSlider"..i]:SetPoint(point, anchor, anchorPoint, x, y - shift) end for i=1, 18 do SkinCheckbox(_G["OptionsFrameCheckButton"..i], 28) end end)
------------------------------------- ---------------- Cuffs -------------- ------------------------------------- -- Copyright (c) 2015 Nathan Healy -- -------- All rights reserved -------- ------------------------------------- -- weapon_cuff_police.lua SHARED -- -- -- -- Strong police handcuffs. -- ------------------------------------- AddCSLuaFile() SWEP.Base = "weapon_cuff_base" SWEP.Category = "Handcuffs" SWEP.Author = "my_hat_stinks" SWEP.Instructions = "Sturdy police-issue handcuffs." SWEP.Spawnable = true SWEP.AdminOnly = true SWEP.AdminSpawnable = true SWEP.Slot = 3 SWEP.PrintName = "Police Handcuffs" // // Handcuff Vars SWEP.CuffTime = 1.0 // Seconds to handcuff SWEP.CuffSound = Sound( "buttons/lever7.wav" ) SWEP.CuffMaterial = "phoenix_storms/gear" SWEP.CuffRope = "cable/cable2" SWEP.CuffStrength = 1.4 SWEP.CuffRegen = 1.4 SWEP.RopeLength = 0 SWEP.CuffReusable = true SWEP.CuffBlindfold = false SWEP.CuffGag = false SWEP.CuffStrengthVariance = 0.1 // Randomise strangth SWEP.CuffRegenVariance = 0.1 // Randomise regen
local cjson = require "cjson" local utils = require "kong.tools.utils" local helpers = require "spec.helpers" local pl_path = require "pl.path" local pl_file = require "pl.file" local pl_stringx = require "pl.stringx" local FILE_LOG_PATH = os.tmpname() describe("Plugin: file-log (log)", function() local client setup(function() local dao = select(3, helpers.get_db_utils()) local api1 = assert(dao.apis:insert { name = "api-1", hosts = { "file_logging.com" }, upstream_url = helpers.mock_upstream_url, }) assert(dao.plugins:insert { api_id = api1.id, name = "file-log", config = { path = FILE_LOG_PATH, reopen = true, }, }) assert(helpers.start_kong({ nginx_conf = "spec/fixtures/custom_nginx.template", })) end) teardown(function() helpers.stop_kong() end) before_each(function() client = helpers.proxy_client() os.remove(FILE_LOG_PATH) end) after_each(function() if client then client:close() end os.remove(FILE_LOG_PATH) end) it("logs to file", function() local uuid = utils.random_string() -- Making the request local res = assert(client:send({ method = "GET", path = "/status/200", headers = { ["file-log-uuid"] = uuid, ["Host"] = "file_logging.com" } })) assert.res_status(200, res) helpers.wait_until(function() return pl_path.exists(FILE_LOG_PATH) and pl_path.getsize(FILE_LOG_PATH) > 0 end, 10) local file_log = pl_file.read(FILE_LOG_PATH) local log_message = cjson.decode(pl_stringx.strip(file_log)) assert.same("127.0.0.1", log_message.client_ip) assert.same(uuid, log_message.request.headers["file-log-uuid"]) end) it("reopens file on each request", function() local uuid1 = utils.uuid() -- Making the request local res = assert(client:send({ method = "GET", path = "/status/200", headers = { ["file-log-uuid"] = uuid1, ["Host"] = "file_logging.com" } })) assert.res_status(200, res) helpers.wait_until(function() return pl_path.exists(FILE_LOG_PATH) and pl_path.getsize(FILE_LOG_PATH) > 0 end, 10) -- remove the file to see whether it gets recreated os.remove(FILE_LOG_PATH) -- Making the next request local uuid2 = utils.uuid() local res = assert(client:send({ method = "GET", path = "/status/200", headers = { ["file-log-uuid"] = uuid2, ["Host"] = "file_logging.com" } })) assert.res_status(200, res) local uuid3 = utils.uuid() local res = assert(client:send({ method = "GET", path = "/status/200", headers = { ["file-log-uuid"] = uuid3, ["Host"] = "file_logging.com" } })) assert.res_status(200, res) helpers.wait_until(function() return pl_path.exists(FILE_LOG_PATH) and pl_path.getsize(FILE_LOG_PATH) > 0 end, 10) local file_log, err = pl_file.read(FILE_LOG_PATH) assert.is_nil(err) assert(not file_log:find(uuid1, nil, true), "did not expected 1st request in logfile") assert(file_log:find(uuid2, nil, true), "expected 2nd request in logfile") assert(file_log:find(uuid3, nil, true), "expected 3rd request in logfile") end) end)
--[[Improved by Cit, You can press a key to respawn, and you don't lose your animation.]] --[[Good for places with lots of explosions or things that would otherwise kill you in normal math.huge godmode.]] --[[ Press p to turn on godmode. Quickly doubletap p to respawn. ]] ---------------------------------------------- local p = game.Players.LocalPlayer local char = game.Players.LocalPlayer.Character local isReset = false local mouse = p:GetMouse() local torso = char.Torso local torw = char.HumanoidRootPart.RootJoint local char_hum = char:WaitForChild'Humanoid' local selfname = game.Players.LocalPlayer.Name isGod = false ---------------------------------------------- mouse.KeyDown:connect(function(k) if k=='p' then if isGod == false then isGod = true char_hum:Destroy() local fakehum=Instance.new('Humanoid',char) fakehum:SetStateEnabled(Enum.HumanoidStateType.Dead,false) char_hum = fakehum wlds={} for i,v in pairs(torso:children())do local cl = v:Clone() table.insert(wlds,cl) end local clj = torw:Clone() local con function onDeath(h) -- for i,v in pairs(torso:children())do v:Destroy()end if h <= 0 then for i,v in pairs(wlds)do local cl = v:Clone()cl.Parent=torso end -- for i,v in pairs(char:children())do if v:IsA'BasePart'then v:MakeJoints()end end local cl=clj:Clone()cl.Parent=char char_hum.Health = 100 -- con:disconnect() -- con=char_hum.HealthChanged:connect(function(h)onDeath(h)end) end end con = char_hum.HealthChanged:connect(function(h)onDeath(h)end) wait(0.1) char.Parent = game.Lighting wait(0.1) char.Parent = game.Workspace print("Godded.") end end end) mouse.KeyDown:connect(function(k) if k=='p' then if isGod == true then isGod = false wlds = {} print("Un-godded and respawned") game.Players.LocalPlayer.Character.Parent = game.Lighting p:LoadCharacter() local redo = script:Clone() redo.Parent = game.Players.LocalPlayer.Character script:Destroy() end end end)
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015 - 2019, TBOOX Open Source Group. -- -- @author ruki -- @file main.lua -- -- imports import("core.base.option") import("core.base.task") import("core.project.config") import("core.platform.environment") import("make.makefile") import("make.xmakefile") import("cmake.cmakelists") import("vstudio.vs") import("vsxmake.vsxmake") import("clang.compile_flags") import("clang.compile_commands") -- make project function _make(kind) -- the maps local maps = { makefile = makefile.make , xmakefile = xmakefile.make , cmakelists = cmakelists.make , vs2002 = vs.make(2002) , vs2003 = vs.make(2003) , vs2005 = vs.make(2005) , vs2008 = vs.make(2008) , vs2010 = vs.make(2010) , vs2012 = vs.make(2012) , vs2013 = vs.make(2013) , vs2015 = vs.make(2015) , vs2017 = vs.make(2017) , vs2019 = vs.make(2019) , vs = vs.make() , vsxmake2010 = vsxmake.make(2010) , vsxmake2012 = vsxmake.make(2012) , vsxmake2013 = vsxmake.make(2013) , vsxmake2015 = vsxmake.make(2015) , vsxmake2017 = vsxmake.make(2017) , vsxmake2019 = vsxmake.make(2019) , vsxmake = vsxmake.make() , compile_flags = compile_flags.make , compile_commands = compile_commands.make } assert(maps[kind], "the project kind(%s) is not supported!", kind) -- make it maps[kind](option.get("outputdir")) end -- main function main() -- config it first task.run("config") -- enter toolchains environment environment.enter("toolchains") -- make project _make(option.get("kind")) -- leave toolchains environment environment.leave("toolchains") -- trace cprint("${bright}create ok!") end
-- lua扩展 -- table扩展 -- 返回table大小 table.size = function(t) local count = 0 for _ in pairs(t) do count = count + 1 end return count end -- 判断table是否为空 table.empty = function(t) return not next(t) end -- 返回table索引列表 table.indices = function(t) local result = {} for k, v in pairs(t) do table.insert(result, k) end end -- 返回table值列表 table.values = function(t) local result = {} for k, v in pairs(t) do table.insert(result, v) end end -- 浅拷贝 table.clone = function(t, nometa) local result = {} if not nometa then setmetatable(result, getmetatable(t)) end for k, v in pairs (t) do result[k] = v end return result end -- 深拷贝 table.copy = function(t, nometa) local result = {} if not nometa then setmetatable(result, getmetatable(t)) end for k, v in pairs(t) do if type(v) == "table" then result[k] = copy(v) else result[k] = v end end return result end table.merge = function(dest, src) for k, v in pairs(src) do dest[k] = v end end -- string扩展 -- 下标运算 do local mt = getmetatable("") local _index = mt.__index mt.__index = function (s, ...) local k = ... if "number" == type(k) then return _index.sub(s, k, k) else return _index[k] end end end --[[ string.split = function(s, delim) local split = {} local pattern = "[^" .. delim .. "]+" string.gsub(s, pattern, function(v) table.insert(split, v) end) return split end --]] function string.split(str, delimiter) if str==nil or str=='' or delimiter==nil then return nil end local result = {} for match in (str..delimiter):gmatch("(.-)"..delimiter) do table.insert(result, match) end return result end string.ltrim = function(s, c) local pattern = "^" .. (c or "%s") .. "+" return (string.gsub(s, pattern, "")) end string.rtrim = function(s, c) local pattern = (c or "%s") .. "+" .. "$" return (string.gsub(s, pattern, "")) end string.trim = function(s, c) return string.rtrim(string.ltrim(s, c), c) end local function dump(obj) local getIndent, quoteStr, wrapKey, wrapVal, dumpObj getIndent = function(level) return string.rep("\t", level) end quoteStr = function(str) return '"' .. string.gsub(str, '"', '\\"') .. '"' end wrapKey = function(val) if type(val) == "number" then return "[" .. val .. "]" elseif type(val) == "string" then return "[" .. quoteStr(val) .. "]" else return "[" .. tostring(val) .. "]" end end wrapVal = function(val, level) if type(val) == "table" then return dumpObj(val, level) elseif type(val) == "number" then return val elseif type(val) == "string" then return quoteStr(val) else return tostring(val) end end dumpObj = function(obj, level) if type(obj) ~= "table" then return wrapVal(obj) end level = level + 1 local tokens = {} tokens[#tokens + 1] = "{" for k, v in pairs(obj) do tokens[#tokens + 1] = getIndent(level) .. wrapKey(k) .. " = " .. wrapVal(v, level) .. "," end tokens[#tokens + 1] = getIndent(level - 1) .. "}" return table.concat(tokens, "\n") end return dumpObj(obj, 0) end do local _tostring = tostring tostring = function(v) if type(v) == 'table' then return dump(v) else return _tostring(v) end end end -- math扩展 do local _floor = math.floor math.floor = function(n, p) if p and p ~= 0 then local e = 10 ^ p return _floor(n * e) / e else return _floor(n) end end end math.round = function(n, p) local e = 10 ^ (p or 0) return math.floor(n * e + 0.5) / e end
-- Copyright (c) 2020-2021 hoob3rt -- MIT license, see LICENSE for more details. local lualine_require = require 'lualine_require' local modules = lualine_require.lazy_require { default_config = 'lualine.components.diagnostics.config', sources = 'lualine.components.diagnostics.sources', highlight = 'lualine.highlight', utils = 'lualine.utils.utils', utils_notices = 'lualine.utils.notices', } local M = lualine_require.require('lualine.component'):extend() M.diagnostics_sources = modules.sources.sources M.get_diagnostics = modules.sources.get_diagnostics -- Initializer function M:init(options) -- Run super() M.super.init(self, options) -- Apply default options self.options = vim.tbl_deep_extend('keep', self.options or {}, modules.default_config.options) -- Apply default symbols self.symbols = vim.tbl_extend( 'keep', self.options.symbols or {}, self.options.icons_enabled ~= false and modules.default_config.symbols.icons or modules.default_config.symbols.no_icons ) -- Initialize highlight groups if self.options.colored then self.highlight_groups = { error = modules.highlight.create_component_highlight_group( self.options.diagnostics_color.error, 'diagnostics_error', self.options ), warn = modules.highlight.create_component_highlight_group( self.options.diagnostics_color.warn, 'diagnostics_warn', self.options ), info = modules.highlight.create_component_highlight_group( self.options.diagnostics_color.info, 'diagnostics_info', self.options ), hint = modules.highlight.create_component_highlight_group( self.options.diagnostics_color.hint, 'diagnostics_hint', self.options ), } end -- Error out no source if #self.options.sources < 1 then print 'no sources for diagnostics configured' return '' end -- Initialize variable to store last update so we can use it in insert -- mode for no update_in_insert self.last_update = '' end function M:update_status() if not self.options.update_in_insert and vim.api.nvim_get_mode().mode:sub(1, 1) == 'i' then return self.last_update end local error_count, warning_count, info_count, hint_count = 0, 0, 0, 0 local diagnostic_data = modules.sources.get_diagnostics(self.options.sources) -- sum all the counts for _, data in pairs(diagnostic_data) do error_count = error_count + data.error warning_count = warning_count + data.warn info_count = info_count + data.info hint_count = hint_count + data.hint end local result = {} local data = { error = error_count, warn = warning_count, info = info_count, hint = hint_count, } -- format the counts with symbols and highlights if self.options.colored then local colors = {} for name, hl in pairs(self.highlight_groups) do colors[name] = modules.highlight.component_format_highlight(hl) end for _, section in ipairs(self.options.sections) do if data[section] ~= nil and data[section] > 0 then table.insert(result, colors[section] .. self.symbols[section] .. data[section]) end end else for _, section in ipairs(self.options.sections) do if data[section] ~= nil and data[section] > 0 then table.insert(result, self.symbols[section] .. data[section]) end end end self.last_update = '' if result[1] ~= nil then self.last_update = table.concat(result, ' ') end return self.last_update end return M
require "json" require "nn" require "paths" require "torch" local models = {} local function LoadNNs(hero) local path = "data/" .. hero .. "/nets/" if not paths.dirp(path) then return false end for net in paths.iterfiles(path) do local parts = net:gmatch("[^_]+") local team = tonumber(parts()) local type = parts() if nns[hero] == nil then nns[hero] = {nil, {}, {}} end nns[hero][team][type] = torch.load(path .. net, "ascii") end return true end local function DoQuery(params, response) local hero = params.hero local type = params.type local team = tonumber(params.team) local input = torch.Tensor(json.decode(params.tensor)) if nns[hero] == nil then if not LoadNNs(hero) then response.status(400) response.send("") return end end local net = nns[hero][team][type] ok, result = pcall(net.forward, net, input) if ok then result = json.encode(torch.totable(result)) response.setStatus(200) response.send(result) else response.status(500) response.send(result) print(result) end end local app = require "waffle" app.post("^/query$", function(request, response) if request.ip ~= "127.0.0.1" then response.status(403) response.send("") return end local ok, msg = pcall(DoQuery, request.url.args, response) if not ok then response.status(500) response.send(msg) end end) app.listen { port = 1414 }
local F, C = unpack(select(2, ...)) C.themes["Blizzard_BlackMarketUI"] = function() local r, g, b = C.r, C.g, C.b F.StripTextures(BlackMarketFrame) BlackMarketFrame.MoneyFrameBorder:SetAlpha(0) F.StripTextures(BlackMarketFrame.HotDeal) F.CreateBG(BlackMarketFrame.HotDeal.Item) BlackMarketFrame.HotDeal.Item.IconTexture:SetTexCoord(unpack(C.TexCoord)) local headers = {"ColumnName", "ColumnLevel", "ColumnType", "ColumnDuration", "ColumnHighBidder", "ColumnCurrentBid"} for _, header in pairs(headers) do local header = BlackMarketFrame[header] F.StripTextures(header) local bg = F.CreateBDFrame(header, .25) bg:SetPoint("TOPLEFT", 2, 0) bg:SetPoint("BOTTOMRIGHT", -1, 0) end F.SetBD(BlackMarketFrame) F.CreateBD(BlackMarketFrame.HotDeal, .25) F.Reskin(BlackMarketFrame.BidButton) F.ReskinClose(BlackMarketFrame.CloseButton) F.ReskinInput(BlackMarketBidPriceGold) F.ReskinScroll(BlackMarketScrollFrameScrollBar) hooksecurefunc("BlackMarketScrollFrame_Update", function() local buttons = BlackMarketScrollFrame.buttons for i = 1, #buttons do local bu = buttons[i] bu.Item.IconTexture:SetTexCoord(unpack(C.TexCoord)) if not bu.reskinned then F.StripTextures(bu) bu.Item:SetNormalTexture("") bu.Item:SetPushedTexture("") bu.Item:GetHighlightTexture():SetColorTexture(1, 1, 1, .25) F.CreateBG(bu.Item) bu.Item.IconBorder:SetAlpha(0) local bg = F.CreateBDFrame(bu, .25) bg:SetPoint("TOPLEFT", bu.Item, "TOPRIGHT", 3, C.mult) bg:SetPoint("BOTTOMRIGHT", 0, 4) bu:SetHighlightTexture(C.media.bdTex) local hl = bu:GetHighlightTexture() hl:SetVertexColor(r, g, b, .2) hl.SetAlpha = F.Dummy hl:ClearAllPoints() hl:SetAllPoints(bg) bu.Selection:ClearAllPoints() bu.Selection:SetAllPoints(bg) bu.Selection:SetTexture(C.media.bdTex) bu.Selection:SetVertexColor(r, g, b, .1) bu.reskinned = true end if bu:IsShown() and bu.itemLink then local _, _, quality = GetItemInfo(bu.itemLink) bu.Name:SetTextColor(GetItemQualityColor(quality)) end end end) hooksecurefunc("BlackMarketFrame_UpdateHotItem", function(self) local hotDeal = self.HotDeal if hotDeal:IsShown() and hotDeal.itemLink then local _, _, quality = GetItemInfo(hotDeal.itemLink) hotDeal.Name:SetTextColor(GetItemQualityColor(quality)) end hotDeal.Item.IconBorder:Hide() end) end
-- Generated By protoc-gen-lua Do not Edit local protobuf = require "protobuf" module('BceGuildFire_pb', package.seeall) local BCEGUILDFIRE = protobuf.Descriptor(); local BCEGUILDFIRE_USERID_FIELD = protobuf.FieldDescriptor(); BCEGUILDFIRE_USERID_FIELD.name = "userid" BCEGUILDFIRE_USERID_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.BceGuildFire.userid" BCEGUILDFIRE_USERID_FIELD.number = 1 BCEGUILDFIRE_USERID_FIELD.index = 0 BCEGUILDFIRE_USERID_FIELD.label = 1 BCEGUILDFIRE_USERID_FIELD.has_default_value = false BCEGUILDFIRE_USERID_FIELD.default_value = "" BCEGUILDFIRE_USERID_FIELD.type = 9 BCEGUILDFIRE_USERID_FIELD.cpp_type = 9 BCEGUILDFIRE.name = "BceGuildFire" BCEGUILDFIRE.full_name = ".com.xinqihd.sns.gameserver.proto.BceGuildFire" BCEGUILDFIRE.nested_types = {} BCEGUILDFIRE.enum_types = {} BCEGUILDFIRE.fields = {BCEGUILDFIRE_USERID_FIELD} BCEGUILDFIRE.is_extendable = false BCEGUILDFIRE.extensions = {} BceGuildFire = protobuf.Message(BCEGUILDFIRE) _G.BCEGUILDFIRE_PB_BCEGUILDFIRE = BCEGUILDFIRE
--[[ Copyright (C) 2013-2018 Draios Inc dba Sysdig. This file is part of sysdig. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --]] -- Chisel description description = "This console visualization shows the frequency of system call latencies. The Y axis unit is time. By default, a new line is created twice a second, but that can be changed by specifying a different refresh time argument. The X axis shows a range of latencies. Each latency value has a color that can be black (no calls), green (tens of calls/s), yellow (hundreds of calls/s) or red (Thousands of calls/s). In other words, red areas mean that there are many system calls taking the specified time to return. Use this chisel in conjunction with filters to visualize latencies for certain processes, types of I/O activity, file systems, etc." short_description = "Visualize OS latency in real time." category = "CPU Usage" -- Chisel argument list args = { { name = "refresh_time", description = "Chart refresh time in milliseconds", argtype = "int", optional = true }, } require "common" terminal = require "ansiterminal" terminal.enable_color(true) refresh_time = 500000000 refresh_per_sec = 1000000000 / refresh_time frequencies = {} colpalette = {22, 28, 64, 34, 2, 76, 46, 118, 154, 191, 227, 226, 11, 220, 209, 208, 202, 197, 9, 1} charpalette = {" ", "░", "▒", "░"} -- Argument initialization Callback function on_set_arg(name, val) if name == "refresh_time" then refresh_time = parse_numeric_input(val, name) * 1000000 refresh_per_sec = 1000000000 / refresh_time return true end return false end -- Initialization callback function on_init() is_tty = sysdig.is_tty() if not is_tty then print("This chisel only works on ANSI terminals. Aborting.") return false end tinfo = sysdig.get_terminal_info() w = tinfo.width h = tinfo.height chisel.set_filter("evt.dir=<") flatency = chisel.request_field("evt.latency") terminal.hidecursor() return true end -- Final chisel initialization function on_capture_start() chisel.set_interval_ns(refresh_time) return true end -- Event parsing callback function on_event() local latency = evt.field(flatency) if latency == 0 then return true end local llatency = math.log10(latency) if(llatency > 11) then llatency = 11 end local norm_llatency = math.floor(llatency * w / 11) + 1 if frequencies[norm_llatency] == nil then frequencies[norm_llatency] = 1 else frequencies[norm_llatency] = frequencies[norm_llatency] + 1 end return true end -- Calculate colors and character to be used function mkcol(n) local col = math.log10(n * refresh_per_sec + 1) / math.log10(1.6) if col < 1 then col = 1 elseif col > #colpalette then col = #colpalette end local low_col = math.floor(col) local high_col = math.ceil(col) local delta = col - low_col local ch = charpalette[math.floor(1 + delta * #charpalette)] -- If delta is > 75% we use 25% fill and flip fg and bg to fake a 75% filled block if delta > .75 then return colpalette[high_col], colpalette[low_col], ch else return colpalette[low_col], colpalette[high_col], ch end end -- Periodic timeout callback function on_interval(ts_s, ts_ns, delta) terminal.moveup(1) for x = 1, w do local fr = frequencies[x] local fg, bg, ch if fr == nil or fr == 0 then terminal.setfgcol(0) terminal.setbgcol(0) ch = " " else fg, bg, ch = mkcol(fr) terminal.setfgcol(fg) terminal.setbgcol(bg) end io.write(ch) end io.write(terminal.reset .. "\n") local x = 0 while true do if x >= w then break end local curtime = math.floor(x * 11 / w) local prevtime = math.floor((x - 1) * 11 / w) if curtime ~= prevtime then io.write("|") local tstr = format_time_interval(math.pow(10, curtime)) io.write(tstr) x = x + #tstr + 1 else io.write(" ") x = x + 1 end end io.write("\n") frequencies = {} return true end -- Called by the engine at the end of the capture (Ctrl-C) function on_capture_end(ts_s, ts_ns, delta) if is_tty then -- Include the last sample on_interval(ts_s, ts_ns, 0) -- reset the terminal print(terminal.reset) terminal.showcursor() end return true end
local Plug = vim.fn['plug#'] vim.call('plug#begin', '~/.config/nvim/plugged') ----------------------------------- -- THEMES -- ----------------------------------- Plug 'bluz71/vim-nightfly-guicolors' ----------------------------------- -- SYNTAX HL COMPLETION LINTER -- ----------------------------------- Plug('nvim-treesitter/nvim-treesitter', { ['do'] = ':TSUpdate' }) -- Plug 'sheerun/vim-polyglot' -- COC -- Plug('neoclide/coc.nvim', { branch = 'release' }) -- Plug 'honza/vim-snippets' -- Plug 'morgsmccauley/vim-react-native-snippets' -- ALE -- Plug 'dense-analysis/ale' -- BUILT-IN LSP Plug 'neovim/nvim-lspconfig' Plug 'hrsh7th/cmp-nvim-lsp' Plug 'hrsh7th/cmp-buffer' Plug 'hrsh7th/cmp-path' Plug 'hrsh7th/cmp-cmdline' Plug 'hrsh7th/nvim-cmp' Plug 'hrsh7th/cmp-vsnip' Plug 'hrsh7th/vim-vsnip' Plug 'hrsh7th/cmp-emoji' Plug 'rafamadriz/friendly-snippets' ----------------------------------- -- EXTRAS -- ----------------------------------- Plug('iamcco/markdown-preview.nvim', { ['do'] = 'cd app && yarn install' }) Plug('mg979/vim-visual-multi', { branch = 'master' }) Plug 'tpope/vim-surround' Plug 'tpope/vim-repeat' Plug 'jiangmiao/auto-pairs' Plug 'preservim/nerdcommenter' Plug 'norcalli/nvim-colorizer.lua' Plug 'karb94/neoscroll.nvim' Plug 'tpope/vim-fugitive' Plug 'airblade/vim-gitgutter' Plug('mhinz/vim-startify', { branch = 'center' }) Plug 'nvim-lualine/lualine.nvim' Plug 'romgrk/barbar.nvim' Plug 'christoomey/vim-tmux-navigator' Plug 'ggandor/lightspeed.nvim' Plug 'nvim-lua/plenary.nvim' Plug 'nvim-telescope/telescope.nvim' Plug 'nvim-telescope/telescope-project.nvim' Plug 'kyazdani42/nvim-tree.lua' Plug 'kyazdani42/nvim-web-devicons' vim.call 'plug#end'
forge.clear() carHeight = math.random(10, 20) / 100 carWidth = math.random(100, 125) / 100 wheelArchHeight = math.random(0, 10) / 100 wheelHeight = 0.3 windshieldHeight = math.random(50, 100) / 100 forge.build("Vehicles/body_standard", {0, -carHeight, 0}, {0, 0, 0}, {carWidth, 1, 1}) randomFronts = { "Vehicles/body_frontStandard", "Vehicles/body_frontSports", "Vehicles/body_frontLuxury" } randomFront = randomFronts[math.random(#randomFronts)]; forge.build(randomFront, {0, -carHeight, 1}, {0, 0, 0}, {carWidth, 1, 1}) randomBacks = { "Vehicles/body_backStandard", "Vehicles/body_backFins", "Vehicles/body_backBed" } randomBack = randomBacks[math.random(#randomBacks)]; forge.build(randomBack, {0, -carHeight, -1}, {0, 0, 0}, {carWidth, 1, 1}) randomWindshields = { "Vehicles/body_topStandard", "Vehicles/body_topSteep" } randomWindshield = randomWindshields[math.random(#randomWindshields)]; forge.build(randomWindshield, {0, 1 - carHeight, 0}, {0, 0, 0}, {1, windshieldHeight, 1}) forge.build("Vehicles/body_topBackStandard", {0, 1 - carHeight, -1}, {0, 0, 0}, {1, windshieldHeight, 1}) randomWheels = { "Vehicles/wheel_standard", "Vehicles/wheel_classic" } randomWheel = randomWheels[math.random(#randomWheels)]; forge.build(randomWheel, {-1, wheelHeight, -0.75}, {0, 180, 0}) forge.build(randomWheel, {-1, wheelHeight, 1}, {0, 180, 0}) forge.build(randomWheel, {1, wheelHeight, -0.75}, {0, 0, 0}) forge.build(randomWheel, {1, wheelHeight, 1}, {0, 0, 0}) forge.build("Vehicles/wheel_coverStandard", {-1, wheelHeight + wheelArchHeight, -0.75}, {0, 180, 0}) forge.build("Vehicles/wheel_coverStandard", {-1, wheelHeight + wheelArchHeight, 1}, {0, 180, 0}) forge.build("Vehicles/wheel_coverStandard", {1, wheelHeight + wheelArchHeight, -0.75}, {0, 0, 0}) forge.build("Vehicles/wheel_coverStandard", {1, wheelHeight + wheelArchHeight, 1}, {0, 0, 0}) randomBumpers = { "Vehicles/bumper", "Vehicles/bumper_detailed", "Vehicles/bumper_large" } randomBumper = randomBumpers[math.random(#randomBumpers)]; forge.build(randomBumper, {0, wheelHeight, 1}, {0, 0, 0}) forge.build(randomBumper, {0, wheelHeight, -1}, {0, 180, 0}) if math.random(0, 2) == 0 then forge.build("Vehicles/bumper", {0, wheelHeight, 0}, {0, 90, 0}) forge.build("Vehicles/bumper", {0, wheelHeight, 0}, {0, -90, 0}) end
local E, L, V, P, G = unpack(select(2, ...)); --Import: Engine, Locales, PrivateDB, ProfileDB, GlobalDB local LSM = LibStub('LibSharedMedia-3.0') local Masque = LibStub('Masque', true) --Cache global variables --Lua functions local _G = _G local tonumber, pairs, ipairs, error, unpack, select, tostring = tonumber, pairs, ipairs, error, unpack, select, tostring local assert, type, collectgarbage, pcall, date = assert, type, collectgarbage, pcall, date local twipe, tinsert, tremove, next = table.wipe, tinsert, tremove, next local floor, gsub, match, strjoin = floor, string.gsub, string.match, strjoin local format, find, strrep, len, sub = string.format, string.find, strrep, string.len, string.sub --WoW API / Variables local UnitGUID = UnitGUID local CreateFrame = CreateFrame local C_Timer_After = C_Timer.After local C_PetBattles_IsInBattle = C_PetBattles.IsInBattle local GetCombatRatingBonus = GetCombatRatingBonus local GetCVar, SetCVar, GetCVarBool = GetCVar, SetCVar, GetCVarBool local GetDodgeChance, GetParryChance = GetDodgeChance, GetParryChance local GetFunctionCPUUsage = GetFunctionCPUUsage local GetSpecialization, GetActiveSpecGroup = GetSpecialization, GetActiveSpecGroup local GetSpecializationRole = GetSpecializationRole local InCombatLockdown = InCombatLockdown local IsAddOnLoaded = IsAddOnLoaded local IsInInstance, IsInGuild = IsInInstance, IsInGuild local RequestBattlefieldScoreData = RequestBattlefieldScoreData local C_ChatInfo_SendAddonMessage = C_ChatInfo.SendAddonMessage local C_ChatInfo_GetNumActiveChannels = C_ChatInfo.GetNumActiveChannels local UnitGroupRolesAssigned = UnitGroupRolesAssigned local UnitHasVehicleUI = UnitHasVehicleUI local GetChannelName = GetChannelName local JoinChannelByName = JoinChannelByName local UnitLevel, UnitStat, UnitAttackPower = UnitLevel, UnitStat, UnitAttackPower local UnitFactionGroup = UnitFactionGroup local IsInRaid, IsInGroup = IsInRaid, IsInGroup local GetNumGroupMembers = GetNumGroupMembers local LE_PARTY_CATEGORY_HOME = LE_PARTY_CATEGORY_HOME local LE_PARTY_CATEGORY_INSTANCE = LE_PARTY_CATEGORY_INSTANCE local COMBAT_RATING_RESILIENCE_PLAYER_DAMAGE_TAKEN = COMBAT_RATING_RESILIENCE_PLAYER_DAMAGE_TAKEN local ERR_NOT_IN_COMBAT = ERR_NOT_IN_COMBAT local RAID_CLASS_COLORS = RAID_CLASS_COLORS --Global variables that we don't cache, list them here for the mikk's Find Globals script -- GLOBALS: ElvDB, LibStub, UIParent, DEFAULT_CHAT_FRAME, CUSTOM_CLASS_COLORS, OrderHallCommandBar -- GLOBALS: MAX_PLAYER_LEVEL, CreateChatChannelList, MAX_WOW_CHAT_CHANNELS, CHAT_CONFIG_CHANNEL_LIST -- GLOBALS: LeftChatPanel, RightChatPanel, ElvUIPlayerBuffs, ElvUIPlayerDebuffs, ScriptErrorsFrame --Constants E.LSM = LSM E.noop = function() end E.title = format('|cfffe7b2c%s |r', 'ElvUI') E.myfaction, E.myLocalizedFaction = UnitFactionGroup('player') E.myLocalizedClass, E.myclass, E.myClassID = UnitClass('player') E.myLocalizedRace, E.myrace = UnitRace('player') E.myname = UnitName('player') E.myrealm = GetRealmName() E.myspec = GetSpecialization() E.version = GetAddOnMetadata('ElvUI', 'Version') E.wowpatch, E.wowbuild = GetBuildInfo() E.wowbuild = tonumber(E.wowbuild) E.resolution = ({GetScreenResolutions()})[GetCurrentResolution()] or GetCVar('gxWindowedResolution') --only used for now in our install.lua line 779 E.screenwidth, E.screenheight = GetPhysicalScreenSize() E.isMacClient = IsMacClient() E.NewSign = '|TInterface\\OptionsFrame\\UI-OptionsFrame-NewFeatureIcon:14:14|t' -- not used by ElvUI yet, but plugins like BenikUI and MerathilisUI use it. E.PixelMode = false --Tables E.media = {} E.frames = {} E.unitFrameElements = {} E.statusBars = {} E.texts = {} E.snapBars = {} E.RegisteredModules = {} E.RegisteredInitialModules = {} E.ModuleCallbacks = {['CallPriority'] = {}} E.InitialModuleCallbacks = {['CallPriority'] = {}} E.valueColorUpdateFuncs = {} E.TexCoords = {.08, .92, .08, .92} E.FrameLocks = {} E.VehicleLocks = {} E.CreditsList = {} E.InversePoints = { TOP = 'BOTTOM', BOTTOM = 'TOP', TOPLEFT = 'BOTTOMLEFT', TOPRIGHT = 'BOTTOMRIGHT', LEFT = 'RIGHT', RIGHT = 'LEFT', BOTTOMLEFT = 'TOPLEFT', BOTTOMRIGHT = 'TOPRIGHT', CENTER = 'CENTER' } E.DispelClasses = { ['PRIEST'] = { ['Magic'] = true, ['Disease'] = true }, ['SHAMAN'] = { ['Magic'] = false, ['Curse'] = true }, ['PALADIN'] = { ['Poison'] = true, ['Magic'] = false, ['Disease'] = true }, ['DRUID'] = { ['Magic'] = false, ['Curse'] = true, ['Poison'] = true, ['Disease'] = false, }, ['MONK'] = { ['Magic'] = false, ['Disease'] = true, ['Poison'] = true }, ['MAGE'] = { ['Curse'] = true } } E.HealingClasses = { PALADIN = 1, SHAMAN = 3, DRUID = 4, MONK = 2, PRIEST = {1, 2} } E.ClassRole = { PALADIN = { [1] = 'Caster', [2] = 'Tank', [3] = 'Melee', }, PRIEST = 'Caster', WARLOCK = 'Caster', WARRIOR = { [1] = 'Melee', [2] = 'Melee', [3] = 'Tank', }, HUNTER = 'Melee', SHAMAN = { [1] = 'Caster', [2] = 'Melee', [3] = 'Caster', }, ROGUE = 'Melee', MAGE = 'Caster', DEATHKNIGHT = { [1] = 'Tank', [2] = 'Melee', [3] = 'Melee', }, DRUID = { [1] = 'Caster', [2] = 'Melee', [3] = 'Tank', [4] = 'Caster' }, MONK = { [1] = 'Tank', [2] = 'Caster', [3] = 'Melee', }, DEMONHUNTER = { [1] = 'Melee', [2] = 'Tank' }, } E.DEFAULT_FILTER = {} for filter, tbl in pairs(G.unitframe.aurafilters) do E.DEFAULT_FILTER[filter] = tbl.type end local hexvaluecolor function E:Print(...) hexvaluecolor = self.media.hexvaluecolor or '|cff00b3ff' (_G[self.db.general.messageRedirect] or DEFAULT_CHAT_FRAME):AddMessage(strjoin('', hexvaluecolor, 'ElvUI:|r ', ...)) -- I put DEFAULT_CHAT_FRAME as a fail safe. end --Workaround for people wanting to use white and it reverting to their class color. E.PriestColors = { r = 0.99, g = 0.99, b = 0.99, colorStr = 'fcfcfc' } function E:GetPlayerRole() local assignedRole = UnitGroupRolesAssigned('player') if assignedRole == 'NONE' then local spec = GetSpecialization() return GetSpecializationRole(spec) end return assignedRole end --Basically check if another class border is being used on a class that doesn't match. And then return true if a match is found. function E:CheckClassColor(r, g, b) r, g, b = floor(r*100+.5)/100, floor(g*100+.5)/100, floor(b*100+.5)/100 local matchFound = false for class in pairs(RAID_CLASS_COLORS) do if class ~= E.myclass then local colorTable = class == 'PRIEST' and E.PriestColors or (CUSTOM_CLASS_COLORS and CUSTOM_CLASS_COLORS[class] or RAID_CLASS_COLORS[class]) if colorTable.r == r and colorTable.g == g and colorTable.b == b then matchFound = true end end end return matchFound end function E:SetColorTable(t, data) if not data.r or not data.g or not data.b then error('SetColorTable: Could not unpack color values.') end if t and (type(t) == 'table') then t[1], t[2], t[3], t[4] = E:UpdateColorTable(data) else t = E:GetColorTable(data) end return t end function E:UpdateColorTable(data) if not data.r or not data.g or not data.b then error('UpdateColorTable: Could not unpack color values.') end if (data.r > 1 or data.r < 0) then data.r = 1 end if (data.g > 1 or data.g < 0) then data.g = 1 end if (data.b > 1 or data.b < 0) then data.b = 1 end if data.a and (data.a > 1 or data.a < 0) then data.a = 1 end if data.a then return data.r, data.g, data.b, data.a else return data.r, data.g, data.b end end function E:GetColorTable(data) if not data.r or not data.g or not data.b then error('GetColorTable: Could not unpack color values.') end if (data.r > 1 or data.r < 0) then data.r = 1 end if (data.g > 1 or data.g < 0) then data.g = 1 end if (data.b > 1 or data.b < 0) then data.b = 1 end if data.a and (data.a > 1 or data.a < 0) then data.a = 1 end if data.a then return {data.r, data.g, data.b, data.a} else return {data.r, data.g, data.b} end end function E:UpdateMedia() if not self.db.general or not self.private.general then return end --Prevent rare nil value errors --Fonts self.media.normFont = LSM:Fetch('font', self.db.general.font) self.media.combatFont = LSM:Fetch('font', self.private.general.dmgfont) --Textures self.media.blankTex = LSM:Fetch('background', 'ElvUI Blank') self.media.normTex = LSM:Fetch('statusbar', self.private.general.normTex) self.media.glossTex = LSM:Fetch('statusbar', self.private.general.glossTex) --Border Color local border = E.db.general.bordercolor if self:CheckClassColor(border.r, border.g, border.b) then local classColor = E.myclass == 'PRIEST' and E.PriestColors or (CUSTOM_CLASS_COLORS and CUSTOM_CLASS_COLORS[E.myclass] or RAID_CLASS_COLORS[E.myclass]) E.db.general.bordercolor.r = classColor.r E.db.general.bordercolor.g = classColor.g E.db.general.bordercolor.b = classColor.b end self.media.bordercolor = {border.r, border.g, border.b} --UnitFrame Border Color border = E.db.unitframe.colors.borderColor if self:CheckClassColor(border.r, border.g, border.b) then local classColor = E.myclass == 'PRIEST' and E.PriestColors or (CUSTOM_CLASS_COLORS and CUSTOM_CLASS_COLORS[E.myclass] or RAID_CLASS_COLORS[E.myclass]) E.db.unitframe.colors.borderColor.r = classColor.r E.db.unitframe.colors.borderColor.g = classColor.g E.db.unitframe.colors.borderColor.b = classColor.b end self.media.unitframeBorderColor = {border.r, border.g, border.b} --Backdrop Color self.media.backdropcolor = E:SetColorTable(self.media.backdropcolor, self.db.general.backdropcolor) --Backdrop Fade Color self.media.backdropfadecolor = E:SetColorTable(self.media.backdropfadecolor, self.db.general.backdropfadecolor) --Value Color local value = self.db.general.valuecolor if self:CheckClassColor(value.r, value.g, value.b) then value = E.myclass == 'PRIEST' and E.PriestColors or (CUSTOM_CLASS_COLORS and CUSTOM_CLASS_COLORS[E.myclass] or RAID_CLASS_COLORS[E.myclass]) self.db.general.valuecolor.r = value.r self.db.general.valuecolor.g = value.g self.db.general.valuecolor.b = value.b end self.media.hexvaluecolor = self:RGBToHex(value.r, value.g, value.b) self.media.rgbvaluecolor = {value.r, value.g, value.b} if LeftChatPanel and LeftChatPanel.tex and RightChatPanel and RightChatPanel.tex then LeftChatPanel.tex:SetTexture(E.db.chat.panelBackdropNameLeft) local a = E.db.general.backdropfadecolor.a or 0.5 LeftChatPanel.tex:SetAlpha(a) RightChatPanel.tex:SetTexture(E.db.chat.panelBackdropNameRight) RightChatPanel.tex:SetAlpha(a) end self:ValueFuncCall() self:UpdateBlizzardFonts() end E.LockedCVars = {} E.IgnoredCVars = {} function E:PLAYER_REGEN_ENABLED(_) if self.CVarUpdate then for cvarName, value in pairs(self.LockedCVars) do if (not self.IgnoredCVars[cvarName] and (GetCVar(cvarName) ~= value)) then SetCVar(cvarName, value) end end self.CVarUpdate = nil end end local function CVAR_UPDATE(cvarName, value) if not E.IgnoredCVars[cvarName] and E.LockedCVars[cvarName] and E.LockedCVars[cvarName] ~= value then if InCombatLockdown() then E.CVarUpdate = true return end SetCVar(cvarName, E.LockedCVars[cvarName]) end end hooksecurefunc('SetCVar', CVAR_UPDATE) function E:LockCVar(cvarName, value) if GetCVar(cvarName) ~= value then SetCVar(cvarName, value) end self.LockedCVars[cvarName] = value end function E:IgnoreCVar(cvarName, ignore) ignore = not not ignore --cast to bool, just in case self.IgnoredCVars[cvarName] = ignore end --Update font/texture paths when they are registered by the addon providing them --This helps fix most of the issues with fonts or textures reverting to default because the addon providing them is loading after ElvUI. --We use a wrapper to avoid errors in :UpdateMedia because "self" is passed to the function with a value other than ElvUI. local function LSMCallback() E:UpdateMedia() end LSM.RegisterCallback(E, 'LibSharedMedia_Registered', LSMCallback) local MasqueGroupState = {} local MasqueGroupToTableElement = { ['ActionBars'] = {'actionbar', 'actionbars'}, ['Pet Bar'] = {'actionbar', 'petBar'}, ['Stance Bar'] = {'actionbar', 'stanceBar'}, ['Buffs'] = {'auras', 'buffs'}, ['Debuffs'] = {'auras', 'debuffs'}, } local function MasqueCallback(_, Group, _, _, _, _, Disabled) if not E.private then return end local element = MasqueGroupToTableElement[Group] if element then if Disabled then if E.private[element[1]].masque[element[2]] and MasqueGroupState[Group] == 'enabled' then E.private[element[1]].masque[element[2]] = false E:StaticPopup_Show('CONFIG_RL') end MasqueGroupState[Group] = 'disabled' else MasqueGroupState[Group] = 'enabled' end end end if Masque then Masque:Register('ElvUI', MasqueCallback) end function E:RequestBGInfo() RequestBattlefieldScoreData() end function E:NEUTRAL_FACTION_SELECT_RESULT() local newFaction, newLocalizedFaction = UnitFactionGroup('player') if E.myfaction ~= newFaction then E.myfaction, E.myLocalizedFaction = newFaction, newLocalizedFaction end end function E:PLAYER_ENTERING_WORLD() self:MapInfo_Update() self:CheckRole() if not self.MediaUpdated then self:UpdateMedia() self.MediaUpdated = true end local _, instanceType = IsInInstance() if instanceType == 'pvp' then self.BGTimer = self:ScheduleRepeatingTimer('RequestBGInfo', 5) self:RequestBGInfo() elseif self.BGTimer then self:CancelTimer(self.BGTimer) self.BGTimer = nil end if tonumber(E.version) >= 10.60 and not E.global.userInformedNewChanges1 then E:StaticPopup_Show('ELVUI_INFORM_NEW_CHANGES') E.global.userInformedNewChanges1 = true end end function E:ValueFuncCall() for func in pairs(self.valueColorUpdateFuncs) do func(self.media.hexvaluecolor, unpack(self.media.rgbvaluecolor)) end end function E:UpdateFrameTemplates() for frame in pairs(self.frames) do if frame and frame.template and not frame.ignoreUpdates then if not frame.ignoreFrameTemplates then frame:SetTemplate(frame.template, frame.glossTex) end else self.frames[frame] = nil end end for frame in pairs(self.unitFrameElements) do if frame and frame.template and not frame.ignoreUpdates then if not frame.ignoreFrameTemplates then frame:SetTemplate(frame.template, frame.glossTex) end else self.unitFrameElements[frame] = nil end end end function E:UpdateBorderColors() for frame in pairs(self.frames) do if frame and not frame.ignoreUpdates then if not frame.ignoreBorderColors then if frame.template == 'Default' or frame.template == 'Transparent' or frame.template == nil then frame:SetBackdropBorderColor(unpack(self.media.bordercolor)) end end else self.frames[frame] = nil end end for frame in pairs(self.unitFrameElements) do if frame and not frame.ignoreUpdates then if not frame.ignoreBorderColors then if frame.template == 'Default' or frame.template == 'Transparent' or frame.template == nil then frame:SetBackdropBorderColor(unpack(self.media.unitframeBorderColor)) end end else self.unitFrameElements[frame] = nil end end end function E:UpdateBackdropColors() for frame in pairs(self.frames) do if frame then if not frame.ignoreBackdropColors then if frame.template == 'Default' or frame.template == nil then if frame.backdropTexture then frame.backdropTexture:SetVertexColor(unpack(self.media.backdropcolor)) else frame:SetBackdropColor(unpack(self.media.backdropcolor)) end elseif frame.template == 'Transparent' then frame:SetBackdropColor(unpack(self.media.backdropfadecolor)) end end else self.frames[frame] = nil end end for frame in pairs(self.unitFrameElements) do if frame then if not frame.ignoreBackdropColors then if frame.template == 'Default' or frame.template == nil then if frame.backdropTexture then frame.backdropTexture:SetVertexColor(unpack(self.media.backdropcolor)) else frame:SetBackdropColor(unpack(self.media.backdropcolor)) end elseif frame.template == 'Transparent' then frame:SetBackdropColor(unpack(self.media.backdropfadecolor)) end end else self.unitFrameElements[frame] = nil end end end function E:UpdateFontTemplates() for text in pairs(self.texts) do if text then text:FontTemplate(text.font, text.fontSize, text.fontStyle) else self.texts[text] = nil end end end function E:RegisterStatusBar(statusBar) tinsert(self.statusBars, statusBar) end function E:UpdateStatusBars() for _, statusBar in pairs(self.statusBars) do if statusBar and statusBar:GetObjectType() == 'StatusBar' then statusBar:SetStatusBarTexture(self.media.normTex) elseif statusBar and statusBar:GetObjectType() == 'Texture' then statusBar:SetTexture(self.media.normTex) end end end --This frame everything in ElvUI should be anchored to for Eyefinity support. E.UIParent = CreateFrame('Frame', 'ElvUIParent', UIParent) E.UIParent:SetFrameLevel(UIParent:GetFrameLevel()) E.UIParent:SetPoint('CENTER', UIParent, 'CENTER') E.UIParent:SetSize(UIParent:GetSize()) E.UIParent.origHeight = E.UIParent:GetHeight() E.snapBars[#E.snapBars + 1] = E.UIParent E.HiddenFrame = CreateFrame('Frame') E.HiddenFrame:Hide() function E:CheckTalentTree(tree) local activeSpec = GetActiveSpecGroup() local currentSpec = activeSpec and GetSpecialization(false, false, activeSpec) if currentSpec and type(tree) == 'number' then return tree == currentSpec elseif currentSpec and type(tree) == 'table' then for _, index in pairs(tree) do if index == currentSpec then return true end end end return false end function E:IsDispellableByMe(debuffType) if not self.DispelClasses[self.myclass] then return end if self.DispelClasses[self.myclass][debuffType] then return true end end function E:CheckRole() local talentTree = GetSpecialization() local IsInPvPGear = false local role local resilperc = GetCombatRatingBonus(COMBAT_RATING_RESILIENCE_PLAYER_DAMAGE_TAKEN) if resilperc > GetDodgeChance() and resilperc > GetParryChance() and UnitLevel('player') == MAX_PLAYER_LEVEL then IsInPvPGear = true end self.myspec = talentTree if type(self.ClassRole[self.myclass]) == 'string' then role = self.ClassRole[self.myclass] elseif talentTree then role = self.ClassRole[self.myclass][talentTree] end --Check for PvP gear if role == 'Tank' and IsInPvPGear then role = 'Melee' end if not role then local playerint = select(2, UnitStat('player', 4)) local playeragi = select(2, UnitStat('player', 2)) local base, posBuff, negBuff = UnitAttackPower('player') local playerap = base + posBuff + negBuff if (playerap > playerint) or (playeragi > playerint) then role = 'Melee' else role = 'Caster' end end if self.role ~= role then self.role = role self.callbacks:Fire('RoleChanged') end if self.HealingClasses[self.myclass] ~= nil and self.myclass ~= 'PRIEST' then if self:CheckTalentTree(self.HealingClasses[self.myclass]) then self.DispelClasses[self.myclass].Magic = true else self.DispelClasses[self.myclass].Magic = false end end end function E:IncompatibleAddOn(addon, module) E.PopupDialogs['INCOMPATIBLE_ADDON'].button1 = addon E.PopupDialogs['INCOMPATIBLE_ADDON'].button2 = 'ElvUI '..module E.PopupDialogs['INCOMPATIBLE_ADDON'].addon = addon E.PopupDialogs['INCOMPATIBLE_ADDON'].module = module E:StaticPopup_Show('INCOMPATIBLE_ADDON', addon, module) end function E:CheckIncompatible() if E.global.ignoreIncompatible then return end if IsAddOnLoaded('Prat-3.0') and E.private.chat.enable then E:IncompatibleAddOn('Prat-3.0', 'Chat') end if IsAddOnLoaded('Chatter') and E.private.chat.enable then E:IncompatibleAddOn('Chatter', 'Chat') end if IsAddOnLoaded('TidyPlates') and E.private.nameplates.enable then E:IncompatibleAddOn('TidyPlates', 'NamePlates') end if IsAddOnLoaded('Aloft') and E.private.nameplates.enable then E:IncompatibleAddOn('Aloft', 'NamePlates') end if IsAddOnLoaded('Healers-Have-To-Die') and E.private.nameplates.enable then E:IncompatibleAddOn('Healers-Have-To-Die', 'NamePlates') end end function E:IsFoolsDay() if find(date(), '04/01/') and not E.global.aprilFools then return true else return false end end function E:CopyTable(currentTable, defaultTable) if type(currentTable) ~= 'table' then currentTable = {} end if type(defaultTable) == 'table' then for option, value in pairs(defaultTable) do if type(value) == 'table' then value = self:CopyTable(currentTable[option], value) end currentTable[option] = value end end return currentTable end function E:RemoveEmptySubTables(tbl) if type(tbl) ~= 'table' then E:Print('Bad argument #1 to \'RemoveEmptySubTables\' (table expected)') return end for k, v in pairs(tbl) do if type(v) == 'table' then if next(v) == nil then tbl[k] = nil else self:RemoveEmptySubTables(v) end end end end --Compare 2 tables and remove duplicate key/value pairs --param cleanTable : table you want cleaned --param checkTable : table you want to check against. --return : a copy of cleanTable with duplicate key/value pairs removed function E:RemoveTableDuplicates(cleanTable, checkTable) if type(cleanTable) ~= 'table' then E:Print('Bad argument #1 to \'RemoveTableDuplicates\' (table expected)') return end if type(checkTable) ~= 'table' then E:Print('Bad argument #2 to \'RemoveTableDuplicates\' (table expected)') return end local cleaned = {} for option, value in pairs(cleanTable) do if type(value) == 'table' and checkTable[option] and type(checkTable[option]) == 'table' then cleaned[option] = self:RemoveTableDuplicates(value, checkTable[option]) else -- Add unique data to our clean table if (cleanTable[option] ~= checkTable[option]) then cleaned[option] = value end end end --Clean out empty sub-tables self:RemoveEmptySubTables(cleaned) return cleaned end --Compare 2 tables and remove blacklisted key/value pairs --param cleanTable : table you want cleaned --param blacklistTable : table you want to check against. --return : a copy of cleanTable with blacklisted key/value pairs removed function E:FilterTableFromBlacklist(cleanTable, blacklistTable) if type(cleanTable) ~= 'table' then E:Print('Bad argument #1 to \'FilterTableFromBlacklist\' (table expected)') return end if type(blacklistTable) ~= 'table' then E:Print('Bad argument #2 to \'FilterTableFromBlacklist\' (table expected)') return end local cleaned = {} for option, value in pairs(cleanTable) do if type(value) == 'table' and blacklistTable[option] and type(blacklistTable[option]) == 'table' then cleaned[option] = self:FilterTableFromBlacklist(value, blacklistTable[option]) else -- Filter out blacklisted keys if (blacklistTable[option] ~= true) then cleaned[option] = value end end end --Clean out empty sub-tables self:RemoveEmptySubTables(cleaned) return cleaned end --The code in this function is from WeakAuras, credit goes to Mirrored and the WeakAuras Team function E:TableToLuaString(inTable) if type(inTable) ~= 'table' then E:Print('Invalid argument #1 to E:TableToLuaString (table expected)') return end local ret = '{\n' local function recurse(table, level) for i,v in pairs(table) do ret = ret..strrep(' ', level)..'[' if type(i) == 'string' then ret = ret..'"'..i..'"' else ret = ret..i end ret = ret..'] = ' if type(v) == 'number' then ret = ret..v..',\n' elseif type(v) == 'string' then ret = ret..'"'..v:gsub('\\', '\\\\'):gsub('\n', '\\n'):gsub('"', '\\"'):gsub('\124', '\124\124')..'",\n' elseif type(v) == 'boolean' then if v then ret = ret..'true,\n' else ret = ret..'false,\n' end elseif type(v) == 'table' then ret = ret..'{\n' recurse(v, level + 1) ret = ret..strrep(' ', level)..'},\n' else ret = ret..'"'..tostring(v)..'",\n' end end end if inTable then recurse(inTable, 1) end ret = ret..'}' return ret end local profileFormat = { ['profile'] = 'E.db', ['private'] = 'E.private', ['global'] = 'E.global', ['filters'] = 'E.global', ['styleFilters'] = 'E.global', } local lineStructureTable = {} function E:ProfileTableToPluginFormat(inTable, profileType) local profileText = profileFormat[profileType] if not profileText then return end twipe(lineStructureTable) local returnString = "" local lineStructure = "" local sameLine = false local function buildLineStructure() local str = profileText for _, v in ipairs(lineStructureTable) do if type(v) == 'string' then str = str..'["'..v..'"]' else str = str..'['..v..']' end end return str end local function recurse(tbl) lineStructure = buildLineStructure() for k, v in pairs(tbl) do if not sameLine then returnString = returnString..lineStructure end returnString = returnString..'[' if type(k) == 'string' then returnString = returnString..'"'..k..'"' else returnString = returnString..k end if type(v) == 'table' then tinsert(lineStructureTable, k) sameLine = true returnString = returnString..']' recurse(v) else sameLine = false returnString = returnString..'] = ' if type(v) == 'number' then returnString = returnString..v..'\n' elseif type(v) == 'string' then returnString = returnString..'"'..v:gsub('\\', '\\\\'):gsub('\n', '\\n'):gsub('"', '\\"'):gsub('\124', '\124\124')..'"\n' elseif type(v) == 'boolean' then if v then returnString = returnString..'true\n' else returnString = returnString..'false\n' end else returnString = returnString..'"'..tostring(v)..'"\n' end end end tremove(lineStructureTable) lineStructure = buildLineStructure() end if inTable and profileType then recurse(inTable) end return returnString end --Split string by multi-character delimiter (the strsplit / string.split function provided by WoW doesn't allow multi-character delimiter) function E:SplitString(s, delim) assert(type (delim) == 'string' and len(delim) > 0, 'bad delimiter') local start = 1 local t = {} -- results table -- find each instance of a string followed by the delimiter while true do local pos = find(s, delim, start, true) -- plain find if not pos then break end tinsert(t, sub(s, start, pos - 1)) start = pos + len(delim) end -- while -- insert final one (after last delimiter) tinsert(t, sub(s, start)) return unpack(t) end local SendMessageWaiting -- only allow 1 delay at a time regardless of eventing function E:SendMessage() if IsInRaid() then C_ChatInfo_SendAddonMessage('ELVUI_VERSIONCHK', E.version, (not IsInRaid(LE_PARTY_CATEGORY_HOME) and IsInRaid(LE_PARTY_CATEGORY_INSTANCE)) and 'INSTANCE_CHAT' or 'RAID') elseif IsInGroup() then C_ChatInfo_SendAddonMessage('ELVUI_VERSIONCHK', E.version, (not IsInGroup(LE_PARTY_CATEGORY_HOME) and IsInGroup(LE_PARTY_CATEGORY_INSTANCE)) and 'INSTANCE_CHAT' or 'PARTY') else local ElvUIGVC = GetChannelName('ElvUIGVC') if ElvUIGVC and ElvUIGVC > 0 then C_ChatInfo_SendAddonMessage('ELVUI_VERSIONCHK', E.version, 'CHANNEL', ElvUIGVC) elseif IsInGuild() then C_ChatInfo_SendAddonMessage('ELVUI_VERSIONCHK', E.version, 'GUILD') end end SendMessageWaiting = nil end local SendRecieveGroupSize = 0 local myRealm = gsub(E.myrealm,'[%s%-]','') local myName = E.myname..'-'..myRealm local function SendRecieve(_, event, prefix, message, _, sender) if event == 'CHAT_MSG_ADDON' then if sender == myName then return end if prefix == 'ELVUI_VERSIONCHK' then local msg, ver = tonumber(message), tonumber(E.version) if msg and (msg > ver) then -- you're outdated D: if not E.recievedOutOfDateMessage then E:Print(L['ElvUI is out of date. You can download the newest version from www.tukui.org. Get premium membership and have ElvUI automatically updated with the Tukui Client!']) if msg and ((msg - ver) >= 0.05) then E:StaticPopup_Show('ELVUI_UPDATE_AVAILABLE') end E.recievedOutOfDateMessage = true end elseif msg and (msg < ver) then -- Send Message Back if not SendMessageWaiting then SendMessageWaiting = E:Delay(10, E.SendMessage) end end end elseif event == 'GROUP_ROSTER_UPDATE' then local num = GetNumGroupMembers() if num ~= SendRecieveGroupSize then if num > 1 and num > SendRecieveGroupSize then if not SendMessageWaiting then SendMessageWaiting = E:Delay(10, E.SendMessage) end end SendRecieveGroupSize = num end elseif event == 'PLAYER_ENTERING_WORLD' then if not SendMessageWaiting then SendMessageWaiting = E:Delay(10, E.SendMessage) end end end C_ChatInfo.RegisterAddonMessagePrefix('ELVUI_VERSIONCHK') local f = CreateFrame('Frame') f:RegisterEvent('CHAT_MSG_ADDON') f:RegisterEvent('GROUP_ROSTER_UPDATE') f:RegisterEvent('PLAYER_ENTERING_WORLD') f:SetScript('OnEvent', SendRecieve) f:SetScript('OnUpdate', function(self, elapsed) self.delayed = (self.delayed or 0) + elapsed if self.delayed > 10 then local numActiveChannels = C_ChatInfo_GetNumActiveChannels() if numActiveChannels and (numActiveChannels >= 1) then if (GetChannelName('ElvUIGVC') == 0) and (numActiveChannels < MAX_WOW_CHAT_CHANNELS) then JoinChannelByName('ElvUIGVC', nil, nil, true) if not SendMessageWaiting then SendMessageWaiting = E:Delay(10, E.SendMessage) end self:SetScript('OnUpdate', nil) end end elseif self.delayed > 30 then self:SetScript('OnUpdate', nil) end end) function E:UpdateAll(ignoreInstall) if not self.initialized then C_Timer_After(1, function() E:UpdateAll(ignoreInstall) end) return end E.private = E.charSettings.profile E.db = E.data.profile E.global = E.data.global E.db.theme = nil E.db.install_complete = nil E:DBConversions() local ActionBars = E:GetModule('ActionBars') local AFK = E:GetModule('AFK') local Auras = E:GetModule('Auras') local Bags = E:GetModule('Bags') local Blizzard = E:GetModule('Blizzard') local Chat = E:GetModule('Chat') local DataBars = E:GetModule('DataBars') local DataTexts = E:GetModule('DataTexts') local Layout = E:GetModule('Layout') local Minimap = E:GetModule('Minimap') local NamePlates = E:GetModule('NamePlates') local Threat = E:GetModule('Threat') local Tooltip = E:GetModule('Tooltip') local Totems = E:GetModule('Totems') local UnitFrames = E:GetModule('UnitFrames') ActionBars.db = E.db.actionbar Auras.db = E.db.auras Bags.db = E.db.bags Chat.db = E.db.chat DataBars.db = E.db.databars DataTexts.db = E.db.datatexts NamePlates.db = E.db.nameplates Threat.db = E.db.general.threat Tooltip.db = E.db.tooltip Totems.db = E.db.general.totems UnitFrames.db = E.db.unitframe --The mover is positioned before it is resized, which causes issues for unitframes --Allow movers to be "pushed" outside the screen, when they are resized they should be back in the screen area. --We set movers to be clamped again at the bottom of this function. E:SetMoversClampedToScreen(false) E:SetMoversPositions() E:UpdateMedia() E:UpdateBorderColors() E:UpdateBackdropColors() E:UpdateFrameTemplates() E:UpdateStatusBars() E:UpdateCooldownSettings('all') Layout:ToggleChatPanels() Layout:BottomPanelVisibility() Layout:TopPanelVisibility() Layout:SetDataPanelStyle() ActionBars:Extra_SetAlpha() ActionBars:Extra_SetScale() ActionBars:ToggleDesaturation() ActionBars:UpdateButtonSettings() ActionBars:UpdateMicroPositionDimensions() ActionBars:UpdatePetCooldownSettings() AFK:Toggle() Bags:Layout() Bags:Layout(true) Bags:SizeAndPositionBagBar() Bags:UpdateCountDisplay() Bags:UpdateItemLevelDisplay() Chat:PositionChat(true) Chat:SetupChat() Chat:UpdateAnchors() DataBars:EnableDisable_AzeriteBar() DataBars:EnableDisable_ExperienceBar() DataBars:EnableDisable_HonorBar() DataBars:EnableDisable_ReputationBar() DataBars:UpdateDataBarDimensions() DataTexts:LoadDataTexts() Minimap:UpdateSettings() NamePlates:ConfigureAll() NamePlates:StyleFilterInitializeAllFilters() Threat:ToggleEnable() Threat:UpdatePosition() Totems:PositionAndSize() Totems:ToggleEnable() UnitFrames:Update_AllFrames() if ElvUIPlayerBuffs then Auras:UpdateHeader(ElvUIPlayerBuffs) end if ElvUIPlayerDebuffs then Auras:UpdateHeader(ElvUIPlayerDebuffs) end if E.RefreshGUI then E:RefreshGUI() end if (ignoreInstall ~= true) and (E.private.install_complete == nil or (E.private.install_complete and type(E.private.install_complete) == 'boolean') or (E.private.install_complete and type(tonumber(E.private.install_complete)) == 'number' and tonumber(E.private.install_complete) <= 3.83)) then E:Install() end Blizzard:SetObjectiveFrameHeight() E:SetMoversClampedToScreen(true) -- Go back to using clamp after resizing has taken place. collectgarbage('collect') end function E:RemoveNonPetBattleFrames() if InCombatLockdown() then return end for object in pairs(E.FrameLocks) do local obj = _G[object] or object obj:SetParent(E.HiddenFrame) end self:RegisterEvent('PLAYER_REGEN_DISABLED', 'AddNonPetBattleFrames') end function E:AddNonPetBattleFrames() if InCombatLockdown() then return end for object, data in pairs(E.FrameLocks) do local obj = _G[object] or object local parent, strata if type(data) == 'table' then parent, strata = data.parent, data.strata elseif data == true then parent = UIParent end obj:SetParent(parent) if strata then obj:SetFrameStrata(strata) end end self:UnregisterEvent('PLAYER_REGEN_DISABLED') end function E:RegisterPetBattleHideFrames(object, originalParent, originalStrata) if not object or not originalParent then E:Print('Error. Usage: RegisterPetBattleHideFrames(object, originalParent, originalStrata)') return end object = _G[object] or object --If already doing pokemon if C_PetBattles_IsInBattle() then object:SetParent(E.HiddenFrame) end E.FrameLocks[object] = { ['parent'] = originalParent, ['strata'] = originalStrata or nil, } end function E:UnregisterPetBattleHideFrames(object) if not object then E:Print('Error. Usage: UnregisterPetBattleHideFrames(object)') return end object = _G[object] or object --Check if object was registered to begin with if not E.FrameLocks[object] then return end --Change parent of object back to original parent local originalParent = E.FrameLocks[object].parent if originalParent then object:SetParent(originalParent) end --Change strata of object back to original local originalStrata = E.FrameLocks[object].strata if originalStrata then object:SetFrameStrata(originalStrata) end --Remove object from table E.FrameLocks[object] = nil end function E:EnterVehicleHideFrames(_, unit) if unit ~= 'player' then return end for object in pairs(E.VehicleLocks) do object:SetParent(E.HiddenFrame) end end function E:ExitVehicleShowFrames(_, unit) if unit ~= 'player' then return end for object, originalParent in pairs(E.VehicleLocks) do object:SetParent(originalParent) end end function E:RegisterObjectForVehicleLock(object, originalParent) if not object or not originalParent then E:Print('Error. Usage: RegisterObjectForVehicleLock(object, originalParent)') return end object = _G[object] or object --Entering/Exiting vehicles will often happen in combat. --For this reason we cannot allow protected objects. if object.IsProtected and object:IsProtected() then E:Print('Error. Object is protected and cannot be changed in combat.') return end --Check if we are already in a vehicles if UnitHasVehicleUI('player') then object:SetParent(E.HiddenFrame) end --Add object to table E.VehicleLocks[object] = originalParent end function E:UnregisterObjectForVehicleLock(object) if not object then E:Print('Error. Usage: UnregisterObjectForVehicleLock(object)') return end object = _G[object] or object --Check if object was registered to begin with if not E.VehicleLocks[object] then return end --Change parent of object back to original parent local originalParent = E.VehicleLocks[object] if originalParent then object:SetParent(originalParent) end --Remove object from table E.VehicleLocks[object] = nil end local EventRegister = {} local EventFrame = CreateFrame('Frame') EventFrame:SetScript('OnEvent', function(_, event, ...) if EventRegister[event] then for object, functions in pairs(EventRegister[event]) do for _, func in ipairs(functions) do --Call the functions that are registered with this object, and pass the object and other arguments back func(object, event, ...) end end end end) --- Registers specified event and adds specified func to be called for the specified object. -- Unless all parameters are supplied it will not register. -- If the specified object has already been registered for the specified event -- then it will just add the specified func to a table of functions that should be called. -- When a registered event is triggered, then the registered function is called with -- the object as first parameter, then event, and then all the parameters for the event itself. -- @param event The event you want to register. -- @param object The object you want to register the event for. -- @param func The function you want executed for this object. function E:RegisterEventForObject(event, object, func) if not event or not object or not func then E:Print('Error. Usage: RegisterEventForObject(event, object, func)') return end if not EventRegister[event] then --Check if event has already been registered EventRegister[event] = {} EventFrame:RegisterEvent(event) else if not EventRegister[event][object] then --Check if this object has already been registered EventRegister[event][object] = {func} else tinsert(EventRegister[event][object], func) --Add func that should be called for this object on this event end end end --- Unregisters specified function for the specified object on the specified event. -- Unless all parameters are supplied it will not unregister. -- @param event The event you want to unregister an object from. -- @param object The object you want to unregister a func from. -- @param func The function you want unregistered for the object. function E:UnregisterEventForObject(event, object, func) if not event or not object or not func then E:Print('Error. Usage: UnregisterEventForObject(event, object, func)') return end --Find the specified function for the specified object and remove it from the register if EventRegister[event] and EventRegister[event][object] then for index, registeredFunc in ipairs(EventRegister[event][object]) do if func == registeredFunc then tremove(EventRegister[event][object], index) break end end --If this object no longer has any functions registered then remove it from the register if #EventRegister[event][object] == 0 then EventRegister[event][object] = nil end --If this event no longer has any objects registered then unregister it and remove it from the register if not next(EventRegister[event]) then EventFrame:UnregisterEvent(event) EventRegister[event] = nil end end end function E:ResetAllUI() self:ResetMovers() if E.db.lowresolutionset then E:SetupResolution(true) end if E.db.layoutSet then E:SetupLayout(E.db.layoutSet, true) end end function E:ResetUI(...) if InCombatLockdown() then E:Print(ERR_NOT_IN_COMBAT) return end if ... == '' or ... == ' ' or ... == nil then E:StaticPopup_Show('RESETUI_CHECK') return end self:ResetMovers(...) end function E:RegisterModule(name, loadFunc) if (loadFunc and type(loadFunc) == 'function') then --New method using callbacks if self.initialized then loadFunc() else if self.ModuleCallbacks[name] then --Don't allow a registered module name to be overwritten E:Print('Invalid argument #1 to E:RegisterModule (module name:', name, 'is already registered, please use a unique name)') return end --Add module name to registry self.ModuleCallbacks[name] = true self.ModuleCallbacks.CallPriority[#self.ModuleCallbacks.CallPriority + 1] = name --Register loadFunc to be called when event is fired E:RegisterCallback(name, loadFunc, E:GetModule(name)) end else if self.initialized then self:GetModule(name):Initialize() else self.RegisteredModules[#self.RegisteredModules + 1] = name end end end function E:RegisterInitialModule(name, loadFunc) if (loadFunc and type(loadFunc) == 'function') then --New method using callbacks if self.InitialModuleCallbacks[name] then --Don't allow a registered module name to be overwritten E:Print('Invalid argument #1 to E:RegisterInitialModule (module name:', name, 'is already registered, please use a unique name)') return end --Add module name to registry self.InitialModuleCallbacks[name] = true self.InitialModuleCallbacks.CallPriority[#self.InitialModuleCallbacks.CallPriority + 1] = name --Register loadFunc to be called when event is fired E:RegisterCallback(name, loadFunc, E:GetModule(name)) else self.RegisteredInitialModules[#self.RegisteredInitialModules + 1] = name end end function E:InitializeInitialModules() --Fire callbacks for any module using the new system for index, moduleName in ipairs(self.InitialModuleCallbacks.CallPriority) do self.InitialModuleCallbacks[moduleName] = nil self.InitialModuleCallbacks.CallPriority[index] = nil E.callbacks:Fire(moduleName) end --Old deprecated initialize method, we keep it for any plugins that may need it for _, module in pairs(E.RegisteredInitialModules) do module = self:GetModule(module, true) if module and module.Initialize then local _, catch = pcall(module.Initialize, module) if catch and GetCVarBool('scriptErrors') == true then ScriptErrorsFrame:OnError(catch, false, false) end end end end function E:RefreshModulesDB() local UF = self:GetModule('UnitFrames') twipe(UF.db) UF.db = self.db.unitframe end function E:InitializeModules() --Fire callbacks for any module using the new system for index, moduleName in ipairs(self.ModuleCallbacks.CallPriority) do self.ModuleCallbacks[moduleName] = nil self.ModuleCallbacks.CallPriority[index] = nil E.callbacks:Fire(moduleName) end --Old deprecated initialize method, we keep it for any plugins that may need it for _, module in pairs(E.RegisteredModules) do module = self:GetModule(module) if module.Initialize then local _, catch = pcall(module.Initialize, module) if catch and GetCVarBool('scriptErrors') == true then ScriptErrorsFrame:OnError(catch, false, false) end end end end --DATABASE CONVERSIONS local function auraFilterStrip(name, content, value) if match(name, value) then E.global.unitframe.aurafilters[gsub(name, value, '')] = E:CopyTable({}, content) E.global.unitframe.aurafilters[name] = nil end end function E:DBConversions() --Make sure default filters use the correct filter type for filter, filterType in pairs(E.DEFAULT_FILTER) do E.global.unitframe.aurafilters[filter].type = filterType end --Add missing nameplates table to Minimalistic profile if ElvDB.profiles['Minimalistic'] and not ElvDB.profiles['Minimalistic'].nameplates then ElvDB.profiles['Minimalistic'].nameplates = { ['filters'] = {}, } end --Combat & Resting Icon options update if E.db.unitframe.units.player.combatIcon ~= nil then E.db.unitframe.units.player.CombatIcon.enable = E.db.unitframe.units.player.combatIcon E.db.unitframe.units.player.combatIcon = nil end if E.db.unitframe.units.player.restIcon ~= nil then E.db.unitframe.units.player.RestIcon.enable = E.db.unitframe.units.player.restIcon E.db.unitframe.units.player.restIcon = nil end --Remove commas from aura filters for name, content in pairs(E.global.unitframe.aurafilters) do auraFilterStrip(name, content, ',') auraFilterStrip(name, content, '^Friendly:') auraFilterStrip(name, content, '^Enemy:') end --Convert old "Buffs and Debuffs" font size option to individual options if E.db.auras.fontSize then local fontSize = E.db.auras.fontSize E.db.auras.buffs.countFontSize = fontSize E.db.auras.buffs.durationFontSize = fontSize E.db.auras.debuffs.countFontSize = fontSize E.db.auras.debuffs.durationFontSize = fontSize E.db.auras.fontSize = nil end --Convert old private cooldown setting to profile setting if E.private.cooldown and (E.private.cooldown.enable ~= nil) then E.db.cooldown.enable = E.private.cooldown.enable E.private.cooldown.enable = nil E.private.cooldown = nil end --Convert Nameplate Aura Duration to new Cooldown system if E.db.nameplates.durationFont then E.db.nameplates.cooldown.fonts.font = E.db.nameplates.durationFont E.db.nameplates.cooldown.fonts.fontSize = E.db.nameplates.durationFontSize E.db.nameplates.cooldown.fonts.fontOutline = E.db.nameplates.durationFontOutline E.db.nameplates.durationFont = nil E.db.nameplates.durationFontSize = nil E.db.nameplates.durationFontOutline = nil end if not E.db.chat.panelColorConverted then local color = E.db.general.backdropfadecolor E.db.chat.panelColor = {r = color.r, g = color.g, b = color.b, a = color.a} E.db.chat.panelColorConverted = true end --Vendor Greys option is now in bags table if E.db.general.vendorGrays then E.db.bags.vendorGrays.enable = E.db.general.vendorGrays E.db.general.vendorGrays = nil E.db.general.vendorGraysDetails = nil end --Heal Prediction is now a table instead of a bool local healPredictionUnits = {'player','target','focus','pet','arena','party','raid','raid40','raidpet'} for _, unit in pairs(healPredictionUnits) do if type(E.db.unitframe.units[unit].healPrediction) ~= 'table' then local enabled = E.db.unitframe.units[unit].healPrediction E.db.unitframe.units[unit].healPrediction = {} E.db.unitframe.units[unit].healPrediction.enable = enabled end end end local CPU_USAGE = {} local function CompareCPUDiff(showall, minCalls) local greatestUsage, greatestCalls, greatestName, newName, newFunc local greatestDiff, lastModule, mod, newUsage, calls, differance = 0 for name, oldUsage in pairs(CPU_USAGE) do newName, newFunc = name:match('^([^:]+):(.+)$') if not newFunc then E:Print('CPU_USAGE:', name, newFunc) else if newName ~= lastModule then mod = E:GetModule(newName, true) or E lastModule = newName end newUsage, calls = GetFunctionCPUUsage(mod[newFunc], true) differance = newUsage - oldUsage if showall and (calls > minCalls) then E:Print('Name('..name..') Calls('..calls..') Diff('..(differance > 0 and format('%.3f', differance) or 0)..')') end if (differance > greatestDiff) and calls > minCalls then greatestName, greatestUsage, greatestCalls, greatestDiff = name, newUsage, calls, differance end end end if greatestName then E:Print(greatestName.. ' had the CPU usage difference of: '..(greatestUsage > 0 and format('%.3f', greatestUsage) or 0)..'ms. And has been called '.. greatestCalls..' times.') else E:Print('CPU Usage: No CPU Usage differences found.') end twipe(CPU_USAGE) end function E:GetTopCPUFunc(msg) if not GetCVarBool('scriptProfile') then E:Print('For `/cpuusage` to work, you need to enable script profiling via: `/console scriptProfile 1` then reload. Disable after testing by setting it back to 0.') return end local module, showall, delay, minCalls = msg:match('^(%S+)%s*(%S*)%s*(%S*)%s*(.*)$') local checkCore, mod = (not module or module == '') and 'E' showall = (showall == 'true' and true) or false delay = (delay == 'nil' and nil) or tonumber(delay) or 5 minCalls = (minCalls == 'nil' and nil) or tonumber(minCalls) or 15 twipe(CPU_USAGE) if module == 'all' then for moduName, modu in pairs(self.modules) do for funcName, func in pairs(modu) do if (funcName ~= 'GetModule') and (type(func) == 'function') then CPU_USAGE[moduName..':'..funcName] = GetFunctionCPUUsage(func, true) end end end else if not checkCore then mod = self:GetModule(module, true) if not mod then self:Print(module..' not found, falling back to checking core.') mod, checkCore = self, 'E' end else mod = self end for name, func in pairs(mod) do if (name ~= 'GetModule') and type(func) == 'function' then CPU_USAGE[(checkCore or module)..':'..name] = GetFunctionCPUUsage(func, true) end end end self:Delay(delay, CompareCPUDiff, showall, minCalls) self:Print('Calculating CPU Usage differences (module: '..(checkCore or module)..', showall: '..tostring(showall)..', minCalls: '..tostring(minCalls)..', delay: '..tostring(delay)..')') end local function SetOriginalHeight() if InCombatLockdown() then E:RegisterEvent('PLAYER_REGEN_ENABLED', SetOriginalHeight) return end E:UnregisterEvent('PLAYER_REGEN_ENABLED') E.UIParent:SetHeight(E.UIParent.origHeight) end local function SetModifiedHeight() if InCombatLockdown() then E:RegisterEvent('PLAYER_REGEN_ENABLED', SetModifiedHeight) return end E:UnregisterEvent('PLAYER_REGEN_ENABLED') local height = E.UIParent.origHeight - (OrderHallCommandBar:GetHeight() + E.Border) E.UIParent:SetHeight(height) end --This function handles disabling of OrderHall Bar or resizing of ElvUIParent if needed local function HandleCommandBar() if E.global.general.commandBarSetting == 'DISABLED' then local bar = OrderHallCommandBar bar:UnregisterAllEvents() bar:SetScript('OnShow', bar.Hide) bar:Hide() UIParent:UnregisterEvent('UNIT_AURA')--Only used for OrderHall Bar elseif E.global.general.commandBarSetting == 'ENABLED_RESIZEPARENT' then E.UIParent:SetPoint('BOTTOM', UIParent, 'BOTTOM') OrderHallCommandBar:HookScript('OnShow', SetModifiedHeight) OrderHallCommandBar:HookScript('OnHide', SetOriginalHeight) end end function E:Initialize(loginFrame) twipe(self.db) twipe(self.global) twipe(self.private) self.myguid = UnitGUID('player') self.data = LibStub('AceDB-3.0'):New('ElvDB', self.DF) self.data.RegisterCallback(self, 'OnProfileChanged', 'UpdateAll') self.data.RegisterCallback(self, 'OnProfileCopied', 'UpdateAll') self.data.RegisterCallback(self, 'OnProfileReset', 'OnProfileReset') self.charSettings = LibStub('AceDB-3.0'):New('ElvPrivateDB', self.privateVars) LibStub('LibDualSpec-1.0'):EnhanceDatabase(self.data, 'ElvUI') self.private = self.charSettings.profile self.db = self.data.profile self.global = self.data.global self:CheckIncompatible() self:DBConversions() self:UIScale('PLAYER_LOGIN', loginFrame) if not E.db.general.cropIcon then E.TexCoords = {0, 1, 0, 1} end self:LoadCommands() --Load Commands self:InitializeModules() --Load Modules self:LoadMovers() --Load Movers self:UpdateCooldownSettings('all') self.initialized = true if self.private.install_complete == nil then self:Install() end if not find(date(), '04/01/') then E.global.aprilFools = nil end if self:HelloKittyFixCheck() then self:HelloKittyFix() end self:UpdateMedia() self:UpdateFrameTemplates() self:UpdateBorderColors() self:UpdateBackdropColors() self:UpdateStatusBars() self:RegisterEvent('UI_SCALE_CHANGED', 'UIScale') self:RegisterEvent('PLAYER_ENTERING_WORLD') self:RegisterEvent('NEUTRAL_FACTION_SELECT_RESULT') self:RegisterEvent('PET_BATTLE_CLOSE', 'AddNonPetBattleFrames') self:RegisterEvent('PET_BATTLE_OPENING_START', 'RemoveNonPetBattleFrames') self:RegisterEvent('UNIT_ENTERED_VEHICLE', 'EnterVehicleHideFrames') self:RegisterEvent('UNIT_EXITED_VEHICLE', 'ExitVehicleShowFrames') self:RegisterEvent('PLAYER_SPECIALIZATION_CHANGED', 'CheckRole') self:RegisterEvent('PLAYER_REGEN_ENABLED') if self.db.general.kittys then self:CreateKittys() self:Delay(5, self.Print, self, L['Type /hellokitty to revert to old settings.']) end self:Tutorials() self:GetModule('Minimap'):UpdateSettings() self:RefreshModulesDB() collectgarbage('collect') if self.db.general.loginmessage then E:Print(select(2, E:GetModule('Chat'):FindURL('CHAT_MSG_DUMMY', format(L['LOGIN_MSG'], self.media.hexvaluecolor, self.media.hexvaluecolor, self.version)))..'.') end if OrderHallCommandBar then HandleCommandBar() else local frame = CreateFrame('Frame') frame:RegisterEvent('ADDON_LOADED') frame:SetScript('OnEvent', function(Frame, event, addon) if event == 'ADDON_LOADED' and addon == 'Blizzard_OrderHallUI' then if InCombatLockdown() then Frame:RegisterEvent('PLAYER_REGEN_ENABLED') else HandleCommandBar() end Frame:UnregisterEvent(event) elseif event == 'PLAYER_REGEN_ENABLED' then HandleCommandBar() Frame:UnregisterEvent(event) end end) end end
local BasePlugin = require "kong.plugins.base_plugin" local init_worker = require "kong.plugins.ip_restriction.init_worker" local access = require "kong.plugins.ip_restriction.access" local IpRestrictionHandler = BasePlugin:extend() function IpRestrictionHandler:new() IpRestrictionHandler.super.new(self, "ip_restriction") end function IpRestrictionHandler:init_worker() IpRestrictionHandler.super.init_worker(self) init_worker.execute() end function IpRestrictionHandler:access(conf) IpRestrictionHandler.super.access(self) access.execute(conf) end IpRestrictionHandler.PRIORITY = 990 return IpRestrictionHandler
function pcl_text(txt, options) local _center,_chars,_w,_x,_y,_col,_stroke,_shadow = options and options.center,#txt,#txt*4,(options and options.x) or 0,(options and options.y) or 0,(options and options.col) or 7,(options and options.stk),options and options.shd if _center then _x = (127-_w)/2 end if _stroke then print(txt, _x-1 ,_y, _stroke) print(txt, _x+1 ,_y, _stroke) print(txt, _x ,_y-1, _stroke) print(txt, _x ,_y+1, _stroke) print(txt, _x+1 ,_y+1, _stroke) print(txt, _x-1 ,_y-1, _stroke) print(txt, _x+1 ,_y-1, _stroke) print(txt, _x-1 ,_y+1, _stroke) end if _shadow and not _stroke then print(txt, _x+1, _y+1, _shadow) end print(txt, _x, _y, _col) end
function widget:GetInfo() return { name = "Loop Select", desc = "Selects units inside drawn loop (Hold meta to draw loop)", author = "Niobium", version = "v1.1", date = "Jul 18, 2009", license = "GNU GPL, v2 or later", layer = 0, enabled = true -- loaded by default? } end --------------------------------------------------------------------------- -- Variables --------------------------------------------------------------------------- local fadeRate = 3.0 -- Alpha reduces at fadeRate per second local conLineAlpha = 0.1 -- Alpha of connecting line when drawing loop --------------------------------------------------------------------------- -- Globals --------------------------------------------------------------------------- local dragging = false -- Obvious local sNodes = {} -- Loop nodes local fNodes = {} -- Fading nodes local fAlpha = 0 -- Fade alpha local sx, sy, sz -- Start pos local lx, ly, lz -- Last added pos --------------------------------------------------------------------------- -- Speedups --------------------------------------------------------------------------- local GL_LINE_LOOP = GL.LINE_LOOP local GL_LINE_STRIP = GL.LINE_STRIP local glDepthTest = gl.DepthTest local glColor = gl.Color local glLineWidth = gl.LineWidth local glVertex = gl.Vertex local glBeginEnd = gl.BeginEnd local spGetMouseState = Spring.GetMouseState local spGetActiveCommand = Spring.GetActiveCommand local spGetDefaultCommand = Spring.GetDefaultCommand local spGetModKeyState = Spring.GetModKeyState local spGetSpecState = Spring.GetSpectatingState local spGetMyTeamID = Spring.GetMyTeamID local spGetVisibleUnits = Spring.GetVisibleUnits local spGetUnitPos = Spring.GetUnitPosition local spTraceScreenRay = Spring.TraceScreenRay local spGetSelUnits = Spring.GetSelectedUnits local spSelUnitArray = Spring.SelectUnitArray local tremove = table.remove --------------------------------------------------------------------------- -- Code --------------------------------------------------------------------------- function widget:Initialize() if Spring.IsReplay() or Spring.GetGameFrame() > 0 then widget:PlayerChanged() end end function widget:PlayerChanged(playerID) if Spring.GetSpectatingState() and Spring.GetGameFrame() > 0 then widgetHandler:RemoveWidget(self) end end function widget:GameStart() widget:PlayerChanged() end function widget:Update(dt) if (fAlpha > 0) then fAlpha = fAlpha - fadeRate * dt end if dragging then local mx, my = spGetMouseState() local _, pos = spTraceScreenRay(mx, my, true) if pos then local wx, wy, wz = pos[1], pos[2], pos[3] if ((wx ~= lx) or (wy ~= ly) or (wz ~= lz)) then sNodes[#sNodes + 1] = {wx, wy, wz} lx = wx; ly = wy; lz = wz end end end end local function sVerts(nodes) for i=1, #nodes do local node = nodes[i] glVertex(node[1], node[2], node[3]) end end function widget:DrawWorld() glDepthTest(false) glLineWidth(2.0) if (#sNodes > 1) then glColor(1.0, 1.0, 1.0, 1.0) glBeginEnd(GL_LINE_STRIP, sVerts, sNodes) glColor(1.0, 1.0, 1.0, conLineAlpha) glBeginEnd(GL_LINE_STRIP, sVerts, {{sx, sy, sz}, {lx, ly, lz}}) end if ((fAlpha > 0) and (#fNodes > 1)) then glColor(1.0, 1.0, 1.0, fAlpha) glBeginEnd(GL_LINE_LOOP, sVerts, fNodes) end end function widget:MousePress(mx, my, mButton) -- Only left click if (mButton ~= 1) then return false end -- Only handle if there is no active command local _, actCmdID = spGetActiveCommand() if (actCmdID ~= nil) then return false end -- Only handle if meta is also pressed local _, _, meta, _ = spGetModKeyState() if not meta then return false end -- Start dragging local _, pos = spTraceScreenRay(mx, my, true) if not pos then return false end local wx, wy, wz = pos[1], pos[2], pos[3] sNodes[1] = {wx, wy, wz} sx = wx; sy = wy; sz = wz lx = wx; ly = wy; lz = wz -- Return true, this gives us the next MouseMove/MouseRelease calls. dragging = true return true end function widget:MouseMove(mx, my, mdx, mdy, mButton) local _, pos = spTraceScreenRay(mx, my, true) if not pos then return end local wx, wy, wz = pos[1], pos[2], pos[3] sNodes[#sNodes + 1] = {wx, wy, wz} lx = wx; ly = wy; lz = wz end function widget:MouseRelease(mx, my, mButton) -- Add final node (If different) local _, pos = spTraceScreenRay(mx, my, true) if pos then local wx, wy, wz = pos[1], pos[2], pos[3] if ((wx ~= lx) or (wy ~= ly) or (wz ~= lz)) then sNodes[#sNodes + 1] = {wx, wy, wz} lx = wx; ly = wy; lz = wz end end if (#sNodes < 2) then -- Not enough nodes -- Reset nodes sNodes = {} dragging = false return end -- We need list of {x1, y1, x2, y2, M, C} local sLines = {} -- First point is end-node local s2x, s2y = lx, lz -- Retain consistancy, check if last nodes value would be modifier in last interation -- i.e. if it was horz/vert w.r.t prev node -- If it would be modified then, then we also need to modify it here, -- otherwise we can get a 'break' in the loop local sp = sNodes[#sNodes - 1] local spx, spy = sp[1], sp[3] if (s2x == spx) then s2x = s2x + 0.01 end if (s2y == spy) then s2y = s2y + 0.01 end for i=1, #sNodes do local s1x = s2x local s1y = s2y local s2 = sNodes[i] s2x = s2[1] s2y = s2[3] -- Our code fails with near horizontal/verticle lines -- This happens often due to integer screen coords -- Proper solution: Handle vert/horz cases -- Easiest solution: Add small number to make non-vert/horz -- Note: These changes will propogate due to 's1x = s2x' etc -- So changing values does not bring about inconsistancies or non-connecting lines if (s2y == s1y) then s2y = s2y + 0.01 end if (s2x == s1x) then s2x = s2x + 0.01 end local Ms = (s2y - s1y) / (s2x - s1x) sLines[i] = {s1x, s1y, s2x, s2y, Ms, s1y - Ms * s1x} end -- Now we find the selected units -- We need a list of all units we can see -- Spectators can select all units, players can only select their own local spec = spGetSpecState() local visUnits if spec then visUnits = spGetVisibleUnits() else visUnits = spGetVisibleUnits(spGetMyTeamID()) end -- Units to select will be an array (Maps are OK too) local toSel = {} local toSelCount = 0 -- Loop over each unit for i=1, #visUnits do -- Get screen position for unit local uID = visUnits[i] local ux, _, uz = spGetUnitPos(uID) -- The 'line' we use for this unit goes from (0, 0) to (sx, sy), why? Easy M and no C local Mu = uz / ux -- Cu = 0 -- Check if point is in selection polygon -- Count intercepts local intercepts = 0 for i=1, #sNodes do -- Speed local sLine = sLines[i] -- Get interception point local ix = sLine[6] / (Mu - sLine[5]) local iy = Mu * ix -- Check bounds if ((-ix) * (ix - ux) >= 0) and ((-iy) * (iy - uz) >= 0) and ((sLine[1] - ix) * (ix - sLine[3]) >= 0) and ((sLine[2] - iy) * (iy - sLine[4]) >= 0) then intercepts = intercepts + 1 end end -- Even = outside, Odd = inside. if ((intercepts % 2) == 1) then toSelCount = toSelCount + 1 toSel[toSelCount] = uID end end -- Select the units -- Different things happen depending on mod keys local _, ctrl, _, shift = spGetModKeyState() if ctrl then -- ctrl 'inverts' when selecting -- For units that we are going to select, if they are already selected, they become unselected local selUnits = spGetSelUnits() -- Loop over selected units for i=1, #selUnits do local uID = selUnits[i] local match = false -- Check this unit against poly units for j=1, toSelCount do if (toSel[j] == uID) then match = j break end end if match then -- Selected unit is also in poly -- So we shouldn't select it -- Remove from toSel tremove(toSel, match) else toSelCount = toSelCount + 1 toSel[toSelCount] = uID end end else if shift then -- Easy, add units we already have selected, unless they are in poly -- We probably don't want to have duplicates in what we select local selUnits = spGetSelUnits() for i=1, #selUnits do local uID = selUnits[i] local inPoly = false -- Check this unit against poly units for j=1, toSelCount do if (toSel[j] == uID) then inPoly = true break end end -- Add if wasn't found if not inPoly then toSelCount = toSelCount + 1 toSel[toSelCount] = uID end end end end -- Modifiers handled, select units spSelUnitArray(toSel) -- Reset nodes fNodes = sNodes fAlpha = 1.0 sNodes = {} dragging = false end ---------------------------------------------------------------------------
if not modules then modules = { } end modules ['font-syn'] = { version = 1.001, comment = "companion to font-ini.mkiv", author = "Hans Hagen, PRAGMA-ADE, Hasselt NL", copyright = "PRAGMA ADE / ConTeXt Development Team", license = "see context related readme files" } -- todo: subs in lookups requests -- todo: see if the (experimental) lua reader (on my machine) be used (it's a bit slower so maybe wait till lua 5.3) -- identifying ttf/otf/ttc/afm : 2200 fonts: -- -- old ff loader: 140 sec -- new lua loader: 5 sec -- maybe find(...,strictname,1,true) local next, tonumber, type, tostring = next, tonumber, type, tostring local sub, gsub, match, find, lower, upper = string.sub, string.gsub, string.match, string.find, string.lower, string.upper local concat, sort, fastcopy, tohash = table.concat, table.sort, table.fastcopy, table.tohash local serialize, sortedhash = table.serialize, table.sortedhash local lpegmatch = lpeg.match local unpack = unpack or table.unpack local formatters, topattern = string.formatters, string.topattern local round = math.round local P, R, S, C, Cc, Ct, Cs = lpeg.P, lpeg.R, lpeg.S, lpeg.C, lpeg.Cc, lpeg.Ct, lpeg.Cs local lpegmatch, lpegpatterns = lpeg.match, lpeg.patterns local allocate = utilities.storage.allocate local sparse = utilities.storage.sparse local setmetatableindex = table.setmetatableindex local removesuffix = file.removesuffix local splitbase = file.splitbase local splitname = file.splitname local basename = file.basename local nameonly = file.nameonly local pathpart = file.pathpart local suffixonly = file.suffix local filejoin = file.join local is_qualified_path = file.is_qualified_path local exists = io.exists local findfile = resolvers.findfile local cleanpath = resolvers.cleanpath local resolveprefix = resolvers.resolve ----- fontloader = fontloader -- still needed for pfb (now) ----- get_font_info = fontloader.info local settings_to_hash = utilities.parsers.settings_to_hash_tolerant local trace_names = false trackers.register("fonts.names", function(v) trace_names = v end) local trace_warnings = false trackers.register("fonts.warnings", function(v) trace_warnings = v end) local trace_specifications = false trackers.register("fonts.specifications", function(v) trace_specifications = v end) local trace_rejections = false trackers.register("fonts.rejections", function(v) trace_rejections = v end) local report_names = logs.reporter("fonts","names") --[[ldx-- <p>This module implements a name to filename resolver. Names are resolved using a table that has keys filtered from the font related files.</p> --ldx]]-- fonts = fonts or { } -- also used elsewhere local names = fonts.names or allocate { } fonts.names = names local filters = names.filters or { } names.filters = filters local treatments = fonts.treatments or { } fonts.treatments = treatments names.data = names.data or allocate { } names.version = 1.131 names.basename = "names" names.saved = false names.loaded = false names.be_clever = true names.enabled = true names.cache = containers.define("fonts","data",names.version,true) local usesystemfonts = true local autoreload = true directives.register("fonts.autoreload", function(v) autoreload = toboolean(v) end) directives.register("fonts.usesystemfonts", function(v) usesystemfonts = toboolean(v) end) --[[ldx-- <p>A few helpers.</p> --ldx]]-- -- -- what to do with these -- -- -- -- thin -> thin -- -- regu -> regular -> normal -- norm -> normal -> normal -- stan -> standard -> normal -- medi -> medium -- ultr -> ultra -- ligh -> light -- heav -> heavy -- blac -> black -- thin -- book -- verylight -- -- buch -> book -- buchschrift -> book -- halb -> demi -- halbfett -> demi -- mitt -> medium -- mittel -> medium -- fett -> bold -- mage -> light -- mager -> light -- nord -> normal -- gras -> normal local weights = Cs ( -- not extra P("demibold") + P("semibold") + P("mediumbold") + P("ultrabold") + P("extrabold") + P("ultralight") + P("extralight") + P("bold") + P("demi") -- / "semibold" + P("semi") -- / "semibold" + P("light") + P("medium") + P("heavy") + P("ultra") + P("black") --+ P("bol") / "bold" -- blocks + P("bol") + P("regular") / "normal" ) -- local weights = { -- [100] = "thin", -- [200] = "extralight", -- [300] = "light", -- [400] = "normal", -- [500] = "medium", -- [600] = "semibold", -- demi demibold -- [700] = "bold", -- [800] = "extrabold", -- [900] = "black", -- } local normalized_weights = sparse { regular = "normal", } local styles = Cs ( P("reverseoblique") / "reverseitalic" + P("regular") / "normal" + P("italic") + P("oblique") / "italic" + P("slanted") + P("roman") / "normal" + P("ital") / "italic" -- might be tricky + P("ita") / "italic" -- might be tricky --+ P("obli") / "oblique" ) local normalized_styles = sparse { reverseoblique = "reverseitalic", regular = "normal", oblique = "italic", } local widths = Cs( P("condensed") + P("thin") + P("expanded") + P("cond") / "condensed" --+ P("expa") / "expanded" + P("normal") + P("book") / "normal" ) local normalized_widths = sparse() local variants = Cs( -- fax casual P("smallcaps") + P("oldstyle") + P("caps") / "smallcaps" ) local normalized_variants = sparse() names.knownweights = { "black", "bold", "demi", "demibold", "extrabold", "heavy", "light", "medium", "mediumbold", "normal", "regular", "semi", "semibold", "ultra", "ultrabold", "ultralight", } names.knownstyles = { "italic", "normal", "oblique", "regular", "reverseitalic", "reverseoblique", "roman", "slanted", } names.knownwidths = { "book", "condensed", "expanded", "normal", "thin", } names.knownvariants = { "normal", "oldstyle", "smallcaps", } local remappedweights = { [""] = "normal", ["bol"] = "bold", } local remappedstyles = { [""] = "normal", } local remappedwidths = { [""] = "normal", } local remappedvariants = { [""] = "normal", } names.remappedweights = remappedweights setmetatableindex(remappedweights ,"self") names.remappedstyles = remappedstyles setmetatableindex(remappedstyles ,"self") names.remappedwidths = remappedwidths setmetatableindex(remappedwidths ,"self") names.remappedvariants = remappedvariants setmetatableindex(remappedvariants,"self") local any = P(1) local analyzed_table local analyzer = Cs ( ( weights / function(s) analyzed_table[1] = s return "" end + styles / function(s) analyzed_table[2] = s return "" end + widths / function(s) analyzed_table[3] = s return "" end + variants / function(s) analyzed_table[4] = s return "" end + any )^0 ) local splitter = lpeg.splitat("-") function names.splitspec(askedname) local name, weight, style, width, variant = lpegmatch(splitter,askedname) weight = weight and lpegmatch(weights, weight) or weight style = style and lpegmatch(styles, style) or style width = width and lpegmatch(widths, width) or width variant = variant and lpegmatch(variants,variant) or variant if trace_names then report_names("requested name %a split in name %a, weight %a, style %a, width %a and variant %a", askedname,name,weight,style,width,variant) end if not weight or not weight or not width or not variant then weight, style, width, variant = weight or "normal", style or "normal", width or "normal", variant or "normal" if trace_names then report_names("request %a normalized to '%s-%s-%s-%s-%s'", askedname,name,weight,style,width,variant) end end return name or askedname, weight, style, width, variant end local function analyzespec(somename) if somename then analyzed_table = { } local name = lpegmatch(analyzer,somename) return name, analyzed_table[1], analyzed_table[2], analyzed_table[3], analyzed_table[4] end end --[[ldx-- <p>It would make sense to implement the filters in the related modules, but to keep the overview, we define them here.</p> --ldx]]-- filters.afm = fonts.handlers.afm.readers.getinfo filters.otf = fonts.handlers.otf.readers.getinfo filters.ttf = filters.otf filters.ttc = filters.otf -------.ttx = filters.otf -- local function normalize(t) -- only for afm parsing -- local boundingbox = t.boundingbox or t.fontbbox -- if boundingbox then -- for i=1,#boundingbox do -- boundingbox[i] = tonumber(boundingbox[i]) -- end -- else -- boundingbox = { 0, 0, 0, 0 } -- end -- return { -- copyright = t.copyright, -- fontname = t.fontname, -- fullname = t.fullname, -- familyname = t.familyname, -- weight = t.weight, -- widtht = t.width, -- italicangle = tonumber(t.italicangle) or 0, -- monospaced = t.monospaced or toboolean(t.isfixedpitch) or false, -- boundingbox = boundingbox, -- version = t.version, -- not used -- capheight = tonumber(t.capheight), -- xheight = tonumber(t.xheight), -- ascender = tonumber(t.ascender), -- descender = tonumber(t.descender), -- } -- end -- -- function filters.afm(name) -- -- we could parse the afm file as well, and then report an error but -- -- it's not worth the trouble -- local pfbname = findfile(removesuffix(name)..".pfb","pfb") or "" -- if pfbname == "" then -- pfbname = findfile(nameonly(name)..".pfb","pfb") or "" -- end -- if pfbname ~= "" then -- local f = io.open(name) -- if f then -- local hash = { } -- local okay = false -- for line in f:lines() do -- slow but only a few lines at the beginning -- if find(line,"StartCharMetrics",1,true) then -- break -- else -- local key, value = match(line,"^(.+)%s+(.+)%s*$") -- if key and #key > 0 then -- hash[lower(key)] = value -- end -- end -- end -- f:close() -- return normalize(hash) -- end -- end -- return nil, "no matching pfb file" -- end -- local p_spaces = lpegpatterns.whitespace -- local p_number = (R("09")+S(".-+"))^1 / tonumber -- local p_boolean = P("false") * Cc(false) -- + P("false") * Cc(false) -- local p_string = P("(") * C((lpegpatterns.nestedparents + 1 - P(")"))^1) * P(")") -- local p_array = P("[") * Ct((p_number + p_boolean + p_string + p_spaces^1)^1) * P("]") -- + P("{") * Ct((p_number + p_boolean + p_string + p_spaces^1)^1) * P("}") -- -- local p_key = P("/") * C(R("AZ","az")^1) -- local p_value = p_string -- + p_number -- + p_boolean -- + p_array -- -- local p_entry = p_key * p_spaces^0 * p_value -- -- function filters.pfb(name) -- local f = io.open(name) -- if f then -- local hash = { } -- local okay = false -- for line in f:lines() do -- slow but only a few lines at the beginning -- if find(line,"dict begin",1,true) then -- okay = true -- elseif not okay then -- -- go on -- elseif find(line,"currentdict end",1,true) then -- break -- else -- local key, value = lpegmatch(p_entry,line) -- if key and value then -- hash[lower(key)] = value -- end -- end -- end -- f:close() -- return normalize(hash) -- end -- end --[[ldx-- <p>The scanner loops over the filters using the information stored in the file databases. Watch how we check not only for the names, but also for combination with the weight of a font.</p> --ldx]]-- filters.list = { "otf", "ttf", "ttc", "afm", -- no longer dfont support (for now) } -- to be considered: loop over paths per list entry (so first all otf ttf etc) names.fontconfigfile = "fonts.conf" -- a bit weird format, bonus feature names.osfontdirvariable = "OSFONTDIR" -- the official way, in minimals etc names.extrafontsvariable = "EXTRAFONTS" -- the official way, in minimals etc names.runtimefontsvariable = "RUNTIMEFONTS" -- the official way, in minimals etc filters.paths = { } filters.names = { } function names.getpaths(trace) local hash, result, r = { }, { }, 0 local function collect(t,where) for i=1,#t do local v = cleanpath(t[i]) v = gsub(v,"/+$","") -- not needed any more local key = lower(v) report_names("variable %a specifies path %a",where,v) if not hash[key] then r = r + 1 result[r] = v hash[key] = true end end end local path = names.osfontdirvariable or "" if path ~= "" then collect(resolvers.expandedpathlist(path),path) end local path = names.extrafontsvariable or "" if path ~= "" then collect(resolvers.expandedpathlist(path),path) end if xml then local confname = resolvers.expansion("FONTCONFIG_FILE") or "" if confname == "" then confname = names.fontconfigfile or "" end if confname ~= "" then -- first look in the tex tree local name = findfile(confname,"fontconfig files") or "" if name == "" then -- after all, fontconfig is a unix thing name = filejoin("/etc",confname) if not lfs.isfile(name) then name = "" -- force quit end end if name ~= "" and lfs.isfile(name) then if trace_names then report_names("%s fontconfig file %a","loading",name) end local xmldata = xml.load(name) -- begin of untested mess xml.include(xmldata,"include","",true,function(incname) if not is_qualified_path(incname) then local path = pathpart(name) -- main name if path ~= "" then incname = filejoin(path,incname) end end if lfs.isfile(incname) then if trace_names then report_names("%s fontconfig file %a","merging included",incname) end return io.loaddata(incname) elseif trace_names then report_names("%s fontconfig file: %a","ignoring included",incname) end end) -- end of untested mess local fontdirs = xml.collect_texts(xmldata,"dir",true) if trace_names then report_names("%s dirs found in fontconfig",#fontdirs) end collect(fontdirs,"fontconfig file") end end end sort(result) function names.getpaths() return result end return result end local function cleanname(name) return (gsub(lower(name),"[^%a%d]","")) end local function cleanfilename(fullname,defaultsuffix) local path, name, suffix = splitname(fullname) name = gsub(lower(name),"[^%a%d]","") if suffix and suffix ~= "" then return name .. ".".. suffix elseif defaultsuffix and defaultsuffix ~= "" then return name .. ".".. defaultsuffix else return name end end local sorter = function(a,b) return a > b -- longest first end -- local sorter = nil names.cleanname = cleanname names.cleanfilename = cleanfilename -- local function check_names(result) -- local names = result.names -- if names then -- for i=1,#names do -- local name = names[i] -- if name.lang == "English (US)" then -- return name.names -- end -- end -- end -- return result -- end local function check_name(data,result,filename,modification,suffix,subfont) -- shortcuts local specifications = data.specifications -- fetch local fullname = result.fullname local fontname = result.fontname local family = result.family local subfamily = result.subfamily local familyname = result.familyname local subfamilyname = result.subfamilyname -- local compatiblename = result.compatiblename -- local cfffullname = result.cfffullname local weight = result.weight local width = result.width local italicangle = tonumber(result.italicangle) local subfont = subfont local rawname = fullname or fontname or familyname local filebase = removesuffix(basename(filename)) local cleanfilename = cleanname(filebase) -- for WS -- normalize fullname = fullname and cleanname(fullname) fontname = fontname and cleanname(fontname) family = family and cleanname(family) subfamily = subfamily and cleanname(subfamily) familyname = familyname and cleanname(familyname) subfamilyname = subfamilyname and cleanname(subfamilyname) -- compatiblename = compatiblename and cleanname(compatiblename) -- cfffullname = cfffullname and cleanname(cfffullname) weight = weight and cleanname(weight) width = width and cleanname(width) italicangle = italicangle == 0 and nil -- analyze local a_name, a_weight, a_style, a_width, a_variant = analyzespec(fullname or fontname or familyname) -- check local width = width or a_width local variant = a_variant local style = subfamilyname or subfamily -- can re really trust subfamilyname? if style then style = gsub(style,"[^%a]","") elseif italicangle then style = "italic" end if not variant or variant == "" then variant = "normal" end if not weight or weight == "" then weight = a_weight end if not style or style == "" then style = a_style end if not familyname then familyname = a_name end fontname = fontname or fullname or familyname or filebase -- maybe cleanfilename fullname = fullname or fontname familyname = familyname or fontname -- we do these sparse -- todo: check table type or change names in ff loader local units = result.units or 1000 -- can be zero too local designsize = result.designsize or 0 local minsize = result.minsize or 0 local maxsize = result.maxsize or 0 local angle = result.italicangle or 0 local pfmwidth = result.pfmwidth or 0 local pfmweight = result.pfmweight or 0 -- local instancenames = result.instancenames -- specifications[#specifications+1] = { filename = filename, -- unresolved cleanfilename = cleanfilename, -- subfontindex = subfont, format = lower(suffix), subfont = subfont, rawname = rawname, fullname = fullname, fontname = fontname, family = family, subfamily = subfamily, familyname = familyname, subfamilyname = subfamilyname, -- compatiblename = compatiblename, -- nor used / needed -- cfffullname = cfffullname, weight = weight, style = style, width = width, variant = variant, units = units ~= 1000 and units or nil, pfmwidth = pfmwidth ~= 0 and pfmwidth or nil, pfmweight = pfmweight ~= 0 and pfmweight or nil, angle = angle ~= 0 and angle or nil, minsize = minsize ~= 0 and minsize or nil, maxsize = maxsize ~= 0 and maxsize or nil, designsize = designsize ~= 0 and designsize or nil, modification = modification ~= 0 and modification or nil, instancenames = instancenames or nil, } end local function cleanupkeywords() local data = names.data local specifications = names.data.specifications if specifications then local weights = { } local styles = { } local widths = { } local variants = { } for i=1,#specifications do local s = specifications[i] -- fix (sofar styles are taken from the name, and widths from the specification) local _, b_weight, b_style, b_width, b_variant = analyzespec(s.weight) local _, c_weight, c_style, c_width, c_variant = analyzespec(s.style) local _, d_weight, d_style, d_width, d_variant = analyzespec(s.width) local _, e_weight, e_style, e_width, e_variant = analyzespec(s.variant) local _, f_weight, f_style, f_width, f_variant = analyzespec(s.fullname or "") local weight = b_weight or c_weight or d_weight or e_weight or f_weight or "normal" local style = b_style or c_style or d_style or e_style or f_style or "normal" local width = b_width or c_width or d_width or e_width or f_width or "normal" local variant = b_variant or c_variant or d_variant or e_variant or f_variant or "normal" weight = remappedweights [weight or ""] style = remappedstyles [style or ""] width = remappedwidths [width or ""] variant = remappedvariants[variant or ""] weights [weight ] = (weights [weight ] or 0) + 1 styles [style ] = (styles [style ] or 0) + 1 widths [width ] = (widths [width ] or 0) + 1 variants[variant] = (variants[variant] or 0) + 1 if weight ~= s.weight then s.fontweight = s.weight end s.weight, s.style, s.width, s.variant = weight, style, width, variant end local statistics = data.statistics statistics.used_weights = weights statistics.used_styles = styles statistics.used_widths = widths statistics.used_variants = variants end end local function collectstatistics(runtime) local data = names.data local specifications = data.specifications local statistics = data.statistics if specifications then local f_w = formatters["%i"] local f_a = formatters["%0.2f"] -- normal stuff local weights = { } local styles = { } local widths = { } local variants = { } -- weird stuff local angles = { } -- extra stuff local pfmweights = { } setmetatableindex(pfmweights,"table") local pfmwidths = { } setmetatableindex(pfmwidths, "table") -- main loop for i=1,#specifications do local s = specifications[i] -- normal stuff local weight = s.weight local style = s.style local width = s.width local variant = s.variant if weight then weights [weight ] = (weights [weight ] or 0) + 1 end if style then styles [style ] = (styles [style ] or 0) + 1 end if width then widths [width ] = (widths [width ] or 0) + 1 end if variant then variants[variant] = (variants[variant] or 0) + 1 end -- weird stuff local angle = f_a(tonumber(s.angle) or 0) angles[angle] = (angles[angles] or 0) + 1 -- extra stuff local pfmweight = f_w(s.pfmweight or 0) local pfmwidth = f_w(s.pfmwidth or 0) local tweights = pfmweights[pfmweight] local twidths = pfmwidths [pfmwidth] tweights[pfmweight] = (tweights[pfmweight] or 0) + 1 twidths[pfmwidth] = (twidths [pfmwidth] or 0) + 1 end -- statistics.weights = weights statistics.styles = styles statistics.widths = widths statistics.variants = variants statistics.angles = angles statistics.pfmweights = pfmweights statistics.pfmwidths = pfmwidths statistics.fonts = #specifications -- setmetatableindex(pfmweights,nil) setmetatableindex(pfmwidths, nil) -- report_names("") report_names("statistics: ") report_names("") report_names("weights") report_names("") report_names(formatters[" %T"](weights)) report_names("") report_names("styles") report_names("") report_names(formatters[" %T"](styles)) report_names("") report_names("widths") report_names("") report_names(formatters[" %T"](widths)) report_names("") report_names("variants") report_names("") report_names(formatters[" %T"](variants)) report_names("") report_names("angles") report_names("") report_names(formatters[" %T"](angles)) report_names("") report_names("pfmweights") report_names("") for k, v in sortedhash(pfmweights) do report_names(formatters[" %-10s: %T"](k,v)) end report_names("") report_names("pfmwidths") report_names("") for k, v in sortedhash(pfmwidths) do report_names(formatters[" %-10s: %T"](k,v)) end report_names("") report_names("registered fonts : %i", statistics.fonts) report_names("read files : %i", statistics.readfiles) report_names("skipped files : %i", statistics.skippedfiles) report_names("duplicate files : %i", statistics.duplicatefiles) if runtime then report_names("total scan time : %0.3f seconds",runtime) end end end local function collecthashes() local data = names.data local mappings = data.mappings local fallbacks = data.fallbacks local specifications = data.specifications local nofmappings = 0 local noffallbacks = 0 if specifications then -- maybe multiple passes (for the compatible and cffnames so that they have less preference) local conflicts = setmetatableindex("table") for index=1,#specifications do local specification = specifications[index] local format = specification.format local fullname = specification.fullname local fontname = specification.fontname -- local rawname = specification.rawname -- local compatiblename = specification.compatiblename -- local cfffullname = specification.cfffullname local familyname = specification.familyname or specification.family local subfamilyname = specification.subfamilyname local subfamily = specification.subfamily local weight = specification.weight local mapping = mappings[format] local fallback = fallbacks[format] local instancenames = specification.instancenames if fullname and not mapping[fullname] then mapping[fullname] = index nofmappings = nofmappings + 1 end if fontname and not mapping[fontname] then mapping[fontname] = index nofmappings = nofmappings + 1 end if instancenames then for i=1,#instancenames do local instance = fullname .. instancenames[i] mapping[instance] = index nofmappings = nofmappings + 1 end end -- if compatiblename and not mapping[compatiblename] then -- mapping[compatiblename] = index -- nofmappings = nofmappings + 1 -- end -- if cfffullname and not mapping[cfffullname] then -- mapping[cfffullname] = index -- nofmappings = nofmappings + 1 -- end if familyname then if weight and weight ~= sub(familyname,#familyname-#weight+1,#familyname) then local madename = familyname .. weight if not mapping[madename] and not fallback[madename] then fallback[madename] = index noffallbacks = noffallbacks + 1 end end if subfamily and subfamily ~= sub(familyname,#familyname-#subfamily+1,#familyname) then local extraname = familyname .. subfamily if not mapping[extraname] and not fallback[extraname] then fallback[extraname] = index noffallbacks = noffallbacks + 1 end end if subfamilyname and subfamilyname ~= sub(familyname,#familyname-#subfamilyname+1,#familyname) then local extraname = familyname .. subfamilyname if not mapping[extraname] and not fallback[extraname] then fallback[extraname] = index noffallbacks = noffallbacks + 1 end end -- dangerous ... first match takes slot if not mapping[familyname] and not fallback[familyname] then fallback[familyname] = index noffallbacks = noffallbacks + 1 end local conflict = conflicts[format] conflict[familyname] = (conflict[familyname] or 0) + 1 end end for format, conflict in next, conflicts do local fallback = fallbacks[format] for familyname, n in next, conflict do if n > 1 then fallback[familyname] = nil noffallbacks = noffallbacks - n end end end end return nofmappings, noffallbacks end local function collectfamilies() local data = names.data local specifications = data.specifications local families = data.families for index=1,#specifications do local familyname = specifications[index].familyname local family = families[familyname] if not family then families[familyname] = { index } else family[#family+1] = index end end end local function checkduplicate(where) -- fails on "Romantik" but that's a border case anyway local data = names.data local mapping = data[where] local specifications = data.specifications local loaded = { } if specifications and mapping then -- was: for _, m in sortedhash(mapping) do local order = filters.list for i=1,#order do local m = mapping[order[i]] for k, v in sortedhash(m) do local s = specifications[v] local hash = formatters["%s-%s-%s-%s-%s"](s.familyname,s.weight or "*",s.style or "*",s.width or "*",s.variant or "*") local h = loaded[hash] if h then local ok = true local fn = s.filename for i=1,#h do if h[i] == fn then ok = false break end end if ok then h[#h+1] = fn end else loaded[hash] = { s.filename } end end end end local n = 0 for k, v in sortedhash(loaded) do local nv = #v if nv > 1 then if trace_warnings then report_names("lookup %a clashes with %a",k,v) end n = n + nv end end report_names("%a double lookups in %a",n,where) end local function checkduplicates() checkduplicate("mappings") checkduplicate("fallbacks") end local function sorthashes() local data = names.data local list = filters.list local mappings = data.mappings local fallbacks = data.fallbacks local sorted_mappings = { } local sorted_fallbacks = { } data.sorted_mappings = sorted_mappings data.sorted_fallbacks = sorted_fallbacks for i=1,#list do local l = list[i] sorted_mappings [l] = table.keys(mappings[l]) sorted_fallbacks[l] = table.keys(fallbacks[l]) sort(sorted_mappings [l],sorter) sort(sorted_fallbacks[l],sorter) end local sorted_families = table.keys(data.families) data.sorted_families = sorted_families sort(sorted_families,sorter) end local function unpackreferences() local data = names.data local specifications = data.specifications if specifications then for k, v in sortedhash(data.families) do for i=1,#v do v[i] = specifications[v[i]] end end local mappings = data.mappings if mappings then for _, m in sortedhash(mappings) do for k, v in sortedhash(m) do m[k] = specifications[v] end end end local fallbacks = data.fallbacks if fallbacks then for _, f in sortedhash(fallbacks) do for k, v in sortedhash(f) do f[k] = specifications[v] end end end end end local function analyzefiles(olddata) if not trace_warnings then report_names("warnings are disabled (tracker 'fonts.warnings')") end local data = names.data local done = { } local totalnofread = 0 local totalnofskipped = 0 local totalnofduplicates = 0 local nofread = 0 local nofskipped = 0 local nofduplicates = 0 local skip_paths = filters.paths local skip_names = filters.names local specifications = data.specifications local oldindices = olddata and olddata.indices or { } local oldspecifications = olddata and olddata.specifications or { } local oldrejected = olddata and olddata.rejected or { } local treatmentdata = treatments.data or { } -- when used outside context ----- walked = setmetatableindex("number") local function walk_tree(pathlist,suffix,identify) if pathlist then for i=1,#pathlist do local path = pathlist[i] path = cleanpath(path .. "/") path = gsub(path,"/+","/") local pattern = path .. "**." .. suffix -- ** forces recurse report_names("globbing path %a",pattern) local t = dir.glob(pattern) sort(t,sorter) for j=1,#t do local completename = t[j] identify(completename,basename(completename),suffix,completename) end -- walked[path] = walked[path] + #t end end end local function identify(completename,name,suffix,storedname) local pathpart, basepart = splitbase(completename) nofread = nofread + 1 local treatment = treatmentdata[completename] or treatmentdata[basepart] if treatment and treatment.ignored then if trace_names or trace_rejections then report_names("%s font %a is ignored, reason %a",suffix,completename,treatment.comment or "unknown") end nofskipped = nofskipped + 1 elseif done[name] then if lower(completename) ~= lower(done[name]) then -- already done (avoid otf afm clash) if trace_names or trace_rejections then report_names("%s font %a already done as %a",suffix,completename,done[name]) end nofduplicates = nofduplicates + 1 nofskipped = nofskipped + 1 end elseif not exists(completename) then -- weird error if trace_names or trace_rejections then report_names("%s font %a does not really exist",suffix,completename) end nofskipped = nofskipped + 1 elseif not is_qualified_path(completename) and findfile(completename,suffix) == "" then -- not locatable by backend anyway if trace_names or trace_rejections then report_names("%s font %a cannot be found by backend",suffix,completename) end nofskipped = nofskipped + 1 else if #skip_paths > 0 then for i=1,#skip_paths do if find(pathpart,skip_paths[i]) then if trace_names or trace_rejections then report_names("rejecting path of %s font %a",suffix,completename) end nofskipped = nofskipped + 1 return end end end if #skip_names > 0 then for i=1,#skip_paths do if find(basepart,skip_names[i]) then done[name] = true if trace_names or trace_rejections then report_names("rejecting name of %s font %a",suffix,completename) end nofskipped = nofskipped + 1 return end end end if trace_names then report_names("identifying %s font %a",suffix,completename) end -- needs checking with ttc / ttx : date not updated ? local result = nil local modification = lfs.attributes(completename,"modification") if olddata and modification and modification > 0 then local oldindex = oldindices[storedname] -- index into specifications if oldindex then local oldspecification = oldspecifications[oldindex] if oldspecification and oldspecification.filename == storedname then -- double check for out of sync local oldmodification = oldspecification.modification if oldmodification == modification then result = oldspecification specifications[#specifications + 1] = result else -- ?? end else -- ?? end elseif oldrejected[storedname] == modification then result = false end end if result == nil then local lsuffix = lower(suffix) local result, message = filters[lsuffix](completename) if result then if #result > 0 then for r=1,#result do check_name(data,result[r],storedname,modification,suffix,r) -- subfonts start at zero end else check_name(data,result,storedname,modification,suffix) end if trace_warnings and message and message ~= "" then report_names("warning when identifying %s font %a, %s",suffix,completename,message) end elseif trace_warnings then nofskipped = nofskipped + 1 report_names("error when identifying %s font %a, %s",suffix,completename,message or "unknown") end end done[name] = completename end logs.flush() -- a bit overkill for each font, maybe not needed here end local function traverse(what, method) local list = filters.list for n=1,#list do local suffix = list[n] local t = os.gettimeofday() -- use elapser nofread, nofskipped, nofduplicates = 0, 0, 0 suffix = lower(suffix) report_names("identifying %s font files with suffix %a",what,suffix) method(suffix) suffix = upper(suffix) report_names("identifying %s font files with suffix %a",what,suffix) method(suffix) totalnofread, totalnofskipped, totalnofduplicates = totalnofread + nofread, totalnofskipped + nofskipped, totalnofduplicates + nofduplicates local elapsed = os.gettimeofday() - t report_names("%s %s files identified, %s skipped, %s duplicates, %s hash entries added, runtime %0.3f seconds",nofread,what,nofskipped,nofduplicates,nofread-nofskipped,elapsed) end logs.flush() end -- problem .. this will not take care of duplicates local function withtree(suffix) resolvers.dowithfilesintree(".*%." .. suffix .. "$", function(method,root,path,name) if method == "file" or method == "tree" then local completename = root .."/" .. path .. "/" .. name completename = resolveprefix(completename) -- no shortcut identify(completename,name,suffix,name) return true end end, function(blobtype,blobpath,pattern) blobpath = resolveprefix(blobpath) -- no shortcut report_names("scanning path %a for %s files",blobpath,suffix) end, function(blobtype,blobpath,pattern,total,checked,done) blobpath = resolveprefix(blobpath) -- no shortcut report_names("%s entries found, %s %s files checked, %s okay",total,checked,suffix,done) end) end local function withlsr(suffix) -- all trees -- we do this only for a stupid names run, not used for context itself, -- using the vars is too clumsy so we just stick to a full scan instead local pathlist = resolvers.splitpath(resolvers.showpath("ls-R") or "") walk_tree(pathlist,suffix,identify) end local function withsystem(suffix) -- OSFONTDIR cum suis walk_tree(names.getpaths(trace),suffix,identify) end traverse("tree",withtree) -- TEXTREE only if not usesystemfonts then report_names("ignoring system fonts") elseif texconfig.kpse_init then traverse("lsr", withlsr) else traverse("system", withsystem) end data.statistics.readfiles = totalnofread data.statistics.skippedfiles = totalnofskipped data.statistics.duplicatefiles = totalnofduplicates -- for k, v in sortedhash(walked) do -- report_names("%s : %i",k,v) -- end end local function addfilenames() local data = names.data local specifications = data.specifications local indices = { } local files = { } for i=1,#specifications do local fullname = specifications[i].filename files[cleanfilename(fullname)] = fullname indices[fullname] = i end data.files = files data.indices = indices end local function rejectclashes() -- just to be sure, so no explicit afm will be found then local specifications = names.data.specifications local used = { } local okay = { } local rejected = { } -- only keep modification local o = 0 for i=1,#specifications do local s = specifications[i] local f = s.fontname if f then local fnd = used[f] local fnm = s.filename if fnd then if trace_warnings then report_names("fontname %a clashes, %a rejected in favor of %a",f,fnm,fnd) end rejected[f] = s.modification else used[f] = fnm o = o + 1 okay[o] = s end else o = o + 1 okay[o] = s end end local d = #specifications - #okay if d > 0 then report_names("%s files rejected due to clashes",d) end names.data.specifications = okay names.data.rejected = rejected end local function resetdata() local mappings = { } local fallbacks = { } for _, k in next, filters.list do mappings [k] = { } fallbacks[k] = { } end names.data = { version = names.version, mappings = mappings, fallbacks = fallbacks, specifications = { }, families = { }, statistics = { }, names = { }, indices = { }, rejected = { }, datastate = resolvers.datastate(), } end function names.identify(force) local starttime = os.gettimeofday() -- use elapser resetdata() analyzefiles(not force and names.readdata(names.basename)) rejectclashes() collectfamilies() cleanupkeywords() collecthashes() checkduplicates() addfilenames() -- sorthashes() -- will be resorted when saved collectstatistics(os.gettimeofday()-starttime) end function names.is_permitted(name) return containers.is_usable(names.cache, name) end function names.writedata(name,data) containers.write(names.cache,name,data) end function names.readdata(name) return containers.read(names.cache,name) end function names.load(reload,force) if not names.loaded then if reload then if names.is_permitted(names.basename) then names.identify(force) names.writedata(names.basename,names.data) else report_names("unable to access database cache") end names.saved = true end local data = names.readdata(names.basename) names.data = data if not names.saved then if not data or not next(data) or not data.specifications or not next(data.specifications) then names.load(true) end names.saved = true end if not data then report_names("accessing the data table failed") else unpackreferences() sorthashes() end names.loaded = true end end local function list_them(mapping,sorted,pattern,t,all) if mapping[pattern] then t[pattern] = mapping[pattern] else for k=1,#sorted do local v = sorted[k] if not t[v] and find(v,pattern) then t[v] = mapping[v] if not all then return end end end end end function names.list(pattern,reload,all) -- here? names.load() -- todo reload if names.loaded then local t = { } local data = names.data if data then local list = filters.list local mappings = data.mappings local sorted_mappings = data.sorted_mappings local fallbacks = data.fallbacks local sorted_fallbacks = data.sorted_fallbacks for i=1,#list do local format = list[i] list_them(mappings[format],sorted_mappings[format],pattern,t,all) if next(t) and not all then return t end list_them(fallbacks[format],sorted_fallbacks[format],pattern,t,all) if next(t) and not all then return t end end end return t end end local reloaded = false local function is_reloaded() if not reloaded then local data = names.data if autoreload then local c_status = serialize(resolvers.datastate()) local f_status = serialize(data.datastate) if c_status == f_status then if trace_names then report_names("font database has matching configuration and file hashes") end return else report_names("font database has mismatching configuration and file hashes") end else report_names("font database is regenerated (controlled by directive 'fonts.autoreload')") end names.loaded = false reloaded = true logs.flush() names.load(true) end end --[[ldx-- <p>The resolver also checks if the cached names are loaded. Being clever here is for testing purposes only (it deals with names prefixed by an encoding name).</p> --ldx]]-- local function fuzzy(mapping,sorted,name,sub) local condensed = gsub(name,"[^%a%d]","") for k=1,#sorted do local v = sorted[k] if find(v,condensed) then return mapping[v], v end end end -- we could cache a lookup .. maybe some day ... (only when auto loaded!) local function checkinstance(found,askedname) local instancenames = found.instancenames if instancenames then local fullname = found.fullname for i=1,#instancenames do local instancename = instancenames[i] if fullname .. instancename == askedname then local f = fastcopy(found) f.instances = nil f.instance = instancename return f end end end return found end local function foundname(name,sub) -- sub is not used currently local data = names.data local mappings = data.mappings local sorted_mappings = data.sorted_mappings local fallbacks = data.fallbacks local sorted_fallbacks = data.sorted_fallbacks local list = filters.list -- dilemma: we lookup in the order otf ttf ttc ... afm but now an otf fallback -- can come after an afm match ... well, one should provide nice names anyway -- and having two lists is not an option for i=1,#list do local l = list[i] local found = mappings[l][name] if found then if trace_names then report_names("resolved via direct name match: %a",name) end return checkinstance(found,name) end end for i=1,#list do local l = list[i] local found, fname = fuzzy(mappings[l],sorted_mappings[l],name,sub) if found then if trace_names then report_names("resolved via fuzzy name match: %a onto %a",name,fname) end return checkinstance(found,name) end end for i=1,#list do local l = list[i] local found = fallbacks[l][name] if found then if trace_names then report_names("resolved via direct fallback match: %a",name) end return checkinstance(found,name) end end for i=1,#list do local l = list[i] local found, fname = fuzzy(sorted_mappings[l],sorted_fallbacks[l],name,sub) if found then if trace_names then report_names("resolved via fuzzy fallback match: %a onto %a",name,fname) end return checkinstance(found,name) end end if trace_names then report_names("font with name %a cannot be found",name) end end function names.resolvedspecification(askedname,sub) if askedname and askedname ~= "" and names.enabled then askedname = cleanname(askedname) names.load() local found = foundname(askedname,sub) if not found and is_reloaded() then found = foundname(askedname,sub) end return found end end function names.resolve(askedname,sub) local found = names.resolvedspecification(askedname,sub) if found then return found.filename, found.subfont and found.rawname, found.subfont, found.instance end end -- function names.getfilename(askedname,suffix) -- last resort, strip funny chars -- names.load() -- local files = names.data.files -- askedname = files and files[cleanfilename(askedname,suffix)] or "" -- if askedname == "" then -- return "" -- else -- never entered -- return resolvers.findbinfile(askedname,suffix) or "" -- end -- end local runtimefiles = { } local runtimedone = false local function addruntimepath(path) names.load() local paths = type(path) == "table" and path or { path } local suffixes = tohash(filters.list) for i=1,#paths do local path = resolveprefix(paths[i]) if path ~= "" then local list = dir.glob(path.."/*") for i=1,#list do local fullname = list[i] local suffix = lower(suffixonly(fullname)) if suffixes[suffix] then local c = cleanfilename(fullname) runtimefiles[c] = fullname if trace_names then report_names("adding runtime filename %a for %a",c,fullname) end end end end end end local function addruntimefiles(variable) local paths = variable and resolvers.expandedpathlistfromvariable(variable) if paths and #paths > 0 then addruntimepath(paths) end end names.addruntimepath = addruntimepath names.addruntimefiles = addruntimefiles function names.getfilename(askedname,suffix) -- last resort, strip funny chars if not runtimedone then addruntimefiles(names.runtimefontsvariable) runtimedone = true end local cleanname = cleanfilename(askedname,suffix) local found = runtimefiles[cleanname] if found then return found end names.load() local files = names.data.files local found = files and files[cleanname] or "" if found == "" and is_reloaded() then files = names.data.files found = files and files[cleanname] or "" end if found and found ~= "" then return resolvers.findbinfile(found,suffix) or "" -- we still need to locate it end end -- specified search local function s_collect_weight_style_width_variant(found,done,all,weight,style,width,variant,family) if family then for i=1,#family do local f = family[i] if f and weight == f.weight and style == f.style and width == f.width and variant == f.variant then found[#found+1], done[f] = f, true if not all then return end end end end end local function m_collect_weight_style_width_variant(found,done,all,weight,style,width,variant,families,sorted,strictname) for i=1,#sorted do local k = sorted[i] local family = families[k] for i=1,#family do local f = family[i] if not done[f] and weight == f.weight and style == f.style and width == f.width and variant == f.variant and find(f.fontname,strictname) then found[#found+1], done[f] = f, true if not all then return end end end end end local function s_collect_weight_style_width(found,done,all,weight,style,width,family) if family then for i=1,#family do local f = family[i] if f and weight == f.weight and style == f.style and width == f.width then found[#found+1], done[f] = f, true if not all then return end end end end end local function m_collect_weight_style_width(found,done,all,weight,style,width,families,sorted,strictname) for i=1,#sorted do local k = sorted[i] local family = families[k] for i=1,#family do local f = family[i] if not done[f] and weight == f.weight and style == f.style and width == f.width and find(f.fontname,strictname) then found[#found+1], done[f] = f, true if not all then return end end end end end local function s_collect_weight_style(found,done,all,weight,style,family) if family then for i=1,#family do local f = family[i] if f and weight == f.weight and style == f.style then found[#found+1], done[f] = f, true if not all then return end end end end end local function m_collect_weight_style(found,done,all,weight,style,families,sorted,strictname) for i=1,#sorted do local k = sorted[i] local family = families[k] for i=1,#family do local f = family[i] if not done[f] and weight == f.weight and style == f.style and find(f.fontname,strictname) then found[#found+1], done[f] = f, true if not all then return end end end end end local function s_collect_style_width(found,done,all,style,width,family) if family then for i=1,#family do local f = family[i] if f and style == f.style and width == f.width then found[#found+1], done[f] = f, true if not all then return end end end end end local function m_collect_style_width(found,done,all,style,width,families,sorted,strictname) for i=1,#sorted do local k = sorted[i] local family = families[k] for i=1,#family do local f = family[i] if not done[f] and style == f.style and width == f.width and find(f.fontname,strictname) then found[#found+1], done[f] = f, true if not all then return end end end end end local function s_collect_weight(found,done,all,weight,family) if family then for i=1,#family do local f = family[i] if f and weight == f.weight then found[#found+1], done[f] = f, true if not all then return end end end end end local function m_collect_weight(found,done,all,weight,families,sorted,strictname) for i=1,#sorted do local k = sorted[i] local family = families[k] for i=1,#family do local f = family[i] if not done[f] and weight == f.weight and find(f.fontname,strictname) then found[#found+1], done[f] = f, true if not all then return end end end end end local function s_collect_style(found,done,all,style,family) if family then for i=1,#family do local f = family[i] if f and style == f.style then found[#found+1], done[f] = f, true if not all then return end end end end end local function m_collect_style(found,done,all,style,families,sorted,strictname) for i=1,#sorted do local k = sorted[i] local family = families[k] for i=1,#family do local f = family[i] if not done[f] and style == f.style and find(f.fontname,strictname) then found[#found+1], done[f] = f, true if not all then return end end end end end local function s_collect_width(found,done,all,width,family) if family then for i=1,#family do local f = family[i] if f and width == f.width then found[#found+1], done[f] = f, true if not all then return end end end end end local function m_collect_width(found,done,all,width,families,sorted,strictname) for i=1,#sorted do local k = sorted[i] local family = families[k] for i=1,#family do local f = family[i] if not done[f] and width == f.width and find(f.fontname,strictname) then found[#found+1], done[f] = f, true if not all then return end end end end end local function s_collect(found,done,all,family) if family then for i=1,#family do local f = family[i] if f then found[#found+1], done[f] = f, true if not all then return end end end end end local function m_collect(found,done,all,families,sorted,strictname) for i=1,#sorted do local k = sorted[i] local family = families[k] for i=1,#family do local f = family[i] if not done[f] and find(f.fontname,strictname) then found[#found+1], done[f] = f, true if not all then return end end end end end local function collect(stage,found,done,name,weight,style,width,variant,all) local data = names.data local families = data.families local sorted = data.sorted_families local strictname = "^".. name -- to be checked local family = families[name] if trace_names then report_names("resolving name %a, weight %a, style %a, width %a, variant %a",name,weight,style,width,variant) end if weight and weight ~= "" then if style and style ~= "" then if width and width ~= "" then if variant and variant ~= "" then if trace_names then report_names("resolving stage %s, name %a, weight %a, style %a, width %a, variant %a",stage,name,weight,style,width,variant) end s_collect_weight_style_width_variant(found,done,all,weight,style,width,variant,family) m_collect_weight_style_width_variant(found,done,all,weight,style,width,variant,families,sorted,strictname) else if trace_names then report_names("resolving stage %s, name %a, weight %a, style %a, width %a",stage,name,weight,style,width) end s_collect_weight_style_width(found,done,all,weight,style,width,family) m_collect_weight_style_width(found,done,all,weight,style,width,families,sorted,strictname) end else if trace_names then report_names("resolving stage %s, name %a, weight %a, style %a",stage,name,weight,style) end s_collect_weight_style(found,done,all,weight,style,family) m_collect_weight_style(found,done,all,weight,style,families,sorted,strictname) end else if trace_names then report_names("resolving stage %s, name %a, weight %a",stage,name,weight) end s_collect_weight(found,done,all,weight,family) m_collect_weight(found,done,all,weight,families,sorted,strictname) end elseif style and style ~= "" then if width and width ~= "" then if trace_names then report_names("resolving stage %s, name %a, style %a, width %a",stage,name,style,width) end s_collect_style_width(found,done,all,style,width,family) m_collect_style_width(found,done,all,style,width,families,sorted,strictname) else if trace_names then report_names("resolving stage %s, name %a, style %a",stage,name,style) end s_collect_style(found,done,all,style,family) m_collect_style(found,done,all,style,families,sorted,strictname) end elseif width and width ~= "" then if trace_names then report_names("resolving stage %s, name %a, width %a",stage,name,width) end s_collect_width(found,done,all,width,family) m_collect_width(found,done,all,width,families,sorted,strictname) else if trace_names then report_names("resolving stage %s, name %a",stage,name) end s_collect(found,done,all,family) m_collect(found,done,all,families,sorted,strictname) end end local function heuristic(name,weight,style,width,variant,all) -- todo: fallbacks local found, done = { }, { } --~ print(name,weight,style,width,variant) weight, style, width, variant = weight or "normal", style or "normal", width or "normal", variant or "normal" name = cleanname(name) collect(1,found,done,name,weight,style,width,variant,all) -- still needed ? if #found == 0 and variant ~= "normal" then -- not weight variant = "normal" collect(4,found,done,name,weight,style,width,variant,all) end if #found == 0 and width ~= "normal" then width = "normal" collect(2,found,done,name,weight,style,width,variant,all) end if #found == 0 and weight ~= "normal" then -- not style weight = "normal" collect(3,found,done,name,weight,style,width,variant,all) end if #found == 0 and style ~= "normal" then -- not weight style = "normal" collect(4,found,done,name,weight,style,width,variant,all) end -- local nf = #found if trace_names then if nf then local t = { } for i=1,nf do t[i] = formatters["%a"](found[i].fontname) end report_names("name %a resolved to %s instances: % t",name,nf,t) else report_names("name %a unresolved",name) end end if all then return nf > 0 and found else return found[1] end end function names.specification(askedname,weight,style,width,variant,reload,all) if askedname and askedname ~= "" and names.enabled then askedname = cleanname(askedname) -- or cleanname names.load(reload) local found = heuristic(askedname,weight,style,width,variant,all) if not found and is_reloaded() then found = heuristic(askedname,weight,style,width,variant,all) if not filename then found = foundname(askedname) -- old method end end return found end end function names.collect(askedname,weight,style,width,variant,reload,all) if askedname and askedname ~= "" and names.enabled then askedname = cleanname(askedname) -- or cleanname names.load(reload) local list = heuristic(askedname,weight,style,width,variant,true) if not list or #list == 0 and is_reloaded() then list = heuristic(askedname,weight,style,width,variant,true) end return list end end function names.collectspec(askedname,reload,all) local name, weight, style, width, variant = names.splitspec(askedname) return names.collect(name,weight,style,width,variant,reload,all) end function names.resolvespec(askedname,sub) -- redefined later local found = names.specification(names.splitspec(askedname)) if found then return found.filename, found.subfont and found.rawname end end function names.collectfiles(askedname,reload) -- no all if askedname and askedname ~= "" and names.enabled then askedname = cleanname(askedname) -- or cleanname names.load(reload) local list = { } local specifications = names.data.specifications for i=1,#specifications do local s = specifications[i] if find(cleanname(basename(s.filename)),askedname) then list[#list+1] = s end end return list end end -- todo: -- -- blacklisted = { -- ["cmr10.ttf"] = "completely messed up", -- } function names.exists(name) local found = false local list = filters.list for k=1,#list do local v = list[k] found = (findfile(name,v) or "") ~= "" if found then return found end end return (findfile(name,"tfm") or "") ~= "" or (names.resolve(name) or "") ~= "" end local lastlookups, lastpattern = { }, "" -- function names.lookup(pattern,name,reload) -- todo: find -- if lastpattern ~= pattern then -- names.load(reload) -- local specifications = names.data.specifications -- local families = names.data.families -- local lookups = specifications -- if name then -- lookups = families[name] -- elseif not find(pattern,"=",1,true) then -- lookups = families[pattern] -- end -- if trace_names then -- report_names("starting with %s lookups for %a",#lookups,pattern) -- end -- if lookups then -- for key, value in gmatch(pattern,"([^=,]+)=([^=,]+)") do -- local t, n = { }, 0 -- if find(value,"*",1,true) then -- value = topattern(value) -- for i=1,#lookups do -- local s = lookups[i] -- if find(s[key],value) then -- n = n + 1 -- t[n] = lookups[i] -- end -- end -- else -- for i=1,#lookups do -- local s = lookups[i] -- if s[key] == value then -- n = n + 1 -- t[n] = lookups[i] -- end -- end -- end -- if trace_names then -- report_names("%s matches for key %a with value %a",#t,key,value) -- end -- lookups = t -- end -- end -- lastpattern = pattern -- lastlookups = lookups or { } -- end -- return #lastlookups -- end local function look_them_up(lookups,specification) for key, value in sortedhash(specification) do local t, n = { }, 0 if find(value,"*",1,true) then value = topattern(value) for i=1,#lookups do local s = lookups[i] if find(s[key],value) then n = n + 1 t[n] = lookups[i] end end else for i=1,#lookups do local s = lookups[i] if s[key] == value then n = n + 1 t[n] = lookups[i] end end end if trace_names then report_names("%s matches for key %a with value %a",#t,key,value) end lookups = t end return lookups end local function first_look(name,reload) names.load(reload) local data = names.data local specifications = data.specifications local families = data.families if name then return families[name] else return specifications end end function names.lookup(pattern,name,reload) -- todo: find names.load(reload) local data = names.data local specifications = data.specifications local families = data.families local lookups = specifications if name then name = cleanname(name) end if type(pattern) == "table" then local familyname = pattern.familyname if familyname then familyname = cleanname(familyname) pattern.familyname = familyname end local lookups = first_look(name or familyname,reload) if lookups then if trace_names then report_names("starting with %s lookups for '%T'",#lookups,pattern) end lookups = look_them_up(lookups,pattern) end lastpattern = false lastlookups = lookups or { } elseif lastpattern ~= pattern then local lookups = first_look(name or (not find(pattern,"=",1,true) and pattern),reload) if lookups then if trace_names then report_names("starting with %s lookups for %a",#lookups,pattern) end local specification = settings_to_hash(pattern) local familyname = specification.familyname if familyname then familyname = cleanname(familyname) specification.familyname = familyname end lookups = look_them_up(lookups,specification) end lastpattern = pattern lastlookups = lookups or { } end return #lastlookups end function names.getlookupkey(key,n) local l = lastlookups[n or 1] return (l and l[key]) or "" end function names.noflookups() return #lastlookups end function names.getlookups(pattern,name,reload) if pattern then names.lookup(pattern,name,reload) end return lastlookups end -- The following is new ... watch the overload! local specifications = allocate() names.specifications = specifications -- files = { -- name = "antykwapoltawskiego", -- list = { -- ["AntPoltLtCond-Regular.otf"] = { -- -- name = "antykwapoltawskiego", -- style = "regular", -- weight = "light", -- width = "condensed", -- }, -- }, -- } function names.register(files) if files then local list, commonname = files.list, files.name if list then local n, m = 0, 0 for filename, filespec in sortedhash(list) do local name = lower(filespec.name or commonname) if name and name ~= "" then local style = normalized_styles [lower(filespec.style or "normal")] local width = normalized_widths [lower(filespec.width or "normal")] local weight = normalized_weights [lower(filespec.weight or "normal")] local variant = normalized_variants[lower(filespec.variant or "normal")] local weights = specifications[name ] if not weights then weights = { } specifications[name ] = weights end local styles = weights [weight] if not styles then styles = { } weights [weight] = styles end local widths = styles [style ] if not widths then widths = { } styles [style ] = widths end local variants = widths [width ] if not variants then variants = { } widths [width ] = variants end variants[variant] = filename n = n + 1 else m = m + 1 end end if trace_specifications then report_names("%s filenames registered, %s filenames rejected",n,m) end end end end function names.registered(name,weight,style,width,variant) local ok = specifications[name] ok = ok and (ok[(weight and weight ~= "" and weight ) or "normal"] or ok.normal) ok = ok and (ok[(style and style ~= "" and style ) or "normal"] or ok.normal) ok = ok and (ok[(width and width ~= "" and width ) or "normal"] or ok.normal) ok = ok and (ok[(variant and variant ~= "" and variant) or "normal"] or ok.normal) -- -- todo: same fallbacks as with database -- if ok then return { filename = ok, subname = "", -- rawname = nil, } end end function names.resolvespec(askedname,sub) -- overloads previous definition local name, weight, style, width, variant = names.splitspec(askedname) if trace_specifications then report_names("resolving specification: %a to name=%s, weight=%s, style=%s, width=%s, variant=%s",askedname,name,weight,style,width,variant) end local found = names.registered(name,weight,style,width,variant) if found and found.filename then if trace_specifications then report_names("resolved by registered names: %a to %s",askedname,found.filename) end return found.filename, found.subname, found.rawname else found = names.specification(name,weight,style,width,variant) if found and found.filename then if trace_specifications then report_names("resolved by font database: %a to %s",askedname,found.filename) end return found.filename, found.subfont and found.rawname end end if trace_specifications then report_names("unresolved: %s",askedname) end end function fonts.names.ignoredfile(filename) -- only supported in mkiv return false -- will be overloaded end -- example made for luatex list (unlikely to be used): -- -- local command = [[reg QUERY "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Fonts"]] -- local pattern = ".-[\n\r]+%s+(.-)%s%(([^%)]+)%)%s+REG_SZ%s+(%S+)%s+" -- -- local function getnamesfromregistry() -- local data = os.resultof(command) -- local list = { } -- for name, format, filename in string.gmatch(data,pattern) do -- list[name] = filename -- end -- return list -- end
local protobuf = require("pb") local protoc = require("Network.Proto.protoc") local tmProto = require("Network.Protos") local all_proto_files = {} local all_loaded_protos = {} local M = {} function M.Register(protos) all_proto_files = protos or {} protoc.unknown_import = function(self, module_name) for k, v in pairs(all_proto_files) do if string.find(k, module_name) then if protoc.loaded[k] then return true else all_loaded_protos[k] = true return protoc:load(v, k) end end end end for k, v in pairs(all_proto_files) do if not all_loaded_protos[k] then protoc:load(v, k) all_loaded_protos[k] = true end end --注册每个字段的类型 for _, proto in pairs(tmProto) do if proto.type == "message" then for _, field in pairs(proto.tmField) do local proto = tmProto[field.type] if proto and proto.type == "message" then field.ismessage = true end if proto and proto.type == "enum" then field.isenum = true end end end end end --获取Proto的信息 function M.GetProto(protoName) return tmProto[protoName] end --获取enumId function M.GetEnumId(protoName, enum) local proto = M.getProto(protoName) return proto.enums[enum] end --获取enum function M.GetEnum(protoName, enumId) local proto = M.getProto(protoName) for _enum,_enumId in pairs(proto.enums) do if _enumId == enumId then return _enum end end return nil end function M.Encode(protoName, data) local proto = M.GetProto(protoName) return protobuf.encode(proto.fullName, data) end function M.Decode(protoName, data) local proto = M.GetProto(protoName) return protobuf.decode(proto.fullName, data) end return M
PROPERTIES = {year=0, month=0, day=0, hour=0, min=0, sec=0} totalTime = 0 startTime = 0 isWorkOvertime = false YYYY = 2021 MM = 1 DD = 5 H = 8 M = 0 S = 0 function Initialize() stringDate = tolua.cast(SKIN:GetMeter("Date"), "CMeterString") stringHour = tolua.cast(SKIN:GetMeter("Hour"), "CMeterString") stringMinute = tolua.cast(SKIN:GetMeter("Minute"), "CMeterString") stringSecond = tolua.cast(SKIN:GetMeter("Second"), "CMeterString") stringmSecond = tolua.cast(SKIN:GetMeter("mSecond"), "CMeterString") startTime = os.time(getStartWorkTime()) countdownTime = getOffWorkTime() totalTime = os.time(countdownTime)-startTime progress = 0 end -- function Initialize function Update() local rLeft = os.time(countdownTime) - os.time() if rLeft < 0 then rLeft = 0 end local dLeft = math.floor(rLeft/60/60/24) local hLeft = math.floor(rLeft/60/60)%24 local mLeft = math.floor(rLeft/60)%60 local sLeft = math.floor(rLeft)%60 local msLeft = math.floor(1000-(os.clock()*1000)%1000) if rLeft == 0 then stringmSecond:SetText(0) else stringmSecond:SetText(msLeft) end if totalTime > 0 and progress <= 1 then progress = (os.time()-startTime)/totalTime local progressWidth = getMeterWidth() * progress progressMeter = SKIN:GetMeter("progress") progressMeter:SetW(progressWidth) local color = getCurrentColor(progress) --myMeter:SetSolidColor(color) --myMeter:SetOption('SolidColor', color) end stringDate:SetText(dLeft) stringHour:SetText(hLeft) stringMinute:SetText(mLeft) stringSecond:SetText(sLeft) end -- function Update function getMeterWidth() local meterWidth = SKIN:GetMeter("Note"):GetW() + SKIN:GetMeter("Date"):GetW() + SKIN:GetMeter("Hour"):GetW() + SKIN:GetMeter("Minute"):GetW() + SKIN:GetMeter("Second"):GetW() return meterWidth end function getOffWorkTime() local w = os.date("%w") local hour = 21 if w == "5" then hour = 18 end if isWorkOvertime == false then hour = 18 end return {year=YYYY, month=MM, day=DD, hour=H, min=M, sec=S} end function getStartWorkTime() return {year=2020, month=12, day=16, hour=15, min=33, sec=35} end function getCurrentColor(progress) local startR = 30 local startG = 199 local startB = 230 local endR = 146 local endG = 185 local endB = 1 local currentR = getCurrentValue(startR, endR, progress) local currentG = getCurrentValue(startG, endG, progress) local currentB = getCurrentValue(startB, endB, progress) local RGB = {} RGB.r = currentR RGB.g = currentG RGB.b = currentB return RGB end function getCurrentValue(startValue, endValue, progress) local left = endValue - startValue if left == 0 then return startValue end local currentValue = startValue + left * progress return currentValue end
local uv = require "lluv" local host = host or "127.0.0.1" local port = port or "8384" local function write(s, data, cb) local ok, err = s:write(data, cb) if not ok then print("write return error :", err) os.exit(-1) end return true end local function on_write(cli, err,...) if err then print("Done!") os.exit(0) end write(cli, "hello", on_write) end uv.tcp():connect(host, port, function(cli, err) if err then cli:close() assert(false, tostring(err)) end write(cli, "hello", on_write) end) uv.run()
BigWigs3DB = nil BigWigsIconDB = { } BigWigsStatsDB = nil
function nether_sword(keys) local caster = keys.caster local target = keys.target local ability = keys.ability if caster:IsRealHero() then local damage = ability:GetSpecialValueFor("max_hp_percent") / 100 * target:GetMaxHealth() local damage_table = { victim = target, attacker = caster, damage = damage, damage_type = DAMAGE_TYPE_PURE, ability = ability } ApplyDamage(damage_table) end end
local world = require 'world' local quads = require 'quads' -- maps local map_01 = require 'maps.map_05' -- local map_02 = require 'maps.map_02' -- environment tilesets local tileset = love.graphics.newImage('tileset.png') tileset:setFilter('nearest', 'nearest', 0) local tilesetQuads = quads:loadQuads(tileset, 1, 6) local map = {maps = {}, objects = {}, mapNumber = 0} function map:load() self.mapNumber = self.mapNumber + 1 self:loadMaps() self:loadObjects() end function map:loadMaps() if #self.maps == 0 then self.maps = { map_01, -- map_02 } end self.currentMap = self.maps[self.mapNumber] end function map:loadObjects() -- remove pre-existing solids on load self:removeSolids() for i = #self.currentMap.layers, 1, -1 do if self.currentMap.layers[i].type == "objectgroup" then local name = self.currentMap.layers[i].name local objects = self.currentMap.layers[i].objects for j = #objects, 1, -1 do local object = objects[j] if name == "Solids" then self:loadSolids(object) elseif name == "Spikes" then self:loadSpikes(object) elseif name == "Coins" then self:loadCoins(object) elseif name == "Boosters" then self:loadBoosters(object) end end end end end function map:loadSolids(object) object.name = "solid" if object.shape == "rectangle" then self.objects[#self.objects+1] = object world.bump:add(object, object.x, object.y, object.width, object.height) end end function map:loadSpikes(object) object.name = "spike" if object.shape == "rectangle" then self.objects[#self.objects+1] = object world.bump:add(object, object.x, object.y, object.width, object.height) end end function map:loadCoins(object) object.name = "coin" if object.shape == "rectangle" then if object.height == 0 then object.height = self.currentMap.height end -- generate individual coins from a large object if object.height > self.currentMap.tileheight or object.width > self.currentMap.tilewidth then local tileshigh = object.height / self.currentMap.tileheight local tileswide = object.width / self.currentMap.tilewidth local x, y = 0, 0 for j = 1, tileshigh do y = (j - 1) * self.currentMap.tileheight + object.y for i = 1, tileswide do x = (i - 1) * self.currentMap.tilewidth + object.x local coin = { x = x, y = y, width = self.currentMap.tilewidth, height = self.currentMap.tileheight, name = "coin", shape = "rectangle" } self.objects[#self.objects+1] = coin world.bump:add(coin, coin.x, coin.y, coin.width, coin.height) end end end if object.height == self.currentMap.tileheight and object.width == self.currentMap.tilewidth then self.objects[#self.objects+1] = object world.bump:add(object, object.x, object.y, object.width, object.height) end end end function map:loadBoosters(object) object.name = "booster" if object.shape == "rectangle" then self.objects[#self.objects+1] = object world.bump:add(object, object.x, object.y, object.width, object.height) end end function map:removeSolids() local len = #self.objects if len > 0 then for i = len, 1, -1 do world.bump:remove(self.objects[i]) end for i = len, 1, -1 do table.remove(self.objects, i) end end end function map:drawTiles() -- TODO: select foreground layer and background layer (in the future) -- tiles local width = self.currentMap.layers[1].width local height = self.currentMap.layers[1].height local tilewidth = self.currentMap.tilewidth local tileheight = self.currentMap.tileheight local x, y = 0, -1 for i = 1, #self.currentMap.layers[1].data do local n = self.currentMap.layers[1].data[i] x = x + 1 if (i-1) % width == 0 then y = y + 1 x = 0 end love.graphics.setColor(255,255,255) if n == 1 then love.graphics.draw(tileset, tilesetQuads[1], x * tilewidth, y * tileheight) elseif n == 2 then love.graphics.draw(tileset, tilesetQuads[2], x * tilewidth, y * tileheight) elseif n == 3 then love.graphics.draw(tileset, tilesetQuads[3], x * tilewidth, y * tileheight) elseif n == 5 then love.graphics.draw(tileset, tilesetQuads[5], x * tilewidth, y * tileheight) end end end function map:drawWorldObjects() -- objects for i = 1, #self.currentMap.layers do local name = self.currentMap.layers[i].name if name == "Solids" or name == "Spikes" then for j = 1, #self.currentMap.layers[i].objects do local object = self.currentMap.layers[i].objects[j] love.graphics.setColor(0,0,0) love.graphics.print(object.type, object.x, object.y) love.graphics.rectangle("line", object.x, object.y, object.width, object.height) end end end end function map:drawCoins(items, len) for i = 1, len do local item = items[i] if item.name == "coin" then love.graphics.setColor(255,255,255) love.graphics.draw(tileset, tilesetQuads[4], item.x, item.y) end end end return map
local class = require 'ext.class' local table = require 'ext.table' local Binary = require 'symmath.op.Binary' local wedge = class(Binary) wedge.precedence = 4 wedge.name = '/\\' -- copied from mul -- is this in add as well? put in parent class? function wedge:flatten() for i=#self,1,-1 do local ch = self[i] if wedge:isa(ch) then local expr = {table.unpack(self)} table.remove(expr, i) for j=#ch,1,-1 do local chch = ch[j] table.insert(expr, i, chch) end return wedge(table.unpack(expr)) end end end wedges.rules = { Prune = { {apply = function(eval, expr) -- TODO sort somehow so db wedge da = -da wedge db -- for the sake of addition/subtraction print'FINISHME' end}, } } return wedge
-- Lit nodes. minetest.register_node("greek:fire_bowl", { description = "Fire Bowl", drawtype = "mesh", mesh = "greek_fire_bowl.obj", tiles = {"greek_fire_bowl.png", "blank.png"}, inventory_image = "greek_fire_bowl_inv.png", paramtype = "light", sunlight_propagates = true, paramtype2 = "facedir", place_param2 = 0, selection_box = {type = "fixed", fixed = {-0.5, -0.5, -0.5, 0.5, -0.25, 0.5}}, collision_box = {type = "fixed", fixed = {-0.5, -0.5, -0.5, 0.5, -0.25, 0.5}}, groups = {cracky = 3, oddly_breakable_by_hand = 2}, sounds = greek.default_sounds("node_sound_glass_defaults"), on_place = function(stack, placer, pointed) -- If placed against ceiling, set to hanging fire bowl local s, p = minetest.item_place((pointed.under.y > pointed.above.y and stack:replace("greek:fire_bowl_hanging") and stack) or stack, placer, pointed) return s:replace("greek:fire_bowl") and s, p end, on_punch = function(pos, _, puncher) for _, group in pairs({"fire", "igniter", "torch"}) do if minetest.get_item_group(puncher:get_wielded_item():get_name(), group) > 0 then return minetest.swap_node(pos, {name = "greek:fire_bowl_lit"}) end end end, }) minetest.register_node("greek:fire_bowl_lit", { description = "Fire Bowl (Lit)", drawtype = "mesh", mesh = "greek_fire_bowl.obj", tiles = {"greek_fire_bowl.png", {name = "greek_fire.png", animation = {type = "vertical_frames", aspect_w = 16, aspect_h = 16, length = 1}}}, inventory_image = "greek_fire_bowl_lit_inv.png", paramtype = "light", sunlight_propagates = true, paramtype2 = "facedir", place_param2 = 0, selection_box = {type = "fixed", fixed = {-0.5, -0.5, -0.5, 0.5, -0.25, 0.5}}, collision_box = {type = "fixed", fixed = {-0.5, -0.5, -0.5, 0.5, -0.25, 0.5}}, light_source = 12, drop = greek.settings_get("fire_bowl_dig_snuff") and "greek:fire_bowl" or nil, groups = {cracky = 3, oddly_breakable_by_hand = 2, torch = 1}, sounds = greek.default_sounds("node_sound_glass_defaults"), on_place = function(stack, placer, pointed) local s, p = minetest.item_place((pointed.under.y > pointed.above.y and stack:replace("greek:fire_bowl_hanging_lit") and stack) or stack, placer, pointed) return s:replace("greek:fire_bowl_lit") and s, p end, on_punch = function(pos, _, puncher) for _, group in pairs({"water", "liquid", "water_bucket"}) do if minetest.get_item_group(puncher:get_wielded_item():get_name(), group) > 0 then return minetest.swap_node(pos, {name = "greek:fire_bowl"}) end end end, }) minetest.register_node("greek:fire_bowl_hanging", { description = "Hanging Fire Bowl (You hacker, you)", drawtype = "mesh", mesh = "greek_fire_bowl_hanging.obj", tiles = {"greek_fire_bowl.png", "blank.png", "greek_chain.png"}, paramtype = "light", sunlight_propagates = true, paramtype2 = "facedir", selection_box = {type = "fixed", fixed = {-0.5, -1.5, -0.5, 0.5, 0.5, 0.5}}, collision_box = {type = "fixed", fixed = {-0.5, -1.5, -0.5, 0.5, 0.5, 0.5}}, groups = {cracky = 3, oddly_breakable_by_hand = 2, not_in_creative_inventory = 1}, sounds = greek.default_sounds("node_sound_glass_defaults"), drop = "greek:fire_bowl", on_punch = function(pos, _, puncher) for _, group in pairs({"fire", "igniter", "torch"}) do if minetest.get_item_group(puncher:get_wielded_item():get_name(), group) > 0 then return minetest.swap_node(pos, {name = "greek:fire_bowl_hanging_lit"}) end end end, }) minetest.register_node("greek:fire_bowl_hanging_lit", { description = "Hanging Fire Bowl (Lit) (You hacker, you)", drawtype = "mesh", mesh = "greek_fire_bowl_hanging.obj", tiles = {"greek_fire_bowl.png", {name = "greek_fire.png", animation = {type = "vertical_frames", aspect_w = 16, aspect_h = 16, length = 1}}, "greek_chain.png"}, paramtype = "light", sunlight_propagates = true, paramtype2 = "facedir", selection_box = {type = "fixed", fixed = {-0.5, -1.5, -0.5, 0.5, 0.5, 0.5}}, collision_box = {type = "fixed", fixed = {-0.5, -1.5, -0.5, 0.5, 0.5, 0.5}}, light_source = 12, groups = {cracky = 3, oddly_breakable_by_hand = 2, not_in_creative_inventory = 1}, sounds = greek.default_sounds("node_sound_glass_defaults"), drop = greek.settings_get("fire_bowl_dig_snuff") and "greek:fire_bowl" or "greek:fire_bowl_lit", on_punch = function(pos, _, puncher) for _, group in pairs({"water", "liquid", "water_bucket"}) do if minetest.get_item_group(puncher:get_wielded_item():get_name(), group) > 0 then return minetest.swap_node(pos, {name = "greek:fire_bowl_hanging"}) end end end, }) minetest.register_craft({ output = "greek:fire_bowl 2", recipe = { {"greek:marble_polished", "", "greek:marble_polished"}, {"", "greek:gilded_gold", ""}, }, }) minetest.register_node("greek:lamp", { description = "Lamp", drawtype = "mesh", mesh = "greek_lamp.obj", tiles = { {name = "greek_lamp.png"}, {name = "greek_lamp.png", animation = {type = "vertical_frames", aspect_w = 16, aspect_h = 4, length = 1}} }, inventory_image = "greek_lamp_inv.png", wield_image = "greek_lamp_inv.png", paramtype = "light", sunlight_propagates = true, paramtype2 = "facedir", selection_box = {type = "fixed", fixed = {-6 / 16, -0.5, -6 / 16, 6 / 16, -0.25, 6 / 16}}, collision_box = {type = "fixed", fixed = {-6 / 16, -0.5, -6 / 16, 6 / 16, -0.25, 6 / 16}}, light_source = 8, groups = {cracky = 3, oddly_breakable_by_hand = 2, torch = 1}, sounds = greek.default_sounds("node_sound_glass_defaults"), }) minetest.register_craft({ output = "greek:lamp 2", recipe = { {"group:greek:red_clay", "", "group:greek:red_clay"}, {"", "group:greek:red_clay", ""}, }, })
----------------------------------- -- Ability: Healing Waltz -- Removes one detrimental status effect from target party member. -- Obtained: Dancer Level 35 -- TP Required: 200 -- Recast Time: 00:00:15 ----------------------------------- require("scripts/globals/status") require("scripts/globals/msg") ----------------------------------- function onAbilityCheck(player,target,ability) if target:getHP() == 0 then return tpz.msg.basic.CANNOT_ON_THAT_TARG,0 elseif player:hasStatusEffect(tpz.effect.SABER_DANCE) then return tpz.msg.basic.UNABLE_TO_USE_JA2, 0 elseif player:hasStatusEffect(tpz.effect.TRANCE) then return 0,0 elseif player:getTP() < 200 then return tpz.msg.basic.NOT_ENOUGH_TP,0 else local recastMod = player:getMod(tpz.mod.WALTZ_DELAY) if recastMod ~= 0 then local newRecast = ability:getRecast() + recastMod ability:setRecast(utils.clamp(newRecast, 0, newRecast)) end return 0,0 end end function onUseAbility(player,target,ability) -- Only remove TP if the player doesn't have Trance. if not player:hasStatusEffect(tpz.effect.TRANCE) then player:delTP(200) end local effect = target:healingWaltz() if effect == tpz.effect.NONE then ability:setMsg(tpz.msg.basic.NO_EFFECT) -- no effect else ability:setMsg(tpz.msg.basic.JA_REMOVE_EFFECT) end player:addRecast(tpz.recast.ABILITY, 217, ability:getRecast()) -- Waltzes return effect end
local syntax = require "core.syntax" syntax.add { files = { "%.php$", "%.phtml", "%.phps$" }, headers = "^<%?php", comment = "//", patterns = { { pattern = "//.-\n", type = "comment" }, { pattern = "#.-\n", type = "comment" }, { pattern = { "/%*", "%*/" }, type = "comment" }, -- I dont know why the '//' are needed but I leave it here for now { pattern = { '"', '"', '\\' }, type = "string" }, { pattern = { "'", "'", '\\' }, type = "string" }, { pattern = "%\\x[%da-fA-F]+", type = "number" }, { pattern = "-?%d+[%d%.eE]*", type = "number" }, { pattern = "-?%.?%d+", type = "number" }, { pattern = "[%.%+%-=/%*%^%%<>!~|&]", type = "operator" }, { pattern = "[%a_][%w_]*%f[(]", type = "function" }, { pattern = "[%a_][%w_]*", type = "symbol" }, -- To indicate variables. { pattern = "%$", type = "operator" }, }, symbols = { ["return"] = "keyword", ["if"] = "keyword", ["else"] = "keyword", ["elseif"] = "keyword", ["endif"] = "keyword", ["declare"] = "keyword", ["enddeclare"] = "keyword", ["switch"] = "keyword", ["endswitch"] = "keyword", ["as"] = "keyword", ["do"] = "keyword", ["for"] = "keyword", ["endfor"] = "keyword", ["foreach"] = "keyword", ["endforeach"] = "keyword", ["while"] = "keyword", ["endwhile"] = "keyword", ["switch"] = "keyword", ["case"] = "keyword", ["continue"] = "keyword", ["default"] = "keyword", ["break"] = "keyword", ["exit"] = "keyword", ["goto"] = "keyword", ["catch"] = "keyword", ["throw"] = "keyword", ["try"] = "keyword", ["finally"] = "keyword", ["class"] = "keyword", ["trait"] = "keyword", ["interface"] = "keyword", ["public"] = "keyword", ["static"] = "keyword", ["protected"] = "keyword", ["private"] = "keyword", ["abstract"] = "keyword", ["final"] = "keyword", ["function"] = "keyword2", ["global"] = "keyword2", ["var"] = "keyword2", ["const"] = "keyword2", ["bool"] = "keyword2", ["boolean"] = "keyword2", ["int"] = "keyword2", ["integer"] = "keyword2", ["real"] = "keyword2", ["double"] = "keyword2", ["float"] = "keyword2", ["string"] = "keyword2", ["array"] = "keyword2", ["object"] = "keyword2", ["callable"] = "keyword2", ["iterable"] = "keyword2", ["namespace"] = "keyword2", ["extends"] = "keyword2", ["implements"] = "keyword2", ["instanceof"] = "keyword2", ["require"] = "keyword2", ["require_once"] = "keyword2", ["include"] = "keyword2", ["include_once"] = "keyword2", ["use"] = "keyword2", ["new"] = "keyword2", ["clone"] = "keyword2", ["true"] = "literal", ["false"] = "literal", ["NULL"] = "literal", ["parent"] = "literal", ["self"] = "literal", }, }
-- LibShowUIPanel-1.0.lua -- @Author : Dencer (tdaddon@163.com) -- @Link : https://dengsir.github.io -- @Date : 6/15/2021, 11:20:01 PM -- local MAJOR, MINOR = "LibShowUIPanel-1.0-KkthnxUI", 5 ---@class LibShowUIPanel-1.0 local Lib, oldminor = LibStub:NewLibrary(MAJOR, MINOR) if not Lib then return end if WOW_PROJECT_ID == WOW_PROJECT_CLASSIC then Lib.ShowUIPanel = ShowUIPanel Lib.HideUIPanel = HideUIPanel Lib.ToggleFrame = ToggleFrame Lib.Show = ShowUIPanel Lib.Hide = HideUIPanel Lib.Toggle = ToggleFrame return end local ShowUIPanel = ShowUIPanel local HideUIPanel = HideUIPanel local InCombatLockdown = InCombatLockdown Lib.Delegate = Lib.Delegate or (function() local frame = EnumerateFrames() while frame do if frame.SetUIPanel and issecurevariable(frame, "SetUIPanel") then return frame end frame = EnumerateFrames(frame) end end)() local Delegate = Lib.Delegate local function GetUIPanelWindowInfo(frame, name) if not frame:GetAttribute("UIPanelLayout-defined") then local info = UIPanelWindows[frame:GetName()] if not info then return end frame:SetAttribute("UIPanelLayout-defined", true) for k, v in pairs(info) do frame:SetAttribute("UIPanelLayout-" .. k, v) end end return frame:GetAttribute("UIPanelLayout-" .. name) end local function ShowPanel(frame, force) if not frame or frame:IsShown() then return end if not GetUIPanelWindowInfo(frame, "area") then frame:Show() return end Delegate:SetAttribute("panel-force", force) Delegate:SetAttribute("panel-frame", frame) Delegate:SetAttribute("panel-show", true) end local function HidePanel(frame, skipSetPoint) if not frame or not frame:IsShown() then return end if not GetUIPanelWindowInfo(frame, "area") then frame:Hide() return end Delegate:SetAttribute("panel-frame", frame) Delegate:SetAttribute("panel-skipSetPoint", skipSetPoint) Delegate:SetAttribute("panel-hide", true) end function Lib.Show(frame, force) if not InCombatLockdown() then return ShowUIPanel(frame, force) else return ShowPanel(frame, force) end end function Lib.Hide(frame, skipSetPoint) if not InCombatLockdown() then return HideUIPanel(frame, skipSetPoint) else return HidePanel(frame, skipSetPoint) end end function Lib.Toggle(frame) if frame:IsShown() then Lib.Hide(frame) else Lib.Show(frame) end end if not oldminor or oldminor < 3 then -- 可长期持有的API function Lib.ShowUIPanel(frame, force) return Lib.Show(frame, force) end function Lib.HideUIPanel(frame, skipSetPoint) return Lib.Hide(frame, skipSetPoint) end function Lib.ToggleFrame(frame) return Lib.Toggle(frame) end end ---- hooks if not Lib.OnCallShowUIPanel then hooksecurefunc("ShowUIPanel", function(...) return Lib.OnCallShowUIPanel(...) end) end if not Lib.OnCallHideUIPanel then hooksecurefunc("HideUIPanel", function(...) return Lib.OnCallHideUIPanel(...) end) end function Lib.OnCallShowUIPanel(frame, force) if not frame or frame:IsShown() or not InCombatLockdown() then return end return ShowPanel(frame, force) end function Lib.OnCallHideUIPanel(frame, skipSetPoint) if not frame or not frame:IsShown() or not InCombatLockdown() then return end return HidePanel(frame, skipSetPoint) end
vim.g.python3_host_prog = vim.fn.expand('~/.config/nvim/venv/bin/python3') -- plugs!! local plug = require('plug') local plug_dir = vim.fn.expand('~/.config/nvim/plugs') plug .start(plug_dir) .install('airblade/vim-gitgutter') .install('crockeo/find-pytest.nvim') .install('neovim/nvim-lspconfig') .install('nvim-lua/completion-nvim') .install('nvim-lua/plenary.nvim') .install('nvim-telescope/telescope.nvim') .install('preservim/nerdtree') .install('rktjmp/lush.nvim') .install('saltstack/salt-vim') .install('tpope/vim-abolish') .install('tpope/vim-commentary') .install('tpope/vim-sensible') .install('tpope/vim-sleuth') .stop() -- install a bunch of other configs local sub_configs = { 'colorscheme', 'keymaps', 'lsp', 'options', } for _, config_name in ipairs(sub_configs) do local config = require(config_name) config.init() end vim.api.nvim_exec([[ set clipboard+=unnamedplus autocmd BufWritePre * %s/\s\+$//e ]], false) vim.api.nvim_exec([[ set wildcharm=<C-Z> cnoremap <expr> <up> getcmdline()[:1] is 'e ' && wildmenumode() ? "\<left>" : "\<up>" cnoremap <expr> <down> getcmdline()[:1] is 'e ' && wildmenumode() ? "\<right>" : "\<down>" cnoremap <expr> <left> getcmdline()[:1] is 'e ' && wildmenumode() ? "\<up>" : "\<left>" cnoremap <expr> <right> getcmdline()[:1] is 'e ' && wildmenumode() ? " \<bs>\<C-Z>" : "\<right>" ]], false)
--- @ignore CLGAMEMODESUBMENU.base = "base_gamemodesubmenu" CLGAMEMODESUBMENU.priority = 96 CLGAMEMODESUBMENU.title = "submenu_appearance_shop_title" function CLGAMEMODESUBMENU:Populate(parent) local form = vgui.CreateTTT2Form(parent, "header_shop_settings") form:MakeHelp({ label = "help_shop_key_desc" }) form:MakeCheckBox({ label = "label_shop_always_show", convar = "ttt_bem_always_show_shop" }) if GetConVar("ttt_bem_allow_change"):GetBool() then local form2 = vgui.CreateTTT2Form(parent, "header_shop_layout") form2:MakeSlider({ label = "label_shop_num_col", convar = "ttt_bem_cols", min = 1, max = 20, decimal = 0 }) form2:MakeSlider({ label = "label_shop_num_row", convar = "ttt_bem_rows", min = 1, max = 20, decimal = 0 }) form2:MakeSlider({ label = "label_shop_item_size", convar = "ttt_bem_size", min = 32, max = 128, decimal = 0 }) end local form3 = vgui.CreateTTT2Form(parent, "header_shop_marker") form3:MakeCheckBox({ label = "label_shop_show_slot", convar = "ttt_bem_marker_slot" }) form3:MakeCheckBox({ label = "label_shop_show_custom", convar = "ttt_bem_marker_custom" }) form3:MakeCheckBox({ label = "label_shop_show_fav", convar = "ttt_bem_marker_fav" }) end
require("firecast.lua"); local __o_rrpgObjs = require("rrpgObjs.lua"); require("rrpgGUI.lua"); require("rrpgDialogs.lua"); require("rrpgLFM.lua"); require("ndb.lua"); require("locale.lua"); local __o_Utils = require("utils.lua"); local function constructNew_frmVantagemItem() local obj = GUI.fromHandle(_obj_newObject("form")); local self = obj; local sheet = nil; rawset(obj, "_oldSetNodeObjectFunction", rawget(obj, "setNodeObject")); function obj:setNodeObject(nodeObject) sheet = nodeObject; self.sheet = nodeObject; self:_oldSetNodeObjectFunction(nodeObject); end; function obj:setNodeDatabase(nodeObject) self:setNodeObject(nodeObject); end; _gui_assignInitialParentForForm(obj.handle); obj:beginUpdate(); obj:setName("frmVantagemItem"); obj:setWidth(110); obj:setHeight(25); obj:setMargins({top=1}); obj.rectangle1 = GUI.fromHandle(_obj_newObject("rectangle")); obj.rectangle1:setParent(obj); obj.rectangle1:setAlign("client"); obj.rectangle1:setColor("#212121"); obj.rectangle1:setName("rectangle1"); obj.edit1 = GUI.fromHandle(_obj_newObject("edit")); obj.edit1:setParent(obj.rectangle1); obj.edit1:setAlign("client"); obj.edit1:setField("nome"); obj.edit1:setName("edit1"); obj.layout1 = GUI.fromHandle(_obj_newObject("layout")); obj.layout1:setParent(obj.rectangle1); obj.layout1:setAlign("right"); obj.layout1:setWidth(275); obj.layout1:setName("layout1"); obj.edit2 = GUI.fromHandle(_obj_newObject("edit")); obj.edit2:setParent(obj.layout1); obj.edit2:setAlign("left"); obj.edit2:setWidth(200); obj.edit2:setField("efeito"); obj.edit2:setName("edit2"); obj.edit3 = GUI.fromHandle(_obj_newObject("edit")); obj.edit3:setParent(obj.layout1); obj.edit3:setAlign("left"); obj.edit3:setWidth(50); obj.edit3:setField("custo"); obj.edit3:setHorzTextAlign("center"); obj.edit3:setType("number"); obj.edit3:setName("edit3"); obj.dataLink1 = GUI.fromHandle(_obj_newObject("dataLink")); obj.dataLink1:setParent(obj.layout1); obj.dataLink1:setFields({'custo'}); obj.dataLink1:setName("dataLink1"); obj.button1 = GUI.fromHandle(_obj_newObject("button")); obj.button1:setParent(obj.layout1); obj.button1:setAlign("right"); obj.button1:setWidth(25); obj.button1:setText("X"); obj.button1:setName("button1"); obj._e_event0 = obj.dataLink1:addEventListener("onUserChange", function (_, field, oldValue, newValue) if sheet~= nil then local node = NDB.getRoot(sheet); local custo = 0; local nodes = NDB.getChildNodes(node.rclVantagens); for i=1, #nodes, 1 do custo = custo + (tonumber(nodes[i].custo) or 0); end node.ppVantagens = custo end; end, obj); obj._e_event1 = obj.button1:addEventListener("onClick", function (_) Dialogs.confirmOkCancel("Tem certeza que quer apagar essa vantagem?", function (confirmado) if confirmado then NDB.deleteNode(sheet); end; end); end, obj); function obj:_releaseEvents() __o_rrpgObjs.removeEventListenerById(self._e_event1); __o_rrpgObjs.removeEventListenerById(self._e_event0); end; obj._oldLFMDestroy = obj.destroy; function obj:destroy() self:_releaseEvents(); if (self.handle ~= 0) and (self.setNodeDatabase ~= nil) then self:setNodeDatabase(nil); end; if self.edit3 ~= nil then self.edit3:destroy(); self.edit3 = nil; end; if self.edit2 ~= nil then self.edit2:destroy(); self.edit2 = nil; end; if self.button1 ~= nil then self.button1:destroy(); self.button1 = nil; end; if self.layout1 ~= nil then self.layout1:destroy(); self.layout1 = nil; end; if self.rectangle1 ~= nil then self.rectangle1:destroy(); self.rectangle1 = nil; end; if self.edit1 ~= nil then self.edit1:destroy(); self.edit1 = nil; end; if self.dataLink1 ~= nil then self.dataLink1:destroy(); self.dataLink1 = nil; end; self:_oldLFMDestroy(); end; obj:endUpdate(); return obj; end; function newfrmVantagemItem() local retObj = nil; __o_rrpgObjs.beginObjectsLoading(); __o_Utils.tryFinally( function() retObj = constructNew_frmVantagemItem(); end, function() __o_rrpgObjs.endObjectsLoading(); end); assert(retObj ~= nil); return retObj; end; local _frmVantagemItem = { newEditor = newfrmVantagemItem, new = newfrmVantagemItem, name = "frmVantagemItem", dataType = "", formType = "undefined", formComponentName = "form", title = "", description=""}; frmVantagemItem = _frmVantagemItem; Firecast.registrarForm(_frmVantagemItem); return _frmVantagemItem;
-- v. 0.2 -- Push subtitles to clipboard -- in linux needs xsel or xclip to work -- -- default keybinding to start/stop: Y -- verify which command to use (false if none is found) local clipboard = package.config:sub(1,1) == '\\' and 'clip.exe' or -- Windows (pcall(function () io.popen('pbcopy'):close() end)) and 'pbcopy' or -- MacOS os.execute('xsel -h > /dev/null 2>&1') and 'xsel -z -b' or -- xsel os.execute('xclip -h > /dev/null 2>&1') and 'xclip -i -selection clipboard' -- xclip local running local function toclipboard(name, value) if running and type(value) == 'string' then io.popen(clipboard, 'w'):write(value):close() end end local function stop() running = false mp.msg.warn('Quitting Yomichampv ...') mp.unregister_event('end-file', stop) mp.unobserve_property('sub-text', 'string', toclipboard) mp.remove_key_binding('Yomichampv-pause') mp.remove_key_binding('Yomichampv-resume') end -- get_active_subtrack from huglovefan/mpv-subside.lua local function get_active_subtrack () local l = mp.get_property_native('track-list') for _, t in ipairs(l) do if t.type == 'sub' and t.selected then return t.lang end end return 'no' end local function start_stop() if running then stop() mp.command('show-text "Quitting Yomichampv..."') else if get_active_subtrack() ~= 'ja' then mp.command('show-text "Select japanese subtitles before' .. ' starting Yomichampv."') else running = true mp.register_event('end-file', stop) mp.observe_property('sub-text', 'string', toclipboard) mp.add_forced_key_binding('mouse_leave', 'Yomichampv-pause', function () mp.set_property_native('pause', true) end) mp.add_forced_key_binding('mouse_move', 'Yomichampv-resume', function () mp.set_property_native('pause', false) end) mp.command('show-text "Starting Yomichampv..."') end end end mp.add_key_binding('y', 'start-stop-Yomichampv', start_stop)
AddCSLuaFile() ENT.Type = "point" util.PrecacheSound("ZMPower.PhysExplode_Buildup") util.PrecacheSound("ZMPower.PhysExplode_Boom") function ENT:DelayedExplode(delay) self:SetSolid( SOLID_NONE ) self:AddEffects( EF_NODRAW ) self:SetMoveType( MOVETYPE_NONE ) self:CreateDelayEffects(delay) self:NextThink(CurTime() + delay) self.delayset = true end function ENT:Think() if self.bPendingDelete then return end if self.delayset then self:EmitSound("ZMPower.PhysExplode_Boom") if SERVER then //make players in range drop their stuff, radius is cvar'd for _, ent in pairs(ents.FindInSphere(self:LocalToWorld(self:OBBCenter()), GetConVar("zm_physexp_forcedrop_radius"):GetFloat())) do if IsValid(ent) and not ent:IsPlayer() then DropEntityIfHeld(ent) end end end //actual physics explosion local entity = ents.Create( "env_physexplosion" ) if IsValid( entity ) then for _, ent in pairs(ents.FindInSphere(self:LocalToWorld(self:OBBCenter()), ZM_PHYSEXP_RADIUS)) do ent:SetPhysicsAttacker(self) end entity:SetPos( self:GetPos() ) entity:SetKeyValue( "magnitude", ZM_PHYSEXP_DAMAGE ) entity:SetKeyValue( "radius", ZM_PHYSEXP_RADIUS ) entity:Spawn() local spawnflags = bit.bor(SF_PHYSEXPLOSION_NODAMAGE, SF_PHYSEXPLOSION_DISORIENT_PLAYER) entity:SetKeyValue( "spawnflags", spawnflags ) entity:Activate() timer.Simple(0.1, function() entity:Fire( "Explode", "", 0 ) entity:Fire( "Kill", "", 0.5 ) end) end //another run for good measure local effectdata = EffectData() effectdata:SetOrigin(self:GetPos()) effectdata:SetMagnitude(15) effectdata:SetScale(3) util.Effect("Sparks",effectdata) self.sparks:Remove() self.bPendingDelete = true self:AddEFlags(EFL_DORMANT) //TGB: clean ourselves up, else we stay around til round end timer.Simple(10, function() if not IsValid(self) then return end self:Remove() end) return true end end function ENT:CreateDelayEffects(delay) if self.bPendingDelete then return end self:EmitSound("ZMPower.PhysExplode_Buildup") //TGB: we want a particle effect instead local effectdata = EffectData() effectdata:SetOrigin(self:GetPos()) effectdata:SetMagnitude(1) effectdata:SetScale(5) util.Effect("Sparks",effectdata) self.sparks = ents.Create("env_spark") local ent = self.sparks if IsValid(ent) then local SF_SPARK_START_ON = 64 local SF_SPARK_GLOW = 128 local SF_SPARK_SILENT = 256 local spawnflags = bit.bor(ent:GetSpawnFlags(), SF_SPARK_START_ON, SF_SPARK_GLOW, SF_SPARK_SILENT ) ent:SetKeyValue("spawnflags", spawnflags) ent:SetKeyValue("MaxDelay", 0.1) ent:SetKeyValue("Magnitude", 2) ent:SetKeyValue("TrailLength", 1.5) //modify delay to account for delayed dying of sparker delay = delay - 2.2 ent:SetKeyValue("DeathTime", (CurTime() + delay)) ent:Spawn() ent:SetPos(self:GetPos()) end end
function love.conf(t) t.window.width = 100 * 6 t.window.height = 100 * 6 end
return {'asfa','asfalt','asfaltbaan','asfaltbestrating','asfaltbeton','asfaltcentrale','asfalteren','asfaltering','asfalthelling','asfaltjeugd','asfaltlaag','asfaltlucht','asfaltpapier','asfaltspreider','asfaltweg','asfaltdakwerk','asfaltjungle','asfaltpad','asfaltfabriek','asfaltfietspad','asfaltverharding','asfaltbekleding','asfaltmengsel','asfalteer','asfalteerde','asfalteerden','asfalteert','asfaltwegen','asfaltweggetje','asfaltbaantje','asfaltlagen','asfaltmengsels','asfaltbanen','asfaltbekledingen','asfaltpaadje'}
/*============================================================================================== Expression Advanced: Entitys. Creditors: Rusketh, Oskar94 ==============================================================================================*/ local LEMON, API = LEMON, LEMON.API local Core = API:GetComponent( "core" ) /*============================================================================================== Section: Class and Operators ==============================================================================================*/ local WireLink = Core:NewClass( "wl", "wirelink" ) WireLink:Extends( "e" ) WireLink:Wire_Name( "WIRELINK" ) function WireLink.Wire_In( Context, Cell, Value ) Context.Memory[ Cell ] = Value end Core:SetPerf( LEMON_PERF_CHEAP ) Core:AddOperator( "default", "wl", "wl", "%NULL_ENTITY" ) -- Get Port Operators: Core:SetPerf( LEMON_PERF_NORMAL ) Core:AddOperator( "[]", "wl,s,n", "n", [[%context:FromWL( value %1, "NORMAL", value %2, 0 )]] ) Core:AddOperator( "[]", "wl,s,s", "s", [[%context:FromWL( value %1, "STRING", value %2, "" )]] ) Core:AddOperator( "[]", "wl,s,e", "e", [[%context:FromWL( value %1, "ENTITY", value %2, %NULL_ENTITY )]] ) Core:AddOperator( "[]", "wl,s,v", "v", [[Vector3( %context:FromWL( value %1, "VECTOR", value %2, Vector( 0, 0, 0) ) )]] ) Core:AddOperator( "[]", "wl,s,a", "a", [[%context:FromWL( value %1, "ANGLE", value %2, Angle( 0, 0, 0) )]] ) -- Set Port Operators: Core:SetPerf( LEMON_PERF_ABNORMAL ) Core:AddOperator( "[]=", "wl,s,n", "", [[%context:ToWL( value %1, "NORMAL", value %2, value %3 )]], "" ) Core:AddOperator( "[]=", "wl,s,s", "", [[%context:ToWL( value %1, "STRING", value %2, value %3 )]], "" ) Core:AddOperator( "[]=", "wl,s,e", "", [[%context:ToWL( value %1, "ENTITY", value %2, value %3 )]], "" ) Core:AddOperator( "[]=", "wl,s,v", "", [[%context:ToWL( value %1, "VECTOR", value %2, value %3:Garry() )]], "" ) Core:AddOperator( "[]=", "wl,s,a", "", [[%context:ToWL( value %1, "ANGLE", value %2, value %3 )]], "" ) /*============================================================================================== Port Functions ==============================================================================================*/ Core:SetPerf( LEMON_PERF_NORMAL ) Core:AddFunction("entity", "wl:", "e", "value %1") Core:AddFunction("hasInput", "wl:s", "b", "local %WL = value %1", "($IsValid( %WL ) and %WL.Inputs and %WL.Inputs[%value2])" ) Core:AddFunction("hasOutput", "wl:s", "b", "local %WL = value %1", "($IsValid( %WL ) and %WL.Outputs and %WL.Outputs[%value2])" ) Core:AddFunction("isHiSpeed", "wl:", "b", "local %WL = value %1", "($IsValid( %WL ) and (%WL.WriteCell or %WL.ReadCell))" ) Core:AddFunction("inputType", "wl:s", "s", [[ local %WL, %Val = value %1, "void" if $IsValid(%WL) and %WL.Inputs then %Input = %WL.Inputs[value %2] %Val = (%Input ~= null and string.lower(%Input.Type) or "void") end]], "%Val" ) Core:AddFunction("outputType", "wl:s", "s", [[ local %WL, %Val = value %1, "void" if $IsValid(%WL) and %WL.Outputs then %Output = %WL.Outputs[value %2] %Val = (%Output ~= null and string.lower(%Output.Type) or "void") end]], "%Val" ) /*============================================================================================== Cell Writing ==============================================================================================*/ Core:SetPerf( LEMON_PERF_EXPENSIVE ) Core:AddFunction("writeCell", "wl:n,n", "b", [[ local %WL, %Val = value %1, false if $IsValid(%WL) and %WL.WriteCell then %Val = %WL:WriteCell(value %2, value %3) or false end]], "%Val" ) Core:AddFunction("readCell", "wl:n", "n", [[ local %WL, %Val = value %1, 0 if $IsValid(%WL) and %WL.ReadCell then %Val = %WL:ReadCell(value %2) or 0 end]], "%Val" ) Core:AddFunction("readArray", "wl:n,n", "t", [[ local %WL, %Result = value %1, %Table() if $IsValid(%WL) and %WL.ReadCell then local Start = value %2 for I = Start, Start + value %3 do %Result:Insert( nil, "n", %WL:ReadCell(I) or 0 ) end end]], "%Result" ) /*============================================================================================== Indexing ==============================================================================================*/ -- Read Cell: Core:AddOperator( "[]", "wl,n", "n", [[ local %WL, %Val = value %1, 0 if $IsValid( %WL ) and %WL.ReadCell then %Val = %WL:ReadCell( value %2 ) or 0 end]], "%Val" ) Core:AddOperator( "[]", "wl,n, n", "n", [[ local %WL, %Val = value %1, 0 if $IsValid( %WL ) and %WL.ReadCell then %Val = %WL:ReadCell( value %2 ) or 0 end]], "%Val" ) Core:AddOperator( "[]", "wl,n,v", "v", [[ local %WL, %Val = value %1, { 0, 0, 0 } if $IsValid( %WL ) and %WL.ReadCell then local Cell = value %2 %Val = Vector3( %WL:ReadCell( Cell ) or 0, %WL:ReadCell( Cell + 1 ) or 0, %WL:ReadCell( Cell + 2 ) or 0 ) end]], "%Val" ) Core:AddOperator( "[]", "wl,n,s", "s", [[ local %WL, %Val = value %1, "" if $IsValid( %WL ) and %WL.ReadCell then local Cell= value %2 for I = Cell, Cell + 16384 do local Byte = %WL:ReadCell(I, Byte) if !Byte then %Val = ""; break elseif Byte < 1 then break elseif byte >= 256 then %Val = %Val .. string.char( 32 ) else %Val = %Val .. string.char( math.floor( Byte ) ) end end end]], "%Val" ) -- Set Cell: Core:AddOperator( "[]=", "wl,n,b", "", [[ local %WL = value %1 if $IsValid(%WL) and %WL.WriteCell then %WL:WriteCell( value %2, value %3 and 1 or 0 ) end]], "" ) Core:AddOperator( "[]=", "wl,n,n", "", [[ local %WL = value %1 if $IsValid(%WL) and %WL.WriteCell then %WL:WriteCell( value %2, value %3 ) end]], "" ) Core:AddOperator( "[]=", "wl,n,v", "", [[ local %WL = value %1 if $IsValid(%WL) and %WL.WriteCell then local %Cell, %Vec = value %2, value %3 %WL:WriteCell( %Cell, %Vec.x ) %WL:WriteCell( %Cell + 1, %Vec.y ) %WL:WriteCell( %Cell + 2, %Vec.z ) end]], "" ) Core:AddOperator( "[]=", "wl,n,s", "", [[ local %WL = value %1 if $IsValid(%WL) and %WL.WriteCell then local Cell, String = value %2, value %3 if %WL:WriteCell( Cell + #String, 0 ) then for I = 1, #String do local Byte = string.byte(String, I) if !%WL:WriteCell(Cell + I - 1, Byte) then break end end end end]], "" ) /*============================================================================================== Console Screens: Just gona use an external to save time =D ==============================================================================================*/ local Clamp = math.Clamp local ToByte = string.byte local function ToColor( Col ) local R = Clamp( Floor(Col[1] / 28), 0, 9 ) local G = Clamp( Floor(Col[2] / 28), 0, 9 ) local B = Clamp( Floor(Col[3] / 28), 0, 9 ) return math.Clamp( Floor(R) * 100 + Floor(G) * 10 + Floor(B), 0, 999 ) end Core:AddExternal( "WriteToScreen", function( Entity, String, X, Y, TextColor, BackGround, Flash ) if IsValid( Entity ) and Entity.WriteCell then TextColor = ( Colour and ToColor( TextColor ) or 999 ) BackGround = ( BackGround and ToColor( BackGround ) or 0 ) Flash = Flash and 1 or 0 local Peram, Xorig = Flash * 1000000 + BackGround * 1000 + TextColor, X for I = 1, #String do local Byte = ToByte(String, I) if Byte == 10 then Y = Y + 1 X = Xorig else if X >= 30 then X = 0 Y = Y + 1 end local Address = 2 * (Y * 30 + X) X = X + 1 if Address >= 1080 or Address < 0 then return end Entity:WriteCell(Address, Byte) Entity:WriteCell(Address + 1, Peram) end end end end ) Core:SetPerf( LEMON_PERF_EXPENSIVE * 2 ) Core:AddFunction("writeString", "wl:s,n,n", "", "%WriteToScreen( value %1, value %2, value %3, value %4, value %5, value %6 )", "" ) Core:AddFunction("writeString", "wl:s,n,n,n", "", "%WriteToScreen( value %1, value %2, value %3, value %4, value %5, value %6 )", "" ) Core:AddFunction("writeString", "wl:s,n,n,c", "", "%WriteToScreen( value %1, value %2, value %3, value %4, value %5, value %6 )", "" ) Core:AddFunction("writeString", "wl:s,n,n,n,n", "", "%WriteToScreen( value %1, value %2, value %3, value %4, value %5, value %6 )", "" ) Core:AddFunction("writeString", "wl:s,n,n,c,c", "", "%WriteToScreen( value %1, value %2, value %3, value %4, value %5, value %6 )", "" ) Core:AddFunction("writeString", "wl:s,n,n,c,n", "", "%WriteToScreen( value %1, value %2, value %3, value %4, value %5, value %6 )", "" ) Core:AddFunction("writeString", "wl:s,n,n,n,c", "", "%WriteToScreen( value %1, value %2, value %3, value %4, value %5, value %6 )", "" ) Core:AddFunction("writeString", "wl:s,n,n,n,n,b", "", "%WriteToScreen( value %1, value %2, value %3, value %4, value %5, value %6 )", "" ) Core:AddFunction("writeString", "wl:s,n,n,c,c,b", "", "%WriteToScreen( value %1, value %2, value %3, value %4, value %5, value %6 )", "" ) Core:AddFunction("writeString", "wl:s,n,n,c,n,b", "", "%WriteToScreen( value %1, value %2, value %3, value %4, value %5, value %6 )", "" ) Core:AddFunction("writeString", "wl:s,n,n,n,c,b", "", "%WriteToScreen( value %1, value %2, value %3, value %4, value %5, value %6 )", "" )
--[[ © 2018 Thriving Ventures AB do not share, re-distribute or modify without permission of its author (gustaf@thrivingventures.com). ]] local plugin = plugin local category = {} local delay = 0 category.name = "MOTD" category.material = "serverguard/menuicons/icon_motd.png" category.permissions = "Manage MOTD" function category:Create(base) base.panel = base:Add("tiger.panel") base.panel:SetTitle("MOTD management") base.panel:Dock(FILL) base.panel.config = base.panel:Add("tiger.panel") base.panel.config:SetTall(68) base.panel.config:Dock(BOTTOM) base.panel.config:DockPadding(8, 8, 8, 8) base.panel.configTop = base.panel.config:Add("Panel") base.panel.configTop:SetTall(22) base.panel.configTop:Dock(TOP) base.panel.configSpacer = base.panel.config:Add("Panel") -- docking is wonky, so we need spacer panels base.panel.configSpacer:SetTall(8) base.panel.configSpacer:Dock(TOP) base.panel.configBottom = base.panel.config:Add("Panel") base.panel.configBottom:SetTall(22) base.panel.configBottom:Dock(FILL) base.panel.spacer = base.panel:Add("Panel") base.panel.spacer:SetTall(24) base.panel.spacer:Dock(BOTTOM) category.html = base.panel:Add("DHTML") category.html:SetHTML(plugin.defaultHTML) category.html:Dock(FILL) base.panel.unlockType = base.panel.configTop:Add("DComboBox") base.panel.unlockType:SetWide(150) base.panel.unlockType:Dock(LEFT) base.panel.unlockType:SetText("Unlock Type") base.panel.unlockType:SetFont("tiger.button") base.panel.unlockType:SetSkin("serverguard") base.panel.unlockType:AddChoice("Slider") base.panel.unlockType:AddChoice("Button") base.panel.unlockType:SetToolTipSG("Changes how the MOTD closes.") function base.panel.unlockType:OpenMenu(pControlOpener) DComboBox.OpenMenu(self, pControlOpener) self.Menu:SetSkin("serverguard") end function base.panel.unlockType:OnSelect(index, value, data) local unlockType = "slider" if (value == "Button") then unlockType = "button" end serverguard.netstream.Start("sgUpdateMOTDConfig", { uniqueID = "Unlock Type", value = unlockType }) end base.panel.spacer = base.panel.configTop:Add("Panel") base.panel.spacer:SetWide(8) base.panel.spacer:Dock(LEFT) category.url = base.panel.configTop:Add("DTextEntry") category.url:Dock(FILL) category.url:SetSkin("serverguard") category.url:SetToolTipSG("The website to load when opened.") function category.url:OnEnter() serverguard.netstream.Start("sgUpdateMOTDConfig", { uniqueID = "URL", value = category.url:GetValue() }) end base.panel.delayLabel = base.panel.configBottom:Add("DLabel") base.panel.delayLabel:SetMouseInputEnabled(true) base.panel.delayLabel:SetFont("tiger.button") base.panel.delayLabel:SetText("Delay ") base.panel.delayLabel:SetSkin("serverguard") base.panel.delayLabel:SizeToContents() base.panel.delayLabel:Dock(LEFT) base.panel.delayLabel:SetToolTipSG("How long you need to wait before you can close the MOTD.") category.delayPanel = base.panel.configBottom:Add("Slider") category.delayPanel:SetTall(22) category.delayPanel:SetSkin("serverguard") category.delayPanel:Dock(FILL) category.delayPanel:SetDecimals(0) category.delayPanel:SetMin(0) category.delayPanel:SetMax(10) category.delayPanel:SetValue(0) category.delayPanel.amount = delay function category.delayPanel:OnValueChanged(value) value = math.Round(value) if (value ~= category.delayPanel.amount) then serverguard.netstream.Start("sgUpdateMOTDConfig", { uniqueID = "Delay", value = value }) category.delayPanel.amount = value end end end function category:Update() serverguard.netstream.Start("sgRequestMOTDConfig", 1) end plugin:AddSubCategory("Server settings", category) serverguard.netstream.Hook("sgReceiveMOTDConfig", function(data) local config = data[1] for k, v in pairs(config) do if (k == "Delay") then delay = tonumber(v) if (IsValid(category.delayPanel)) then category.delayPanel.amount = tonumber(v) category.delayPanel:SetValue(tonumber(v)) end elseif (k == "URL") then if (IsValid(category.url)) then local url = tostring(v) category.url:SetValue(url) if (url == "") then category.html:SetHTML(plugin.defaultHTML) else category.html:OpenURL(url) end end end end end)
local lib, oldminor = LibStub:NewLibrary("tekKonfig-TopTab", 1) if not lib then return end oldminor = oldminor or 0 function lib:activatetab() self.left:ClearAllPoints() self.left:SetPoint("TOPLEFT") self.left:SetTexture("Interface\\OptionsFrame\\UI-OptionsFrame-ActiveTab") self.middle:SetTexture("Interface\\OptionsFrame\\UI-OptionsFrame-ActiveTab") self.right:SetTexture("Interface\\OptionsFrame\\UI-OptionsFrame-ActiveTab") self:Disable() end function lib:deactivatetab() self.left:ClearAllPoints() self.left:SetPoint("BOTTOMLEFT", 0, 2) self.left:SetTexture("Interface\\OptionsFrame\\UI-OptionsFrame-InActiveTab") self.middle:SetTexture("Interface\\OptionsFrame\\UI-OptionsFrame-InActiveTab") self.right:SetTexture("Interface\\OptionsFrame\\UI-OptionsFrame-InActiveTab") self:Enable() end function lib:SetTextHelper(...) self:SetWidth(40 + self:GetFontString():GetStringWidth()); return ... end function lib:NewSetText(...) return lib.SetTextHelper(self, self.OrigSetText(self, ...)) end function lib.new(parent, text, ...) local tab = CreateFrame("Button", nil, parent) tab:SetHeight(24) tab:SetPoint(...) tab:SetFrameLevel(tab:GetFrameLevel() + 4) tab.left = tab:CreateTexture(nil, "BORDER") tab.left:SetWidth(20) tab.left:SetHeight(24) tab.left:SetTexCoord(0, 0.15625, 0, 1) tab.right = tab:CreateTexture(nil, "BORDER") tab.right:SetWidth(20) tab.right:SetHeight(24) tab.right:SetPoint("TOP", tab.left) tab.right:SetPoint("RIGHT", tab) tab.right:SetTexCoord(0.84375, 1, 0, 1) tab.middle = tab:CreateTexture(nil, "BORDER") tab.middle:SetHeight(24) tab.middle:SetPoint("LEFT", tab.left, "RIGHT") tab.middle:SetPoint("RIGHT", tab.right, "Left") tab.middle:SetTexCoord(0.15625, 0.84375, 0, 1) tab:SetHighlightTexture("Interface\\PaperDollInfoFrame\\UI-Character-Tab-Highlight", "ADD") local hilite = tab:GetHighlightTexture() hilite:ClearAllPoints() hilite:SetPoint("LEFT", 10, -4) hilite:SetPoint("RIGHT", -10, -4) tab:SetDisabledFontObject(GameFontHighlightSmall) tab:SetHighlightFontObject(GameFontHighlightSmall) tab:SetNormalFontObject(GameFontNormalSmall) tab.OrigSetText = tab.SetText tab.SetText = lib.NewSetText tab:SetText(text) tab.Activate, tab.Deactivate = lib.activatetab, lib.deactivatetab tab:Activate() return tab end
---------------------- -------------------- -- Table Functions ---------------- -------------- ------------ ---------- -------- ------ ---- -- ------------------ -- Private Functions -------- ------ ---- -- -- Insert element property into `t` -- based on index type. -- -- @private -- Note: assumes `t` is a table. local __insert = function(t, k, v) if _:isNumber(k) then _.__insert(t, v) else t[k] = v end return t end local __remove = function(t, k, v) if _:isNumber(k) then _.__remove(t, k, v) else t[k] = nil end return t end -- Returns table of keys from `t` in -- natural order -- -- Credit: [lua-users](http://lua-users.org/wiki/SortedIteration) local __orderedKeys = function(t) local keys = {} _:i('len', 0) for k, v in pairs(t) do keys[_:up('len')] = k end -- sort, multi-type _.__sort(keys, function(a, b) local at = _.__type(a) local bt = _.__type(b) if at ~= bt then return at < bt elseif _:isString(at) or _:isNumber(at) then return a < b elseif _:isBoolean(at) then return at == true else return tostring(a) < tostring(b) end end) return keys end -- Imitates next(t, state). -- Returns next key/value pair in -- natural order. -- -- Credit: [lua-users](http://lua-users.org/wiki/SortedIteration) local __next = function(t, state) local key = nil if state == nil then t.__orderedIndex = __orderedKeys(t) key = t.__orderedIndex[1] else for i = 1, #t.__orderedIndex do if t.__orderedIndex[i] == state then key = t.__orderedIndex[i + 1] end end end -- return next key/value pair.. if key then return key, t[key] end -- done. t.__orderedIndex = nil return end -- Imitates pairs(t). -- Iterates over `t` in natural order. local __iterator = function(t) return __next, t, nil end ------------------ -- Public Functions -------- ------ ---- -- -- _:chunk(tabl, [size=1]) -- Splits elements of `tabl` into groups of `size`. -- -- @param table(tabl) - table to process -- @param number([size=1]) - length of each chunk -- @return table function _:chunk(tabl, size) tabl = _:assertArgument('tabl', tabl, 'table') size = _:assertArgument('size', size, 'number', 1) -- local out, sub = {}, {} local max = _:size(tabl) local cnt = 0 for k, v in __iterator(tabl) do sub = __insert(sub, k, v) cnt = cnt + 1 if cnt % size == 0 or cnt == max then _.__insert(out, sub) sub = {} -- reset end end return out end -- _:combine(keys, values) -- creates new `tabl` with `keys` as the -- keys and `values` as the values. -- -- requirement: -- both tables must be equal in size -- -- @param table(keys) - keys table -- @param table(values) - values table -- @return table function _:combine(keys, values) keys = _:assertArgument('keys', keys, 'table') values = _:assertArgument('values', values, 'table') _:assertEqualSize('tabl', keys, values) -- local out = {} local k2, v2 for k1, v1 in __iterator(keys) do k2, v2 = __next(values, k2) __insert(out, v1, v2) end return out end -- _:compact(tabl) -- Creates copy of `tabl` with Lua-falsy -- values filtered out. -- -- @param table(tabl) -- @return table function _:compact(tabl) tabl = _:assertArgument('tabl', tabl, 'table') -- return _:filter(tabl, 'isTruthy') end -- _:conformsTo(value, source) -- Determines if `value` conforms to `source`, -- by invoking the predicate properties of source -- with corresponding propery values of `value`. -- -- @param table(value) -- @param table(source) -- @return boolean function _:conformsTo(tabl, source) tabl = _:assertArgument('tabl', tabl, 'table') source = _:assertArgument('source', source, 'table') -- for k, v in pairs(tabl) do if _:isFunction(source[k]) then local stat, conform = _:attempt(source[k], v, k) if stat and conform == false then return false end end end return true end -- _:difference(tabl, other) -- Creates copy of `tabl`, excluding any same -- values from `other`. -- -- @param table(tabl) - table to process -- @param table(other) - compare table -- @return table function _:difference(tabl, other) tabl = _:assertArgument('tabl', tabl, 'table') other = _:assertArgument('other', other, 'table') -- -- local out = _:copy(tabl) local keys = {} local values = {} -- create reference table... for k, v in pairs(other) do keys[k] = true values[v] = true end -- ...now exclude for k, v in pairs(out) do if keys[k] and values[v] then out[k] = nil end end -- return out end -- _:flatten(tabl) -- Creates new `tabl` flattened one level deep. -- -- @param table(tabl) - table to flatten -- @return table function _:flatten(tabl) tabl = _:assertArgument('tabl', tabl, 'table') -- local out = {} for k1, v1 in __iterator(tabl) do if _:isTable(v1) then for k2, v2 in __iterator(v1) do __insert(out, k2, v2) end else __insert(out, k1, v1) end end return out end -- _:flattenDeep(tabl) -- Creates new `tabl`, recursively flattening table. -- -- @param table(tabl) - table to flatten -- @return table function _:flattenDeep(tabl) tabl = _:assertArgument('tabl', tabl, 'table') -- local function flatten(out, values) for k, v in __iterator(values) do if _:isTable(v) then flatten(out, v) else __insert(out, k, v) end end return out end return flatten({}, tabl) end -- _:filter(tabl, iteratee) -- Creates copy of `tabl` with values that fail -- `iteratee` filtered out. -- -- Note: -- `iteratee` will receive arguments: -- * `value` -- * `key` -- Warning: -- Lua tables are volitile when it comes to -- manipulating keys manually. -- -- @param table(tabl) -- @param function(iteratee) -- @return table function _:filter(tabl, iteratee) tabl = _:assertArgument('tabl', tabl, 'table') iteratee = _:assertArgument('tabl', iteratee, 'function') -- local out = {} for k, v in __iterator(tabl) do local stat, passed = _:attempt(iteratee, v, k) if stat and passed == true then __insert(out, k, v) end end return out end -- _:find(tabl, predicate) -- Return first element in `tabl`, which -- `predicate` returns a truthy value. -- -- @param table(tabl) - table to fill -- @param function(predicate) - function ivoked per element -- @return mixed(v), mixed(k) function _:find(tabl, predicate) tabl = _:assertArgument('tabl', tabl, 'table') predicate = _:assertArgument('predicate', predicate, 'function') -- for k, v in __iterator(tabl) do local stat, res = _:attempt(predicate, v, k) if stat and _:isTruthy(res) then return v, k end end end -- _:keys(tabl) -- Creates new table made up of keys from `tabl`. -- -- @param table(tabl) -- @return table function _:keys(tabl) tabl = _:assertArgument('tabl', tabl, 'table') -- return __orderedKeys(tabl) end -- _:map(tabl, iteratee) -- Creates new table executing `iteratee` -- on every element of `tabl`. -- -- @param table(keys) - keys table -- @param function(iteratee) - values table -- @return table function _:map(tabl, iteratee) tabl = _:assertArgument('tabl', tabl, 'table') iteratee = _:assertArgument('iteratee', iteratee, 'function') -- local out = {} for k, v in __iterator(tabl) do __insert(out, k, _:force(iteratee, v, k)) end return out end -- _:merge(...) -- Creates new table merging from left to right. -- -- Warning: -- Overwritting may occur. -- -- @param table(keys) - keys table -- @param function(iteratee) - values table -- @return table function _:merge(...) local out = {} for _k, tabl in ipairs({...}) do if _:isTable(tabl) then for k, v in __iterator(tabl) do __insert(out, k, v) end end end return out end -- _:resize(tabl, size) -- Creates copy of `tabl`, resized to `size`. -- -- @param table(tabl) -- @param number(size) -- @return table function _:resize(tabl, size) tabl = _:assertArgument('tabl', tabl, 'table') size = _:assertArgument('size', size, 'number') -- local currSize = _:size(tabl) local newSize = currSize - _:abs(size) newSize = _.__max(0, newSize) if _:isNegative(size) then newSize = newSize * -1 end return _:drop(tabl, newSize) end -- _:unique(tabl) -- Creates unique set of elements, dropping duplicate indices. -- -- @param table(tabl) -- @return table function _:unique(tabl) tabl = _:assertArgument('tabl', tabl, 'table') -- local out = {} local values = {} for k, v in __iterator(tabl) do if not values[v] then out[k] = v values[v] = true end end return out end -- _:values(tabl) -- Creates new table made up of values from `tabl`. -- -- @param table(tabl) -- @return table function _:values(tabl) tabl = _:assertArgument('tabl', tabl, 'table') -- local out = {} _:i('i', 0) for k, v in __iterator(tabl) do __insert(out, _:up('i'), v) end return out end
local penisx = -600 local penisy = -400 function onCreate() -- le bg fuckin shit makeLuaSprite('bg', 'bgs/syn/SynTech', -400, -300); scaleObject('bg',0.7,0.7); setLuaSpriteScrollFactor('bg', 0.9, 0.9); makeLuaSprite('wires', 'bgs/syn/SynTechwires', -500, -70); scaleObject('wires',0.7,0.7); setLuaSpriteScrollFactor('wires', 1.3,1.3); --NOOO STEP-SNUSSY TECHHHHH IT WASNT MEEEE I WAS IN ELECTRICAL FIXING WIRES :((((( addLuaSprite('bg', false); addLuaSprite('wires', false); close(true); --For performance reasons, close this script once the stage is fully loaded, as this script won't be used anymore after loading the stage end
local t = require('luatest') local log = require('log') local Cluster = require('test.luatest_helpers.cluster') local server = require('test.luatest_helpers.server') local pg = t.group('no_quorum', {{engine = 'memtx'}, {engine = 'vinyl'}}) pg.before_each(function(cg) local engine = cg.params.engine cg.cluster = Cluster:new({}) cg.master = cg.cluster:build_server({alias = 'master', engine = engine}) local box_cfg = { listen = server.build_instance_uri('no_quorum'), replication = server.build_instance_uri('master'), memtx_memory = 107374182, replication_connect_quorum = 0, replication_timeout = 0.1, } cg.replica = cg.cluster:build_server( {alias = 'no_quorum', engine = engine, box_cfg = box_cfg}) pcall(log.cfg, {level = 6}) end) pg.after_each(function(cg) cg.cluster.servers = nil end) pg.before_test('test_replication_no_quorum', function(cg) local engine = cg.params.engine cg.cluster:add_server(cg.master) cg.cluster:add_server(cg.replica) cg.master:start() cg.master:eval(("space = box.schema.space.create('test', {engine = '%s'})"):format(engine)) cg.master:eval("index = space:create_index('primary')") end) pg.after_test('test_replication_no_quorum', function(cg) cg.cluster:drop() end) pg.test_replication_no_quorum = function(cg) -- gh-3278: test different replication and replication_connect_quorum configs. -- Insert something just to check that replica with quorum = 0 works as expected. t.assert_equals(cg.master:eval("return space:insert{1}"), {1}) cg.replica:start() t.assert_equals( cg.replica:eval('return box.space.test:select()'), {{1}}) cg.replica:stop() cg.master:eval("return box.cfg{listen = ''}") cg.replica:start() -- Check that replica is able to reconnect, case was broken with earlier quorum "fix". cg.master:eval("return box.cfg{listen = os.getenv('TARANTOOL_LISTEN')}") t.assert_equals(cg.master:eval("return space:insert{2}"), {2}) cg.replica:wait_vclock_of(cg.master) t.assert_str_matches( cg.replica:eval('return box.info.status'), 'running') t.assert_equals(cg.master:eval("return space:select()"), {{1}, {2}}) t.assert_equals( cg.replica:eval('return box.space.test:select()'), {{1}, {2}}) end
require "busted" local DurstenfeldShuffle = require "DurstenfeldShuffle" describe("Durstenfeld Shuffle | ", function() test("Shuffle zero element; Should Return zero element", function() -- Arrange local t1 = {} -- Act local t2 = DurstenfeldShuffle:shuffle(t1) -- Assert assert.is.same(t1, t2) end) test("Shuffle one element; Should return itself", function() -- Arrange local t1 = {1} -- Act local t2 = DurstenfeldShuffle:shuffle(t1) -- Assert assert.is.same(t1, t2) end) test("Shuffle ten elements; Should be... different", function() -- Arrange local t1 = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} -- Act local t2 = DurstenfeldShuffle:shuffle(t1) -- Assert assert.is_not.same(t1, t2) end) end)