content
stringlengths
5
1.05M
--- CONFIG IN "CUSTOM OPTIONS" TAB - DO NOT TOUCH THIS --- aura_env.anchorConfValues = { [1] = "TOP", [2] = "BOTTOM", [3] = "LEFT", [4] = "RIGHT", [5] = "CENTER", [6] = "TOPLEFT", [7] = "TOPRIGHT", [8] = "BOTTOMLEFT", [9] = "BOTTOMRIGHT", } -- check if ElvUI is used and the nameplates module is enabled aura_env.useElvUINameplates = ElvUI and ElvUI[1].NamePlates -- check if KuiNameplates are used aura_env.useKuiNameplates = KuiNameplates ~= nil -- check if Tidy Plates are used aura_env.useTidyPlates = TidyPlates ~= nil aura_env.usePlater = Plater ~= nil aura_env.isMDTInstalled = MethodDungeonTools ~= nil and MethodDungeonTools.GetEnemyForces ~= nil if not aura_env.isMDTInstalled then print(("%s require to enable MethodDungeonTools"):format(aura_env.id)) end aura_env.updateTeeming = function() local _, affixes = C_ChallengeMode.GetActiveKeystoneInfo() aura_env.teeming = false for _, affixID in ipairs(affixes) do if affixID == 5 then aura_env.teeming = true end end end aura_env.NEAupdateRegion = function(state) if state.isMaster then return end local region = WeakAuras.GetRegion(aura_env.id, state.cloneId) state.nameplate = state.nameplate or C_NamePlate.GetNamePlateForUnit(state.unit) if not state.nameplate or not state.show then return end local xOffset = aura_env.config["xOffset"] local yOffset = aura_env.config["yOffset"] if aura_env.useElvUINameplates then region:SetAnchor(aura_env.anchorConfValues[aura_env.config["anchorPoint"]], state.nameplate.unitFrame.Health, aura_env.anchorConfValues[aura_env.config["relativeAnchor"]]) elseif aura_env.useTidyPlates then region:SetAnchor(aura_env.anchorConfValues[aura_env.config["anchorPoint"]], state.nameplate.extended.bars.healthbar, aura_env.anchorConfValues[aura_env.config["relativeAnchor"]]) elseif aura_env.useKuiNameplates then region:SetAnchor(aura_env.anchorConfValues[aura_env.config["anchorPoint"]], state.nameplate.kui.HealthBar, aura_env.anchorConfValues[aura_env.config["relativeAnchor"]]) elseif aura_env.usePlater then region:SetAnchor(aura_env.anchorConfValues[aura_env.config["anchorPoint"]], state.nameplate.unitFrame.healthBar, aura_env.anchorConfValues[aura_env.config["relativeAnchor"]]) else region:SetAnchor(aura_env.anchorConfValues[aura_env.config["anchorPoint"]], state.nameplate, aura_env.anchorConfValues[aura_env.config["relativeAnchor"]]) end region:SetOffset(xOffset, yOffset) region:Show() end aura_env.GetMobCount = function() local _,_,steps = C_Scenario.GetStepInfo() local percent, total,_,_,current = select(4, C_Scenario.GetCriteriaInfo(steps)) if current then current = tonumber(string.sub(current, 1, string.len(current) - 1)) or 0 current = (current / total) * 100 return current or 0 end return 0 end
--[[ Workshop: https://steamcommunity.com/sharedfiles/filedetails/?id=2523149203 Profile Page: https://steamcommunity.com/id/Piengineer12 GitHub Page: https://github.com/Piengineer12/public-addons/tree/master/hacpg Donate: https://ko-fi.com/piengineer12 Links above are confirmed working as of 2021-06-21. All dates are in ISO 8601 format. VERSION = 1.0.1 VERSION_DATE = 2021-06-21 ]] AddCSLuaFile() ENT.Base = "base_anim" ENT.Type = "anim" ENT.Category = "HACPG" ENT.PrintName = "Particle Generator" ENT.Author = "Piengineer" ENT.Contact = "https://steamcommunity.com/id/Piengineer12/" ENT.Purpose = "Highly Advanced Customizable Particle Generator" ENT.Instructions = "Use and see." ENT.Spawnable = true --ENT.AdminOnly = false ENT.RenderGroup = RENDERGROUP_OPAQUE --ENT.DisableDuplicator = false --ENT.DoNotDuplicate = false --ENT.IconOverride = "materials/entities/base.png" --ENT.AutomaticFrameAdvance = false --ENT.Editable = false ENT.ClientHACPGVarInfo = { { name = "Particle Density", options = { { class = "BurstDelay", type = "Float", min = 0, max = 10, name = "Burst Delay", desc = "Time between bursts." }, { class = "ParticlesPerBurst", type = "Int", min = 1, max = 100, name = "Particles Per Burst", desc = "Number of particles to create per burst." }, { class = "BurstDuration", type = "Float", min = 0, max = 10, name = "Burst Duration", desc = "Amount of time to spend spawning particles within a burst." }, } }, { name = "Particle Spawning", options = { { class = "LifeTime", type = "Float", min = 0, max = 10, name = "Life Time", desc = "How long each particle lasts." }, { class = "Origin", type = "Vector", minmax = false, min = -500, max = 500, name = "Origin Offset", desc = "The origin's offset from the center of the emitter." }, { class = "SpawnDistance", type = "Float", min = 0, max = 1000, name = "Spawn Distance From Origin", desc = "Particle spawn distance from the origin of the particle emitter." }, { class = "SpawnOffset", type = "Vector", min = -500, max = 500, name = "Spawn Offset", desc = "The origin's offset from the center of the emitter." }, { class = "ParticleAngles", type = "Angle", name = "Spawn Angle", desc = "Angle of particles when spawned. If 2D, only the roll component is used." }, } }, { name = "Particle Rendering", options = { { class = "MaterialList", type = "MaterialList", name = "Materials", desc = "Materials that the particles should be animated from. At least 1 material is required." }, { class = "3D", name = "3D Particles", desc = "Allows particles to be rendered in 3D, unlike 2D particles which always face the player." }, { class = "StartSize", type = "Float", min = 0, max = 100, name = "Starting Size", desc = "Size of particles right after spawning." }, { class = "EndSize", type = "Float", min = 0, max = 100, name = "Ending Size", desc = "Size of particles right before dying." }, { class = "ParticleColor", type = "Color", name = "Color", desc = "Color of particles. Note that colors are applied subtractively." }, { class = "Unlit", name = "Always Bright", desc = "Causes particles to be unaffected by darkness. Useful on dark maps." }, { class = "StartAlpha", type = "Int", min = 0, max = 255, name = "Starting Alpha", desc = "Opacity of particles right after spawning." }, { class = "EndAlpha", type = "Int", min = 0, max = 255, name = "Ending Alpha", desc = "Opacity of particles right before dying." }, { class = "StartLength", type = "Float", min = 0, max = 100, name = "Starting Length", desc = "Length of particles right after spawning." }, { class = "EndLength", type = "Float", min = 0, max = 100, name = "Ending Length", desc = "Length of particles right before dying." } } }, { name = "Particle Physics", options = { { class = "ParticleVelocity", type = "Vector", min = -500, max = 500, name = "Velocity", desc = "Particle velocity." }, { class = "VelocityFromOrigin", type = "Float", min = -500, max = 500, name = "Velocity From Origin", desc = "Particle outward velocity from the origin. Negative values cause particles to move towards the origin instead." }, { class = "ClockwiseVelocityFromOrigin", type = "Float", min = -500, max = 500, name = "Clockwise Velocity From Origin", desc = "Particle rightward velocity from the origin. Negative values cause particles to move leftwards instead." }, { class = "Acceleration", type = "Vector", min = -500, max = 500, name = "Acceleration", desc = "Particle acceleration. Can be used to simulate gravity." }, { class = "Orbiting", name = "Always Adjust Acceleration To Point Towards Origin", desc = "Causes particles to orbit around the origin." }, { class = "AngularVelocity", type = "Angle", mul = 10, name = "Angular Velocity", desc = "Angular velocity of particles. If 2D, only the roll component is used." }, { class = "CollisionsEnabled", name = "Collisions", desc = "Allows particles to collide with terrain." }, { class = "Bounciness", type = "Float", min = 0, max = 10, name = "Bounciness", desc = "Multiplier for velocity after any collision." }, { class = "AirResistance", type = "Float", min = 0, max = 100, name = "Air Resistance", desc = "Multiplier for how much air slows down each particle." } } }, } ENT.ServerHACPGVarInfo = {} for k,v in pairs(ENT.ClientHACPGVarInfo) do for k2,v2 in pairs(v.options) do ENT.ServerHACPGVarInfo[v2.class] = v2.type or "Bool" end end function ENT:SetupDataTables() self:NetworkVar("Bool",0,"3D") self:NetworkVar("Bool",1,"CollisionsEnabled") self:NetworkVar("Bool",2,"Orbiting") self:NetworkVar("Bool",3,"Unlit") self:NetworkVar("Int",0,"MinParticlesPerBurst") self:NetworkVar("Int",1,"MaxParticlesPerBurst") self:NetworkVar("Int",2,"MinStartAlpha") self:NetworkVar("Int",3,"MaxStartAlpha") self:NetworkVar("Int",4,"MinEndAlpha") self:NetworkVar("Int",5,"MaxEndAlpha") self:NetworkVar("Float",0,"MinBurstDuration") self:NetworkVar("Float",1,"MaxBurstDuration") self:NetworkVar("Float",2,"MinBurstDelay") self:NetworkVar("Float",3,"MaxBurstDelay") self:NetworkVar("Float",4,"MinSpawnDistance") self:NetworkVar("Float",5,"MaxSpawnDistance") self:NetworkVar("Float",6,"MinLifeTime") self:NetworkVar("Float",7,"MaxLifeTime") self:NetworkVar("Float",8,"MinVelocityFromOrigin") self:NetworkVar("Float",9,"MaxVelocityFromOrigin") self:NetworkVar("Float",10,"MinBounciness") self:NetworkVar("Float",11,"MaxBounciness") self:NetworkVar("Float",12,"MinAirResistance") self:NetworkVar("Float",13,"MaxAirResistance") self:NetworkVar("Float",14,"MinStartSize") self:NetworkVar("Float",15,"MaxStartSize") self:NetworkVar("Float",16,"MinEndSize") self:NetworkVar("Float",17,"MaxEndSize") self:NetworkVar("Float",18,"MinStartLength") self:NetworkVar("Float",19,"MaxStartLength") self:NetworkVar("Float",20,"MinEndLength") self:NetworkVar("Float",21,"MaxEndLength") self:NetworkVar("Float",22,"MinClockwiseVelocityFromOrigin") self:NetworkVar("Float",23,"MaxClockwiseVelocityFromOrigin") self:NetworkVar("Vector",0,"Origin") self:NetworkVar("Vector",1,"MinSpawnOffset") self:NetworkVar("Vector",2,"MaxSpawnOffset") self:NetworkVar("Vector",3,"MinParticleColor") self:NetworkVar("Vector",4,"MaxParticleColor") self:NetworkVar("Vector",5,"MinParticleAngles") self:NetworkVar("Vector",6,"MaxParticleAngles") self:NetworkVar("Vector",7,"MinParticleVelocity") self:NetworkVar("Vector",8,"MaxParticleVelocity") self:NetworkVar("Vector",9,"MinAngularVelocity") self:NetworkVar("Vector",10,"MaxAngularVelocity") self:NetworkVar("Vector",11,"MinAcceleration") self:NetworkVar("Vector",12,"MaxAcceleration") end function ENT:SpawnFunction(ply, trace, classname) if not trace.Hit then return end local ent = ents.Create(classname) ent:Spawn() ent:Activate() ent:SetSubMaterial(2, "sprites/glow04_noz_gmod") ent:SetHACPGVar("ParticlesPerBurst", 10) ent:SetHACPGVar("StartAlpha", 255) ent:SetHACPGVar("BurstDelay", 1) ent:SetHACPGVar("LifeTime", 1) ent:SetHACPGVar("ParticleVelocity", Vector(-100,-100,-100), Vector(100,100,100)) ent:SetHACPGVar("StartSize", 10) ent:SetHACPGVar("ParticleColor", Vector(1,1,1)) ent:SetHACPGVar("Unlit", true) ent:SetPos(trace.HitPos+trace.HitNormal*16) ent:SetAngles(ply:GetAngles()) return ent end function ENT:Initialize() if SERVER then self:SetModel("models/maxofs2d/cube_tool.mdl") self:SetMaterial("models/hacpg_generator") self:PhysicsInit(SOLID_VPHYSICS) local physobj = self:GetPhysicsObject() if IsValid(physobj) then physobj:Wake() end self:SetUseType(SIMPLE_USE) if WireLib then local inputs, inputTypes = {"Fire"}, {"NORMAL"} for i,v in ipairs(self.ClientHACPGVarInfo) do for i2,v2 in ipairs(v.options) do local class = v2.class if v2.type == "Float" or v2.type == "Int" then table.insert(inputs, "Min"..class) table.insert(inputTypes, "NORMAL") table.insert(inputs, "Max"..class) table.insert(inputTypes, "NORMAL") elseif v2.type == "Vector" or v2.type == "Color" or v2.type == "Angle" then if v2.minmax == false then table.insert(inputs, class) table.insert(inputTypes, "VECTOR") else table.insert(inputs, "Min"..class) table.insert(inputTypes, "VECTOR") table.insert(inputs, "Max"..class) table.insert(inputTypes, "VECTOR") end --[[elseif v2.type == "Angle" then table.insert(inputs, "Min"..class) table.insert(inputTypes, "ANGLE") table.insert(inputs, "Max"..class) table.insert(inputTypes, "ANGLE")]] elseif v2.type == "MaterialList" then table.insert(inputs, class) table.insert(inputTypes, "STRING") else table.insert(inputs, class) table.insert(inputTypes, "NORMAL") end end end self.ValidWiremodInputNames = {} for k,v in pairs(inputs) do self.ValidWiremodInputNames[v] = true end self.Inputs = WireLib.CreateSpecialInputs(self, inputs, inputTypes) -- Had to scrape code from other addons for Wiremod functionality. -- Where on earth is the official API documentation anyway?! local baseClass = baseclass.Get("base_wire_entity") self.OnRemove = baseClass.OnRemove self.OnRestore = baseClass.OnRestore self.BuildDupeInfo = baseClass.BuildDupeInfo self.ApplyDupeInfo = baseClass.ApplyDupeInfo self.OnEntityCopyTableFinish = baseClass.OnEntityCopyTableFinish self.OnDuplicated = baseClass.OnDuplicated end end if CLIENT then self.ParticleEmitters = {} self.DeadParticleEmitters = {} end end function ENT:TriggerInput(input, value) if self.ValidWiremodInputNames[input] then self:SetHACPGVar(input, value) end end function ENT:Think() if CLIENT then if CurTime() > (self.NextBurst or 0) then self.NextBurst = CurTime() + self:GetHACPGVar("BurstDelay") self:FireBurst() end --[[if CurTime() > (self.NextAngleParameterCheck or 0) then self.NextAngleParameterCheck = CurTime() + 1 for class,typ in pairs(self.ServerHACPGVarInfo) do if typ == "Angle" then -- ... end end end]] self:DoParticleEmitterThink() self:SetNextClientThink(CurTime()) end end function ENT:Use(activator, caller) if activator:IsPlayer() then net.Start("hacpg") net.WriteString("customize_generator") net.WriteEntity(self) net.Send(activator) end end function ENT:PreEntityCopy() -- this is kind of inefficient baseclass.Get("base_wire_entity").PreEntityCopy(self) -- invalid submaterials are not transferred, but we want to do it anyway self.CopyParticleMaterials = {} for i=0,31 do self.CopyParticleMaterials[i] = self:GetSubMaterial(i) end end function ENT:PostEntityPaste(...) -- again baseclass.Get("base_wire_entity").PostEntityPaste(self, ...) if self.CopyParticleMaterials then for i=0,31 do self:SetSubMaterial(i, self.CopyParticleMaterials[i]) end end end if CLIENT then function ENT:OnRemove() local particleEmitters = self.ParticleEmitters or {} -- Wait! Sometimes OnRemove is lying! timer.Simple(1, function() if not IsValid(self) then for k,v in pairs(particleEmitters) do if IsValid(v.emitter) then v.emitter:Finish() end end end end) end end --[[function ENT:Draw() self:DrawModel() end]] if SERVER then util.AddNetworkString("hacpg") end net.Receive("hacpg", function(length, ply) local func = net.ReadString() if func == "customize_generator" then if SERVER then if (ply.HACPG_ExpensiveMessageDelay or 0) > RealTime() then return end local ent = net.ReadEntity() if (IsValid(ent) and ent:GetClass()=="hacpg_default_generator") then local receivedTable = net.ReadTable() --PrintTable(receivedTable) for k,v in pairs(receivedTable) do if istable(v) then if ent.ServerHACPGVarInfo[k]=="MaterialList" then local checksOut = true for k2,v2 in pairs(v) do if not isstring(v2) then checksOut = false end end if checksOut then for k2,v2 in pairs(v) do ent:SetSubMaterial(math.Clamp(k2, 2, 31), v2) end end elseif ent:TypesCheckOut(v[1], ent.ServerHACPGVarInfo[k]) and ent:TypesCheckOut(v[2], ent.ServerHACPGVarInfo[k]) then ent:SetHACPGVar(k, v[1], v[2]) end elseif ent:TypesCheckOut(v, ent.ServerHACPGVarInfo[k]) then ent:SetHACPGVar(k, v) end end end ply.HACPG_ExpensiveMessageDelay = RealTime() + 1 end if CLIENT then net.ReadEntity():CreateEditUI() end end end) function ENT:TypesCheckOut(argument, typeStr) if not typeStr then return false elseif typeStr == "Float" or typeStr == "Int" then return isnumber(argument) and (typeStr ~= "Int" or argument % 1 == 0) elseif typeStr == "Vector" or typeStr == "Color" or typeStr == "Angle" then return isvector(argument) --[[elseif typeStr == "Angle" then return isangle(argument)]] elseif typeStr == "Bool" then return isbool(argument) end return false end function ENT:RandomFloat(minFloat, maxFloat) return math.random()*(maxFloat-minFloat)+minFloat end function ENT:RandomVector(minVector, maxVector) local retVector = maxVector-minVector retVector.x = retVector.x * math.random() retVector.y = retVector.y * math.random() retVector.z = retVector.z * math.random() retVector:Add(minVector) return retVector end --[[function ENT:RandomAngle(minAngle, maxAngle) local retAngle = maxAngle-minAngle retAngle.p = retAngle.p * math.random() retAngle.y = retAngle.y * math.random() retAngle.r = retAngle.r * math.random() retAngle:Add(minAngle) return retAngle end]] function ENT:VectorToAngle(vector) return Angle(vector.x, vector.y, vector.z) end function ENT:CreateRandomNormalizedVector() for i=1,1000 do local vector = VectorRand() if vector:LengthSqr() <= 1 and not vector:IsZero() then vector:Normalize() return vector end end return vector_up end local thingsThatDontReturnAFloat = { ParticlesPerBurst = "Int", SpawnOffset = "Vector", ParticleColor = "Vector", StartAlpha = "Int", EndAlpha = "Int", ParticleVelocity = "Vector", Acceleration = "Vector", ParticleAngles = "Vector", AngularVelocity = "Vector" } function ENT:SetHACPGVar(var, minValue, maxValue) local setFunction = self["Set"..var] if setFunction then setFunction(self, minValue) else local setFunctionMin = self["SetMin"..var] local setFunctionMax = self["SetMax"..var] if setFunctionMin and setFunctionMax then setFunctionMin(self, minValue) setFunctionMax(self, maxValue or minValue) end end end function ENT:GetHACPGVar(var) local getFunction = self["Get"..var] if getFunction then return getFunction(self) else local getFunctionMin = self["GetMin"..var] local getFunctionMax = self["GetMax"..var] if getFunctionMin and getFunctionMax then local customReturnType = thingsThatDontReturnAFloat[var] if customReturnType == "Int" then return math.random(getFunctionMin(self), getFunctionMax(self)) elseif customReturnType == "Vector" then return self:RandomVector(getFunctionMin(self), getFunctionMax(self)) --[[elseif customReturnType == "Angle" then return self:RandomAngle(getFunctionMin(self), getFunctionMax(self))]] else return self:RandomFloat(getFunctionMin(self), getFunctionMax(self)) end end end end function ENT:GetMaterialList() local materials = {} for i=2,31 do materials[i] = self:GetSubMaterial(i) end return materials end function ENT:FireBurst() local emitter = ParticleEmitter(self:LocalToWorld(self:GetHACPGVar("Origin")), self:GetHACPGVar("3D")) if IsValid(emitter) then table.insert(self.ParticleEmitters, { emitter = emitter, curParticles = 0, maxParticles = self:GetHACPGVar("ParticlesPerBurst"), startTime = CurTime(), endTime = CurTime()+self:GetHACPGVar("BurstDuration") }) end end function ENT:GenerateParticleThinkFunction(emitter) local orbitPos = emitter:GetPos() local gravityMul local materialsNeeded = {} for i=2,31 do if self:GetSubMaterial(i)~="" then materialsNeeded[i-1] = self:GetSubMaterial(i) else break end end local materialCount = #materialsNeeded -- cheaper than doing it every frame local currentMaterial = materialsNeeded[1] return function(particle) if not gravityMul then gravityMul = particle:GetGravity():Length()*1e4 end if IsValid(self) then if self:GetHACPGVar("Orbiting") then local gravityVector = orbitPos - particle:GetPos() gravityVector:Mul(gravityMul/gravityVector:Length()^3) particle:SetGravity(gravityVector) --print("[HACPG] particle "..CurTime()..' '..gravityMul..' '..tostring(particle:GetGravity())) if materialCount <= 1 then particle:SetNextThink(CurTime()) end end if materialCount > 1 then local materialIndex = math.min(math.floor(materialCount*particle:GetLifeTime()/particle:GetDieTime())+1, materialCount) local neededMaterial = materialsNeeded[materialIndex] if currentMaterial ~= neededMaterial then particle:SetMaterial(neededMaterial) currentMaterial = neededMaterial end particle:SetNextThink(CurTime()) end end end end function ENT:DoParticleEmitterThink() for k,v in pairs(self.ParticleEmitters) do if IsValid(v.emitter) then local expectedActivations if v.endTime - v.startTime <= 0 then expectedActivations = v.maxParticles else expectedActivations = math.min(math.floor(math.Remap(CurTime(), v.startTime, v.endTime, 0, v.maxParticles)), v.maxParticles) end for i=1, expectedActivations - v.curParticles do self:GetEmitterToAddParticle(v.emitter) end v.curParticles = expectedActivations if expectedActivations == v.maxParticles then table.insert(self.DeadParticleEmitters, k) end else print("[HACPG] NULL CLuaEmitter - this is not supposed to happen!") end end table.SortDesc(self.DeadParticleEmitters) for i,v in ipairs(self.DeadParticleEmitters) do self.ParticleEmitters[v].emitter:Finish() table.remove(self.ParticleEmitters, v) end table.Empty(self.DeadParticleEmitters) end local rot90 = Angle(0,-90,0) function ENT:GetEmitterToAddParticle(emitter) local spawnPos = Vector(0,0,0) local spawnDistance = self:GetHACPGVar("SpawnDistance") if spawnDistance ~= 0 then spawnPos = self:CreateRandomNormalizedVector() spawnPos:Mul(spawnDistance) end spawnPos:Add(self:GetHACPGVar("SpawnOffset")) spawnPos:Add(self:WorldToLocal(emitter:GetPos())) local particle = emitter:Add(self:GetSubMaterial(2), self:LocalToWorld(spawnPos)) if particle then local velocity = self:LocalToWorld(spawnPos) - emitter:GetPos() velocity:Normalize() local upVector = Vector(0,0,1) upVector:Rotate(self:GetAngles()) local velocity2 = upVector:Cross(velocity) --velocity2:Rotate(rot90) --velocity2:Rotate(self:GetAngles()) velocity2:Normalize() velocity:Mul(self:GetHACPGVar("VelocityFromOrigin")) velocity2:Mul(self:GetHACPGVar("ClockwiseVelocityFromOrigin")) velocity:Add(velocity2) velocity2 = self:GetHACPGVar("ParticleVelocity") velocity2:Rotate(self:GetAngles()) velocity:Add(velocity2) local angles = self:LocalToWorldAngles(self:VectorToAngle(self:GetHACPGVar("ParticleAngles"))) local angularVelocity = self:VectorToAngle(self:GetHACPGVar("AngularVelocity")) local particleColor = self:GetHACPGVar("ParticleColor"):ToColor() local acceleration = self:GetHACPGVar("Acceleration") acceleration:Rotate(self:GetAngles()) particle:SetStartSize(self:GetHACPGVar("StartSize")) particle:SetEndSize(self:GetHACPGVar("EndSize")) particle:SetStartLength(self:GetHACPGVar("StartLength")) particle:SetEndLength(self:GetHACPGVar("EndLength")) particle:SetLighting(not self:GetHACPGVar("Unlit")) particle:SetColor(particleColor.r, particleColor.g, particleColor.b) particle:SetStartAlpha(self:GetHACPGVar("StartAlpha")) particle:SetEndAlpha(self:GetHACPGVar("EndAlpha")) particle:SetDieTime(self:GetHACPGVar("LifeTime")) particle:SetVelocityScale(false) particle:SetVelocity(velocity) particle:SetGravity(acceleration) if emitter:Is3D() then particle:SetAngles(angles) particle:SetAngleVelocity(angularVelocity) else particle:SetRoll(angles.r) particle:SetRollDelta(angularVelocity.r) end particle:SetCollide(self:GetHACPGVar("CollisionsEnabled")) particle:SetBounce(self:GetHACPGVar("Bounciness")) particle:SetAirResistance(self:GetHACPGVar("AirResistance")) particle:SetThinkFunction(self:GenerateParticleThinkFunction(emitter)) end end function ENT:CreateDataTable() local dataTable = {} for k,v in pairs(self.ClientHACPGVarInfo) do for k2,v2 in pairs(v.options) do local var = v2.class local getFunction = self["Get"..var] if getFunction then dataTable[var] = getFunction(self) else local getFunctionMin = self["GetMin"..var] local getFunctionMax = self["GetMax"..var] if getFunctionMin and getFunctionMax then dataTable[var] = {getFunctionMin(self), getFunctionMax(self)} end end end end return dataTable end function ENT:SendDataTable(dataTable) --PrintTable(dataTable) net.Start("hacpg") net.WriteString("customize_generator") net.WriteEntity(self) net.WriteTable(dataTable) -- I'm too lazy to think about this properly... net.SendToServer() end function ENT:CreateEditUI() local ent = self local dataTable = ent:CreateDataTable() local Main = vgui.Create("DFrame") Main:SetSize(ScrW()/2, ScrH()/2) Main:Center() Main:SetSizable(true) Main:SetTitle("Particle Generator Settings Editor") Main:MakePopup() function Main:InsertMinMaxSliders(OptionPanel, name, desc, decimals, minValue, maxValue, minDefault, maxDefault, minFunction, maxFunction) local MinSlider, MaxSlider MinSlider = OptionPanel:Add("DNumSlider") MinSlider:SetText("Minimum "..name) MinSlider:SetMinMax(minValue, maxValue) MinSlider:SetValue(minDefault) MinSlider:SetDefaultValue(minDefault) MinSlider:SetDecimals(decimals) MinSlider:SetDark(true) MinSlider:Dock(TOP) MinSlider:SetTooltip(desc) function MinSlider:OnValueChanged(value) if MaxSlider:GetValue() < value then MaxSlider:SetValue(value) end minFunction(value) end MaxSlider = OptionPanel:Add("DNumSlider") MaxSlider:SetText("Maximum "..name) MaxSlider:SetMinMax(minValue, maxValue) MaxSlider:SetValue(maxDefault) MaxSlider:SetDefaultValue(maxDefault) MaxSlider:SetDecimals(decimals) MaxSlider:SetDark(true) MaxSlider:Dock(TOP) MaxSlider:SetTooltip(desc) function MaxSlider:OnValueChanged(value) if MinSlider:GetValue() > value then MinSlider:SetValue(value) end maxFunction(value) end end if not file.IsDir("hacpg_presets", "DATA") then file.CreateDir("hacpg_presets") end if not file.IsDir("hacpg_presets/examples", "DATA") then file.CreateDir("hacpg_presets/examples") self:CreateExamples() end local Categories = vgui.Create("DCategoryList", Main) Categories:SetTall(ScrH()) Categories:Dock(FILL) function Categories:Paint() end function Main:Refresh() if not IsValid(ent) then return end Categories:Clear() local Category = Categories:Add("Presets") local Options = vgui.Create("DPanel") Options:DockPadding(2,2,2,2) Category:SetContents(Options) local WarningLabel = Options:Add("DLabel") WarningLabel:SetText("Remember that your settings will be lost if you close this window without saving!") WarningLabel:SetDark(true) WarningLabel:Dock(TOP) local PresetPanel = Options:Add("DPanel") PresetPanel:Dock(TOP) local LoadButton = PresetPanel:Add("DButton") LoadButton:SetText("Load Preset") LoadButton:SizeToContentsX(8) LoadButton:Dock(RIGHT) local SaveButton = PresetPanel:Add("DButton") SaveButton:SetText("Save Preset") SaveButton:SizeToContentsX(8) SaveButton:Dock(RIGHT) local PresetEntry = PresetPanel:Add("DTextEntry") PresetEntry:SetPlaceholderText("Preset name...") PresetEntry:Dock(FILL) PresetEntry.knownPresetNames = {} function PresetEntry:ScanFiles(filePath) local files, dirs = file.Find("hacpg_presets/"..filePath.."*", "DATA") for k,v in pairs(files) do self.knownPresetNames[filePath..v:StripExtension()] = true end for k,v in pairs(dirs) do self:ScanFiles(filePath..v..'/') end end function PresetEntry:GetAutoComplete(text) local results = {} for k,v in pairs(PresetEntry.knownPresetNames) do if k:StartWith(text:lower()) then table.insert(results, k) end end return results end PresetEntry:ScanFiles("") PresetPanel:SetTall(LoadButton:GetTall()) function SaveButton:SaveData(fileName, overwrite) -- Windows becomes suprisingly unstable if these names are used, better reject these local illegalNames = {"con", "prn", "aux", "nul", "lpt1", "lpt2", "lpt3", "lpt4", "com1", "com2", "com3", "com4"} local illegal = false for k,v in pairs(illegalNames) do if fileName:match("%W"..v.."%W") then illegal = v break end end if illegal and system.IsWindows() then Derma_Message("You can't name a file/folder \""..illegal.."\"!\n(Blame Microsoft)", "Save Failed", "#GameUI_OK") elseif file.Exists(fileName, "DATA") and not overwrite then Derma_Query("Are you sure you want to overwrite this preset?", "Overwrite Preset", "Yes", function() if IsValid(self) then self:SaveData(fileName, true) end end, "No") else surface.PlaySound("buttons/button15.wav") local dataStr = util.TableToJSON(dataTable) local filePath = fileName:GetPathFromFilename() if not file.IsDir(filePath, "DATA") then file.CreateDir(filePath:sub(1,-2)) end file.Write(fileName, dataStr) PresetEntry.knownPresetNames = {} PresetEntry:ScanFiles("") end end function SaveButton:DoClick() if PresetEntry:GetValue()=="" then Derma_Message("Please enter a preset name.","Save Failed","#GameUI_OK") else local fileName = string.format("hacpg_presets/%s.dat", PresetEntry:GetValue()) self:SaveData(fileName:lower()) end end function LoadButton:DoClick() if IsValid(ent) then ent:FileLoader(function(fileName) if IsValid(Main) then local dataStr = file.Read(fileName, "DATA") dataTable = util.JSONToTable(dataStr) Main:Refresh() ent:SendDataTable(dataTable) end end) end end Category:SetExpanded(false) for i,v in ipairs(ent.ClientHACPGVarInfo) do local Category = Categories:Add(v.name) local Options = vgui.Create("DPanel") Options:DockPadding(2,2,2,2) Category:SetContents(Options) for i2,v2 in ipairs(v.options) do if v2.type == "Float" or v2.type == "Int" then local decimals = v2.type == "Int" and 0 or math.Round(4-math.log10(v2.max-v2.min)) Main:InsertMinMaxSliders(Options, v2.name, v2.desc, decimals, v2.min, v2.max, dataTable[v2.class][1], dataTable[v2.class][2], function(value) dataTable[v2.class][1] = math.Round(value, decimals) end, function(value) dataTable[v2.class][2] = math.Round(value, decimals) end) elseif v2.type == "Vector" then local decimals = math.Round(4-math.log10(v2.max-v2.min)) -- this looks ugly as hell, but I really don't have much of a choice here... for i3,v3 in ipairs({{'x'," X"}, {'y'," Y"}, {'z'," Z"}}) do local axis = v3[1] if v2.minmax ~= false then Main:InsertMinMaxSliders(Options, v2.name..v3[2], v2.desc, decimals, v2.min, v2.max, dataTable[v2.class][1][axis], dataTable[v2.class][2][axis], function(value) dataTable[v2.class][1][axis] = value end, function(value) dataTable[v2.class][2][axis] = value end) else local Slider = Options:Add("DNumSlider") Slider:SetText(v2.name..v3[2]) Slider:SetMinMax(v2.min, v2.max) Slider:SetValue(dataTable[v2.class][axis]) Slider:SetDefaultValue(dataTable[v2.class][axis]) Slider:SetDecimals(decimals) Slider:SetDark(true) Slider:Dock(TOP) Slider:SetTooltip(v2.desc) function Slider:OnValueChanged(value) dataTable[v2.class][axis] = value end end end elseif v2.type == "Angle" then --[[for i3,v3 in ipairs({{'p'," Pitch"}, {'y'," Yaw"}, {'r'," Roll"}}) do local axis = v3[1] Main:InsertMinMaxSliders(Options, v2.name..v3[2], 1, axis=='p' and -90 or -179.9, axis=='p' and 90 or 180, dataTable[v2.class][1][axis], dataTable[v2.class][2][axis], function(value) dataTable[v2.class][1][axis] = value end, function(value) dataTable[v2.class][2][axis] = value end) end]] for i3,v3 in ipairs({{'x'," Pitch"}, {'y'," Yaw"}, {'z'," Roll"}}) do local axis = v3[1] Main:InsertMinMaxSliders(Options, v2.name..v3[2], v2.desc, 1, -180*(v2.mul or 1), 180*(v2.mul or 1), dataTable[v2.class][1][axis], dataTable[v2.class][2][axis], function(value) dataTable[v2.class][1][axis] = value end, function(value) dataTable[v2.class][2][axis] = value end) end elseif v2.type == "Color" then for i3,v3 in ipairs({{'x'," Red"}, {'y'," Green"}, {'z'," Blue"}}) do local axis = v3[1] Main:InsertMinMaxSliders(Options, v2.name..v3[2], v2.desc, 4, 0, 1, dataTable[v2.class][1][axis], dataTable[v2.class][2][axis], function(value) dataTable[v2.class][1][axis] = value end, function(value) dataTable[v2.class][2][axis] = value end) end elseif v2.type == "MaterialList" then local Label = Options:Add("DLabel") Label:SetText("Animation Material List") Label:SetDark(true) Label:Dock(TOP) Label:SetTooltip(v2.desc) local ScrollPanel = Options:Add("DScrollPanel") ScrollPanel:SetTall(ScrH()/9) ScrollPanel:Dock(TOP) ScrollPanel:SetTooltip(v2.desc) local MaterialEntries = ScrollPanel:Add("DIconLayout") MaterialEntries:SetSpaceY(0) MaterialEntries:SetStretchHeight(true) MaterialEntries:Dock(TOP) for i=2,31 do local MaterialDPanel = MaterialEntries:Add("DPanel") MaterialDPanel:SetTall(24) MaterialDPanel:Dock(TOP) local BrowserButton = MaterialDPanel:Add("DButton") BrowserButton:SetText("Browse...") BrowserButton:SizeToContentsX(8) BrowserButton:Dock(LEFT) local MaterialEntry = MaterialDPanel:Add("DTextEntry") MaterialEntry:SetText(dataTable[v2.class][i]) MaterialEntry:Dock(FILL) function MaterialEntry:OnChange() dataTable[v2.class][i] = self:GetText() end function BrowserButton:DoClick() if IsValid(ent) then ent:CreateMaterialBrowser(function(material) MaterialEntry:SetText(material) dataTable[v2.class][i] = material end) end end end else local CheckBox = Options:Add("DCheckBoxLabel") CheckBox:SetText(v2.name) CheckBox:SetValue(dataTable[v2.class]) CheckBox:SetDark(true) CheckBox:Dock(TOP) CheckBox:SetTooltip(v2.desc) function CheckBox:OnChange(value) dataTable[v2.class] = value end end end Category:SetExpanded(false) --Options:SetTall(ScrH()/6) end end Main:Refresh() local Accept = Main:Add("DButton") Accept:SetText("Set Changes") Accept:Dock(BOTTOM) function Accept:DoClick() surface.PlaySound("buttons/button15.wav") if IsValid(ent) then ent:SendDataTable(dataTable) end end end function ENT:CreateMaterialBrowser(callback) local Main = vgui.Create("DFrame") Main:SetSize(640, 480) Main:SetTitle("Material Browser") Main:Center() Main:MakePopup() Main:SetSizable(true) Main.btnMaxim:SetDisabled(false) function Main.btnMaxim:DoClick() if Main:GetDraggable() then Main.savedPos = {Main:GetPos()} Main:SetPos(0, 0) Main:SetSize(ScrW(), ScrH()) Main:SetDraggable(false) Main:SetSizable(false) else Main:SetPos(unpack(Main.savedPos)) Main:SetSize(640, 480) Main:SetDraggable(true) Main:SetSizable(true) end end local Label = vgui.Create("DLabel", Main) Label:SetText("I'd recommend searching through the \"effects\", \"sprites\" or \"particle\" folders to find a good particle image.\n\z NOTE: I very strongly recommend using Extended Spawnmenu's material browser and copying the image you want to your clipboard rather than using this, \z as there are MAJOR bugs with this browser (including one which keeps creating giant rapidly flickering pixels on the screen!).") Label:SetWrap(true) Label:SetAutoStretchVertical(true) Label:Dock(TOP) local HorizontalDivider = vgui.Create("DHorizontalDivider", Main) HorizontalDivider:Dock(FILL) HorizontalDivider:SetLeftWidth(240) local Browser = vgui.Create("DTree") HorizontalDivider:SetLeft(Browser) local MaterialNode = Browser:AddNode("materials") MaterialNode:MakeFolder("materials", "GAME") local MaterialSelectScroller = vgui.Create("DScrollPanel") HorizontalDivider:SetRight(MaterialSelectScroller) local MaterialSelect = vgui.Create("DIconLayout", MaterialSelectScroller) MaterialSelect:Dock(FILL) MaterialSelect.nextLoad = RealTime() function Browser:DoClick() local selectedNode = self:GetSelectedItem() MaterialSelect:GetMaterialsInFolder(selectedNode:GetFolder()) end function MaterialSelect:GetMaterialsInFolder(folder) MaterialSelect:Clear() self.materialStrings = {} self.lastMaterial = nil for i,v in ipairs(file.Find(folder.."/*.vmt", "GAME")) do if v:GetExtensionFromFilename() == "vmt" then local path = folder:sub(11)..'/' table.insert(self.materialStrings, path..v) end end end function MaterialSelect:Think() if self.materialStrings and self.nextLoad <= RealTime() then local k,v = next(self.materialStrings, self.lastMaterial) if v then local startTime = SysTime() local material = Material(v) if material:GetShader():lower() ~= "spritecard" then local Image = vgui.Create("DImageButton", MaterialSelect) Image:SetSize(128, 128) Image:SetMaterial(material) Image:SetTooltip(v) function Image:DoClick() Main:Close() callback(v) end end self.nextLoad = RealTime() + (SysTime() - startTime) self.lastMaterial = k else self.materialStrings = nil end end end end function ENT:FileLoader(callback) local ent = self local FileMain = vgui.Create("DFrame") FileMain:SetSize(ScrH()/2,ScrH()/2) FileMain:Center() FileMain:MakePopup() FileMain:SetTitle("File Browser") local ButtonPanel = vgui.Create("DPanel", FileMain) function ButtonPanel:Paint() end local FileEntry = vgui.Create("DTextEntry", ButtonPanel) FileEntry:Dock(FILL) FileEntry:SetPlaceholderText("Enter a preset name...") local OKButton = vgui.Create("DButton", ButtonPanel) OKButton:SetText("Load Preset") OKButton:SizeToContentsX(8) OKButton:SizeToContentsY(8) ButtonPanel:SetHeight(OKButton:GetTall()) ButtonPanel:Dock(BOTTOM) OKButton:Dock(RIGHT) local DeleteButton = vgui.Create("DButton", ButtonPanel) DeleteButton:SetText("Delete Preset") DeleteButton:SizeToContentsX(8) DeleteButton:SizeToContentsY(8) DeleteButton:Dock(RIGHT) function DeleteButton:DoClick() local pathFileName = "hacpg_presets/"..FileEntry:GetValue()..".dat" if FileEntry:GetValue()=="" then Derma_Message("Please enter a preset name.","Load Failed","#GameUI_OK") elseif file.Exists(pathFileName, "DATA") then Derma_Query("Are you sure you want to delete the preset \""..FileEntry:GetValue().."\"?", "Confirm Deletion", "Yes", function() if IsValid(FileMain) and IsValid(ent) then file.Delete(pathFileName) local localPath = pathFileName:GetPathFromFilename() local otherThingsInPath = table.Add(file.Find(localPath.."*", "DATA")) if table.IsEmpty(otherThingsInPath) and localPath ~= "hacpg_presets/" then file.Delete(localPath) end FileMain:Close() ent:FileLoader(callback) end end, "No") else Derma_Message("Cannot find preset \""..FileEntry:GetValue().."\".","Load Failed","#GameUI_OK") end end local FileBrowser = vgui.Create("DFileBrowser", FileMain) FileBrowser:Dock(FILL) FileBrowser:SetPath("DATA") FileBrowser:SetBaseFolder("hacpg_presets") FileBrowser:SetCurrentFolder("hacpg_presets") --FileBrowser:SetOpen(true) function FileBrowser:OnSelect(fileName) FileEntry:SetText(fileName:sub(15):StripExtension()) end function OKButton:DoClick() if FileEntry:GetValue()=="" then Derma_Message("Please enter a preset name.","Load Failed","#GameUI_OK") elseif file.Exists("hacpg_presets/"..FileEntry:GetValue()..".dat", "DATA") then callback("hacpg_presets/"..FileEntry:GetValue()..".dat") FileMain:Close() else Derma_Message("Cannot find preset \""..FileEntry:GetValue().."\".","Load Failed","#GameUI_OK") end end end function ENT:CreateExamples() local examples = { ["booster"] = [[{"ParticlesPerBurst":[1.0,1.0],"3D":true,"ParticleVelocity":["[100 0 0]","[100 0 0]"],"EndSize":[50.0,50.0],"AngularVelocity":["[0 0 0]","[0 0 0]"],"BurstDelay":[0.05,0.05],"Orbiting":false,"Bounciness":[0.0,0.0],"CollisionsEnabled":false,"EndAlpha":[0.0,0.0],"AirResistance":[0.0,0.0],"BurstDuration":[0.0,0.0],"Acceleration":["[0 0 0]","[0 0 0]"],"ClockwiseVelocityFromOrigin":[0.0,0.0],"SpawnDistance":[0.0,0.0],"VelocityFromOrigin":[0.0,0.0],"EndLength":[0.0,0.0],"StartLength":[0.0,0.0],"Unlit":true,"LifeTime":[2.0,2.0],"SpawnOffset":["[0 0 0]","[0 0 0]"],"MaterialList":{"2":"effects/select_ring.vmt","3":"","4":"","5":"","6":"","7":"","8":"","9":"","10":"","11":"","12":"","13":"","14":"","15":"","16":"","17":"","18":"","19":"","20":"","21":"","22":"","23":"","24":"","25":"","26":"","27":"","28":"","29":"","30":"","31":""},"Origin":"[8 0 0]","ParticleColor":["[0 0.5 1]","[0 0.5 1]"],"ParticleAngles":["[0 0 0]","[0 0 0]"],"StartSize":[5.0,5.0],"StartAlpha":[255.0,255.0]}]], ["booster static"] = [[{"ParticlesPerBurst":[1.0,1.0],"3D":true,"ParticleVelocity":["[0 0 0]","[0 0 0]"],"EndSize":[20.0,20.0],"AngularVelocity":["[0 0 0]","[0 0 0]"],"BurstDelay":[0.05,0.05],"Orbiting":false,"Bounciness":[0.0,0.0],"CollisionsEnabled":false,"EndAlpha":[0.0,0.0],"AirResistance":[0.0,0.0],"BurstDuration":[0.0,0.0],"Acceleration":["[0 0 0]","[0 0 0]"],"ClockwiseVelocityFromOrigin":[0.0,0.0],"SpawnDistance":[0.0,0.0],"VelocityFromOrigin":[0.0,0.0],"EndLength":[0.0,0.0],"StartLength":[0.0,0.0],"Unlit":true,"LifeTime":[1.0,1.0],"SpawnOffset":["[0 0 0]","[0 0 0]"],"MaterialList":{"2":"effects/select_ring.vmt","3":"","4":"","5":"","6":"","7":"","8":"","9":"","10":"","11":"","12":"","13":"","14":"","15":"","16":"","17":"","18":"","19":"","20":"","21":"","22":"","23":"","24":"","25":"","26":"","27":"","28":"","29":"","30":"","31":""},"Origin":"[8 0 0]","ParticleColor":["[0 0.5 1]","[0 0.5 1]"],"ParticleAngles":["[0 0 0]","[0 0 0]"],"StartSize":[5.0,5.0],"StartAlpha":[255.0,255.0]}]], ["fake ball generator"] = [[{"ParticlesPerBurst":[1.0,1.0],"3D":false,"ParticleVelocity":["[-100 -100 200]","[100 100 400]"],"EndSize":[10.0,10.0],"AngularVelocity":["[0 0 0]","[0 0 0]"],"BurstDelay":[0.1,0.1],"Orbiting":false,"Bounciness":[1.0,1.0],"CollisionsEnabled":true,"EndAlpha":[255.0,255.0],"AirResistance":[1.0,1.0],"BurstDuration":[0.0,0.0],"Acceleration":["[0 0 -300]","[0 0 -300]"],"ClockwiseVelocityFromOrigin":[0.0,0.0],"SpawnDistance":[0.0,0.0],"VelocityFromOrigin":[0.0,0.0],"EndLength":[0.0,0.0],"StartLength":[0.0,0.0],"Unlit":true,"LifeTime":[10.0,10.0],"SpawnOffset":["[0 0 0]","[0 0 0]"],"MaterialList":{"2":"sprites/sent_ball.vmt","3":"","4":"","5":"","6":"","7":"","8":"","9":"","10":"","11":"","12":"","13":"","14":"","15":"","16":"","17":"","18":"","19":"","20":"","21":"","22":"","23":"","24":"","25":"","26":"","27":"","28":"","29":"","30":"","31":""},"Origin":"[0 0 0]","ParticleColor":["[0 0 0]","[1 1 1]"],"ParticleAngles":["[0 0 0]","[0 0 0]"],"StartSize":[10.0,10.0],"StartAlpha":[255.0,255.0]}]], ["purple magic barrier"] = [[{"ParticlesPerBurst":[1.0,1.0],"3D":false,"ParticleVelocity":["[0 0 0]","[0 0 0]"],"EndSize":[5.0,5.0],"AngularVelocity":["[0 0 0]","[0 0 0]"],"BurstDelay":[0.0,0.0],"Orbiting":true,"Bounciness":[0.0,0.0],"CollisionsEnabled":false,"EndAlpha":[0.0,0.0],"AirResistance":[0.0,0.0],"BurstDuration":[0.0,0.0],"Acceleration":["[0 0 -38]","[0 0 -38]"],"ClockwiseVelocityFromOrigin":[100.0,100.0],"SpawnDistance":[40.0,40.0],"VelocityFromOrigin":[0.0,0.0],"EndLength":[0.0,0.0],"StartLength":[0.0,0.0],"Unlit":true,"LifeTime":[10.0,10.0],"SpawnOffset":["[0 0 0]","[0 0 0]"],"MaterialList":{"2":"sprites/glow04_noz_gmod.vmt","3":"","4":"","5":"","6":"","7":"","8":"","9":"","10":"","11":"","12":"","13":"","14":"","15":"","16":"","17":"","18":"","19":"","20":"","21":"","22":"","23":"","24":"","25":"","26":"","27":"","28":"","29":"","30":"","31":""},"Origin":"[0 0 50]","ParticleColor":["[0 0 1]","[1 0 1]"],"ParticleAngles":["[0 0 0]","[0 0 0]"],"StartSize":[5.0,5.0],"StartAlpha":[255.0,255.0]}]], ["rain maker"] = [[{"ParticlesPerBurst":[20.0,20.0],"3D":false,"ParticleVelocity":["[-10 -10 -500]","[10 10 -500]"],"EndSize":[0.2,0.2],"AngularVelocity":["[0 0 0]","[0 0 0]"],"BurstDelay":[0.0,0.0],"Orbiting":false,"Bounciness":[0.02,0.02],"CollisionsEnabled":true,"EndAlpha":[255.0,255.0],"AirResistance":[0.0,0.0],"BurstDuration":[0.0,0.0],"Acceleration":["[0 0 -500]","[0 0 -500]"],"ClockwiseVelocityFromOrigin":[0.0,0.0],"SpawnDistance":[0.0,0.0],"VelocityFromOrigin":[0.0,0.0],"EndLength":[10.0,10.0],"StartLength":[10.0,10.0],"Unlit":true,"LifeTime":[1.3,1.3],"SpawnOffset":["[-500 -500 500]","[500 500 500]"],"MaterialList":{"2":"effects/laser_tracer","3":"","4":"","5":"","6":"","7":"","8":"","9":"","10":"","11":"","12":"","13":"","14":"","15":"","16":"","17":"","18":"","19":"","20":"","21":"","22":"","23":"","24":"","25":"","26":"","27":"","28":"","29":"","30":"","31":""},"Origin":"[0 0 500]","ParticleColor":["[0 0 0.5]","[0 0.5 1]"],"ParticleAngles":["[0 0 0]","[0 0 0]"],"StartSize":[10.0,10.0],"StartAlpha":[0.0,0.0]}]], ["rainbow fountain"] = [[{"ParticlesPerBurst":[4.0,4.0],"3D":false,"ParticleVelocity":["[0 0 0]","[0 0 0]"],"EndSize":[0.0,0.0],"AngularVelocity":["[0 0 0]","[0 0 0]"],"BurstDelay":[0.0,0.0],"Orbiting":false,"Bounciness":[0.0,0.5],"CollisionsEnabled":true,"EndAlpha":[255.0,255.0],"AirResistance":[20.0,30.0],"BurstDuration":[0.0,0.0],"Acceleration":["[0 0 -200]","[0 0 -150]"],"ClockwiseVelocityFromOrigin":[0.0,0.0],"SpawnDistance":[0.1,0.1],"VelocityFromOrigin":[150.0,200.0],"EndLength":[0.0,0.0],"StartLength":[0.0,0.0],"Unlit":true,"LifeTime":[3.0,3.0],"SpawnOffset":["[0 0 1]","[0 0 1]"],"MaterialList":{"2":"sprites/blueflare1_noz_gmod.vmt","3":"","4":"","5":"","6":"","7":"","8":"","9":"","10":"","11":"","12":"","13":"","14":"","15":"","16":"","17":"","18":"","19":"","20":"","21":"","22":"","23":"","24":"","25":"","26":"","27":"","28":"","29":"","30":"","31":""},"Origin":"[0 0 8]","ParticleColor":["[0 0 0]","[1 1 1]"],"ParticleAngles":["[0 0 0]","[0 0 0]"],"StartSize":[3.0,3.0],"StartAlpha":[255.0,255.0]}]], ["rainbow star field"] = [[{"ParticlesPerBurst":[1.0,1.0],"3D":false,"ParticleVelocity":["[0 0 0]","[0 0 0]"],"EndSize":[5.0,5.0],"AngularVelocity":["[0 0 0]","[0 0 0]"],"BurstDelay":[0.0,0.0],"Orbiting":false,"Bounciness":[0.0,0.0],"CollisionsEnabled":false,"EndAlpha":[0.0,0.0],"AirResistance":[0.0,0.0],"BurstDuration":[0.0,0.0],"Acceleration":["[0 0 0]","[0 0 0]"],"ClockwiseVelocityFromOrigin":[0.0,0.0],"SpawnDistance":[0.0,1000.0],"VelocityFromOrigin":[0.0,0.0],"EndLength":[0.0,0.0],"StartLength":[0.0,0.0],"Unlit":true,"LifeTime":[10.0,10.0],"SpawnOffset":["[-500 -500 -500]","[500 500 500]"],"MaterialList":{"2":"effects/yellowflare.vmt","3":"","4":"","5":"","6":"","7":"","8":"","9":"","10":"","11":"","12":"","13":"","14":"","15":"","16":"","17":"","18":"","19":"","20":"","21":"","22":"","23":"","24":"","25":"","26":"","27":"","28":"","29":"","30":"","31":""},"Origin":"[0 0 0]","ParticleColor":["[0.5 0.5 0.5]","[1 1 1]"],"ParticleAngles":["[0 0 -180]","[0 0 180]"],"StartSize":[5.0,5.0],"StartAlpha":[255.0,255.0]}]], ["rainbow star field ignore walls"] = [[{"ParticlesPerBurst":[1.0,1.0],"3D":false,"ParticleVelocity":["[0 0 0]","[0 0 0]"],"EndSize":[5.0,5.0],"AngularVelocity":["[0 0 0]","[0 0 0]"],"BurstDelay":[0.0,0.0],"Orbiting":false,"Bounciness":[0.0,0.0],"CollisionsEnabled":false,"EndAlpha":[0.0,0.0],"AirResistance":[0.0,0.0],"BurstDuration":[0.0,0.0],"Acceleration":["[0 0 0]","[0 0 0]"],"ClockwiseVelocityFromOrigin":[0.0,0.0],"SpawnDistance":[0.0,1000.0],"VelocityFromOrigin":[0.0,0.0],"EndLength":[0.0,0.0],"StartLength":[0.0,0.0],"Unlit":true,"LifeTime":[10.0,10.0],"SpawnOffset":["[-500 -500 -500]","[500 500 500]"],"MaterialList":{"2":"effects/yellowflare_noz.vmt","3":"","4":"","5":"","6":"","7":"","8":"","9":"","10":"","11":"","12":"","13":"","14":"","15":"","16":"","17":"","18":"","19":"","20":"","21":"","22":"","23":"","24":"","25":"","26":"","27":"","28":"","29":"","30":"","31":""},"Origin":"[0 0 0]","ParticleColor":["[0.5 0.5 0.5]","[1 1 1]"],"ParticleAngles":["[0 0 -180]","[0 0 180]"],"StartSize":[5.0,5.0],"StartAlpha":[255.0,255.0]}]], ["red bouncing laser"] = [[{"ParticlesPerBurst":[1.0,1.0],"3D":false,"ParticleVelocity":["[500 0 0]","[500 0 0]"],"EndSize":[2.0,2.0],"AngularVelocity":["[0 0 -180]","[0 0 -180]"],"BurstDelay":[0.0,0.0],"Orbiting":false,"Bounciness":[1.0,1.0],"CollisionsEnabled":true,"EndAlpha":[255.0,255.0],"AirResistance":[0.0,0.0],"BurstDuration":[0.0,0.0],"Acceleration":["[0 0 0]","[0 0 0]"],"ClockwiseVelocityFromOrigin":[0.0,0.0],"SpawnDistance":[0.0,0.0],"VelocityFromOrigin":[0.0,0.0],"EndLength":[50.0,50.0],"StartLength":[50.0,50.0],"Unlit":true,"LifeTime":[1.0,1.0],"SpawnOffset":["[0 0 0]","[0 0 0]"],"MaterialList":{"2":"effects/laser_tracer","3":"","4":"","5":"","6":"","7":"","8":"","9":"","10":"","11":"","12":"","13":"","14":"","15":"","16":"","17":"","18":"","19":"","20":"","21":"","22":"","23":"","24":"","25":"","26":"","27":"","28":"","29":"","30":"","31":""},"Origin":"[-15 0 0]","ParticleColor":["[1 0 0]","[1 0.0938 0.0938]"],"ParticleAngles":["[0 0 0]","[0 0 0]"],"StartSize":[2.0,2.0],"StartAlpha":[255.0,255.0]}]], ["red laser"] = [[{"ParticlesPerBurst":[1.0,1.0],"3D":false,"ParticleVelocity":["[500 0 0]","[500 0 0]"],"EndSize":[2.0,2.0],"AngularVelocity":["[0 0 -180]","[0 0 -180]"],"BurstDelay":[0.0,0.0],"Orbiting":false,"Bounciness":[0.0,0.0],"CollisionsEnabled":true,"EndAlpha":[255.0,255.0],"AirResistance":[0.0,0.0],"BurstDuration":[0.0,0.0],"Acceleration":["[0 0 0]","[0 0 0]"],"ClockwiseVelocityFromOrigin":[0.0,0.0],"SpawnDistance":[0.0,0.0],"VelocityFromOrigin":[0.0,0.0],"EndLength":[100.0,100.0],"StartLength":[100.0,100.0],"Unlit":true,"LifeTime":[1.0,1.0],"SpawnOffset":["[0 0 0]","[0 0 0]"],"MaterialList":{"2":"effects/laser_tracer","3":"","4":"","5":"","6":"","7":"","8":"","9":"","10":"","11":"","12":"","13":"","14":"","15":"","16":"","17":"","18":"","19":"","20":"","21":"","22":"","23":"","24":"","25":"","26":"","27":"","28":"","29":"","30":"","31":""},"Origin":"[-15 0 0]","ParticleColor":["[1 0 0]","[1 0.0938 0.0938]"],"ParticleAngles":["[0 0 0]","[0 0 0]"],"StartSize":[2.0,2.0],"StartAlpha":[255.0,255.0]}]], ["red super long laser"] = [[{"ParticlesPerBurst":[1.0,1.0],"3D":false,"ParticleVelocity":["[500 0 0]","[500 0 0]"],"EndSize":[2.0,2.0],"AngularVelocity":["[0 0 0]","[0 0 0]"],"BurstDelay":[0.0,0.0],"Orbiting":false,"Bounciness":[0.0,0.0],"CollisionsEnabled":true,"EndAlpha":[255.0,255.0],"AirResistance":[0.0,0.0],"BurstDuration":[0.0,0.0],"Acceleration":["[500 0 0]","[500 0 0]"],"ClockwiseVelocityFromOrigin":[0.0,0.0],"SpawnDistance":[0.0,0.0],"VelocityFromOrigin":[0.0,0.0],"EndLength":[100.0,100.0],"StartLength":[100.0,100.0],"Unlit":true,"LifeTime":[10.0,10.0],"SpawnOffset":["[0 0 0]","[0 0 0]"],"MaterialList":{"2":"effects/laser_tracer","3":"","4":"","5":"","6":"","7":"","8":"","9":"","10":"","11":"","12":"","13":"","14":"","15":"","16":"","17":"","18":"","19":"","20":"","21":"","22":"","23":"","24":"","25":"","26":"","27":"","28":"","29":"","30":"","31":""},"Origin":"[-15 0 0]","ParticleColor":["[1 0 0]","[1 0.0938 0.0938]"],"ParticleAngles":["[0 0 0]","[0 0 0]"],"StartSize":[2.0,2.0],"StartAlpha":[255.0,255.0]}]], ["rotate indicator"] = [[{"ParticlesPerBurst":[1.0,1.0],"3D":true,"ParticleVelocity":["[0 0 0]","[0 0 0]"],"EndSize":[20.0,20.0],"AngularVelocity":["[0 0 -180]","[0 0 -180]"],"BurstDelay":[2.0,2.0],"Orbiting":false,"Bounciness":[0.0,0.0],"CollisionsEnabled":false,"EndAlpha":[255.0,255.0],"AirResistance":[0.0,0.0],"BurstDuration":[0.0,0.0],"Acceleration":["[0 0 0]","[0 0 0]"],"ClockwiseVelocityFromOrigin":[0.0,0.0],"SpawnDistance":[0.0,0.0],"VelocityFromOrigin":[0.0,0.0],"EndLength":[0.0,0.0],"StartLength":[0.0,0.0],"Unlit":true,"LifeTime":[2.05,2.05],"SpawnOffset":["[0 0 0]","[0 0 0]"],"MaterialList":{"2":"effects/wheel_ring","3":"","4":"","5":"","6":"","7":"","8":"","9":"","10":"","11":"","12":"","13":"","14":"","15":"","16":"","17":"","18":"","19":"","20":"","21":"","22":"","23":"","24":"","25":"","26":"","27":"","28":"","29":"","30":"","31":""},"Origin":"[15 0 0]","ParticleColor":["[1 1 1]","[1 1 1]"],"ParticleAngles":["[0 0 0]","[0 0 0]"],"StartSize":[20.0,20.0],"StartAlpha":[255.0,255.0]}]], ["simple explosion"] = [[{"ParticlesPerBurst":[100.0,100.0],"3D":false,"ParticleVelocity":["[0 0 0]","[0 0 0]"],"EndSize":[100.0,100.0],"AngularVelocity":["[0 0 0]","[0 0 0]"],"BurstDelay":[2.5,2.5],"Orbiting":false,"Bounciness":[0.0,0.0],"CollisionsEnabled":false,"EndAlpha":[0.0,0.0],"AirResistance":[0.0,0.0],"BurstDuration":[0.0,0.0],"Acceleration":["[0 0 0]","[0 0 0]"],"ClockwiseVelocityFromOrigin":[0.0,0.0],"SpawnDistance":[1.0,1.0],"VelocityFromOrigin":[100.0,150.0],"EndLength":[0.0,0.0],"StartLength":[0.0,0.0],"Unlit":true,"LifeTime":[2.5,2.5],"SpawnOffset":["[0 0 0]","[0 0 0]"],"MaterialList":{"2":"sprites/orangecore1_gmod","3":"","4":"","5":"","6":"","7":"","8":"","9":"","10":"","11":"","12":"","13":"","14":"","15":"","16":"","17":"","18":"","19":"","20":"","21":"","22":"","23":"","24":"","25":"","26":"","27":"","28":"","29":"","30":"","31":""},"Origin":"[0 0 0]","ParticleColor":["[1 0.5 0]","[1 0.5 0]"],"ParticleAngles":["[0 0 0]","[0 0 0]"],"StartSize":[10.0,10.0],"StartAlpha":[255.0,255.0]}]], ["smoke generator"] = [[{"ParticlesPerBurst":[1.0,1.0],"3D":false,"ParticleVelocity":["[0 0 0]","[0 0 0]"],"EndSize":[100.0,100.0],"AngularVelocity":["[0 0 0]","[0 0 0]"],"BurstDelay":[0.0,0.0],"Orbiting":false,"Bounciness":[1.0,1.0],"CollisionsEnabled":true,"EndAlpha":[0.0,0.0],"AirResistance":[100.0,100.0],"BurstDuration":[0.0,0.0],"Acceleration":["[0 0 -20]","[0 0 -20]"],"ClockwiseVelocityFromOrigin":[0.0,0.0],"SpawnDistance":[1.0,1.0],"VelocityFromOrigin":[200.0,500.0],"EndLength":[0.0,0.0],"StartLength":[0.0,0.0],"Unlit":true,"LifeTime":[10.0,10.0],"SpawnOffset":["[0 0 0]","[0 0 0]"],"MaterialList":{"2":"particles/smokey","3":"","4":"","5":"","6":"","7":"","8":"","9":"","10":"","11":"","12":"","13":"","14":"","15":"","16":"","17":"","18":"","19":"","20":"","21":"","22":"","23":"","24":"","25":"","26":"","27":"","28":"","29":"","30":"","31":""},"Origin":"[0 0 8]","ParticleColor":["[1 1 1]","[1 1 1]"],"ParticleAngles":["[0 0 0]","[0 0 0]"],"StartSize":[10.0,10.0],"StartAlpha":[255.0,255.0]}]], ["snow maker"] = [[{"ParticlesPerBurst":[2.0,2.0],"3D":false,"ParticleVelocity":["[-10 -10 -120]","[10 10 -120]"],"EndSize":[0.0,0.0],"AngularVelocity":["[0 0 0]","[0 0 0]"],"BurstDelay":[0.0,0.0],"Orbiting":false,"Bounciness":[0.0,0.0],"CollisionsEnabled":true,"EndAlpha":[255.0,255.0],"AirResistance":[0.0,0.0],"BurstDuration":[0.0,0.0],"Acceleration":["[0 0 0]","[0 0 0]"],"ClockwiseVelocityFromOrigin":[0.0,0.0],"SpawnDistance":[0.0,0.0],"VelocityFromOrigin":[0.0,0.0],"EndLength":[0.0,0.0],"StartLength":[0.0,0.0],"Unlit":true,"LifeTime":[10.0,10.0],"SpawnOffset":["[-500 -500 500]","[500 500 500]"],"MaterialList":{"2":"sprites/blueflare1_noz_gmod.vmt","3":"","4":"","5":"","6":"","7":"","8":"","9":"","10":"","11":"","12":"","13":"","14":"","15":"","16":"","17":"","18":"","19":"","20":"","21":"","22":"","23":"","24":"","25":"","26":"","27":"","28":"","29":"","30":"","31":""},"Origin":"[0 0 500]","ParticleColor":["[1 1 1]","[1 1 1]"],"ParticleAngles":["[0 0 0]","[0 0 0]"],"StartSize":[5.0,5.0],"StartAlpha":[0.0,0.0]}]], } for k,v in pairs(examples) do file.Write("hacpg_presets/examples/"..k..".dat", v) end end
-- Minichunkspy: Disassemble and reassemble chunks. -- Copyright M Joonas Pihlaja 2009 -- MIT license -- -- minichunkspy = require"minichunkspy" -- -- chunk = string.dump(loadfile"blabla.lua") -- disassembled_chunk = minichunkspy.disassemble(chunk) -- chunk = minichunkspy.assemble(disassembled_chunk) -- assert(minichunkspy.validate(<function or chunk>)) -- -- Tested on little-endian 32 and 64 bit platforms. local string, table, math = string, table, math local ipairs, setmetatable, type, assert = ipairs, setmetatable, type, assert local _ = __END_OF_GLOBALS__ local string_char, string_byte, string_sub = string.char, string.byte, string.sub local math_frexp, math_ldexp, math_abs = math.frexp, math.ldexp, math.abs local table_concat = table.concat local Inf = math.huge local NaN = Inf - Inf local BIG_ENDIAN = false local SIZEOF_SIZE_T = 4 local SIZEOF_INT = 4 local SIZEOF_NUMBER = 8 local save_stack = {} local function save() save_stack[#save_stack+1] = {BIG_ENDIAN, SIZEOF_SIZE_T, SIZEOF_INT, SIZEOF_NUMBER} end local function restore () BIG_ENDIAN, SIZEOF_SIZE_T, SIZEOF_INT, SIZEOF_NUMBER = unpack(save_stack[#save_stack]) save_stack[#save_stack] = nil end local function construct (class, self) return class.new(class, self) end local mt_memo = {} local Field = construct{ new = function (class, self) local self = self or {} local mt = mt_memo[class] or { __index = class, __call = construct } mt_memo[class] = mt return setmetatable(self, mt) end, } local None = Field{ unpack = function (self, bytes, ix) return nil, ix end, pack = function (self, val) return "" end } local char_memo = {} local function char(n) local field = char_memo[n] or Field{ unpack = function (self, bytes, ix) return string_sub(bytes, ix, ix+n-1), ix+n end, pack = function (self, val) return string_sub(val, 1, n) end } char_memo[n] = field return field end local uint8 = Field{ unpack = function (self, bytes, ix) return string_byte(bytes, ix, ix), ix+1 end, pack = function (self, val) return string_char(val) end } local uint32 = Field{ unpack = function (self, bytes, ix) local a,b,c,d = string_byte(bytes, ix, ix+3) if BIG_ENDIAN then a,b,c,d = d,c,b,a end return a + b*256 + c*256^2 + d*256^3, ix+4 end, pack = function (self, val) assert(type(val) == "number", "unexpected value type to pack as an uint32") local a,b,c,d d = val % 2^32 a = d % 256; d = (d - a) / 256 b = d % 256; d = (d - b) / 256 c = d % 256; d = (d - c) / 256 if BIG_ENDIAN then a,b,c,d = d,c,b,a end return string_char(a,b,c,d) end } local uint64 = Field{ unpack = function (self, bytes, ix) local a = uint32:unpack(bytes, ix) local b = uint32:unpack(bytes, ix+4) if BIG_ENDIAN then a,b = b,a end return a + b*2^32, ix+8 end, pack = function (self, val) assert(type(val) == "number", "unexpected value type to pack as an uint64") local a = val % 2^32 local b = (val - a) / 2^32 if BIG_ENDIAN then a,b = b,a end return uint32:pack(a) .. uint32:pack(b) end } local function explode_double(bytes, ix) local a = uint32:unpack(bytes, ix) local b = uint32:unpack(bytes, ix+4) if BIG_ENDIAN then a,b = b,a end --XXX: ARM mixed-endian local sig_hi = b % 2^20 local sig_lo = a local significand = sig_lo + sig_hi*2^32 b = (b - sig_hi) / 2^20 local biased_exp = b % 2^11 local sign = b <= biased_exp and 1 or -1 --print(sign, significand, biased_exp, "explode") return sign, biased_exp, significand end local function implode_double(sign, biased_exp, significand) --print(sign, significand, biased_exp, "implode") local sig_lo = significand % 2^32 local sig_hi = (significand - sig_lo) / 2^32 local a = sig_lo local b = ((sign < 0 and 2^11 or 0) + biased_exp)*2^20 + sig_hi if BIG_ENDIAN then a,b = b,a end --XXX: ARM mixed-endian return uint32.pack(nil, a) .. uint32.pack(nil, b) end local function math_sign(x) if x ~= x then return x end --sign of NaN is NaN if x == 0 then x = 1/x end --extract sign of zero return x > 0 and 1 or -1 end local SMALLEST_SUBNORMAL = math_ldexp(1, -1022 - 52) local SMALLEST_NORMAL = SMALLEST_SUBNORMAL * 2^52 local LARGEST_SUBNORMAL = math_ldexp(2^52 - 1, -1022 - 52) local LARGEST_NORMAL = math_ldexp(2^53 - 1, 1023 - 52) assert(SMALLEST_SUBNORMAL ~= 0.0 and SMALLEST_SUBNORMAL / 2 == 0.0) assert(LARGEST_NORMAL ~= Inf) assert(LARGEST_NORMAL * 2 == Inf) local double = Field{ unpack = function (self, bytes, ix) local sign, biased_exp, significand = explode_double(bytes, ix) local val if biased_exp == 0 then --subnormal val = math_ldexp(significand, -1022 - 52) elseif biased_exp == 2047 then val = significand == 0 and Inf or NaN --XXX: loses NaN mantissa else --normal val = math_ldexp(2^52 + significand, biased_exp - 1023 - 52) end val = sign*val return val, ix+8 end, pack = function (self, val) if val ~= val then return implode_double(1,2047,2^52-1) --XXX: loses NaN mantissa end local sign = math_sign(val) val = math_abs(val) if val == Inf then return implode_double(sign, 2047, 0) end if val == 0 then return implode_double(sign, 0, 0) end local biased_exp, significand if val <= LARGEST_SUBNORMAL then biased_exp = 0 significand = val / SMALLEST_SUBNORMAL else local frac, exp = math_frexp(val) significand = (2*frac - 1)*2^52 biased_exp = exp + 1022 end return implode_double(sign, biased_exp, significand) end } local Byte = uint8 local IntegralTypes = { [4] = uint32, [8] = uint64 } local FloatTypes = { [4] = float, [8] = double } local Size_t = Field{ unpack = function (self, bytes, ix) return IntegralTypes[SIZEOF_SIZE_T]:unpack(bytes, ix) end, pack = function (self, val) return IntegralTypes[SIZEOF_SIZE_T]:pack(val) end, } local Integer = Field{ unpack = function (self, bytes, ix) return IntegralTypes[SIZEOF_INT]:unpack(bytes, ix) end, pack = function (self, val) return IntegralTypes[SIZEOF_INT]:pack(val) end, } local Number = Field{ unpack = function (self, bytes, ix) return FloatTypes[SIZEOF_NUMBER]:unpack(bytes, ix) end, pack = function (self, val) return FloatTypes[SIZEOF_NUMBER]:pack(val) end, } -- Opaque types: local Insn = char(4) local Struct = Field{ unpack = function (self, bytes, ix) local val = {} local i,j = 1,1 while self[i] do local field = self[i] local key = field.name if not key then key, j = j, j+1 end --print("unpacking struct field", key, " at index ", ix) val[key], ix = field:unpack(bytes, ix) i = i+1 end return val, ix end, pack = function (self, val) local data = {} local i,j = 1,1 while self[i] do local field = self[i] local key = field.name if not key then key, j = j, j+1 end data[i] = field:pack(val[key]) i = i+1 end return table_concat(data) end } local List = Field{ unpack = function (self, bytes, ix) local len, ix = Integer:unpack(bytes, ix) local vals = {} local field = self.type for i=1,len do --print("unpacking list field", i, " at index ", ix) vals[i], ix = field:unpack(bytes, ix) end return vals, ix end, pack = function (self, vals) local len = #vals local data = { Integer:pack(len) } local field = self.type for i=1,len do data[#data+1] = field:pack(vals[i]) end return table_concat(data) end } local Boolean = Field{ unpack = function (self, bytes, ix) local val, ix = Integer:unpack(bytes, ix) assert(val == 0 or val == 1, "unpacked an unexpected value "..val.." for a Boolean") return val == 1, ix end, pack = function (self, val) assert(type(val) == "boolean", "unexpected value type to pack as a Boolean") return Integer:pack(val and 1 or 0) end } local String = Field{ unpack = function (self, bytes, ix) local len, ix = Size_t:unpack(bytes, ix) local val = nil if len > 0 then -- len includes trailing nul byte; ignore it local string_len = len - 1 val = bytes:sub(ix, ix+string_len-1) end return val, ix + len end, pack = function (self, val) assert(type(val) == "nil" or type(val) == "string", "unexpected value type to pack as a String") if val == nil then return Size_t:pack(0) end return Size_t:pack(#val+1) .. val .. "\000" end } local ChunkHeader = Struct{ char(4){name = "signature"}, Byte{name = "version"}, Byte{name = "format"}, Byte{name = "endianness"}, Byte{name = "sizeof_int"}, Byte{name = "sizeof_size_t"}, Byte{name = "sizeof_insn"}, Byte{name = "sizeof_Number"}, Byte{name = "integral_flag"}, } local ConstantTypes = { [0] = None, [1] = Boolean, [3] = Number, [4] = String, } local Constant = Field{ unpack = function (self, bytes, ix) local t, ix = Byte:unpack(bytes, ix) local field = ConstantTypes[t] assert(field, "unknown constant type "..t.." to unpack") local v, ix = field:unpack(bytes, ix) if t == 3 then assert(type(v) == "number") end return { type = t, value = v }, ix end, pack = function (self, val) local t, v = val.type, val.value return Byte:pack(t) .. ConstantTypes[t]:pack(v) end } local Local = Struct{ String{name = "name"}, Integer{name = "startpc"}, Integer{name = "endpc"} } local Function = Struct{ String{name = "name"}, Integer{name = "line"}, Integer{name = "last_line"}, Byte{name = "num_upvalues"}, Byte{name = "num_parameters"}, Byte{name = "is_vararg"}, Byte{name = "max_stack_size"}, List{name = "insns", type = Insn}, List{name = "constants", type = Constant}, List{name = "prototypes", type = nil}, --patch type below List{name = "source_lines", type = Integer}, List{name = "locals", type = Local}, List{name = "upvalues", type = String}, } assert(Function[10].name == "prototypes", "missed the function prototype list") Function[10].type = Function local Chunk = Field{ unpack = function (self, bytes, ix) local chunk = {} local header, ix = ChunkHeader:unpack(bytes, ix) assert(header.signature == "\027Lua", "signature check failed") assert(header.version == 81, "version mismatch") assert(header.format == 0, "format mismatch") assert(header.endianness == 0 or header.endianness == 1, "endianness mismatch") assert(IntegralTypes[header.sizeof_int], "int size unsupported") assert(IntegralTypes[header.sizeof_size_t], "size_t size unsupported") assert(header.sizeof_insn == 4, "insn size unsupported") assert(FloatTypes[header.sizeof_Number], "number size unsupported") assert(header.integral_flag == 0, "integral flag mismatch; only floats supported") save() BIG_ENDIAN = header.endianness == 0 SIZEOF_SIZE_T = header.sizeof_size_t SIZEOF_INT = header.sizeof_int SIZEOF_NUMBER = header.sizeof_Number chunk.header = header chunk.body, ix = Function:unpack(bytes, ix) restore() return chunk, ix end, pack = function (self, val) local data save() local header = val.header BIG_ENDIAN = header.endianness == 0 SIZEOF_SIZE_T = header.sizeof_size_t SIZEOF_INT = header.sizeof_int SIZEOF_NUMBER = header.sizeof_Number data = ChunkHeader:pack(val.header) .. Function:pack(val.body) restore() return data end } local function validate(chunk) if type(chunk) == "function" then return validate(string.dump(chunk)) end local f = Chunk:unpack(chunk, 1) local chunk2 = Chunk:pack(f) if chunk == chunk2 then return true end local i local len = math.min(#chunk, #chunk2) for i=1,len do local a = chunk:sub(i,i) local b = chunk:sub(i,i) if a ~= b then return false, ("chunk roundtripping failed: ".. "first byte difference at index %d"):format(i) end end return false, ("chunk round tripping failed: ".. "original length %d vs. %d"):format(#chunk, #chunk2) end return { disassemble = function (chunk) return Chunk:unpack(chunk, 1) end, assemble = function (disassembled) return Chunk:pack(disassembled) end, validate = validate }
-- Standard awesome library local gears = require("gears") local awful = require("awful") require("awful.autofocus") -- does not reside inside the default awesome 4.0 config rc.lua -- awful.rules = require("awful.rules") -- Widget and layout library local wibox = require("wibox") -- Theme handling library local beautiful = require("beautiful") -- Notification library local naughty = require("naughty") local menubar = require("menubar") local hotkeys_popup = require("awful.hotkeys_popup").widget -- {{{ Error handling -- Check if awesome encountered an error during startup and fell back to -- another config (This code will only ever execute for the fallback config) if awesome.startup_errors then naughty.notify({ preset = naughty.config.presets.critical, title = "Oops, there were errors during startup!", text = awesome.startup_errors }) end -- Handle runtime errors after startup do local in_error = false awesome.connect_signal("debug::error", function (err) -- Make sure we don't go into an endless error loop if in_error then return end in_error = true naughty.notify({ preset = naughty.config.presets.critical, title = "Oops, an error happened!", text = tostring(err) }) in_error = false end) end -- }}} -- {{{ Variable definitions -- Themes define colours, icons, and wallpapers beautiful.init("~/.config/awesome/lenny-theme/theme.lua") -- This is used later as the default terminal and editor to run. terminal = "lxterminal" editor = "code" editor_cmd = editor screenAdjust = "~/.config/awesome/lenny-theme/screen-adjust.sh" editAwesomeConfig = "code -n .config/awesome/" -- obviously cwd is ~ when spawning ;-) -- Default modkey. -- Usually, Mod4 is the key with a logo between Control and Alt. modkey = "Mod4" -- Table of layouts to cover with awful.layout.inc, order matters. awful.layout.layouts = { awful.layout.suit.tile, awful.layout.suit.tile.left, awful.layout.suit.tile.bottom, awful.layout.suit.tile.top, awful.layout.suit.fair, awful.layout.suit.fair.horizontal, awful.layout.suit.floating } menubar.utils.terminal = terminal -- Set the terminal for applications that require it awful.spawn(terminal) awful.spawn(terminal) awful.spawn.with_shell(screenAdjust) screenSpawningRule = { rule = { }, properties = { maximized = false, screen = 1, focus = true } } local function adjustScreenSpawningRule(screenIndex) if type(screenIndex) ~= "number" then -- naughty.notify({ preset = naughty.config.presets.normal, -- title = "FYI", -- text = "We noticed this is not a number!"}) return end -- naughty.notify({ preset = naughty.config.presets.normal, -- title = "FYI", -- text = "I set the screenSpawningRule to have screen: " .. tostring(screenIndex)}) screenSpawningRule.properties.screen = screenIndex end local function assertMouseIsInFocusedScreen(c) -- naughty.notify({ preset = naughty.config.presets.normal, -- title = "FYI", -- text = "mouse is in: " .. mouse.screen.index .. " and focus is on: " .. c.screen.index}) if mouse.screen.index == c.screen.index then return end -- naughty.notify({ preset = naughty.config.presets.normal, -- title = "FYI", -- text = "We should use the force!"}) -- use the force sloppily to make mouse move on that screen awful.screen.focus(c.screen) end -- {{{ All Wiboxes --------------------------------------------------------------------------------------------- -- Wallpaper local function init_screen(s) -- hide all panels if s.screenToppanel then s.screenToppanel.visible = false end if s.screenLeftpanel then s.screenLeftpanel.visible = false end if s.screenBottompanel then s.screenBottompanel.visible = false end -- Wallpaper if beautiful.wallpaper then local wallpaper = beautiful.wallpaper -- If wallpaper is a function, call it with the screen if type(wallpaper) == "function" then wallpaper = wallpaper(s) end gears.wallpaper.maximized(wallpaper, s, true) end end screen.connect_signal("property::geometry", init_screen) -- Create a textclock widget as global widget because it is the same for each screen mytextclock = awful.widget.textclock() --mytaglist.buttons = awful.util.table.join( local taglist_buttons = awful.util.table.join( awful.button({ }, 1, function(t) t:view_only() end), awful.button({ modkey }, 1, function(t) if client.focus then client.focus:move_to_tag(t) end end), awful.button({ }, 3, awful.tag.viewtoggle), awful.button({ modkey }, 3, function(t) if client.focus then client.focus:toggle_tag(t) end end), awful.button({ }, 4, function(t) awful.tag.viewnext(t.screen) end), awful.button({ }, 5, function(t) awful.tag.viewprev(t.screen) end) ) --mytasklist = {} --mytasklist.buttons = awful.util.table.join( local tasklist_buttons = awful.util.table.join( awful.button({ }, 1, function (c) if c == client.focus then c.minimized = true else -- Without this, the following -- :isvisible() makes no sense c.minimized = false if not c:isvisible() and c.first_tag then c.first_tag:view_only() end -- This will also un-minimize -- the client, if needed client.focus = c c:raise() end end), awful.button({ }, 3, function () -- showing the menu? / not for me :-) end), awful.button({ }, 4, function () awful.client.focus.byidx(1) if client.focus then client.focus:raise() end end), awful.button({ }, 5, function () awful.client.focus.byidx(-1) if client.focus then client.focus:raise() end end)) -- set up all the screens, by attaching awful.screen.connect_for_each_screen( function(s) --give every screen it's own tag "table" awful.tag({ "1", "2", "3", "4", "5", "6", "7", "8", "9" }, s, awful.layout.layouts[1]) --layoutbox every screen has it's own current layout - layoutbox is indicating the current layout s.screenLayoutbox = awful.widget.layoutbox(s) s.screenLayoutbox:buttons( awful.util.table.join( awful.button({ }, 1, function () awful.layout.inc( 1) end), awful.button({ }, 3, function () awful.layout.inc(-1) end), awful.button({ }, 4, function () awful.layout.inc( 1) end), awful.button({ }, 5, function () awful.layout.inc(-1) end) ) ) --create taglist widget s.screenTaglist = awful.widget.taglist(s, awful.widget.taglist.filter.all, taglist_buttons) --create tasklist widget s.screenTasklist = awful.widget.tasklist(s, awful.widget.tasklist.filter.currenttags, tasklist_buttons) --create the panels s.screenBottompanel = awful.wibar({ position = "bottom", screen = s }) s.screenLeftpanel = awful.wibar({ position = "left", screen = s }) s.screenToppanel = awful.wibar({ position = "top", screen = s }) -- the leftpanel -- not yet any entries here... s.screenLeftpanel:setup { layout = wibox.layout.fixed.vertical, { layout = wibox.layout.fixed.horizontal, wibox.widget{ markup = tostring(s.index), align = 'center', valign = 'center', widget = wibox.widget.textbox } }, -- nil, nil, nil } -- the bottompanel s.screenBottompanel:setup { layout = wibox.layout.align.horizontal, { -- Left widgets^^ layout = wibox.layout.fixed.horizontal, s.screenLayoutbox, s.screenTaglist }, nil, -- Middle widget { -- Right widgets layout = wibox.layout.fixed.horizontal, mytextclock } } -- the toppanel s.screenToppanel:setup { layout = wibox.layout.align.horizontal, { -- Left widgets layout = wibox.layout.fixed.horizontal, s.screenTasklist }, nil, -- Middle widget nil -- Right widget } init_screen(s) end ) -- {{{ Key bindings globalkeys = awful.util.table.join( awful.key({ modkey, }, "Left", awful.tag.viewprev ), awful.key({ modkey, }, "Right", awful.tag.viewnext ), -- navigation awful.key({ modkey, }, "w", function () awful.client.focus.byidx( 1) if client.focus then client.focus:raise() end end), awful.key({ modkey, }, "s", function () awful.client.focus.byidx(-1) if client.focus then client.focus:raise() end end), awful.key({ modkey, }, "a", function () awful.screen.focus_relative( 1) end), awful.key({ modkey, }, "d", function () awful.screen.focus_relative(-1) end), -- Layout manipulation awful.key({ modkey, "Shift" }, "j", function () awful.client.swap.byidx( 1) end), awful.key({ modkey, "Shift" }, "k", function () awful.client.swap.byidx( -1) end), -- Standard program awful.key({ modkey, }, "t", function () adjustScreenSpawningRule(mouse.screen.index) awful.spawn(terminal) end ), awful.key({ modkey, }, "´", function () -- TODO write this functionality on another key...^^ -- naughty.notify({ preset = naughty.config.presets.normal, -- title = "FYI", -- text = "Pause key did work!" }) awful.spawn.with_shell(screenAdjust) end ), awful.key({ modkey, }, "#", function () adjustScreenSpawningRule(mouse.screen.index) awful.spawn.with_shell(editAwesomeConfig) end ), awful.key({ modkey, "Shift" }, "^", awesome.restart), awful.key({ modkey, "Shift" }, "Escape", awesome.quit), awful.key({ modkey, }, "l", function () awful.tag.incmwfact( 0.05) end), awful.key({ modkey, }, "h", function () awful.tag.incmwfact(-0.05) end), awful.key({ modkey, "Shift" }, "h", function () awful.tag.incnmaster( 1) end), awful.key({ modkey, "Shift" }, "l", function () awful.tag.incnmaster(-1) end), awful.key({ modkey, "Control" }, "h", function () awful.tag.incncol( 1) end), awful.key({ modkey, "Control" }, "l", function () awful.tag.incncol(-1) end), awful.key({ modkey, }, "Up", function () awful.layout.inc( 1) end), awful.key({ modkey, }, "Down", function () awful.layout.inc(-1) end), awful.key({ modkey, "Control" }, "n", awful.client.restore), -- Menubar awful.key({ modkey }, "p", function() adjustScreenSpawningRule(mouse.screen.index) menubar.show() end), -- show/hide all wiboxes awful.key({ modkey}, "v", function () --check how much boxes are visible local mostly_seen = 0 if mouse.screen.screenToppanel.visible then mostly_seen = mostly_seen + 1 end if mouse.screen.screenLeftpanel.visible then mostly_seen = mostly_seen + 1 end if mouse.screen.screenBottompanel.visible then mostly_seen = mostly_seen + 1 end --when more then the half of them is visible hide othervise show them all if mostly_seen >= 2 then mouse.screen.screenToppanel.visible = false mouse.screen.screenLeftpanel.visible = false mouse.screen.screenBottompanel.visible = false else mouse.screen.screenToppanel.visible = true mouse.screen.screenLeftpanel.visible = true mouse.screen.screenBottompanel.visible = true end end ), -- selective show/hide awful.key({ modkey}, "b", function () mouse.screen.screenBottompanel.visible = not mouse.screen.screenBottompanel.visible end ), awful.key({ modkey}, "c", function () mouse.screen.screenLeftpanel.visible = not mouse.screen.screenLeftpanel.visible end ), awful.key({ modkey}, "g", function () mouse.screen.screenToppanel.visible = not mouse.screen.screenToppanel.visible end ) ) clientkeys = awful.util.table.join( awful.key({ modkey, }, "Return", function (c) c.fullscreen = not c.fullscreen end), awful.key({ modkey, }, "Delete", function (c) c:kill() end), awful.key({ modkey, "Control" }, "space", awful.client.floating.toggle ), awful.key({ modkey, "Control" }, "Return", function (c) c:swap(awful.client.getmaster()) end), awful.key({ modkey, }, "o", awful.client.movetoscreen ), awful.key({ modkey, }, "-", function (c) c.ontop = not c.ontop end), awful.key({ modkey, }, "n", function (c) -- The client currently has the input focus, so it cannot be -- minimized, since minimized clients can't have the focus. c.minimized = true end)--, ) -- Bind all key numbers to tags. -- Be careful: we use keycodes to make it work on any keyboard layout. -- This should map on the top row of your keyboard, usually 1 to 9. for i = 1, 9 do globalkeys = awful.util.table.join(globalkeys, awful.key({ modkey }, "#" .. i + 9, function () local screen = mouse.screen local tag = awful.tag.gettags(screen)[i] if tag then awful.tag.viewonly(tag) end end), awful.key({ modkey, "Control" }, "#" .. i + 9, function () local screen = mouse.screen local tag = awful.tag.gettags(screen)[i] if tag then awful.tag.viewtoggle(tag) end end), awful.key({ modkey, "Shift" }, "#" .. i + 9, function () if client.focus then local tag = awful.tag.gettags(client.focus.screen)[i] if tag then awful.client.movetotag(tag) end end end), awful.key({ modkey, "Control", "Shift" }, "#" .. i + 9, function () if client.focus then local tag = awful.tag.gettags(client.focus.screen)[i] if tag then awful.client.toggletag(tag) end end end)) end clientbuttons = awful.util.table.join( awful.button({ }, 1, function (c) client.focus = c; c:raise() end), awful.button({ modkey }, 1, awful.mouse.client.move), awful.button({ modkey }, 3, awful.mouse.client.resize) ) -- Set keys root.keys(globalkeys) -- }}} -- {{{ Rules awful.rules.rules = { -- All clients will match this rule. { rule = { }, properties = { border_width = beautiful.border_width, border_color = beautiful.border_normal, keys = clientkeys, buttons = clientbuttons } }, screenSpawningRule } -- }}} -- {{{ Signals -- Signal function to execute when a new client appears. client.connect_signal("manage", function (c, startup) -- Enable sloppy focus --c:connect_signal("mouse::enter", function(c) -- if awful.layout.get(c.screen) ~= awful.layout.suit.magnifier -- and awful.client.focus.filter(c) then -- client.focus = c -- end --end) if not startup then -- Set the windows at the slave, -- i.e. put it at the end of others instead of setting it master. -- awful.client.setslave(c) -- Put windows in a smart way, only if they does not set an initial position. if not c.size_hints.user_position and not c.size_hints.program_position then awful.placement.no_overlap(c) awful.placement.no_offscreen(c) end end local titlebars_enabled = false if titlebars_enabled and (c.type == "normal" or c.type == "dialog") then -- buttons for the titlebar local buttons = awful.util.table.join( awful.button({ }, 1, function() client.focus = c c:raise() awful.mouse.client.move(c) end), awful.button({ }, 3, function() client.focus = c c:raise() awful.mouse.client.resize(c) end) ) -- Widgets that are aligned to the left local left_layout = wibox.layout.fixed.horizontal() left_layout:add(awful.titlebar.widget.iconwidget(c)) left_layout:buttons(buttons) -- Widgets that are aligned to the right local right_layout = wibox.layout.fixed.horizontal() right_layout:add(awful.titlebar.widget.floatingbutton(c)) right_layout:add(awful.titlebar.widget.maximizedbutton(c)) right_layout:add(awful.titlebar.widget.stickybutton(c)) right_layout:add(awful.titlebar.widget.ontopbutton(c)) right_layout:add(awful.titlebar.widget.closebutton(c)) -- The title goes in the middle local middle_layout = wibox.layout.flex.horizontal() local title = awful.titlebar.widget.titlewidget(c) title:set_align("center") middle_layout:add(title) middle_layout:buttons(buttons) -- Now bring it all together local layout = wibox.layout.align.horizontal() layout:set_left(left_layout) layout:set_right(right_layout) layout:set_middle(middle_layout) awful.titlebar(c):set_widget(layout) end end) -- awful.tag.connect_signal("request::select", function(s) -- naughty.notify({ preset = naughty.config.presets.normal, -- title = "FYI", -- text = "I have been called"}) -- end) -- client.connect_signal("property::screen", function(s) -- naughty.notify({ preset = naughty.config.presets.normal, -- title = "FYI", -- text = "I have been called, screen property fo client Changed!"}) -- end) -- screen.connect_signal("focus", function(s) -- naughty.notify({ preset = naughty.config.presets.normal, -- title = "FYI", -- text = "I have been called - screen focus signal!"}) -- end) -- client.connect_signal("mouse::enter", function(c) adjustScreenSpawningRule(c.screen.index); end) client.connect_signal("focus", function(c) c.border_color = beautiful.border_focus; adjustScreenSpawningRule(c.screen.index); assertMouseIsInFocusedScreen(c) end) client.connect_signal("unfocus", function(c) c.border_color = beautiful.border_normal end) -- }}} -- monkey path to do some magic ;-) local original_focus = awful.screen.focus awful.screen.focus = function(leScreen) original_focus(leScreen) adjustScreenSpawningRule(leScreen) -- naughty.notify({ preset = naughty.config.presets.normal, -- title = "FYI", -- text = "We used the monkey magic!"}) -- unfocus the the client when he is not in the current screen. -- todo end
-- trackselect.lua -- -- Because --slang isn't smart enough. -- -- This script tries to select non-dub -- audio and subtitle tracks. -- Idea from https://github.com/siikamiika/scripts/blob/master/mpv%20scripts/dualaudiofix.lua local defaults = { audio = { selected = nil, best = {}, lang_score = nil, channels_score = -math.huge, preferred = "jpn/japanese", excluded = "", expected = "", id = "" }, video = { selected = nil, best = {}, lang_score = nil, preferred = "", excluded = "", expected = "", id = "" }, sub = { selected = nil, best = {}, lang_score = nil, preferred = "eng", excluded = "sign", expected = "", id = "" } } local options = { enabled = true, -- Do track selection synchronously, plays nicer with other scripts hook = true, -- Mimic mpv's track list fingerprint to preserve user-selected tracks across files fingerprint = true, -- Override user's explicit track selection force = false, -- Try to re-select the last track if mpv cannot do it e.g. when fingerprint changes smart_keep = false } for _type, track in pairs(defaults) do options["preferred_" .. _type .. "_lang"] = track.preferred options["excluded_" .. _type .. "_words"] = track.excluded options["expected_" .. _type .. "_words"] = track.expected end options["preferred_audio_channels"] = "" local tracks = {} local last = {} local fingerprint = "" mp.options = require "mp.options" function contains(track, words, attr) if not track[attr] then return false end local i = 0 if track.external then i = 1 end for word in string.gmatch(words:lower(), "([^/]+)") do i = i - 1 if string.match(tostring(track[attr] or ""):lower(), word) then return i end end return false end function preferred(track, words, attr, title) local score = contains(track, words, attr) if not score then if tracks[track.type][title] == nil then tracks[track.type][title] = -math.huge return true end return false end if tracks[track.type][title] == nil or score > tracks[track.type][title] then tracks[track.type][title] = score return true end return false end function preferred_or_equals(track, words, attr, title) local score = contains(track, words, attr) if not score then if tracks[track.type][title] == nil then return true end return false end if tracks[track.type][title] == nil or score >= tracks[track.type][title] then return true end return false end function copy(obj) if type(obj) ~= "table" then return obj end local res = {} for k, v in pairs(obj) do res[k] = copy(v) end return res end function track_layout_hash(tracklist) local t = {} for _, track in ipairs(tracklist) do t[#t+1] = string.format("%s-%d-%s-%s-%s-%s", track.type, track.id, tostring(track.default), tostring(track.external), track.lang or "", track.external and "" or (track.title or "")) end return table.concat(t, "\n") end function trackselect() mp.options.read_options(options, "trackselect") if not options.enabled then return end tracks = copy(defaults) local filename = mp.get_property("filename/no-ext") local tracklist = mp.get_property_native("track-list") local tracklist_changed = false local found_last = {} if options.fingerprint then local new_fingerprint = track_layout_hash(tracklist) if new_fingerprint == fingerprint then return end fingerprint = new_fingerprint tracklist_changed = true end for _, track in ipairs(tracklist) do if options.smart_keep and last[track.type] ~= nil and last[track.type].lang == track.lang and last[track.type].codec == track.codec and last[track.type].external == track.external and last[track.type].title == track.title then tracks[track.type].best = track options["preferred_" .. track.type .. "_lang"] = "" options["excluded_" .. track.type .. "_words"] = "" options["expected_" .. track.type .. "_words"] = "" options["preferred_" .. track.type .. "_channels"] = "" found_last[track.type] = true elseif not options.force and (tracklist_changed or not options.fingerprint) then if tracks[track.type].id == "" then tracks[track.type].id = mp.get_property(track.type:sub(1, 1) .. "id", "auto") end if tracks[track.type].id ~= "auto" then options["preferred_" .. track.type .. "_lang"] = "" options["excluded_" .. track.type .. "_words"] = "" options["expected_" .. track.type .. "_words"] = "" options["preferred_" .. track.type .. "_channels"] = "" end end if options["preferred_" .. track.type .. "_lang"] ~= "" or options["excluded_" .. track.type .. "_words"] ~= "" or options["expected_" .. track.type .. "_words"] ~= "" or (options["preferred_" .. track.type .. "_channels"] or "") ~= "" then if track.selected then tracks[track.type].selected = track.id if options.smart_keep then last[track.type] = track end end if track.external then track.title = string.gsub(string.gsub(track.title, "%W", "%%%1"), filename, "") end if next(tracks[track.type].best) == nil or not (tracks[track.type].best.external and tracks[track.type].best.lang ~= nil) then if options["excluded_" .. track.type .. "_words"] == "" or not contains(track, options["excluded_" .. track.type .. "_words"], "title") then if options["expected_" .. track.type .. "_words"] == "" or contains(track, options["expected_" .. track.type .. "_words"], "title") then local pass = true local channels = false local lang = false if (options["preferred_" .. track.type .. "_channels"] or "") ~= "" and preferred_or_equals(track, options["preferred_" .. track.type .. "_lang"], "lang", "lang_score") then channels = preferred(track, options["preferred_" .. track.type .. "_channels"], "demux-channel-count", "channels_score") pass = channels end if options["preferred_" .. track.type .. "_lang"] ~= "" then lang = preferred(track, options["preferred_" .. track.type .. "_lang"], "lang", "lang_score") end if (options["preferred_" .. track.type .. "_lang"] == "" and pass) or channels or lang or (track.external and track.lang == nil and (not tracks[track.type].best.external or tracks[track.type].best.lang == nil)) then tracks[track.type].best = track end end end end end end for _type, track in pairs(tracks) do if next(track.best) ~= nil and track.best.id ~= track.selected then mp.set_property(_type:sub(1, 1) .. "id", track.best.id) if options.smart_keep and found_last[track.best.type] then last[track.best.type] = track.best end end end end function selected_tracks() local tracklist = mp.get_property_native("track-list") last = {} for _, track in ipairs(tracklist) do if track.selected then last[track.type] = track end end end if options.hook then mp.add_hook("on_preloaded", 50, trackselect) else mp.register_event("file-loaded", trackselect) end if options.smart_keep then mp.register_event("track-switched", selected_tracks) end
local Items = { { -- Ice ["titleBGA"] = color("#4488FF"), ["titleBGB"] = color("#112244"), ["titleBGPattern"] = color("#4488FF"), ["swmeHF"] = color("#224488"), ["swmeFooter"] = color("#224488"), ["swmeBGA"] = color("#224488"), ["swmeBGB"] = color("#224488"), ["swmeGrid"] = color("#224488"), ["swmePattern"] = color("#22448850"), ["serviceBG"] = color("#224488"), ["playModeIconsBaseColor"] = color("#4488FF73"), ["playModeIconsBaseGradient"] = color("#22448873"), ["playModeIconsEmblem"] = color("#FFFFFF75"), ["headerTextColor"] = color("#FFFFFF"), ["headerTextGradient"] = color("#BBDDFF"), ["midShadeA"] = color("#4488FF"), ["headerSortA"] = color("#224488"), ["headerSortB"] = color("#112244"), ["headerStripeA"] = color("#224488"), ["headerStripeB"] = color("#4488FF"), ["promptBG"] = color("#112244"), ["wheelHighlightFade"] = color("#4488FF50"), ["wheelHighlightA"] = color("#FFFFFF"), ["wheelHighlightB"] = color("#4488FF"), ["wheelSongItem"] = color("#000000"), ["wheelSectionItemA"] = color("#4488FF"), ["wheelSectionItemB"] = color("#4488FF"), ["SSMHelpPopup"] = color("#000000"), ["gameplayHeader"] = color("#000000"), ["gameplayTitle"] = color("#FFFFFF"), ["gameplayMeter"] = color("#000000"), ["lifeFrame"] = color("#112244"), ["lifeMeter"] = color("#224488"), ["menuBlockBase"] = color("#000000"), ["menuBlockGlow"] = color("#000000"), ["titlemenuBlockGlow"] = color("#112244"), ["menuBlockHighlightA"] = color("#FFFFFF"), ["menuBlockHighlightB"] = color("#4488FF"), ["menuTextGainFocus"] = color("#FFFFFF"), ["menuTextLoseFocus"] = color("#4488FF"), ["optionExplanationBG"] = color("#00000050") } -- end Ice }
return { hand_left = { { {9, 40}, {12, 35}, {7, 39}, {-1, 38}, {0, 0}, {9, 40}, {9, 40}, {10, 40}, {8, 40}, {9, 39}, {1, 40}, {-10, 40}, }, { {9, 40}, {12, 32}, {7, 38}, {-2, 38}, {0, 0}, {-10, 40}, {-10, 40}, {-10, 40}, {-10, 40}, {-9, 38}, {-1, 40}, {-10, 40}, }, { {14, 30}, {0, 0}, {0, 0}, {18, 34}, {0, 0}, {-17, 45}, {14, 25}, {20, 40}, {10, 40}, {10, 40}, {10, 40}, {10, 40}, }, { {15, 30}, {0, 0}, {0, 0}, {10, 26}, {0, 0}, {12, 36}, {14, 25}, {5, 30}, {14, 28}, {18, 30}, {15, 32}, {19, 32}, }, { {5, 24}, {5, 22}, {5, 23}, {0, 0}, {0, 0}, {5, 22}, {11, 25}, {9, 25}, {10, 25}, {5, 33}, {2, 46}, {15, 29}, }, { {12, 24}, {12, 22}, {12, 23}, {0, 0}, {0, 0}, {12, 22}, {-13, 25}, {-13, 25}, {-13, 25}, {13, 32}, {8, 46}, {0, 0}, }, { {-4, 28}, {-4, 26}, {-4, 27}, {0, 0}, {0, 0}, {-4, 26}, {3, 41}, {3, 39}, {3, 40}, {0, 0}, {0, 0}, {3, 39}, }, { {14, 25}, {15, 23}, {15, 24}, {0, 0}, {0, 0}, {15, 23}, {13, 40}, {13, 38}, {13, 39}, {0, 0}, {0, 0}, {13, 38}, }, { {9, 40}, {9, 38}, {9, 39}, {9, 38}, {9, 40}, {9, 38}, {9, 39}, {9, 38}, {9, 40}, {11, 35}, {7, 39}, {7, 38}, }, { {17, 23}, {17, 21}, {17, 22}, {17, 21}, {17, 38}, {17, 36}, {17, 37}, {17, 36}, {18, 32}, {18, 30}, {18, 31}, {18, 30}, }, { {5, 26}, {-10, 31}, {3, 31}, {9, 29}, {5, 26}, {-10, 31}, {3, 31}, {10, 29}, {5, 23}, {-10, 27}, {3, 27}, {10, 25}, }, { {18, 31}, {18, 31}, {18, 31}, {17, 31}, {18, 31}, {18, 31}, {18, 31}, {18, 31}, {18, 27}, {18, 27}, {18, 27}, {18, 27}, }, { {-1, 46}, {-1, 46}, {0, 46}, {-1, 46}, {10, 43}, {9, 44}, {4, 46}, {10, 44}, {2, 37}, {1, 45}, {1, 33}, {0, 0}, }, { {10, 46}, {11, 46}, {12, 46}, {11, 46}, {-10, 38}, {-11, 33}, {-9, 34}, {-10, 33}, {16, 35}, {16, 45}, {16, 32}, {0, 0}, }, { {-9, 32}, {-9, 32}, {-9, 32}, {0, 0}, {-9, 31}, {-9, 31}, {-9, 31}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, }, { {12, 32}, {12, 32}, {12, 32}, {0, 0}, {12, 31}, {12, 31}, {12, 31}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, }, }, hand_right = { { {-10, 40}, {-13, 32}, {-8, 38}, {3, 37}, {0, 0}, {-10, 40}, {-10, 40}, {-10, 40}, {-10, 39}, {-9, 40}, {0, 40}, {9, 40}, }, { {-10, 40}, {-12, 35}, {-8, 39}, {0, 38}, {0, 0}, {9, 40}, {9, 40}, {9, 40}, {8, 38}, {9, 40}, {-2, 40}, {9, 40}, }, { {-16, 30}, {0, 0}, {0, 0}, {-10, 26}, {0, 0}, {-13, 36}, {-15, 25}, {-7, 30}, {-15, 28}, {-18, 30}, {-16, 32}, {-20, 32}, }, { {-15, 30}, {0, 0}, {0, 0}, {-18, 34}, {0, 0}, {16, 45}, {-15, 25}, {-21, 40}, {-11, 40}, {-10, 40}, {-11, 40}, {-11, 40}, }, { {-13, 24}, {-13, 22}, {-13, 23}, {0, 0}, {0, 0}, {-13, 22}, {-10, 25}, {-11, 25}, {-10, 25}, {-13, 32}, {-9, 46}, {-17, 29}, }, { {-6, 24}, {-6, 22}, {-6, 23}, {0, 0}, {0, 0}, {-6, 22}, {9, 25}, {9, 25}, {9, 25}, {-5, 33}, {-3, 46}, {0, 0}, }, { {-16, 25}, {-16, 23}, {-16, 24}, {0, 0}, {0, 0}, {-16, 23}, {-14, 40}, {-14, 38}, {-14, 39}, {0, 0}, {0, 0}, {-14, 38}, }, { {2, 28}, {3, 26}, {3, 27}, {0, 0}, {0, 0}, {3, 26}, {-4, 41}, {-4, 39}, {-4, 40}, {0, 0}, {0, 0}, {-4, 39}, }, { {-18, 23}, {-18, 21}, {-18, 22}, {-18, 21}, {-18, 38}, {-18, 36}, {-18, 37}, {-18, 36}, {-19, 32}, {-19, 30}, {-19, 31}, {-19, 30}, }, { {-10, 40}, {-10, 38}, {-10, 39}, {-10, 38}, {-10, 40}, {-10, 38}, {-10, 39}, {-10, 38}, {-10, 40}, {-13, 35}, {-8, 39}, {-8, 38}, }, { {-19, 31}, {-19, 31}, {-19, 31}, {-19, 31}, {-19, 31}, {-19, 31}, {-19, 31}, {-19, 31}, {-19, 27}, {-19, 27}, {-19, 27}, {-19, 27}, }, { {-6, 26}, {9, 31}, {-4, 31}, {-12, 29}, {-6, 26}, {9, 31}, {-4, 31}, {-11, 29}, {-6, 22}, {9, 27}, {-4, 27}, {-11, 25}, }, { {-11, 46}, {-12, 46}, {-13, 46}, {-12, 46}, {-3, 46}, {-8, 44}, {-8, 43}, {-8, 44}, {-17, 35}, {-17, 45}, {-17, 33}, {0, 0}, }, { {0, 46}, {-1, 46}, {-2, 46}, {-1, 46}, {10, 34}, {11, 33}, {11, 38}, {12, 33}, {-3, 37}, {-2, 45}, {-2, 33}, {0, 0}, }, { {-13, 32}, {-13, 32}, {-13, 32}, {0, 0}, {-13, 31}, {-13, 31}, {-13, 31}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, }, { {8, 32}, {8, 32}, {8, 32}, {0, 0}, {8, 31}, {8, 31}, {8, 31}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, }, }, }
local playsession = { {"Turbulent_Bread", {1902}}, {"Chevalier1200", {5595}}, {"ETK03", {99384}}, {"StormBreaker", {88794}}, {"tickterd", {71586}} } return playsession
---- TODO: make this a module with creation arguments, &c -- build a JI rate knob that goes through zero local ji = dofile(_path.code .. 'zebra/lib/ji.lua') -- the gamut local gam = ji.partch() n = #gam print("gamut size: "..#gam) -- multiply index by float, return pair gam.fmul = function(i,f) return { f*gam[i][1], gam[i][2] } end -- divide index by float, return pair gam.fdiv = function(i,f) return { gam[i][1], gam[i][2]*f } end -- multiply scale index by pair, return pair gam.mul = function(i, p) return { p[1] * gam[i][1], p[2] * gam[i][2] } end -- get float for index gam.f = function(i) if gam[i][2] == 0 then return 0 else return gam[i][1] / gam[i][2] end end local octa = 3 -- octaves above local octb = 3 -- octaves below local r = 0 -- current ratio local o = nil -- current octave local i = 0 -- current index local pval = {} -- list of positive values local plo = 2 ^ (-1 * octb) -- positive lower bound local phi = 2 ^ (octa) -- positive upper bound -- generating o = -1 * octb while o < octa do print("octave: " .. o) i = 0 while i < n do i=i+1 --print(i) if (o<0) then pval[#pval + 1] = gam.fdiv(i, 2^(-1*o)) else pval[#pval + 1] = gam.fmul(i, 2^o) end end o = o + 1 end pval[#pval + 1] = { phi, 1}; -- build bipolar values local bval = {} i = #pval print("negative...") while i > 0 do --print(i) bval[#bval + 1] = {pval[i][1] * -1, pval[i][2]} i=i-1 end ----- ZERO bval[#bval+1] = {0,1} i = 0 print("positive again...") while i < #pval do i = i + 1 bval[#bval + 1] = pval[i] end print("done.") pval = nil local nob = {} for k,v in pairs(bval) do nob[k] = { v[1], v[2], v[1]/v[2] } end for k,v in pairs(nob) do if v[1] == -1 and v[2] == 1 then print(k, v[1], v[2], v[3]) end if v[1] == 0 and v[2] == 1 then print(k, v[1], v[2], v[3]) end if v[1] == 1 and v[2] == 1 then print(k, v[1], v[2], v[3]) end end bval = nil return nob
local _ = function(k,...) return ImportPackage("i18n").t(GetPackageName(),k,...) end gatherTable = { --[[ { gather_zone = { 186601, -39031, 1451 }, gather_item = "unprocessed_weed", process_zone = { 70695, 9566, 1366 }, process_item = "processed_weed" }, { gather_zone = { 186474, -43277, 1451 }, gather_item = "unprocessed_heroin", process_zone = { 73218, 3822, 1367 }, process_item = "processed_heroin" }, { gather_zone = { 193607, -46512, 1451 }, gather_item = "unprocessed_meth", process_zone = { 72095, 1418, 1367 }, process_item = "processed_meth" }, { gather_zone = { 192080, -45155, 1529 }, gather_item = "unprocessed_coke", process_zone = { 71981, 106, 1367 }, process_item = "processed_coke" }, ]] { gather_zone = { -96766, 88886, 180 }, gather_item = "unprocessed_rock", gather_tool = "pickaxe", process_zone = { -82629, 90991, 481 }, process_item = "processed_rock" }, { gather_zone = { 232464, 193521, 112 }, gather_item = "fish", gather_tool = "fishing_rod", }, } gatherZoneCached = {} processZoneCached = {} AddEvent("OnPackageStart", function() for k,v in pairs(gatherTable) do if v.gather_zone ~= nil then v.gatherObject = CreatePickup(2, v.gather_zone[1], v.gather_zone[2], v.gather_zone[3]) CreateText3D(_("gather").."\n".._("press_e"), 18, v.gather_zone[1], v.gather_zone[2], v.gather_zone[3] + 120, 0, 0, 0) table.insert(gatherZoneCached, v.gatherObject) end if v.process_zone ~= nil then v.processObject = CreatePickup(2, v.process_zone[1], v.process_zone[2], v.process_zone[3]) CreateText3D(_("process").."\n".._("press_e"), 18, v.process_zone[1], v.process_zone[2], v.process_zone[3] + 120, 0, 0, 0) table.insert(processZoneCached, v.processObject) end end end) AddEvent("OnPlayerJoin", function(player) CallRemoteEvent(player, "gatheringSetup", gatherZoneCached, processZoneCached) end) AddEvent("OnPlayerDeath", function(player) PlayerData[player].onAction = false PlayerData[player].isActioned = false end) AddRemoteEvent("StartGathering", function(player, gatherzone) local gather = GetGatherByGatherzone(gatherzone) local animation = "" local attached_item = 0 if gatherTable[gather].gather_tool ~= nil then if PlayerData[player].inventory[gatherTable[gather].gather_tool] == nil then return CallRemoteEvent(player, "MakeNotification", _("need_tool"), "linear-gradient(to right, #ff5f6d, #ffc371)") end end if PlayerData[player].onAction then PlayerData[player].onAction = false return end if GetPlayerVehicle(player) ~= 0 then return end if gatherTable[gather].gather_tool == "pickaxe" then animation = "PICKAXE_SWING" attached_item = 1063 elseif gatherTable[gather].gather_tool == "fishing_rod" then animation = "FISHING" attached_item = 1111 else animation = "PICKUP_LOWER" end PlayerData[player].onAction = true function DoGathering(player, animation, gather, attached_item) if PlayerData[player].onAction and not PlayerData[player].isActioned then CallRemoteEvent(player, "LockControlMove", true) PlayerData[player].isActioned = true SetPlayerAnimation(player, animation) SetAttachedItem(player, "hand_r", attached_item) Delay(4000, function() SetPlayerAnimation(player, animation) end) Delay(8000, function() PlayerData[player].isActioned = false AddInventory(player, gatherTable[gather].gather_item, 1) CallRemoteEvent(player, "MakeNotification", _("gather_success", _(gatherTable[gather].gather_item)), "linear-gradient(to right, #00b09b, #96c93d)") SetPlayerAnimation(player, "STOP") CallRemoteEvent(player, "LockControlMove", false) SetAttachedItem(player, "hand_r", 0) return DoGathering(player, animation, gather, attached_item) end) end end DoGathering(player, animation, gather, attached_item) end) AddRemoteEvent("StartProcessing", function(player, processzone) gather = GetGatherByProcesszone(processzone) unprocessed_item = gatherTable[gather].gather_item if PlayerData[player].onAction then PlayerData[player].onAction = false return end if GetPlayerVehicle(player) ~= 0 then return end PlayerData[player].onAction = true function DoProcessing(player, gather, unprocessed_item) if PlayerData[player].onAction and not PlayerData[player].isActioned then if PlayerData[player].inventory[unprocessed_item] == nil then PlayerData[player].onAction = false return CallRemoteEvent(player, "MakeNotification", _("not_enough_item"), "linear-gradient(to right, #ff5f6d, #ffc371)") end if tonumber(PlayerData[player].inventory[unprocessed_item]) < 1 then PlayerData[player].onAction = false return CallRemoteEvent(player, "MakeNotification", _("not_enough_item"), "linear-gradient(to right, #ff5f6d, #ffc371)") else CallRemoteEvent(player, "LockControlMove", true) RemoveInventory(player, unprocessed_item, 1) SetPlayerAnimation(player, "COMBINE") PlayerData[player].isActioned = true Delay(4000, function() SetPlayerAnimation(player, "COMBINE") end) Delay(8000, function() PlayerData[player].isActioned = false AddInventory(player, gatherTable[gather].process_item, 1) CallRemoteEvent(player, "MakeNotification", _("process_success", _(gatherTable[gather].process_item)), "linear-gradient(to right, #00b09b, #96c93d)") CallRemoteEvent(player, "LockControlMove", false) SetPlayerAnimation(player, "STOP") return DoProcessing(player, gather, unprocessed_item) end) end end end DoProcessing(player, gather, unprocessed_item) end) function GetGatherByGatherzone(gatherzone) for k,v in pairs(gatherTable) do if v.gatherObject == gatherzone then return k end end end function GetGatherByProcesszone(processzone) for k,v in pairs(gatherTable) do if v.processObject == processzone then return k end end end
-- TargetScore Graphs and Pacemaker contributed by iamjackg -- ActionOnMissedTarget contributed by DinsFire64 -- cleanup + fixes by djpohly and andrewipark -- --------------------------------------------------------------- -- first, the usual suspects local player = ... local pn = ToEnumShortString(player) -- Make sure that someone requested something from this file. -- (There's a lot. See the long note near the end, just above the pacemaker implementation.) local Pacemaker = SL[pn].ActiveModifiers.Pacemaker local WantsTargetGraph = SL[pn].ActiveModifiers.DataVisualizations == "Target Score Graph" local FailOnMissedTarget = PREFSMAN:GetPreference("EventMode") and SL[pn].ActiveModifiers.ActionOnMissedTarget == "Fail" local RestartOnMissedTarget = PREFSMAN:GetPreference("EventMode") and SL[pn].ActiveModifiers.ActionOnMissedTarget == "Restart" -- if none of them apply, bail now if not (Pacemaker or WantsTargetGraph or FailOnMissedTarget or RestartOnMissedTarget) then return end local pss = STATSMAN:GetCurStageStats():GetPlayerStageStats(player) -- --------------------------------------------------------------- -- some functions local to this file -- Finds the top score for the current song (or course) given a player. local function GetTopScore(pn, kind) if not pn or not kind then return end local SongOrCourse, StepsOrTrail, scorelist if GAMESTATE:IsCourseMode() then SongOrCourse = GAMESTATE:GetCurrentCourse() StepsOrTrail = GAMESTATE:GetCurrentTrail(pn) else SongOrCourse = GAMESTATE:GetCurrentSong() StepsOrTrail = GAMESTATE:GetCurrentSteps(pn) end if kind == "Machine" then scorelist = PROFILEMAN:GetMachineProfile():GetHighScoreList(SongOrCourse,StepsOrTrail) elseif kind == "Personal" then scorelist = PROFILEMAN:GetProfile(pn):GetHighScoreList(SongOrCourse,StepsOrTrail) end if scorelist then local topscore = scorelist:GetHighScores()[1] if topscore then return topscore:GetPercentDP() end end return 0 end -- Ported from PSS.cpp, can be removed if that gets exported to Lua local function GetCurMaxPercentDancePoints() local possible = pss:GetPossibleDancePoints() if possible == 0 then return 0 end local currentMax = pss:GetCurrentPossibleDancePoints() if currentMax == possible then return 1 end return currentMax / possible end -- --------------------------------------------------------------- -- flags for fail/restart behavior -- --------------------------------------------------------------- -- possible targets, as defined in ./Scripts/SL-PlayerOptions.lua within TargetScore.Values() -- { 'C-', 'C', 'C+', 'B-', 'B', 'B+', 'A-', 'A', 'A+', 'S-', 'S', 'S+', '*', '**', '***', '****', 'Machine best', 'Personal best' } -- get personal best score local pbGradeScore = GetTopScore(player, "Personal") local target_grade = { -- the index of the target score chosen in the PlayerOptions menu index = tonumber(SL[pn].ActiveModifiers.TargetScore), -- the score the player is trying to achieve score = 0 } if (target_grade.index == 17) then -- player set TargetGrade as Machine best target_grade.score = GetTopScore(player, "Machine") elseif (target_grade.index == 18) then -- player set TargetGrade as Personal best target_grade.score = pbGradeScore else -- player set TargetGrade as a particular letter grade -- anything from C- to ☆☆☆☆ target_grade.score = THEME:GetMetric("PlayerStageStats", "GradePercentTier" .. string.format("%02d", 17 - target_grade.index)) end -- if there is no personal/machine score, default to S as target if target_grade.score == 0 then target_grade.score = THEME:GetMetric("PlayerStageStats", "GradePercentTier06") end -- --------------------------------------------------------------- -- the main ActorFrame for this player local player_af = Def.ActorFrame{ OnCommand=function(self) self:xy(_screen.w-7, 58):zoom(0.25) end, -- any time we receive a judgment JudgmentMessageCommand=function(self,params) self:queuecommand("Update") end, } -- --------------------------------------------------------------- -- FIXME: The ActionOnMissedTarget logic depends on the Pacemaker logic. -- From a programmer's perspective, it makes sense to lump it all together in a single Actor, -- but to the player, the Pacemaker and ActionOnMissedTarget are distinct features -- that do not and should not depend on one another being active. -- -- I've modified this file enough that the features can be activated independently now, -- but there's still too much code involving disparate features in this one single file. -- -- I don't have the time to fully detangle all this so it's staying this way until -- someone rewrites this file OR human civilization ends in fire paving the way for GNU/Hurd. if not SL[pn].ActiveModifiers.DoNotJudgeMe and (SL[pn].ActiveModifiers.Pacemaker or FailOnMissedTarget or RestartOnMissedTarget) then -- pacemaker text player_af[#player_af+1] = Def.BitmapText{ -- FIXME this should use Wendy Monospace to prevent flicker whenever a 1 appears. -- For that, need to add +/- signs to the font file. Font="Common Bold", InitCommand=function(self) -- don't draw it if we don't need it self:visible(SL[pn].ActiveModifiers.Pacemaker) self:horizalign(right) end, UpdateCommand=function(self) local DPCurr = pss:GetActualDancePoints() local DPCurrMax = pss:GetCurrentPossibleDancePoints() local DPMax = pss:GetPossibleDancePoints() local percentDifference = (DPCurr - (target_grade.score * DPCurrMax)) / DPMax -- cap negative score displays percentDifference = math.max(percentDifference, -target_grade.score) local places = 2 -- if there's enough dance points so that our current precision is ambiguous, -- i.e. each dance point is less than half of a digit in the last place, -- and we don't already display 2.5 digits, -- i.e. 2 significant figures and (possibly) a leading 1, -- add a decimal point. -- .1995 prevents flickering between .01995, which is rounded and displayed as ".0200", and -- and an actual .0200, which is displayed as ".020" while (math.abs(percentDifference) < 0.1995 / math.pow(10, places)) and (DPMax >= 2 * math.pow(10, places + 2)) and (places < 4) do places = places + 1 end self:settext(string.format("%+."..places.."f", percentDifference * 100)) -- have we already missed so many dance points -- that the current goal is not possible anymore? if ((DPCurrMax - DPCurr) > (DPMax * (1 - target_grade.score))) then self:diffusealpha(0.65) -- check to see if the user wants to do something when they don't achieve their score. if FailOnMissedTarget then -- use SM_BeginFailed instead of SM_NotesEnded to *immediately* leave the screen instead of a nice fadeout. -- we want to get back into the next round because we want that score boi. SCREENMAN:GetTopScreen():PostScreenMessage("SM_BeginFailed", 0) elseif RestartOnMissedTarget then -- this setting assumes event mode, so no need for changing stage number. SCREENMAN:GetTopScreen():SetPrevScreenName("ScreenGameplay"):SetNextScreenName("ScreenGameplay"):begin_backing_out() end end end, } end return player_af
position = {x = 49.8963356018066, y = 0.94785475730896, z = 17.2338695526123} rotation = {x = 1.53067890096281E-06, y = 270.005737304688, z = -5.80849473408307E-06}
AddCSLuaFile("cl_init.lua") AddCSLuaFile("shared.lua") include("shared.lua") local RD = CAF.GetAddon("Resource Distribution") local EnergyToTemperature_Increment = 250 function ENT:Initialize() self:PhysicsInit(SOLID_VPHYSICS) self:SetMoveType(MOVETYPE_VPHYSICS) self:SetSolid(SOLID_VPHYSICS) self:SetNWInt("overlaymode", 1) self:SetNWInt("OOO", 0) self.Active = 0 self:SetTemperature(-1) self.caf = self.caf or {} self.caf.custom = self.caf.custom or {} end function ENT:GetThermalMass() if not self.ThermalMass then local phys = self:GetPhysicsObject() if phys:IsValid() then self.ThermalMass = phys:GetMass() end end return self.ThermalMass or 1 end --use this to set self.active --put a self:TurnOn and self:TurnOff() in your ent --give value as nil to toggle --override to do overdrive --AcceptInput (use action) calls this function with value = nil function ENT:SetActive(value, caller) if ((not (value == nil) and value ~= 0) or (value == nil)) and self.Active == 0 then if self.TurnOn then self:TurnOn(nil, caller) end elseif ((not (value == nil) and value == 0) or (value == nil)) and self.Active == 1 then if self.TurnOff then self:TurnOff(nil, caller) end end end function ENT:SetOOO(value) self:SetNWInt("OOO", value) end AccessorFunc(ENT, "LSMULTIPLIER", "Multiplier", FORCE_NUMBER) function ENT:GetMultiplier() return self.LSMULTIPLIER or 1 end function ENT:NormalizeTemperatureTo(otherTemperature, increment) local selfTemperature = self:GetTemperature() if selfTemperature < 0 or math.abs(selfTemperature - otherTemperature) < 0.1 then self:SetTemperature(otherTemperature) return end self:SetTemperature(selfTemperature + ((otherTemperature - selfTemperature) * increment / self:GetThermalMass())) end function ENT:WarmUpWithEnergy(energy, dontconsume) if not dontconsume then energy = self:ConsumeResource("energy", energy) end self:SetTemperature(self:GetTemperature() + (energy * EnergyToTemperature_Increment / self:GetThermalMass())) end function ENT:SetTemperature(temp) self:SetNWFloat("Temperature", temp) end function ENT:Think() self:NextThink(CurTime() + 1) local envTemperature = -1 if self.environment then if self.environment.GetTemperature then envTemperature = self.environment:GetTemperature(self) elseif self.environment.environment and self.environment.environment.GetTemperature then envTemperature = self.environment.environment:GetTemperature(self) end end if envTemperature < 0 then if self.UpdateWireOutput then self:UpdateWireOutput() end return true end self:NormalizeTemperatureTo(envTemperature, 0.1) if self.UpdateWireOutput then self:UpdateWireOutput() end return true end function ENT:Repair() self:SetHealth(self:GetMaxHealth()) end function ENT:AcceptInput(name, activator, caller) if name == "Use" and caller:IsPlayer() and caller:KeyDownLast(IN_USE) == false then if self.Inputs and caller.useaction and caller.useaction == true then local maxz = table.Count(self.Inputs) local last = false local num = 1 for k, v in pairs(self.Inputs) do if num >= maxz then last = true end net.Start("RD_AddInputToMenu") net.WriteBool(last) net.WriteString(v.Name) net.WriteEntity(self) net.Send(caller) num = num + 1 end else self:SetActive(nil, caller) end end end util.AddNetworkString("RD_AddInputToMenu") --should make the damage go to the shield if the shield is installed(CDS) function ENT:OnTakeDamage(DmgInfo) if self.Shield then self.Shield:ShieldDamage(DmgInfo:GetDamage()) CDS_ShieldImpact(self:GetPos()) return end if CAF and CAF.GetAddon("Life Support") then CAF.GetAddon("Life Support").DamageLS(self, DmgInfo:GetDamage()) end end function ENT:OnRemove() RD.Unlink(self) RD.RemoveRDEntity(self) if WireLib then WireLib.Remove(self) end if self.InputsBeingTriggered then for k, v in pairs(self.InputsBeingTriggered) do hook.Remove("Think", "ButtonHoldThinkNumber" .. v.hooknum) end end end --NEW Functions function ENT:RegisterNonStorageDevice() return RD.RegisterNonStorageDevice(self) end function ENT:AddResource(resource, maxamount, defaultvalue) return RD.AddResource(self, resource, maxamount, defaultvalue) end function ENT:ConsumeResource(resource, amount) return RD.ConsumeResource(self, resource, amount) end function ENT:SupplyResource(resource, amount, temperature) return RD.SupplyResource(self, resource, amount, temperature) end function ENT:Link(netid) return RD.Link(self, netid) end function ENT:Unlink() return RD.Unlink(self) end function ENT:GetResourceAmount(resource) return RD.GetResourceAmount(self, resource) end function ENT:GetResourceData(resource) return RD.GetResourceData(self, resource) end function ENT:GetUnitCapacity(resource) return RD.GetUnitCapacity(self, resource) end function ENT:GetNetworkCapacity(resource) return RD.GetNetworkCapacity(self, resource) end function ENT:GetEntityTable() return RD.GetEntityTable(self) end --END NEW Functions function ENT:OnRestore() if WireLib then WireLib.Restored(self) end end function ENT:PreEntityCopy() RD.BuildDupeInfo(self) if WireLib then local DupeInfo = WireLib.BuildDupeInfo(self) if DupeInfo then duplicator.StoreEntityModifier(self, "WireDupeInfo", DupeInfo) end end end function ENT:PostEntityPaste(Player, Ent, CreatedEntities) RD.ApplyDupeInfo(Ent, CreatedEntities) if WireLib and Ent.EntityMods and Ent.EntityMods.WireDupeInfo then WireLib.ApplyDupeInfo(Player, Ent, Ent.EntityMods.WireDupeInfo, function(id) return CreatedEntities[id] end) end end function ENT:DoUpdateWireOutput(outputName, resourceName) local amount, capacity = self:GetResourceData(resourceName) Wire_TriggerOutput(self, outputName, amount) Wire_TriggerOutput(self, "Max " .. outputName, capacity) end
local _, private = ... -- Lua Globals -- -- luacheck: globals tinsert ipairs next -- RealUI -- local RealUI = private.RealUI local MODNAME = "InterfaceTweaks" local InterfaceTweaks = RealUI:NewModule(MODNAME, "AceEvent-3.0") local modules, moduleEvents = {}, {} local moduleAddons = { nibRealUI = { function() for tag, info in next, modules do if info.setEnabled then info.setEnabled(InterfaceTweaks.db.global[tag]) end end end } } local function AddTweak(tag, info) modules[tag] = info if info.addon then if not moduleAddons[info.addon] then moduleAddons[info.addon] = {} end tinsert(moduleAddons[info.addon], info.onLoad) end if info.event then if not moduleEvents[info.event] then moduleEvents[info.event] = {} end tinsert(moduleEvents[info.event], info.func) InterfaceTweaks:RegisterEvent(info.event, "OnEvent") end end function InterfaceTweaks:AddTweak(tag, info, enabled) if self.db then self.db.global[tag] = enabled else info.isEnabled = enabled end AddTweak(tag, info) end function InterfaceTweaks:GetTweaks() return RealUI.ShallowCopy(modules) end function InterfaceTweaks:OnEvent(event, ...) if event == "ADDON_LOADED" then local addon = ... if moduleAddons[addon] then for _, func in ipairs(moduleAddons[addon]) do func() end end else for _, func in ipairs(moduleEvents[event]) do func(...) end end end ----====####$$$$%%%%%$$$$####====---- -- Achievement Screenshots -- ----====####$$$$%%%%%$$$$####====---- AddTweak("achShots", { name = "Tweaks_Achievements", event = "ACHIEVEMENT_EARNED", func = function(achievementID, alreadyEarned) if not InterfaceTweaks.db.global.achShots then return end _G.C_Timer.After(1, function() _G.Screenshot() end) end }) ----====####$$$$%%%%%$$$$####====---- -- Auto Holiday Boss -- ----====####$$$$%%%%%$$$$####====---- do AddTweak("autoHoliday", { name = "Tweaks_AutoHoliday", }) local doneHoliday _G.LFDParentFrame:HookScript("OnShow", function() if not InterfaceTweaks.db.global.autoHoliday then return end if not doneHoliday then for index = 1, _G.GetNumRandomDungeons() do local dungeonID = _G.GetLFGRandomDungeonInfo(index) local isHoliday = _G.select(15, _G.GetLFGDungeonInfo(dungeonID)) if isHoliday then if _G.GetLFGDungeonRewards(dungeonID) then doneHoliday = true else _G.LFDQueueFrame_SetType(dungeonID) end end end end end) end ----====####$$$$%%%%%$$$$####====---- -- Mouse Trail -- ----====####$$$$%%%%%$$$$####====---- do local pollingRate, numLines = 0.05, 15 local lines = {} for i = 1, numLines do local line = _G.UIParent:CreateLine() line:SetThickness(_G.Lerp(5, 1, (i - 1)/numLines)) line:SetColorTexture(1, 1, 1) local startA, endA = _G.Lerp(1, 0, (i - 1)/numLines), _G.Lerp(1, 0, i/numLines) line:SetGradientAlpha("HORIZONTAL", 1, 1, 1, startA, 1, 1, 1, endA) lines[i] = {line = line, x = 0, y = 0} end local function UpdateTrail() local scale = _G.UIParent:GetEffectiveScale() local startX, startY = _G.GetCursorPosition() for i = 1, numLines do local info = lines[i] local endX, endY = info.x, info.y info.line:SetStartPoint("BOTTOMLEFT", _G.UIParent, startX / scale, startY / scale) info.line:SetEndPoint("BOTTOMLEFT", _G.UIParent, endX / scale, endY / scale) info.x, info.y = startX, startY startX, startY = endX, endY end end local ticker AddTweak("mouseTrail", { name = "Tweaks_MouseTrail", setEnabled = function(enabled) if enabled then ticker = _G.C_Timer.NewTicker(pollingRate, UpdateTrail) elseif ticker then ticker:Cancel() end end, }) end InterfaceTweaks:RegisterEvent("ADDON_LOADED", "OnEvent") function InterfaceTweaks:OnInitialize() self.db = RealUI.db:RegisterNamespace(MODNAME) self.db:RegisterDefaults({ global = { ["**"] = false }, }) for tag, info in next, modules do if info.isEnabled ~= nil then self.db.global[tag] = info.isEnabled info.isEnabled = nil end end end
-- -*- mode: lua; tab-width: 2; indent-tabs-mode: 1; st-rulers: [70] -*- -- vim: ts=4 sw=4 ft=lua noet ---------------------------------------------------------------------- -- @author Daniel Barney <daniel@pagodabox.com> -- @copyright 2015, Pagoda Box, Inc. -- @doc -- -- @end -- Created : 15 May 2015 by Daniel Barney <daniel@pagodabox.com> ---------------------------------------------------------------------- -- round_robin evenly divides the data over all nodes in the cluster. -- when one node is down, the data is divided over the remaining nodes return function(data,order,state,id) -- if this node is not alive, then we don't need to do any -- calcualtions if not state[id] then return {} end local add = {} local count = #order local failover_idx = 0 local alive_count = count local node_idx = count + 1 -- really gets set in the for loop local node_failover_idx = 0 local is_alive = {} -- count how many servers are alive, count how many servers have -- failed before we find the id so that we can shift the id down -- when we are doing failover for other nodes local failed_count = 0 for idx,name in pairs(order) do if name == id then node_idx = idx end local alive = state[name] is_alive[idx] = alive if not alive then if idx < node_idx then failed_count = failed_count + 1 end alive_count = alive_count - 1 end end node_failover_idx = node_idx - failed_count for i=1,#data do -- lua arrays are not 0 indexed, but mod is, so we account for it -- here local real_idx = ((i - 1) % count) + 1 if real_idx == node_idx then -- the data point is assigned to this node add[#add + 1] = data[i] elseif not is_alive[real_idx] then -- if the other node is down, and we are responsible for it then -- add it in if ((failover_idx - 1) % alive_count) + 1 == node_failover_idx then add[#add + 1] = data[i] end failover_idx = failover_idx + 1 end end return add end
-- coding: utf-8 --[[ -- PLEASE DO "NOT" EDIT THIS FILE! -- This file was automatically created. -- -- If you won't to apply correction go to: -- http://rom.curseforge.com/addons/dailynotes/localization/ --]] return { ["AAHFILTER"] = "Objetos diarios. Con/<min_xp>/<max_level> (opcional)", ["CFG_CHARLVL"] = "Nivel del personaje en lugar del nivel de la misión", ["CFG_TITLE"] = "DailyNotes - Opciones", ["CFG_TT_DIALOG"] = "Información en ventana emergente", ["CFG_TT_ITEMS"] = "Información sobre los objetos", ["CFG_TT_MOBS"] = "Información sobre las bestias", ["CFG_UNDONEQUEST"] = "Muestra misiones diarias no realizadas", ["CFG_ZBAGHOOK"] = "Resaltar objetos", ["CONFIG_CLEAR"] = [=[Eliminar la configuración de DailyNotes. ¿Estás seguro?]=], ["COUNT"] = "%i de %i para %s", ["COUNT_FIN"] = "Estado de la misión: Finalizadas", ["COUNT_START"] = "Estado de la misión: Iniciadas", ["DAILIES_RESET"] = "Misión diaria disponible de nuevo", ["DAILY"] = "Misiones diarias", ["DN_CFG_COUNTER"] = "Mostrar contador de objetos", ["DN_CFG_DQ_ONLY"] = "sólo para objetos de misión diaria", ["DN_CFG_RESET"] = "Reinicializar", ["DN_CFG_TAKER"] = "Auto-Aceptar sólo con objetos suficientes", ["DN_CFG_VERBOSE"] = "Información extendida", ["DN_CFG_VERBOSE_QUEST"] = "Incluir texto de la misión", ["DN_F_C_ZONE"] = "Zona", ["DN_F_COUNT"] = "Contador", ["DN_F_DAILIES"] = "Diarias:", ["DN_F_FINISHED"] = "Finalizadas:", ["DN_F_ITEM"] = "Objeto", ["DN_F_LEVEL"] = "Nivel", ["DN_F_NAME"] = "Nombre", ["DN_F_Q_ALL"] = "Todas <tooltip>Seleccionar todas las misiones", ["DN_F_Q_GATHER"] = [=[Objetos <tooltip>Marcar misiones de recolección (misiones donde sólo se pueden recoger objetos si la misión está activa)]=], ["DN_F_Q_KILL"] = "Asesinato <tooltip>Marcar misiones en las que el objetivo es acabar con algo o alguien", ["DN_F_Q_NONE"] = "Ninguna <tooltip>Eliminar todas las selecciones", ["DN_F_Q_OPTIONS"] = "Opciones <tooltip>Mostrar opciones", ["DN_F_Q_TAKE"] = "Misión automática", ["DN_F_REW1"] = "Pexp", ["DN_F_REW2"] = "Energía", ["DN_F_TARGET"] = "Objetivo", ["DN_F_ZONE"] = "Zona", ["DROPSITEM"] = "Objeto de misión diaria: |cfff0d030%s", ["ENERGY"] = "Energía: %i", ["EPIC"] = "Misiones épicas", ["ERR_DAILIES"] = "Las 10 misiones diarias ya están realizadas.", ["ERR_QUESTS"] = "Libro de misiones lleno.", ["F_MAINCHAR"] = "Sólo clase principal", ["F_SECCHAR"] = "Sólo clase secundaria", ["FILTER_CLEAR"] = "Reiniciar filtro", ["FILTER_ENERGY"] = "Misiones de justicia", ["FILTER_XP"] = "EXP en misiones", ["FIN"] = "|cffA0A0FF Suficiente para %i misión(es)", ["FIND_END"] = "PNJ que da la recompensa: |cffe0e000", ["FIND_MOB"] = "Localiza |cffe01010", ["FIND_NPC"] = "PNJ: |cffe0e000", ["FIND_START"] = "PNJ que ofrece la misión: |cffe0e000", ["INVOLVED"] = "Misión diaria: |cfffccf00%s", ["KILLCOUNT"] = "|cffFCCF00%i para %s", ["NEED"] = "|cffff8080 Necesitas %i más", ["NEEDSOTHER"] = "|cffff8080 Necesitas otro objeto", ["PREQUEST"] = "Requiere misión: ", ["PUBLIC"] = "Misiones públicas", ["QEND"] = "Final: %s", ["QPOS"] = "|cff909090(%s: %g/%g)", ["QSTART"] = "Inicio: %s", ["QSTARTEND"] = "Inicio/Final: %s", ["REPEATABLE"] = "Misiones repetibles", ["T_AUTOQUEST"] = [=[Cada misión seleccionada será aceptada y finalizada de forma automática si se interacciona con un PNJ o un tablón de anuncios. Las misiones de recolección son unicamente aceptadas si las condiciones de la misión se cumplen.]=], ["T_CHARLVL"] = "Cambiar la visualización entre el nivel de la misión y el nivel requerido del jugador.", ["T_COUNT"] = "Filtro por contador.", ["T_COUNTER"] = "Mostrar contador de objetos del inventario en el mensaje de recogida.", ["T_DQ_ONLY"] = "Mostrar contador sólo si el objeto es un objeto de misión diaria.", ["T_LVL1"] = "Mostrar misiones para el nivel de la clase principal.", ["T_LVL2"] = "Mostrar misiones para el nivel de la clase secundaria.", ["T_RESET"] = [=[Reiniciar todas las opciones de DailyNotes (Opciones y la configuración de auto-misión).]=], ["T_TAKER"] = [=[Las misiones sólo serán aceptadas automaticamente cuando tengas los objetos suficientes en el inventario. (Por defecto).]=], ["T_TT_DIALOG"] = "Mostrar información completa de las misiones diarias en DailyNotes.", ["T_TT_ITEMS"] = "Mostrar información de los objetos en una ventana emergente.", ["T_TT_MOBS"] = "Mostrar en la descripción de la bestia si está involucrada en una misión diaria.", ["T_UNDONEQUEST"] = "Muestra misiones diarias no realizadas todavía como misiones normales en los diálogos con PNJ", ["T_VERBOSE"] = [=[Mostrar posiciones de los PNJ (Información de los objetos como ventana de diálogo).]=], ["T_VERBOSE_QUEST"] = "Mostrar el texto de la misión en la ventana emergente.", ["T_ZBAGHOOK"] = "Resaltar objetos de misión diaria en la bolsa (requiere Zbag)", ["T_ZONE"] = "Mostrar misiones sólo en esta zona.", ["UNDONE"] = "Sólo no realizadas", ["XP"] = "XP: %i Oro/Doblones: %i/%i", ["ZONE_ALL"] = "Todas las zonas", ["ZONE_CUR"] = "Zona actual", ["ZONE_YLAB"] = "Laboratorio de Ystra" }
local http = require "socket.http" local json = require "lib/dkjson" -- Temp bot loading. Will need to clean this up. local nbot = require "bots/example" -- Initiate some global variables that bots will -- need access to. game = {} map = {taverns = {}, mines = {}, heros = true, hero = true} -- Set up for validity checks local valid_modes = { arena = "http://vindinium.org/api/arena", training = "http://vindinium.org/api/training" } local valid_moves = {"Stay", "North", "South", "East", "West"} local valid_tiles = { ground = {s = " ", v = 0}, hero = {s = "@(%d)", v = 0}, mine = {s = "$([%d%-])", v = 5}, tavern = {s = "%[%]", v = 10}, wall = {s = "##", v = 11} } -- Make the the body for a POST HTTP request -- @param body_pairs: a table of key-value pairs -- @return: a string local function mk_request_body(body_pairs) local buffer = {} for k, v in pairs(body_pairs) do table.insert(buffer, k .. "=" .. v) end return table.concat(buffer, "&") end -- Send a POST HTTP request, update game with respose values -- @param game: a game object including a url or mode -- @param body_pairs: a table of key-value pairs -- @return: the response as a json string local function request(body_pairs) local response_body = {} local request_body = mk_request_body(body_pairs) --Send the request local _, code, headers = http.request{ url = game.playUrl or valid_modes[game.mode], method = "POST", sink = ltn12.sink.table(response_body), source = ltn12.source.string(request_body), headers = { ["Content-Type"] = "application/x-www-form-urlencoded", ["Content-Length"] = string.len(request_body) } } -- Validate response assert(type(response_body) == 'table', 'Invalid response from server') local response = table.concat(response_body) assert(code == 200, "Request failed: " .. code .. " - ".. response) return response end -- Vindinium uses a 0 base and X as the vertical direction, -- while lua uses 1 as a base and X is traditionally horizontal. -- This corrects that. local function correct_pos(pos) pos.x, pos.y = pos.y + 1, pos.x + 1 end -- Turn the position of a tile in the string -- into x and y values local function correct_xy(a,b) x = (a - 1) / 2 % map.size + 1 y = ((b / 2) - x) / map.size + 1 return x, y end -- Replace the heroes last positions with ground on the map. local function remove_heroes() for i = 1, 4 do map[map.heroes[i].pos.y][map.heroes[i].pos.x] = 0 end end local function update_map(board, tile, store) local i = 1 while true do local a, b, c = string.find(board, tile.s, i) if a then i = b + 1 else break end local x, y = correct_xy(a, b) if not map[y] then map[y] = {} end if c then if c == "-" then c = 0 else c = tonumber(c) end map[y][x] = tile.v + c else map[y][x] = tile.v end if store then table.insert(store, { pos = {x = x, y = y}, id = c }) end end end -- Map parsers local function parse_first_response(response) local parsed = json.decode(response) game.finished = parsed.game.finished game.id = parsed.game.id game.turn = parsed.game.turn game.maxTurns = parsed.game.maxTurns game.token = parsed.token game.viewUrl = parsed.viewUrl game.playUrl = parsed.playUrl map.size = parsed.game.board.size map.heroes = parsed.game.heroes correct_pos(map.heroes[1].pos) correct_pos(map.heroes[2].pos) correct_pos(map.heroes[3].pos) correct_pos(map.heroes[4].pos) map.hero = parsed.hero correct_pos(map.hero.pos) local board = parsed.game.board.tiles update_map(board, valid_tiles.ground) update_map(board, valid_tiles.wall) update_map(board, valid_tiles.hero) update_map(board, valid_tiles.mine, map.mines) update_map(board, valid_tiles.tavern, map.taverns) end local function parse_response(response) local parsed = json.decode(response) game.finished = parsed.game.finished game.turn = parsed.game.turn remove_heroes() map.heroes = parsed.game.heroes correct_pos(map.heroes[1].pos) correct_pos(map.heroes[2].pos) correct_pos(map.heroes[3].pos) correct_pos(map.heroes[4].pos) map.hero = parsed.hero correct_pos(map.hero.pos) map.mines = {} local board = parsed.game.board.tiles update_map(board, valid_tiles.hero) update_map(board, valid_tiles.mine, map.mines) end -- Function that returns a random valid move. -- Good for testing and example bots. function game.random_move() return valid_moves[math.random(1,5)] end -- -- Set filtering to nearest neighbor, for sprite art love.graphics.setDefaultFilter("nearest", "nearest") -- Load all needed images local gfx = { tile_size = 24, tile_offset = 8, [0] = love.graphics.newImage("gfx/0_ground.png"), [1] = { north = love.graphics.newImage("gfx/1_heroN.png"), east = love.graphics.newImage("gfx/1_heroE.png"), south = love.graphics.newImage("gfx/1_heroS.png"), west = love.graphics.newImage("gfx/1_heroW.png") }, [2] = { north = love.graphics.newImage("gfx/2_heroN.png"), east = love.graphics.newImage("gfx/2_heroE.png"), south = love.graphics.newImage("gfx/2_heroS.png"), west = love.graphics.newImage("gfx/2_heroW.png") }, [3] = { north = love.graphics.newImage("gfx/3_heroN.png"), east = love.graphics.newImage("gfx/3_heroE.png"), south = love.graphics.newImage("gfx/3_heroS.png"), west = love.graphics.newImage("gfx/3_heroW.png") }, [4] = { north = love.graphics.newImage("gfx/4_heroN.png"), east = love.graphics.newImage("gfx/4_heroE.png"), south = love.graphics.newImage("gfx/4_heroS.png"), west = love.graphics.newImage("gfx/4_heroW.png") }, [5] = love.graphics.newImage("gfx/5_mine.png"), [6] = love.graphics.newImage("gfx/6_mine.png"), [7] = love.graphics.newImage("gfx/7_mine.png"), [8] = love.graphics.newImage("gfx/8_mine.png"), [9] = love.graphics.newImage("gfx/9_mine.png"), [10] = love.graphics.newImage("gfx/10_tavern.png") } -- Draw the map to a canvas, as it never changes. local function draw_map() local map_canvas = love.graphics.newCanvas(map.size*gfx.tile_size, map.size*gfx.tile_size), love.graphics.setCanvas(map_canvas) for y = 1, map.size do if map[y] then for x = 1, map.size do if map[y][x] ~= 11 then love.graphics.draw(gfx[0], x*gfx.tile_size, y*(gfx.tile_size-gfx.tile_offset)) end end end end love.graphics.setCanvas() gfx.map = love.graphics.newImage(map_canvas:getImageData()) end --- function love.load() assert(type(nbot) == "table", "Settings table is invalid.") game.key = assert(nbot.key, "A key must be provided") game.mode = nbot.mode or "training" game.loop = nbot.loop or random_move game.pre_loop = nbot.pre_loop assert(valid_modes[game.mode], "Invalid game mode: " .. game.mode) -- Initial connection request local response = request{key = game.key} parse_first_response(response) -- Run pre_loop function if availiable if game.pre_loop then game.pre_loop() end end function love.update() if not game.finished then local move = game.loop() response = request{key = game.key, dir = move} parse_response(response) else love.event.quit() end end function love.draw() -- init the map if it doesn't exist if not gfx.map then draw_map() end -- draw the map love.graphics.draw(gfx.map, 1, 1) -- draw a test sprite every other turn, because I -- can't figure out why the map disappears and this doesn't. if game.turn % 8 == 0 then love.graphics.draw(gfx[10], 24, 25) end end
local gHunger = 0.0 local gThirst = 0.0 RegisterNetEvent('BasicNeeds.utils') AddEventHandler('BasicNeeds.utils', function(calledFunction, ...) local p = promise.new() p:resolve({...}) local result = Citizen.Await(p) calledFunction(table.unpack(result)) end) RegisterCommand("callit", function(source, args) VaryHunger(source, 1.5) end) function VaryHunger(source, variation) local _source = source -- local User = API.getUserFromSource(_source) -- if User == nil then -- return -- end -- local Character = User:getCharacter() -- if Character == nil then -- return -- end local hunger = 25 hunger = tonumber(hunger) if hunger then local was_starving = hunger >= 100 hunger = hunger + variation local is_starving = hunger >= 100 local overflow = hunger - 100 if overflow > 0 then -- TriggerClientEvent("BasicNeeds.utils", _source, VaryPlayerHealth, -overflow * 8) end TriggerClientEvent("BasicNeeds.utils", _source, VaryPlayerHealth, -overflow * 8,0) if hunger < 0 then hunger = 0 elseif hunger > 100 then hunger = 100 end gHunger = tonumber(math.floor(hunger * 100) / 100) -- Character:setData(Character:getId(), 'metaData', 'hunger', gHunger) updateSocialNeeds(_source, _source) end end function VaryThirst(variation) local _source = source local User = getUserFromSource(_source) if User == nil then return end local Character = User:getCharacter() if Character == nil then return end local thirst = json.decode(Character:getData(Character:getId(), 'metaData', 'thirst')) thirst = tonumber(thirst) if thirst then local was_starving = thirst >= 100 thirst = thirst + variation local is_starving = thirst >= 100 local overflow = thirst - 100 if overflow > 0 then cAPI.VaryPlayerHealth(_source, -overflow * 8) end if thirst < 0 then thirst = 0 elseif thirst > 100 then thirst = 100 end gThirst = tonumber(math.floor(thirst * 100) / 100) Character:setData(Character:getId(), 'metaData', 'thirst', gThirst) updateSocialNeeds(_source, _source) end end function updateSocialNeeds(src) local _source = src -- TriggerClientEvent('BasicNeeds.update', _source, gHunger, gThirst) end
position = {x = -11.2038688659668, y = 1.43724429607391, z = 17.7157440185547} rotation = {x = -8.22400543256663E-05, y = 90.027229309082, z = -0.000312642223434523}
air = build.blockState("minecraft:air"); frameBlock = build.blockState("minecraft:light_gray_concrete"); platBlock = build.blockState("minecraft:polished_andesite"); ventBlock = build.blockState("minecraft:gray_concrete"); wallBlock = build.blockState("minecraft:quartz_pillar"); floorBlock = build.blockState("minecraft:polished_granite"); dirt = build.blockState("minecraft:dirt"); stone = build.blockState("minecraft:stone"); sandstone = build.blockState("minecraft:sandstone"); hazardBlock = build.blockState("minecraft:yellow_concrete"); emeraldBlock = build.blockState("minecraft:emerald_block");
-- There shall be light ! -- -- WTFPL by Gundul lightup = {} lightup.switch = {} local timer = 0 -- do not touch local check = 0.1 -- intervall in which is checked for light, the smaller the more realistic but the harder for cpu local turnoff = 0.2 -- after how many seconds the light is turned off again local distance = 20 -- max distance of the torchlight local brightness = 14 -- max brightness minetest.register_privilege("lightup", {description ="automatic light in air and water"}) -- register water and airnodes, together with their new brothers. lightup.switch[1] = {name="default:water_source", change="lightup:brightwater"} lightup.switch[2] = {name="default:water_flowing", change="lightup:brightwater_flowing"} lightup.switch[3] = {name="default:river_water_source", change="lightup:brightriverwater"} lightup.switch[4] = {name="default:river_water_flowing", change="lightup:brightriverwater_flowing"} lightup.switch[5] = {name="water_life:muddy_river_water_source", change="lightup:brightmuddywater"} lightup.switch[6] = {name="water_life:muddy_river_water_flowing", change="lightup:brightmuddywater_flowing"} lightup.switch[7] = {name="air", change="lightup:brightair"} -- this function is taken from Termos' mobkit api. local function pos_shift(pos,vec) -- vec components can be omitted e.g. vec={y=1} vec.x=vec.x or 0 vec.y=vec.y or 0 vec.z=vec.z or 0 return {x=pos.x+vec.x, y=pos.y+vec.y, z=pos.z+vec.z} end -- the name says it all local function clone_node(node_name) if not (node_name and type(node_name) == 'string') then return end local node = minetest.registered_nodes[node_name] return table.copy(node) end -- throwing a raycast local function find_collision(pos1,dir) pos1 = pos_shift(pos1,vector.multiply(dir,1)) local pos2 = pos_shift(pos1,vector.multiply(dir,distance)) local ray = minetest.raycast(pos1, pos2, true, false) for pointed_thing in ray do if pointed_thing.type == "node" then local dist = math.floor(vector.distance(pos1,pointed_thing.under)) pos2 = pos_shift(pos1,vector.multiply(dir,dist-1)) return pos2 end if pointed_thing.type == "object" then local obj = pointed_thing.ref local objpos = obj:get_pos() return objpos end end return nil end --register all that new bright nodes for i = 1,#lightup.switch,1 do if minetest.registered_nodes[lightup.switch[i].name] and not minetest.registered_nodes[lightup.switch[i].change] then local water = clone_node(lightup.switch[i].name) water.liquid_alternative_flowing = lightup.switch[i].change water.liquid_alternative_source = lightup.switch[i].change water.groups.not_in_creative_inventory = 1 water.light_source = brightness water.liquid_renewable = false water.on_timer = function(pos, elapsed) minetest.set_node(pos,{name=lightup.switch[i].name}) -- when node timer is elapsed turn back into src end minetest.register_node(lightup.switch[i].change, water) end end -- globalstep to check for people with lightup priv -- change that check for a certain item in player inventory -- or whatever you want and need minetest.register_globalstep(function(dtime) timer = timer + dtime if timer > check then for _,plyr in ipairs(minetest.get_connected_players()) do local name = plyr:get_player_name() local privs = minetest.get_player_privs(name) if privs.lightup or privs.server then local yaw = plyr:get_look_horizontal() local pos = plyr:get_pos() local dir = plyr:get_look_dir() pos.y = pos.y + 1.4 local target = find_collision(pos,dir) if target then local node = minetest.get_node_or_nil(target) --minetest.chat_send_all(dump(node.name)) for i = 1,#lightup.switch,1 do -- found a node ? change it into a bright brother if node and node.name == lightup.switch[i].name then minetest.swap_node(target, {name=lightup.switch[i].change}) minetest.after(1,function(target) local timer = minetest.get_node_timer(target) timer:start(turnoff) end, target) end -- still pointing to a bright node ? set nodetimer to max again. if node and node.name == lightup.switch[i].change then local timer = minetest.get_node_timer(target) if timer:is_started() then timer:set(turnoff,0) end end end end end end timer = 0 end end)
-- keybindings ---@diagnostic disable-next-line: lowercase-global screen = screen or {} local awful = require('awful') local beautiful = require('beautiful') local gtable = require('gears.table') local config = require('config') local modkey = config.modkey local clientkeys = gtable.join( -- awful.key({ modkey }, 'q', function(c) c:kill() end), awful.key({ modkey }, '[', function(c) c:kill() end), awful.key({ modkey, 'Shift' }, '[', function(c) c:move_to_screen(c.screen.index - 1) end), awful.key({ modkey, 'Shift' }, ']', function(c) c:move_to_screen() end), awful.key({ modkey, 'Shift' }, 'space', awful.client.floating.toggle) ) local clientbuttons = gtable.join( awful.button({ }, 1, function(c) c:emit_signal('request::activate', 'mouse_click', { raise = true }) end), awful.button({ modkey }, 1, function(c) c:emit_signal('request::activate', 'mouse_click', { raise = true }) c.floating = true awful.mouse.client.move(c) end), awful.button({ modkey }, 3, function(c) c:emit_signal('request::activate', 'mouse_click', { raise = true }) awful.layout.set(awful.layout.suit.floating) awful.mouse.client.resize(c) end) ) local rules = { { rule = {}, properties = { border_width = beautiful.border_width, border_color = beautiful.border_normal, focus = awful.client.focus.filter, raise = false, keys = clientkeys, buttons = clientbuttons, screen = awful.screen.preferred, placement = awful.placement.no_overlap + awful.placement.no_offscreen, maximized = false, }, callback = function(c) awful.client.setslave(c) end }, { rule_any = { class = { 'dialog', 'pop-up', 'task-dialog' }, }, properties = { floating = true, ontop = true, sticky = true, above = true }, }, { rule = { class = 'firefoxdeveloperedition' }, properties = { tag = ' ☰ ', screen = screen[1], }, }, { rule_any = { class = { 'sun-awt-X11-XDialogPeer', 'jetbrains-idea' }, }, properties = { tag = screen.count() > 1 and ' ☲ ' or ' ☱ ', screen = screen[1], }, }, { rule_any = { instance = { 'nnnterm', 'tmuxterm' }, }, properties = { tag = ' ☲ ', screen = screen[3] or screen[1], }, }, { rule = { class = 'Slack' }, properties = { tag = screen.count() > 1 and ' ☱ ' or ' ☴ ' , screen = screen[3] or screen[1], }, }, { rule = { class = 'Google-chrome' }, properties = { tag = screen.count() > 1 and ' ☰ ' or ' ☶ ', screen = screen[2] or screen[1], }, }, { rule = { class = 'Postman' }, properties = { tag = screen.count() > 1 and ' ☶ ' or ' ☰ ', screen = screen[3] or screen[1], }, }, { rule_any = { instance = { 'rtorrentterm', 'sptterm' }, }, properties = { tag = screen.count() > 1 and ' ☴ ' or ' ☵ ', screen = screen[3] or screen[1], }, }, { rule = { class = 'qBittorrent', instance = 'qbittorrent', }, properties = { tag = screen.count() > 1 and ' ☴ ' or ' ☴ ', screen = screen[3] or screen[1], }, }, } return rules
require("common/commonLogic"); require("hall/common/commonJumpCmds"); require("hall/gameData/share/shareDataInterface"); require("gameData/weixinShareUtil"); CommonJumpLogic = class(CommonLogic); CommonJumpLogic.s_commonJumpEvent = EventDispatcher.getInstance():getUserEvent(); CommonJumpLogic.getInstance = function() if not CommonJumpLogic.s_instance then CommonJumpLogic.s_instance = new(CommonJumpLogic); end return CommonJumpLogic.s_instance; end CommonJumpLogic.releaseInstance = function() delete(CommonJumpLogic.s_instance); CommonJumpLogic.s_instance = nil; end CommonJumpLogic.ctor = function(self) self.m_jumpData = {}; end --@brief 执行js调用 --@param data:必须包含cmd命令 --@return 此调用是否需要在大厅才能执行 CommonJumpLogic.executeJsCall = function(self, data) Log.v("CommonJumpLogic.executeJsCall", "data = ", data); if table.isEmpty(data) then return; end local cmd = number.valueOf(data.cmd); local config = CommonJumpCmds.s_jumpCmdConfig[cmd]; if table.isEmpty(config) then return; end local func = config.func; if func and type(func) == "function" then self:resetJumpData(); local funcTab = config.onPreExecuteFunc; if funcTab and type(funcTab) == "function" then funcTab(self, data); end local onlyExecuteInHall = func(self, data, unpack( table.verify(config.extParams) ) ); local hasExecuted = false; if onlyExecuteInHall then hasExecuted = EventDispatcher.getInstance():dispatch(CommonJumpLogic.s_commonJumpEvent); end if hasExecuted then return false; else return onlyExecuteInHall; end end end --设置跳转参数 --[[ self.m_jumpData { cmd = xxx; -- 对应 CommonJumpCmds stateId = xxx; --跳转状态id params = {}; --参数列表 } --]] --设置跳转参数 CommonJumpLogic.setJumpData = function(self, cmd, stateId, params) if not cmd and not stateId then return; end self.m_jumpData = { cmd = cmd; stateId = stateId; params = table.verify(params); } end --重置跳转参数 CommonJumpLogic.resetJumpData = function(self) self.m_jumpData = {}; end --判断是否已经含有跳转命令 CommonJumpLogic.hasJumpCommond = function(self) if table.isEmpty(self.m_jumpData) then return false; else return true; end end --获取跳转参数 CommonJumpLogic.getJumpParams = function(self) return self.m_jumpData.cmd, self.m_jumpData.stateId, table.verify(self.m_jumpData.params); end --跳转到其他状态 CommonJumpLogic.__onExecuteJumpState = function(self, data, state, style, isPopupState) if not kLoginDataInterface:getIsLoginSuccess() then Toast.getInstance():showText("请先登录游戏",50,30,kAlginLeft,"",26,250,210,70); return; end if state then StateMachine.getInstance():pushState(state, style, isPopupState) end end --返回大厅 CommonJumpLogic.__onBackToHall = function(self, data) return true; end --调用下载 CommonJumpLogic.__onToDownLoad = function(self, data) self.m_jumpData = { cmd = CommonJumpCmds.SEND_DOWNLOAD; } return true; end --跳转到游戏 CommonJumpLogic.__onJumpToGame = function(self, data) local gameId = number.valueOf(data.gameid); local levelId = number.valueOf(data.level); if gameId <= 0 then return; end --将参数补全 防止需要安装或更新 local gameConfig = kGameManager:getGameConfigById(gameId); gameConfig.status = HallUpdateConfig.getInstance():getGameStatus(gameId); gameConfig.levelId = levelId; self.m_jumpData = { cmd = CommonJumpCmds.GOTO_GAME; params = gameConfig; } return true; end --跳转到任务 CommonJumpLogic.__onJumpToTask = function(self, data) self.m_jumpData = { cmd = CommonJumpCmds.GOTO_TASK }; return true; end --更新银币 CommonJumpLogic.__onUpdateUserMoney = function(self, data) local money = tonumber(data.money); if money and money >= 0 then kUserInfoData:setMoney(money); end end --更新用户钻石 CommonJumpLogic.__onUpdateUserDiamond = function(self, data) local diamond = tonumber(data.diamond); if diamond and diamond >= 0 then kUserInfoData:setDiamond(diamond); end end --更新用户金条 CommonJumpLogic.__onUpdateUserCrystal = function(self, data) local crystal = tonumber(data.crystal); if crystal and crystal >= 0 then kUserInfoData:setCrystal(crystal); end end --跳转到私人房 CommonJumpLogic.__onJumpToPrivateRoom = function(self, data) self.m_jumpData = { cmd = CommonJumpCmds.GOTO_PRIVATE_ROOM; } require("hall/privateRoom/data/privateRoomDataInterface"); PrivateRoomDataInterface.getInstance():setJumpInfo(data); return true; end --跳转到广播界面 CommonJumpLogic.__onJumpToBroadcast = function(self) self.m_jumpData = { cmd = CommonJumpCmds.GOTO_BROADCAST }; return true; end --微信分享/微信邀请 CommonJumpLogic.__onWeiXinShare = function(self, data, isSendToFriendsCircle) local info = table.verify(data.info); local weiChatInfo = ShareDataInterface.getInstance():getWeiXinChatInfo(); local url = isSendToFriendsCircle and weiChatInfo.space_url or weiChatInfo.friend_url; url = info.share_url or url; local title = info.title or weiChatInfo.title; local desc = info.desc or weiChatInfo.desc; local share_icon = info.share_icon or weiChatInfo.share_icon; WeixinShareUtil.getInstance():weixinSendWebPage(url, title, desc, share_icon, isSendToFriendsCircle); end --跳转到比赛界面 CommonJumpLogic.__onJumpToMatchRoom = function(self, data) self.m_jumpData = { cmd = CommonJumpCmds.GOTO_MATCH_ROOM; } require("isolater/interface/matchIsolater"); MatchIsolater.getInstance():setMatchJumpInfo(data); return true; end --跳转到房间列表界面 CommonJumpLogic.__onJumpToRoomList = function(self, data) local gameid = number.valueOf(data.gameid); if gameid <= 0 then return; end --将参数补全 防止需要安装或更新 local gameConfig = kGameManager:getGameConfigById(gameid); gameConfig.status = HallUpdateConfig.getInstance():getGameStatus(gameid); self.m_jumpData = { cmd = CommonJumpCmds.GOTO_GAME_ROOM_LIST; params = gameConfig; } return true; end --跳转到团队赛 CommonJumpLogic.__onToGroupRoom = function(self) self.m_jumpData = { stateId = States.GroupGame; } return true; end --empty function CommonJumpLogic.__emptyFunc = function(self) end CommonJumpLogic.__onExecuteRechargeJumpTab = function(self, data) local tab = number.valueOf(data.tab); require("hall/recharge/data/rechargeDataInterface"); RechargeDataInterface.getInstance():setToRechargeModeByJumpTab(tab); end --跳转到注册界面 CommonJumpLogic.__onJumpToRegisterAccount = function(self) self.m_jumpData = { cmd = CommonJumpCmds.GOTO_REGISTER_ACCOUNT }; return true; end CommonJumpCmds.s_jumpCmdConfig = { [CommonJumpCmds.GET_USER_DATA] = { func = CommonJumpLogic.__emptyFunc }; [CommonJumpCmds.SEND_DOWNLOAD] = { func = CommonJumpLogic.__onToDownLoad }; [CommonJumpCmds.QUIT_GAME] = { func = CommonJumpLogic.__emptyFunc }; [CommonJumpCmds.GOTO_LOGIN] = { func = CommonJumpLogic.__onBackToHall }; [CommonJumpCmds.GOTO_USERINFO] = { func = CommonJumpLogic.__onExecuteJumpState, extParams = {States.UserInfo, nil, true} }; [CommonJumpCmds.GOTO_HALL] = { func = CommonJumpLogic.__onBackToHall }; [CommonJumpCmds.GOTO_GAME] = { func = CommonJumpLogic.__onJumpToGame }; [CommonJumpCmds.GOTO_SHOP] = { func = CommonJumpLogic.__onExecuteJumpState, extParams = {States.Recharge}, onPreExecuteFunc = CommonJumpLogic.__onExecuteRechargeJumpTab}; [CommonJumpCmds.GOTO_TASK] = { func = CommonJumpLogic.__onJumpToTask }; [CommonJumpCmds.GOTO_RANK] = { func = CommonJumpLogic.__onExecuteJumpState, extParams = {States.RankList} }; [CommonJumpCmds.GOTO_FRIENDS] = { func = CommonJumpLogic.__onExecuteJumpState, extParams = {States.Community} }; [CommonJumpCmds.UPDATE_MONEY] = { func = CommonJumpLogic.__onUpdateUserMoney }; [CommonJumpCmds.INPUT_CDKEY] = { func = CommonJumpLogic.__emptyFunc }; [CommonJumpCmds.GOTO_ACTIVITY_ONLY_LUA] = { func = CommonJumpLogic.__onExecuteJumpState, extParams = {States.Activity} }; [CommonJumpCmds.GOTO_ACTIVITY] = { func = CommonJumpLogic.__onExecuteJumpState, extParams = {States.Activity} }; [CommonJumpCmds.GOTO_DIAMOND_SHOP] = { func = CommonJumpLogic.__onExecuteJumpState, extParams = {States.DiamondShop} }; [CommonJumpCmds.GOTO_PRIVATE_ROOM] = { func = CommonJumpLogic.__onJumpToPrivateRoom }; [CommonJumpCmds.GOTO_BROADCAST] = { func = CommonJumpLogic.__onJumpToBroadcast }; [CommonJumpCmds.GOTO_SEND_MESSAGE] = { func = CommonJumpLogic.__onExecuteJumpState, extParams = {States.Message} }; [CommonJumpCmds.GOTO_WEIXIN_SHARE] = { func = CommonJumpLogic.__onWeiXinShare, extParams = {true} }; [CommonJumpCmds.GOTO_WEIXIN_INVITE] = { func = CommonJumpLogic.__onWeiXinShare, extParams = {false} }; [CommonJumpCmds.GOTO_MATCH_ROOM] = { func = CommonJumpLogic.__onJumpToMatchRoom }; [CommonJumpCmds.GOTO_GAME_ROOM_LIST] = { func = CommonJumpLogic.__onJumpToRoomList }; [CommonJumpCmds.GOTO_GROUP_ROOM] = { func = CommonJumpLogic.__onExecuteJumpState, extParams = {States.GroupGame} }; [CommonJumpCmds.UPDATE_DIAMOND] = { func = CommonJumpLogic.__onUpdateUserDiamond }; [CommonJumpCmds.START_RECHARGE] = { func = CommonJumpLogic.__emptyFunc }; [CommonJumpCmds.ANGECY_RECHARGE] = { func = CommonJumpLogic.__emptyFunc }; [CommonJumpCmds.ANGECY_H5_BACK] = { func = CommonJumpLogic.__emptyFunc }; [CommonJumpCmds.UPDATE_CRYSTAL] = { func = CommonJumpLogic.__onUpdateUserCrystal }; [CommonJumpCmds.GOTO_REGISTER_ACCOUNT] = { func = CommonJumpLogic.__onJumpToRegisterAccount }; }
local hap = require "hap" local Active = require "hap.char.Active" local CurTemp = require "hap.char.CurrentTemperature" local CurHeatCoolState = require "hap.char.CurrentHeaterCoolerState" local TgtHeatCoolState = require "hap.char.TargetHeaterCoolerState" local CoolThrholdTemp = require "hap.char.CoolingThresholdTemperature" local HeatThrholdTemp = require "hap.char.HeatingThresholdTemperature" local SwingMode = require "hap.char.SwingMode" local searchKey = require "util".searchKey local raiseEvent = hap.raiseEvent local M = {} --- Property value -> Characteristic value. local valMapping = { power = { on = Active.value.Active, off = Active.value.Inactive }, ver_swing = { on = SwingMode.value.Enabled, off = SwingMode.value.Disabled }, mode = { cool = TgtHeatCoolState.value.Cool, heat = TgtHeatCoolState.value.Heat, auto = TgtHeatCoolState.value.HeatOrCool, } } ---Create a acpartner. ---@param device MiioDevice Device object. ---@param info MiioDeviceInfo Device inforamtion. ---@param conf MiioAccessoryConf Device configuration. ---@return HAPAccessory accessory HomeKit Accessory. function M.gen(device, info, conf) local iids = conf.iids return { aid = conf.aid, category = "BridgedAccessory", name = conf.name or "Lumi Acpartner", mfg = "lumi", model = info.model, sn = conf.sn, fwVer = info.fw_ver, hwVer = info.hw_ver, services = { hap.AccessoryInformationService, { iid = iids.heaterCooler, type = "HeaterCooler", props = { primaryService = true, hidden = false }, chars = { Active.new(iids.active, function (request) local value = valMapping.power[device:getProp("power")] device.logger:info("Read Active: " .. searchKey(Active.value, value)) return value end, function (request, value) device.logger:info("Write Active: " .. searchKey(Active.value, value)) device:setProp("power", searchKey(valMapping.power, value)) raiseEvent(request.aid, request.sid, request.cid) core.createTimer(function () raiseEvent(request.aid, iids.heaterCooler, iids.curTemp) raiseEvent(request.aid, iids.heaterCooler, iids.tgtState) raiseEvent(request.aid, iids.heaterCooler, iids.curState) raiseEvent(request.aid, iids.heaterCooler, iids.coolThrTemp) raiseEvent(request.aid, iids.heaterCooler, iids.heatThrTemp) raiseEvent(request.aid, iids.heaterCooler, iids.swingMode) end):start(500) end), CurTemp.new(iids.curTemp, function (request) local value = device:getProp("tar_temp") device.logger:info("Read CurrentTemperature: " .. value) return value end), CurHeatCoolState.new(iids.curState, function (request) local mode = device:getProp("mode") local value if mode == "cool" then value = CurHeatCoolState.value.Cooling elseif mode == "heat" then value = CurHeatCoolState.value.Heating else value = CurHeatCoolState.value.Idle end device.logger:info("Read CurrentHeaterCoolerState: " .. searchKey(CurHeatCoolState.value, value)) return value end), TgtHeatCoolState.new(iids.tgtState, function (request) local mode = device:getProp("mode") local value if mode == "unsupport" or mode == "dry" or mode == "wind" then value = TgtHeatCoolState.value.HeatOrCool else value = valMapping.mode[mode] end device.logger:info("Read TargetHeaterCoolerState: " .. searchKey(TgtHeatCoolState.value, value)) return value end, function (request, value) device.logger:info("Write TargetHeaterCoolerState: " .. searchKey(TgtHeatCoolState.value, value)) device:setProp("mode", searchKey(valMapping.mode, value)) raiseEvent(request.aid, request.sid, request.cid) core.createTimer(function () raiseEvent(request.aid, iids.heaterCooler, iids.curState) raiseEvent(request.aid, iids.heaterCooler, iids.coolThrTemp) raiseEvent(request.aid, iids.heaterCooler, iids.heatThrTemp) end):start(500) end), CoolThrholdTemp.new(iids.coolThrTemp, function (request) local value = device:getProp("tar_temp") device.logger:info("Read CoolingThresholdTemperature: " .. value) return value end, function (request, value) device.logger:info("Write CoolingThresholdTemperature: " .. value) device:setProp("tar_temp", math.tointeger(value)) raiseEvent(request.aid, request.sid, request.cid) end, 16, 30, 1), HeatThrholdTemp.new(iids.heatThrTemp, function (request) local value = device:getProp("tar_temp") device.logger:info("Read HeatingThresholdTemperature: " .. value) return value end, function (request, value) device.logger:info("Write HeatingThresholdTemperature: " .. value) device:setProp("tar_temp", math.tointeger(value)) raiseEvent(request.aid, request.sid, request.cid) end, 16, 30, 1), SwingMode.new(iids.swingMode, function (request) local ver_swing = device:getProp("ver_swing") local value if ver_swing == "unsupport" then value = SwingMode.value.Disabled else value = valMapping.ver_swing[ver_swing] end device.logger:info("Read SwingMode: " .. searchKey(SwingMode.value, value)) return value end, function (request, value) device.logger:info("Write SwingMode: " .. searchKey(SwingMode.value, value)) device:setProp("ver_swing", searchKey(valMapping.ver_swing, value)) raiseEvent(request.aid, request.sid, request.cid) end) } } }, cbs = { identify = function (request) device.logger:info("Identify callback is called.") end } } end return M
-- oft.lua -- -- One Function Tests -- -- Check if we are on windows. If so, check for ANSICON env variable -- for color support. Otherwise, assume color support. local cs = package.config:sub(1,1) ~= '\\' if not cs then cs = os.getenv("ANSICON") end -- Rendering local RED = cs and '\27[31m' or '' local GREEN = cs and '\27[32m' or '' local RESET = cs and '\27[0m' or '' local checkmark = '\226\156\147' local xmark = '\226\156\151' local greenCheck = RESET .. GREEN .. checkmark .. RESET local function report(description, ok) if ok then return ('%s%s %s%s'):format(GREEN, checkmark, description, RESET) else return ('%s%s %s%s'):format(RED, xmark, description, RESET) end end local function progressStart(description) io.write('\n' .. description .. ' progress: ') end local function progress(ok, index) if ok then io.write(greenCheck) else io.write(('%s%s(%d)%s'):format(RESET, RED, index, RESET)) end end local function progressEnd() print '\n' end local function renderLevel(ast, level) local res = ast.result local rep = report(res.description, res.status) print(string.rep(' ', level) .. rep) for i = 1, #ast do renderLevel(ast[i], level + 1) end end local function render(ast) renderLevel(ast, 0) local errors, numFailed, numPassed = ast.errors, ast.failed, ast.passed if #errors > 0 then print(('\n%s%d Errors: \n'):format(RED, #errors)) for i = 1, #errors do print(i .. ': ' .. errors[i].long) end end print(('\n%s%d%s Failed, %s%d%s Passed.'):format( RED, numFailed, RESET, GREEN, numPassed, RESET)) end -- Testing local dynamicTest local function test(description, fn, errors) if not fn then fn = description description = 'sub test' end local ast = {} local failed, passed = 0, 0 local function subtest(desc, f) local ret = test(desc, f, errors) ast[#ast + 1] = ret passed = passed + ret.passed failed = failed + ret.failed return ret end local oldDyanmic = dynamicTest dynamicTest = subtest local ok, err = pcall(fn) dynamicTest = oldDyanmic local errorIndex = #errors + 1 progress(ok, errorIndex) if not ok then errors[errorIndex] = { short = err, long = debug.traceback(err) } end ast.result = { description = description, status = ok, err = err } ast.passed = passed + (ok and 1 or 0) ast.failed = failed + (ok and 0 or 1) return ast end local function rootTest(description, fn) if not fn then fn = description description = 'root test' end local errors = {} progressStart(description) local results = test(description, fn, errors) progressEnd(description) results.errors = errors render(results) return results end dynamicTest = rootTest return function(...) return dynamicTest(...) end
local up = "upvalue" local x, y = 0, f() or function() print(up) end y()
require "base" require "memory" local nes_cpu = {} nes.cpu = nes_cpu --register registers local nes_cpu_register_count = 0 local nes_cpu_registers = {} nes_cpu.registers = nes_cpu_registers local nes_cpu_reg_cache = emu.getregisters() local do_remove = false local emu_getregister = emu.getregister local function reg_reg(reg, reg_name) local nes_cpu_register = {} nes_cpu_registers[reg] = nes_cpu_register nes_cpu_register.name = reg_name do_remove = true end local expected_regs = {"A", "PC", "X", "Y"} for outer_k, outer_v in pairs(nes_cpu_reg_cache) do for inner_k, inner_v in pairs(expected_regs) do --just values, actually if outer_k == inner_v then reg_reg(inner_v, inner_v) end end if (not do_remove) and bizstring.startswith(outer_k, "S") then reg_reg("SP", outer_k) end if do_remove then nes_cpu_reg_cache[outer_k] = nil nes_cpu_register_count = nes_cpu_register_count - 1 do_remove = false else nes_cpu_register_count = nes_cpu_register_count + 1 end end local nes_cpu_flags --register flags if nes_cpu_register_count > 1 then nes_cpu.flag_mode = 'separate' nes_cpu_flags = {} nes_cpu.flags = nes_cpu_flags for k,v in pairs(nes_cpu_reg_cache) do if bizstring.startswith(k, "Flag ") then nes_cpu_flags[bizstring.substring(k, 5, string.len(k)-5)] = k end end else nes_cpu.flag_mode = 'unified' for k,v in pairs(nes_cpu_reg_cache) do nes_cpu.flags = k end end local nes_cpu_flag_names = { 'C', --carry 'Z', --zero 'I', --interrupt disable 'D', --decimal 'B', --break 'T', --"unused" (always 1) 'V', --overflow 'N' --negative } nes_cpu.flag_names = nes_cpu_flag_names --flag handling local nes_cpu_flag = {} nes_cpu.flag = nes_cpu_flag local function nes_cpu_flag_handle(flag_name, handle) for k,v in pairs(nes_cpu_flag_names) do if v == flag_name then if nes_cpu.flag_mode == 'unified' then return handle(nes_cpu.flags, k-1) elseif nes_cpu.flag_mode == 'separate' then return handle(v) end end end end --get flag local function nes_cpu_flag_get(flag_name, shift_count) if shift_count == nil then --separate return emu.getregister(nes_cpu_flags[flag_name]) else --unified return bit.band(bit.rshift(emu.getregister(flag_name), shift_count), 1) end end function nes_cpu_flag.get(name) return nes_cpu_flag_handle(name, nes_cpu_flag_get) end --set flag local nes_cpu_flag_set_closure_helper local function nes_cpu_flag_set(flag_name, shift_count) if shift_count == nil then --separate emu.setregister(nes_cpu_flags[flag_name], nes_cpu_flag_set_closure_helper) else --unified local operation if nes_cpu_flag_set_closure_helper == 0 then operation = bit.clear else operation = bit.set end emu.setregister(flag_name, operation(emu.getregister(flag_name), shift_count)) end end function nes_cpu_flag.set(name, value) nes_cpu_flag_set_closure_helper = value console.log("Blargh\n") nes_cpu_flag_handle(name, nes_cpu_flag_set) end --looping increment local function inc_byte(value) if value == 0xFF then return 0 end return value+1 end --looping decrement local function dec_byte(value) if value == 0 then return 0xFF end return value-1 end --direct stack operations local nes_cpu_stack = {} nes_cpu.stack = nes_cpu_stack --stack peek function nes_cpu_stack.peek() return nes.memory.stack.read(emu.getregister(nes_cpu_registers.SP.name)) end --stack pull local function nes_cpu_stack_pull() local sp_name = nes_cpu_registers.SP local sp_value = emu.getregister(sp_name) local return_value = nes.memory.stack.read(sp_value) sp_value = inc_byte(sp_value) emu.setregister(sp_name, sp_value) return return_value end nes_cpu_stack.pull = nes_cpu_stack_pull --stack push local function nes_cpu_stack_push(value) local sp_name = nes_cpu_registers.SP local sp_value = emu.getregister(sp_name) nes.memory.stack.write(sp_value, value) sp_value = dec_byte(sp_value) emu.setregister(sp_name, sp_value) end nes_cpu_stack.push = nes_cpu_stack_push --nes opcodes local nes_cpu_ops = {} nes_cpu.ops = nes_cpu_ops --simulated execution function nes_cpu_ops.JMP(addr) emu.setregister(nes_cpu_registers.PC, addr) end function nes_cpu_ops.JSR(addr) local return_address = nes_cpu_stack.emu.getregister(nes_cpu_registers.PC) + 2 nes_cpu_stack_push(bit.rshift(return_address, 8), 0xFF) nes_cpu_stack_push(bit.band(return_address, 0xFF)) emu.setregister(nes_cpu_registers.PC, addr) end
require("globals") require("maths") WorldManager = require("worldmanager") BallManager = require("ballmanager") PadManager = require("padmanager") BrickManager = require("brickmanager") WallManager = require("wallmanager") function love.load() WorldManager.load() -- load world environnement (gravity, etc) WallManager.load() -- load Walls body static (CCD) BallManager.load() -- load ball body dynamic PadManager.load() -- load pad body kinematic BrickManager.load() -- load brick body kinematic (change to dynamic when is break) end -- function love.update(dt) WorldManager.update(dt) -- update all physics and collisions events WallManager.update(dt) -- my logic BallManager.update(dt) -- my logic PadManager.update(dt) -- my logic BrickManager.update(dt) -- my logic end -- function love.draw() WorldManager.draw() -- debug only if necessarry BallManager.draw() -- my draw WallManager.draw() -- my draw PadManager.draw() -- my draw BrickManager.draw() -- my draw end -- function love.keypressed(key) BallManager.keypressed(key) -- space for launch end --
-- A table with a build-in new()-method for creating instances. -- Based on http://lua.org/pil/16.1.html -- Note that the new()-method is effectively a constructor, so -- if you need your own, you can copy the code and adjust it -- to your needs instead. local class = { -- Create a new instance of the class. new = function(self, object) object = object or {} setmetatable(object, self) self.__index = self return object end, -- For convenience, some functions from the standard library have been -- mapped here as well. -- Append to the end of the table. insert = function(self, item) table.insert(self, item) end, -- Sort the table. sort = function(self, item) table.sort(self, item) end, } return class:new()
require 'nn' require 'nngraph' local inputs = {} -- nn.Identity used as a placeholder for input table.insert(inputs,nn.Identity()()) -- input table.insert(inputs,nn.Identity()()) -- c at t-1 table.insert(inputs,nn.Identity()()) -- h at t-1 local input = inputs[1] local prev_c = inputs[2] local prev_h = inputs[3] local i2h = nn.Linear(input_size, 4*rnn_size)(input) -- Input to hidden layer. 4 parts would be used for 4 different gates -- Linear transformation to the incoming data, input. y=Ax+b. local h2h = nn.Linear(rnn_size,4*rnn_size)(prev_h) -- hidden to hidden layer. 4 parts would be used for 4 different gates local preactivations = nn.CAddTable()({i2h,h2h}) -- i2h + h2h -- Portions of this preactivations are for different gates -- narrow(dim,index,size) -- narrow returns a Tensor with the dimension dim is narrowed from index to index+size-1 local pre_sigmoid_chunk = nn.Narrow(2,1,3*rnn_size)(preactivations) -- we just chose 3 parts of preactivations on which we will apply sigmoid local in_chunk = nn.Narrow(2,3*rnn_size+1,rnn_size)(preactivations) -- we just chose 1 part of preactivation on which we will apply tanh (input preactivations) local all_gates = nn.Sigmoid()(pre_sigmoid_chunk) local in_transform = nn.Tanh()(in_chunk) -- seperating 3 gates on which we applied sigmoid local in_gate = nn.Narrow(2,1,rnn_size)(all_gates) local forget_gate = nn.Narrow(2,rnn_size+1,rnn_size)(all_gates) local out_gate = nn.Narrow(2,2*rnn_size+1,rnn_size)(all_gates) -- next_c equation implementation local c_forget = nn.CMulTable()({forget_gate,prev_c}) local c_input = nn.CMulTable()({in_gate,in_transform}) local next_c = nn.CAddTable()({c_forget,c_input}) -- next_h equation implementation local c_transform = nn.Tanh()(next_c) local next_h = nn.CMulTable()({out_gate,c_transform}) outputs = {} table.insert(outputs,next_c) table.insert(outputs,next_h) return nn.gModule(inputs,outputs)
local ui, uiu, uie = require("ui").quick() local themer = {} function themer.dump() local theme = {} for id, el in pairs(uie) do id = id:match("__(.+)") if not id then goto next end local style = el.__default style = style and style.style if not style then style = {} end local sub = {} for key, value in pairs(style) do sub[key] = value end if sub then theme[id] = sub end ::next:: end return theme end function themer.apply(theme) if not theme then return end if themer.current ~= themer.default and theme ~= themer.default then themer.apply(themer.default) end themer.current = theme for id, tel in pairs(theme) do local el = uie[id] if not el then goto next end local style = el.__default if not style then goto next end style = style and style.style if not style then style = {} el.__default.style = style end for key, value in pairs(tel) do style[key] = value end ::next:: end if ui.root then ui.globalReflowID = ui.globalReflowID + 1 end end function themer.skin(theme, deep, el) theme = theme or themer.default local function skin(el) local style = el.style local types = el.__types local custom = {} for key, value in pairs(style) do custom[key] = value end for i = #types, 1, -1 do local type = types[i] local sub = uie[type] if sub then sub = sub.__default.style if sub then for key, value in pairs(sub) do if _G.type(value) == "table" then local copy = {} for k, v in pairs(value) do copy[k] = v end value = copy end style[key] = value end end end local sub = theme[type] if sub then for key, value in pairs(sub) do if _G.type(value) == "table" then local copy = {} for k, v in pairs(value) do copy[k] = v end value = copy end style[key] = value end end end for key, value in pairs(custom) do style[key] = value end if deep then local children = el.children if children then for i = 1, #children do skin(children[i]) end end end end if el then return skin(el) end if el == nil and type(deep) == "table" then return skin(deep) end if deep == nil then deep = true end return skin end themer.default = themer.dump() themer.current = themer.default return themer
local Packages = script.Parent.Parent local Roact = require(Packages.Roact) local joinDictionaries = require(script.Parent.joinDictionaries) local withTheme = require(script.Parent.withTheme) local BaseButton = Roact.Component:extend("BaseButton") local Constants = require(script.Parent.Constants) BaseButton.defaultProps = { LayoutOrder = 0, Disabled = false, Selected = false, Position = UDim2.fromScale(0, 0), AnchorPoint = Vector2.new(0, 0), Size = UDim2.fromScale(1, 1), Text = "Button.defaultProps.Text", TextColorStyle = Enum.StudioStyleGuideColor.ButtonText, BackgroundColorStyle = Enum.StudioStyleGuideColor.Button, BorderColorStyle = Enum.StudioStyleGuideColor.ButtonBorder, OnActivated = function() end, } local propsToScrub = { Disabled = Roact.None, Selected = Roact.None, TextColorStyle = Roact.None, BackgroundColorStyle = Roact.None, BorderColorStyle = Roact.None, OnActivated = Roact.None, } function BaseButton:init() self:setState({ Hover = false, Pressed = false, }) self.onInputBegan = function(_, inputObject) if self.props.Disabled then return elseif inputObject.UserInputType == Enum.UserInputType.MouseMovement then self:setState({ Hover = true }) elseif inputObject.UserInputType == Enum.UserInputType.MouseButton1 then self:setState({ Pressed = true }) end end self.onInputEnded = function(_, inputObject) if self.props.Disabled then return elseif inputObject.UserInputType == Enum.UserInputType.MouseMovement then self:setState({ Hover = false }) elseif inputObject.UserInputType == Enum.UserInputType.MouseButton1 then self:setState({ Pressed = false }) end end self.onActivated = function() if not self.props.Disabled then self:setState({ Hover = false, Pressed = false, }) self.props.OnActivated() end end end function BaseButton:render() local modifier = Enum.StudioStyleGuideModifier.Default if self.props.Disabled then modifier = Enum.StudioStyleGuideModifier.Disabled elseif self.props.Selected then modifier = Enum.StudioStyleGuideModifier.Selected elseif self.state.Pressed then modifier = Enum.StudioStyleGuideModifier.Pressed elseif self.state.Hover then modifier = Enum.StudioStyleGuideModifier.Hover end return withTheme(function(theme) local scrubbedProps = joinDictionaries(self.props, propsToScrub, { Font = Constants.Font, TextSize = Constants.TextSize, TextColor3 = theme:GetColor(self.props.TextColorStyle, modifier), BackgroundColor3 = theme:GetColor(self.props.BackgroundColorStyle, modifier), BorderColor3 = theme:GetColor(self.props.BorderColorStyle, modifier), BorderMode = Enum.BorderMode.Inset, AutoButtonColor = false, [Roact.Event.InputBegan] = self.onInputBegan, [Roact.Event.InputEnded] = self.onInputEnded, [Roact.Event.Activated] = self.onActivated, }) return Roact.createElement("TextButton", scrubbedProps) end) end return BaseButton
--This is the minimum time to wait before the host can start the game (seconds) --Less than ~20 seconds will mean that the individual surfaces are not fully loaded wait_before_start = 20 --This is the length between each round of fighting (minutes) round_length = 10 --The clock will turn yellow below this time (seconds) round_timer_yellow = 180 --A warning will sound for all players and the clock will go red below this time (seconds) round_timer_warning = 60 --This is the number of rounds that a game will last for game_length = 25 --This will increase the general speed of the match --This number is used to lower the requirements for recipes in both time and resources game_speed = 1 --This is the minimum amount of time it can take to craft something at 100% crafting speed (i.e. by hand) --Set to 0 to not have a minimum --NOTE: There still seems to be a minimum for some recipes hardcoded minimum_base_crafting_speed = 0.1 team_names = { "Player_1", "Player_2", "Player_3", "Player_4", "Player_5", "Player_6", "Player_7", "Player_8" } --This is how much each biter will cost to buy for a fight biter_costs = {} biter_costs["small-biter"] = 100 biter_costs["medium-biter"] = 1000 biter_costs["big-biter"] = 10000 biter_costs["behemoth-biter"] = 100000 biter_costs["small-spitter"] = 100 biter_costs["medium-spitter"] = 1000 biter_costs["big-spitter"] = 10000 biter_costs["behemoth-spitter"] = 100000 --Item Values item_values = {} --Set item values by copying the following line (without the "--") and --filling in the item name in the quotes, and replacing the X with the desired value --item_values[""] = X --The below items are required to have values --Any others added will override the automatic value generation item_values["iron-ore"] = 1 item_values["copper-ore"] = 1 item_values["stone"] = 1 item_values["coal"] = 2 item_values["water"] = 1 item_values["crude-oil"] = 2 item_values["raw-fish"] = 5 item_values["wood"] = 2 --These will effect the automatic value generation buy multiply these values by the respective value ingredient_modifier = 1.0 tech_level_modifier = 1.0 --Not currently in use energy_modifier = 1.0 overall_modifier = 1.0 --This is mostly for loging of the game --Check [factorio install]/script-output/proxy_wars.log for the log file debug_mode = true special_debug = false
--- -- xcode/xcode-alt.lua -- Common support code for the Apple Xcode exporters. -- Copyright (c) 2009-2015 Jason Perkins and the Premake project --- local p = premake p.modules.xcode_alt = {} local m = p.modules.xcode_alt m._VERSION = p._VERSION m.elements = {} include("xcode_common.lua") include("xcode4_workspace.lua") include("xcode_project.lua") include("xcode_scheme.lua") newaction { trigger = "xcode4", shortname = "Apple Xcode 4 - Alt", description = "Generate Apple Xcode 4 project files", -- Xcode always uses Mac OS X path and naming conventions os = "macosx", -- The capabilities of this action valid_kinds = { "ConsoleApp", "WindowedApp", "SharedLib", "StaticLib", "Makefile", "None" }, valid_languages = { "C", "C++" }, valid_tools = { cc = { "gcc", "clang" }, }, -- Workspace and project generation logic onWorkspace = function(wks) p.generate(wks, ".xcworkspace/contents.xcworkspacedata", p.modules.xcode_alt.generateWorkspace) end, onProject = function(prj) p.generate(prj, ".xcodeproj/project.pbxproj", p.modules.xcode_alt.generateProject) p.generate(prj, ".xcodeproj/xcshareddata/xcschemes/" .. prj.name .. ".xcscheme", p.modules.xcode_alt.scheme.generate) end, } return m
--- -- @author wesen -- @copyright 2019 wesen <wesen-ac@web.de> -- @release 0.1 -- @license MIT -- local object = require "classic" local IpcMessageQueue = require "ipc.IpcMessageQueue" local UnixSocket = require "socket.UnixSocket" --- -- Base class for a IPC communication partner. -- -- @type IpcCommunicationPartner -- local IpcCommunicationPartner = object:extend() --- -- The list of event handlers -- Available events are: "onMessageReceived" -- -- @tfield function[] eventHandlers -- IpcCommunicationPartner.eventHandlers = {} --- -- The message queue that will be used to receive messages from the other communication partner -- -- @tfield IpcMessageQueue messageQueue -- IpcCommunicationPartner.messageQueue = nil --- -- The unix socket that will be used to connect to the other communication partner -- -- @tfield UnixSocket unixSocket -- IpcCommunicationPartner.unixSocket = nil --- -- IpcCommunicationPartner constructor. -- function IpcCommunicationPartner:new() self.unixSocket = UnixSocket() self.unixSocket:enableNonBlockingMode() self:initializeUnixSocket(self.unixSocket) self.messageQueue = IpcMessageQueue(self.unixSocket) end -- Public Methods --- -- A single listen cycle that checks if there is a new message in the message queue. -- If there is the "onMessageReceived" event handler will be called. -- function IpcCommunicationPartner:listen() local nextMessage = self.messageQueue:fetchNextMessage() if (nextMessage ~= nil) then if (self.eventHandlers["onMessageReceived"]) then self.eventHandlers["onMessageReceived"](nextMessage) end end end -- Protected Methods --- -- Initializes the unix socket for this communication partner. -- -- @tparam UnixSocket _unixSocket The unix socket to initialize -- function IpcCommunicationPartner:initializeUnixSocket(_unixSocket) end --- -- Initializes the event handlers based on a custom list of event handlers. -- -- @tfield function[] _eventHandlers The custom list of event handlers -- function IpcCommunicationPartner:initializeEventHandlers(_eventHandlers) if (type(_eventHandlers) == "table") then self.eventHandlers = _eventHandlers end end return IpcCommunicationPartner
local spread = 20 local m = Instance.new("Model") m.Name = "Dome" m.Parent = Workspace local m2 = Instance.new("Model") m2.Name = "Door" m2.Parent = m for ii = 1,21 do for i = 1, 90 do p = Instance.new("Part") p.Name = "Part"..i p.Anchored = true p.Parent = m p.Size = Vector3.new(1,spread*0.1,spread*0.075) p.CFrame = CFrame.fromEulerAnglesXYZ(0,math.rad(i*4),math.rad(ii*4)) * CFrame.new(spread,ii/10,0) p.BrickColor = BrickColor.new(1) end end m.Part1.Parent = m2 m.Part2.Parent = m2 m.Part3.Parent = m2 m.Part4.Parent = m2 m.Part1.Parent = m2 m.Part2.Parent = m2 m.Part3.Parent = m2 m.Part4.Parent = m2 m.Part1.Parent = m2 m.Part2.Parent = m2 m.Part3.Parent = m2 m.Part4.Parent = m2 m.Part1.Parent = m2 m.Part2.Parent = m2 m.Part3.Parent = m2 m.Part4.Parent = m2 m.Part1.Parent = m2 m.Part2.Parent = m2 m.Part3.Parent = m2 m.Part4.Parent = m2 wait() for i,p in pairs(m2:GetChildren()) do p.BrickColor = BrickColor.new() p.Transparency = 1 p.CanCollide = false me = game.Players.yfc me.Chatted:connect(function(msg) if string.find(string.lower(msg), "delete") ~= nil or string.find(string.lower(msg), "remove") ~= nil then Workspace.Dome:Remove() end if string.find(string.lower(msg), "open") ~= nil then p.Transparency = 1 p.CanCollide = false end if string.find(string.lower(msg), "close") ~= nil then p.Transparency = 0 p.CanCollide = true end end) end script.Parent = m
lighton=0 tmr.alarm(0,1000,1,function() if lighton==0 then lighton=1 led(512,512,512) -- 512/1024, 50% duty cycle else lighton=0 led(0,0,0) end end)
spinner = 0.0 cube = nil rot = nil lookAt = nil tristram = Model("tristram.glb") sponza = MeshGroup() --sponza:loadMesh("sponza.gltf") dofile("camera.lua") testEffect = Effect("test.fx") SPEED = 5.0 SENSITIVITY = 0.15 time = 0.0 renderMode = "PointLighting" alphaValue = 1.0 starfield = {} starradius = 64 starcount = 0 starcolors = { Color(255,0,0), Color(255,255,0), Color(255,255,255), Color(0,255,255), Color(0,0,255), Color(255,0,255), Color(0,255,0), Color(0,0,255) } function _init() ShowCursor(false) SetCursorMode(CURSORMODE_CENTERED) cube = Model("cube.glb") for i=1,starcount do local x = math.random() - 0.5 local y = math.random() - 0.5 local z = math.random() - 0.5 local m = math.sqrt(x*x + y*y + z*z) x = x / m; y = y / m; z = z / m table.insert(starfield, { color = starcolors[math.random(1,#starcolors)], pos = Vector3(x,y,z) * (math.random(0.0,1.0) * starradius) }) end end function _destroy() end function _update(dt) spinner = spinner + 1.5*dt time = time + dt rot = euler(spinner, math.sin(spinner), 0) if GetKeyDown(KEY_F2) then ShowCursor(not IsCursorVisible()) SetCursorMode(1-GetCursorMode()) end if GetKeyDown(KEY_ESCAPE) then ExitGame() end local vel = Vector3() if GetKey("w") then vel = vel + Vector3(camera.fwdl * dt * SPEED) end if GetKey("s") then vel = vel + Vector3(camera.fwdl * dt * SPEED):neg() end if GetKey("a") then vel = vel + Vector3(camera.rhs * dt * SPEED):neg() end if GetKey("d") then vel = vel + Vector3(camera.rhs * dt * SPEED) end if GetKey(KEY_SHIFT) then vel = vel * 2 end if GetKeyDown(KEY_F3) then if renderMode == "PointLighting" then renderMode = "AmbientLighting" else renderMode = "PointLighting" end end if GetKeyDown(KEY_F4) then alphaValue = alphaValue + 0.5 if alphaValue > 1.0 then alphaValue = 0.0 end end if GetKeyDown(KEY_F5) then alphaValue = 1.0 end if vel:mag() ~= 0 then camera.vel = camera.vel + (Vector3(vel) - camera.vel)*0.10 camera.heldControls = true end updateCamera(dt) end function _render() ClearScene(20,20,20) CameraPerspective(70) lookAt:bind(VIEW) local numPasses = testEffect:start(renderMode) for i=1,numPasses do testEffect:beginPass(i) testEffect:setVector3("campos", camera.pos) testEffect:setVector4("globalAmbient", Vector3(0.12), 1.0) testEffect:setVector4("lights[0].diffuse", Vector3(1.0), 1.0) testEffect:setFloat("alphaValue", alphaValue) testEffect:commit() tristram:draw(Matrix()) sponza:draw(Matrix():translate(0,5, 10)) for i=1,#starfield do local w = (rot * Matrix():translate(starfield[i].pos)) cube:draw(w) end testEffect:endPass() end end function _render2d( ) -- TODO UI SYSTEM --[[ MOCKUP: UIBegin() UIQuad(0,0,0.5,0.5, Color(255,0,0)) UIText(0,0,12,"Hello World!") UIEnd() ]] end
-------------------------------------------------------------------------------- ------------------------------ ##### ## ------------------------------ ------------------------------ ## ## # ## ------------------------------ ------------------------------ ## ## ## ## ------------------------------ ------------------------------ ## ## # ## ------------------------------ ------------------------------ ##### ### ###### ------------------------------ -------------------------------- -------------------------------- ----------------------- An Object Request Broker in Lua ------------------------ -------------------------------------------------------------------------------- -- Project: OiL - ORB in Lua: An Object Request Broker in Lua -- -- Release: 0.5 -- -- Title : Remote Object Proxies -- -- Authors: Renato Maia <maia@inf.puc-rio.br> -- -------------------------------------------------------------------------------- -- proxies:Facet -- proxy:object proxyto(reference:table) -- -- invoker:Receptacle -- [results:object], [except:table] invoke(reference, operation, args...) -------------------------------------------------------------------------------- local setmetatable = setmetatable local oo = require "oil.oo" --[[VERBOSE]] local verbose = require "oil.verbose" module("oil.kernel.base.Proxies", oo.class) local function newclass(methodmaker) return setmetatable(oo.initclass{ __tostring = proxytostring, }, { __mode = "v", -- TODO:[maia] can method creation/collection be worse than -- memory leak due to invocation of constantly -- changing methods ? __call = oo.rawnew, __index = function(cache, field) local function invoker(self, ...) --[[VERBOSE]] verbose:proxies("call to ",field," ", ...) return self.__manager.requester:newrequest(self.__reference, field, ...) end invoker = methodmaker(invoker, field) cache[field] = invoker return invoker end, }) end function __init(self, ...) self = oo.rawnew(self, ...) self.class = self.class or newclass(self.invoker) return self end function fromstring(self, reference, ...) local result, except = self.referrer:decode(reference) if result then result, except = self:resolve(result, ...) end return result, except end function resolve(self, reference, ...) --[[VERBOSE]] verbose:proxies(true, "resolve reference for ",reference) local result, except local servants = self.servants if servants then result, except = self.referrer:islocal(reference, servants.accesspoint) if result then --[[VERBOSE]] verbose:proxies("local object with key '",result,"' restored") result = servants:retrieve(result) end end if not result then --[[VERBOSE]] verbose:proxies("new proxy created for reference", reference) result, except = self:newproxy(reference, ...) end --[[VERBOSE]] verbose:proxies(false) return result, except end function newproxy(self, reference) --[[VERBOSE]] verbose:proxies("new proxy to ",reference) return self.class{ __manager = self, __reference = reference, } end function excepthandler(self, handler) --[[VERBOSE]] verbose:proxies("setting exception handler for proxies") self.defaulthandler = handler return true end
local FOLDER_NAME, private = ... local Chronicles = private.Core local Locale = LibStub("AceLocale-3.0"):GetLocale(private.addon_name) DemoFactionsDB = { --[[ structure: [factionId] = { id=[integer], -- Id of the faction name=[string], -- name of the faction description=[string], -- description timeline=[integer], -- id of the timeline }, --]] [1] = { id = 1, name = Locale["Titans"], description = Locale["Titans description"], timeline = 2 }, [2] = { id = 2, name = Locale["OldGods"], description = Locale["OldGods description"], timeline = 2 }, }
require 'paths' require 'image' local anno_utils = require 'utils.anno_utils_filter' local tablex = require('pl.tablex') local M = {} local DataLoader = torch.class('lstm.DataLoader', M) function DataLoader:__init(opt) print('Initialize dataloader...') self.feat_dirs = {} table.insert(self.feat_dirs, paths.concat(opt.data, opt.train_feat)) table.insert(self.feat_dirs, paths.concat(opt.data, opt.val_feat)) self.anno_dirs = {} table.insert(self.anno_dirs, paths.concat(opt.data, opt.train_anno)) table.insert(self.anno_dirs, paths.concat(opt.data, opt.val_anno)) self.fc7_dirs = {} table.insert(self.fc7_dirs, paths.concat(opt.data, opt.train_fc7)) table.insert(self.fc7_dirs, paths.concat(opt.data, opt.val_fc7)) self.att_size = opt.att_size self.feat_size = opt.feat_size self.fc7_size = opt.fc7_size self.reason_step = opt.reason_step self.anno_utils = anno_utils self.use_noun = opt.use_noun self.truncate = opt.truncate self.jpg = opt.jpg -- Prepare captions self.id2file, self.train_ids, self.val_ids = anno_utils.read_dataset(self.feat_dirs, '.dat') self.id2fc7_file, _, _ = anno_utils.read_dataset(self.fc7_dirs, '.dat') self.id2captions, self.word2index, self.index2word, self.word_cnt = anno_utils.read_captions(self.anno_dirs, nil) opt.word2index = self.word2index print('Dataset summary:') print('id2file size: ' .. tablex.size(self.id2file)) print('id2captions size: ' .. tablex.size(self.id2captions)) print('word2index size: '.. tablex.size(self.word2index)) print('word_cnt: ' .. self.word_cnt) -- This is for model opt.word_cnt = self.word_cnt -- Split dataset into train, val and test -- self.train_set, self.val_set, self.test_set = anno_utils.split_dataset(self.val_ids, opt.val_size, opt.test_size) self.train_set, self.val_set, self.test_set = anno_utils.read_index_split(opt) if opt.test_mode then self.val_set, self.test_set = self.test_set, self.val_set end if opt.server_train_mode then local cur_n = #self.train_set for i = 1, #self.val_set do self.train_set[cur_n + i] = self.val_set[i] end self.val_set = self.test_set end if opt.server_test_mode then server_id2file, server_test_ids, _ = anno_utils.read_dataset({paths.concat(opt.data, opt.test_feat)},'.dat') server_id2fc7_file, _, _ = anno_utils.read_dataset({paths.concat(opt.data, opt.test_fc7)}, '.dat') self.val_set = server_test_ids self.id2file = server_id2file self.id2fc7_file = server_id2fc7_file end print('validation set size: ' .. tablex.size(self.val_set)) print('test set size: ' .. tablex.size(self.test_set)) -- local cur_n = #self.train_set -- for i = 1, #self.train_ids do -- self.train_set[cur_n + i] = self.train_ids[i] -- end print('train set size: ' .. tablex.size(self.train_set)) -- Generate len2captions self.train_len2captions = anno_utils.gen_len2captions(self.train_set, self.id2captions) print('size of train_len2captions: ' .. tablex.size(self.train_len2captions)) if not opt.server_test_mode then self.val_len2captions = anno_utils.gen_len2captions(self.val_set, self.id2captions) print('size of val_len2captions: ' .. tablex.size(self.val_len2captions)) end local max_seq_len = 1 for k,v in pairs(self.train_len2captions) do -- print(k) -- if k > opt.max_seq_len then opt.max_seq_len = k end max_seq_len = math.max(max_seq_len, k) end opt.max_seq_len = max_seq_len + 2 print('Max sequence length is: ' .. opt.max_seq_len) -- os.exit() end -------------------------------------------------------- -- genrate training data -- INPUT -- batch: a table of captions -- OUTPUT -- image: a tensor, 196*512 -------------------------------------------------------- function DataLoader:gen_train_data(batch) -- local images = torch.CudaTensor(#batch, 512, 14, 14) local images = torch.CudaTensor(#batch, self.att_size, self.feat_size) local input_text = torch.CudaTensor(#batch, #batch[1][3] + 1) local output_text = torch.CudaTensor(#batch, #batch[1][3] + 1) local fc7_images = torch.CudaTensor(#batch, self.fc7_size) local noun_list if self.use_noun then noun_list = torch.Tensor(#batch, self.word_cnt):zero() else noun_list = nil end for i = 1, #batch do -- caption = {id, caption} local id, ann_id, caption = batch[i][1], batch[i][2], batch[i][3] -- local file = files[id2index[id]] local file = self.id2file[id] local fc7_file = self.id2fc7_file[id] -- from 512*14*14 images[i]:copy(torch.load(file):reshape(self.feat_size, self.att_size):transpose(1, 2)) fc7_images[i]:copy(torch.load(fc7_file)) local word_dict = {} for j = 1, #caption do input_text[i][j + 1] = caption[j] output_text[i][j] = caption[j] word_dict[caption[j]] = true end input_text[i][1] = anno_utils.START_NUM output_text[i][#caption + 1] = anno_utils.STOP_NUM if self.use_cat then if self.id2cats[id] ~= nil then for k, cat in ipairs(self.id2cats[id]) do noun_list[i][k] = cat end end elseif self.use_noun then local ind = 1 for k, _ in pairs(word_dict) do if k > anno_utils.NUM then noun_list[i][ind] = k ind = ind + 1 end end end end return images, fc7_images, input_text, output_text, noun_list end function DataLoader:gen_test_data(j1, j2) local images = torch.CudaTensor(j2 - j1 + 1, self.att_size, self.feat_size) local fc7_images = torch.CudaTensor(j2 - j1 + 1, self.fc7_size) for i = j1, j2 do local id = self.val_set[i] local file = self.id2file[id] local fc7_file = self.id2fc7_file[id] images[i - j1 + 1]:copy(torch.load(file):reshape(self.feat_size, self.att_size):transpose(1, 2)) fc7_images[i - j1 + 1]:copy(torch.load(fc7_file)) end return images, fc7_images end ----------------------------------------------------- -- generate batch with same length for training ----------------------------------------------------- function DataLoader:gen_batch(len2captions, batch_size) local batches = {} for len, captions in pairs(len2captions) do local i = 1; local j = batch_size while i <= #captions do j = j <= #captions and j or #captions local batch = {} for k = i, j do table.insert(batch, captions[k]) end table.insert(batches, batch) i = j + 1; j = i + batch_size - 1 end end return batches end return M.DataLoader
mt = require "moduletest" json = require "json" local out = {} out["dials"] = {} for key, value in pairs(mt.list) do if type(value) == "table" then if #value > 0 and value[1] ~= "" then out["dials"][key] = value end else out[key] = value end end print(json.encode(out))
PWM_PINS = {5, 6, 7} -- gpio12, gpio13, gpio14 INPUT_PIN = 2 -- gpio04 function startup() if abort == true then print('Start aborted!') return end print('Start.') dofile('rgb-pwm.lua') end uart.setup(0, 9600, 8, 0, 1, 1) gpio.mode(INPUT_PIN, gpio.INPUT) for i=1, 3 do gpio.mode(PWM_PINS[i], gpio.OUTPUT) gpio.write(PWM_PINS[i], gpio.LOW) end abort = false tmr.alarm(0,10000,0,startup)
local function onCreate(overlay) local menu = StackMenu:create(500, overlay, 15) local resume = menu:addButton("Resume") local exit = menu:addButton("Exit") resume.onClick = function() game.gui.pop() game.input.hideMouse() game.control.resume() end exit.onClick = function() game.gui.change("main_menu") game.control.exitGame() end end game.gui.addGui{ id = "pause", title = "Pause Menu", create = onCreate, } game.onKeyReleased(game.Keyboard.Escape, function() if game.control.currentState() == game.State.InGame then game.control.pause() game.gui.push("pause") game.input.showMouse() end end)
local themes = require('telescope.themes') local builtin = require('telescope.builtin') local extensions = require('telescope._extensions').manager local config = require('telescope.config') local command = {} local arg_value = { ['nil'] = nil,['""'] = '',['"'] = '' } local bool_type = { ['false'] = false,['true'] = true } -- convert command line string arguments to -- lua number boolean type and nil value local function convert_user_opts(user_opts) local default_opts = config.values local _switch = { ['boolean'] = function(key,val) if val == 'false' then user_opts[key] = false return end user_opts[key] = true end, ['number'] = function(key,val) user_opts[key] = tonumber(val) end, ['string'] = function(key,val) if arg_value[val] ~= nil then user_opts[key] = arg_value[val] return end if bool_type[val] ~= nil then user_opts[key] = bool_type[val] end end } local _switch_metatable = { __index = function(_,k) print(string.format('Type of %s does not match',k)) end } setmetatable(_switch,_switch_metatable) for key,val in pairs(user_opts) do if default_opts[key] ~= nil then _switch[type(default_opts[key])](key,val) else _switch['string'](key,val) end end end -- receive the viml command args -- it should be a table value like -- { -- cmd = 'find_files', -- theme = 'dropdown', -- extension_type = 'command' -- opts = { -- cwd = '***', -- } function command.run_command(args) local user_opts = args or {} if next(user_opts) == nil and not user_opts.cmd then print('[Telescope] your command miss args') return end local cmd = user_opts.cmd local opts = user_opts.opts or {} local extension_type = user_opts.extension_type or '' local theme = user_opts.theme or '' if next(opts) ~= nil then convert_user_opts(opts) end if string.len(theme) > 0 then opts = themes[theme](opts) end if string.len(extension_type) > 0 and extension_type ~= '"' then extensions[cmd][extension_type](opts) return end if builtin[cmd] then builtin[cmd](opts) return end if rawget(extensions,cmd) then extensions[cmd][cmd](opts) end end return command
local status, hyperModeAppMappings = pcall(require, 'keyboard.hyper-apps') if not status then hyperModeAppMappings = require('keyboard.hyper-apps-defaults') end for i, mapping in ipairs(hyperModeAppMappings) do hs.hotkey.bind({'shift', 'ctrl', 'alt', 'cmd'}, mapping[1], function() local appName = mapping[2] local app = hs.application.get(appName) if app then app:activate() else hs.application.launchOrFocus(appName) end end) end
--[[ Lua 5.1 Copyright (C) 1994-2006 Lua.org, PUC-Rio ]] package.path = ngx.var.app.."/?.lua;"..package.path local Http = require ("contrib/http"); local Crypt = require ("contrib/crypt"); local Sql = require ("contrib/sql"); --GenerateSessionId function GenUid (PseudoId) local Dict = "0X1P2QV4cCUdeAfgMhijEklmnS5OpZ@qrKsWt9vIw7by6zBu-DF3Hx8JaL_NRoTYG"; local DictLen = string.len (Dict); local Index = 0; local Pch = 0; local SessionId = ""; local Salt = os.time(); PseudoId = string.sub(tostring(Salt-64), -3, -1)..PseudoId..string.sub(tostring(Salt+64), -3, -1); local Len = string.len (PseudoId); for i=1, Len do Index = string.find (Dict, string.sub (PseudoId, i, i)); Index = Index + 13; if Index > DictLen then Index = Index - DictLen; end SessionId = SessionId..string.sub(Dict, Index, Index); end return (SessionId); end --Method local Method = Http.Request ("Method"); --Start if Method == "Start" then local UserName = Http.Request ("UserName"); local Password = Http.Request ("Password"); local Q = Sql.Query; Q:New ([[SELECT "UserName", "Password" FROM "Auth"."User" WHERE "UserName"=? LIMIT 1;]]); Q:SetString (UserName); local pgmoon = require ("pgmoon"); local db = pgmoon.new(Sql.Conf); assert(db:connect()); local Res, Err = db:query (Q.Stm); if table.getn(Res) == 0 then Http.Response ({Result = 0}); db:keepalive(); return; end if not Crypt.CheckPassw(Password, Res[1].Password) then Http.Response ({Result = 0}); return; end db:keepalive(); local Session = require ("resty.session").start(); --Session.cookie.lifetime = 60; Session.cookie.persistent = true; Session.data.uid = UserName; Session:save (); Http.Response ({Result = 1}); return; end --Renew if Method == "Renew" then local Session = require ("resty.session").open(); if not Session.data.uid then Http.Response ({Result = 0}); return false; end --Session.cookie.lifetime = 60; --Session:save (); Http.Response ({Result = 1}); return; end --Terminate if Method == "Terminate" then local Session = require ("resty.session").start(); Session:destroy (); Http.Response ({Result = 1}); return; end --LoginRequired function LoginRequired () local Session = require ("resty.session").open(); if not Session.data.uid then return false; end --Session.cookie.lifetime = 60; --Session:save (); return true; end --GetUser function GetUser () local Session = require ("resty.session").open(); if not Session.data.uid then return ""; end return Session.data.uid; end return {LoginRequired = LoginRequired, GetUser = GetUser}
local dataforms = require "util.dataforms"; local adhoc_util = require "util.adhoc"; local serialization = require "util.serialization"; local adhoc_new = module:require "adhoc".new; -- Dataform borrowed from Prosodys busted test for util.dataforms local form = dataforms.new({ title = "form-title", instructions = "form-instructions", { type = "hidden", name = "FORM_TYPE", value = "xmpp:prosody.im/spec/util.dataforms#1", }; { type = "fixed"; value = "Fixed field"; }, { type = "boolean", label = "boolean-label", name = "boolean-field", value = true, }, { type = "fixed", label = "fixed-label", name = "fixed-field", value = "fixed-value", }, { type = "hidden", label = "hidden-label", name = "hidden-field", value = "hidden-value", }, { type = "jid-multi", label = "jid-multi-label", name = "jid-multi-field", value = { "jid@multi/value#1", "jid@multi/value#2", }, }, { type = "jid-single", label = "jid-single-label", name = "jid-single-field", value = "jid@single/value", }, { type = "list-multi", label = "list-multi-label", name = "list-multi-field", value = { "list-multi-option-value#1", "list-multi-option-value#3", }, options = { { label = "list-multi-option-label#1", value = "list-multi-option-value#1", default = true, }, { label = "list-multi-option-label#2", value = "list-multi-option-value#2", default = false, }, { label = "list-multi-option-label#3", value = "list-multi-option-value#3", default = true, }, } }, { type = "list-single", label = "list-single-label", name = "list-single-field", value = "list-single-value", options = { "list-single-value", "list-single-value#2", "list-single-value#3", } }, { type = "text-multi", label = "text-multi-label", name = "text-multi-field", value = "text\nmulti\nvalue", }, { type = "text-private", label = "text-private-label", name = "text-private-field", value = "text-private-value", }, { type = "text-single", label = "text-single-label", name = "text-single-field", value = "text-single-value", }, }) local function handler(fields, err, data) -- luacheck: ignore 212/data return { status = "completed", info = "Data was:\n" .. serialization.serialize(err or fields), }; end module:provides("adhoc", adhoc_new("Dataforms Demo", "xmpp:zash.se/mod_adhoc_test", adhoc_util.new_simple_form(form, handler)));
return { encode = function(s) end, decode = function(s) end }
local shell = require("shell") local args, opts = shell.parse(...) local str = "" local out = {} if opts.a then opts.s = true; opts.r = true; opts.v = true; opts.p = true; opts.o = true; end if opts.s then table.insert(out, "Fuchas Kernel") end if opts.r then table.insert(out, OSDATA.VERSION) end if opts.v then table.insert(out, OSDATA.BUILD_DATE) end if opts.p then table.insert(out, _VERSION) end if opts.o then table.insert(out, "Fuchas") end print(table.concat(out, " "))
dbg=require("debugger") function arrayInit(Arr,lim) for i=1,lim do Arr[i]=0 end return Arr end --copies contents of array A1 to A2 --optional 3rd argument: lim --controls how much of A1 to copy to A2 function arrayCopy(A1,A2,lim) lim=lim or #A1 for i=1,lim do table.insert(A2,A1[i]) end end function mergeSort(list) -- dbg() firstHalf={} secondHalf={} if #list > 1 then arrayCopy(list, firstHalf, (#list)/2) mergeSort(firstHalf) --merge sort the second half secondHalfLength=#list - (#list)/2 arrayCopy(list, secondHalf, secondHalfLength) mergeSort(secondHalf) merge(list,firstHalf,secondHalf) end return end function merge(list1,list2,temp) temp=temp or {} local current1 = 1 --current index in list1 local current2 = 1 --current index in list2 local current3 = 1 --current index in temp while current1< #list1 and current2 < #list2 do if list1[current1] < list2[current2] then temp[current3] = list1[current1]; current3=current3+1 current1=current1+1 else temp[current3]=list2[current2]; current3=current3+1 current2=current2+1 end end while current1 < #list1 do temp[current3] = list1[current1] current3=current3+1 current1=current1+1 end while current2 < #list2 do temp[current3] = list2[current2]; current3=current3+1 current2=current2+1 end end function printArray(Arr) for i,v in ipairs(Arr) do io.write(v," ") end io.write("\n") end function main() local list={350, 223, 445, -45, 56, 234, -99, 498, 428, -990, 56, 78, 88, -999}; local s1 = "Before invoking the Merge Sort algorithm:\n"; local s2 = "After invoking the Merge Sort algorithm:\n"; local s3 = "Merge Sort runs in O(n lg n) time!\n"; print(s1) printArray(list); print("\n"); mergeSort(list); print(s2); printArray(list); print("\n"); print(s3); end main()
---addon namespace local _, ns = ... ns.pigments = { { itemId = 39151, name = "Alabaster Pigment", sources = { { itemId = 765, name = "Silverleaf", chance = 1.0, }, { itemId = 2447, name = "Peacebloom", chance = 1.0, }, { itemId = 2449, name = "Earthroot", chance = 1.0, }, } }, { itemId = 39334, name = "Dusky Pigment", sources = { { itemId = 2452, name = "Swiftthistle", chance = 1.0, }, { itemId = 3820, name = "Stranglekelp", chance = 1.0, }, { itemId = 785, name = "Mageroyal", chance = 1.0, }, { itemId = 2453, name = "Bruiseweed", chance = 1.0, }, { itemId = 2450, name = "Briarthorn", chance = 1.0, }, } }, { itemId = 43103, name = "Verdent Pigment", sources = { { itemId = 2452, name = "Swiftthistle", chance = 0.25, }, { itemId = 3820, name = "Stranglekelp", chance = 0.50, }, { itemId = 785, name = "Mageroyal", chance = 0.25, }, { itemId = 2453, name = "Bruiseweed", chance = 0.50, }, { itemId = 2450, name = "Briarthorn", chance = 0.25, }, } }, { itemId = 39338, name = "Golden Pigment", sources = { { itemId = 3355, name = "Wild Steelbloom", chance = 1.0, }, { itemId = 3357, name = "Liferoot", chance = 1.0, }, { itemId = 3356, name = "Kingsblood", chance = 1.0, }, { itemId = 3369, name = "Grave Moss", chance = 1.0, }, } }, { itemId = 43104, name = "Burnt Pigment", sources = { { itemId = 3355, name = "Wild Steelbloom", chance = 0.25, }, { itemId = 3357, name = "Liferoot", chance = 0.50, }, { itemId = 3356, name = "Kingsblood", chance = 0.50, }, { itemId = 3369, name = "Grave Moss", chance = 0.25, }, } }, { itemId = 39339, name = "Emerald Pigment", sources = { { itemId = 3819, name = "Wintersbite", chance = 1.0, }, { itemId = 3358, name = [[Khadgar's Whisker]], chance = 1.0, }, { itemId = 3821, name = "Goldthorn", chance = 1.0, }, { itemId = 3818, name = "Fadeleaf", chance = 1.0, }, } }, { itemId = 43105, name = "Indigo Pigment", sources = { { itemId = 3819, name = "Wintersbite", chance = 0.50, }, { itemId = 3358, name = [[Khadgar's Whisker]], chance = 0.50, }, { itemId = 3821, name = "Goldthorn", chance = 0.25, }, { itemId = 3818, name = "Fadeleaf", chance = 0.25, }, } }, { itemId = 39340, name = "Violet Pigment", sources = { { itemId = 8838, name = "Sungrass", chance = 1.0, }, { itemId = 8836, name = [[Arthas' Tears]], chance = 1.0, }, { itemId = 8831, name = "Purple Lotus", chance = 1.0, }, { itemId = 8846, name = "Gromsblood", chance = 1.0, }, { itemId = 8845, name = "Ghost Mushroom", chance = 1.0, }, { itemId = 4625, name = "Firebloom", chance = 1.0, }, { itemId = 8839, name = "Blindweed", chance = 1.0, }, } }, { itemId = 43106, name = "Ruby Pigment", sources = { { itemId = 8838, name = "Sungrass", chance = 0.25, }, { itemId = 8836, name = [[Arthas' Tears]], chance = 0.25, }, { itemId = 8831, name = "Purple Lotus", chance = 0.25, }, { itemId = 8846, name = "Gromsblood", chance = 0.50, }, { itemId = 8845, name = "Ghost Mushroom", chance = 0.50, }, { itemId = 4625, name = "Firebloom", chance = 0.25, }, { itemId = 8839, name = "Blindweed", chance = 0.50, }, } }, { itemId = 39341, name = "Silvery Pigment", sources = { { itemId = 13466, name = "Plaguebloom", chance = 1.0, }, { itemId = 13465, name = "Mountain Silversage", chance = 1.0, }, { itemId = 13467, name = "Icecap", chance = 1.0, }, { itemId = 13464, name = "Golden Sansam", chance = 1.0, }, { itemId = 13463, name = "Dreamfoil", chance = 1.0, }, } }, { itemId = 43107, name = "Sapphire Pigment", sources = { { itemId = 13466, name = "Plaguebloom", chance = 0.50, }, { itemId = 13465, name = "Mountain Silversage", chance = 0.50, }, { itemId = 13467, name = "Icecap", chance = 0.50, }, { itemId = 13464, name = "Golden Sansam", chance = 0.25, }, { itemId = 13463, name = "Dreamfoil", chance = 0.25, }, } }, { itemId = 39342, name = "Nether Pigment", sources = { { itemId = 22789, name = "Terocone", chance = 1.0, }, { itemId = 22787, name = "Ragveil", chance = 1.0, }, { itemId = 22792, name = "Nightmare Vine", chance = 1.0, }, { itemId = 22791, name = "Netherbloom", chance = 1.0, }, { itemId = 22793, name = "Mana Thistle", chance = 1.0, }, { itemId = 22785, name = "Felweed", chance = 1.0, }, { itemId = 22786, name = "Dreaming Glory", chance = 1.0, }, { itemId = 22790, name = "Ancient Lichen", chance = 1.0, }, } }, { itemId = 43108, name = "Ebon Pigment", sources = { { itemId = 22789, name = "Terocone", chance = 0.25, }, { itemId = 22787, name = "Ragveil", chance = 0.25, }, { itemId = 22792, name = "Nightmare Vine", chance = 0.50, }, { itemId = 22791, name = "Netherbloom", chance = 0.50, }, { itemId = 22793, name = "Mana Thistle", chance = 0.50, }, { itemId = 22785, name = "Felweed", chance = 0.25, }, { itemId = 22786, name = "Dreaming Glory", chance = 0.25, }, { itemId = 22790, name = "Ancient Lichen", chance = 0.50, }, } }, { itemId = 39343, name = "Azure Pigment", sources = { { itemId = 36904, name = "Tiger Lily", chance = 1.0, }, { itemId = 36907, name = [[Talandra's Rose]], chance = 1.0, }, { itemId = 36905, name = "Lichbloom", chance = 1.0, }, { itemId = 36906, name = "Icethorn", chance = 1.0, }, { itemId = 36901, name = "Goldclover", chance = 1.0, }, { itemId = 39969, name = "Fire Seed", chance = 1.0, }, { itemId = 39970, name = "Fire Leaf", chance = 1.0, }, { itemId = 37921, name = "Deadnettle", chance = 1.0, }, { itemId = 36903, name = [[Adder's Tongue]], chance = 1.0, }, } }, { itemId = 43109, name = "Icy Pigment", sources = { { itemId = 36904, name = "Tiger Lily", chance = 0.25, }, { itemId = 36907, name = [[Talandra's Rose]], chance = 0.25, }, { itemId = 36905, name = "Lichbloom", chance = 0.50, }, { itemId = 36906, name = "Icethorn", chance = 0.50, }, { itemId = 36901, name = "Goldclover", chance = 0.25, }, { itemId = 39969, name = "Fire Seed", chance = 0.25, }, { itemId = 39970, name = "Fire Leaf", chance = 0.25, }, { itemId = 37921, name = "Deadnettle", chance = 0.25, }, { itemId = 36903, name = [[Adder's Tongue]], chance = 0.50, }, } }, } ns.inks = { { itemId = 37101, name = "Ivory Ink", pigments = { { itemId = 39151, quantidy = 1.0, name = "Alabaster Pigment", dbName = "pigments", } } }, { itemId = 39469, name = "Moonglow Ink", pigments = { { itemId = 39151, quantidy = 2.0, name = "Alabaster Pigment", dbName = "pigments", } } }, { itemId = 39774, name = "Midnight Ink", pigments = { { itemId = 39334, quantidy = 2.0, name = "Dusky Pigment", dbName = "pigments", } } }, { itemId = 43115, name = [[Hunter's Ink]], pigments = { { itemId = 43103, quantidy = 2.0, name = "Verdent Pigment", dbName = "pigments", } } }, { itemId = 43116, name = [[Lion's Ink]], pigments = { { itemId = 39338, quantidy = 2.0, name = "Golden Pigment", dbName = "pigments", } } }, { itemId = 43117, name = "Dawnstar Ink", pigments = { { itemId = 43104, quantidy = 1.0, name = "Burnt Pigment", dbName = "pigments", } } }, { itemId = 43118, name = "Jadefire Ink", pigments = { { itemId = 39339, quantidy = 2.0, name = "Emerald Pigment", dbName = "pigments", } } }, { itemId = 43119, name = "Royal Ink", pigments = { { itemId = 43105, quantidy = 1.0, name = "Indigo Pigment", dbName = "pigments", } } }, { itemId = 43120, name = "Celestial Ink", pigments = { { itemId = 39340, quantidy = 2.0, name = "Violet Pigment", dbName = "pigments", } } }, { itemId = 43121, name = "Firey Ink", pigments = { { itemId = 43106, quantidy = 1.0, name = "Ruby Pigment", dbName = "pigments", } } }, { itemId = 43122, name = "Shimmering Ink", pigments = { { itemId = 39341, quantidy = 2.0, name = "Silvery Pigment", dbName = "pigments", } } }, { itemId = 43123, name = "Ink of the Sky", pigments = { { itemId = 43107, quantidy = 1.0, name = "Sapphire Pigment", dbName = "pigments", } } }, { itemId = 43124, name = "Ethereal Ink", pigments = { { itemId = 39342, quantidy = 2.0, name = "Nether Pigment", dbName = "pigments", } } }, { itemId = 43125, name = "Darkflame Ink", pigments = { { itemId = 43108, quantidy = 1.0, name = "Ebon Pigment", dbName = "pigments", } } }, { itemId = 43126, name = "Ink of the Sea", pigments = { { itemId = 39343, quantidy = 2.0, name = "Azure Pigment", dbName = "pigments", } } }, { itemId = 43127, name = "Snowfall Ink", pigments = { { itemId = 43109, quantidy = 2.0, name = "Icy Pigment", dbName = "pigments", } } }, } ns.glyphs = { { type = "Major", name = "Glyph of Mass Dispel", requiredLevel = 70, class = "PRIEST", level = 75, itemId = 42404, }, -- [1] { type = "Major", name = "Glyph of Vigor", requiredLevel = 70, class = "ROGUE", level = 75, itemId = 42971, }, -- [2] { type = "Major", name = "Glyph of Frostfire", requiredLevel = 75, class = "MAGE", level = 75, itemId = 44684, }, -- [3] { type = "Major", name = "Glyph of Fire Elemental Totem", requiredLevel = 68, class = "SHAMAN", level = 73, itemId = 41529, }, -- [4] { type = "Major", name = "Glyph of Invisibility", requiredLevel = 68, class = "MAGE", level = 73, itemId = 42748, }, -- [5] { type = "Major", name = "Glyph of Snake Trap", requiredLevel = 68, class = "HUNTER", level = 73, itemId = 42913, }, -- [6] { type = "Major", name = "Glyph of Lifebloom", requiredLevel = 64, class = "DRUID", level = 71, itemId = 40915, }, -- [7] { type = "Major", name = "Glyph of Lava", requiredLevel = 66, class = "SHAMAN", level = 71, itemId = 41524, }, -- [8] { type = "Major", name = "Glyph of Ice Lance", requiredLevel = 66, class = "MAGE", level = 71, itemId = 42745, }, -- [9] { type = "Major", name = "Glyph of Avenging Wrath", requiredLevel = 70, class = "PALADIN", level = 70, itemId = 41107, }, -- [10] { type = "Minor", name = "Glyph of Curse of Exhaustion", requiredLevel = 70, class = "WARLOCK", level = 70, itemId = 43392, }, -- [11] { type = "Major", name = "Glyph of Intervene", requiredLevel = 70, class = "WARRIOR", level = 70, itemId = 43419, }, -- [12] { type = "Minor", name = "Glyph of Blast Wave", requiredLevel = 70, class = "MAGE", level = 70, itemId = 44920, }, -- [13] { type = "Minor", name = "Glyph of Typhoon", requiredLevel = 70, class = "DRUID", level = 70, itemId = 44922, }, -- [14] { type = "Minor", name = "Glyph of Thunderstorm", requiredLevel = 70, class = "SHAMAN", level = 70, itemId = 44923, }, -- [15] { type = "Major", name = "Glyph of Focus", requiredLevel = 70, class = "DRUID", level = 70, itemId = 44928, }, -- [16] { type = "Major", name = "Glyph of Deadly Throw", requiredLevel = 64, class = "ROGUE", level = 69, itemId = 42959, }, -- [17] { type = "Minor", name = "Glyph of Souls", requiredLevel = 68, class = "WARLOCK", level = 68, itemId = 43394, }, -- [18] { type = "Minor", name = "Glyph of Command", requiredLevel = 68, class = "WARRIOR", level = 68, itemId = 49084, }, -- [19] { type = "Major", name = "Glyph of Shadow Word: Death", requiredLevel = 62, class = "PRIEST", level = 67, itemId = 42414, }, -- [20] { type = "Major", name = "Glyph of Molten Armor", requiredLevel = 62, class = "MAGE", level = 67, itemId = 42751, }, -- [21] { type = "Major", name = "Glyph of Steady Shot", requiredLevel = 62, class = "HUNTER", level = 67, itemId = 42914, }, -- [22] { type = "Minor", name = "Glyph of Shadowfiend", requiredLevel = 66, class = "PRIEST", level = 66, itemId = 43374, }, -- [23] { type = "Major", name = "Glyph of Starfall", requiredLevel = 60, class = "DRUID", level = 65, itemId = 40921, }, -- [24] { type = "Major", name = "Glyph of Arcane Blast", requiredLevel = 64, class = "MAGE", level = 64, itemId = 44955, }, -- [25] { type = "Minor", name = "Glyph of Enduring Victory", requiredLevel = 62, class = "WARRIOR", level = 62, itemId = 43400, }, -- [26] { type = "Major", name = "Glyph of Mangle", requiredLevel = 50, class = "DRUID", level = 55, itemId = 40900, }, -- [27] { type = "Major", name = [[Glyph of Avenger's Shield]], requiredLevel = 50, class = "PALADIN", level = 55, itemId = 41101, }, -- [28] { type = "Major", name = "Glyph of Elemental Mastery", requiredLevel = 50, class = "SHAMAN", level = 55, itemId = 41552, }, -- [29] { type = "Major", name = "Glyph of Circle of Healing", requiredLevel = 50, class = "PRIEST", level = 55, itemId = 42396, }, -- [30] { type = "Major", name = "Glyph of Felguard", requiredLevel = 50, class = "WARLOCK", level = 55, itemId = 42459, }, -- [31] { type = "Major", name = "Glyph of Unstable Affliction", requiredLevel = 50, class = "WARLOCK", level = 55, itemId = 42472, }, -- [32] { type = "Major", name = "Glyph of Water Elemental", requiredLevel = 50, class = "MAGE", level = 55, itemId = 42754, }, -- [33] { type = "Major", name = "Glyph of Anti-Magic Shell", requiredLevel = 55, class = "DEATH KNIGHT", level = 55, itemId = 43533, }, -- [34] { type = "Major", name = "Glyph of Heart Strike", requiredLevel = 55, class = "DEATH KNIGHT", level = 55, itemId = 43534, }, -- [35] { type = "Minor", name = "Glyph of Blood Tap", requiredLevel = 55, class = "DEATH KNIGHT", level = 55, itemId = 43535, }, -- [36] { type = "Major", name = "Glyph of Bone Shield", requiredLevel = 55, class = "DEATH KNIGHT", level = 55, itemId = 43536, }, -- [37] { type = "Major", name = "Glyph of Chains of Ice", requiredLevel = 55, class = "DEATH KNIGHT", level = 55, itemId = 43537, }, -- [38] { type = "Major", name = "Glyph of Dark Command", requiredLevel = 55, class = "DEATH KNIGHT", level = 55, itemId = 43538, }, -- [39] { type = "Minor", name = [[Glyph of Death's Embrace]], requiredLevel = "55", class = "DEATH KNIGHT", level = "55", itemId = 43539, }, -- [40] { type = "Major", name = "Glyph of Death Grip", requiredLevel = 55, class = "DEATH KNIGHT", level = 55, itemId = 43541, }, -- [41] { type = "Major", name = "Glyph of Death and Decay", requiredLevel = 55, class = "DEATH KNIGHT", level = 55, itemId = 43542, }, -- [42] { type = "Major", name = "Glyph of Frost Strike", requiredLevel = 55, class = "DEATH KNIGHT", level = 55, itemId = 43543, }, -- [43] { type = "Minor", name = "Glyph of Horn of Winter", requiredLevel = 55, class = "DEATH KNIGHT", level = 55, itemId = 43544, }, -- [44] { type = "Major", name = "Glyph of Icebound Fortitude", requiredLevel = 55, class = "DEATH KNIGHT", level = 55, itemId = 43545, }, -- [45] { type = "Major", name = "Glyph of Icy Touch", requiredLevel = 55, class = "DEATH KNIGHT", level = 55, itemId = 43546, }, -- [46] { type = "Major", name = "Glyph of Obliterate", requiredLevel = 55, class = "DEATH KNIGHT", level = 55, itemId = 43547, }, -- [47] { type = "Major", name = "Glyph of Plague Strike", requiredLevel = 55, class = "DEATH KNIGHT", level = 55, itemId = 43548, }, -- [48] { type = "Major", name = "Glyph of the Ghoul", requiredLevel = 55, class = "DEATH KNIGHT", level = 55, itemId = 43549, }, -- [49] { type = "Major", name = "Glyph of Rune Strike", requiredLevel = 55, class = "DEATH KNIGHT", level = 55, itemId = 43550, }, -- [50] { type = "Major", name = "Glyph of Scourge Strike", requiredLevel = 55, class = "DEATH KNIGHT", level = 55, itemId = 43551, }, -- [51] { type = "Major", name = "Glyph of Strangulate", requiredLevel = 55, class = "DEATH KNIGHT", level = 55, itemId = 43552, }, -- [52] { type = "Major", name = "Glyph of Unbreakable Armor", requiredLevel = 55, class = "DEATH KNIGHT", level = 55, itemId = 43553, }, -- [53] { type = "Major", name = "Glyph of Vampiric Blood", requiredLevel = 55, class = "DEATH KNIGHT", level = 55, itemId = 43554, }, -- [54] { type = "Minor", name = "Glyph of Corpse Explosion", requiredLevel = 55, class = "DEATH KNIGHT", level = 55, itemId = 43671, }, -- [55] { type = "Minor", name = "Glyph of Pestilence", requiredLevel = 55, class = "DEATH KNIGHT", level = 55, itemId = 43672, }, -- [56] { type = "Minor", name = "Glyph of Raise Dead", requiredLevel = 55, class = "DEATH KNIGHT", level = 55, itemId = 44432, }, -- [57] { type = "Major", name = "Glyph of Rune Tap", requiredLevel = 55, class = "DEATH KNIGHT", level = 55, itemId = 43825, }, -- [58] { type = "Major", name = "Glyph of Blood Strike", requiredLevel = 55, class = "DEATH KNIGHT", level = 55, itemId = 43826, }, -- [59] { type = "Major", name = "Glyph of Death Strike", requiredLevel = 55, class = "DEATH KNIGHT", level = 55, itemId = 43827, }, -- [60] { type = "Major", name = "Glyph of Holy Wrath", requiredLevel = 50, class = "PALADIN", level = 55, itemId = 43867, }, -- [61] { type = "Major", name = "Glyph of Seal of Righteousness", requiredLevel = 50, class = "PALADIN", level = 55, itemId = 43868, }, -- [62] { type = "Major", name = "Glyph of Seal of Vengeance", requiredLevel = 50, class = "PALADIN", level = 55, itemId = 43869, }, -- [63] { type = "Major", name = "Glyph of Raise Dead", requiredLevel = 55, class = "DEATH KNIGHT", level = 55, itemId = 44432, }, -- [64] { type = "Major", name = "Glyph of Eternal Water", requiredLevel = 50, class = "MAGE", level = 55, itemId = 50045, }, -- [65] { type = "Major", name = "Glyph of Devastate", requiredLevel = 50, class = "WARRIOR", level = 50, itemId = 43415, }, -- [66] { type = "Major", name = "Glyph of Hammer of Wrath", requiredLevel = 44, class = "PALADIN", level = 49, itemId = 41097, }, -- [67] { type = "Major", name = "Glyph of Death Coil", requiredLevel = 42, class = "WARLOCK", level = 47, itemId = 42457, }, -- [68] { type = "Major", name = "Glyph of Swiftmend", requiredLevel = 40, class = "DRUID", level = 45, itemId = 40906, }, -- [69] { type = "Major", name = "Glyph of Innervate", requiredLevel = 40, class = "DRUID", level = 45, itemId = 40908, }, -- [70] { type = "Major", name = "Glyph of Hurricane", requiredLevel = 40, class = "DRUID", level = 45, itemId = 40920, }, -- [71] { type = "Major", name = "Glyph of Chain Heal", requiredLevel = 40, class = "SHAMAN", level = 45, itemId = 41517, }, -- [72] { type = "Major", name = "Glyph of Mana Tide Totem", requiredLevel = 40, class = "SHAMAN", level = 45, itemId = 41538, }, -- [73] { type = "Major", name = "Glyph of Stormstrike", requiredLevel = 40, class = "SHAMAN", level = 45, itemId = 41539, }, -- [74] { type = "Major", name = "Glyph of Lightwell", requiredLevel = 40, class = "PRIEST", level = 45, itemId = 42403, }, -- [75] { type = "Major", name = "Glyph of Conflagrate", requiredLevel = 40, class = "WARLOCK", level = 45, itemId = 42454, }, -- [76] { type = "Major", name = "Glyph of Howl of Terror", requiredLevel = 40, class = "WARLOCK", level = 45, itemId = 42463, }, -- [77] { type = "Major", name = "Glyph of Arcane Power", requiredLevel = 40, class = "MAGE", level = 45, itemId = 42736, }, -- [78] { type = "Major", name = "Glyph of Bestial Wrath", requiredLevel = 40, class = "HUNTER", level = 45, itemId = 42902, }, -- [79] { type = "Major", name = "Glyph of Trueshot Aura", requiredLevel = 40, class = "HUNTER", level = 45, itemId = 42915, }, -- [80] { type = "Major", name = "Glyph of Volley", requiredLevel = 40, class = "HUNTER", level = 45, itemId = 42916, }, -- [81] { type = "Major", name = "Glyph of Wyvern Sting", requiredLevel = 40, class = "HUNTER", level = 45, itemId = 42917, }, -- [82] { type = "Major", name = "Glyph of Adrenaline Rush", requiredLevel = 40, class = "ROGUE", level = 45, itemId = 42954, }, -- [83] { type = "Major", name = "Glyph of Berserk", requiredLevel = 60, class = "DRUID", level = 45, itemId = 45601, }, -- [84] { type = "Major", name = "Glyph of Wild Growth", requiredLevel = 60, class = "DRUID", level = 45, itemId = 45602, }, -- [85] { type = "Major", name = "Glyph of Nourish", requiredLevel = 80, class = "DRUID", level = 45, itemId = 45603, }, -- [86] { type = "Major", name = "Glyph of Savage Roar", requiredLevel = 75, class = "DRUID", level = 45, itemId = 45604, }, -- [87] { type = "Major", name = "Glyph of Monsoon", requiredLevel = 50, class = "DRUID", level = 45, itemId = 45622, }, -- [88] { type = "Major", name = "Glyph of Barkskin", requiredLevel = 44, class = "DRUID", level = 45, itemId = 45623, }, -- [89] { type = "Major", name = "Glyph of Chimera Shot", requiredLevel = 60, class = "HUNTER", level = 45, itemId = 45625, }, -- [90] { type = "Major", name = "Glyph of Explosive Shot", requiredLevel = 60, class = "HUNTER", level = 45, itemId = 45731, }, -- [91] { type = "Major", name = "Glyph of Kill Shot", requiredLevel = 71, class = "HUNTER", level = 45, itemId = 45732, }, -- [92] { type = "Major", name = "Glyph of Explosive Trap", requiredLevel = 34, class = "HUNTER", level = 45, itemId = 45733, }, -- [93] { type = "Major", name = "Glyph of Scatter Shot", requiredLevel = 20, class = "HUNTER", level = 45, itemId = 45734, }, -- [94] { type = "Major", name = "Glyph of Raptor Strike", requiredLevel = 15, class = "HUNTER", level = 45, itemId = 45735, }, -- [95] { type = "Major", name = "Glyph of Deep Freeze", requiredLevel = 60, class = "MAGE", level = 45, itemId = 45736, }, -- [96] { type = "Major", name = "Glyph of Envenom", requiredLevel = 62, class = "ROGUE", level = 45, itemId = 45908, }, -- [97] { type = "Major", name = "Glyph of Seal of Wisdom", requiredLevel = 38, class = "PALADIN", level = 43, itemId = 41109, }, -- [98] { type = "Major", name = "Glyph of Frenzied Regeneration", requiredLevel = 36, class = "DRUID", level = 41, itemId = 40896, }, -- [99] { type = "Minor", name = "Glyph of the Pack", requiredLevel = 40, class = "HUNTER", level = 40, itemId = 43355, }, -- [100] { type = "Minor", name = "Glyph of Safe Fall", requiredLevel = 40, class = "ROGUE", level = 40, itemId = 43378, }, -- [101] { type = "Major", name = "Glyph of Bloodthirst", requiredLevel = 40, class = "WARRIOR", level = 40, itemId = 43412, }, -- [102] { type = "Major", name = "Glyph of Mortal Strike", requiredLevel = 40, class = "WARRIOR", level = 40, itemId = 43421, }, -- [103] { type = "Major", name = "Glyph of Blocking", requiredLevel = 40, class = "WARRIOR", level = 40, itemId = 43425, }, -- [104] { type = "Major", name = "Glyph of Mage Armor", requiredLevel = 34, class = "MAGE", level = 39, itemId = 42749, }, -- [105] { type = "Major", name = "Glyph of Chain Lightning", requiredLevel = 32, class = "SHAMAN", level = 37, itemId = 41518, }, -- [106] { type = "Major", name = "Glyph of Whirlwind", requiredLevel = 36, class = "WARRIOR", level = 36, itemId = 43432, }, -- [107] { type = "Major", name = "Glyph of Cleansing", requiredLevel = 35, class = "PALADIN", level = 35, itemId = 41104, }, -- [108] { type = "Major", name = "Glyph of Seal of Light", requiredLevel = 30, class = "PALADIN", level = 35, itemId = 41110, }, -- [109] { type = "Major", name = "Glyph of Earthliving Weapon", requiredLevel = 30, class = "SHAMAN", level = 35, itemId = 41527, }, -- [110] { type = "Major", name = "Glyph of Windfury Weapon", requiredLevel = 30, class = "SHAMAN", level = 35, itemId = 41542, }, -- [111] { type = "Major", name = "Glyph of Mind Control", requiredLevel = 30, class = "PRIEST", level = 35, itemId = 42405, }, -- [112] { type = "Major", name = "Glyph of Prayer of Healing", requiredLevel = 30, class = "PRIEST", level = 35, itemId = 42409, }, -- [113] { type = "Major", name = "Glyph of Spirit of Redemption", requiredLevel = 30, class = "PRIEST", level = 35, itemId = 42417, }, -- [114] { type = "Major", name = "Glyph of Felhunter", requiredLevel = 30, class = "WARLOCK", level = 35, itemId = 42460, }, -- [115] { type = "Major", name = "Glyph of Siphon Life", requiredLevel = 30, class = "WARLOCK", level = 35, itemId = 42469, }, -- [116] { type = "Major", name = "Glyph of Ice Block", requiredLevel = 30, class = "MAGE", level = 35, itemId = 42744, }, -- [117] { type = "Major", name = "Glyph of Mana Gem", requiredLevel = 30, class = "MAGE", level = 35, itemId = 42750, }, -- [118] { type = "Major", name = "Glyph of the Beast", requiredLevel = 30, class = "HUNTER", level = 35, itemId = 42899, }, -- [119] { type = "Major", name = "Glyph of Blade Flurry", requiredLevel = 30, class = "ROGUE", level = 35, itemId = 42957, }, -- [120] { type = "Major", name = "Glyph of Hemorrhage", requiredLevel = 30, class = "ROGUE", level = 35, itemId = 42967, }, -- [121] { type = "Major", name = "Glyph of Preparation", requiredLevel = 30, class = "ROGUE", level = 35, itemId = 42968, }, -- [122] { type = "Minor", name = "Glyph of Feign Death", requiredLevel = 30, class = "HUNTER", level = 35, itemId = 43351, }, -- [123] { type = "Minor", name = "Glyph of Levitate", requiredLevel = 34, class = "PRIEST", level = 34, itemId = 43370, }, -- [124] { type = "Major", name = "Glyph of Incinerate", requiredLevel = 28, class = "WARLOCK", level = 33, itemId = 42453, }, -- [125] { type = "Major", name = "Glyph of Frost Trap", requiredLevel = 28, class = "HUNTER", level = 33, itemId = 42906, }, -- [126] { type = "Minor", name = "Glyph of Challenging Roar", requiredLevel = 28, class = "DRUID", level = 33, itemId = 43334, }, -- [127] { type = "Major", name = "Glyph of Succubus", requiredLevel = 26, class = "WARLOCK", level = 31, itemId = 42471, }, -- [128] { type = "Major", name = "Glyph of Rapid Fire", requiredLevel = 26, class = "HUNTER", level = 31, itemId = 42911, }, -- [129] { type = "Minor", name = "Glyph of the Wise", requiredLevel = 15, class = "PALADIN", level = 30, itemId = 43369, }, -- [130] { type = "Minor", name = "Glyph of Shadow Protection", requiredLevel = 30, class = "PRIEST", level = 30, itemId = 43372, }, -- [131] { type = "Minor", name = "Glyph of Astral Recall", requiredLevel = 30, class = "SHAMAN", level = 30, itemId = 43381, }, -- [132] { type = "Minor", name = "Glyph of Renewed Life", requiredLevel = 30, class = "SHAMAN", level = 30, itemId = 43385, }, -- [133] { type = "Minor", name = "Glyph of Enslave Demon", requiredLevel = 30, class = "WARLOCK", level = 30, itemId = 43393, }, -- [134] { type = "Major", name = "Glyph of Sweeping Strikes", requiredLevel = 30, class = "WARRIOR", level = 30, itemId = 43428, }, -- [135] { type = "Major", name = "Glyph of Turn Evil", requiredLevel = 24, class = "PALADIN", level = 29, itemId = 41102, }, -- [136] { type = "Major", name = "Glyph of Rake", requiredLevel = 24, class = "DRUID", level = 28, itemId = 40903, }, -- [137] { type = "Minor", name = "Glyph of Water Walking", requiredLevel = 28, class = "SHAMAN", level = 28, itemId = 43388, }, -- [138] { type = "Major", name = "Glyph of Shred", requiredLevel = 22, class = "DRUID", level = 26, itemId = 40901, }, -- [139] { type = "Major", name = "Glyph of Rip", requiredLevel = 20, class = "DRUID", level = 25, itemId = 40902, }, -- [140] { type = "Major", name = "Glyph of Rebirth", requiredLevel = 20, class = "DRUID", level = 25, itemId = 40909, }, -- [141] { type = "Major", name = "Glyph of Starfire", requiredLevel = 20, class = "DRUID", level = 25, itemId = 40916, }, -- [142] { type = "Major", name = "Glyph of Insect Swarm", requiredLevel = 20, class = "DRUID", level = 25, itemId = 40919, }, -- [143] { type = "Major", name = "Glyph of Seal of Command", requiredLevel = 20, class = "PALADIN", level = 25, itemId = 41094, }, -- [144] { type = "Major", name = "Glyph of Crusader Strike", requiredLevel = 20, class = "PALADIN", level = 25, itemId = 41098, }, -- [145] { type = "Major", name = "Glyph of Consecration", requiredLevel = 20, class = "PALADIN", level = 25, itemId = 41099, }, -- [146] { type = "Major", name = "Glyph of Exorcism", requiredLevel = 20, class = "PALADIN", level = 25, itemId = 41103, }, -- [147] { type = "Major", name = "Glyph of Flash of Light", requiredLevel = 20, class = "PALADIN", level = 25, itemId = 41105, }, -- [148] { type = "Major", name = "Glyph of Healing Stream Totem", requiredLevel = 20, class = "SHAMAN", level = 25, itemId = 41533, }, -- [149] { type = "Major", name = "Glyph of Lesser Healing Wave", requiredLevel = 20, class = "SHAMAN", level = 25, itemId = 41535, }, -- [150] { type = "Major", name = "Glyph of Water Mastery", requiredLevel = 20, class = "SHAMAN", level = 25, itemId = 41541, }, -- [151] { type = "Major", name = "Glyph of Frost Shock", requiredLevel = 20, class = "SHAMAN", level = 25, itemId = 41547, }, -- [152] { type = "Major", name = "Glyph of Fear Ward", requiredLevel = 20, class = "PRIEST", level = 25, itemId = 42399, }, -- [153] { type = "Major", name = "Glyph of Flash Heal", requiredLevel = 20, class = "PRIEST", level = 25, itemId = 42400, }, -- [154] { type = "Major", name = "Glyph of Holy Nova", requiredLevel = 20, class = "PRIEST", level = 25, itemId = 42401, }, -- [155] { type = "Major", name = "Glyph of Shadow", requiredLevel = 20, class = "PRIEST", level = 25, itemId = 42407, }, -- [156] { type = "Major", name = "Glyph of Scourge Imprisonment", requiredLevel = 20, class = "PRIEST", level = 25, itemId = 42412, }, -- [157] { type = "Major", name = "Glyph of Shadowburn", requiredLevel = 20, class = "WARLOCK", level = 25, itemId = 42468, }, -- [158] { type = "Major", name = "Glyph of Blink", requiredLevel = 20, class = "MAGE", level = 25, itemId = 42737, }, -- [159] { type = "Major", name = "Glyph of Evocation", requiredLevel = 20, class = "MAGE", level = 25, itemId = 42738, }, -- [160] { type = "Major", name = "Glyph of Icy Veins", requiredLevel = 20, class = "MAGE", level = 25, itemId = 42746, }, -- [161] { type = "Major", name = "Glyph of Scorch", requiredLevel = 20, class = "MAGE", level = 25, itemId = 42747, }, -- [162] { type = "Major", name = "Glyph of Aimed Shot", requiredLevel = 20, class = "HUNTER", level = 25, itemId = 42897, }, -- [163] { type = "Major", name = "Glyph of Deterrence", requiredLevel = 20, class = "HUNTER", level = 25, itemId = 42903, }, -- [164] { type = "Major", name = "Glyph of Disengage", requiredLevel = 20, class = "HUNTER", level = 25, itemId = 42904, }, -- [165] { type = "Major", name = "Glyph of Freezing Trap", requiredLevel = 20, class = "HUNTER", level = 25, itemId = 42905, }, -- [166] { type = "Major", name = "Glyph of Crippling Poison", requiredLevel = 20, class = "ROGUE", level = 25, itemId = 42958, }, -- [167] { type = "Major", name = "Glyph of Ghostly Strike", requiredLevel = 20, class = "ROGUE", level = 25, itemId = 42965, }, -- [168] { type = "Major", name = "Glyph of Rupture", requiredLevel = 20, class = "ROGUE", level = 25, itemId = 42969, }, -- [169] { type = "Minor", name = "Glyph of Unburdened Rebirth", requiredLevel = 20, class = "DRUID", level = 25, itemId = 43331, }, -- [170] { type = "Major", name = "Glyph of Execution", requiredLevel = 24, class = "WARRIOR", level = 24, itemId = 43416, }, -- [171] { type = "Major", name = "Glyph of Dispel Magic", requiredLevel = 18, class = "PRIEST", level = 23, itemId = 42397, }, -- [172] { type = "Major", name = "Glyph of Searing Pain", requiredLevel = 18, class = "WARLOCK", level = 23, itemId = 42466, }, -- [173] { type = "Major", name = "Glyph of Soulstone", requiredLevel = 18, class = "WARLOCK", level = 23, itemId = 42470, }, -- [174] { type = "Major", name = "Glyph of Remove Curse", requiredLevel = 18, class = "MAGE", level = 23, itemId = 42753, }, -- [175] { type = "Major", name = "Glyph of Multi-Shot", requiredLevel = 18, class = "HUNTER", level = 23, itemId = 42910, }, -- [176] { type = "Major", name = "Glyph of Ambush", requiredLevel = 18, class = "ROGUE", level = 23, itemId = 42955, }, -- [177] { type = "Minor", name = "Glyph of Water Breathing", requiredLevel = 22, class = "SHAMAN", level = 22, itemId = 43344, }, -- [178] { type = "Minor", name = "Glyph of Frost Ward", requiredLevel = 22, class = "MAGE", level = 22, itemId = 43360, }, -- [179] { type = "Minor", name = "Glyph of Distract", requiredLevel = 22, class = "ROGUE", level = 22, itemId = 43376, }, -- [180] { type = "Minor", name = "Glyph of Vanish", requiredLevel = 22, class = "ROGUE", level = 22, itemId = 43380, }, -- [181] { type = "Minor", name = "Glyph of Kilrogg", requiredLevel = 22, class = "WARLOCK", level = 22, itemId = 43391, }, -- [182] { type = "Major", name = "Glyph of Immolation Trap", requiredLevel = 16, class = "HUNTER", level = 21, itemId = 42908, }, -- [183] { type = "Major", name = "Glyph of Feint", requiredLevel = 16, class = "ROGUE", level = 21, itemId = 42963, }, -- [184] { type = "Minor", name = "Glyph of Aquatic Form", requiredLevel = 16, class = "DRUID", level = 21, itemId = 43316, }, -- [185] { type = "Minor", name = "Glyph of Dash", requiredLevel = 16, class = "DRUID", level = 21, itemId = 43674, }, -- [186] { type = "Major", name = "Glyph of Mind Flay", requiredLevel = 20, class = "PRIEST", level = 20, itemId = 42415, }, -- [187] { type = "Major", name = "Glyph of Aspect of the Viper", requiredLevel = 20, class = "HUNTER", level = 20, itemId = 42901, }, -- [188] { type = "Minor", name = "Glyph of Fire Ward", requiredLevel = 20, class = "MAGE", level = 20, itemId = 43357, }, -- [189] { type = "Minor", name = "Glyph of Blessing of Kings", requiredLevel = 20, class = "PALADIN", level = 20, itemId = 43365, }, -- [190] { type = "Minor", name = "Glyph of Sense Undead", requiredLevel = 20, class = "PALADIN", level = 20, itemId = 43368, }, -- [191] { type = "Minor", name = "Glyph of Shackle Undead", requiredLevel = 20, class = "PRIEST", level = 20, itemId = 43373, }, -- [192] { type = "Minor", name = "Deprecated Glyph of the Black Wolf", requiredLevel = 20, class = "SHAMAN", level = 20, itemId = 43384, }, -- [193] { type = "Minor", name = "Glyph of Water Shield", requiredLevel = 20, class = "SHAMAN", level = 20, itemId = 43386, }, -- [194] { type = "Major", name = "Glyph of Cleaving", requiredLevel = 20, class = "WARRIOR", level = 20, itemId = 43414, }, -- [195] { type = "Major", name = "Glyph of Last Stand", requiredLevel = 20, class = "WARRIOR", level = 20, itemId = 43426, }, -- [196] { type = "Major", name = "Glyph of Survival Instincts", requiredLevel = 20, class = "DRUID", level = 20, itemId = 46372, }, -- [197] { type = "Major", name = "Glyph of Claw", requiredLevel = 20, class = "DRUID", level = 20, itemId = 48720, }, -- [198] { type = "Major", name = "Glyph of Righteous Defense", requiredLevel = 15, class = "PALADIN", level = 19, itemId = 41100, }, -- [199] { type = "Major", name = "Glyph of Psychic Scream", requiredLevel = 15, class = "PRIEST", level = 19, itemId = 42410, }, -- [200] { type = "Major", name = "Glyph of Arcane Explosion", requiredLevel = 15, class = "MAGE", level = 19, itemId = 42734, }, -- [201] { type = "Major", name = "Glyph of Expose Armor", requiredLevel = 15, class = "ROGUE", level = 19, itemId = 42962, }, -- [202] { type = "Major", name = "Glyph of Garrote", requiredLevel = 15, class = "ROGUE", level = 19, itemId = 42964, }, -- [203] { type = "Major", name = "Glyph of Regrowth", requiredLevel = 15, class = "DRUID", level = 18, itemId = 40912, }, -- [204] { type = "Major", name = "Glyph of Spiritual Attunement", requiredLevel = 18, class = "PALADIN", level = 18, itemId = 41096, }, -- [205] { type = "Major", name = "Glyph of Fire Nova", requiredLevel = 15, class = "SHAMAN", level = 18, itemId = 41530, }, -- [206] { type = "Major", name = "Glyph of Inner Fire", requiredLevel = 15, class = "PRIEST", level = 17, itemId = 42402, }, -- [207] { type = "Major", name = "Glyph of Health Funnel", requiredLevel = 15, class = "WARLOCK", level = 17, itemId = 42461, }, -- [208] { type = "Minor", name = "Glyph of Pick Lock", requiredLevel = 16, class = "ROGUE", level = 16, itemId = 43377, }, -- [209] { type = "Minor", name = "Glyph of Mocking Blow", requiredLevel = 16, class = "WARRIOR", level = 16, itemId = 43398, }, -- [210] { type = "Major", name = "Glyph of Barbaric Insults", requiredLevel = 16, class = "WARRIOR", level = 16, itemId = 43420, }, -- [211] { type = "Minor", name = "Glyph of Ghost Wolf", requiredLevel = 16, class = "SHAMAN", level = 16, itemId = 43725, }, -- [212] { type = "Major", name = "Glyph of Growl", requiredLevel = 15, class = "DRUID", level = 15, itemId = 40899, }, -- [213] { type = "Major", name = "Glyph of Moonfire", requiredLevel = 15, class = "DRUID", level = 15, itemId = 40923, }, -- [214] { type = "Major", name = "Glyph of Divinity", requiredLevel = 15, class = "PALADIN", level = 15, itemId = 41108, }, -- [215] { type = "Major", name = "Glyph of Flame Shock", requiredLevel = 15, class = "SHAMAN", level = 15, itemId = 41531, }, -- [216] { type = "Major", name = "Glyph of Flametongue Weapon", requiredLevel = 15, class = "SHAMAN", level = 15, itemId = 41532, }, -- [217] { type = "Major", name = "Glyph of Lava Lash", requiredLevel = 15, class = "SHAMAN", level = 15, itemId = 41540, }, -- [218] { type = "Major", name = "Glyph of Shadow Word: Pain", requiredLevel = 15, class = "PRIEST", level = 15, itemId = 42406, }, -- [219] { type = "Major", name = "Glyph of Corruption", requiredLevel = 15, class = "WARLOCK", level = 15, itemId = 42455, }, -- [220] { type = "Major", name = "Glyph of Healthstone", requiredLevel = 15, class = "WARLOCK", level = 15, itemId = 42462, }, -- [221] { type = "Major", name = "Glyph of Voidwalker", requiredLevel = 15, class = "WARLOCK", level = 15, itemId = 42473, }, -- [222] { type = "Major", name = "Glyph of Frost Nova", requiredLevel = 15, class = "MAGE", level = 15, itemId = 42741, }, -- [223] { type = "Major", name = "Glyph of Ice Armor", requiredLevel = 15, class = "MAGE", level = 15, itemId = 42743, }, -- [224] { type = "Major", name = "Glyph of the Hawk", requiredLevel = 15, class = "HUNTER", level = 15, itemId = 42909, }, -- [225] { type = "Major", name = "Glyph of Sap", requiredLevel = 15, class = "ROGUE", level = 15, itemId = 42970, }, -- [226] { type = "Major", name = "Glyph of Slice and Dice", requiredLevel = 15, class = "ROGUE", level = 15, itemId = 42973, }, -- [227] { type = "Major", name = "Glyph of Sprint", requiredLevel = 15, class = "ROGUE", level = 15, itemId = 42974, }, -- [228] { type = "Minor", name = "Glyph of Revive Pet", requiredLevel = 15, class = "HUNTER", level = 15, itemId = 43338, }, -- [229] { type = "Major", name = "Glyph of Victory Rush", requiredLevel = 15, class = "WARRIOR", level = 15, itemId = 43431, }, -- [230] { type = "Major", name = "Glyph of Quick Decay", requiredLevel = 15, class = "WARLOCK", level = 15, itemId = 50077, }, -- [231] { type = "Minor", name = "Glyph of Possessed Strength", requiredLevel = 15, class = "HUNTER", level = 14, itemId = 43354, }, -- [232] { type = "Minor", name = "Glyph of Scare Beast", requiredLevel = 15, class = "HUNTER", level = 14, itemId = 43356, }, -- [233] { type = "Minor", name = "Glyph of Blessing of Wisdom", requiredLevel = 15, class = "PALADIN", level = 14, itemId = 43366, }, -- [234] { type = "Major", name = "Glyph of Revenge", requiredLevel = 15, class = "WARRIOR", level = 14, itemId = 43424, }, -- [235] { type = "Major", name = "Glyph of Hammer of Justice", requiredLevel = 15, class = "PALADIN", level = 13, itemId = 41095, }, -- [236] { type = "Major", name = "Glyph of Lightning Shield", requiredLevel = 15, class = "SHAMAN", level = 13, itemId = 41537, }, -- [237] { type = "Major", name = "Glyph of Fade", requiredLevel = 15, class = "PRIEST", level = 13, itemId = 42398, }, -- [238] { type = "Major", name = "Glyph of Renew", requiredLevel = 15, class = "PRIEST", level = 13, itemId = 42411, }, -- [239] { type = "Major", name = "Glyph of Curse of Agony", requiredLevel = 15, class = "WARLOCK", level = 13, itemId = 42456, }, -- [240] { type = "Major", name = "Glyph of Fear", requiredLevel = 15, class = "WARLOCK", level = 13, itemId = 42458, }, -- [241] { type = "Major", name = "Glyph of Arcane Missiles", requiredLevel = 15, class = "MAGE", level = 13, itemId = 42735, }, -- [242] { type = "Major", name = "Glyph of Polymorph", requiredLevel = 15, class = "MAGE", level = 13, itemId = 42752, }, -- [243] { type = "Major", name = "Glyph of Evasion", requiredLevel = 15, class = "ROGUE", level = 13, itemId = 42960, }, -- [244] { type = "Minor", name = "Glyph of Mend Pet", requiredLevel = 15, class = "HUNTER", level = 12, itemId = 43350, }, -- [245] { type = "Minor", name = "Glyph of Slow Fall", requiredLevel = 15, class = "MAGE", level = 12, itemId = 43364, }, -- [246] { type = "Major", name = "Glyph of Living Bomb", requiredLevel = 60, class = "MAGE", level = 45, itemId = 45737, }, -- [247] { type = "Major", name = "Glyph of Arcane Barrage", requiredLevel = 60, class = "MAGE", level = 45, itemId = 45738, }, -- [248] { type = "Major", name = "Glyph of Mirror Image", requiredLevel = 80, class = "MAGE", level = 45, itemId = 45739, }, -- [249] { type = "Major", name = "Glyph of Ice Barrier", requiredLevel = 46, class = "MAGE", level = 45, itemId = 45740, }, -- [250] { type = "Major", name = "Glyph of Beacon of Light", requiredLevel = 60, class = "PALADIN", level = 45, itemId = 45741, }, -- [251] { type = "Major", name = "Glyph of Hammer of the Righteous", requiredLevel = 60, class = "PALADIN", level = 45, itemId = 45742, }, -- [252] { type = "Major", name = "Glyph of Divine Storm", requiredLevel = 60, class = "PALADIN", level = 45, itemId = 45743, }, -- [253] { type = "Major", name = "Glyph of Shield of Righteousness", requiredLevel = 75, class = "PALADIN", level = 45, itemId = 45744, }, -- [254] { type = "Major", name = "Glyph of Divine Plea", requiredLevel = 71, class = "PALADIN", level = 45, itemId = 45745, }, -- [255] { type = "Major", name = "Glyph of Holy Shock", requiredLevel = 40, class = "PALADIN", level = 45, itemId = 45746, }, -- [256] { type = "Major", name = "Glyph of Salvation", requiredLevel = 26, class = "PALADIN", level = 45, itemId = 45747, }, -- [257] { type = "Major", name = "Glyph of Dispersion", requiredLevel = 60, class = "PRIEST", level = 45, itemId = 45753, }, -- [258] { type = "Major", name = "Glyph of Guardian Spirit", requiredLevel = 60, class = "PRIEST", level = 45, itemId = 45755, }, -- [259] { type = "Major", name = "Glyph of Penance", requiredLevel = 60, class = "PRIEST", level = 45, itemId = 45756, }, -- [260] { type = "Major", name = "Glyph of Mind Sear", requiredLevel = 75, class = "PRIEST", level = 45, itemId = 45757, }, -- [261] { type = "Major", name = "Glyph of Hymn of Hope", requiredLevel = 60, class = "PRIEST", level = 45, itemId = 45758, }, -- [262] { type = "Major", name = "Glyph of Pain Suppression", requiredLevel = 50, class = "PRIEST", level = 45, itemId = 45760, }, -- [263] { type = "Major", name = "Glyph of Hunger for Blood", requiredLevel = 60, class = "ROGUE", level = 45, itemId = 45761, }, -- [264] { type = "Major", name = "Glyph of Killing Spree", requiredLevel = 60, class = "ROGUE", level = 45, itemId = 45762, }, -- [265] { type = "Major", name = "Glyph of Shadow Dance", requiredLevel = 60, class = "ROGUE", level = 45, itemId = 45764, }, -- [266] { type = "Major", name = "Glyph of Fan of Knives", requiredLevel = 80, class = "ROGUE", level = 45, itemId = 45766, }, -- [267] { type = "Major", name = "Glyph of Tricks of the Trade", requiredLevel = 75, class = "ROGUE", level = 45, itemId = 45767, }, -- [268] { type = "Major", name = "Glyph of Mutilate", requiredLevel = 50, class = "ROGUE", level = 45, itemId = 45768, }, -- [269] { type = "Major", name = "Glyph of Cloak of Shadows", requiredLevel = 66, class = "ROGUE", level = 45, itemId = 45769, }, -- [270] { type = "Major", name = "Glyph of Thunder", requiredLevel = 60, class = "SHAMAN", level = 45, itemId = 45770, }, -- [271] { type = "Major", name = "Glyph of Feral Spirit", requiredLevel = 60, class = "SHAMAN", level = 45, itemId = 45771, }, -- [272] { type = "Major", name = "Glyph of Riptide", requiredLevel = 60, class = "SHAMAN", level = 45, itemId = 45772, }, -- [273] { type = "Major", name = "Glyph of Earth Shield", requiredLevel = 50, class = "SHAMAN", level = 45, itemId = 45775, }, -- [274] { type = "Major", name = "Glyph of Totem of Wrath", requiredLevel = 50, class = "SHAMAN", level = 45, itemId = 45776, }, -- [275] { type = "Major", name = "Glyph of Hex", requiredLevel = 80, class = "SHAMAN", level = 45, itemId = 45777, }, -- [276] { type = "Major", name = "Glyph of Stoneclaw Totem", requiredLevel = 15, class = "SHAMAN", level = 45, itemId = 45778, }, -- [277] { type = "Major", name = "Glyph of Haunt", requiredLevel = 60, class = "WARLOCK", level = 45, itemId = 45779, }, -- [278] { type = "Major", name = "Glyph of Metamorphosis", requiredLevel = 60, class = "WARLOCK", level = 45, itemId = 45780, }, -- [279] { type = "Major", name = "Glyph of Chaos Bolt", requiredLevel = 60, class = "WARLOCK", level = 45, itemId = 45781, }, -- [280] { type = "Major", name = "Glyph of Demonic Circle", requiredLevel = 80, class = "WARLOCK", level = 45, itemId = 45782, }, -- [281] { type = "Major", name = "Glyph of Shadowflame", requiredLevel = 75, class = "WARLOCK", level = 45, itemId = 45783, }, -- [282] { type = "Major", name = "Glyph of Life Tap", requiredLevel = 15, class = "WARLOCK", level = 45, itemId = 45785, }, -- [283] { type = "Major", name = "Glyph of Soul Link", requiredLevel = 20, class = "WARLOCK", level = 45, itemId = 45789, }, -- [284] { type = "Major", name = "Glyph of Bladestorm", requiredLevel = 60, class = "WARRIOR", level = 45, itemId = 45790, }, -- [285] { type = "Major", name = "Glyph of Shockwave", requiredLevel = 60, class = "WARRIOR", level = 45, itemId = 45792, }, -- [286] { type = "Major", name = "Glyph of Vigilance", requiredLevel = 40, class = "WARRIOR", level = 45, itemId = 45793, }, -- [287] { type = "Major", name = "Glyph of Enraged Regeneration", requiredLevel = 75, class = "WARRIOR", level = 45, itemId = 45794, }, -- [288] { type = "Major", name = "Glyph of Spell Reflection", requiredLevel = 64, class = "WARRIOR", level = 45, itemId = 45795, }, -- [289] { type = "Major", name = "Glyph of Shield Wall", requiredLevel = 28, class = "WARRIOR", level = 45, itemId = 45797, }, -- [290] { type = "Major", name = "Glyph of Dancing Rune Weapon", requiredLevel = 60, class = "DEATH KNIGHT", level = 45, itemId = 45799, }, -- [291] { type = "Major", name = "Glyph of Hungering Cold", requiredLevel = 60, class = "DEATH KNIGHT", level = 45, itemId = 45800, }, -- [292] { type = "Major", name = "Glyph of Unholy Blight", requiredLevel = 60, class = "DEATH KNIGHT", level = 45, itemId = 45803, }, -- [293] { type = "Major", name = "Glyph of Dark Death", requiredLevel = 55, class = "DEATH KNIGHT", level = 45, itemId = 45804, }, -- [294] { type = "Major", name = "Glyph of Disease", requiredLevel = 55, class = "DEATH KNIGHT", level = 45, itemId = 45805, }, -- [295] { type = "Major", name = "Glyph of Howling Blast", requiredLevel = 60, class = "DEATH KNIGHT", level = 45, itemId = 45806, }, -- [296] } ns.minorResearch = { { itemId = 43316, name = [[Glyph of Aquatic Form]], requiredLevel = 100, }, { itemId = 43339, name = [[Glyph of Arcane Intellect]], requiredLevel = 75, }, { itemId = 43381, name = [[Glyph of Astral Recall]], requiredLevel = 150, }, { itemId = 43395, name = [[Glyph of Battle]], requiredLevel = 75, }, { itemId = 44920, name = [[Glyph of Blast Wave]], requiredLevel = 350, }, { itemId = 43365, name = [[Glyph of Blessing of Kings]], requiredLevel = 100, }, { itemId = 43340, name = [[Glyph of Blessing of Might]], requiredLevel = 75, }, { itemId = 43366, name = [[Glyph of Blessing of Wisdom]], requiredLevel = 75, }, { itemId = 43535, name = [[Glyph of Blood Tap]], requiredLevel = 325, }, { itemId = 43396, name = [[Glyph of Bloodrage]], requiredLevel = 75, }, { itemId = 43379, name = [[Glyph of Blurred Speed]], requiredLevel = 75, }, { itemId = 43334, name = [[Glyph of Challenging Roar]], requiredLevel = 150, }, { itemId = 43397, name = [[Glyph of Charge]], requiredLevel = 75, }, { itemId = 49084, name = [[Glyph of Command]], requiredLevel = 350, }, { itemId = 43671, name = [[Glyph of Corpse Explosion]], requiredLevel = 300, }, { itemId = 43392, name = [[Glyph of Curse of Exhaustion]], requiredLevel = 150, }, { itemId = 43674, name = [[Glyph of Dash]], requiredLevel = 150, }, { itemId = 43539, name = [[Glyph of Death's Embrace]], requiredLevel = 300, }, { itemId = 43376, name = [[Glyph of Distract]], requiredLevel = 125, }, { itemId = 43390, name = [[Glyph of Drain Soul]], requiredLevel = 75, }, { itemId = 43400, name = [[Glyph of Enduring Victory]], requiredLevel = 325, }, { itemId = 43393, name = [[Glyph of Enslave Demon]], requiredLevel = 150, }, { itemId = 43342, name = [[Glyph of Fading]], requiredLevel = 75, }, { itemId = 43351, name = [[Glyph of Feign Death]], requiredLevel = 150, }, { itemId = 43357, name = [[Glyph of Fire Ward]], requiredLevel = 100, }, { itemId = 43371, name = [[Glyph of Fortitude]], requiredLevel = 75, }, { itemId = 43359, name = [[Glyph of Frost Armor]], requiredLevel = 75, }, { itemId = 43360, name = [[Glyph of Frost Ward]], requiredLevel = 125, }, { itemId = 43725, name = [[Glyph of Ghost Wolf]], requiredLevel = 100, }, { itemId = 43544, name = [[Glyph of Horn of Winter]], requiredLevel = 325, }, { itemId = 43391, name = [[Glyph of Kilrogg]], requiredLevel = 125, }, { itemId = 43367, name = [[Glyph of Lay on Hands]], requiredLevel = 75, }, { itemId = 43370, name = [[Glyph of Levitate]], requiredLevel = 175, }, { itemId = 43350, name = [[Glyph of Mend Pet]], requiredLevel = 75, }, { itemId = 43398, name = [[Glyph of Mocking Blow]], requiredLevel = 100, }, { itemId = 43672, name = [[Glyph of Pestilence]], requiredLevel = 300, }, { itemId = 43377, name = [[Glyph of Pick Lock]], requiredLevel = 100, }, { itemId = 43343, name = [[Glyph of Pick Pocket]], requiredLevel = 75, }, { itemId = 43354, name = [[Glyph of Possessed Strength]], requiredLevel = 75, }, { itemId = 43673, name = [[Glyph of Raise Dead]], requiredLevel = 300, }, { itemId = 43385, name = [[Glyph of Renewed Life]], requiredLevel = 150, }, { itemId = 43338, name = [[Glyph of Revive Pet]], requiredLevel = 75, }, { itemId = 43378, name = [[Glyph of Safe Fall]], requiredLevel = 200, }, { itemId = 43356, name = [[Glyph of Scare Beast]], requiredLevel = 75, }, { itemId = 43368, name = [[Glyph of Sense Undead]], requiredLevel = 100, }, { itemId = 43373, name = [[Glyph of Shackle Undead]], requiredLevel = 100, }, { itemId = 43372, name = [[Glyph of Shadow Protection]], requiredLevel = 150, }, { itemId = 43374, name = [[Glyph of Shadowfiend]], requiredLevel = 385, }, { itemId = 43364, name = [[Glyph of Slow Fall]], requiredLevel = 75, }, { itemId = 43394, name = [[Glyph of Souls]], requiredLevel = 385, }, { itemId = 43355, name = [[Glyph of the Pack]], requiredLevel = 200, }, { itemId = 43361, name = [[Glyph of the Penguin]], requiredLevel = 75, }, { itemId = 43335, name = [[Glyph of the Wild]], requiredLevel = 75, }, { itemId = 43369, name = [[Glyph of the Wise]], requiredLevel = 150, }, { itemId = 43332, name = [[Glyph of Thorns]], requiredLevel = 75, }, { itemId = 43399, name = [[Glyph of Thunder Clap]], requiredLevel = 75, }, { itemId = 44923, name = [[Glyph of Thunderstorm]], requiredLevel = 350, }, { itemId = 44922, name = [[Glyph of Typhoon]], requiredLevel = 350, }, { itemId = 43331, name = [[Glyph of Unburdened Rebirth]], requiredLevel = 100, }, { itemId = 43389, name = [[Glyph of Unending Breath]], requiredLevel = 100, }, { itemId = 43380, name = [[Glyph of Vanish]], requiredLevel = 125, }, { itemId = 43344, name = [[Glyph of Water Breathing]], requiredLevel = 125, }, { itemId = 43386, name = [[Glyph of Water Shield]], requiredLevel = 100, }, { itemId = 43388, name = [[Glyph of Water Walking]], requiredLevel = 150, }, } ns.northrendResearch = { { itemId = 42954, name = [[Glyph of Adrenaline Rush]], minLevel = 385, }, { itemId = 43533, name = [[Glyph of Anti-Magic Shell]], minLevel = 385, }, { itemId = 42901, name = [[Glyph of Aspect of the Viper]], minLevel = 385, }, { itemId = 41101, name = [[Glyph of Avenger's Shield]], minLevel = 385, }, { itemId = 41107, name = [[Glyph of Avenging Wrath]], minLevel = 385, }, { itemId = 42902, name = [[Glyph of Bestial Wrath]], minLevel = 385, }, { itemId = 42957, name = [[Glyph of Blade Flurry]], minLevel = 385, }, { itemId = 43425, name = [[Glyph of Blocking]], minLevel = 385, }, { itemId = 43412, name = [[Glyph of Bloodthirst]], minLevel = 385, }, { itemId = 41517, name = [[Glyph of Chain Heal]], minLevel = 385, }, { itemId = 41518, name = [[Glyph of Chain Lightning]], minLevel = 385, }, { itemId = 43537, name = [[Glyph of Chains of Ice]], minLevel = 385, }, { itemId = 42396, name = [[Glyph of Circle of Healing]], minLevel = 385, }, { itemId = 42454, name = [[Glyph of Conflagrate]], minLevel = 385, }, { itemId = 42958, name = [[Glyph of Crippling Poison]], minLevel = 385, }, { itemId = 42456, name = [[Glyph of Curse of Agony]], minLevel = 385, }, { itemId = 43538, name = [[Glyph of Dark Command]], minLevel = 385, }, { itemId = 42959, name = [[Glyph of Deadly Throw]], minLevel = 385, }, { itemId = 43542, name = [[Glyph of Death and Decay]], minLevel = 385, }, { itemId = 42457, name = [[Glyph of Death Coil]], minLevel = 385, }, { itemId = 43415, name = [[Glyph of Devastate]], minLevel = 385, }, { itemId = 41552, name = [[Glyph of Elemental Mastery]], minLevel = 385, }, { itemId = 42459, name = [[Glyph of Felguard]], minLevel = 385, }, { itemId = 42460, name = [[Glyph of Felhunter]], minLevel = 385, }, { itemId = 42740, name = [[Glyph of Fire Blast]], minLevel = 385, }, { itemId = 41529, name = [[Glyph of Fire Elemental Totem]], minLevel = 385, }, { itemId = 42739, name = [[Glyph of Fireball]], minLevel = 385, }, { itemId = 42742, name = [[Glyph of Frostbolt]], minLevel = 385, }, { itemId = 44684, name = [[Glyph of Frostfire]], minLevel = 385, }, { itemId = 42965, name = [[Glyph of Ghostly Strike]], minLevel = 385, }, { itemId = 40899, name = [[Glyph of Growl]], minLevel = 385, }, { itemId = 41097, name = [[Glyph of Hammer of Wrath]], minLevel = 385, }, { itemId = 41534, name = [[Glyph of Healing Wave]], minLevel = 385, }, { itemId = 43534, name = [[Glyph of Heart Strike]], minLevel = 385, }, { itemId = 42967, name = [[Glyph of Hemorrhage]], minLevel = 385, }, { itemId = 43867, name = [[Glyph of Holy Wrath]], minLevel = 385, }, { itemId = 42463, name = [[Glyph of Howl of Terror]], minLevel = 385, }, { itemId = 40920, name = [[Glyph of Hurricane]], minLevel = 385, }, { itemId = 42745, name = [[Glyph of Ice Lance]], minLevel = 385, }, { itemId = 43545, name = [[Glyph of Icebound Fortitude]], minLevel = 385, }, { itemId = 42464, name = [[Glyph of Immolate]], minLevel = 385, }, { itemId = 40908, name = [[Glyph of Innervate]], minLevel = 385, }, { itemId = 43419, name = [[Glyph of Intervene]], minLevel = 385, }, { itemId = 42748, name = [[Glyph of Invisibility]], minLevel = 385, }, { itemId = 43426, name = [[Glyph of Last Stand]], minLevel = 385, }, { itemId = 41524, name = [[Glyph of Lava]], minLevel = 385, }, { itemId = 40915, name = [[Glyph of Lifebloom]], minLevel = 385, }, { itemId = 42403, name = [[Glyph of Lightwell]], minLevel = 385, }, { itemId = 41538, name = [[Glyph of Mana Tide Totem]], minLevel = 385, }, { itemId = 40900, name = [[Glyph of Mangle]], minLevel = 385, }, { itemId = 42404, name = [[Glyph of Mass Dispel]], minLevel = 385, }, { itemId = 42405, name = [[Glyph of Mind Control]], minLevel = 385, }, { itemId = 42751, name = [[Glyph of Molten Armor]], minLevel = 385, }, { itemId = 43421, name = [[Glyph of Mortal Strike]], minLevel = 385, }, { itemId = 43547, name = [[Glyph of Obliterate]], minLevel = 385, }, { itemId = 42752, name = [[Glyph of Polymorph]], minLevel = 385, }, { itemId = 42409, name = [[Glyph of Prayer of Healing]], minLevel = 385, }, { itemId = 42968, name = [[Glyph of Preparation]], minLevel = 385, }, { itemId = 40912, name = [[Glyph of Regrowth]], minLevel = 385, }, { itemId = 42753, name = [[Glyph of Remove Curse]], minLevel = 385, }, { itemId = 43430, name = [[Glyph of Resonating Power]], minLevel = 385, }, { itemId = 43550, name = [[Glyph of Rune Strike]], minLevel = 385, }, { itemId = 42969, name = [[Glyph of Rupture]], minLevel = 385, }, { itemId = 42412, name = [[Glyph of Scourge Imprisonment]], minLevel = 385, }, { itemId = 41110, name = [[Glyph of Seal of Light]], minLevel = 385, }, { itemId = 43868, name = [[Glyph of Seal of Righteousness]], minLevel = 385, }, { itemId = 43869, name = [[Glyph of Seal of Vengeance]], minLevel = 385, }, { itemId = 41109, name = [[Glyph of Seal of Wisdom]], minLevel = 385, }, { itemId = 42407, name = [[Glyph of Shadow]], minLevel = 385, }, { itemId = 42414, name = [[Glyph of Shadow Word: Death]], minLevel = 385, }, { itemId = 43374, name = [[Glyph of Shadowfiend]], minLevel = 385, }, { itemId = 41526, name = [[Glyph of Shocking]], minLevel = 385, }, { itemId = 42469, name = [[Glyph of Siphon Life]], minLevel = 385, }, { itemId = 42913, name = [[Glyph of Snake Trap]], minLevel = 385, }, { itemId = 43394, name = [[Glyph of Souls]], minLevel = 385, }, { itemId = 42417, name = [[Glyph of Spirit of Redemption]], minLevel = 385, }, { itemId = 40921, name = [[Glyph of Starfall]], minLevel = 385, }, { itemId = 42914, name = [[Glyph of Steady Shot]], minLevel = 385, }, { itemId = 41539, name = [[Glyph of Stormstrike]], minLevel = 385, }, { itemId = 43552, name = [[Glyph of Strangulate]], minLevel = 385, }, { itemId = 40906, name = [[Glyph of Swiftmend]], minLevel = 385, }, { itemId = 43429, name = [[Glyph of Taunt]], minLevel = 385, }, { itemId = 42899, name = [[Glyph of the Beast]], minLevel = 385, }, { itemId = 42909, name = [[Glyph of the Hawk]], minLevel = 385, }, { itemId = 42915, name = [[Glyph of Trueshot Aura]], minLevel = 385, }, { itemId = 41102, name = [[Glyph of Turn Evil]], minLevel = 385, }, { itemId = 42472, name = [[Glyph of Unstable Affliction]], minLevel = 385, }, { itemId = 43431, name = [[Glyph of Victory Rush]], minLevel = 385, }, { itemId = 42971, name = [[Glyph of Vigor]], minLevel = 385, }, { itemId = 42916, name = [[Glyph of Volley]], minLevel = 385, }, { itemId = 42754, name = [[Glyph of Water Elemental]], minLevel = 385, }, { itemId = 42917, name = [[Glyph of Wyvern Sting]], minLevel = 385, }, } ns.bisGlyphs = { } ns.darkmoonCards = { { itemId = 44318, name = "Darkmoon Card of the North", reagents = { { itemId = 39502, quantidy = 1.0, }, { itemId = 43127, quantidy = 6.0, }, { itemId = 35625, quantidy = 3.0, }, { itemId = 43126, quantidy = 3.0, } } } } ns.materials = { { itemId = 39151, name = "Alabaster Pigment", quantidy = 62, }, { itemId = 39334, name = "Dusky Pigment", quantidy = 40, }, { itemId = 39338, name = "Golden Pigment", quantidy = 120, }, { itemId = 39339, name = "Emerald Pigment", quantidy = 120, }, { itemId = 43105, name = "Indigo Pigment", quantidy = 20, }, { itemId = 39340, name = "Violet Pigment", quantidy = 100, }, { itemId = 43106, name = "Ruby Pigment", quantidy = 12, }, { itemId = 39341, name = "Silvery Pigment", quantidy = 50, }, { itemId = 43107, name = "Sapphire Pigment", quantidy = 10, }, { itemId = 39342, name = "Nether Pigment", quantidy = 80, }, { itemId = 43108, name = "Ebon Pigment", quantidy = 20, }, { itemId = 39343, name = "Azure Pigment", quantidy = 190, }, { itemId = 43109, name = "Icy Pigment", quantidy = 20, }, { itemId = 37101, name = "Ivory Ink", quantidy = 14, }, { itemId = 39469, name = "Moonglow Ink", quantidy = 22, }, { itemId = 39774, name = "Midnight Ink", quantidy = 25, }, { itemId = 43116, name = [[Lion's Ink]], quantidy = 90, }, { itemId = 43118, name = "Jadefire Ink", quantidy = 85, }, { itemId = 43120, name = "Celestial Ink", quantidy = 65, }, { itemId = 43122, name = "Shimmering Ink", quantidy = 45, }, { itemId = 43124, name = "Ethereal Ink", quantidy = 60, }, { itemId = 43126, name = "Ink of the Sea", quantidy = 100, }, { itemId = 39354, name = "Light Parchment", quantidy = 97, }, { itemId = 10648, name = "Common Parchment", quantidy = 105, }, { itemId = 39501, name = "Heavy Parchment", quantidy = 135, }, { itemId = 39502, name = "Resilient Parchment", quantidy = 210, }, } ns.guide = { { step = 1, start = 1, finish = 18, title = "Ivory Ink", notes = "Convert Alabaster Pigment into Ivory Ink", materials = { { itemId = 39151, name = "Alabaster Pigment", quantidy = 17, dbName = "pigments", }, }, creates = { { itemId = 37101, name = "Ivory Ink", quantidy = 17, dbName = "inks", }, }, }, { step = 2, start = 19, finish = 35, title = "Scroll of Stamina", notes = "Use Ivory Ink to write Scroll of Stamina", materials = { { itemId = 37101, name = "Ivory Ink", quantidy = 17, dbName = "inks", }, { itemId = 39354, name = "Light Parchment", quantidy = 17, dbName = "materials", }, }, creates = { { itemId = 1180, name = "Scroll of Stamina", quantidy = 17, }, }, }, { step = 3, start = 36, finish = 55, title = "Moonglow Ink", notes = "Convert Alabaster Pigment into Moonglow Ink", materials = { { itemId = 39151, name = "Alabaster Pigment", quantidy = 50, dbName = "pigments", }, }, creates = { { itemId = 39469, name = "Moonglow Ink", quantidy = 25, dbName = "inks", }, }, }, { step = 4, start = 56, finish = 75, title = "Armor Vellum", notes = "Use Moonglow Ink to craft Armor Vellum", materials = { { itemId = 39469, name = "Moonglow Ink", quantidy = 20, dbName = "inks", }, }, creates = { { itemId = 38682, name = "Armor Vellum", quantidy = 20, }, }, }, { step = 5, start = 75, finish = 75, title = "Learn Journeyman Inscription", notes = "Visit your trainer", materials = nil, creates = nil, }, { step = 6, start = 75, finish = 76, title = "Minor Inscription Research", notes = "Create a Minor Inscription Research", materials = { { itemId = 39469, name = "Moonglow Ink", quantidy = 1, dbName = "inks", }, { itemId = 39354, name = "Light Parchment", quantidy = 2, dbName = "materials", }, }, creates = nil, }, { step = 7, start = 77, finish = 80, title = "Midnight Ink", notes = "Convert Dusky Pigment into Midnight Ink, you will need 20-25 inks so keep making even if recipe is grey.", materials = { { itemId = 39334, name = "Dusky Pigment", quantidy = 50, dbName = "pigments", }, }, creates = { { itemId = 39774, name = "Midnight Ink", quantidy = 25, dbName = "inks", }, }, }, { step = 8, start = 81, finish = 100, title = "Glyphs", notes = "Use Midnight Ink to create glyphs up to 100.", materials = { { itemId = 39774, name = "Midnight Ink", quantidy = 25, dbName = "inks", }, { itemId = 39354, name = "Light Parchment", quantidy = 25, dbName = "materials", }, }, creates = nil, -- do i add the glyphs? }, { step = 9, start = 101, finish = 105, title = [[Lion's Ink]], notes = [[Convert Golden Pigment into Lion’s Ink, you'll need 50-60 inks so keep making even if recipe is grey.]], materials = { { itemId = 39338, name = "Golden Pigment", quantidy = 120, dbName = "pigments", }, }, creates = { { itemId = 43116, name = [[Lion's Ink]], quantidy = 60, dbName = "inks", } }, }, { step = 10, start = 106, finish = 125, title = "Glyphs", notes = [[Use Lion's Ink to create glyphs up to 125. |cff3399FFAt about 110 the parchment changes to Common Parchment and at 120 the ink cost doubles|r for some glyphs, the quantities given are approximate]], materials = { { itemId = 43116, name = [[Lion's Ink]], quantidy = 25, dbName = "inks", }, { itemId = 39354, name = "Light Parchment", quantidy = 5, dbName = "materials", }, { itemId = 10648, name = "Common Parchment", quantidy = 15, dbName = "materials", }, }, creates = nil, }, { step = 11, start = 125, finish = 125, title = "Learn Expert Inscription", notes = "Visit your trainer", materials = nil, creates = nil, }, { step = 12, start = 126, finish = 133, title = "Dawnstar Ink", notes = [[Convert Burnt Pigment into Dawnstar Ink, you will need 16 for the tarot cards so keep making it. Alternatively you can keep using Lion's Ink to make glyphs up to 140.]], materials = { { itemId = 43104, name = "Burnt Pigment", quantidy = 16, dbName = "pigments", }, }, creates = { { itemId = 43117, name = "Dawnstar Ink", quantidy = 16, dbName = "inks", }, }, }, { step = 13, start = 134, finish = 141, title = "Strange Tarot", notes = [[Use Dawnstar Ink and Lion's Ink to make Strange Tarot]], materials = { { itemId = 43116, name = [[Lion's Ink]], quantidy = 8, dbName = "inks", }, { itemId = 43117, name = "Dawnstar Ink", quantidy = 16, dbName = "inks", }, { itemId = 10648, name = "Common Parchment", quantidy = 8, }, }, creates = { { itemId = 44142, name = "Strange Tarot", quantidy = 8, }, }, }, { step = 14, start = 142, finish = 150, title = "Glyphs", notes = [[Use Lion's Ink to create glyphs up to 150]], materials = { { itemId = 43116, name = [[Lion's Ink]], quantidy = 9, dbName = "inks", }, { itemId = 10648, name = "Common Parchment", quantidy = 9, }, }, creates = nil, }, { step = 15, start = 151, finish = 155, title = "Jadefire Ink", notes = "Convert Emerald Pigment into Jadefire Ink, you'll need about 20 so keep making them.", materials = { { itemId = 39339, name = "Emerald Pigment", quantidy = 40, dbName = "pigments", }, }, creates = { { itemId = 43118, name = "Jadefire Ink", quantidy = 20, dbName = "inks", }, }, }, { step = 16, start = 156, finish = 175, title = "Glyphs", notes = "Use Jadefire Ink to create glyphs up to 175.", materials = { { itemId = 43118, name = "Jadefire Ink", quantidy = 20, dbName = "inks", }, { itemId = 10648, name = "Common Parchment", quantidy = 20, }, }, creates = nil, }, }
-- shears minetest.register_tool("creatures:shears", { description = "Shears", inventory_image = "creatures_shears.png", }) minetest.register_craft({ output = 'creatures:shears', recipe = { {'','default:steel_ingot'}, {'default:steel_ingot','default:stick'}, } }) -- drop items minetest.register_craftitem("creatures:flesh", { description = "Flesh", inventory_image = "creatures_flesh.png", on_use = minetest.item_eat(2), }) minetest.register_craftitem("creatures:rotten_flesh", { description = "Rotten Flesh", inventory_image = "creatures_rotten_flesh.png", on_use = minetest.item_eat(1), }) -- food minetest.register_craftitem("creatures:meat", { description = "Cooked Meat", inventory_image = "creatures_meat.png", on_use = minetest.item_eat(4), }) minetest.register_craft({ type = "cooking", output = "creatures:meat", recipe = "creatures:flesh", }) -- spawn-eggs minetest.register_craftitem("creatures:zombie_spawn_egg", { description = "Zombie spawn-egg", inventory_image = "creatures_egg_zombie.png", liquids_pointable = false, stack_max = 99, on_place = function(itemstack, placer, pointed_thing) if pointed_thing.type == "node" then local p = pointed_thing.above p.y = p.y+1 creatures.spawn(p, 1, "creatures:zombie", 1, 1) if not minetest.setting_getbool("creative_mode") then itemstack:take_item() end return itemstack end end, }) minetest.register_craftitem("creatures:ghost_spawn_egg", { description = "Ghost spawn-egg", inventory_image = "creatures_egg_ghost.png", liquids_pointable = false, stack_max = 99, on_place = function(itemstack, placer, pointed_thing) if pointed_thing.type == "node" then local p = pointed_thing.above p.y = p.y+0.5 creatures.spawn(p, 1, "creatures:ghost", 1, 1) if not minetest.setting_getbool("creative_mode") then itemstack:take_item() end return itemstack end end, }) minetest.register_craftitem("creatures:sheep_spawn_egg", { description = "Sheep spawn-egg", inventory_image = "creatures_egg_sheep.png", liquids_pointable = false, stack_max = 99, on_place = function(itemstack, placer, pointed_thing) if pointed_thing.type == "node" then local p = pointed_thing.above p.y = p.y+0.5 creatures.spawn(p, 1, "creatures:sheep", 1, 1) if not minetest.setting_getbool("creative_mode") then itemstack:take_item() end return itemstack end end, })
function main(splash) splash:autoload([[ function get_document_title(){ return document.title; } ]]) assert(splash:go(splash.args.url)) return splash:evaljs("get_document_title()") end
local scene = {} scene.name = "Bars" scene.color = {} scene.color.fg = {5/8, 5/8, 5/8} scene.color.bg = {3/8, 3/8, 3/8} local speed, num, bars, barWidth local WIDTH, HEIGHT local str = [[ speed: %d (change with left/right arrow) number of bars: %d (change with -/+)]] newBars = function() barWidth = WIDTH / (num * 3) for i = 1, num do bars[i] = WIDTH / num * (i - 1) end end scene.load = function(w, h) WIDTH, HEIGHT = w, h speed = 10 num = 3 bars = {} newBars() scene.strWidth = love.graphics.getFont():getWidth(str:format(1000, 1000)) end scene.resize = function(w, h) WIDTH, HEIGHT = w, h end scene.update = function(dt, fps) for i = 1, num do bars[i] = (bars[i] + speed * dt * WIDTH / 20) % (WIDTH) end scene.str = str:format(speed, num) end scene.draw = function(x, y) for i = 1, num do love.graphics.rectangle("fill", bars[i] + x , y, barWidth, HEIGHT) if bars[i] > WIDTH - barWidth then love.graphics.rectangle("fill", bars[i] - WIDTH + x, y, barWidth, HEIGHT) end end end scene.keypressed = function(key, keycode, isRepeat) local ctrl = love.keyboard.isDown("lctrl", "rctrl") local shift = love.keyboard.isDown("lshift", "rshift") local alt = love.keyboard.isDown("ralt", "lalt") if ctrl or shift or alt then return end if key == "-" then num = num - 1 num = math.max(1, num) newBars() elseif key == "+" then num = num + 1 num = math.max(1, num) newBars() elseif key == "left" then speed = speed - 1 elseif key == "right" then speed = speed + 1 end speed = math.max(1, speed) end return scene
resource_manifest_version '77731fab-63ca-442c-a67b-abc70f28dfa5' client_script "basic-c.lua" server_script "basic-s.lua" --[[ DO NOT REMOVE BELOW This script was fully created and developed by "Sean" there discord is "Sean B.#0899" if you need any help with the script please contact me on my discord and I will try to help as many of you as possibe. ]]
fx_version 'cerulean' game 'gta5' description 'QB-Inventory' version '1.0.0' shared_scripts { 'config.lua', '@qb-core/import.lua', '@qb-weapons/config.lua' } server_script 'server/main.lua' client_script 'client/main.lua' ui_page { 'html/ui.html' } files { 'html/ui.html', 'html/css/main.css', 'html/js/app.js', 'html/images/*.png', 'html/images/*.jpg', 'html/ammo_images/*.png', 'html/attachment_images/*.png', 'html/*.ttf' } dependency 'qb-weapons'
require("ZZBase64") require("TSLib") require("leoScript") init(1) local ts = require("ts") local json = ts.json local image = require("tsimg") syxTime = ts.ms() local getAllFlag = false local bbmapcount = 0 jyc = {} wzg = {} stl = {} zzg = {} dhw = {} dtjw = {} dtgj = {} alg = {} nec = {} hgs = {} mjc = {} pts = {} csjw = {} jnyw = {} bjlz = {} qls = {} wuzhuangguanArray = {} shituolingArray = {} zhuziguoArray = {} jianyechengArray = {} donghaiwanArray = {} datangjingwaiArray = {} datangguojingArray = {} aolaiguoArray = {} nvercunArray = {} huaguoshanArray = {} mojiacunArray = {} putuoshanArray = {} changshoujiaowaiArray = {} jiangnanyewaiArray = {} beijuluzhouArray = {} qilinshanArray = {} wuzhuangguanXYArray = {} shituolingXYArray = {} zhuziguoXYArray = {} jianyechengXYArray = {} donghaiwanXYArray = {} datangjingwaiXYArray = {} datangguojingXYArray = {} aolaiguoXYArray = {} nvercunXYArray = {} huaguoshanXYArray = {} mojiacunXYArray = {} putuoshanXYArray = {} changshoujiaowaiXYArray = {} jiangnanyewaiXYArray = {} beijuluzhouXYArray = {} qilinshanXYArray = {} wuzhuangguanRow = 1 shituolingRow = 1 zhuziguoRow = 1 jianyechengRow = 1 donghaiwanRow = 1 datangjingwaiRow = 1 datangguojingRow = 1 aolaiguoRow = 1 nvercunRow = 1 huaguoshanRow = 1 mojiacunRow = 1 putuoshanRow = 1 changshoujiaowaiRow = 1 jiangnanyewaiRow = 1 beijuluzhouRow = 1 qilinshanRow = 1 beijuluzhouFlag = 't' qilinshanFlag = 't' tempPackageFlag = false currentPage = 1 tapflag = false function table_leng(t) local leng=0 for k, v in pairs(t) do leng=leng+1 end return leng; end --修改完毕 function useFly() local x1,y1 x1,y1 = findFly() if x1 == -1 then dialog("请在1分钟内购买飞行符,并放在包囊最下排") mSleep(60000) x1,y1 = findFly() if x1 == -1 then error("未发现飞行符,脚本结束") mSleep(10) end end tapp(x1,y1,5) --使用飞行符 mSleep(600) --点击使用 tapp(664,611,5) for i=0,9,1 do if isFlyOpen() then return end end error("异常:使用飞行符失败") end --修改完毕 function useSYX() local x1,y1 x1,y1 = findSYX() if x1 == -1 then error("未发现摄妖香,脚本结束") end tapp(x1,y1,5) mSleep(600) --点击使用 tapp(663,608,5) end --修改完毕 function closePacket() mSleep(500) tapp(1603,86,0) mSleep(500) end --修改完毕 function openMap(...) tapp(155,80,5) mSleep(100) tapp(66,71,2) mSleep(500) end --to长安城 function toChangancheng(...) useFly() tapp(1187,495,5) closePacket() if getCAC() then return else dialog("飞长安城失败") end end --修改完毕 function toJianyecheng(...) useFly() tapp(1218,654,5) closePacket() if getJYC() then return else dialog("飞建邺城失败") end end --修改完毕 function jianyecheng(data) openMap() mSleep(200) while true do tapp(415,125,20) x = strSplit(data[2],"-") for i=1,table_leng(x)-1 do local n = x[i] if(n == "1") then mSleep(100) tapp(365,300,20) elseif(n == "2") then mSleep(100) tapp(515,300,20) elseif(n == "3") then mSleep(100) tapp(665,300,20) elseif(n == "4") then mSleep(100) tapp(365,450,20) elseif(n == "5") then mSleep(100) tapp(515,450,20) elseif(n == "6") then mSleep(100) tapp(665,450,20) elseif(n == "7") then mSleep(100) tapp(365,600,20) elseif(n == "8") then mSleep(100) tapp(515,600,20) elseif(n == "9") then mSleep(100) tapp(665,600,20) elseif(n == "0") then mSleep(100) tapp(815,450,20) end end --点击确定 mSleep(200) tapp(815,600,20) mSleep(400) if inputWordValidate(data[2],380,109,444,142) then break end end while true do --选择y坐标输入框 tapp(617,124,20) y = strSplit(data[3],"-") for i=1,table_leng(y)-1 do local n = y[i] if(n == "1") then mSleep(100) tapp(565,300,20) elseif(n == "2") then mSleep(100) tapp(715,300,20) elseif(n == "3") then mSleep(100) tapp(865,300,20) elseif(n == "4") then mSleep(100) tapp(565,450,20) elseif(n == "5") then mSleep(100) tapp(715,450,20) elseif(n == "6") then mSleep(100) tapp(865,450,20) elseif(n == "7") then mSleep(100) tapp(565,600,20) elseif(n == "8") then mSleep(100) tapp(715,600,20) elseif(n == "9") then mSleep(100) tapp(865,600,20) elseif(n == "0") then mSleep(100) tapp(1015,450,20) end end --点击确定 mSleep(200) tapp(1015,600,20) mSleep(400) if inputWordValidate(data[3],584,109,649,143) then break end end --点击前往 tappp(811,122,30,20) --点击关闭地图 mSleep(200) tapp(1697,79,10) end --修改完毕 function toAolaiguo(...) useFly() tapp(1525,781,5) closePacket() if getALG() then return else dialog("飞傲来国失败") end end --修改完毕 function aolaiguo(data) --closePacket() openMap() mSleep(200) while true do tappp(602,123,20,10) x = strSplit(data[2],"-") for i=1,table_leng(x)-1 do local n = x[i] if(n == "1") then mSleep(100) tapp(545,300,20) elseif(n == "2") then mSleep(100) tapp(695,300,20) elseif(n == "3") then mSleep(100) tapp(845,300,20) elseif(n == "4") then mSleep(100) tapp(545,450,20) elseif(n == "5") then mSleep(100) tapp(695,450,20) elseif(n == "6") then mSleep(100) tapp(845,450,20) elseif(n == "7") then mSleep(100) tapp(545,600,20) elseif(n == "8") then mSleep(100) tapp(695,600,20) elseif(n == "9") then mSleep(100) tapp(845,600,20) elseif(n == "0") then mSleep(100) tapp(995,450,20) end end --点击确定 mSleep(200) tapp(995,600,20) mSleep(400) if inputWordValidate(data[3],560,105,624,141) then break end end while true do --选择y坐标输入框 tappp(799,126,20,10) y = strSplit(data[3],"-") for i=1,table_leng(y)-1 do local n = y[i] if(n == "1") then mSleep(100) tapp(745,300,20) elseif(n == "2") then mSleep(100) tapp(895,300,20) elseif(n == "3") then mSleep(100) tapp(1045,300,20) elseif(n == "4") then mSleep(100) tapp(745,450,20) elseif(n == "5") then mSleep(100) tapp(895,450,20) elseif(n == "6") then mSleep(100) tapp(1045,450,20) elseif(n == "7") then mSleep(100) tapp(745,600,20) elseif(n == "8") then mSleep(100) tapp(895,600,20) elseif(n == "9") then mSleep(100) tapp(1045,600,20) elseif(n == "0") then mSleep(100) tapp(1195,450,20) end end --点击确定 mSleep(200) tapp(1195,600,20) --点击前往 mSleep(400) if inputWordValidate(data[3],764,105,822,140) then break end end tappp(991,123,20,10) --点击关闭地图 mSleep(400) tapp(1512,74,10) end --修改完毕 function toZhuziguo(...) useFly() tapp(866,725,5) closePacket() if getZZG() then return else dialog("飞朱紫国失败") end end --修改完毕 function zhuziguo(data) --closePacket() openMap() while true do tappp(550,115,20,10) x = strSplit(data[2],"-") for i=1,table_leng(x)-1 do local n = x[i] if(n == "1") then mSleep(100) tapp(495,295,20) elseif(n == "2") then mSleep(100) tapp(645,295,20) elseif(n == "3") then mSleep(100) tapp(795,295,20) elseif(n == "4") then mSleep(100) tapp(495,445,20) elseif(n == "5") then mSleep(100) tapp(645,445,20) elseif(n == "6") then mSleep(100) tapp(795,445,20) elseif(n == "7") then mSleep(100) tapp(495,595,20) elseif(n == "8") then mSleep(100) tapp(645,595,20) elseif(n == "9") then mSleep(100) tapp(795,595,20) elseif(n == "0") then mSleep(100) tapp(945,445,20) end end mSleep(200) tapp(945,595,20) mSleep(400) if inputWordValidate(data[2],511,101,577,135) then break end end while true do tappp(749,116,20,10) y = strSplit(data[3],"-") for i=1,table_leng(y)-1 do local n = y[i] if(n == "1") then mSleep(100) tapp(695,295,20) elseif(n == "2") then mSleep(100) tapp(845,295,20) elseif(n == "3") then mSleep(100) tapp(995,295,20) elseif(n == "4") then mSleep(100) tapp(695,445,20) elseif(n == "5") then mSleep(845) tapp(849,445,20) elseif(n == "6") then mSleep(100) tapp(995,445,20) elseif(n == "7") then mSleep(100) tapp(695,595,20) elseif(n == "8") then mSleep(100) tapp(845,595,20) elseif(n == "9") then mSleep(100) tapp(995,595,20) elseif(n == "0") then mSleep(100) tapp(1145,445,20) end end mSleep(200) tapp(1145,595,20) mSleep(400) if inputWordValidate(data[3],713,100,776,135) then break end end tappp(941,117,20,10) mSleep(200) tapp(1563,70,10) end --修改完毕 function toNvercun() --[[useFly() mSleep(500) tapp(1531,770,5) closePacket()]] toAolaiguo() toNvercun2() end --修改完毕??? function toNvercun2() --9,141 --[[ openMap() mSleep(200) tapp(609,119,2) mSleep(200) tapp(852,595,20) mSleep(200) tapp(1015,593,2) mSleep(200) tapp(800,129,2) mSleep(200) tapp(753,296,20) mSleep(200) tapp(752,449,20) mSleep(200) tapp(755,299,20) mSleep(200) tapp(1205,594,2) mSleep(200) tapp(999,123,2) mSleep(200) tapp(1517,77,2) ]] aolaiguo({"1","9-","1-4-1-"}) mSleep(2000) openPacket() mSleep(500) tapPackageMapX(500) mSleep(2000) closePacket() local str = "@9-@1-4-1-@" local lastxy,nowxy --容错 repeat mSleep(3000) nowxy = localZuobiao() if nowxy == lastxy then return toNvercun2() else lastxy = nowxy end until(nowxy==str) tapp(61,313,0) mSleep(1000) if getNEC() then return else dialog("进入女儿村失败") end end --修改完毕 function nvercun(data) --closePacket() openMap() while true do tappp(526,361,20,10) x = strSplit(data[2],"-") for i=1,table_leng(x)-1 do local n = x[i] if(n == "1") then mSleep(100) tapp(475,540,20) elseif(n == "2") then mSleep(100) tapp(625,540,20) elseif(n == "3") then mSleep(100) tapp(775,540,20) elseif(n == "4") then mSleep(100) tapp(475,690,20) elseif(n == "5") then mSleep(100) tapp(625,690,20) elseif(n == "6") then mSleep(100) tapp(775,690,20) elseif(n == "7") then mSleep(100) tapp(475,840,20) elseif(n == "8") then mSleep(100) tapp(625,840,20) elseif(n == "9") then mSleep(100) tapp(775,840,20) elseif(n == "0") then mSleep(100) tapp(925,687,20) end end mSleep(200) tapp(925,835,20) mSleep(400) if inputWordValidate(data[2],491,345,554,379) then break end end while true do tappp(530,463,20,10) y = strSplit(data[3],"-") for i=1,table_leng(y)-1 do local n = y[i] if(n == "1") then mSleep(100) tapp(475,645,20) elseif(n == "2") then mSleep(100) tapp(625,645,20) elseif(n == "3") then mSleep(100) tapp(775,645,20) elseif(n == "4") then mSleep(100) tapp(475,795,20) elseif(n == "5") then mSleep(100) tapp(625,795,20) elseif(n == "6") then mSleep(100) tapp(775,795,20) elseif(n == "7") then mSleep(100) tapp(471,945,20) elseif(n == "8") then mSleep(100) tapp(625,945,20) elseif(n == "9") then mSleep(100) tapp(775,945,20) elseif(n == "0") then mSleep(100) tapp(925,795,20) end end mSleep(200) tapp(925,945,20) mSleep(400) if inputWordValidate(data[3],490,444,560,479) then break end end tappp(516,544,20,10) mSleep(200) tapp(1507,62,10) end --修改完毕 function toBeijuluzhou() toChangshoujiaowai() toBeijuluzhou2() end --修改完毕 function toBeijuluzhou2() --63,66 --[[ openMap() mSleep(200) tapp(603,161,2) mSleep(200) tapp(854,490,20) mSleep(200) tapp(860,340,20) mSleep(200) tapp(1010,635,2) mSleep(200) tapp(795,164,2) mSleep(200) tapp(1061,488,20) mSleep(200) tapp(1064,491,20) mSleep(200) tapp(1213,637,2) mSleep(200) tapp(999,167,2) mSleep(200) tapp(1509,120,2) ]] changshoujiaowai({"1","6-3-","6-6-"}) mSleep(1000) openPacket() mSleep(500) --tapPackageMapX(100) tapPackageMap5time() mSleep(1000) closePacket() local str = "@6-3-@6-6-@" local lastxy,nowxy --容错 repeat mSleep(3000) nowxy = localZuobiao() if nowxy == lastxy then return toBeijuluzhou2() else lastxy = nowxy end until(nowxy==str) tapp(840,388,10) mSleep(3000) tapp(1592,499,2) mSleep(1000) --进入北俱芦洲验证 if getBJLZ() then return else dialog("进入北俱芦洲失败") end end --修改完毕 function beijuluzhou(data) --closePacket() openMap() while true do tappp(530,167,20,10) x = strSplit(data[2],"-") for i=1,table_leng(x)-1 do local n = x[i] if(n == "1") then mSleep(100) tapp(480,335,20) elseif(n == "2") then mSleep(100) tapp(630,335,20) elseif(n == "3") then mSleep(100) tapp(780,335,20) elseif(n == "4") then mSleep(100) tapp(480,485,20) elseif(n == "5") then mSleep(100) tapp(630,485,20) elseif(n == "6") then mSleep(100) tapp(780,485,20) elseif(n == "7") then mSleep(100) tapp(480,635,20) elseif(n == "8") then mSleep(100) tapp(630,635,20) elseif(n == "9") then mSleep(100) tapp(780,635,20) elseif(n == "0") then mSleep(100) tapp(930,485,20) end end mSleep(200) tapp(930,635,20) mSleep(400) if inputWordValidate(data[2],494,144,568,180) then break end end while true do tappp(736,163,20,10) y = strSplit(data[3],"-") for i=1,table_leng(y)-1 do local n = y[i] if(n == "1") then mSleep(100) tapp(680,340,20) elseif(n == "2") then mSleep(100) tapp(830,340,20) elseif(n == "3") then mSleep(100) tapp(980,340,20) elseif(n == "4") then mSleep(100) tapp(680,490,20) elseif(n == "5") then mSleep(100) tapp(830,490,20) elseif(n == "6") then mSleep(100) tapp(980,490,20) elseif(n == "7") then mSleep(100) tapp(680,640,20) elseif(n == "8") then mSleep(100) tapp(830,640,20) elseif(n == "9") then mSleep(100) tapp(980,640,20) elseif(n == "0") then mSleep(100) tapp(1130,490,20) end end mSleep(200) tapp(1130,640,20) mSleep(400) if inputWordValidate(data[3],697,141,766,181) then break end end tappp(928,159,20,10) mSleep(200) tapp(1580,113,10) end function toChangshoucun() useFly() mSleep(500) tapp(775,312,5) closePacket() if getCSC() then return else dialog("飞长寿村失败") end end --修改完毕 function toChangshoujiaowai() toChangshoucun() toChangshoujiaowai2() end --修改完毕 function toChangshoujiaowai2() openMap() --151,3 mSleep(200) tapp(752,142,2) mSleep(200) tapp(683,344,20) mSleep(200) tapp(685,490,20) mSleep(200) tapp(686,626,20) mSleep(200) tapp(1140,627,2) mSleep(200) tapp(927,158,2) mSleep(200) tapp(889,623,20) mSleep(200) tapp(1349,627,2) mSleep(200) tapp(1125,158,2) mSleep(200) tapp(1382,113,2) mSleep(2000) openPacket() mSleep(500) tapPackageMapX(350) mSleep(2000) closePacket() local str = "@1-4-7-@7-@" local lastxy,nowxy repeat mSleep(3000) local nowxy = localZuobiao() if nowxy == lastxy then return toChangshoujiaowai2() else lastxy = nowxy end until(nowxy==str) tapp(1731,932,0) mSleep(1000) if getCSJW() then return else dialog("进入长寿郊外失败") end end --修改完毕 function changshoujiaowai(data) --关闭背包 --closePacket() --点开地图输入坐标 openMap() while true do --选择X坐标输入框 tappp(603,169,20,10) --获取x坐标 x-x-x- x = strSplit(data[2],"-") for i=1,table_leng(x)-1 do local n = x[i] if(n == "1") then mSleep(100) tapp(550,340,20) elseif(n == "2") then mSleep(100) tapp(700,340,20) elseif(n == "3") then mSleep(100) tapp(850,340,20) elseif(n == "4") then mSleep(100) tapp(550,490,20) elseif(n == "5") then mSleep(100) tapp(700,490,20) elseif(n == "6") then mSleep(100) tapp(850,490,20) elseif(n == "7") then mSleep(100) tapp(550,640,20) elseif(n == "8") then mSleep(100) tapp(700,640,20) elseif(n == "9") then mSleep(100) tapp(850,640,20) elseif(n == "0") then mSleep(100) tapp(1000,490,20) end end --点击确定 mSleep(200) tapp(1000,640,20) mSleep(400) if inputWordValidate(data[2],568,151,634,184) then break end end while true do --选择y坐标输入框 tappp(805,167,20,10) y = strSplit(data[3],"-") for i=1,table_leng(y)-1 do local n = y[i] if(n == "1") then mSleep(100) tapp(750,340,20) elseif(n == "2") then mSleep(100) tapp(900,340,20) elseif(n == "3") then mSleep(100) tapp(1050,340,20) elseif(n == "4") then mSleep(100) tapp(750,490,20) elseif(n == "5") then mSleep(100) tapp(900,490,20) elseif(n == "6") then mSleep(100) tapp(1050,490,20) elseif(n == "7") then mSleep(100) tapp(750,640,20) elseif(n == "8") then mSleep(100) tapp(900,640,20) elseif(n == "9") then mSleep(100) tapp(1050,640,20) elseif(n == "0") then mSleep(100) tapp(1200,490,20) end end --点击确定 mSleep(200) tapp(1200,640,20) --点击前往 mSleep(400) if inputWordValidate(data[3],768,150,832,186) then break end end tappp(998,164,20,10) --点击关闭地图 mSleep(200) tapp(1507,120,10) end --修改完毕 function toQilinshan() -- body useFly() --点击朱紫国 mSleep(500) tapp(860,724,5) --关闭背包 closePacket() toQilinshan2() end --修改完毕 function toQilinshan2() --4,109 --点开地图输入坐标 --[[ openMap() tapp(543,120,2) --选择X坐标输入框 mSleep(200) tapp(503,437,20) mSleep(200) tapp(967,584,2) --选择y坐标输入框 mSleep(200) tapp(760,125,2) mSleep(200) tapp(700,300,20) mSleep(200) tapp(1150,430,20) mSleep(200) tapp(1000,600,20) --点击确定 mSleep(200) tapp(1150,600,2) --点击前往 mSleep(200) tapp(900,100,2) --点击关闭地图 mSleep(200) tapp(1550,70,2) ]] zhuziguo({"1","4-","1-0-9-"}) mSleep(2000) openPacket() mSleep(500) tapPackageMapX(400) mSleep(2000) closePacket() local str = "@4-@1-0-9-@" local lastxy,nowxy --容错 repeat mSleep(3000) nowxy = localZuobiao() if nowxy == lastxy then return toQilinshan2() else lastxy = nowxy end until(nowxy==str) tapp(50,150,0) mSleep(3000) end --修改完毕 function qilinshan(data) -- nLog("麒麟山移动坐标:"..data[2]..","..data[3]) --closePacket() openMap() mSleep(200) while true do --选择X坐标输入框 tappp(523,168,20,10) --获取x坐标 x-x-x- x = strSplit(data[2],"-") for i=1,table_leng(x)-1 do local n = x[i] if(n == "1") then mSleep(100) tapp(470,345,20) elseif(n == "2") then mSleep(100) tapp(620,345,20) elseif(n == "3") then mSleep(100) tapp(770,345,20) elseif(n == "4") then mSleep(100) tapp(470,495,20) elseif(n == "5") then mSleep(100) tapp(620,495,20) elseif(n == "6") then mSleep(100) tapp(770,495,20) elseif(n == "7") then mSleep(100) tapp(470,645,20) elseif(n == "8") then mSleep(100) tapp(620,645,20) elseif(n == "9") then mSleep(100) tapp(770,645,20) elseif(n == "0") then mSleep(100) tapp(920,495,20) end end --点击确定 mSleep(200) tapp(920,645,20) mSleep(400) if inputWordValidate(data[2],490,149,548,185) then break end end --选择y坐标输入框 while true do tappp(727,171,20,10) y = strSplit(data[3],"-") for i=1,table_leng(y)-1 do local n = y[i] if(n == "1") then mSleep(100) tapp(670,345,20) elseif(n == "2") then mSleep(100) tapp(820,345,20) elseif(n == "3") then mSleep(100) tapp(970,345,20) elseif(n == "4") then mSleep(100) tapp(670,495,20) elseif(n == "5") then mSleep(100) tapp(820,495,20) elseif(n == "6") then mSleep(100) tapp(970,495,20) elseif(n == "7") then mSleep(100) tapp(670,645,20) elseif(n == "8") then mSleep(100) tapp(820,645,20) elseif(n == "9") then mSleep(100) tapp(970,645,20) elseif(n == "0") then mSleep(100) tapp(1120,495,20) end end --点击确定 mSleep(200) tapp(1120,645,20) mSleep(400) if inputWordValidate(data[2],690,149,755,186) then break end end --点击前往 tappp(919,166,20,10) --点击关闭地图 mSleep(200) tapp(1587,120,10) end --修改完毕 function changan2guojing() --点开地图输入坐标 --12,3去大唐国境 openMap() --X坐标输入框 mSleep(200) tapp(452,127,2) mSleep(200) tapp(387,302,20) mSleep(200) tapp(548,302,20) --点击确定 mSleep(200) tapp(846,604,2) --y坐标输入框 mSleep(200) tapp(624,127,2) mSleep(200) tapp(893,302,20) --点击确定 mSleep(200) tapp(1050,604,2) --点击前往 mSleep(200) tapp(833,124,2) --点击关闭地图 mSleep(200) tapp(1680,80,2) mSleep(2000) openPacket() mSleep(500) tapPackageMapX(1950) mSleep(2000) closePacket() --local str = "@2-2-2-@1-4-1-@" local str = "@1-2-@3-@" local lastxy,nowxy --容错 repeat mSleep(3000) nowxy = localZuobiao() if nowxy == lastxy then return changan2guojing() else lastxy = nowxy end until(nowxy==str) tapp(36,963,0) mSleep(1000) if getDTGJ() then return else dialog("进入大唐国境失败") end end --修改完毕 function zhuzi2jingwai() --7,3 --朱紫国--大唐境外 --[[ mSleep(2000) --点开地图输入坐标 openMap() --选择X坐标输入框 tapp(548,126,2) mSleep(200) tapp(503,587,20) --点击确定 mSleep(200) tapp(960,591,2) --选择y坐标输入框 mSleep(200) tapp(738,122,2) mSleep(200) tapp(1000,290,20) --点击确定 mSleep(200) tapp(1164,580,2) --点击前往 mSleep(200) tapp(948,110,2) --点击关闭地图 mSleep(200) tapp(1570,69,2) ]] zhuziguo({"1-","7-","3-"}) mSleep(2000) openPacket() mSleep(500) tapPackageMapX(450) mSleep(2000) closePacket() local str = "@7-@3-@" local lastxy,nowxy --容错 repeat mSleep(3000) nowxy = localZuobiao() if nowxy == lastxy then return zhuzi2jingwai() else lastxy = nowxy end until(nowxy==str) tapp(38,945,0) mSleep(1000) if getDTJW() then return else dialog("朱紫国进入大唐境外失败") end end --修改完毕 function guojing2putuo() --长安--大唐国境227,60--普陀仙子 --点开地图输入坐标 --[[ openMap() --选择X坐标输入框 mSleep(200) tapp(566,88,2) mSleep(200) tapp(660,262,20) mSleep(200) tapp(663,263,20) mSleep(200) tapp(504,546,20) --点击确定 mSleep(200) tapp(958,550,2) --选择y坐标输入框 mSleep(400) tapp(747,87,2) mSleep(200) tapp(1013,420,20) mSleep(200) tapp(1164,404,20) --点击确定 mSleep(200) tapp(1163,557,2) --点击前往 mSleep(200) tapp(947,79,2) --点击关闭地图 mSleep(200) tapp(1562,39,2) ]] datangguojing({"1","2-2-7-","6-0-"}) mSleep(2000) openPacket() mSleep(500) tapPackageMapX(400) mSleep(2000) closePacket() local str = "@2-2-7-@6-0-@" local lastxy,nowxy --容错 repeat mSleep(3000) nowxy = localZuobiao() if nowxy == lastxy then return guojing2putuo() else lastxy = nowxy end until(nowxy==str) tapp(717,437,5) if ifDialogOpen() == false then dialog("请手动进入普陀山") else tappp(1600,520,100,20) end --进入普陀山验证 mSleep(1000) if getPTS() then return else dialog("进入普陀山失败") end end --修改完毕 function toDatangguojing() --[[ body useFly() --点击长安 mSleep(500) tapp(1187 495") --关闭背包 closePacket() -- body]] toChangancheng() changan2guojing() end --修改完毕 function datangguojing(data) --closePacket() --点开地图输入坐标 openMap() while true do --选择X坐标输入框 tappp(549,90,20,10) --获取x坐标 x-x-x- x = strSplit(data[2],"-") for i=1,table_leng(x)-1 do local n = x[i] if(n == "1") then mSleep(100) tapp(500,265,20) elseif(n == "2") then mSleep(100) tapp(650,265,20) elseif(n == "3") then mSleep(100) tapp(800,265,20) elseif(n == "4") then mSleep(100) tapp(500,415,20) elseif(n == "5") then mSleep(100) tapp(650,415,20) elseif(n == "6") then mSleep(100) tapp(800,415,20) elseif(n == "7") then mSleep(100) tapp(500,565,20) elseif(n == "8") then mSleep(100) tapp(650,565,20) elseif(n == "9") then mSleep(100) tapp(800,565,20) elseif(n == "0") then mSleep(100) tapp(950,415,20) end end --点击确定 mSleep(200) tapp(950,565,20) mSleep(400) if inputWordValidate(data[3],510,68,579,104) then break end end while true do --选择y坐标输入框 tappp(753,86,20,10) y = strSplit(data[3],"-") for i=1,table_leng(y)-1 do local n = y[i] if(n == "1") then mSleep(100) tapp(700,260,20) elseif(n == "2") then mSleep(100) tapp(850,260,20) elseif(n == "3") then mSleep(100) tapp(1000,260,20) elseif(n == "4") then mSleep(100) tapp(700,410,20) elseif(n == "5") then mSleep(100) tapp(850,410,20) elseif(n == "6") then mSleep(100) tapp(1000,410,20) elseif(n == "7") then mSleep(100) tapp(700,560,20) elseif(n == "8") then mSleep(100) tapp(850,560,20) elseif(n == "9") then mSleep(100) tapp(1000,560,20) elseif(n == "0") then mSleep(100) tapp(1150,410,20) end end --点击确定 mSleep(200) tapp(1150,560,20) mSleep(400) if inputWordValidate(data[3],711,69,779,102) then break end end --点击前往 tappp(944,86,20,10) --点击关闭地图 mSleep(200) tapp(1561,38,10) end --修改完毕 function toDatangjingwai() --[[ body useFly() --点击朱紫国 mSleep(500) tapp(862 730") --关闭背包 closePacket()]] toZhuziguo() zhuzi2jingwai() end --修改完毕 function datangjingwai(data) --closePacket() --点开地图 openMap() while true do --选择X坐标输入框 tappp(358,335,20,10) --获取x坐标 x-x-x- x = strSplit(data[2],"-") for i=1,table_leng(x)-1 do local n = x[i] if(n == "1") then mSleep(100) tapp(305,510,20) elseif(n == "2") then mSleep(100) tapp(455,510,20) elseif(n == "3") then mSleep(100) tapp(605,510,20) elseif(n == "4") then mSleep(100) tapp(305,660,20) elseif(n == "5") then mSleep(100) tapp(455,660,20) elseif(n == "6") then mSleep(100) tapp(605,660,20) elseif(n == "7") then mSleep(100) tapp(305,810,20) elseif(n == "8") then mSleep(100) tapp(455,810,20) elseif(n == "9") then mSleep(100) tapp(605,810,20) elseif(n == "0") then mSleep(100) tapp(755,660,20) end end --点击确定 mSleep(200) tapp(755,810,20) mSleep(400) if inputWordValidate(data[2],318,317,388,354) then break end end while true do --选择y坐标输入框 tappp(557,337,20,10) y = strSplit(data[3],"-") for i=1,table_leng(y)-1 do local n = y[i] if(n == "1") then mSleep(100) tapp(505,510,20) elseif(n == "2") then mSleep(100) tapp(655,510,20) elseif(n == "3") then mSleep(100) tapp(805,510,20) elseif(n == "4") then mSleep(100) tapp(505,660,20) elseif(n == "5") then mSleep(100) tapp(655,660,20) elseif(n == "6") then mSleep(100) tapp(805,660,20) elseif(n == "7") then mSleep(100) tapp(505,810,20) elseif(n == "8") then mSleep(100) tapp(655,810,20) elseif(n == "9") then mSleep(100) tapp(805,810,20) elseif(n == "0") then mSleep(100) tapp(955,660,20) end end --点击确定 mSleep(200) tapp(955,810,20) mSleep(400) if inputWordValidate(data[3],522,317,587,354) then break end end --点击前往 tappp(752,336,20,10) --点击关闭地图 mSleep(200) tapp(1754,289,10) end --修改完毕 function jingwai2mojiacun(...) -- body --大唐境外234,110 ---墨家村 --点开地图 mSleep(1000) --[[ openMap() --选择X坐标输入框 tapp(354,333,2) mSleep(200) tapp(437,526,20) mSleep(200) tapp(621,529,20) mSleep(200) tapp(308,649,20) --点击确定 mSleep(200) tapp(767,807,2) --选择y坐标输入框 mSleep(400) tapp(547,330,2) mSleep(200) tapp(514,523,20) mSleep(200) tapp(517,525,20) mSleep(200) tapp(965,658,20) --点击确定 mSleep(200) tapp(967,803,2) --点击前往 mSleep(200) tapp(752,332,2) --点击关闭地图 mSleep(200) tapp(1755,283,2) ]] datangjingwai({"1","2-3-4-","1-1-0-"}) mSleep(2000) openPacket() mSleep(500) tapPackageMapX(600) mSleep(2000) closePacket() local str = "@2-3-4-@1-1-0-@" local lastxy,nowxy --容错 repeat mSleep(3000) nowxy = localZuobiao() if nowxy == lastxy then return jingwai2mojiacun() else lastxy = nowxy end until(nowxy==str) --点击火焰山土地 tapp(1124,319,0) if ifDialogOpen() == false then dialog("手动进入墨家村") mSleep(10000) else --todo --墨家村传送人对话框 tappp(1550,380,100,20) end mSleep(1000) --进入墨家村判断 if getMJC() then return else dialog("进入墨家村失败") end end --修改完毕 function toMojiacun() -- body toDatangjingwai() jingwai2mojiacun() end --修改完毕 function mojiacun(data) --关闭背包 --closePacket() --点开地图输入坐标 openMap() while true do --选择X坐标输入框 tappp(651,328,20,10) --获取x坐标 x-x-x- x = strSplit(data[2],"-") for i=1,table_leng(x)-1 do local n = x[i] if(n == "1") then mSleep(100) tapp(600,510,20) elseif(n == "2") then mSleep(100) tapp(750,510,20) elseif(n == "3") then mSleep(100) tapp(900,510,20) elseif(n == "4") then mSleep(100) tapp(600,660,20) elseif(n == "5") then mSleep(100) tapp(750,660,20) elseif(n == "6") then mSleep(100) tapp(900,660,20) elseif(n == "7") then mSleep(100) tapp(600,810,20) elseif(n == "8") then mSleep(100) tapp(750,810,20) elseif(n == "9") then mSleep(100) tapp(900,810,20) elseif(n == "0") then mSleep(100) tapp(1050,660,20) end end --点击确定 mSleep(200) tapp(1050,810,20) mSleep(400) if inputWordValidate(data[2],611,311,674,348) then break end end while true do --选择y坐标输入框 tappp(652,430,20,10) y = strSplit(data[3],"-") for i=1,table_leng(y)-1 do local n = y[i] if(n == "1") then mSleep(100) tapp(600,610,20) elseif(n == "2") then mSleep(100) tapp(750,610,20) elseif(n == "3") then mSleep(100) tapp(900,610,20) elseif(n == "4") then mSleep(100) tapp(600,760,20) elseif(n == "5") then mSleep(100) tapp(750,760,20) elseif(n == "6") then mSleep(100) tapp(900,760,20) elseif(n == "7") then mSleep(100) tapp(600,910,20) elseif(n == "8") then mSleep(100) tapp(750,910,20) elseif(n == "9") then mSleep(100) tapp(900,910,20) elseif(n == "0") then mSleep(100) tapp(1050,760,20) end end --点击确定 mSleep(200) tapp(1050,910,20) mSleep(400) if inputWordValidate(data[3],610,408,677,450) then break end end --点击前往 tappp(641,519,20,10) --点击关闭地图 mSleep(200) tapp(1382,30,10) end --修改完毕 function toPutuoshan() --[[ body useFly() --点击长安 mSleep(500) tapp(1195 492") --关闭背包 closePacket() -- body changan2putuo()]] toDatangguojing() guojing2putuo() end --修改完毕 function putuoshan(data) --关闭背包 --closePacket() --点开地图 openMap() while true do --选择X坐标输入框 tappp(532,164,20,10) --获取x坐标 x-x-x- x = strSplit(data[2],"-") for i=1,table_leng(x)-1 do local n = x[i] if(n == "1") then mSleep(100) tapp(480,340,20) elseif(n == "2") then mSleep(100) tapp(630,340,20) elseif(n == "3") then mSleep(100) tapp(780,340,20) elseif(n == "4") then mSleep(100) tapp(480,490,20) elseif(n == "5") then mSleep(100) tapp(630,490,20) elseif(n == "6") then mSleep(100) tapp(780,490,20) elseif(n == "7") then mSleep(100) tapp(480,640,20) elseif(n == "8") then mSleep(100) tapp(630,640,20) elseif(n == "9") then mSleep(100) tapp(780,640,20) elseif(n == "0") then mSleep(100) tapp(930,490,20) end end --点击确定 mSleep(200) tapp(930,640,20) mSleep(400) if inputWordValidate(data[2],493,145,540,182) then break end end while true do --选择y坐标输入框 tappp(734,165,20,10) y = strSplit(data[3],"-") for i=1,table_leng(y)-1 do local n = y[i] if(n == "1") then mSleep(100) tapp(680,340,20) elseif(n == "2") then mSleep(100) tapp(830,340,20) elseif(n == "3") then mSleep(100) tapp(980,340,20) elseif(n == "4") then mSleep(100) tapp(680,490,20) elseif(n == "5") then mSleep(100) tapp(830,490,20) elseif(n == "6") then mSleep(100) tapp(980,490,20) elseif(n == "7") then mSleep(100) tapp(680,640,20) elseif(n == "8") then mSleep(100) tapp(830,640,20) elseif(n == "9") then mSleep(100) tapp(980,640,20) elseif(n == "0") then mSleep(100) tapp(1130,490,20) end end --点击确定 mSleep(200) tapp(1130,640,20) mSleep(400) if inputWordValidate(data[3],692,145,750,183) then break end end --点击前往 tappp(926,165,20,10) --点击关闭地图 mSleep(200) tapp(1580,117,10) end --修改完毕 function toDonghaiwan() toJianyecheng() toDonghaiwan2() end --修改完毕 function toDonghaiwan2() --270,29 -- body --点开地图输入坐标 --[[ openMap() --选择X坐标输入框 mSleep(200) tapp(416,126,2) mSleep(200) tapp(520,309,20) mSleep(200) tapp(370,596,20) mSleep(200) tapp(821,451,20) --点击确定 mSleep(200) tapp(830,581,2) --选择y坐标输入框 mSleep(400) tapp(605,129,2) mSleep(200) tapp(724,302,20) mSleep(200) tapp(875,596,20) --点击确定 mSleep(200) tapp(1034,599,2) --点击前往 mSleep(200) tapp(808,123,2) --点击关闭地图 mSleep(200) tapp(1691,81,2) ]] jianyecheng({"1-","2-7-0-","2-9-"}) mSleep(2000) openPacket() mSleep(500) tapPackageMapX(1500) mSleep(2000) closePacket() local str = "@2-7-0-@2-9-@" local lastxy,nowxy --容错 repeat mSleep(3000) nowxy = localZuobiao() if nowxy == lastxy then return toDonghaiwan2() else lastxy = nowxy end until(nowxy==str) tapp(1900,800,0) mSleep(1000) if getDHW() then return else dialog("进入东海湾失败") end end --修改完毕 function donghaiwan(data) --closePacket() openMap() while true do --选择X坐标输入框 tappp(658,167,20,10) --获取x坐标 x-x-x- x = strSplit(data[2],"-") for i=1,table_leng(x)-1 do local n = x[i] if(n == "1") then mSleep(100) tapp(605,345,20) elseif(n == "2") then mSleep(100) tapp(755,345,20) elseif(n == "3") then mSleep(100) tapp(905,345,20) elseif(n == "4") then mSleep(100) tapp(605,495,20) elseif(n == "5") then mSleep(100) tapp(755,495,20) elseif(n == "6") then mSleep(100) tapp(905,495,20) elseif(n == "7") then mSleep(100) tapp(605,645,20) elseif(n == "8") then mSleep(100) tapp(755,645,20) elseif(n == "9") then mSleep(100) tapp(905,645,20) elseif(n == "0") then mSleep(100) tapp(1055,495,20) end end --点击确定 mSleep(200) tapp(1055,645,20) mSleep(400) if inputWordValidate(data[2],618,149,682,185) then break end end while true do --选择y坐标输入框 tappp(856,166,20,10) y = strSplit(data[3],"-") for i=1,table_leng(y)-1 do local n = y[i] if(n == "1") then mSleep(100) tapp(805,345,20) elseif(n == "2") then mSleep(100) tapp(955,345,20) elseif(n == "3") then mSleep(100) tapp(1105,345,20) elseif(n == "4") then mSleep(100) tapp(805,495,20) elseif(n == "5") then mSleep(100) tapp(955,495,20) elseif(n == "6") then mSleep(100) tapp(1105,495,20) elseif(n == "7") then mSleep(100) tapp(805,645,20) elseif(n == "8") then mSleep(100) tapp(955,645,20) elseif(n == "9") then mSleep(100) tapp(1105,645,20) elseif(n == "0") then mSleep(100) tapp(1255,495,20) end end --点击确定 mSleep(200) tapp(1255,645,20) mSleep(400) if inputWordValidate(data[3],821,150,882,184) then break end end --点击前往 tappp(1046,166,20,10) --点击关闭地图 mSleep(200) tapp(1459,119,10) end --修改完毕 function toJiangnanyewai() --[[ body useFly() --点击建邺城位置 mSleep(500) tapp(1226 657") -- body closePacket()]] toJianyecheng() toJiangnanyewai2() end --修改完毕 function toJiangnanyewai2() --18,5 --点开地图输入坐标 --[[ openMap() --选择X坐标输入框 tapp(426,129,2) mSleep(200) tapp(368,303,20) mSleep(200) tapp(519,598,20) --点击确定 mSleep(200) tapp(830,600,2) --选择y坐标输入框 mSleep(400) tapp(623,123,2) mSleep(200) tapp(722,450,20) --点击确定 mSleep(200) tapp(1032,603,2) --点击前往 mSleep(200) tapp(815,126,2) --点击关闭地图 mSleep(200) tapp(1695,77,2) ]] jianyecheng({"1","1-8-","5-"}) mSleep(1000) openPacket() mSleep(500) tapPackageMap5time() mSleep(1000) closePacket() local str = "@1-8-@5-@" local lastxy,nowxy --容错 repeat mSleep(3000) nowxy = localZuobiao() if nowxy == lastxy then return toJiangnanyewai2() else lastxy = nowxy end until(nowxy==str) --点击传送 tapp(555,747,0) if ifDialogOpen() == false then dialog("手动进入江南野外") else tapp(1597,499,0) end mSleep(1000) if getJNYW() then return else dialog("进入江南野外失败") end end --修改完毕 function jiangnanyewai(data) --关闭背包 --closePacket() --点开地图输入坐标 openMap() --选择X坐标输入框 mSleep(200) while true do tapp(543,169,2) --获取x坐标 x-x-x- x = strSplit(data[2],"-") for i=1,table_leng(x)-1 do local n = x[i] if(n == "1") then mSleep(100) tapp(479,334,20) elseif(n == "2") then mSleep(100) tapp(635,336,20) elseif(n == "3") then mSleep(100) tapp(788,338,20) elseif(n == "4") then mSleep(100) tapp(482,491,20) elseif(n == "5") then mSleep(100) tapp(638,493,20) elseif(n == "6") then mSleep(100) tapp(791,495,20) elseif(n == "7") then mSleep(100) tapp(485,625,20) elseif(n == "8") then mSleep(100) tapp(641,627,20) elseif(n == "9") then mSleep(100) tapp(794,629,20) elseif(n == "0") then mSleep(100) tapp(933,497,20) end end --点击确定 mSleep(200) tapp(936,631,2) mSleep(400) if inputWordValidate(data[2],493,146,554,177) then break end end while true do --选择y坐标输入框 tapp(719,172,2) y = strSplit(data[3],"-") for i=1,table_leng(y)-1 do local n = y[i] if(n == "1") then mSleep(100) tapp(678,341,20) elseif(n == "2") then mSleep(100) tapp(838,344,20) elseif(n == "3") then mSleep(100) tapp(992,346,20) elseif(n == "4") then mSleep(100) tapp(681,499,20) elseif(n == "5") then mSleep(100) tapp(841,501,20) elseif(n == "6") then mSleep(100) tapp(995,503,20) elseif(n == "7") then mSleep(100) tapp(684,633,20) elseif(n == "8") then mSleep(100) tapp(844,635,20) elseif(n == "9") then mSleep(100) tapp(998,637,20) elseif(n == "0") then mSleep(100) tapp(1139,505,20) end end --点击确定 mSleep(200) tapp(1142,639,2) mSleep(400) if inputWordValidate(data[3],692,146,758,178) then break end end --点击前往 tapp(915,165,2) --点击关闭地图 mSleep(200) tapp(1582,113,2) end --修改完毕 function toHuaguoshan() --[[ body useFly() --点击傲来国 mSleep(500) tapp(1523 774") --关闭背包 closePacket() ]] toAolaiguo() toHuaguoshan2() end --修改完毕 function toHuaguoshan2() --212,143 -- body --点开地图输入坐标 --[[ openMap() --选择X坐标输入框 mSleep(200) tapp(620,128,2) mSleep(200) tapp(704,292,20) mSleep(200) tapp(551,295,20) mSleep(200) tapp(701,289,20) --点击确定 mSleep(200) tapp(995,598,2) --选择y坐标输入框 mSleep(400) tapp(799,127,2) mSleep(200) tapp(752,296,20) mSleep(200) tapp(758,446,20) mSleep(200) tapp(1055,300,20) --点击确定 mSleep(200) tapp(1213,601,2) --点击前往 mSleep(200) tapp(988,128,2) --点击关闭地图 mSleep(200) tapp(1515,74,2) ]] aolaiguo({"1","2-1-2-","1-4-3-"}) mSleep(2000) openPacket() mSleep(500) tapPackageMapX(250) mSleep(2000) closePacket() local str = "@2-1-2-@1-4-3-@" local lastxy,nowxy --容错 repeat mSleep(3000) nowxy = localZuobiao() if nowxy == lastxy then return toHuaguoshan2() else lastxy = nowxy end until(nowxy==str) tapp(1640,156,0) mSleep(1000) if getHGS then return else dialog("进入花果山失败") end end --处理完毕 function huaguoshan(data) --点开地图输入坐标 --closePacket() openMap() while true do --选择X坐标输入框 tappp(539,169,20,10) --获取x坐标 x-x-x- x = strSplit(data[2],"-") for i=1,table_leng(x)-1 do local n = x[i] if(n == "1") then mSleep(100) tapp(485,345,20) elseif(n == "2") then mSleep(100) tapp(635,345,20) elseif(n == "3") then mSleep(100) tapp(785,345,20) elseif(n == "4") then mSleep(100) tapp(485,495,20) elseif(n == "5") then mSleep(100) tapp(635,495,20) elseif(n == "6") then mSleep(100) tapp(785,495,20) elseif(n == "7") then mSleep(100) tapp(485,645,20) elseif(n == "8") then mSleep(100) tapp(635,645,20) elseif(n == "9") then mSleep(100) tapp(785,645,20) elseif(n == "0") then mSleep(100) tapp(935,495,20) end end --点击确定 mSleep(200) tapp(935,645,20) mSleep(400) if inputWordValidate(data[2],501,151,566,184) then break end end while true do --选择y坐标输入框 tappp(739,165,20,10) y = strSplit(data[3],"-") for i=1,table_leng(y)-1 do local n = y[i] if(n == "1") then mSleep(100) tapp(685,345,20) elseif(n == "2") then mSleep(100) tapp(845,345,20) elseif(n == "3") then mSleep(100) tapp(985,345,20) elseif(n == "4") then mSleep(100) tapp(685,495,20) elseif(n == "5") then mSleep(100) tapp(845,495,20) elseif(n == "6") then mSleep(100) tapp(985,495,20) elseif(n == "7") then mSleep(100) tapp(685,645,20) elseif(n == "8") then mSleep(100) tapp(845,645,20) elseif(n == "9") then mSleep(100) tapp(985,645,20) elseif(n == "0") then mSleep(100) tapp(1145,495,20) end end --点击确定 mSleep(200) tapp(1145,645,20) mSleep(400) if inputWordValidate(data[3],703,151,766,184) then break end end --点击前往 tappp(930,168,20,10) --点击关闭地图 mSleep(200) tapp(1574,120,10) end --已修改 function toWuzhuangguan() --跑图 toDatangjingwai() toWuzhuangguan2() end --已修改 function toWuzhuangguan2() --628,71 --点开地图 mSleep(1000) --[[ openMap() --选择X坐标输入框 mSleep(200) tapp(358,336,2) mSleep(200) tapp(615,657,20) mSleep(200) tapp(566,508,20) mSleep(200) tapp(566,508,20) --点击确定 mSleep(200) tapp(769,797,2) --选择y坐标输入框 mSleep(400) tapp(561,336,2) mSleep(200) tapp(505,809,20) mSleep(200) tapp(510,650,20) --点击确定 mSleep(200) tapp(967,813,2) --点击前往 mSleep(200) tapp(746,338,2) --点击关闭地图 mSleep(200) tapp(1759,288,2) ]] datangjingwai({"1","6-3-3-","7-4-"}) mSleep(2000) openPacket() mSleep(500) tapPackageMapX(3000) mSleep(2000) closePacket() mSleep(10000) openPacket() mSleep(500) tapPackageMapX(2000) mSleep(2000) closePacket() local str = "@6-3-3-@7-4-@" local lastxy,nowxy --容错 repeat mSleep(3000) nowxy = localZuobiao() if nowxy == lastxy then return toWuzhuangguan2() else lastxy = nowxy end until(nowxy==str) mSleep(1000) tapp(1700,290,0) mSleep(1000) --getWZG todo --if getWZG() then if exitDTJW() then return else dialog("进入五庄观失败") end end --修改完毕 function wuzhuangguan(data) --关闭背包 --closePacket() --点开地图输入坐标 openMap() --选择X坐标输入框 mSleep(200) while true do tappp(540,166,20,10) --获取x坐标 x-x-x- x = strSplit(data[2],"-") for i=1,table_leng(x)-1 do local n = x[i] if(n == "1") then mSleep(100) tapp(480,340,20) elseif(n == "2") then mSleep(100) tapp(630,340,20) elseif(n == "3") then mSleep(100) tapp(780,340,20) elseif(n == "4") then mSleep(100) tapp(480,490,20) elseif(n == "5") then mSleep(100) tapp(630,490,20) elseif(n == "6") then mSleep(100) tapp(780,490,20) elseif(n == "7") then mSleep(100) tapp(480,640,20) elseif(n == "8") then mSleep(100) tapp(630,640,20) elseif(n == "9") then mSleep(100) tapp(790,640,20) elseif(n == "0") then mSleep(100) tapp(930,490,20) end end --点击确定 mSleep(200) tapp(930,640,20) mSleep(400) if inputWordValidate(data[2],498,146,561,182) then break end end while true do --选择y坐标输入框 tappp(735,162,20,10) y = strSplit(data[3],"-") for i=1,table_leng(y)-1 do local n = y[i] if(n == "1") then mSleep(100) tapp(680,340,20) elseif(n == "2") then mSleep(100) tapp(830,340,20) elseif(n == "3") then mSleep(100) tapp(980,340,20) elseif(n == "4") then mSleep(100) tapp(680,490,20) elseif(n == "5") then mSleep(100) tapp(830,490,20) elseif(n == "6") then mSleep(100) tapp(980,490,20) elseif(n == "7") then mSleep(100) tapp(680,640,20) elseif(n == "8") then mSleep(100) tapp(830,640,20) elseif(n == "9") then mSleep(100) tapp(980,640,20) elseif(n == "0") then mSleep(100) tapp(1130,490,20) end end --点击确定 mSleep(200) tapp(1130,640,20) mSleep(400) if inputWordValidate(data[3],694,146,755,181) then break end end --点击前往 tappp(926,162,20,10) --点击关闭地图 mSleep(200) tapp(1580,117,10) end --修改完毕 function toShituoling(...) --跑图 toDatangjingwai() mSleep(1000) tapp(31,1065,0) mSleep(1000) if getSTL() then return else dialog("进入狮驼岭失败") end end --修改完毕 function shituoling(data) --点开地图输入坐标 openMap() --选择X坐标输入框 mSleep(200) while true do tappp(528,160,20,10) --获取x坐标 x-x-x- x = strSplit(data[2],"-") for i=1,table_leng(x)-1 do local n = x[i] if(n == "1") then mSleep(100) tapp(475,335,20) elseif(n == "2") then mSleep(100) tapp(625,335,20) elseif(n == "3") then mSleep(100) tapp(775,335,20) elseif(n == "4") then mSleep(100) tapp(475,485,20) elseif(n == "5") then mSleep(100) tapp(625,485,20) elseif(n == "6") then mSleep(100) tapp(775,485,20) elseif(n == "7") then mSleep(100) tapp(475,635,20) elseif(n == "8") then mSleep(100) tapp(625,635,20) elseif(n == "9") then mSleep(100) tapp(775,635,20) elseif(n == "0") then mSleep(100) tapp(925,485,20) end end --点击确定 mSleep(200) tapp(925,635,20) mSleep(400) if inputWordValidate(data[2],490,142,555,178) then break end end while true do --选择y坐标输入框 tappp(733,156,20,10) y = strSplit(data[3],"-") for i=1,table_leng(y)-1 do local n = y[i] if(n == "1") then mSleep(100) tapp(675,335,20) elseif(n == "2") then mSleep(100) tapp(825,335,20) elseif(n == "3") then mSleep(100) tapp(975,335,20) elseif(n == "4") then mSleep(100) tapp(675,485,20) elseif(n == "5") then mSleep(100) tapp(825,485,20) elseif(n == "6") then mSleep(100) tapp(975,485,20) elseif(n == "7") then mSleep(100) tapp(675,635,20) elseif(n == "8") then mSleep(100) tapp(825,635,20) elseif(n == "9") then mSleep(100) tapp(975,635,20) elseif(n == "0") then mSleep(100) tapp(1125,485,20) end end --点击确定 mSleep(200) tapp(1125,635,20) mSleep(400) if inputWordValidate(data[3],690,141,755,178) then break end end --点击前往 tappp(922,159,20,10) --点击关闭地图 mSleep(200) tapp(1586,112,10) end --修改完毕 --打开背包需要遍历所有的藏宝图 function findMap() keepScreen(true) local mapArray = {} local row = 1 for x=0,3 do for y=0,4 do x1,y1 = findMultiColorInRegionFuzzy( 0x71867a, "0|4|0x6c8375,12|8|0xed2b5f,4|12|0xf01460,-4|15|0xee2358,14|27|0x6d8378,6|47|0xf0f095,-25|38|0xeff0cc,-10|-22|0xf0f2d4,18|-15|0xf0edab", 90, 302+x*135, 908+y*135, 394+x*135, 1019+y*135) if x1~=-1 then --dialog(x..","..y,1) mapArray[row] = y1.."@"..(1080-x1) row = row+1 end end end keepScreen(false) return mapArray end --修改完毕 --打开背包需要遍历所有的藏宝图 function countMap() keepScreen(true) local mapCount = 0 local x1,y1 for x=0,4 do for y=0,2 do x1,y1 = findMultiColorInRegionFuzzy( 0xf0f5e2, "-9|22|0xeceab3,13|31|0xec3877,51|41|0xeae59b,60|16|0xf0f5d0,43|67|0xeff2cc", 90, 897+x*135, 260+y*135, 1026+x*135, 391+y*135) if x1~=-1 then mapCount = mapCount +1 end end end keepScreen(false) return mapCount end --无需改 function useSuccess() bbmapcount = bbmapcount-1 -- body while(true) do mSleep(200) if countMap() == bbmapcount then break end end end --无需改 function slayMonster(...) time = 0 while(true) do fightflag = waitFight() if fightflag == 1 then time = time +1 --toast("fighting...",1) tapp(1832,1021,5) mSleep(500) tapp(1832,1021,5) else return time end end end --已修改 function addBlood(time) -- 人物补血 if isColor(1912, 12,0xec2602,95) == false then tapp(1873,45,2) mSleep(300) tapp(1503,157,2) mSleep(300) end -- 人物补篮 if isColor( 1830, 32, 0x1d8af2 ,95) == false then tapp(1842,40,2) mSleep(300) tapp(1760,152,2) mSleep(300) end -- 宝宝补血 if isColor( 1652, 10, 0xeb1d02 ,95) == false then mSleep(300) tapp(1616,29,2) mSleep(300) tapp(1211,159,2) end end --已修改 function cut() bbMapOpenSuc() snapshot("test1.png", 531,440,572,760) local str --[[ --将文件转换为图片对象 local img,msg = image.loadFile(userPath() .. "/res/test1.png") if image.is(img) then --将图片对象顺时针旋转 270 度 local img,msg = image.setRotation270(img); if image.is(img) then --将图片对象转换为图片 local boo,msg = image.saveToPngFile(img,userPath() .. "/res/test2.png") else dialog(msg,3) end else dialog(msg,3) end ]] str = upload() if str == false then return cut() end return str end --无需改 local function imageToBase64(imageObj) local boo,msg = image.saveToPngFile(imageObj,userPath() .. "/res/1.jpg") local files local file = io.open(userPath() .. "/res/1.jpg","rb") if file then files = file:read("*a") file:close() else toast("没有找到文件",2) end return ZZBase64.encode(files) end --无需改 local function imageTurn270ToBase64(imageObj) local newImage,msg = image.setRotation270(imageObj) return imageToBase64(newImage) end --已修改 function post1(base64str) --local url = "http://118.31.47.19:30000/cd1080/getLocation" local url = "http://101.34.73.218:30000/cd1080/getLocation" --local data = [[{"body":base64str,"uuid":"uuid"}]] local data = "{\"body\":\""..base64str.."\",\"uuid\":\"uuid\"}" --local data = [[{"action": "getAuth","key": "开发者的key","devices": {"设备号1"},"valid": 3600,"time": ]].. os.time() ..[[}]] local options = { ["tstab"] = 1, -- 必填项 ["timeOut"] = 90, ["urlEnCode"] = false } return httpPost(url,data,options) end --修改完毕 function localZuobiao() --snapshot(userPath() .. "/res/getColor.png", 957, 151, 988, 300) path = userPath(); path = path.."/res/test1.png" snapshot(path, 151, 92, 300, 123) local files local file = io.open(path,"rb") if file then files = file:read("*a") file:close() else toast("没有找到文件",2) end base64 = ZZBase64.encode(files) --local newImage1,msg = image.loadFile(userPath() .. "/res/getColor.png") --local base64 = imageTurn270ToBase64(newImage1) local a = post1(base64) return a end --修改完毕 --背包物品存入仓库 function beibao2cangku(count) if count < 15 then --每次存储一个,然后重新调用 arrayList = findCangKuBeiBaoNoEmptyMapY(2) if tapflag == false then tapflag = true for key, var in ipairs(arrayList) do mapxy = strSplit(var,"@") --点击坐标 tapp(mapxy[1],mapxy[2],5) mSleep(100) end tapp(1526,217,5) end mSleep(250) local cangkuEmpCount = countCangKuEmpty() if cangkuEmpCount == 0 then tapp(259,944,2) mSleep(500) beibao2cangku(count) return end if count > 9 then mSleep(1000) end if count > 4 then mSleep(1000) end --t1Count = #arrayList for key, var in ipairs(arrayList) do local crflag = false while true do mapxy = strSplit(var,"@") --点击坐标 tapp(mapxy[1],mapxy[2],5) mSleep(500) --why:修改点击存入仓库按钮范围。有个别物品按钮扫描不到 x,y = findMultiColorInRegionFuzzy( 0x385868, "11|4|0x8aa1a9,-1|17|0x758d9a,15|18|0x304c60,13|32|0x66828d,-2|36|0x305060", 90, 367, 592, 440, 1078) if x ~= -1 and y ~= -1 then --如果在指定区域找到某点符合条件 tapp(x,y,5) end for tmptime =0,100 do mSleep(100) beibaoemp = countCangKuBeiBaoEmptyY(2) --toast(beibaoemp,1) if beibaoemp > count then count = beibaoemp crflag = true break end end if crflag == true then break end end cangkuEmpCount = cangkuEmpCount -1 if cangkuEmpCount == 0 then break end end --点一下仓库 mSleep(200) tapp(259,944,5) mSleep(500) count = countCangKuBeiBaoEmptyY(2) beibao2cangku(count) end end --修改完毕 function initMap(...) --初始化数据 wuzhuangguanArray = {} shituolingArray = {} zhuziguoArray = {} jianyechengArray = {} donghaiwanArray = {} datangjingwaiArray = {} datangguojingArray = {} aolaiguoArray = {} nvercunArray = {} huaguoshanArray = {} mojiacunArray = {} putuoshanArray = {} changshoujiaowaiArray = {} jiangnanyewaiArray = {} beijuluzhouArray = {} qilinshanArray = {} wuzhuangguanXYArray = {} shituolingXYArray = {} zhuziguoXYArray = {} jianyechengXYArray = {} donghaiwanXYArray = {} datangjingwaiXYArray = {} datangguojingXYArray = {} aolaiguoXYArray = {} nvercunXYArray = {} huaguoshanXYArray = {} mojiacunXYArray = {} putuoshanXYArray = {} changshoujiaowaiXYArray = {} jiangnanyewaiXYArray = {} beijuluzhouXYArray = {} qilinshanXYArray = {} wuzhuangguanRow = 1 shituolingRow = 1 zhuziguoRow = 1 jianyechengRow = 1 donghaiwanRow = 1 datangjingwaiRow = 1 datangguojingRow = 1 aolaiguoRow = 1 nvercunRow = 1 huaguoshanRow = 1 mojiacunRow = 1 putuoshanRow = 1 changshoujiaowaiRow = 1 jiangnanyewaiRow = 1 beijuluzhouRow = 1 qilinshanRow = 1 -- body --[[ openPacket() useFly() --点击长安 --tapp(1174 496") --关闭背包 closePacket() getCAC() mSleep(3000) tapp(559 503") mSleep(3000) doStay() doClear() --打开仓库 mSleep(500) tapp(849 484") if isCangKuOpen() then mSleep(1000) tapp(1614 634") mSleep(500) closeClear() mSleep(2000) else dialog("打开仓库失败,10秒内打开仓库") mSleep(10000) end ]] openPacket() useFly() --点击西凉女国 tapp(750,434,10) closePacket() --西凉女国仓库 getXLNG() mSleep(1000) doClear() mSleep(500) --点击管理员 tapp(960,200,10) if isCangKuOpen() then mSleep(1000) tappp(1600,660,150,20) mSleep(500) closeClear() if cangKuOpenSuccess() == false then dialog("请手动打开仓库") cangKuOpenSuccess() end else dialog("打开仓库失败,10秒内打开仓库") mSleep(10000) end --进入仓库预读取所有仓库内容 while( havNext() ) do tapp(549,944,2) mSleep(200) end --[[ while( havLast() ) do mSleep(200) tapp(259 944") end ]] --优化第一次取藏宝图速度 bbempCount = countCangKuBeiBaoEmptyY(2) if bbempCount >10 then mSleep(2000) end if bbempCount >5 then mSleep(2000) end if bbempCount<15 then --[[ --获取仓库空格,然后将身上的前三排扔到仓库,直到前三排都说空为止 while( havNext() ) do mSleep(200) tapp(549 944") end ]] tapflag = false beibao2cangku(bbempCount) end --回到第一页,然后从仓库里面拿藏宝图 while( havLast() ) do tapp(259,944,2) mSleep(200) end if getAllFlag ==false then getAllFlag = true jyc = {} wzg = {} stl = {} zzg = {} dhw = {} dtjw = {} dtgj = {} alg = {} nec = {} hgs = {} mjc = {} pts = {} csjw = {} jnyw = {} bjlz = {} qls = {} getAllMap() end bbmapcount = 15 - getCityMap() --关闭仓库 mSleep(500) tapp(1618,80,2) openPacket() mSleep(2000) end function autoDo() require("TSLib") UINew({width=1000,height=600}) UICheck("qls,bjlz","麒麟山,北俱芦洲","0@1",-1,0,"",1,1) UIShow() beijuluzhouFlag = bjlz qilinshanFlag = qls -- nLog(beijuluzhouFlag) -- nLog(qilinshanFlag) while (true) do --把物品存到仓库,把仓库宝图挪到身上 initMap() --如果所有的数组都是空,证明已经没有图了 if(#wuzhuangguanArray == 0) and (#shituolingArray == 0) and (#zhuziguoArray == 0) and (#jianyechengArray == 0) and (#donghaiwanArray == 0) and (#datangjingwaiArray == 0) and (#datangguojingArray == 0) and (#aolaiguoArray == 0) and (#nvercunArray == 0) and (#huaguoshanArray == 0) and (#mojiacunArray == 0) and (#putuoshanArray == 0) and (#changshoujiaowaiArray == 0) and (#jiangnanyewaiArray == 0) and (#beijuluzhouArray == 0) and (#qilinshanArray == 0) then break end useSYX() tapPackageMap4() --麒麟山 if(#qilinshanArray > 0) then -- nLog("麒麟山宝图排序") sortxr(qilinshanArray,qilinshanXYArray) -- nLog("麒麟山挖宝开始") openPacket() toQilinshan() for key,value in ipairs(qilinshanArray) do mapxy = strSplit(value,"@") local mapLocal = qilinshanXYArray[key] data = strSplit(mapLocal,"@") qilinshan(data) --对比当前坐标和地图坐标是否一致 repeat mSleep(3000) if getLocation(data) then break end until(false) doStay() --打包背包 openPacket() --选择藏宝图 使用 mSleep(500) if getRandom10() < 4 then tmpbt = qilinshanArray[key+1] if tmpbt ~= nil then tmpxy = strSplit(tmpbt,"@") tapp(tmpxy[1],tmpxy[2],5) mSleep(500) local mapLocal2 = qilinshanXYArray[key+1] data2 = strSplit(mapLocal2,"@") if isSimilarLocate(data,data2) == false then useCangbaotu() end end end if getRandom10() < 4 then tmpbt = qilinshanArray[key+2] if tmpbt ~= nil then tmpxy = strSplit(tmpbt,"@") tapp(tmpxy[1],tmpxy[2],5) mSleep(500) local mapLocal2 = qilinshanXYArray[key+2] data2 = strSplit(mapLocal2,"@") if isSimilarLocate(data,data2) == false then useCangbaotu() end end end tapp(mapxy[1],mapxy[2],5) mSleep(500) useCangbaotu() useSuccess() tapPackageMap5time() closePacket() local times = slayMonster() addBlood(times) end end --花果山 if(#huaguoshanArray > 0) then -- nLog("花果山宝图排序") sortxl(huaguoshanArray,huaguoshanXYArray) -- nLog("花果山挖宝开始") openPacket() toHuaguoshan() for key,value in ipairs(huaguoshanArray) do mapxy = strSplit(value,"@") local mapLocal = huaguoshanXYArray[key] data = strSplit(mapLocal,"@") huaguoshan(data) --对比当前坐标和地图坐标是否一致 repeat mSleep(3000) if getLocation(data) then break end until(false) doStay() --打包背包 openPacket() --选择藏宝图 使用 mSleep(500) if getRandom10() < 4 then tmpbt = huaguoshanArray[key+1] if tmpbt ~= nil then tmpxy = strSplit(tmpbt,"@") tapp(tmpxy[1],tmpxy[2],5) mSleep(500) local mapLocal2 = huaguoshanXYArray[key+1] data2 = strSplit(mapLocal2,"@") if isSimilarLocate(data,data2) == false then useCangbaotu() end end end if getRandom10() < 4 then tmpbt = huaguoshanArray[key+2] if tmpbt ~= nil then tmpxy = strSplit(tmpbt,"@") tapp(tmpxy[1],tmpxy[2],5) mSleep(500) local mapLocal2 = huaguoshanXYArray[key+2] data2 = strSplit(mapLocal2,"@") if isSimilarLocate(data,data2) == false then useCangbaotu() end end end tapp(mapxy[1],mapxy[2],5) mSleep(500) useCangbaotu() useSuccess() tapPackageMap5time() closePacket() local times = slayMonster() addBlood(times) end end --墨家村 if(#mojiacunArray > 0) then -- nLog("墨家村宝图排序") sortyd(mojiacunArray,mojiacunXYArray) -- nLog("墨家村挖宝开始") openPacket() toMojiacun() for key,value in ipairs(mojiacunArray) do mapxy = strSplit(value,"@") local mapLocal = mojiacunXYArray[key] data = strSplit(mapLocal,"@") mojiacun(data) --对比当前坐标和地图坐标是否一致 repeat mSleep(3000) if getLocation(data) then break end until(false) doStay() --打包背包 openPacket() --选择藏宝图 使用 mSleep(500) if getRandom10() < 4 then tmpbt = mojiacunArray[key+1] if tmpbt ~= nil then tmpxy = strSplit(tmpbt,"@") tapp(tmpxy[1],tmpxy[2],5) mSleep(500) local mapLocal2 = mojiacunXYArray[key+1] data2 = strSplit(mapLocal2,"@") if isSimilarLocate(data,data2) == false then useCangbaotu() end end end if getRandom10() < 4 then tmpbt = mojiacunArray[key+2] if tmpbt ~= nil then tmpxy = strSplit(tmpbt,"@") tapp(tmpxy[1],tmpxy[2],5) mSleep(500) local mapLocal2 = mojiacunXYArray[key+2] data2 = strSplit(mapLocal2,"@") if isSimilarLocate(data,data2) == false then useCangbaotu() end end end tapp(mapxy[1],mapxy[2],5) mSleep(500) useCangbaotu() useSuccess() tapPackageMap5time() closePacket() local times = slayMonster() addBlood(times) end end --女儿村 if(#nvercunArray > 0) then -- nLog("女儿村宝图排序") sortyd(nvercunArray,nvercunXYArray) -- nLog("女儿村挖宝开始") openPacket() toNvercun() for key,value in ipairs(nvercunArray) do mapxy = strSplit(value,"@") local mapLocal = nvercunXYArray[key] data = strSplit(mapLocal,"@") nvercun(data) --对比当前坐标和地图坐标是否一致 repeat mSleep(3000) if getLocation(data) then break end until(false) doStay() --打包背包 openPacket() --选择藏宝图 使用 mSleep(500) if getRandom10() < 4 then tmpbt = nvercunArray[key+1] if tmpbt ~= nil then tmpxy = strSplit(tmpbt,"@") tapp(tmpxy[1],tmpxy[2],5) mSleep(500) local mapLocal2 = nvercunArray[key+1] data2 = strSplit(mapLocal2,"@") if isSimilarLocate(data,data2) == false then useCangbaotu() end end end if getRandom10() < 4 then tmpbt = nvercunArray[key+2] if tmpbt ~= nil then tmpxy = strSplit(tmpbt,"@") tapp(tmpxy[1],tmpxy[2],5) mSleep(500) local mapLocal2 = nvercunArray[key+2] data2 = strSplit(mapLocal2,"@") if isSimilarLocate(data,data2) == false then useCangbaotu() end end end tapp(mapxy[1],mapxy[2],5) mSleep(500) useCangbaotu() useSuccess() tapPackageMap5time() closePacket() local times = slayMonster() addBlood(times) end end --大唐国境 if(#datangguojingArray > 0) then -- nLog("大唐国境宝图排序") sortxr(datangguojingArray,datangguojingXYArray) -- nLog("大唐国境挖宝开始") openPacket() toDatangguojing() for key,value in ipairs(datangguojingArray) do mapxy = strSplit(value,"@") local mapLocal = datangguojingXYArray[key] data = strSplit(mapLocal,"@") datangguojing(data) --对比当前坐标和地图坐标是否一致 repeat mSleep(3000) if getLocation(data) then break end until(false) doStay() --打包背包 openPacket() --选择藏宝图 使用 mSleep(500) if getRandom10() < 4 then tmpbt = datangguojingArray[key+1] if tmpbt ~= nil then tmpxy = strSplit(tmpbt,"@") tapp(tmpxy[1],tmpxy[2],5) mSleep(500) local mapLocal2 = datangguojingArray[key+1] data2 = strSplit(mapLocal2,"@") if isSimilarLocate(data,data2) == false then useCangbaotu() end end end if getRandom10() < 4 then tmpbt = datangguojingArray[key+2] if tmpbt ~= nil then tmpxy = strSplit(tmpbt,"@") tapp(tmpxy[1],tmpxy[2],5) mSleep(500) local mapLocal2 = datangguojingArray[key+2] data2 = strSplit(mapLocal2,"@") if isSimilarLocate(data,data2) == false then useCangbaotu() end end end tapp(mapxy[1],mapxy[2],5) mSleep(500) useCangbaotu() useSuccess() tapPackageMap5time() closePacket() local times = slayMonster() addBlood(times) end end --普陀山 if(#putuoshanArray > 0) then -- nLog("普陀山宝图排序") sortyd(putuoshanArray,putuoshanXYArray) -- nLog("普陀山挖宝开始") openPacket() toPutuoshan() for key,value in ipairs(putuoshanArray) do mapxy = strSplit(value,"@") local mapLocal = putuoshanXYArray[key] data = strSplit(mapLocal,"@") putuoshan(data) --对比当前坐标和地图坐标是否一致 repeat mSleep(3000) if getLocation(data) then break end until(false) doStay() --打包背包 openPacket() --选择藏宝图 使用 mSleep(500) if getRandom10() < 4 then tmpbt = putuoshanArray[key+1] if tmpbt ~= nil then tmpxy = strSplit(tmpbt,"@") tapp(tmpxy[1],tmpxy[2],5) mSleep(500) local mapLocal2 = putuoshanXYArray[key+1] data2 = strSplit(mapLocal2,"@") if isSimilarLocate(data,data2) == false then useCangbaotu() end end end if getRandom10() < 4 then tmpbt = putuoshanArray[key+2] if tmpbt ~= nil then tmpxy = strSplit(tmpbt,"@") tapp(tmpxy[1],tmpxy[2],5) mSleep(500) local mapLocal2 = putuoshanXYArray[key+2] data2 = strSplit(mapLocal2,"@") if isSimilarLocate(data,data2) == false then useCangbaotu() end end end tapp(mapxy[1],mapxy[2],5) mSleep(500) useCangbaotu() useSuccess() tapPackageMap5time() closePacket() local times = slayMonster() addBlood(times) end end --长寿郊外 if(#changshoujiaowaiArray > 0) then -- nLog("长寿郊外宝图排序") sortyt(changshoujiaowaiArray,changshoujiaowaiXYArray) -- nLog("长寿郊外挖宝开始") openPacket() toChangshoujiaowai() for key,value in ipairs(changshoujiaowaiArray) do mapxy = strSplit(value,"@") local mapLocal = changshoujiaowaiXYArray[key] data = strSplit(mapLocal,"@") changshoujiaowai(data) --对比当前坐标和地图坐标是否一致 repeat mSleep(3000) if getLocation(data) then break end until(false) doStay() --打包背包 openPacket() --选择藏宝图 使用 mSleep(500) if getRandom10() < 4 then tmpbt = changshoujiaowaiArray[key+1] if tmpbt ~= nil then tmpxy = strSplit(tmpbt,"@") tapp(tmpxy[1],tmpxy[2],5) mSleep(500) local mapLocal2 = changshoujiaowaiXYArray[key+1] data2 = strSplit(mapLocal2,"@") if isSimilarLocate(data,data2) == false then useCangbaotu() end end end if getRandom10() < 4 then tmpbt = changshoujiaowaiArray[key+2] if tmpbt ~= nil then tmpxy = strSplit(tmpbt,"@") tapp(tmpxy[1],tmpxy[2],5) mSleep(500) local mapLocal2 = changshoujiaowaiXYArray[key+2] data2 = strSplit(mapLocal2,"@") if isSimilarLocate(data,data2) == false then useCangbaotu() end end end tapp(mapxy[1],mapxy[2],5) mSleep(500) useCangbaotu() useSuccess() tapPackageMap5time() closePacket() local times = slayMonster() addBlood(times) end end --江南野外 if(#jiangnanyewaiArray > 0) then -- nLog("江南野外宝图排序") sortyd(jiangnanyewaiArray,jiangnanyewaiXYArray) -- nLog("江南野外挖宝开始") openPacket() toJiangnanyewai() for key,value in ipairs(jiangnanyewaiArray) do mapxy = strSplit(value,"@") local mapLocal = jiangnanyewaiXYArray[key] data = strSplit(mapLocal,"@") jiangnanyewai(data) --对比当前坐标和地图坐标是否一致 repeat mSleep(3000) if getLocation(data) then break end until(false) doStay() --打包背包 openPacket() --选择藏宝图 使用 mSleep(500) if getRandom10() < 4 then tmpbt = jiangnanyewaiArray[key+1] if tmpbt ~= nil then tmpxy = strSplit(tmpbt,"@") tapp(tmpxy[1],tmpxy[2],5) mSleep(500) local mapLocal2 = jiangnanyewaiXYArray[key+1] data2 = strSplit(mapLocal2,"@") if isSimilarLocate(data,data2) == false then useCangbaotu() end end end if getRandom10() < 4 then tmpbt = jiangnanyewaiArray[key+2] if tmpbt ~= nil then tmpxy = strSplit(tmpbt,"@") tapp(tmpxy[1],tmpxy[2],5) mSleep(500) local mapLocal2 = jiangnanyewaiXYArray[key+2] data2 = strSplit(mapLocal2,"@") if isSimilarLocate(data,data2) == false then useCangbaotu() end end end tapp(mapxy[1],mapxy[2],5) mSleep(500) useCangbaotu() useSuccess() tapPackageMap5time() closePacket() local times = slayMonster() addBlood(times) end end --五庄观 if(#wuzhuangguanArray > 0) then -- nLog("五庄观宝图排序") sortxl(wuzhuangguanArray,wuzhuangguanXYArray) -- nLog("五庄观挖宝开始") openPacket() toWuzhuangguan() for key,value in ipairs(wuzhuangguanArray) do mapxy = strSplit(value,"@") local mapLocal = wuzhuangguanXYArray[key] data = strSplit(mapLocal,"@") wuzhuangguan(data) --对比当前坐标和地图坐标是否一致 repeat mSleep(3000) if getLocation(data) then break end until(false) doStay() --打包背包 openPacket() --选择藏宝图 使用 mSleep(500) if getRandom10() < 4 then tmpbt = wuzhuangguanArray[key+1] if tmpbt ~= nil then tmpxy = strSplit(tmpbt,"@") tapp(tmpxy[1],tmpxy[2],5) mSleep(500) local mapLocal2 = wuzhuangguanXYArray[key+1] data2 = strSplit(mapLocal2,"@") if isSimilarLocate(data,data2) == false then useCangbaotu() end end end if getRandom10() < 4 then tmpbt = wuzhuangguanArray[key+2] if tmpbt ~= nil then tmpxy = strSplit(tmpbt,"@") tapp(tmpxy[1],tmpxy[2],5) mSleep(500) local mapLocal2 = wuzhuangguanXYArray[key+2] data2 = strSplit(mapLocal2,"@") if isSimilarLocate(data,data2) == false then useCangbaotu() end end end tapp(mapxy[1],mapxy[2],5) mSleep(500) useCangbaotu() useSuccess() tapPackageMap5time() closePacket() local times = slayMonster() addBlood(times) end end --狮驼岭 if(#shituolingArray > 0) then -- nLog("狮驼岭宝图排序") sortyt(shituolingArray,shituolingXYArray) -- nLog("狮驼岭挖宝开始") if isPackageOpen() then toShituoling() else openPacket() toShituoling() end for key,value in ipairs(shituolingArray) do mapxy = strSplit(value,"@") local mapLocal = shituolingXYArray[key] data = strSplit(mapLocal,"@") data = strSplit(mapLocal,"@") wuzhuangguan(data) --对比当前坐标和地图坐标是否一致 repeat mSleep(3000) if getLocation(data) then break end until(false) doStay() --打包背包 openPacket() --选择藏宝图 使用 mSleep(500) if getRandom10() < 4 then tmpbt = shituolingArray[key+1] if tmpbt ~= nil then tmpxy = strSplit(tmpbt,"@") tapp(tmpxy[1],tmpxy[2],5) mSleep(500) local mapLocal2 = shituolingXYArray[key+1] data2 = strSplit(mapLocal2,"@") if isSimilarLocate(data,data2) == false then useCangbaotu() end end end if getRandom10() < 4 then tmpbt = shituolingArray[key+2] if tmpbt ~= nil then tmpxy = strSplit(tmpbt,"@") tapp(tmpxy[1],tmpxy[2],5) mSleep(500) local mapLocal2 = shituolingXYArray[key+2] data2 = strSplit(mapLocal2,"@") if isSimilarLocate(data,data2) == false then useCangbaotu() end end end tapp(mapxy[1],mapxy[2],5) mSleep(500) useCangbaotu() useSuccess() tapPackageMap5time() closePacket() local times = slayMonster() addBlood(times) end end --东海湾 if(#donghaiwanArray > 0) then -- nLog("东海湾宝图排序") sortxr(donghaiwanArray,donghaiwanXYArray) -- nLog("东海湾挖宝开始") openPacket() toDonghaiwan() for key,value in ipairs(donghaiwanArray) do mapxy = strSplit(value,"@") local mapLocal = donghaiwanXYArray[key] data = strSplit(mapLocal,"@") donghaiwan(data) --对比当前坐标和地图坐标是否一致 repeat mSleep(3000) if getLocation(data) then break end until(false) doStay() --打包背包 openPacket() --选择藏宝图 使用 mSleep(500) if getRandom10() < 4 then tmpbt = donghaiwanArray[key+1] if tmpbt ~= nil then tmpxy = strSplit(tmpbt,"@") tapp(tmpxy[1],tmpxy[2],5) mSleep(500) local mapLocal2 = donghaiwanXYArray[key+1] data2 = strSplit(mapLocal2,"@") if isSimilarLocate(data,data2) == false then useCangbaotu() end end end if getRandom10() < 4 then tmpbt = donghaiwanArray[key+2] if tmpbt ~= nil then tmpxy = strSplit(tmpbt,"@") tapp(tmpxy[1],tmpxy[2],5) mSleep(500) local mapLocal2 = donghaiwanXYArray[key+2] data2 = strSplit(mapLocal2,"@") if isSimilarLocate(data,data2) == false then useCangbaotu() end end end tapp(mapxy[1],mapxy[2],5) mSleep(500) useCangbaotu() useSuccess() tapPackageMap5time() closePacket() local times = slayMonster() addBlood(times) end end --北俱芦洲 if(#beijuluzhouArray > 0) then -- nLog("北俱芦洲宝图排序") sortxr(beijuluzhouArray,beijuluzhouXYArray) -- nLog("北俱芦洲挖宝开始") openPacket() toBeijuluzhou() for key,value in ipairs(beijuluzhouArray) do mapxy = strSplit(value,"@") local mapLocal = beijuluzhouXYArray[key] data = strSplit(mapLocal,"@") beijuluzhou(data) --对比当前坐标和地图坐标是否一致 repeat mSleep(3000) if getLocation(data) then break end until(false) doStay() --打包背包 openPacket() --选择藏宝图 使用 mSleep(500) if getRandom10() < 4 then tmpbt = beijuluzhouArray[key+1] if tmpbt ~= nil then tmpxy = strSplit(tmpbt,"@") tapp(tmpxy[1],tmpxy[2],5) mSleep(500) local mapLocal2 = beijuluzhouXYArray[key+1] data2 = strSplit(mapLocal2,"@") if isSimilarLocate(data,data2) == false then useCangbaotu() end end end if getRandom10() < 4 then tmpbt = beijuluzhouArray[key+2] if tmpbt ~= nil then tmpxy = strSplit(tmpbt,"@") tapp(tmpxy[1],tmpxy[2],5) mSleep(500) local mapLocal2 = beijuluzhouXYArray[key+2] data2 = strSplit(mapLocal2,"@") if isSimilarLocate(data,data2) == false then useCangbaotu() end end end tapp(mapxy[1],mapxy[2],5) mSleep(500) useCangbaotu() useSuccess() tapPackageMap5time() closePacket() local times = slayMonster() addBlood(times) end end --大唐境外 if(#datangjingwaiArray > 0) then -- nLog("大唐境外宝图排序") sortxl(datangjingwaiArray,datangjingwaiXYArray) -- nLog("大唐境外挖宝开始") openPacket() toDatangjingwai() for key,value in ipairs(datangjingwaiArray) do mapxy = strSplit(value,"@") local mapLocal = datangjingwaiXYArray[key] data = strSplit(mapLocal,"@") datangjingwai(data) --对比当前坐标和地图坐标是否一致 repeat mSleep(3000) if getLocation(data) then break end until(false) doStay() --打包背包 openPacket() --选择藏宝图 使用 mSleep(500) if getRandom10() < 4 then tmpbt = datangjingwaiArray[key+1] if tmpbt ~= nil then tmpxy = strSplit(tmpbt,"@") tapp(tmpxy[1],tmpxy[2],5) mSleep(500) local mapLocal2 = datangjingwaiXYArray[key+1] data2 = strSplit(mapLocal2,"@") if isSimilarLocate(data,data2) == false then useCangbaotu() end end end if getRandom10() < 4 then tmpbt = datangjingwaiArray[key+2] if tmpbt ~= nil then tmpxy = strSplit(tmpbt,"@") tapp(tmpxy[1],tmpxy[2],5) mSleep(500) local mapLocal2 = datangjingwaiXYArray[key+2] data2 = strSplit(mapLocal2,"@") if isSimilarLocate(data,data2) == false then useCangbaotu() end end end tapp(mapxy[1],mapxy[2],5) mSleep(500) useCangbaotu() useSuccess() tapPackageMap5time() closePacket() local times = slayMonster() addBlood(times) end end --朱紫国 if(#zhuziguoArray > 0) then -- nLog("朱紫国宝图排序") sortyt(zhuziguoArray,zhuziguoXYArray) -- nLog("朱紫国挖宝开始") openPacket() toZhuziguo() for key,value in ipairs(zhuziguoArray) do mapxy = strSplit(value,"@") local mapLocal = zhuziguoXYArray[key] data = strSplit(mapLocal,"@") zhuziguo(data) --对比当前坐标和地图坐标是否一致 repeat mSleep(3000) if getLocation(data) then break end until(false) doStay() --打包背包 openPacket() --选择藏宝图 使用 mSleep(500) if getRandom10() < 4 then tmpbt = zhuziguoArray[key+1] if tmpbt ~= nil then tmpxy = strSplit(tmpbt,"@") tapp(tmpxy[1],tmpxy[2],5) mSleep(500) local mapLocal2 = zhuziguoXYArray[key+1] data2 = strSplit(mapLocal2,"@") if isSimilarLocate(data,data2) == false then useCangbaotu() end end end if getRandom10() < 4 then tmpbt = zhuziguoArray[key+2] if tmpbt ~= nil then tmpxy = strSplit(tmpbt,"@") tapp(tmpxy[1],tmpxy[2],5) mSleep(500) local mapLocal2 = zhuziguoXYArray[key+2] data2 = strSplit(mapLocal2,"@") if isSimilarLocate(data,data2) == false then useCangbaotu() end end end tapp(mapxy[1],mapxy[2],5) mSleep(500) useCangbaotu() useSuccess() tapPackageMap5time() closePacket() local times = slayMonster() addBlood(times) end end --傲来国 if(#aolaiguoArray > 0) then -- nLog("傲来国宝图排序") sortyt(aolaiguoArray,aolaiguoXYArray) -- nLog("傲来国挖宝开始") openPacket() toAolaiguo() for key,value in ipairs(aolaiguoArray) do mapxy = strSplit(value,"@") local mapLocal = aolaiguoXYArray[key] data = strSplit(mapLocal,"@") aolaiguo(data) --对比当前坐标和地图坐标是否一致 repeat mSleep(3000) if getLocation(data) then break end until(false) doStay() --打包背包 openPacket() --选择藏宝图 使用 mSleep(500) if getRandom10() < 4 then tmpbt = aolaiguoArray[key+1] if tmpbt ~= nil then tmpxy = strSplit(tmpbt,"@") tapp(tmpxy[1],tmpxy[2],5) mSleep(500) local mapLocal2 = aolaiguoXYArray[key+1] data2 = strSplit(mapLocal2,"@") if isSimilarLocate(data,data2) == false then useCangbaotu() end end end if getRandom10() < 4 then tmpbt = aolaiguoArray[key+2] if tmpbt ~= nil then tmpxy = strSplit(tmpbt,"@") tapp(tmpxy[1],tmpxy[2],5) mSleep(500) local mapLocal2 = aolaiguoXYArray[key+2] data2 = strSplit(mapLocal2,"@") if isSimilarLocate(data,data2) == false then useCangbaotu() end end end tapp(mapxy[1],mapxy[2],5) mSleep(500) useCangbaotu() useSuccess() tapPackageMap5time() closePacket() local times = slayMonster() addBlood(times) end end --建邺城 if(#jianyechengArray > 0) then -- nLog("建邺城宝图排序") sortyd(jianyechengArray,jianyechengXYArray) -- nLog("建邺城挖宝开始") openPacket() toJianyecheng() for key,value in ipairs(jianyechengArray) do -- nLog("当前宝图使用开始") mapxy = strSplit(value,"@") local mapLocal = jianyechengXYArray[key] data = strSplit(mapLocal,"@") -- nLog("开始移动:坐标"..data[1]..","..data[2]) jianyecheng(data) --对比当前坐标和地图坐标是否一致 repeat mSleep(3000) if getLocation(data) then break end until(false) doStay() --打包背包 openPacket() --选择藏宝图 使用 mSleep(500) if getRandom10() < 4 then tmpbt = jianyechengArray[key+1] if tmpbt ~= nil then tmpxy = strSplit(tmpbt,"@") tapp(tmpxy[1],tmpxy[2],5) mSleep(500) local mapLocal2 = jianyechengXYArray[key+1] data2 = strSplit(mapLocal2,"@") if isSimilarLocate(data,data2) == false then useCangbaotu() end end end if getRandom10() < 4 then tmpbt = jianyechengArray[key+2] if tmpbt ~= nil then tmpxy = strSplit(tmpbt,"@") tapp(tmpxy[1],tmpxy[2],5) mSleep(500) local mapLocal2 = jianyechengXYArray[key+2] data2 = strSplit(mapLocal2,"@") if isSimilarLocate(data,data2) == false then useCangbaotu() end end end tapp(mapxy[1],mapxy[2],5) mSleep(500) useCangbaotu() useSuccess() tapPackageMap5time() closePacket() local times = slayMonster() addBlood(times) -- nLog("当前宝图使用结束") end end if tempPackageFlag == true then tempPackageFlag = false mSleep(500) tapp(1701,1021,10) mSleep(500) tapp(1606,702,30) mSleep(500) tappp(775,859,100,20) mSleep(5000) end end end function useCangbaotu() while (true) do x1,y1 = findMultiColorInRegionFuzzy( 0x02f602, "", 90, 441, 511, 669, 548) if x1>-1 then break end end x1,y1 = findMultiColorInRegionFuzzy( 0xffffff, "1|-20|0x385c70,0|28|0x284450,67|-23|0x3e5c70,71|-5|0x305368", 90, 665, 564, 768, 887) tapp(x1,y1,10) end function getLocation(data) data1 = strSplit(localZuobiao(),"@") if #data1 < 3 then return false end local cx,cy,tx,ty tx = string.gsub(data[2], "-", "") ty = string.gsub(data[3], "-", "") cx = string.gsub(data1[2], "-", "") cy = string.gsub(data1[3], "-", "") if math.abs(tx - cx) <2 and math.abs(ty - cy) < 2 then return true else return false end end function isSimilarLocate(data1,data2) return true --[[nLog("data1:"..data1[1]..","..data1[2]..","..data1[3].." data2:"..data2[1]..","..data2[2]..","..data2[3]) local islx1,islx2,isly1,isly2,islstr islx1 = tonumber(string.gsub(data1[2],"[^0-9]","")) islx2 = tonumber(string.gsub(data2[2],"[^0-9]","")) isly1 = tonumber(string.gsub(data1[3],"[^0-9]","")) isly2 = tonumber(string.gsub(data2[3],"[^0-9]","")) isltr = "比较坐标:("..islx1..","..isly1.."),("..islx2..","..isly2..")->" if math.abs(islx1 - islx2) < 10 and math.abs(isly1 - isly2) < 10 then isltr = isltr + "相近" nLog(isltr) return true end isltr = isltr + "不相近" nLog(isltr) return false]] end --pcall(autoDo) autoDo() --closePacket() --mSleep(500) --exitGame() --toast(inputWordValidate(nil,498,146,561,182),1) --mSleep(1000) --toast(inputWordValidate(nil,694,146,755,181),1) --mSleep(1000) --[[ x: 498 146 561 182 y: 694 146 755 181 ]]
local super = Class("BorderFactory", LuaObject).getSuperclass() function BorderFactory.createLineBorder(...) return LineBorder(...) end
-- Punctuation, Other local make_set = require 'parse.char.utf8.make.set' return make_set { S = [["'\]] .. '*,./!#%&:;?@' .. '\u{a1}\u{a7}\u{b6}\u{b7}\u{bf}' .. '\u{37e}\u{387}\u{589}\u{5c0}\u{5c3}\u{5c6}\u{5f3}\u{5f4}\u{609}\u{60a}\u{60c}\u{60d}\u{61b}' .. '\u{61e}\u{61f}\u{6d4}\u{85e}\u{964}\u{965}\u{970}\u{af0}\u{df4}\u{e4f}\u{e5a}\u{e5b}\u{f14}' .. '\u{f85}\u{fd9}\u{fda}' .. '\u{10fb}\u{166d}\u{166e}\u{1735}\u{1736}\u{1944}\u{1945}\u{1a1e}\u{1a1f}\u{1c7e}\u{1c7f}\u{1cd3}' .. '\u{2016}\u{2017}\u{2053}\u{2cfe}\u{2cff}\u{2d70}\u{2e00}\u{2e01}\u{2e0b}\u{2e18}\u{2e19}\u{2e1b}' .. '\u{2e1e}\u{2e1f}\u{2e41}\u{303d}\u{30fb}\u{a4fe}\u{a4ff}\u{a673}\u{a67e}\u{a8ce}\u{a8cf}\u{a8fc}' .. '\u{a92e}\u{a92f}\u{a95f}\u{a9de}\u{a9df}\u{aade}\u{aadf}\u{aaf0}\u{aaf1}\u{abeb}\u{fe19}\u{fe30}' .. '\u{fe45}\u{fe46}\u{fe68}\u{fe6a}\u{fe6b}\u{ff0a}\u{ff0c}\u{ff0e}\u{ff0f}\u{ff1a}\u{ff1b}\u{ff1f}' .. '\u{ff20}\u{ff3c}\u{ff61}\u{ff64}\u{ff65}' .. '\u{1039f}\u{103d0}\u{1056f}\u{10857}\u{1091f}\u{1093f}\u{10a7f}\u{110bb}\u{110bc}\u{11174}\u{11175}' .. '\u{111cd}\u{111db}\u{112a9}\u{114c6}\u{16a6e}\u{16a6f}\u{16af5}\u{16b44}\u{1bc9f}'; R = { "\u{55a}\u{55f}","\u{66a}\u{66d}","\u{700}\u{70d}","\u{7f7}\u{7f9}","\u{830}\u{83e}", "\u{f04}\u{f12}","\u{fd0}\u{fd4}", "\u{104a}\u{104f}","\u{1360}\u{1368}","\u{16eb}\u{16ed}","\u{17d4}\u{17d6}","\u{17d8}\u{17da}", "\u{1800}\u{1805}","\u{1807}\u{180a}","\u{1aa0}\u{1aa6}","\u{1aa8}\u{1aad}","\u{1b5a}\u{1b60}", "\u{1bfc}\u{1bff}","\u{1c3b}\u{1c3f}","\u{1cc0}\u{1cc7}","\u{2020}\u{2027}","\u{2030}\u{2038}", "\u{203b}\u{203e}","\u{2041}\u{2043}","\u{2047}\u{2051}","\u{2055}\u{205e}","\u{2cf9}\u{2cfc}", "\u{2e06}\u{2e08}","\u{2e0e}\u{2e16}","\u{2e2a}\u{2e2e}","\u{2e30}\u{2e39}","\u{2e3c}\u{2e3f}", "\u{3001}\u{3003}","\u{a60d}\u{a60f}","\u{a6f2}\u{a6f7}","\u{a874}\u{a877}","\u{a8f8}\u{a8fa}", "\u{a9c1}\u{a9cd}","\u{aa5c}\u{aa5f}","\u{fe10}\u{fe16}","\u{fe49}\u{fe4c}","\u{fe50}\u{fe52}", "\u{fe54}\u{fe57}","\u{fe5f}\u{fe61}","\u{ff01}\u{ff03}","\u{ff05}\u{ff07}", "\u{10100}\u{10102}","\u{10a50}\u{10a58}","\u{10af0}\u{10af6}","\u{10b39}\u{10b3f}", "\u{10b99}\u{10b9c}","\u{11047}\u{1104d}","\u{110be}\u{110c1}","\u{11140}\u{11143}", "\u{111c5}\u{111c9}","\u{111dd}\u{111df}","\u{11238}\u{1123d}","\u{115c1}\u{115d7}", "\u{11641}\u{11643}","\u{1173c}\u{1173e}","\u{12470}\u{12474}","\u{16b37}\u{16b3b}", "\u{1da87}\u{1da8b}" }; }
self = {} function OnSpellStart( keys )self.ap_scaling = keys.ability:GetSpecialValueFor( "ap_scaling" ) self.explosion_radius = keys.ability:GetSpecialValueFor( "explosion_radius" ) self.explosion_delay = keys.ability:GetSpecialValueFor( "explosion_delay" ) self.base_damage = keys.ability:GetAbilityDamage() self.damage_type = keys.ability:GetAbilityDamageType() AddFOWViewer(keys.caster:GetTeamNumber(), keys.target_points[1], self.explosion_radius, self.explosion_delay, false) local caster_ap = keys.caster:GetAbilityPower() self.final_damage = self.base_damage + (caster_ap * self.ap_scaling) end function OnHit( keys ) local damage = { victim = keys.target, attacker = keys.caster, damage = self.final_damage, damage_type = self.damage_type, ability = keys.ability, } ApplyDamage( damage ) end
---@meta ---게임 클라이언트를 스크립트로 조작할 수 있게 해주는 클래스입니다. ---@class Game.Scripts.ScriptClient ---@field appVersion string 현재 유저의 네코랜드 앱 버전 ---@field changeSlot Game.Scripts.ScriptChangeSlot 게임 화면 내의 교체 슬롯 ---@field controller Game.Scripts.ScriptController 게임 화면 내의 방향키 패드(D-Pad) 객체 ---@field field Game.Scripts.ScriptField 현재 내 플레이어가 접속해 있는 필드 객체 ---@field frameRate number ---@field height integer 게임 화면의 세로 크기 (단위: 픽셀) ---@field id string 접속한 게임의 고유 UUID ---@field myPlayerUnit Game.Scripts.ScriptMyPlayerUnit ---@field onTick Game.Scripts.ScriptEventPublisher 매 프레임마다 호출되는 이벤트입니다 ---@field quickSlots Game.Scripts.ScriptChangeSlot[] 게임 화면 내의 퀵 슬롯 목록 ---@field screenHeight integer 세로 해상도 크기 ---@field screenWidth integer 가로 해상도 크기 ---@field targetFrameRate integer { get; set; } ---@field width integer 게임 화면의 가로 크기 (단위: 픽셀) Client = {} --문자열 변수로 Lua 스크립트를 실행합니다. ---@param text string 스크립트 내용 ---@param context table 컨텍스트 테이블 ---@return string value Lua 스크립트 호출 후의 리턴 값 Client.DoString = function(text, context) end --서버로 Topic에 대한 이벤트를 보냅니다 ---@param topic? string 보낼 Topic ---@vararg System.Object[]? 함께보낼 인자들 Client.FireEvent = function(topic, ...) end --데이터베이스의 애니메이션 정보를 가져옵니다 ---@param id integer 애니메이션ID ---@return TGameAnimation TGameAnimation 데이터베이스의 애니메이션 정보 Client.GetAnimation = function(id) end --데이터베이스의 상태(버프) 정보를 가져옵니다 ---@param id integer 상태(버프)ID ---@return TGameBuff TGameBuff 데이터베이스의 상태(버프) 정보 Client.GetBuff = function(id) end -- 데이터베이스의 캐릭터 정보를 가져옵니다 ---@param id integer 캐릭터ID ---@return TGameCharacter TGameCharacter 데이터베이스 캐릭터 정보 Client.GetCharacter = function(id) end -- 데이터베이스의 공용 이벤트 정보를 가져옵니다 ---@param id integer 캐릭터ID ---@return TGameCommonEvent TGameCommonEvent 공용 이벤트 정보 Client.GetCommonEvent = function(id) end -- 그림 파일의 이름을 가져옵니다 ---@param imageID string 이름을 가져올 대상 이미지의 ID ---@return string imageName 이미지의 이름(경로) Client.GetImageName = function(imageID) end -- 데이터베이스의 아이템 정보를 가져옵니다 ---@param id number 아이템 ID ---@return TGameItem TGameItem 데이터베이스 아이템 정보 Client.GetItem = function(id) end -- 데이터베이스의 직업 정보를 가져옵니다 ---@param id number 직업 ID ---@return TGameJob TGameJob 데이터베이스의 직업 정보 Client.GetJob = function(id) end -- 맵 데이터 정보를 가져옵니다 ---@param id number 맵 ID ---@param parent? TGameMapStub 선택된 맵의 부모 (기본: nil) ---@return TGameMapStub TGameMapStub 맵 데이터 정보 Client.GetMap = function(id, parent) end -- 데이터베이스의 몬스터 정보를 가져옵니다 ---@param id number 몬스터 ID ---@return TGameMonster TGameMonster 데이터베이스의 몬스터 정보 Client.GetMonster = function(id) end --* 특정 레이아웃 페이지를 가져옵니다. -- 하위 컨트롤들은 로드되지 않습니다. 이미 로드된 페이지 또한 가져옵니다. ---@param pageName string 가져올 페이지의 이름 ---@return Game.Scripts.ScriptPage ScriptPage 가져온 페이지 Client.GetPage = function(pageName) end --* 데이터베이스의 스킬 정보를 가져옵니다 ---@param id integer 스킬 ID ---@return TGameSkill TGameSkill 데이터베이스의 스킬 정보 Client.GetSkill = function(id) end --* 데이터베이스의 시스템 글자 정보를 가져옵니다 ---@return TGameStrings TGameStrings 데이터베이스 시스템 글자 정보 Client.GetStrings = function() end --* 데이터베이스의 타일셋 정보를 가져옵니다 ---@param id integer 타일셋 ID ---@return TGameTileset TGameTileset 데이터베이스의 타일셋 정보 Client.GetTileset = function(id) end --* 특정 Topic에 대한 이벤트 콜백을 가져옵니다. -- (클라이언트에서 보낸 특정 Topic에 대한 이벤트를 처리합니다) ---@param topic string 보낼 Topic ---@return Game.Scripts.ScriptEventPublisher ScriptEventPublisher Client.GetTopic = function(topic) end --* Http GET 요청을 보내고, 데이터를 가져옵니다 ---@param url string URL주소 ---@param callback Closure ---@return boolean resolve Client.HttpGet = function(url, callback) end --* Http POST 요청을 보내고, 데이터를 가져옵니다 ---@param url string URL주소 ---@param data table ---@param callback Closure ---@return boolean resolve Client.HttpPost = function(url, data, callback) end --* 모든 실행중인 스크립트들을 중지하고 다시 로드합니다 Client.InitScript = function() end --* 가방 UI 팝업이 열려있는지 확인합니다 Client.IsShowBag = function() end --* 도감 UI 팝업이 열려있는지 확인합니다 Client.IsShowCollection = function() end --* 파티 UI 팝업이 열려있는지 확인합니다 Client.IsShowParty = function() end --* 스킬 UI 팝업이 열려있는지 확인합니다 Client.IsShowSkills = function() end --* 스탯 UI 팝업이 열려있는지 확인합니다 Client.IsShowStats = function() end --* 특정 레이아웃 페이지를 로드합니다. -- -- *이미 로드된 페이지는 다시 로드됩니다. 페이지가 로드될 때 하위 컨트롤들 또한 함께 로드됩니다* ---@param pageName string 로드할 페이지의 이름 ---@return Game.Scripts.ScriptPage ScriptPage 로드한 페이지 Client.LoadPage = function(pageName) end --* 지정한 URL을 엽니다 ---@param url string URL주소 Client.OpenURL = function(url) end --* 게임을 종료합니다 Client.Quit = function() end --* 다른 게임을 실행합니다 Client.RunGame = function() end ---* 일정 시간 후에, 정해진 함수를 실행합니다 ---@param callback Closure 실행할 함수 ---@param t number 실행시간까지의 대기시간 (초) Client.RunLater = function(callback, t) end ---* 기본적인 알림 팝업을 표시합니다 ---@param text string 사용자에게 보여줄 문구 ---@param callback Closure 팝업이 닫혔을 때 호출될 함수 Client.ShowAlert = function(text, callback) end ---* 가방 UI를 켜거나 끕니다 ---@param show boolean 표시 여부 Client.ShowBag = function(show) end ---* 도감을 켜거나 끕니다 ---@param show boolean 표시 여부 Client.ShowCollection = function(show) end ---* 화면 하단에 위치한 경험치 바를 켜거나 끕니다 ---@param show boolean 표시 여부 Client.ShowEXPBar = function(show) end ---* 파티창의 켜거나 끕니다 ---@param show boolean 표시 여부 Client.ShowParty = function(show) end ---* 스킬창을 켜거나 끕니다 ---@param show boolean 표시 여부 Client.ShowSkills = function(show) end ---* 스탯창을 켜거나 끕니다 ---@param show boolean 표시 여부 Client.ShowStats = function(show) end ---* 상단 패널 (HP 바, MP 바, 버프 패널 등)을 켜거나 끕니다 ---@param show boolean 표시 여부 Client.ShowTopUI = function(show) end --* 예, 아니오의 선택지가 있는 알림 팝업을 표시합니다 ---@param text string 사용자에게 보여줄 문구 ---@param callback Closure 팝업이 닫혔을때 호출될 함수 Client.ShowYesNoAlert = function(text, callback) end
require("@vue/compiler-core") require("@vue/compiler-core/ErrorCodes") require("compiler-dom/src/errors/DOMErrorCodes") function createDOMCompilerError(code, loc) -- [ts2lua]lua中0和空字符串也是true,此处__DEV__ or not __BROWSER__需要确认 return createCompilerError(code, loc, (__DEV__ or not __BROWSER__ and {DOMErrorMessages} or {undefined})[1]) end local DOMErrorMessages = {DOMErrorCodes.X_V_HTML_NO_EXPRESSION=, DOMErrorCodes.X_V_HTML_WITH_CHILDREN=, DOMErrorCodes.X_V_TEXT_NO_EXPRESSION=, DOMErrorCodes.X_V_TEXT_WITH_CHILDREN=, DOMErrorCodes.X_V_MODEL_ON_INVALID_ELEMENT=, DOMErrorCodes.X_V_MODEL_ARG_ON_ELEMENT=, DOMErrorCodes.X_V_MODEL_ON_FILE_INPUT_ELEMENT=, DOMErrorCodes.X_V_MODEL_UNNECESSARY_VALUE=, DOMErrorCodes.X_V_SHOW_NO_EXPRESSION=, DOMErrorCodes.X_TRANSITION_INVALID_CHILDREN=}
return { HOOK_ENTITY_TELEPORT = { CalledWhen = "Any entity teleports. Plugin may refuse teleport.", DefaultFnName = "OnEntityTeleport", -- also used as pagename Desc = [[ This function is called in each server tick for each {{cEntity|Entity}} that has teleported. Plugins may refuse the teleport. ]], Params = { { Name = "Entity", Type = "{{cEntity}}", Notes = "The entity who has teleported. New position is set in the object after successfull teleport" }, { Name = "OldPosition", Type = "{{Vector3d}}", Notes = "The old position." }, { Name = "NewPosition", Type = "{{Vector3d}}", Notes = "The new position." }, }, Returns = [[ If the function returns true, teleport is prohibited.</p> <p> If the function returns false or no value, other plugins' callbacks are called and finally the new position is permanently stored in the cEntity object.</p> ]], }, -- HOOK_ENTITY_TELEPORT }
--[[ NPCAI - Server by: standardcombo v0.9.1 Logical state machine for an enemy NPC. Works in conjunction with NPCAttackServer. Will walk over terrain and any objects to get to its objective. To mark objects as not walkable, add to each one a custom property called "Walkable" of type boolean and set to false. --]] -- Component dependencies local MODULE = require( script:GetCustomProperty("ModuleManager") ) require ( script:GetCustomProperty("NPCManager") ) function NPC_MANAGER() return MODULE.Get("standardcombo.NPCKit.NPCManager") end function NAV_MESH() return _G.NavMesh end local ROOT = script:GetCustomProperty("Root"):WaitForObject() local ROTATION_ROOT = script:GetCustomProperty("RotationRoot"):WaitForObject() local COLLIDER = script:GetCustomProperty("Collider"):WaitForObject() local TRIGGER = script:GetCustomProperty("Trigger"):GetObject() local ATTACK_COMPONENT = script:GetCustomProperty("AttackComponent"):WaitForObject() local MOVE_SPEED = ROOT:GetCustomProperty("MoveSpeed") or 400 local TURN_SPEED = ROOT:GetCustomProperty("TurnSpeed") or 2 local LOGICAL_PERIOD = ROOT:GetCustomProperty("LogicalPeriod") or 0.5 local RETURN_TO_SPAWN = ROOT:GetCustomProperty("ReturnToSpawn") local VISION_HALF_ANGLE = ROOT:GetCustomProperty("VisionHalfAngle") or 0 local VISION_RADIUS = ROOT:GetCustomProperty("VisionRadius") or 2500 local HEARING_RADIUS = ROOT:GetCustomProperty("HearingRadius") or 1000 local SEARCH_BONUS_VISION = ROOT:GetCustomProperty("SearchBonusVision") or 5000 local SEARCH_DURATION = ROOT:GetCustomProperty("SearchDuration") or 6 local POSSIBILITY_RADIUS = ROOT:GetCustomProperty("PossibilityRadius") or 600 local CHASE_RADIUS = ROOT:GetCustomProperty("ChaseRadius") or 3500 local ATTACK_RANGE = ROOT:GetCustomProperty("AttackRange") or 1500 local ATTACK_CAST_TIME = ROOT:GetCustomProperty("AttackCast") or 0.5 local ATTACK_RECOVERY_TIME = ROOT:GetCustomProperty("AttackRecovery") or 1.5 local ATTACK_COOLDOWN = ROOT:GetCustomProperty("AttackCooldown") or 0 local OBJECTIVE_THRESHOLD_DISTANCE_SQUARED = 900 MAX_HEALTH = ROOT:GetCustomProperty("CurrentHealth") local PATHING_STEP = MOVE_SPEED * LOGICAL_PERIOD + 10 local PATHING_STEP_SQUARED = PATHING_STEP * PATHING_STEP local RAY_DISTANCE_FROM_GROUND = COLLIDER:GetPosition().z + 400 local RAY_DISTANCE_DOWN_VECTOR = Vector3.New(0, 0, -900) local VISION_RADIUS_SQUARED = VISION_RADIUS * VISION_RADIUS local HEARING_RADIUS_SQUARED = HEARING_RADIUS * HEARING_RADIUS local SEARCH_RADIUS_SQUARED = (VISION_RADIUS + SEARCH_BONUS_VISION) * (VISION_RADIUS + SEARCH_BONUS_VISION) local CHASE_RADIUS_SQUARED = CHASE_RADIUS * CHASE_RADIUS local ATTACK_RANGE_SQUARED = ATTACK_RANGE * ATTACK_RANGE local SPAWN_POSITION = ROOT:GetWorldPosition() local DEAD_1_DURATION = 4 local DEAD_2_DURATION = 6 local STATE_SLEEPING = 0 local STATE_ENGAGING = 1 local STATE_ATTACK_CAST = 2 local STATE_ATTACK_RECOVERY = 3 local STATE_PATROLLING = 4 local STATE_LOOKING_AROUND = 5 local STATE_DEAD_1 = 6 local STATE_DEAD_2 = 7 local STATE_DISABLED = 8 local currentState = STATE_SLEEPING local stateTime = 0 local logicStepDelay = 0 local target = nil local moveObjective = nil local nextMoveObjective = nil local stepDestination = SPAWN_POSITION local navMeshPath = nil local searchStartPosition = nil local searchEndPosition = nil local searchTimeElapsed = -1 local searchPrecision = 1 local attackCooldown = 0 local temporaryVisionAngle = nil local temporaryVisionRadius = nil local temporaryHearingRadius = nil function SetState(newState) --print("NewState = " .. newState) if (newState == STATE_SLEEPING) then ROTATION_ROOT:StopRotate() elseif (newState == STATE_ENGAGING) then --print("target = " .. tostring(target) .. ", moveSpeed = " .. tostring(MOVE_SPEED) .. ", attackRange = " .. ATTACK_RANGE) if (not IsWithinRangeSquared(target, ATTACK_RANGE_SQUARED)) then local targetPosition = target:GetWorldPosition() StepTowards(targetPosition) end if navMeshPath and #navMeshPath > 1 then local pos = ROOT:GetWorldPosition() local direction = navMeshPath[2] - pos local r = Rotation.New(direction, Vector3.UP) ROTATION_ROOT:RotateTo(r, GetRotateToTurnSpeed(), false) else ROTATION_ROOT:LookAtContinuous(target, true, TURN_SPEED) end elseif (newState == STATE_PATROLLING) then local targetPosition = moveObjective StepTowards(targetPosition) local pos = ROOT:GetWorldPosition() local direction = targetPosition - pos if navMeshPath and stepDestination then direction = stepDestination - pos end local r = Rotation.New(direction, Vector3.UP) ROTATION_ROOT:RotateTo(r, GetRotateToTurnSpeed(), false) elseif (newState == STATE_LOOKING_AROUND) then -- elseif (newState == STATE_DEAD_1) then ROOT:StopMove() ROTATION_ROOT:StopRotate() SetCollision(false) elseif (newState == STATE_DEAD_2) then ROOT:MoveTo(ROOT:GetWorldPosition() + Vector3.New(0, 0, -500), DEAD_2_DURATION) elseif (newState == STATE_DISABLED) then ROOT:Destroy() end currentState = newState stateTime = 0 if Object.IsValid(ROOT) then ROOT:SetNetworkedCustomProperty("CurrentState", newState) end end function Tick(deltaTime) stateTime = stateTime + deltaTime logicStepDelay = logicStepDelay - deltaTime attackCooldown = attackCooldown - deltaTime if (searchTimeElapsed >= 0) then searchTimeElapsed = searchTimeElapsed + deltaTime end if (currentState == STATE_ATTACK_CAST or currentState == STATE_ATTACK_RECOVERY) and not IsObjectAlive(target) then target = nil EngageNearest() if (not target) then ResumePatrol() end elseif currentState == STATE_ATTACK_CAST and stateTime >= ATTACK_CAST_TIME then ExecuteAttack() attackCooldown = ATTACK_COOLDOWN SetState(STATE_ATTACK_RECOVERY) elseif currentState == STATE_ATTACK_RECOVERY and stateTime >= ATTACK_RECOVERY_TIME then SetState(STATE_ENGAGING) end if currentState == STATE_ENGAGING then if (not IsObjectAlive(target)) then target = nil elseif IsWithinRangeSquared(target, ATTACK_RANGE_SQUARED) then if attackCooldown <= 0 then SetState(STATE_ATTACK_CAST) end else UpdateMovement(deltaTime) end elseif currentState == STATE_PATROLLING then UpdateMovement(deltaTime) elseif (currentState == STATE_DEAD_1 and stateTime >= DEAD_1_DURATION) then SetState(STATE_DEAD_2) elseif (currentState == STATE_DEAD_2 and stateTime >= DEAD_2_DURATION) then SetState(STATE_DISABLED) end if logicStepDelay <= 0 then logicStepDelay = LOGICAL_PERIOD if currentState == STATE_SLEEPING then EngageNearest() elseif currentState == STATE_ENGAGING then local chaseRadiusSquared = CHASE_RADIUS_SQUARED if (searchTimeElapsed >= 0 and searchTimeElapsed < SEARCH_DURATION * 4) then chaseRadiusSquared = SEARCH_RADIUS_SQUARED else searchTimeElapsed = -1 end --print("chaseRadiusSquared = " .. chaseRadiusSquared .. ", searchTimeElapsed = " .. searchTimeElapsed) if IsWithinRangeSquared(target, chaseRadiusSquared) then SetState(STATE_ENGAGING) else EngageNearest() if (not target) then --print("ResumePatrol 1") ResumePatrol() end end elseif currentState == STATE_PATROLLING then local pos = ROOT:GetWorldPosition() local delta = pos - moveObjective delta.z = 0 if (delta.sizeSquared < OBJECTIVE_THRESHOLD_DISTANCE_SQUARED) then --print("OBJECTIVE REACHED") if nextMoveObjective then moveObjective = nextMoveObjective nextMoveObjective = nil SetState(STATE_PATROLLING) elseif RETURN_TO_SPAWN and moveObjective ~= SPAWN_POSITION then moveObjective = SPAWN_POSITION SetState(STATE_PATROLLING) else SetState(STATE_SLEEPING) end else EngageNearest() if (not target) then SetState(STATE_PATROLLING) end end elseif currentState == STATE_LOOKING_AROUND then if (searchTimeElapsed >= SEARCH_DURATION) then --print("ResumePatrol 2") ResumePatrol() else EngageNearest() if (not target) then DoLookAround() end end end end UpdateTemporaryProperties(deltaTime) end function ResumePatrol() --print("ResumePatrol") target = nil if moveObjective then SetState(STATE_PATROLLING) elseif RETURN_TO_SPAWN then SetObjective(SPAWN_POSITION) else SetState(STATE_SLEEPING) end end function SetObjective(pos) --print("SetObjective = " .. tostring(pos)) if (currentState == STATE_PATROLLING) then nextMoveObjective = pos elseif (not target) then moveObjective = pos SetState(STATE_PATROLLING) end end function ExecuteAttack() if ATTACK_COMPONENT then ATTACK_COMPONENT.context.Attack(target) end end function StepTowards(targetPosition) local pos = ROOT:GetWorldPosition() if NAV_MESH() then navMeshPath = NAV_MESH().FindPath(pos, targetPosition) if navMeshPath and #navMeshPath > 1 then table.remove(navMeshPath, 1) stepDestination = navMeshPath[1] return end end navMeshPath = nil -- No NavMesh available, fallback -- Calculate step destination local direction = targetPosition - pos if (direction.sizeSquared > PATHING_STEP_SQUARED) then direction = direction:GetNormalized() * PATHING_STEP end local rayStart = pos + direction rayStart.z = rayStart.z + RAY_DISTANCE_FROM_GROUND --print("pos = " .. tostring(pos) .. ", targetPosition = " .. tostring(targetPosition) .. ", rayStart = " .. tostring(rayStart)) local hitResult = nil repeat local rayEnd = rayStart + RAY_DISTANCE_DOWN_VECTOR hitResult = World.Raycast(rayStart, rayEnd, {ignorePlayers = true}) local isWalkable if hitResult then isWalkable = IsObjectWalkable(hitResult.other) if (not isWalkable) then rayStart = hitResult:GetImpactPosition() + Vector3.New(0,0,-0.5) end end until hitResult == nil or hitResult.other == nil or isWalkable if hitResult then --print("HitResult.other = " .. tostring(hitResult.other)) local groundPos = hitResult:GetImpactPosition() stepDestination = groundPos else stepDestination = targetPosition end end local overlappingObjects = {} function UpdateMovement(deltaTime) local pos = ROOT:GetWorldPosition() -- Test overlap against other objects and adjust if TRIGGER then local overlaps = overlappingObjects for i,other in ipairs(overlaps) do local triggerPos = TRIGGER:GetWorldPosition() local otherPos = other:GetWorldPosition() local v = triggerPos - otherPos v.z = 0 local distance = v.size local radii = 50 * (other:GetWorldScale().y + TRIGGER:GetWorldScale().y) local removeAmount = radii - distance if (removeAmount > 0) then v = v / distance * removeAmount * 0.5 pos = pos + v ROOT:SetWorldPosition(pos) end end end -- Move forward if navMeshPath then local moveAmount = MOVE_SPEED * deltaTime while moveAmount > 0 do stepDestination = navMeshPath[1] local moveV = stepDestination - pos local distance = moveV.size if (distance <= moveAmount) then pos = stepDestination table.remove(navMeshPath, 1) if #navMeshPath > 0 then moveAmount = moveAmount - distance else navMeshPath = nil moveAmount = 0 end else pos = pos + moveV / distance * moveAmount moveAmount = 0 end end else local moveV = stepDestination - pos local distance = moveV.size local moveAmount = MOVE_SPEED * deltaTime if (distance <= moveAmount) then pos = stepDestination else pos = pos + moveV / distance * moveAmount end end ROOT:SetWorldPosition(pos) end function EngageNearest() target = nil local enemy = FindNearestEnemy() if enemy then target = enemy SetState(STATE_ENGAGING) end end function FindNearestEnemy() local myPos = ROOT:GetWorldPosition() local forwardVector = ROTATION_ROOT:GetWorldRotation() * Vector3.FORWARD local myTeam = GetTeam() local nearestEnemy = nil local nearestDistSquared = 9999999999 -- Players for _,enemy in ipairs(Game.GetPlayers()) do if (enemy.team ~= myTeam and not enemy.isDead) then local canSee,distSquared = CanSeeEnemy(enemy, myPos, forwardVector, nearestDistSquared) if canSee then nearestDistSquared = distSquared nearestEnemy = enemy --print("Distance to enemy = " .. tostring(math.sqrt(nearestDistSquared))) end end end -- Other NPCs local enemyNPCs = NPC_MANAGER().GetEnemies(myTeam) for _,enemy in ipairs(enemyNPCs) do if enemy.context.IsAlive() then local canSee,distSquared = CanSeeEnemy(enemy, myPos, forwardVector, nearestDistSquared) if canSee then nearestDistSquared = distSquared nearestEnemy = enemy --print("Distance to enemy = " .. tostring(math.sqrt(nearestDistSquared))) end end end return nearestEnemy end function CanHear(noisePos) local myPos = ROOT:GetWorldPosition() local delta = noisePos - myPos local distSquared = delta.sizeSquared if (distSquared < GetHearingRadiusSquared()) then return true end return false end function CanSeeEnemy(enemy, myPos, forwardVector, nearestDistSquared) local enemyPos = enemy:GetWorldPosition() local delta = enemyPos - myPos local distSquared = delta.sizeSquared if (distSquared > nearestDistSquared) then return false, distSquared end local canSeeFromDistance = (distSquared <= GetVisionRadiusSquared()) -- Is searching if (not canSeeFromDistance and currentState == STATE_LOOKING_AROUND and distSquared < SEARCH_RADIUS_SQUARED and SEARCH_RADIUS_SQUARED > GetVisionRadiusSquared()) then local p = (distSquared - GetVisionRadiusSquared()) / (SEARCH_RADIUS_SQUARED - GetVisionRadiusSquared()) p = CoreMath.Lerp(0.5 / searchPrecision, 1, p) local rng = math.random() if (rng >= p) then canSeeFromDistance = true end --print("rng = " .. rng .. ", p = " .. p) end -- Angle vision in front if (canSeeFromDistance and GetVisionHalfAngle() > 0 and GetVisionHalfAngle() < 360) then local distance = math.sqrt(distSquared) local directionToEnemy = delta / distance local angle = Angle(directionToEnemy, forwardVector) if (angle > GetVisionHalfAngle()) then canSeeFromDistance = false end end -- Test if there is something obstructing the view. If searching for the enemy ignore this constraint local ENEMY_RADIUS = 150 -- TODO if (canSeeFromDistance and (currentState ~= STATE_LOOKING_AROUND or (searchEndPosition - enemyPos).size > 400) and distSquared > ENEMY_RADIUS * ENEMY_RADIUS) then local rayStart = script:GetWorldPosition() local rayEnd = enemyPos - delta:GetNormalized() * ENEMY_RADIUS local myTeam = GetTeam() local hitResult = World.Raycast(rayStart, rayEnd, {ignorePlayers = true, ignoreTeams = myTeam}) if hitResult then canSeeFromDistance = false --CoreDebug.DrawLine(rayStart, rayEnd, {duration = 1, color = Color.RED}) else --CoreDebug.DrawLine(rayStart, rayEnd, {duration = 1, color = Color.WHITE}) end end --print("dist = " .. tostring(math.sqrt(distSquared)) .. ", " .. tostring(distSquared) .. ", " .. tostring(GetVisionRadiusSquared())) return canSeeFromDistance, distSquared end function Angle(normV1, normV2) local value = normV1 .. normV2 value = CoreMath.Clamp(value, -1, 1) return math.acos(value) * 57.29578 end function IsWithinRangeSquared(enemy, rangeSquared) if Object.IsValid(enemy) then local pos = ROOT:GetWorldPosition() local enemyPos = enemy:GetWorldPosition() local delta = pos - enemyPos return (delta.sizeSquared < rangeSquared) end return false end function GetVisionHalfAngle() if temporaryVisionAngle ~= nil then return temporaryVisionAngle.value end return VISION_HALF_ANGLE end function GetVisionRadiusSquared() if temporaryVisionRadius ~= nil then return temporaryVisionRadius.value end return VISION_RADIUS_SQUARED end function GetHearingRadiusSquared() if temporaryHearingRadius ~= nil then return temporaryHearingRadius.value end return HEARING_RADIUS_SQUARED end function SetTemporaryVisionHalfAngle(angle, duration) temporaryVisionAngle = {value = angle, timeRemaining = duration} end function SetTemporaryVisionRadius(radius, duration) temporaryVisionRadius = {value = radius, timeRemaining = duration} end function SetTemporaryHearingRadius(radius, duration) temporaryHearingRadius = {value = radius, timeRemaining = duration} end function UpdateTemporaryProperties(deltaTime) temporaryVisionAngle = UpdateTemporary(temporaryVisionAngle, deltaTime) temporaryVisionRadius = UpdateTemporary(temporaryVisionRadius, deltaTime) temporaryHearingRadius = UpdateTemporary(temporaryHearingRadius, deltaTime) end function UpdateTemporary(property, deltaTime) if property ~= nil then property.timeRemaining = property.timeRemaining - deltaTime if property.timeRemaining <= 0 then return nil end end return property end function SetCollision(enabled) if enabled then COLLIDER.collision = Collision.INHERIT else COLLIDER.collision = Collision.FORCE_OFF end end function IsObjectAlive(obj) if Object.IsValid(obj) then if obj:IsA("Player") then return (not obj.isDead) end if obj.context and obj.context.IsAlive then return obj.context.IsAlive() end end return false end function IsAlive() return currentState < STATE_DEAD_1 end function OnObjectDamaged(id, prevHealth, dmgAmount, impactPosition, impactRotation, sourceObject) if (currentState == STATE_SLEEPING or currentState == STATE_PATROLLING or currentState == STATE_LOOKING_AROUND) then if Object.IsValid(sourceObject) and GetObjectTeam(sourceObject) ~= GetTeam() and IsObjectAlive(sourceObject) and CanHear(impactPosition) then Search(impactPosition, sourceObject:GetWorldPosition()) end end end function Search(fromPos, toPos) --print("Search") searchStartPosition = fromPos searchEndPosition = toPos searchTimeElapsed = 0 if (currentState == STATE_LOOKING_AROUND) then searchPrecision = searchPrecision * 2 else searchPrecision = 1 end DoLookAround() SetState(STATE_LOOKING_AROUND) end function DoLookAround() local t = 1 if (SEARCH_DURATION > 0) then t = searchTimeElapsed / SEARCH_DURATION end local searchPos = Vector3.Lerp(searchStartPosition, searchEndPosition, t) local area = math.ceil(POSSIBILITY_RADIUS / searchPrecision) searchPos.x = searchPos.x + math.random(-area, area) searchPos.y = searchPos.y + math.random(-area, area) local myPos = ROOT:GetWorldPosition() local forward = searchPos - myPos local rot = Rotation.New(forward, Vector3.UP) ROTATION_ROOT:RotateTo(rot, GetRotateToTurnSpeed(), false) end function GetRotateToTurnSpeed() local turnTime = 0.25 if TURN_SPEED > 0 then turnTime = 1 / TURN_SPEED end return turnTime end function IsObjectWalkable(object) if object == nil then return false end local isWalkable, hasProperty = object:GetCustomProperty("Walkable") if (hasProperty and not isWalkable) then return false end return true end function OnObjectDestroyed(id) if IsAlive() then local myId = ROOT:GetCustomProperty("ObjectId") if (myId == id) then SetState(STATE_DEAD_1) end end end local damagedListener = Events.Connect("ObjectDamaged", OnObjectDamaged) local destroyedListener = Events.Connect("ObjectDestroyed", OnObjectDestroyed) function Cleanup() --print("Cleanup()") if damagedListener then damagedListener:Disconnect() damagedListener = nil end if destroyedListener then destroyedListener:Disconnect() destroyedListener = nil end end function OnDestroyed(obj) --print("OnDestroyed()") Cleanup() end ROOT.destroyEvent:Connect(OnDestroyed) function OnBeginOverlap(whichTrigger, other) if other == COLLIDER then return end if other:IsA("StaticMesh") then if not IsObjectWalkable(other) then table.insert(overlappingObjects, other) end end end function OnEndOverlap(whichTrigger, other) for i,obj in ipairs(overlappingObjects) do if other == obj then table.remove(overlappingObjects, i) break end end end if TRIGGER then TRIGGER.beginOverlapEvent:Connect(OnBeginOverlap) TRIGGER.endOverlapEvent:Connect(OnEndOverlap) end function GetTeam() return ROOT:GetCustomProperty("Team") end function GetObjectTeam(object) if object.team ~= nil then return object.team end local templateRoot = object:FindTemplateRoot() if templateRoot then return templateRoot:GetCustomProperty("Team") end return nil end function OnPropertyChanged(object, propertyName) if (propertyName == "Team") then HandleTeamChanged() end end function HandleTeamChanged() COLLIDER.team = GetTeam() end HandleTeamChanged() ROOT.networkedPropertyChangedEvent:Connect(OnPropertyChanged) NPC_MANAGER().Register(script) NPC_MANAGER().RegisterCollider(script, COLLIDER)
#! /usr/bin/lua require( "common" ) Items = data( "items" ) Shots = data( "shots" ) local Dir = "weapons" local Names, NamesCount = loadNames( Dir .. "/namesGuns.txt" ) local Types = { "lbg", "hbg", "bow", } local Bases = { lbg = { name = { hgg = "Light Bowguns" } }, hbg = { name = { hgg = "Heavy Bowguns" } }, bow = { name = { hgg = "Bows" } }, } local Reloads = { VerySlow = "vslow", Slow = "slow", Normal = "normal", Fast = "fast", VeryFast = "vfast", } local Drifts = { None = "None", [ "???" ] = "???", } local Recoils = { Heavy = "heavy", Moderate = "moderate", Light = "light", Strong = "strong", } local Elements = { "fire", "water", "thunder", "ice", "dragon", "poison", "paralyze", "sleep", } function isElement( element ) for _, elem in ipairs( Elements ) do if elem == element then return true end end return false end local BowRains = { Focused = "focused", Spread = "spread", Blast = "blast", } local BowCoatings = { "power", "poison", "paralyze", "sleep", "razor", "paint", "fatigue", } local CoatingsPattern = "^" .. ( "([YN])" ):rep( table.getn( BowCoatings ) ) .. "$" local ChargeTypes = { R = "rapid", P = "pierce", S = "scatter", } local MaxSlots = 3 local LastShot = 1 -- FSM controlling how each line is parsed -- each action returns the key of the next state local Actions = { init = function( line, weapon ) assert( Names[ line ], "bad name: " .. line ) Names[ line ] = nil weapon.name = { hgg = line } return "attack" end, attack = function( line, weapon ) weapon.attack = tonumber( line ) return "special" end, special = function( line, weapon ) local rarity = line:match( "^R(%d)$" ) if rarity then weapon.rarity = tonumber( rarity ) return "affinity" end local defense = line:match( "^Def (%d+)$" ) if defense then weapon.defense = tonumber( defense ) return "special" end local element, elemAttack = line:match( "^(%a+) (%d+)$" ) if element then element = element:lower() assert( isElement( element ), "bad element in " .. weapon.name.hgg .. ": " .. line ) weapon.element = element weapon.elemAttack = elemAttack return "special" end assert( BowRains[ line ], "bad special in " .. weapon.name.hgg .. ": " .. line ) weapon.rain = BowRains[ line ] return "special" end, affinity = function( line, weapon ) local success, _, affinity = line:find( "^(-?%d+)%%$" ) assert( success, "bad affinity in " .. weapon.name.hgg .. ": " .. line ) weapon.affinity = tonumber( affinity ) return "slots" end, slots = function( line, weapon ) local slots = 0 for i = 1, MaxSlots do if line:sub( i, i ) == "O" then slots = slots + 1 else break end end weapon.slots = slots return weapon.rain and "improve" or "reload" end, reload = function( line, weapon ) local reload = Reloads[ line ] assert( reload, "bad reload in " .. weapon.name.hgg .. ": " .. line ) weapon.reload = reload return "drift" end, drift = function( line, weapon ) local drift = Drifts[ line ] assert( drift, "bad drift in " .. weapon.name.hgg .. ": " .. line ) weapon.drift = drift return "recoil" end, recoil = function( line, weapon ) local recoil = Recoils[ line ] assert( recoil, "bad recoil in " .. weapon.name.hgg .. ": " .. line ) weapon.recoil = recoil return "improve" end, improve = function( line, weapon ) if line:sub( -1 ) == "z" then weapon.price = tonumber( line:sub( 1, -2 ) ) if not weapon.improve then weapon.price = weapon.price / 1.5 end return "create" end local id, count = parseItem( line ) if not id then weapon.description = line return "scraps" end assert( weapon.improve, "bad improve in " .. weapon.name.hgg .. ": " .. line ) table.insert( weapon.improve.materials, { id = id, count = count } ) return "improve" end, create = function( line, weapon ) local id, count = parseItem( line ) if not id then weapon.description = line return "scraps" end if not weapon.create then weapon.create = { } end table.insert( weapon.create, { id = id, count = count } ) return "create" end, scraps = function( line, weapon ) local id, count = parseItem( line ) if not id then if weapon.rain then local chargeType, chargeLevel = line:match( "^(%u)(%d)$" ) assert( chargeType, "bad charge in " .. weapon.name.hgg .. ": " .. line ) weapon.charges = { { type = ChargeTypes[ chargeType ], level = tonumber( chargeLevel ), } } return "charges" else local success, _, l1, l2, l3 = line:find( "^([%d!WMSG]+) ([%d!WMSG]+) ([%d!WMSG]+)$" ) assert( success, "bad scrap in " .. weapon.name.hgg .. ": " .. line ) local success, _, clip, l1RapidNum, l1RapidRecoil = l1:find( "^(%d+)!(%d)(%u)$" ) if success then l1 = clip else local success, _, clip = l1:find( "^(%d+)!$" ) if success then l1 = clip l1siege = true end end local success, _, clip, l2RapidNum, l2RapidRecoil = l2:find( "^(%d+)!(%d)(%u)$" ) if success then l2 = clip else local success, _, clip = l2:find( "^(%d+)!$" ) if success then l2 = clip l2siege = true end end local success, _, clip, l3RapidNum, l3RapidRecoil = l3:find( "^(%d+)!(%d)(%u)$" ) if success then l3 = clip else local success, _, clip = l3:find( "^(%d+)!$" ) if success then l3 = clip l3siege = true end end -- lua automatically drops nils from tables so the result is clean weapon.shots = { { { clip = tonumber( l1 ), rapidClip = tonumber( l1RapidNum ), rapidRecoil = l1RapidRecoil, siege = l1siege }, { clip = tonumber( l2 ), rapidClip = tonumber( l2RapidNum ), rapidRecoil = l2RapidRecoil, siege = l2siege }, { clip = tonumber( l3 ), rapidClip = tonumber( l3RapidNum ), rapidRecoil = l3RapidRecoil, siege = l3siege }, } } return "shots" end end if not weapon.scraps then weapon.scraps = { } end table.insert( weapon.scraps, { id = id, count = count } ) return "scraps" end, -- i hate guns shots = function( line, weapon ) LastShot = LastShot + 1 assert( Shots[ LastShot ], "bad shot in " .. weapon.name.hgg .. ": " .. line .. " (" .. LastShot .. ")" ) local success, _, l1, l2, l3 = line:find( ( "([%d!WMSG]+) " ):rep( Shots[ LastShot ].levels ):sub( 1, -2 ) ) assert( success, "bad shot in " .. weapon.name.hgg .. ": " .. line .. " (" .. Shots[ LastShot ].name.hgg .. ")" ) local success, _, clip, l1RapidNum, l1RapidRecoil = l1:find( "^(%d+)!(%d)(%u)$" ) if success then l1 = clip else local success, _, clip = l1:find( "^(%d+)!$" ) if success then l1 = clip l1siege = true end end table.insert( weapon.shots, { { clip = tonumber( l1 ), rapidClip = tonumber( l1RapidNum ), rapidRecoil = l1RapidRecoil, siege = l1siege } } ) if l2 then local success, _, clip, l2RapidNum, l2RapidRecoil = l2:find( "^(%d+)!(%d)(%u)$" ) if success then l2 = clip else local success, _, clip = l2:find( "^(%d+)!$" ) if success then l2 = clip l2siege = true end end table.insert( weapon.shots[ LastShot ], { clip = tonumber( l2 ), rapidClip = tonumber( l2RapidNum ), rapidRecoil = l2RapidRecoil, siege = l2siege } ) if l3 then local success, _, clip, l3RapidNum, l3RapidRecoil = l3:find( "^(%d+)!(%d)(%u)$" ) if success then l3 = clip else local success, _, clip = l3:find( "^(%d+)!$" ) if success then l3 = clip l3siege = true end end table.insert( weapon.shots[ LastShot ], { clip = tonumber( l3 ), rapidClip = tonumber( l3RapidNum ), rapidRecoil = l3RapidRecoil, siege = l3siege } ) end end return "shots" end, charges = function( line, weapon ) local chargeType, chargeLevel, loadUp = line:match( "^(%u)(%d)(!?)$" ) if not chargeType then local coatings = { line:match( CoatingsPattern ) } assert( table.getn( coatings ) == table.getn( BowCoatings ), "bad coatings in " .. weapon.name.hgg .. ": " .. line ) weapon.coatings = { } for i, coating in ipairs( BowCoatings ) do weapon.coatings[ coating ] = coatings[ i ] == "Y" end return "coatingsup" end table.insert( weapon.charges, { type = ChargeTypes[ chargeType ], level = tonumber( chargeLevel ), load = loadUp ~= "" and loadUp or nil, } ) return "charges" end, coatingsup = function( line, weapon ) end, } function string.detab( self ) return self:gsub( "^\t+", "" ) end function doLine( line, weapon, state ) if not Actions[ state ] then print( state ) end return Actions[ state ]( line, weapon ) end function generatePath( weapon, weapons, path ) if not path then path = { } end if weapon.improve then table.insert( path, weapon.improve.from ) return generatePath( weapons[ weapon.improve.from ], weapons, path ) end return table.getn( path ) ~= 0 and path or nil end local Weapons = { } local WeaponsCount = 0 for _, short in pairs( Types ) do io.input( Dir .. "/" .. short .. ".txt" ) local class = Bases[ short ] class.short = short class.weapons = { } local state = "init" local weapon = { } LastShot = 1 local lastDepth = { } local currentIdx = 1 for line in io.lines() do local trimmed = line:detab() if trimmed == "" then weapon.path = generatePath( weapon, class.weapons ) -- if the weapon is an upgrade then check -- i didn't forget the materials assert( not weapon.improve or table.getn( weapon.improve.materials ) ~= 0, "no improve materials for " .. weapon.name.hgg ) table.insert( class.weapons, weapon ) WeaponsCount = WeaponsCount + 1 state = "init" weapon = { } LastShot = 1 currentIdx = currentIdx + 1 else local depth = 1 if state == "init" then while line:sub( depth, depth ) == '\t' do depth = depth + 1 end lastDepth[ depth ] = currentIdx if depth ~= 1 then local from = lastDepth[ depth - 1 ] weapon.improve = { from = from, materials = { } } if not class.weapons[ from ].upgrades then class.weapons[ from ].upgrades = { } end table.insert( class.weapons[ from ].upgrades, currentIdx ) end end state = doLine( trimmed, weapon, state ) end end table.insert( class.weapons, weapon ) table.insert( Weapons, class ) end print( ( "genGuns: ok, %.1f%% complete! (%d/%d)" ):format( 100 * ( WeaponsCount / NamesCount ), WeaponsCount, NamesCount ) ) io.output( "../guns.json" ) io.write( json.encode( Weapons ) )
local ObjectID = 900118 local TeleportSpells{36400,48335,46705} local function StrangePortal_OnUse (event, player, object) for _, TeleportOnCastSpell in ipairs (TeleportSpells[Class]) do player:CastSpell(player, TeleportOnCastSpell) end player:Teleport(33, -322.891632, 2083.733154, 25.270866, 3.140095) player:SetPhaseMask(2) end RegisterGameObjectGossipEvent(ObjectID, 1, StrangePortal_OnUse) ----------------------------------- --------[[Made by PassCody]]------- --[[Made for KappaLounge Repack]]-- -----------------------------------
addEvent("playerChatting", true ) addEvent("playerNotChatting", true ) function playerChatting() triggerClientEvent("updateChatList", getRootElement(), source, true) end function playerNotChatting() triggerClientEvent("updateChatList", getRootElement(), source, false) end addEventHandler("playerChatting", getRootElement(), playerChatting) addEventHandler("playerNotChatting", getRootElement(), playerNotChatting) addEventHandler ("onPlayerQuit", getRootElement(), playerNotChatting )
local function hax_prng_next(v) local hi = math.floor(v / 127773.0) local lo = v % 127773 v = 16807 * lo - 2836 * hi if v <= 0 then v = v + 2147483647 end return v end local function shuffle(arr, seed) local v = math.floor(seed / 2) + 0x30f6 v = hax_prng_next(v) for i = #arr, 1, -1 do v = hax_prng_next(v) local fidx = v / 2^31 local target = math.floor(fidx * i) + 1 arr[i], arr[target] = arr[target], arr[i] end end local LIQUIDS = {"water", "water_ice", "water_swamp", "oil", "alcohol", "swamp", "mud", "blood", "blood_fungi", "blood_worm", "radioactive_liquid", "cement", "acid", "lava", "urine", "poison", "magic_liquid_teleportation", "magic_liquid_polymorph", "magic_liquid_random_polymorph", "magic_liquid_berserk", "magic_liquid_charm", "magic_liquid_invisibility"} local ORGANICS = {"sand", "bone", "soil", "honey", "slime", "snow", "rotten_meat", "wax", "gold", "silver", "copper", "brass", "diamond", "coal", "gunpowder", "gunpowder_explosive", "grass", "fungi"} local function copy_arr(arr) local ret = {} for k, v in pairs(arr) do ret[k] = v end return ret end local function random_material(v, mats) for _ = 1, 1000 do v = hax_prng_next(v) local rval = v / 2^31 local sel_idx = math.floor(#mats * rval) + 1 local selection = mats[sel_idx] if selection then mats[sel_idx] = false return v, selection end end end local function random_recipe(rand_state, seed) local liqs = copy_arr(LIQUIDS) local orgs = copy_arr(ORGANICS) local m1, m2, m3, m4 = "?", "?", "?", "?" rand_state, m1 = random_material(rand_state, liqs) rand_state, m2 = random_material(rand_state, liqs) rand_state, m3 = random_material(rand_state, liqs) rand_state, m4 = random_material(rand_state, orgs) local combo = {m1, m2, m3, m4} rand_state = hax_prng_next(rand_state) local prob = 10 + math.floor((rand_state / 2^31) * 91) rand_state = hax_prng_next(rand_state) shuffle(combo, seed) return rand_state, {combo[1], combo[2], combo[3]}, prob end function get_alchemy() local seed = tonumber(StatsGetValue("world_seed")) local rand_state = math.floor(seed * 0.17127000 + 1323.59030000) for i = 1, 6 do rand_state = hax_prng_next(rand_state) end local lc_combo, ap_combo = {"?"}, {"?"} rand_state, lc_combo, lc_prob = random_recipe(rand_state, seed) rand_state, ap_combo, ap_prob = random_recipe(rand_state, seed) return lc_combo, ap_combo, lc_prob, ap_prob end
local prefill_hooks = {} prefill_hooks["on_console_command"] = function(event) return not (settings.global["scis-logging-ignore-own-commands"] and tostring(event.command):find('^scis_logging.') ~= nil) end return prefill_hooks
ndoc.table.fwZoneControl = {} local cache = {} function fw.zone.setupCaptureNetworking(zone) ndoc.table.fwZoneControl[zone.id] = {} ndoc.table.fwZoneControl[zone.id].scores = {} if (cache[zone.id]) then ndoc.table.fwZoneControl[zone.id].isProtected = cache[zone.id].prot ndoc.table.fwZoneControl[zone.id].isNotCapturable = cache[zone.id].not_cap ndoc.table.fwZoneControl[zone.id].isFactionBase = cache[zone.id].fac_base end end --- --- LOADING AND SETTING OF ZONE CAPTURABILITY / PROTECTED ZONES AND BASES --- local path = fw.zone.zoneDataDir..game.GetMap().."_cap.txt" function fw.zone.loadCaptureData() local data = file.Read(path, "DATA") if (not data) then return end for k,v in pairs(spon.decode(data)) do cache[k] = v end end fw.zone.loadCaptureData() function fw.zone.saveCaptureData() local cache = {} for zID, data in ndoc.pairs(ndoc.table.fwZoneControl) do local isProt = data.isProtected local isNotCap = data.isNotCapturable local isBase = data.isFactionBase --the zone is not protected, and it is capturable or a faction base, no point saving this data! if (not isProt and not isNotCap and not isBase) then continue end cache[zID] = {} if (isProt) then cache[zID].prot = true end if (isNotCap) then cache[zID].not_cap = true end if (isBase) then cache[zID].fac_base = isBase --isbase isn't a bool, it's a faction id! end end cache = spon.encode(cache) file.Write(path, cache) end --- --- CHAT COMMANDS FOR SETTING FACTION BASES, CAPTURABILITY, AND PROTECTED ZONES --- fw.chat.addCMD({"setprotected", "setprot"}, "Sets a zone to be protected(no damage taken while inside) or not", function(ply, boolProtected) local pZone = fw.zone.playerGetZone(ply) if (not pZone) then return end ndoc.table.fwZoneControl[pZone.id].isProtected = boolProtected fw.zone.saveCaptureData() end):addParam("bool_protect", "bool"):restrictTo("superadmin") fw.chat.addCMD({"setcapturable", "setcap"}, "Sets a zone to be capturable or not", function(ply, boolCaptureable) local pZone = fw.zone.playerGetZone(ply) if (not pZone) then return end ndoc.table.fwZoneControl[pZone.id].isNotCapturable = not boolCaptureable fw.zone.saveCaptureData() end):addParam("bool_capturable", "bool"):restrictTo("superadmin") fw.chat.addCMD({"setfactionbase", "setbase"}, "Sets the zone to be a default base for a faction", function(ply, sFactionID) local pZone = fw.zone.playerGetZone(ply) if (not pZone) then return end local fac = fw.team.getFactionByStringID(sFactionID) if (not fac) then return end ndoc.table.fwZoneControl[pZone.id].isFactionBase = fac:getID() fw.zone.saveCaptureData() end):addParam("faction_string_id", "string"):restrictTo("superadmin") fw.chat.addCMD({"removefactionbase", "removebase"}, "Removes the base set to a zone you are in", function(ply) local pZone = fw.zone.playerGetZone(ply) if (not pZone) then return end local fac = pZone:getFactionBase() if (not fac) then return end ndoc.table.fwZoneControl[pZone.id].isFactionBase = false fw.zone.saveCaptureData() end):restrictTo("superadmin") concommand.Add("fw_zone_createBackup", function(pl) if not pl:IsSuperAdmin() then return pl:FWConPrint(Color(255, 0, 0), "you do not have permission to run this command") end fw.zone.createZonesBackup() pl:FWConPrint(Color(0, 255, 0), "Created a backup of the zones file.") end) -- -- SIMPLE ALGORITHMS THAT MANAGES ZONE CAPTURING -- function fw.zone._zone_mt:canBeCaptured() local canCapture = hook.Call("CanZoneBeCaptured", GAMEMODE, self) if (canCapture == false) then return false end local zoneData = ndoc.table.fwZoneControl[self.id] if (zoneData.isNotCapturable) then return false end if (zoneData.isProtected) then return false end if (zoneData.isFactionBase) then return false end return true end local MAX_CAPTURE_SCORE = fw.config.zoneCaptureScore local ZONE_CAPTURE_RATE = fw.config.zoneCaptureRate local notificationCache = {} timer.Create("fw.zone_capture.updateCaptureProgress", 1, 0, function() for k, zone in pairs(fw.zone.zoneList) do if (not zone:canBeCaptured()) then continue end notificationCache[ zone ] = notificationCache[ zone ] or {} local zoneControl = ndoc.table.fwZoneControl[zone.id].scores local controllingInterests = {} local mostInterest = nil for k, pl in ipairs(zone.players) do if IsValid(pl) then local fac = pl:getFaction() if fac ~= FACTION_DEFAULT then controllingInterests[fac] = (controllingInterests[fac] or 0) + 1 if not mostInterest or controllingInterests[mostInterest] < controllingInterests[fac] then mostInterest = fac end end end end if mostInterest then if (zoneControl[mostInterest] or 0) < MAX_CAPTURE_SCORE then zoneControl[mostInterest] = math.min((zoneControl[mostInterest] or 0) + ZONE_CAPTURE_RATE, MAX_CAPTURE_SCORE) end for k,v in ndoc.pairs(zoneControl) do if k ~= mostInterest and v ~= 0 then zoneControl[k] = math.max(0, zoneControl[k] - ZONE_CAPTURE_RATE) local protecting = k local contesting = mostInterest --if the stored contesting faction is different, that means we are being contested! :D local notif = notificationCache[ zone ] if (notif.contesting ~= contesting) then notif.contesting = contesting fw.hook.Call("FWZoneContested", zone, protecting, contesting) end end end end end end) fw.hook.Add("FWZoneContested", "ZoneContestingNotification", function(zone, protecting, contesting) local protectingPlayers = fw.team.factions[ protecting ]:getPlayers() local contestingFaction = fw.team.factions[ contesting ]:getName() fw.hud.pushNotification(protectingPlayers, 'ZONES', zone.name .. " is being contested by the " .. contestingFaction .. "!") end) --- --- HOOKS TO MAINTAIN CAPTURABILITY / BASE / PROTECTED ZONES --- --stop players from taking damage in protected zones -from weapons hook.Add("EntityTakeDamage", "StopPlayerDamageInProtectedZones", function(ent, dmg) if (ent:IsPlayer()) then local zone = fw.zone.playerGetZone(ent) if (zone) then local isprotected = zone:isProtected() if (isprotected) then dmg:SetDamage(0) end end end end) --don't let players pickup weapons in a protected zone hook.Add("PlayerCanPickupWeapon", "StopPickingUpGunsWhileInProtectedZone", function(ply, wep) local zone = fw.zone.playerGetZone(ply) if (zone) then local isprotected = zone:isProtected() if (isprotected and ply.weaponCache) then return false end end end) --when a player enters a protected zone, strip their weapons fw.hook.Add("PlayerEnteredZone", "PlayerGetsWeaponsrestricted", function(enterZone, lastZone, ply) if (not enterZone and lastZone) then local isprotected = lastZone:isProtected() if (isprotected and ply.weaponCache) then for k,v in pairs(ply.weaponCache) do ply:Give(k) end ply.weaponCache = nil end end if (enterZone) then local isprotected = enterZone:isProtected() if (isprotected) then ply.weaponCache = {} for k,v in pairs(ply:GetWeapons()) do ply.weaponCache[v:GetClass()] = true end ply:StripWeapons() end end end) --[[ function fw.zone.initiate(zone) local id = zone.id ndoc.table.zones[id] = {} ndoc.table.zones[id].controlling = nil ndoc.table.zones[id].factions = {} ndoc.table.zones[id].contesting = nil for k,v in pairs(fw.team.factions) do ndoc.table.zones[id].factions[k] = {} ndoc.table.zones[id].factions[k].score = 0 ndoc.table.zones[id].factions[k].players = {} end end fw.zone.cap_cache = {} --saves zone protection and capture data local path = fw.zone.zoneDataDir..game.GetMap().."_cap.txt" function fw.zone.saveCapCache() local pon = spon.encode(fw.zone.cap_cache) file.Write(path, pon) end --loads zone protection & capture data function fw.zone.loadCapCache() local f = file.Read(path, "DATA") if (not f) then return end fw.zone.cap_cache = spon.decode(f) for k,v in pairs(fw.zone.cap_cache) do ndoc.table.zones[k].capturable = v.capturable ndoc.table.zones[k].protected = v.protected ndoc.table.zones[k].faction_base = v.faction_base end end fw.chat.addCMD({"setprotected", "setprot"}, "Sets a zone to be protected(no damage taken while inside) or not", function(ply, boolProtected) local pZone = fw.zone.playerGetZone(ply) if (not pZone) then return end fw.zone.cap_cache[pZone.id] = fw.zone.cap_cache[pZone.id] or {} if (boolProtected == false) then fw.zone.cap_cache[pZone.id].protected = nil ndoc.table.zones[pZone.id].protected = nil fw.zone.saveCapCache() return end fw.zone.cap_cache[pZone.id].protected = boolProtected ndoc.table.zones[pZone.id].protected = boolProtected fw.zone.saveCapCache() end):addParam("bool_protect", "bool"):restrictTo("superadmin") fw.chat.addCMD({"setcapturable", "setcap"}, "Sets a zone to be capturable or not", function(ply, boolCaptureable) local pZone = fw.zone.playerGetZone(ply) if (not pZone) then return end fw.zone.cap_cache[pZone.id] = fw.zone.cap_cache[pZone.id] or {} if (boolCaptureable == true) then fw.zone.cap_cache[pZone.id].capturable = nil ndoc.table.zones[pZone.id].capturable = nil fw.zone.saveCapCache() return end fw.zone.cap_cache[pZone.id].capturable = boolCaptureable ndoc.table.zones[pZone.id].capturable = boolCaptureable fw.zone.saveCapCache() end):addParam("bool_capturable", "bool"):restrictTo("superadmin") fw.chat.addCMD({"setfactionbase", "setbase"}, "Sets the zone to be a default base for a faction", function(ply, sFactionID) local pZone = fw.zone.playerGetZone(ply) if (not pZone) then return end local fac = fw.team.getFactionByStringID(sFactionID) if (not fac) then return end fw.zone.cap_cache[pZone.id] = fw.zone.cap_cache[pZone.id] or {} fw.zone.cap_cache[pZone.id].faction_base = fac:getID() ndoc.table.zones[pZone.id].faction_base = fac:getID() fw.zone.saveCapCache() end):addParam("faction_string_id", "string"):restrictTo("superadmin") fw.chat.addCMD({"removefactionbase", "removebase"}, "Removes the base set to a zone you are in", function(ply) local pZone = fw.zone.playerGetZone(ply) if (not pZone) then return end local fac = fw.zone.isFactionBase(pZone) if (not fac) then return end fw.zone.cap_cache[pZone.id] = fw.zone.cap_cache[pZone.id] or {} fw.zone.cap_cache[pZone.id].faction_base = nil ndoc.table.zones[pZone.id].faction_base = nil fw.zone.saveCapCache() end):restrictTo("superadmin") concommand.Add("fw_zone_createBackup", function(pl) if not pl:IsSuperAdmin() then return pl:FWConPrint(Color(255, 0, 0), "you do not have permission to run this command") end fw.zone.createZonesBackup() pl:FWConPrint(Color(0, 255, 0), "Created a backup of the zones file.") end) --logic for contesting another faction's zone function fw.zone.contest(zone, faction) --cooldown for adding score to teams! local id = zone.id local facScore = ndoc.table.zones[id].factions[faction.factionID].score if (ndoc.table.zones[id].controlling == faction.factionID) then return end if (facScore == fw.config.zoneCaptureScore) then ndoc.table.zones[id].controlling = faction.factionID ndoc.table.zones[id].contesting = nil hook.Call("FactionCapturedZone", GAMEMODE, faction, zone) for k,v in pairs(fw.team.factions) do if (k == faction.factionID) then continue end ndoc.table.zones[id].factions[k].score = 0 end return end hook.Call("FactionContestingZone", GAMEMODE, faction, zone) ndoc.table.zones[id].contesting = faction ndoc.table.zones[id].factions[faction.factionID].score = ndoc.table.zones[id].factions[faction.factionID].score + 1 zone.nextRegisterScore = CurTime() + fw.config.zoneCaptureRate end --returns whether or not a zone can be captured function fw.zone.canBeCaptured(zone) local canCapture = hook.Call("CanZoneBeCaptured", GAMEMODE, zone) --make sure it's false, not just doesn't exist if (fw.zone.cap_cache[zone.id] and fw.zone.cap_cache[zone.id].faction_base) then return false end if (fw.zone.cap_cache[zone.id] and fw.zone.cap_cache[zone.id].capturable != nil and fw.zone.cap_cache[zone.id].capturable == false) then return false end if (fw.zone.cap_cache[zone.id] and fw.zone.cap_cache[zone.id].protected != nil and fw.zone.cap_cache[zone.id].protected == true) then return false end if (zone.nextRegisterScore and CurTime() - zone.nextRegisterScore < 0) then return false end return true end --stop players from taking damage in protected zones -from weapons hook.Add("EntityTakeDamage", "StopPlayerDamageInProtectedZones", function(ent, dmg) if (ent:IsPlayer()) then local zone = fw.zone.playerGetZone(ent) if (zone) then local isprotected = fw.zone.isProtectedZone(zone) if (isprotected) then dmg:SetDamage(0) end end end end) --don't let players pickup weapons in a protected zone hook.Add("PlayerCanPickupWeapon", "StopPickingUpGunsWhileInProtectedZone", function(ply, wep) local zone = fw.zone.playerGetZone(ply) if (zone) then local isprotected = fw.zone.isProtectedZone(zone) if (isprotected and ply.weaponCache) then return false end end end) --when a player leaves a protected zone, give their weapons back fw.hook.Add("PlayerLeftZone", "PlayerGetsWeaponsback", function(zone, ply) local isprotected = fw.zone.isProtectedZone(zone) if (isprotected and ply.weaponCache) then for k,v in pairs(ply.weaponCache) do ply:Give(k) end ply.weaponCache = nil end end) --when a player enters a protected zone, strip their weapons fw.hook.Add("PlayerEnteredZone", "PlayerGetsWeaponsrestricted", function(zone, ply) local isprotected = fw.zone.isProtectedZone(zone) if (isprotected) then ply.weaponCache = {} for k,v in pairs(ply:GetWeapons()) do ply.weaponCache[v:GetClass()] = true end ply:StripWeapons() end end) fw.hook.Add("Think", "ZoneControlLogic", function() --reset player counts for each faction in the zone for k,v in pairs(player.GetAll()) do local pZone = fw.zone.playerGetZone(v) --incase the player changed factions, and left the zone, we want to remove all instances of them being there if (not pZone and v.lastZone) then local zoneData = ndoc.table.zones[v.lastZone.id].factions local z = v.lastZone hook.Call("PlayerLeftZone", GAMEMODE, z, v) for k,fac in ndoc.pairs(zoneData) do ndoc.table.zones[v.lastZone.id].factions[k].players[v] = nil end v.lastZone = nil --if the player is in a zone, make sure the counter is ready, and insert them into the faction thingy elseif (pZone) then if (v.lastFaction and v.lastFaction != v:getFaction()) then ndoc.table.zones[pZone.id].factions[v.lastFaction].players[v] = nil v.lastFaction = nil end v.lastFaction = v:getFaction() local id = pZone.id --no use constantly syncing the player already in here if (not ndoc.table.zones[id].factions[v:getFaction()].players[v]) then ndoc.table.zones[id].factions[v:getFaction()].players[v] = true hook.Call("PlayerEnteredZone", GAMEMODE, pZone, v) end v.lastZone = pZone if (not fw.zone.canBeCaptured(pZone)) then continue end end end --loop through the zones and do the logic for zoneid, zoneTable in ndoc.pairs(ndoc.table.zones) do local factionInPower = nil local zone = fw.zone.zoneList[zoneid] if (not zone) then continue end if (not fw.zone.canBeCaptured(zone)) then continue end for fac,v in ndoc.pairs(zoneTable.factions) do local plys = {} for k,v in ndoc.pairs(v.players) do --remove players that left and stuff if (not IsValid(k)) then ndoc.table.zones[zoneid].factions[fac].players[k] = nil end table.insert(plys, k) end --if there are more players in another faction than the one who is control of the faction if (factionInPower and #plys > #factionInPower.playersInZone) then factionInPower = {} factionInPower.playersInZone = plys factionInPower.factionID = fac --equal disbursement of players in the zone for all factions elseif (factionInPower and #plys == #factionInPower.playersInZone) then if (ndoc.table.zones[zoneid].contesting and ndoc.table.zones[zoneid].contesting and ndoc.table.zones[zoneid].contesting.factionID != factionInPower.factionID) then ndoc.table.zones[zoneid].contesting = nil end return --for when players first enter a zone :D elseif (not factionInPower and #plys > 0) then factionInPower = {} factionInPower.playersInZone = plys factionInPower.factionID = fac end end --if we have a new faction in power, contest the zone if (factionInPower) then if (ndoc.table.zones[zoneid].contesting and ndoc.table.zones[zoneid].contesting.factionID != factionInPower.factionID) then ndoc.table.zones[zoneid].contesting = nil end fw.zone.contest(zone, factionInPower) end end end) ]]
SuperSurvivorManager = {} SuperSurvivorManager.__index = SuperSurvivorManager function SuperSurvivorManager:new() local o = {} setmetatable(o, self) self.__index = self o.SuperSurvivors = {} o.SurvivorCount = 3 return o end function SuperSurvivorManager:init() self.SuperSurvivors[0] = SuperSurvivor:newSet(getSpecificPlayer(0)) self.SuperSurvivors[0]:setID(0) end function SuperSurvivorManager:setPlayer(player,ID) self.SuperSurvivors[ID] = SuperSurvivor:newSet(player) self.SuperSurvivors[0]:setID(ID) self.SuperSurvivors[0]:setName("Player " .. tostring(ID)) return self.SuperSurvivors[ID] ; end function SuperSurvivorManager:LoadSurvivor(ID, square) if( not checkSaveFileExists("Survivor"..tostring(ID))) then return false end if(ID ~= nil) and (square ~= nil) then -- if(self.SuperSurvivors[ID] ~= nil) and (self.SuperSurvivors[ID].player ~= nil) then if(self.SuperSurvivors[ID]:isInCell()) then return false else self.SuperSurvivors[ID]:delete() end end print("loading survivor ".. tostring(ID) .." on " .. tostring(square:getX()) .. "," .. tostring(square:getY())) self.SuperSurvivors[ID] = SuperSurvivor:newLoad(ID,square) if(self.SuperSurvivors[ID]:Get():getPrimaryHandItem() == nil) and (self.SuperSurvivors[ID]:getWeapon() ~= nil) then self.SuperSurvivors[ID]:Get():setPrimaryHandItem(self.SuperSurvivors[ID]:getWeapon()) end self.SuperSurvivors[ID]:refreshName() if(self.SuperSurvivors[ID]:Get():getModData().isHostile == true) then self.SuperSurvivors[ID]:setHostile(true) end if(self.SurvivorCount == nil) then self.SurvivorCount = 1 end if(ID > self.SurvivorCount) then self.SurvivorCount = ID end self.SuperSurvivors[ID].player:getModData().LastSquareSaveX = nil self.SuperSurvivors[ID]:SaveSurvivor() local melewep = self.SuperSurvivors[ID].player:getModData().meleWeapon local gunwep = self.SuperSurvivors[ID].player:getModData().gunWeapon if(melewep ~= nil) then self.SuperSurvivors[ID].LastMeleUsed = self.SuperSurvivors[ID].player:getInventory():FindAndReturn(melewep) if not self.SuperSurvivors[ID].LastMeleUsed then self.SuperSurvivors[ID].LastMeleUsed = self.SuperSurvivors[ID]:getBag():FindAndReturn(melewep) end end if(gunwep ~= nil) then self.SuperSurvivors[ID].LastGunUsed = self.SuperSurvivors[ID].player:getInventory():FindAndReturn(gunwep) if not self.SuperSurvivors[ID].LastGunUsed then self.SuperSurvivors[ID].LastGunUsed = self.SuperSurvivors[ID]:getBag():FindAndReturn(gunwep) end end if(self.SuperSurvivors[ID]:getAIMode() == "FollowRoute") then self.SuperSurvivors[ID]:getTaskManager():AddToTop(FollowRouteTask:new(self.SuperSurvivors[ID],0)) elseif(self.SuperSurvivors[ID]:getAIMode() == "Follow") then self.SuperSurvivors[ID]:getTaskManager():AddToTop(FollowTask:new(self.SuperSurvivors[ID],nil)) elseif(self.SuperSurvivors[ID]:getAIMode() == "Guard") then self.SuperSurvivors[ID]:getTaskManager():AddToTop(GuardTask:new(self.SuperSurvivors[ID],self.SuperSurvivors[ID].player:getCurrentSquare())) elseif(self.SuperSurvivors[ID]:getAIMode() == "Patrol") then self.SuperSurvivors[ID]:getTaskManager():AddToTop(PatrolTask:new(self.SuperSurvivors[ID], nil, nil)) elseif(self.SuperSurvivors[ID]:getAIMode() == "Wander") then self.SuperSurvivors[ID]:getTaskManager():AddToTop(WanderTask:new(self.SuperSurvivors[ID])) elseif(self.SuperSurvivors[ID]:getAIMode() == "Stand Ground") then self.SuperSurvivors[ID]:getTaskManager():AddToTop(GuardTask:new(self.SuperSurvivors[ID],self.SuperSurvivors[ID].player:getCurrentSquare())) self.SuperSurvivors[ID]:setWalkingPermitted(false) elseif(self.SuperSurvivors[ID]:getAIMode() == "Doctor") then self.SuperSurvivors[ID]:getTaskManager():AddToTop(DoctorTask:new(self.SuperSurvivors[ID])) end if(isModEnabled("ArmorMod")) then ArmorInitCheck(self.SuperSurvivors[ID].player) end local phi = self.SuperSurvivors[ID]:Get():getPrimaryHandItem() -- to trigger onEquipPrimary self.SuperSurvivors[ID]:Get():setPrimaryHandItem(nil) self.SuperSurvivors[ID]:Get():setPrimaryHandItem(phi) end end function SuperSurvivorManager:spawnSurvivor(isFemale,square) if(square ~= nil) then local newSurvivor = SuperSurvivor:new(isFemale,square) if(newSurvivor ~= nil) then self.SuperSurvivors[self.SurvivorCount+1] = newSurvivor self.SurvivorCount = self.SurvivorCount + 1; self.SuperSurvivors[self.SurvivorCount]:setID(self.SurvivorCount) return self.SuperSurvivors[self.SurvivorCount] else return nil end end end function SuperSurvivorManager:Get(thisID) if(not self.SuperSurvivors[thisID]) then --print("super survivor #"..tostring(thisID).." was not found") return nil else return self.SuperSurvivors[thisID] end end function SuperSurvivorManager:update() --getSpecificPlayer(0):Say(tostring(self.SurvivorCount)) --print("SSM updating..."..tostring(self.SurvivorCount)) for i=1, self.SurvivorCount+1 do --local id = i --local theSuperSurvivor = self.SuperSurvivors[i] --if(self.SuperSurvivors[i] ~= nil) then getSpecificPlayer(0):Say(tostring(id)..") ".. tostring(theSuperSurvivor ~= nil) ..",".. tostring(theSuperSurvivor:updateTime()) ..",".. tostring(theSuperSurvivor:isInCell()) ) end if(self.SuperSurvivors[i] ~= nil) and (self.SuperSurvivors[i]:updateTime()) and (self.SuperSurvivors[i]:isInCell()) then self.SuperSurvivors[i]:update() end end end function SuperSurvivorManager:GetClosest() local closestSoFar = 20 local closestID = 0 for i=1, self.SurvivorCount+1 do if(self.SuperSurvivors[i] ~= nil) and (self.SuperSurvivors[i]:isInCell()) then local distance = getDistanceBetween(self.SuperSurvivors[i]:Get(),getSpecificPlayer(0)) if(distance < closestSoFar) then closestID = i closestSoFar = distance end end end if(closestID ~= 0) then return self.SuperSurvivors[closestID] else return nil end end function SuperSurvivorManager:GetClosestNonParty() local closestSoFar = 20 local closestID = 0 for i=1, self.SurvivorCount+1 do if(self.SuperSurvivors[i] ~= nil) and (self.SuperSurvivors[i]:isInCell()) then local distance = getDistanceBetween(self.SuperSurvivors[i]:Get(),getSpecificPlayer(0)) if(distance < closestSoFar) and (self.SuperSurvivors[i]:getGroupID() == nil) then closestID = i closestSoFar = distance end end end if(closestID ~= 0) then return self.SuperSurvivors[closestID] else return nil end end SSM = SuperSurvivorManager:new() function loadSurvivorMap( ) local tempTable = {} tempTable = table.load("SurvivorManagerInfo") if (tempTable) and (tempTable[1]) then SSM.SurvivorCount = tonumber(tempTable[1]) print("set SurvivorCount:"..tostring(tempTable[1]) .. " from SurvivorManagerInfo file"); else print("SurvivorManagerInfo was not found. this save file could be corrupt"); end local fileTable = {} local readFile = getModFileReader("SuperSurvivors",getWorld():getWorld()..getFileSeparator().."SurvivorMap.lua", true) local scanLine = readFile:readLine() while scanLine do local values = {} for input in scanLine:gmatch("%S+") do table.insert(values,input) end --print("loading line: "..values[1] .. " " .. values[2]) if(fileTable[values[1]] == nil) then fileTable[values[1]] = {} end table.insert(fileTable[values[1]], tonumber(values[2])) scanLine = readFile:readLine() if not scanLine then break end end readFile:close() return fileTable end function saveSurvivorMap( ) local tempTable = {} tempTable[1] = SSM.SurvivorCount table.save(tempTable,"SurvivorManagerInfo") local destFile = getWorld():getWorld()..getFileSeparator().."SurvivorMap.lua" local writeFile = getModFileWriter("SuperSurvivors", destFile, true, false) --print("saving SurvivorMap:".. tostring(SurvivorMap)) for index,value in pairs(SurvivorMap) do for i = 1,#value do writeFile:write(tostring(index) .. " " .. tostring(value[i]) .. "\r\n"); --print("saving: " .. tostring(index) .. " " .. tostring(value[i])) end end writeFile:close(); end
local old_instanted_init = EquipmentsTweakData.init function EquipmentsTweakData:init(tweak_data) old_instanted_init(self, tweak_data) self.trip_mine = { deploy_time = 0, dummy_unit = "units/payday2/equipment/gen_equipment_tripmine/gen_equipment_tripmine_dummy", use_function_name = "use_trip_mine", text_id = "debug_trip_mine", visual_object = "g_toolbag", icon = "equipment_trip_mine", description_id = "des_trip_mine", quantity = { 3, 3 }, upgrade_deploy_time_multiplier = { upgrade = "trip_mine_deploy_time_multiplier", category = "player" }, upgrade_name = { "trip_mine", "shape_charge" } } self.ammo_bag = { deploy_time = 0, use_function_name = "use_ammo_bag", dummy_unit = "units/payday2/equipment/gen_equipment_ammobag/gen_equipment_ammobag_dummy_unit", text_id = "debug_ammo_bag", icon = "equipment_ammo_bag", description_id = "des_ammo_bag", visual_object = "g_ammobag", quantity = {1} } self.doctor_bag = { deploy_time = 0, dummy_unit = "units/payday2/equipment/gen_equipment_medicbag/gen_equipment_medicbag_dummy_unit", use_function_name = "use_doctor_bag", text_id = "debug_doctor_bag", visual_object = "g_medicbag", icon = "equipment_doctor_bag", description_id = "des_doctor_bag", quantity = {1}, upgrade_deploy_time_multiplier = { upgrade = "deploy_time_multiplier", category = "first_aid_kit" } } self.sentry_gun = { deploy_time = 0, dummy_unit = "units/payday2/equipment/gen_equipment_sentry/gen_equipment_sentry_dummy", text_id = "debug_sentry_gun", use_function_name = "use_sentry_gun", unit = 1, min_ammo_cost = 0.8, ammo_cost = 0.7, visual_object = "g_sentrybag", icon = "equipment_sentry", description_id = "des_sentry_gun", quantity = {1}, upgrade_deploy_time_multiplier = { upgrade = "sentry_gun_deploy_time_multiplier", category = "player" } } self.sentry_gun_silent = { deploy_time = 0, dummy_unit = "units/payday2/equipment/gen_equipment_sentry/gen_equipment_sentry_dummy", text_id = "debug_sentry_gun", use_function_name = "use_sentry_gun", unit = 2, min_ammo_cost = 0.33, ammo_cost = 0.46, visual_object = "g_sentrybag", icon = "equipment_sentry_silent", description_id = "des_sentry_gun", quantity = {1}, upgrade_deploy_time_multiplier = { upgrade = "sentry_gun_deploy_time_multiplier", category = "player" }, upgrade_name = {"sentry_gun"} } self.ecm_jammer = { deploy_time = 0, use_function_name = "use_ecm_jammer", dummy_unit = "units/payday2/equipment/gen_equipment_jammer/gen_equipment_jammer_dummy", text_id = "debug_equipment_ecm_jammer", icon = "equipment_ecm_jammer", description_id = "des_ecm_jammer", visual_object = "g_toolbag", quantity = {1} } self.armor_kit = { deploy_time = 0, use_function_name = "use_armor_kit", sound_done = "bar_armor_finished", dropin_penalty_function_name = "use_armor_kit_dropin_penalty", icon = "equipment_armor_kit", description_id = "des_armor_kit", limit_movement = true, sound_start = "bar_armor", sound_interupt = "bar_armor_cancel", text_id = "debug_equipment_armor_kit", on_use_callback = "on_use_armor_bag", deploying_text_id = "hud_equipment_equipping_armor_kit", action_timer = 2, visual_object = "g_armorbag", quantity = {1} } self.first_aid_kit = { deploy_time = 0, dummy_unit = "units/pd2_dlc_old_hoxton/equipment/gen_equipment_first_aid_kit/gen_equipment_first_aid_kit_dummy", use_function_name = "use_first_aid_kit", text_id = "debug_equipment_first_aid_kit", visual_object = "g_firstaidbag", icon = "equipment_first_aid_kit", description_id = "des_first_aid_kit", quantity = {4}, upgrade_deploy_time_multiplier = { upgrade = "deploy_time_multiplier", category = "first_aid_kit" } } self.bodybags_bag = { deploy_time = 0, dummy_unit = "units/payday2/equipment/gen_equipment_bodybags_bag/gen_equipment_bodybags_bag_dummy", use_function_name = "use_bodybags_bag", text_id = "debug_equipment_bodybags_bag", visual_object = "g_bodybagsbag", icon = "equipment_bodybags_bag", description_id = "des_bodybags_bag", quantity = {1}, upgrade_deploy_time_multiplier = { upgrade = "bodybags_bag_deploy_time_multiplier", category = "player" } } end
local accumulator = {} local LARGE_TIMEOUT = 1000.0 function accumulator.new(max_size, timeout, func) local ngx = require "ngx" local semaphore = require "ngx.semaphore" local function makeState() return { tasks = {}, sema = semaphore.new(), } end local state0 = makeState() local function applyFunc(_, state) if not state.applied then state.applied = true state0 = makeState() local ok, second = pcall(func, state.tasks) if ok and second then state.results = second else state.error_msg = second end state.sema:post(#state.tasks) end end local function wrapper(task) assert(task ~= nil) local state = state0 table.insert(state.tasks, task) local index = #state.tasks if #state.tasks == max_size then ngx.timer.at(0.0, applyFunc, state) elseif #state.tasks == 1 then ngx.timer.at(timeout, applyFunc, state) end repeat until state.sema:wait(LARGE_TIMEOUT) if state.results then return state.results[index] else return nil, state.error_msg end end return wrapper end return accumulator
--[[-- Hotpatch Core: Module Object for Hotpatch-MultiMod: a tool to load multiple scenarios side-by-side, with support for both static loading and dynamic loading, as well as run-time patching. This module handles loading and running code, setting up environments, etc @module hotpatch.core-mod_object @author Chrisgbk ]] --[[ Copyright 2018 Chrisgbk 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. ]] -- MIT License, https://opensource.org/licenses/MIT -- Hotpatch-MultiMod: a tool to load multiple scenarios side-by-side, with support for both static loading and dynamic loading, as well as run-time patching --[==[ -- internal mod object: local mod_obj_template = { -- references to global table mod = mod name = mod_name, version = mod.version, files = mod.files, global = mod.global, -- _ENV = {}, -- environment of the mod loaded = false, running = false, -- event handlers on_init = nil, -- called once after first install, or when specifically requested to be re-ran (good practice is to never request a re-run) on_load = nil, -- called every time the scenario loads from disk on_configuration_changed = nil, -- called every time the external mod configuration changes, OR when the hotpatch mod configuration changes on_tick = nil, -- cache the on-tick event handler, because it is ID 0, which causes it to be stored in the hash part, which causes a 50% increase in access time on_event = {}, -- list of on_event handlers registered on_nth_tick = {}, -- list of on_nth_tick handlers registered custom_events = {}, -- names for printing -- package handling loaded = {}, -- list of files loaded by require() that were installed into the virtual file system preload = {}, searchers = {}, -- commands = {}, interfaces = {}, } --]==] local rendering = rendering --this is a workaround specifically because rendering is available in control.lua processing but not on_load, where mods are loaded local function create_proxy_table(table) return setmetatable({}, { __index = table, __pairs = function(t) local function iter(t, k) local v; k, v = next(table, k); if v then return k, t[k] end; end; return iter, t, nil end }) end local function create_readonly_proxy_table(table) return setmetatable({}, { __index = table, __newindex = function(t,k,v) end, __pairs = function(t) local function iter(t, k) local v; k, v = next(table, k); if v then return k, t[k] end; end; return iter, t, nil end }) end local function generate_mod_obj(mod) local mod_name = mod.name local mod_obj = { -- references to global table mod = mod, name = mod_name, version = mod.version, files = mod.files, global = mod.global, -- _ENV = {}, -- environment of the mod loaded = false, running = false, -- event handlers on_init = nil, -- called once after first install, or when specifically requested to be re-ran (good practice is to never request a re-run) on_load = nil, -- called every time the scenario loads from disk on_configuration_changed = nil, -- called every time the external mod configuration changes, OR when the hotpatch mod configuration changes on_tick = nil, -- cache the on-tick event handler, because it is ID 0, which causes it to be stored in the hash part, which causes a 50% increase in access time on_event = {}, -- list of on_event handlers registered on_nth_tick = {}, -- list of on_nth_tick handlers registered custom_events = {}, -- names for printing -- package handling loaded = {}, -- list of files loaded by require() that were installed into the virtual file system preload = {}, searchers = {}, -- commands = {}, interfaces = {}, } hotpatch_log({'hotpatch-info.script-shim'}, mod_name) --mods private script table/shim local mod_script = {} mod_script.on_init = function(f) mod_obj.on_init = f end mod_script.on_load = function(f) mod_obj.on_load = f end mod_script.on_configuration_changed = function(f) mod_obj.on_configuration_changed = f end if not compat_mode then mod_script.on_event = function(event, f) if event == defines.events.on_tick then mod_obj.on_tick = f else mod_obj.on_event[event] = f end end mod_script.on_nth_tick = function(tick, f) if tick then if type(tick) == 'table' then for _, v in pairs(tick) do mod_script.on_nth_tick(v, f) end return end mod_obj.on_nth_tick[tick] = f else mod_obj.on_nth_tick = {} end end else mod_script.on_event = function(event, f) if event == defines.events.on_tick then mod_obj.on_tick = f if mod_obj.running then if f then register_on_tick(mod_name) else unregister_on_tick(mod_name) end end else mod_obj.on_event[event] = f if mod_obj.running then if f then register_event(mod_name, event) else unregister_event(mod_name, event) end end end end mod_script.on_nth_tick = function(tick, f) if tick then if type(tick) == 'table' then for _, v in pairs(tick) do mod_script.on_nth_tick(v, f) end return end mod_obj.on_nth_tick[tick] = f if mod_obj.running then if f then register_nth_tick(mod_name, tick) else unregister_nth_tick(mod_name, tick) end end else local mod_on_nth_tick = mod_obj.on_nth_tick mod_obj.on_nth_tick = {} if mod_obj.running then for _, v in pairs(mod_on_nth_tick) do unregister_nth_tick(mod_name, v) end end end end end mod_script.generate_event_name = function() local n = script.generate_event_name() mod_obj.custom_events[n] = mod_name .. n return n end mod_script.get_event_handler = function(event) return mod_obj.on_event[event] end mod_script.raise_event = function(event, table) script.raise_event(event, table) end --TODO: replace these with mod-provided versions, so multi-mod aware softmods can easily detect other loaded softmods mod_script.get_event_order = function() return script.get_event_order() end mod_script.mod_name = function() return script.mod_name() end hotpatch_log({'hotpatch-info.setting-env'}, mod_name) -- mods private env local env = mod_obj._ENV -- copy the current environment for k,v in pairs(_ENV) do env[k] = v end env._G = env -- mods private package local package = {} env.package = package package._current_path_in_package = nil package._current_package = mod local loaded = {} package.loaded = loaded local preload = {} package.preload = preload local searchers = {} package.searchers = searchers -- copy package.loaded for k,v in pairs(_ENV.package.loaded) do loaded[k] = v end loaded._G = env loaded.package = package local require -- first check if we preloaded this module searchers[1] = function(modulename) local r = preload[modulename] if r then return r end end -- then check other file systems, if another was specified searchers[2] = function(modulename) local fs, mn = modulename:match('^__(.-)__%.(.*)$') if not fs then return nil end local m = global.mods[fs] if not m then -- specified mod doesn't exist error('mod ' .. fs .. ' doesn\'t exist') end if m == mod then modulename = mn else package._current_package = m package._current_path_in_package = mn:match('^(.*)%.([^.]-)$') end local result = nil local f = m.files[mn] if f then local func, err = load(f, '[' .. mod_name .. '] ' .. modulename .. '.lua', 'bt', mod_obj._ENV) if func then result = func hotpatch_log({'hotpatch-trace.load-require', modulename .. '(2)'}, nil, 4) end else -- specified file doesn't exist error('mod ' .. fs .. ' doesn\'t contain file ' .. mn) end return result, modulename end -- then check if the current file system contains this module searchers[3] = function(modulename) local cp = package._current_package local cpp = package._current_path_in_package if not cp then return nil end modulename = ((cpp and (cpp .. '.')) or '') .. modulename local path, file = modulename:match('^(.*)%.([^.]-)$') if not file then file = modulename end if file == '' then file = path path = nil end package._current_path_in_package = path local result = nil local f = cp.files[modulename] if f then local func, err = load(f, '[' .. mod_name .. '] ' .. modulename .. '.lua', 'bt', mod_obj._ENV) if func then result = func hotpatch_log({'hotpatch-trace.load-require', modulename .. '(3)'}, nil, 4) end end if cp ~= mod then modulename = '__' .. cp.name .. '__.' .. modulename end return result, modulename end -- relative to base searchers[4] = function(modulename) local cp = package._current_package local cpp = package._current_path_in_package if not cp then return nil end local path, file = modulename:match('^(.*)%.([^.]-)$') if not file then file = modulename end if file == '' then file = path path = nil end package._current_path_in_package = path local result = nil local f = cp.files[modulename] if f then local func, err = load(f, '[' .. mod_name .. '] ' .. modulename .. '.lua', 'bt', mod_obj._ENV) if func then result = func hotpatch_log({'hotpatch-trace.load-require', modulename .. '(4)'}, nil, 4) end end if cp ~= mod then modulename = '__' .. cp.name .. '__.' .. modulename end return result, modulename end -- factorio library searchers[5] = function(modulename) local lib = _ENV.package.loaded[modulename] if lib then hotpatch_log({'hotpatch-trace.load-core-lib', modulename}, nil, 4) return function() return lib end end end require = function(modulename) --local file = modulename:match('%.?([^.]-)$') --local path = modulename:match('%.(.*)%.') --local mod = modulename:match('^__(.-)__%.') modulename = modulename:gsub('[/\\]', '.') -- loaded? local fs, mn = modulename:match('^__(.-)__%.(.*)$') if fs then local m = global.mods[fs] local r, p if m == mod then r = loaded[mn] p = mn else r = loaded[modulename] p = modulename end if r then hotpatch_log({'hotpatch-trace.cached-load-require', modulename}, nil, 3) hotpatch_log('Requested: ' .. modulename .. ' found: ' .. p); return r end end local cp = package._current_package if cp == mod then cp = nil end local cpp = package._current_path_in_package local r,path path = ((cp and ('__' .. cp.name .. '__.')) or '') .. ((cpp and (cpp .. '.')) or '') .. modulename r = loaded[path] if r then hotpatch_log({'hotpatch-trace.cached-load-require', path}, nil, 3) hotpatch_log('Requested: ' .. modulename .. ' found: ' .. path); return r end cpp = nil path = ((cp and ('__' .. cp.name .. '__.')) or '') .. ((cpp and (cpp .. '.')) or '') .. modulename r = loaded[path] if r then hotpatch_log({'hotpatch-trace.cached-load-require', path}, nil, 3) hotpatch_log('Requested: ' .. modulename .. ' found: ' .. path); return r end -- not loaded, find it local old_package = package._current_package local old_path = package._current_path_in_package for i = 1, #package.searchers do local l,p = package.searchers[i](modulename) if l then p = p or modulename r = l() or true loaded[p] = r hotpatch_log('Requested: ' .. modulename .. ' found: ' .. p); package._current_path_in_package = old_path package._current_package = old_package return r end end hotpatch_log({'hotpatch-error.module-not-found', modulename}, nil, 3) error('module ' .. modulename .. ' not found') end env.require = require env['game'] = setmetatable({}, { __index = function(_, k) return game[k] end, __pairs = function(t) local function iter(t, k) local v; k, v = next(game, k); if v then return k, t[k] end; end; return iter, t, nil end }) env['script'] = setmetatable({}, { __index = mod_script, __pairs = function(t) local function iter(t, k) local v; k, v = next(mod_script, k); if v then return k, t[k] end; end; return iter, t, nil end }) env.global = mod.global env['remote'] = { add_interface = function(name, functions) if remote.interfaces[name] then hotpatch_log({'hotpatch-warning.remote-interface-exists', name}, mod_name) remote.remove_interface(name) end hotpatch_log({'hotpatch-info.adding-remote', name}, mod_name) remote.add_interface(name, functions) mod_obj.interfaces[name] = true end, remove_interface = function(name) mod_obj.interfaces[name] = nil hotpatch_log({'hotpatch-info.removing-remote', name}, mod_name) return remote.remove_interface(name) end, call = function(...) return remote.call(...) end, interfaces = setmetatable({}, { __index = function(_, k) return remote.interfaces[k] end, __pairs = function(t) local function iter(t, k) local v; k, v = next(remote.interfaces, k); if v then return k, t[k] end; end; return iter, t, nil end }) } env['commands'] = { add_command = function(name, help, func) if commands.commands[name] then hotpatch_log({'hotpatch-warning.command-exists', name}, mod_name) commands.remove_command(name) end hotpatch_log({'hotpatch-info.adding-command', name}, mod_name) commands.add_command(name, help, func) mod_obj.commands[name] = true end, remove_command = function(name) mod_obj.commands[name] = nil hotpatch_log({'hotpatch-info.removing-command', name}, mod_name) return commands.remove_command(name) end, commands = setmetatable({}, { __index = function(_, k) return commands.commands[k] end, __pairs = function(t) local function iter(t, k) local v; k, v = next(commands.commands, k); if v then return k, t[k] end; end; return iter, t, nil end }), game_commands = setmetatable({}, { __index = function(_, k) return commands.game_commands[k] end, __pairs = function(t) local function iter(t, k) local v; k, v = next(commands.game_commands, k); if v then return k, t[k] end; end; return iter, t, nil end }) } env['settings'] = setmetatable({}, { __index = function(_, k) return settings[k] end, __pairs = function(t) local function iter(t, k) local v; k, v = next(settings, k); if v then return k, t[k] end; end; return iter, t, nil end }) env['rcon'] = setmetatable({}, { __index = function(_, k) return rcon[k] end, __pairs = function(t) local function iter(t, k) local v; k, v = next(rcon, k); if v then return k, t[k] end; end; return iter, t, nil end }) hotpatch_log('rendering') for k,v in pairs(rendering) do hotpatch_log(k) end env['rendering'] = setmetatable({}, { __index = function(_, k) return rendering[k] end, __pairs = function(t) local function iter(t, k) local v; k, v = next(rendering, k); if v then return k, t[k] end; end; return iter, t, nil end }) env['load'] = function(l, s, m, e) return load(l, s, m, e or env) end env['loadstring'] = env['load'] local mt = {} local umt env['setmetatable'] = function(t, metat) if t == env then umt = metat return t end return setmetatable(t, metat) end mt.__index = function(t, k) hotpatch_log({'hotpatch-trace.nil-var-access', k}, nil, 3) if umt then local index = umt.__index if type(index) == 'function' then return index(t,k) else return index[k] end end end mt.__newindex = function(t, k, v) hotpatch_log({'hotpatch-trace.nil-var-assignment', k}, nil, 3) if umt then local newindex = umt.__newindex if type(newindex) == 'function' then return newindex(t,k,v) else newindex[k] = v return end end rawset(t,k,v) end mt.__metatable = umt setmetatable(env, mt) return mod_obj end return generate_mod_obj
-- object based faces renderer, default renderer for faces. local ReplicatedStorage = game:GetService("ReplicatedStorage") local common = ReplicatedStorage:WaitForChild("common") local Assets = require(common:WaitForChild("Assets")) local FaceRenderer = {} local function applyFaceToRig(rig,image) local torso = rig:FindFirstChild("Torso") if torso then local face = torso:FindFirstChild("Decal") if face then face.Texture = image or "rbxassetid://102312301" end end end function FaceRenderer.new(assetId,rig) local self = setmetatable({},{__index = FaceRenderer}) self.rig = rig self.assetId = assetId local faceAsset = Assets.byId[assetId] if faceAsset then applyFaceToRig(rig,faceAsset.metadata.image) end return self end function FaceRenderer:update() -- nothing needed here end function FaceRenderer:destroy() applyFaceToRig(self.rig, nil) self.rig = nil end return FaceRenderer
return { _VERSION = "0.0.1"; }
--!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-2020, TBOOX Open Source Group. -- -- @author ruki -- @file main.lua -- -- imports import("core.base.option") import("core.project.config") import("core.project.project") import("core.platform.platform") import("core.package.repository") import("devel.git") import("private.async.runjobs") import("actions.require.impl.environment", {rootdir = os.programdir()}) -- add repository url function _add(name, url, branch, is_global) -- add url repository.add(name, url, branch, is_global) -- remove previous repository if exists local repodir = path.join(repository.directory(is_global), name) if os.isdir(repodir) then os.rmdir(repodir) end -- enter environment environment.enter() -- clone repository if not os.isdir(url) then git.clone(url, {verbose = option.get("verbose"), branch = branch or "master", outputdir = repodir}) end -- trace cprint("${color.success}add %s repository(%s): %s%s ok!", ifelse(is_global, "global", "local"), name, url, branch and (" " .. branch) or "") -- leave environment environment.leave() end -- remove repository url function _remove(name, is_global) -- remove url repository.remove(name, is_global) -- remove repository local repodir = path.join(repository.directory(is_global), name) if os.isdir(repodir) then os.rmdir(repodir) end -- trace cprint("${bright}remove %s repository(%s): ok!", ifelse(is_global, "global", "local"), name) end -- update repositories function _update() -- enter environment environment.enter() -- trace printf("updating repositories .. ") if option.get("verbose") then print("") end -- create a pull task local task = function () -- get all repositories (local first) local repos = table.join(repository.repositories(false), repository.repositories(true)) -- pull all repositories local pulled = {} for _, repo in ipairs(repos) do -- the repository directory local repodir = repo:directory() -- remove repeat and only pull the first repository if not pulled[repodir] then if os.isdir(repodir) then -- update the local repository with the remote url if not os.isdir(repo:url()) then -- trace vprint("pulling repository(%s): %s to %s ..", repo:name(), repo:url(), repodir) -- pull it git.pull({verbose = option.get("verbose"), branch = repo:branch() or "master", repodir = repodir}) -- mark as updated io.save(path.join(repodir, "updated"), {}) end else -- trace vprint("cloning repository(%s): %s to %s ..", repo:name(), repo:url(), repodir) -- clone it git.clone(repo:url(), {verbose = option.get("verbose"), branch = repo:branch() or "master", outputdir = repodir}) -- mark as updated io.save(path.join(repodir, "updated"), {}) end -- pull this repository ok pulled[repodir] = true end end end -- pull repositories if option.get("verbose") then task() else runjobs("update repo", task, {showtips = true}) end -- leave environment environment.leave() -- trace cprint("${green}ok") end -- clear all repositories function _clear(is_global) -- clear all urls repository.clear(is_global) -- remove all repositories local repodir = repository.directory(is_global) if os.isdir(repodir) then os.rmdir(repodir) end -- trace cprint("${color.success}clear %s repositories: ok!", ifelse(is_global, "global", "local")) end -- list all repositories function _list() -- list all repositories local count = 0 for _, position in ipairs({"local", "global"}) do -- trace print("%s repositories:", position) -- list all for _, repo in pairs(repository.repositories(position == "global")) do -- trace local description = repo:get("description") print(" %s %s%s %s", repo:name(), repo:url(), repo:branch() and (" " .. repo:branch()) or "", description and ("(" .. description .. ")") or "") -- update count count = count + 1 end -- trace print("") end -- trace print("%d repositories were found!", count) end -- get the repository directory function _directory(is_global) print(repository.directory(is_global)) end -- load project function _load_project() -- enter project directory os.cd(project.directory()) -- load config config.load() -- load platform platform.load(config.plat()) end -- main function main() -- load project if operate local repositories if not option.get("global") then _load_project() end -- add repository url if option.get("add") then _add(option.get("name"), option.get("url"), option.get("branch"), option.get("global")) -- remove repository url elseif option.get("remove") then _remove(option.get("name"), option.get("global")) -- update repository url elseif option.get("update") then _update() -- clear all repositories elseif option.get("clear") then _clear(option.get("global")) -- list all repositories elseif option.get("list") then _list() -- show repo directory else _directory(option.get("global")) end end
local settings_key = KEYS[1] local running_key = KEYS[2] local executing_key = KEYS[3] local index = ARGV[1] local now = ARGV[2] redis.call('zadd', executing_key, 0, index) return refresh_running(executing_key, running_key, settings_key, now)
local cm = {} function cm.new(init) init = init or {} local self = {} self.draw = cm.draw self.update = cm.update self.getHeight = cm.getHeight self.getWidth = cm.getWidth self.getEntryArea = cm.getEntryArea self.mouseInArea = cm.mouseInArea self.data = init.data or {} self.color_off = init.color_off or {0,0,0} self.color_on = init.color_on or {255,255,255} self.color_disabled = init.color_disabled or {127,127,127} self.padding = init.padding or 2 self.elementpadding = init.elementpadding or 2 self.selectpadding = init.selectpadding or 1 self.x,self.y,self.w,self.h = 0,0,0,0 return self end function cm:draw(x,y) self.x,self.y,self.w,self.h = x,y,self:getWidth(),self:getHeight() local w,h = self.w,self.h love.graphics.setColor(self.color_on) love.graphics.rectangle("fill",x-self.padding,y-self.padding, w+self.padding*2,h+self.padding*2) local f = love.graphics.getFont() for i,v in pairs(self.data) do local vx,vy,vw,vh = self:getEntryArea(i) if v.hover then love.graphics.setColor(self.color_off) love.graphics.rectangle("fill", vx-self.selectpadding,vy-self.selectpadding, vw+self.selectpadding*2,vh+self.selectpadding*2) end if v.color then love.graphics.setColor(v.color) love.graphics.rectangle("fill",vx,vy,vw,vh) end if v.label or v.label_left or v.label_right then if v.hover then love.graphics.setColor(self.color_on) else love.graphics.setColor(v.exe and self.color_off or self.color_disabled) end if v.label_left then love.graphics.printf(v.label_left,vx,vy,vw,"left") end if v.label then love.graphics.printf(v.label,vx,vy,vw,"center") end if v.label_right then love.graphics.printf(v.label_right,vx,vy,vw,"right") end if v.tooltip and v.hover and v.hover > 0.25 then local ttx,tty = vx+vw+self.padding*3,vy local ttw = 100 local f = love.graphics.getFont() local ttw,wrappedtext = f:getWrap(v.tooltip,ttw) local tth = #wrappedtext * f:getHeight() love.graphics.setColor(self.color_on) love.graphics.rectangle("fill", ttx-self.padding,tty-self.padding, ttw+self.padding*2,tth+self.padding*2) love.graphics.setColor(self.color_off) love.graphics.printf(v.tooltip,ttx,tty,ttw) end end end end function cm:getEntryArea(index) local f = love.graphics.getFont() return self.x,self.y+(index-1)*(f:getHeight()+self.elementpadding), self.w,f:getHeight() end function cm:mouseInArea() local mx,my = love.mouse.getPosition() return mx >= self.x and mx <= self.x + self.w and my >= self.y and my <= self.y + self.h end function cm:update(dt) local mx,my = love.mouse.getPosition() local click = love.mouse.isDown(1,2,3) for i,v in pairs(self.data) do local x,y,w,h = self:getEntryArea(i) if mx >= x and mx <= x+w and my >= y and my <= y+h then v.hover = (v.hover or 0) + dt if click then if v.exe then v.exe() end return true end else v.hover = nil end end return false end function cm:getHeight() local f = love.graphics.getFont() return #self.data*(f:getHeight()+self.elementpadding)-self.elementpadding end function cm:getWidth() local f = love.graphics.getFont() local width = f:getHeight() for _,v in pairs(self.data) do width = math.max(width, f:getWidth(v.label_left or "") + f:getWidth(v.label or "") + f:getWidth(v.label_right or "") + (v.label == nil and 8 or 0) ) end return width end return cm
require("mod.elona.data.map_archetype.world") require("mod.elona.data.map_archetype.town") require("mod.elona.data.map_archetype.guild") require("mod.elona.data.map_archetype.instanced") require("mod.elona.data.map_archetype.player_owned") require("mod.elona.data.map_archetype.dungeon") require("mod.elona.data.map_archetype.unique") require("mod.elona.data.map_archetype.special")
local S = aurum.get_translator() aurum.tools.enchants = {} function aurum.tools.get_category_enchants(category) local ret = {} for k,v in pairs(aurum.tools.enchants) do if v.categories[category] then table.insert(ret, k) end end return ret end function aurum.tools.register_enchant(name, def) local def = b.t.combine({ categories = {}, description = "?", longdesc = nil, apply = function(state, level, stack) end, -- Required mana level threshold to apply this enchantment. mana_level = function(level) return (level + 1) ^ 2 end, -- How high can naturally generated enchantments of this kind go? max_level = 3, }, def) aurum.tools.enchants[name] = def local docs = {} if def.longdesc then table.insert(docs, def.longdesc) end local category_keys = b.t.keys(b.t.map(def.categories, function(v) return v or nil end)) if #category_keys > 0 then table.sort(category_keys) table.insert(docs, S("Enchantment categories: @1", table.concat(category_keys, ", "))) end doc.add_entry("enchants", name, { name = def.description, data = table.concat(docs, "\n\n"), }) end -- Get possible enchant types for a tool, returns array or nil if unenchantable. function aurum.tools.get_possible_enchants(name) local def = minetest.registered_items[name] if (def._enchant_levels or 0) == 0 then return nil end local ret = {} for _,index in ipairs(def._enchants) do ret = b.t.icombine(ret, aurum.tools.get_category_enchants(index) or {}) end return ret end doc.sub.items.register_factoid("tools", "use", function(itemstring, def) local possible = aurum.tools.get_possible_enchants(itemstring) if possible then possible = b.t.map(possible, function(v) return aurum.tools.enchants[v].description end) table.sort(possible) return S("This tool has a potential enchantment level of @1.", def._enchant_levels) .. ((#possible > 0) and ("\n" .. S("Enchantment types: @1", table.concat(possible, ", "))) or "") end return "" end) -- Get a table of item enchants. function aurum.tools.get_item_enchants(stack) local meta = stack:get_meta() return meta:contains("enchants") and minetest.deserialize(meta:get_string("enchants")) or {} end -- Write back enchants and refresh properties. -- Returns stack. function aurum.tools.set_item_enchants(stack, enchants) stack:get_meta():set_string("enchants", minetest.serialize(enchants)) return aurum.tools.refresh_item(stack) end function aurum.tools.get_item_info(stack) local def = minetest.registered_items[stack:get_name()] if not def or not aurum.tools.get_possible_enchants(stack:get_name()) then return nil end local enchants = aurum.tools.get_item_enchants(stack) local used = 0 for _,v in pairs(enchants) do used = used + v end return { total = def._enchant_levels, used = used, enchants = enchants, } end aurum.tools.enchant_callbacks = {} function aurum.tools.register_enchant_callback(def) table.insert(aurum.tools.enchant_callbacks, b.t.combine({ init = function(state, stack) end, apply = function(state, stack) end, }, def)) end -- Refresh item properties from def and enchants. -- Returns stack. function aurum.tools.refresh_item(stack) local enchants = aurum.tools.get_item_enchants(stack) -- Create initial state from base properties. local state = { description = {stack:get_definition().description}, } for _,v in ipairs(aurum.tools.enchant_callbacks) do v.init(state, stack) end local applied = false -- Apply all enchantments. for name,level in b.t.spairs(enchants) do if level > 0 then applied = true table.insert(state.description, S("@1: @2", aurum.tools.enchants[name].description, level)) stack = aurum.tools.enchants[name].apply(state, level, stack) or stack end end -- Update enchanted variant. stack:set_name(applied and stack:get_definition()._enchanted or stack:get_definition()._unenchanted) -- Write refreshed data. for _,v in ipairs(aurum.tools.enchant_callbacks) do v.apply(state, stack) end aurum.set_stack_description(stack, table.concat(state.description, "\n")) return stack end
local lspconfig = require('lspconfig') local util = require('lspconfig/util') -- local lsp_status = require('lsp-status') local api = vim.api -- lsp_status.register_progress() local custom_on_attach = function(client, bufnr) api.nvim_buf_set_option(bufnr, 'omnifunc', 'v:lua.vim.lsp.omnifunc') -- Mappings. local opts = { noremap=true, silent=true, } local function nmap_lsp(keys, cmd) api.nvim_buf_set_keymap( bufnr, 'n', keys, '<cmd>lua vim.lsp.'..cmd..'<CR>', opts ) end nmap_lsp('gd', 'buf.declaration()') nmap_lsp('<c-]>', 'buf.definition()') nmap_lsp('K', 'buf.hover()') nmap_lsp('D', 'util.show_line_diagnostics()') nmap_lsp('gi', 'util.implementation()') nmap_lsp('<C-k>', 'buf.signature_help()') nmap_lsp(',rn', 'buf.rename()') nmap_lsp('gy', 'buf.type_definition()') nmap_lsp('pd', 'buf.peek_definition()') nmap_lsp('gr', 'buf.references()') nmap_lsp(']d', 'diagnostic.goto_next()') nmap_lsp('[d', 'diagnostic.goto_prev()') nmap_lsp('<leader>do', 'diagnostic.set_loclist()') -- api.nvim_set_var('diagnostic_enable_virtual_text','1') require'completion'.on_attach() -- lsp_status.on_attach(client) end -- efm doesn't like being told to fold, so only fold on buffers that -- don't have EFM but use an LSP server that supports folding. local custom_on_attach_folding = function(client, bufnr) custom_on_attach(client, bufnr) require('folding').on_attach() end -- lspconfig.bashls.setup{ -- on_attach = custom_on_attach, -- filetypes = { "sh", "zsh" } -- } lspconfig.ccls.setup{ on_attach = custom_on_attach_folding, } lspconfig.html.setup{ on_attach = custom_on_attach_folding, } lspconfig.cssls.setup{ cmd = {"/home/rkumar/Executables/npm/bin/vscode-json-languageserver"}, on_attach = custom_on_attach_folding, root_dir = util.root_pattern("package.json",".git") } lspconfig.gopls.setup{ on_attach = custom_on_attach_folding, init_options = { linkTarget="pkg.go.dev", completionDocumentation=true, deepCompletion=true, fuzzyMatching=true } } lspconfig.dockerls.setup{ on_attach = custom_on_attach_folding, } lspconfig.ghcide.setup{ on_attach = custom_on_attach_folding, } lspconfig.jsonls.setup{ on_attach = custom_on_attach_folding, } lspconfig.vimls.setup{ on_attach = custom_on_attach } lspconfig.efm.setup{ on_attach = custom_on_attach, -- only run on configured filetypes filetypes = {'pandoc', 'markdown', 'gfm', 'markdown.pandoc.gfm', 'rst','sh','vim','make','yaml','dockerfile'}, } -- lspconfig.jedi_language_server.setup{ -- on_attach = custom_on_attach, -- } lspconfig.pyright.setup{ on_attach=custom_on_attach, } local custom_on_attach_nlua = function(client, bufnr) custom_on_attach_folding(client, bufnr) end require('nlua.lsp.nvim').setup(lspconfig, { on_attach = custom_on_attach_nlua, settings = { Lua = { runtime = { version = "LuaJIT" } } } })
local android = premake.extensions.android android.manifest = {} local manifest = android.manifest -- -- Generate AndroidManifest.xml -- function manifest.generate(prj) _p(0, '<?xml version="1.0" encoding="utf-8"?>') _p(0, '<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.%s" android:versionCode="1" android:versionName="1.0">', prj.targetname) _p(1, '<uses-sdk android:minSdkVersion="9" android:targetSdkVersion="21"/>') _p(1, '<application android:label="%s" android:hasCode="false">', prj.targetname) _p(2, '<activity android:name="android.app.NativeActivity" android:label="%s" android:configChanges="orientation|keyboardHidden">', prj.targetname) _p(3, '<meta-data android:name="android.app.lib_name" android:value="$(AndroidAppLibName)" />') _p(3, '<intent-filter>') _p(4, '<action android:name="android.intent.action.MAIN" />') _p(4, '<category android:name="android.intent.category.LAUNCHER" />') _p(3, '</intent-filter>') _p(2, '</activity>') _p(1, '</application>') _p(0, '</manifest>') end
local files = {} local ctrlp = require('core.ctrlp') files.name = 'files' files.version = 'v0.1' files.cmds = {} files.cmds.grep = ctrlp.require_on_exported_call('ctrlp_files.files').grep function files.setup() ctrlp.register(files) end return files
print( "sh_sound_precacher" ) --[[ local sound_list = sound_list or {} hook.Add( "EntityEmitSound", "TV_ShSoundPrecacher_EntityEmitSound", function( data ) if not sound_list[ data.SoundName ] then print( "NEW:", data.SoundName, RealTime() ) sound_list[data.SoundName] = true end end ) ]]
local io = require('io') local os = require('os') local function dirname(str) if str:match(".-/.-") then local name = string.gsub(str, "(.*/)(.*)", "%1") return name else return '' end end local function basename(s) local name = string.gsub(s, "(.*/)(.*)", "%2") return name end local function check(ok, ...) if ok then return ok, ... end io.stderr:write("luajit: ", ...) io.stderr:write("\n") os.exit(1) end local function bytearray(s, indent) local bytes, lines = {}, {} local n, m = 0, 0 for i=1,#s do local byte = tostring(string.byte(s, i)) m = m + #byte + 1 if m > 78 then table.insert(lines, table.concat(bytes, ",", 1, n)) n, m = 0, #byte + 1 end n = n + 1 bytes[n] = byte end table.insert(lines, table.concat(bytes, ",", 1, n)) return table.concat(lines, ",\n" .. indent) end local function bytecode(file) return bytearray(file.bytecode, "\t\t") end -- -- collect local function collect_file(root, file, debug) local id = file:sub(#root + 1, -5):gsub("/", "."):gsub(".init$", "") local f = check(loadfile(file)) return { id = id, req_name = id, func_name = id:gsub("%.", "_"), path = path, bytecode = string.dump(f, not debug) } end local function collect(path, files, debug) for file in io.popen("find -L '" .. path .. "' -name '*.lua'"):lines() do local f = collect_file(dirname(path), file, debug) if f then table.insert(files, f) end end end -- -- output local function output_bytecode(file) return ([[ static const unsigned char buf[] = { %s }; if (luaL_loadbufferx (L, (const char *)buf, sizeof buf, "%s", "b")) { lua_pop (L, 2); return 0; } lua_pushstring (L, "%s"); lua_call (L, 1, 1); ]]):format(bytecode(file), file.id, file.id) end local function output_file(file) return ([[ static int load_%s (lua_State *L) { %s return 1; } ]]):format(file.func_name, output_bytecode(file)) end local function output_open_file(file) return ([[ lua_pushcfunction (L, load_%s); lua_setfield (L, -2, "%s"); ]]):format(file.func_name, file.req_name) end local function output_open(name, files) local calls = {} for i, file in ipairs(files) do table.insert(calls, output_open_file(file)) end return ([[ int luaopen_%s (lua_State *L) { lua_getfield (L, LUA_REGISTRYINDEX, "_PRELOAD"); %s lua_pop (L, 1); return 0; } ]]):format(name, table.concat(calls, "\n")) end local function output_bundle(out, inc, name, files) out:write('#include <'..inc..'/lua.h>\n') out:write('#include <'..inc..'/lauxlib.h>\n') out:write('#include <'..inc..'/lualib.h>\n') for i, file in ipairs(files) do out:write(output_file(file)) out:write("\n") end out:write(output_open(name, files)) out:write("\n") end return { usage = function() return ([[Usage: %s bundle [-o <file] [-n <name>] <module> [module...] Options: -o <file>, --out <file> # file to out to [default: stdout] -n <name>, --name <name> # bundle name [default: name of first module # listed] -f <file>, --file <file> # bundle a single file ]]):format(require("levee.meta").name) end, parse = function(argv) local options = {modules = {}} while argv:more() do local opt = argv:option() if opt == nil then local path = argv:next():gsub("/$", "") table.insert(options.modules, path) elseif opt == "o" or opt == "output" then options.out = argv:output() elseif opt == "n" or opt == "name" then options.name = argv:next() elseif opt == "f" or opt == "file" then options.file = argv:next() end end if #options.modules == 0 and not options.file then io.stderr:write("no modules provided\n") os.exit(1) end options.out = options.out or io.stdout return options end, run = function(options) local files = {} local inc = options.include or "levee" local debug = true if options.script then options.name = options.name or "__script" local f = check(loadstring(options.script)) table.insert(files, { id = "__script", req_name = "__script.main", func_name = "__script", bytecode = string.dump(f), }) elseif options.file then options.name = options.name or basename(options.file:match("^(.+)%..+$")) local f = collect_file(dirname(options.file), options.file, debug) if f then f.req_name = f.req_name .. ".main" table.insert(files, f) end else options.name = options.name or basename(options.modules[1]) for _, path in ipairs(options.modules) do -- TODO: make debug mode externally configurable collect(path, files, debug) if not options.bootstrap then local _ = require("levee")._ local file = _.path.join(path, "assets") local f = _.bundle.assets(file) local root = dirname(path) local id = file:sub(#root + 1):gsub("/", ".") table.insert(files, { id = id, req_name = id, func_name = id:gsub("%.", "_"), bytecode = string.dump(f), }) local file = _.path.join(path, "templates") local f = _.bundle.templates(file) local root = dirname(path) local id = file:sub(#root + 1):gsub("/", ".") table.insert(files, { id = id, req_name = id, func_name = id:gsub("%.", "_"), bytecode = string.dump(f), }) end end end output_bundle(options.out, inc, options.name, files) end, }
local typedefs = require 'nelua.typedefs' local tabler = require 'nelua.utils.tabler' local types = require 'nelua.types' local Symbol = require 'nelua.symbol' local Attr = require 'nelua.attr' local version = require 'nelua.version' local primtypes = typedefs.primtypes local symdefs = {} local function define_symbol(name, type, attrs) local symbol = Symbol{ name = name, codename = 'nelua_' .. name, type = type or primtypes.any, used = true, const = true, builtin = true, staticstorage = true } if attrs then tabler.update(symbol, attrs) end symdefs[name] = symbol return symbol end local function define_function(name, argattrs, rettypes, attrs) local type = types.FunctionType(argattrs, rettypes) type:suggest_nickname(name) type.sideeffect = (attrs and attrs.sideeffect) and true or false local symbol = define_symbol(name, type, attrs) type.symbol = symbol return symbol end -- nelua only define_function('likely', {Attr{name='cond', type=primtypes.boolean}}, {primtypes.boolean}) define_function('unlikely', {Attr{name='cond', type=primtypes.boolean}}, {primtypes.boolean}) define_function('panic', {Attr{name='message', type=primtypes.stringview}}, {}, {noreturn=true, sideeffect=true}) define_symbol('check') define_symbol('nilptr', primtypes.nilptr) -- lua define_function('error', {Attr{name='message', type=primtypes.stringview}}, {}, {noreturn=true, sideeffect=true}) define_function('warn', {Attr{name='message', type=primtypes.stringview}}, {}, {sideeffect=true}) define_function('type', {Attr{name='value', type=primtypes.any}}, {primtypes.stringview}) define_function('require', {Attr{name='modname', type=primtypes.stringview}}, {}) define_symbol('print') define_symbol('assert') define_symbol('_G', primtypes.table) define_symbol('_VERSION', primtypes.stringview, {comptime=true, value=version.NELUA_VERSION}) return symdefs
-------------------------------------------------------------------------------- -- Exponential statistical distribution. -- -- Copyright (C) 2011-2016 Stefano Peluchetti. All rights reserved. -------------------------------------------------------------------------------- local ffi = require "ffi" local exp, log = math.exp, math.log local expo_mt = { __new = function(ct, lambda) if not lambda then error("distribution parameters must be set at construction") end if lambda <= 0 then error("lambda must be positive, lambda is ", lambda) end return ffi.new(ct, lambda) end, copy = function(self) return ffi.new(ffi.typeof(self), self) end, range = function(self) return 0, 1/0 end, pdf = function(self, x) if x < 0 then return 0 end return self._lambda*exp(-self._lambda*x) end, logpdf = function(self, x) if x < 0 then return -1/0 end return log(self._lambda) -self._lambda*x end, mean = function(self) return 1/self._lambda end, var = function(self) return 1/self._lambda^2 end, sample = function(self, rng) return -log(rng:sample())/self._lambda end, } expo_mt.__index = expo_mt local dist = ffi.metatype("struct { double _lambda; }", expo_mt) return { dist = dist, }
require ("_prolog") require ("_opencv") function RequireParams() lips_RequireParams("features_detector = combo([AKAZE, ORBS, BRISK, KAZE, SURF, SIFT, FAST_DAISY, FAST_FREAK] 0);" .. "matching_algorithm = combo([Brute Hamming, Brute force matching, FLANN] 2);" .. "homography = combo([LS, RANSAC, LMEDS, RHO] 1);" .. "match_ratio = float([0.1, 2.0] 0.7);" .. "detect_multiple = bool([] false);") end function main() if (not OcvEnabled) then lips_SendMessage(errOcvDisabed) return end if (TargetImage.Plane == nil) then lips_SendMessage(errTargetEmpty) return end lips_SendCommand("LayerClearAll") lips_SendCommand("LayerBackground", "target") -- set source and target image ocv_SetImage("source", SourceImage) ocv_SetImage("target", TargetImage) local params = tostring(features_detector)..", 0, 0, 0" -- initialize/create object detector ocv_Process("ObjDetectorBegin") -- detect and compute ocv_Process("Features2D", params) local matchParams = tostring(matching_algorithm)..", "..tostring(match_ratio)..", true" -- true => OpenCV matching image is created/exported ocv_Process("Matches2D", matchParams) ocv_FlipExport() -- because image is upside down in OpenCV local id = ocv_GetLastImageId() local pictMatch = lips_GetImageFromId(id) if (pictMatch ~= nil) then lips_ExportImage(pictMatch, "matches", true) end params = "6, "..tostring(homography)..", true, true, false" -- image is created/exported and alpha channel added (if necessary) ocv_Process("Homography2D", params) ocv_FlipExport() -- because image is upside down in OpenCV id = ocv_GetLastImageId() --lips_SendMessage(tostring(id)) local pictHomography = lips_GetImageFromId(id) if (pictHomography ~= nil) then lips_ExportImage(pictHomography, "aligned image 1.") lips_SendCommand("LayerAdd", "last") end if (not detect_multiple) then ocv_Process("ObjDetectorEnd") return end local rc = 0 local objCounter = 2 while (rc == 0) do ocv_FlipExport() -- flip it back again because we'll use it for recalculation rc = ocv_Process("ReduceFeatures2D", "2, false") if rc ~= 0 then break end -- find new matches rc = ocv_Process("Matches2D", matchParams) if rc ~= 0 then break end rc = ocv_Process("RecalcHomography2D") if rc == 0 then ocv_FlipExport() -- because image is upside down in OpenCV id = ocv_GetLastImageId() --lips_SendMessage(tostring(id)) pictHomography = lips_GetImageFromId(id) if (pictHomography ~= nil) then --lips_SendMessage(tostring(pictHomography.Width).." x "..tostring(pictHomography.Height)) lips_ExportImage(pictHomography, "aligned image "..tostring(objCounter)..".") lips_SendCommand("LayerAdd", "last") objCounter = objCounter + 1 end end end ocv_Process("ObjDetectorEnd") end
function LoadSPH(property) local sphloader sphloader = require("SphLoader")() sphloader:Load(property.filepath) return sphloader end
local rdebug = require 'remotedebug.visitor' local variables = require 'backend.worker.variables' local readfile = package.readfile if not readfile then function readfile(filename) local fullpath = assert(package.searchpath(filename, package.path)) local f = assert(io.open(fullpath)) local str = f:read 'a' f:close() return str end end local eval_repl = assert(rdebug.reffunc(readfile 'backend.worker.eval_repl')) local eval_watch = assert(rdebug.reffunc(readfile 'backend.worker.eval_watch')) local function run_repl(frameId, expression) local res = table.pack(rdebug.evalwatch(eval_repl, 'return ' .. expression, frameId)) if not res[1] then local ok = rdebug.evalwatch(eval_repl, expression, frameId) if not ok then return false, res[2] end return true, '' end if #res == 1 then return true, 'nil' end local _, ref res[2], _, ref = variables.createRef(frameId, res[2], expression) for i = 3, res.n do res[i] = variables.createText(res[i]) end return true, table.concat(res, ',', 2), ref end local function run_hover(frameId, expression) local ok, res = rdebug.evalwatch(eval_watch, expression, frameId) if not ok then return false, res end local res, _, ref = variables.createRef(frameId, res, expression) return true, res, ref end local function run_watch(frameId, expression) local res = table.pack(rdebug.evalwatch(eval_watch, expression, frameId)) if not res[1] then return false, res[2] end if #res == 0 then return true, 'nil' end local _, ref res[2], _, ref = variables.createRef(frameId, res[2], expression) for i = 3, res.n do res[i] = variables.createText(res[i]) end return true, table.concat(res, ',', 2), ref end local function run_copyvalue(frameId, expression) local res = table.pack(rdebug.evalwatch(eval_watch, expression, frameId)) if not res[1] then return false, res[2] end if #res == 0 then return true, 'nil' end for i = 2, res.n do res[i] = variables.createText(res[i]) end return true, table.concat(res, ',', 2) end local m = {} function m.run(frameId, expression, context) if context == "watch" then return run_watch(frameId, expression) end if context == "hover" then return run_hover(frameId, expression) end if context == "repl" then return run_repl(frameId, expression) end if context == nil then return run_copyvalue(frameId, expression) end return nil, ("unknown context `%s`"):format(context) end function m.eval(expression) return rdebug.eval(eval_watch, expression, 0) end return m
return {'edmond','edmund','edmee','edmonds','edmunds','edmees'}
-- See LICENSE for terms local properties = {} local c = 0 local T = T local table_concat = table.concat local TraitPresets = TraitPresets --~ local added_cats = {} local function AddColonists(list) for i = 1, #list do local id = list[i] local trait = TraitPresets[id] local cat = trait.category == "other" and T(10405, "Other") or trait.category == "Age Group" and T(11607, "Age Group") or T(trait.category) --or trait.category == "Negative" and T(0000, "Negative") --~ -- add categories --~ if not added_cats[trans(cat)] then --~ c = c + 1 --~ properties[c] = PlaceObj("ModItemOptionToggle", { --~ "name", "cats" .. cat, --~ "DisplayName", table_concat(T(cat) .. T(" <yellow>-Category-</color>")), --~ "Help", T(302535920011751, "On/Off does nothing."), --~ }) --~ added_cats[trans(cat)] = true --~ end c = c + 1 properties[c] = PlaceObj("ModItemOptionToggle", { "name", "Trait_" .. id, "DisplayName", table_concat(cat .. ": " .. T(trait.display_name)), "Help", table_concat(T(trait.description) .. "\n\n" .. id), "DefaultValue", false, }) end end local t = ChoGGi.Tables AddColonists(t.ColonistAges) AddColonists(t.NegativeTraits) AddColonists(t.PositiveTraits) AddColonists(t.OtherTraits) local CmpLower = CmpLower local _InternalTranslate = _InternalTranslate table.sort(properties, function(a, b) return CmpLower(_InternalTranslate(a.DisplayName), _InternalTranslate(b.DisplayName)) end) table.insert(properties, 1, PlaceObj("ModItemOptionToggle", { "name", "SkipTourists", "DisplayName", T(302535920011898, "Skip Tourists"), "Help", T(302535920011899, "Never remove tourists."), "DefaultValue", false, })) return properties
local assets = { Asset("ANIM", "anim/maxwell_torch.zip") } local prefabs = { "maxwelllight_flame", } local function changelevels(inst, order) for i=1, #order do inst.components.burnable:SetFXLevel(order[i]) Sleep(0.05) end end local function light(inst) inst.task = inst:StartThread(function() changelevels(inst, inst.lightorder) end) end local function extinguish(inst) if inst.components.burnable:IsBurning() then inst.components.burnable:Extinguish() end end local function fn() local inst = CreateEntity() local trans = inst.entity:AddTransform() local anim = inst.entity:AddAnimState() inst.entity:AddSoundEmitter() local minimap = inst.entity:AddMiniMapEntity() minimap:SetIcon("maxwelltorch.png") anim:SetBank("maxwell_torch") anim:SetBuild("maxwell_torch") anim:PlayAnimation("idle",false) inst:AddTag("structure") MakeObstaclePhysics(inst, .1) ----------------------- inst:AddComponent("burnable") inst.components.burnable:AddBurnFX("maxwelllight_flame", Vector3(0,0,0), "fire_marker") inst.components.burnable:SetOnIgniteFn(light) ------------------------ inst:AddComponent("inspectable") return inst end local function arealight() local inst = fn() inst.lightorder = {5,6,7,8,7} inst:AddComponent("playerprox") inst.components.playerprox:SetDist(17, 27 ) inst.components.playerprox:SetOnPlayerNear(function() if not inst.components.burnable:IsBurning() then inst.components.burnable:Ignite() end end) inst.components.playerprox:SetOnPlayerFar(extinguish) inst:AddComponent("named") inst.components.named:SetName(STRINGS.NAMES["MAXWELLLIGHT"]) inst.components.inspectable.nameoverride = "maxwelllight" return inst end local function spotlight() local inst = fn() inst.lightorder = {1,2,3,4,3} return inst end return Prefab( "common/objects/maxwelllight", spotlight, assets, prefabs), Prefab("common/objects/maxwelllight_area", arealight, assets, prefabs)
TestModule2 = {} register_module(TestModule2,"TestModule2"); function TestModule2.Init() io.write("TestModule2 Init!\n"); end function TestModule2.AfterInit() io.write("TestModule2 AfterInit!" .. tostring(pLuaScriptModule) .. "\n"); end function TestModule2.Execute() io.write("TestModule2 Execute!\n"); end function TestModule2.BeforeShut() io.write("TestModule2 BeforeShut!\n"); end function TestModule2.Shut() io.write("TestModule2 Shut!\n"); end
-- Main module -- Namespaces and global variables local _, SCRollHelper = ...; SCRollHelper.globalRolling = false; SCRollHelper.globalBonusesValue = 0; -- Some basics SCrollHelperCurrentDB = {}; -- Initalise main database troubleshootingEnabled = true; -- "true"" if troubleshooting is enabled -- helper function to throw errors. function SCRollHelper.UIError( msg ) if troubleshootingEnabled == false then print(msg); end end -- Function to clean out nil values from an array function SCRollHelper.CleanNils(array) local sorted = {} -- Make a temporary array for _,i in pairs(array) do -- Iterate the Database sorted[ #sorted+1 ] = i -- Add non-nil items end return sorted -- Return the sorted array end -- Function to load in all the saved variables function SCRollHelper.loadSavedVariables () -- Copy SavedVariables into Database, or create a new Database if one doesn't exist. SCrollHelperCurrentDB = SCrollHelperDB or {RollRow={},Settings={},GlobalBonus=0,CurrentVersion="v0.6 Alpha"}; -- Load global roll bonus, or set it to 0 SCRollHelper.globalBonusesValue = SCrollHelperCurrentDB["GlobalBonus"] or 0; -- Check version - If version data doesn't exist then wipe the database (For version 0.6) if SCrollHelperCurrentDB["CurrentVersion"] ~= "v0.6 Alpha" then SendSystemMessage("SCRollHelper - Database error or old database -> Resetting the addon's SavedVariables."); SCrollHelperCurrentDB = {RollRow={},Settings={},GlobalBonus=0,CurrentVersion="v0.6 Alpha"} -- Make a new working database end -- Load the current version SCRollHelper.CurrentVersion = SCrollHelperCurrentDB["CurrentVersion"]; SCRollHelper.UIError("SCRollHelper (SCRollHelperInit.lua) - Savedvariables loaded. globalBonusesValue is " .. SCRollHelper.globalBonusesValue); end SCRollHelper.UIError("SCRollHelper (SCRollHelperInit.lua) - Initialisation complete "); -- Troubleshooting
-- Copyright 2006-2019 Mitchell mitchell.att.foicica.com. See License.txt. -- C LPeg lexer. local lexer = require('lexer') local token, word_match = lexer.token, lexer.word_match local P, R, S = lpeg.P, lpeg.R, lpeg.S local lex = lexer.new('ansi_c') -- Whitespace. lex:add_rule('whitespace', token(lexer.WHITESPACE, lexer.space^1)) -- Keywords. lex:add_rule('keyword', token(lexer.KEYWORD, word_match[[ auto break case const continue default do else extern for goto if inline register restrict return sizeof static switch typedef volatile while -- C11. _Alignas _Alignof _Atomic _Generic _Noreturn _Static_assert _Thread_local ]])) -- Types. lex:add_rule('type', token(lexer.TYPE, word_match[[ char double enum float int long short signed struct union unsigned void _Bool _Complex _Imaginary -- Stdlib types. ptrdiff_t size_t max_align_t wchar_t intptr_t uintptr_t intmax_t uintmax_t ]] + P('u')^-1 * 'int' * (P('_least') + '_fast')^-1 * R('09')^1 * '_t')) -- Constants. lex:add_rule('constants', token(lexer.CONSTANT, word_match[[ NULL -- Preprocessor. __DATE__ __FILE__ __LINE__ __TIME__ __func__ -- errno.h. E2BIG EACCES EADDRINUSE EADDRNOTAVAIL EAFNOSUPPORT EAGAIN EALREADY EBADF EBADMSG EBUSY ECANCELED ECHILD ECONNABORTED ECONNREFUSED ECONNRESET EDEADLK EDESTADDRREQ EDOM EDQUOT EEXIST EFAULT EFBIG EHOSTUNREACH EIDRM EILSEQ EINPROGRESS EINTR EINVAL EIO EISCONN EISDIR ELOOP EMFILE EMLINK EMSGSIZE EMULTIHOP ENAMETOOLONG ENETDOWN ENETRESET ENETUNREACH ENFILE ENOBUFS ENODATA ENODEV ENOENT ENOEXEC ENOLCK ENOLINK ENOMEM ENOMSG ENOPROTOOPT ENOSPC ENOSR ENOSTR ENOSYS ENOTCONN ENOTDIR ENOTEMPTY ENOTRECOVERABLE ENOTSOCK ENOTSUP ENOTTY ENXIO EOPNOTSUPP EOVERFLOW EOWNERDEAD EPERM EPIPE EPROTO EPROTONOSUPPORT EPROTOTYPE ERANGE EROFS ESPIPE ESRCH ESTALE ETIME ETIMEDOUT ETXTBSY EWOULDBLOCK EXDEV ]])) -- Identifiers. lex:add_rule('identifier', token(lexer.IDENTIFIER, lexer.word)) -- Strings. local sq_str = P('L')^-1 * lexer.delimited_range("'", true) local dq_str = P('L')^-1 * lexer.delimited_range('"', true) lex:add_rule('string', token(lexer.STRING, sq_str + dq_str)) -- Comments. local line_comment = '//' * lexer.nonnewline_esc^0 local block_comment = '/*' * (lexer.any - '*/')^0 * P('*/')^-1 + lexer.starts_line('#if') * S(' \t')^0 * '0' * lexer.space * (lexer.any - lexer.starts_line('#endif'))^0 * (lexer.starts_line('#endif'))^-1 lex:add_rule('comment', token(lexer.COMMENT, line_comment + block_comment)) -- Numbers. lex:add_rule('number', token(lexer.NUMBER, lexer.float + lexer.integer)) -- Preprocessor. local preproc_word = word_match[[ define elif else endif if ifdef ifndef line pragma undef ]] lex:add_rule('preprocessor', #lexer.starts_line('#') * (token(lexer.PREPROCESSOR, '#' * S('\t ')^0 * preproc_word) + token(lexer.PREPROCESSOR, '#' * S('\t ')^0 * 'include') * (token(lexer.WHITESPACE, S('\t ')^1) * token(lexer.STRING, lexer.delimited_range('<>', true, true)))^-1)) -- Operators. lex:add_rule('operator', token(lexer.OPERATOR, S('+-/*%<>~!=^&|?~:;,.()[]{}'))) -- Fold points. lex:add_fold_point(lexer.PREPROCESSOR, '#if', '#endif') lex:add_fold_point(lexer.PREPROCESSOR, '#ifdef', '#endif') lex:add_fold_point(lexer.PREPROCESSOR, '#ifndef', '#endif') lex:add_fold_point(lexer.OPERATOR, '{', '}') lex:add_fold_point(lexer.COMMENT, '/*', '*/') lex:add_fold_point(lexer.COMMENT, '//', lexer.fold_line_comments('//')) return lex
------------------------------------------------------------------------------- -- Title: Mik's Scrolling Battle Text Parser -- Author: Mikord ------------------------------------------------------------------------------- -- Create module and set its name. local module = {} local moduleName = "Parser" MikSBT[moduleName] = module ------------------------------------------------------------------------------- -- Imports. ------------------------------------------------------------------------------- -- Local references to various functions for faster access. local string_find = string.find local string_gmatch = string.gmatch local string_gsub = string.gsub local string_len = string.len local bit_band = bit.band local bit_bor = bit.bor local GetTime = GetTime local UnitClass = UnitClass local UnitGUID = UnitGUID local Print = MikSBT.Print local EraseTable = MikSBT.EraseTable ------------------------------------------------------------------------------- -- Constants. ------------------------------------------------------------------------------- -- Bit flags. local AFFILIATION_MINE = 0x00000001 local AFFILIATION_PARTY = 0x00000002 local AFFILIATION_RAID = 0x00000004 local AFFILIATION_OUTSIDER = 0x00000008 local REACTION_FRIENDLY = 0x00000010 local REACTION_NEUTRAL = 0x00000020 local REACTION_HOSTILE = 0x00000040 local CONTROL_HUMAN = 0x00000100 local CONTROL_SERVER = 0x00000200 local UNITTYPE_PLAYER = 0x00000400 local UNITTYPE_NPC = 0x00000800 local UNITTYPE_PET = 0x00001000 local UNITTYPE_GUARDIAN = 0x00002000 local UNITTYPE_OBJECT = 0x00004000 local TARGET_TARGET = 0x00010000 local TARGET_FOCUS = 0x00020000 local OBJECT_NONE = 0x80000000 -- Value when there is no GUID. local GUID_NONE = "0x0000000000000000" -- The maximum number of buffs and debuffs that can be on a unit. local MAX_BUFFS = 16 local MAX_DEBUFFS = 40 -- Aura types. local AURA_TYPE_BUFF = "BUFF" local AURA_TYPE_DEBUFF = "DEBUFF" -- Update timings. local UNIT_MAP_UPDATE_DELAY = 0.2 local PET_UPDATE_DELAY = 1 local REFLECT_HOLD_TIME = 3 local CLASS_HOLD_TIME = 300 -- Commonly used flag combinations. local FLAGS_ME = bit_bor(AFFILIATION_MINE, REACTION_FRIENDLY, CONTROL_HUMAN, UNITTYPE_PLAYER) local FLAGS_MINE = bit_bor(AFFILIATION_MINE, REACTION_FRIENDLY, CONTROL_HUMAN) local FLAGS_MY_GUARDIAN = bit_bor(AFFILIATION_MINE, REACTION_FRIENDLY, CONTROL_HUMAN, UNITTYPE_GUARDIAN) ------------------------------------------------------------------------------- -- Private variables. ------------------------------------------------------------------------------- -- Prevent tainting global _. local _ -- Dynamically created frames for receiving events and tooltip info. local eventFrame -- Name and GUID of the player. local playerName local playerGUID -- Used for timing between updates. local lastUnitMapUpdate = 0 local lastPetMapUpdate = 0 -- Whether or not values that need to be updated after a delay are stale. local isUnitMapStale local isPetMapStale -- Map of guids to unit ids. local unitMap = {} local petMap = {} -- Map of functions to call for supported combat log events. local captureFuncs -- Events to parse even if the source or recipient is not the player or pet. local fullParseEvents -- Information about global strings for CHAT_MSG_X events. local searchMap local searchCaptureFuncs local rareWords = {} local searchPatterns = {} local captureOrders = {} -- Captured and parsed event data. local captureTable = {} local parserEvent = {} -- List of functions to call when an event occurs. local handlers = {} -- Holds information about reflected skills to track how much was reflected. local reflectedSkills = {} local reflectedTimes = {} -- Holds information about guid to class mappings for known units. local classMapCleanupTime = 0 local classMap = {} local classTimes = {} local arenaUnits = {} ------------------------------------------------------------------------------- -- Utility functions. ------------------------------------------------------------------------------- -- **************************************************************************** -- Registers a function to be called when an event occurs. -- **************************************************************************** local function RegisterHandler(handler) handlers[handler] = true end -- **************************************************************************** -- Unregisters a previously registered function. -- **************************************************************************** local function UnregisterHandler(handler) handlers[handler] = nil end -- **************************************************************************** -- Tests if any of the bits in the passed testFlags are set in the unit flags. -- **************************************************************************** local function TestFlagsAny(unitFlags, testFlags) if (bit_band(unitFlags, testFlags) > 0) then return true end end -- **************************************************************************** -- Tests if all of the passed testFlags are set in the unit flags. -- **************************************************************************** local function TestFlagsAll(unitFlags, testFlags) if (bit_band(unitFlags, testFlags) == testFlags) then return true end end -- **************************************************************************** -- Sends the parser event to the registered handlers. -- **************************************************************************** local function SendParserEvent() for handler in pairs(handlers) do local success, ret = pcall(handler, parserEvent) if (not success) then geterrorhandler()(ret) end end end -- **************************************************************************** -- Compares two global strings so the most specific one comes first. This -- prevents incorrectly capturing information for certain events. -- **************************************************************************** local function GlobalStringCompareFunc(globalStringNameOne, globalStringNameTwo) -- Get the global string for the passed names. local globalStringOne = _G[globalStringNameOne] local globalStringTwo = _G[globalStringNameTwo] local gsOneStripped = string_gsub(globalStringOne, "%%%d?%$?[sd]", "") local gsTwoStripped = string_gsub(globalStringTwo, "%%%d?%$?[sd]", "") -- Check if the stripped global strings are the same length. if (string_len(gsOneStripped) == string_len(gsTwoStripped)) then -- Count the number of captures in each string. local numCapturesOne = 0 for _ in string_gmatch(globalStringOne, "%%%d?%$?[sd]") do numCapturesOne = numCapturesOne + 1 end local numCapturesTwo = 0 for _ in string_gmatch(globalStringTwo, "%%%d?%$?[sd]") do numCapturesTwo = numCapturesTwo + 1 end -- Return the global string with the least captures. return numCapturesOne < numCapturesTwo else -- Return the longest global string. return string_len(gsOneStripped) > string_len(gsTwoStripped) end end -- **************************************************************************** -- Converts the passed global string into a lua search pattern with a capture -- order table and stores the results so any requests to convert the same -- global string will just return the cached one. -- **************************************************************************** local function ConvertGlobalString(globalStringName) -- Don't do anything if the passed global string does not exist. local globalString = _G[globalStringName] if (globalString == nil) then return end -- Return the cached conversion if it has already been converted. if (searchPatterns[globalStringName]) then return searchPatterns[globalStringName], captureOrders[globalStringName] end -- Hold the capture order. local captureOrder local numCaptures = 0 -- Escape lua magic chars. local searchPattern = string.gsub(globalString, "([%^%(%)%.%[%]%*%+%-%?])", "%%%1") -- Loop through each capture and setup the capture order. for captureIndex in string_gmatch(searchPattern, "%%(%d)%$[sd]") do if (not captureOrder) then captureOrder = {} end numCaptures = numCaptures + 1 captureOrder[tonumber(captureIndex)] = numCaptures end -- Convert %1$s / %s to (.+) and %1$d / %d to (%d+). searchPattern = string.gsub(searchPattern, "%%%d?%$?s", "(.+)") searchPattern = string.gsub(searchPattern, "%%%d?%$?d", "(%%d+)") -- Escape any remaining $ chars. searchPattern = string.gsub(searchPattern, "%$", "%%$") -- Cache the converted pattern and capture order. searchPatterns[globalStringName] = searchPattern captureOrders[globalStringName] = captureOrder -- Return the converted global string. return searchPattern, captureOrder end -- **************************************************************************** -- Fills in the capture table with the captured data if a match is found. -- **************************************************************************** local function CaptureData(matchStart, matchEnd, c1, c2, c3, c4, c5, c6, c7, c8, c9) -- Check if a match was found. if (matchStart) then captureTable[1] = c1 captureTable[2] = c2 captureTable[3] = c3 captureTable[4] = c4 captureTable[5] = c5 captureTable[6] = c6 captureTable[7] = c7 captureTable[8] = c8 captureTable[9] = c9 -- Return the last position of the match. return matchEnd end -- Don't return anything since no match was found. return nil end -- **************************************************************************** -- Reorders the capture table according to the passed capture order. -- **************************************************************************** local function ReorderCaptures(capOrder) local t, o = captureTable, capOrder t[1], t[2], t[3], t[4], t[5], t[6], t[7], t[8], t[9] = t[o[1] or 1], t[o[2] or 2], t[o[3] or 3], t[o[4] or 4], t[o[5] or 5], t[o[6] or 6], t[o[7] or 7], t[o[8] or 8], t[o[9] or 9] end -- **************************************************************************** -- Parses the CHAT_MSG_X search style events. -- **************************************************************************** local function ParseSearchMessage(event, combatMessage) -- Leave if there is no map of global strings to search for the event. if (not searchMap[event]) then return end -- Loop through all of the global strings to search for the event. for _, globalStringName in pairs(searchMap[event]) do -- Make sure the capture func for the global string exists. local captureFunc = searchCaptureFuncs[globalStringName] if (captureFunc) then -- First, check if there is a rare word for the global string and it is in the combat -- message since a plain text search is faster than doing a full regular expression search. if (not rareWords[globalStringName] or string_find(combatMessage, rareWords[globalStringName], 1, true)) then -- Get capture data. local matchEnd = CaptureData(string_find(combatMessage, searchPatterns[globalStringName])) -- Check if a match was found. if (matchEnd) then -- Check if there is a capture order for the global string and reorder the data accordingly. if (captureOrders[globalStringName]) then ReorderCaptures(captureOrders[globalStringName]) end -- Erase the parser event table.. for key in pairs(parserEvent) do parserEvent[key] = nil end -- Populate fields that exist for all events. parserEvent.sourceGUID = GUID_NONE parserEvent.sourceFlags = OBJECT_NONE parserEvent.recipientGUID = playerGUID parserEvent.recipientName = playerName parserEvent.recipientFlags = FLAGS_ME parserEvent.recipientUnit = "player" -- Map the captured arguments into the parser event table. captureFunc(parserEvent, captureTable) -- Send the event. SendParserEvent() return end -- Match found. end -- Fast plain search. end -- Capture func is valid. end -- Loop through global strings to search. end -- **************************************************************************** -- Parses the parameter style events going to the combat log. -- **************************************************************************** local function ParseLogMessage(timestamp, event, hideCaster, sourceGUID, sourceName, sourceFlags, sourceRaidFlags, recipientGUID, recipientName, recipientFlags, recipientRaidFlags, ...) -- Make sure the capture function for the event exists. local captureFunc = captureFuncs[event] if (not captureFunc) then return end -- Look for spells the player reflected and make the damage belong to the player. if (sourceGUID == recipientGUID and reflectedTimes[recipientGUID] and event == "SPELL_DAMAGE") then local skillID = ... if (skillID == reflectedSkills[recipientGUID]) then -- Clear the reflected skill entries. reflectedTimes[recipientGUID] = nil reflectedSkills[recipientGUID] = nil -- Change the source to the player. sourceGUID = playerGUID sourceName = playerName sourceFlags = FLAGS_ME end end -- Attempt to figure out the source and recipient unitIDs. local sourceUnit = unitMap[sourceGUID] or petMap[sourceGUID] local recipientUnit = unitMap[recipientGUID] or petMap[recipientGUID] -- Treat guardians that are flagged as belonging to the player as their pet and vehicles and other objects as the player. if (not sourceUnit and TestFlagsAll(sourceFlags, FLAGS_MINE)) then sourceUnit = TestFlagsAll(sourceFlags, FLAGS_MY_GUARDIAN) and "pet" or "player" end if (not recipientUnit and TestFlagsAll(recipientFlags, FLAGS_MINE)) then recipientUnit = TestFlagsAll(recipientFlags, FLAGS_MY_GUARDIAN) and "pet" or "player" end -- Ignore the event if it is not one that should be fully parsed and it doesn't pertain to the player -- or pet. This is done to avoid wasting time parsing events that won't be used like damage that other -- players are doing. if (not fullParseEvents[event] and sourceUnit ~= "player" and sourceUnit ~= "pet" and recipientUnit ~= "player" and recipientUnit ~= "pet") then return end -- Erase the parser event table. for k in pairs(parserEvent) do parserEvent[k] = nil end -- Populate fields that exist for all events. parserEvent.sourceGUID = sourceGUID parserEvent.sourceName = sourceName parserEvent.sourceFlags = sourceFlags parserEvent.sourceUnit = sourceUnit parserEvent.recipientGUID = recipientGUID parserEvent.recipientName = recipientName parserEvent.recipientFlags = recipientFlags parserEvent.recipientUnit = recipientUnit -- Map the local arguments into the parser event table. captureFunc(parserEvent, ...) -- Track reflected skills. if (parserEvent.eventType == "miss" and parserEvent.missType == "REFLECT" and recipientUnit == "player") then -- Clean up old entries. for guid, reflectTime in pairs(reflectedTimes) do if (timestamp - reflectTime > REFLECT_HOLD_TIME) then reflectedTimes[guid] = nil reflectedSkills[guid] = nil end end -- Save the time of the reflect and the reflected skillID. reflectedTimes[sourceGUID] = timestamp reflectedSkills[sourceGUID] = parserEvent.skillID end -- Send the event. SendParserEvent() end ------------------------------------------------------------------------------- -- Startup utility functions. ------------------------------------------------------------------------------- -- **************************************************************************** -- Creates a list of events that will be fully parsed even if they event -- doesn't pertain to the player or player's pet. -- **************************************************************************** local function CreateFullParseList() fullParseEvents = { SPELL_AURA_APPLIED = true, SPELL_AURA_REMOVED = true, SPELL_AURA_APPLIED_DOSE = true, SPELL_AURA_REMOVED_DOSE = true, SPELL_CAST_START = true, } end -- **************************************************************************** -- Creates a map of global strings to search for CHAT_MSG_X events. -- **************************************************************************** local function CreateSearchMap() searchMap = { -- Honor Gains. CHAT_MSG_COMBAT_HONOR_GAIN = {"COMBATLOG_HONORGAIN", "COMBATLOG_HONORAWARD"}, -- Reputation Gains/Losses. CHAT_MSG_COMBAT_FACTION_CHANGE = {"FACTION_STANDING_INCREASED", "FACTION_STANDING_DECREASED"}, -- Skill Gains. CHAT_MSG_SKILL = {"SKILL_RANK_UP"}, -- Experience Gains. CHAT_MSG_COMBAT_XP_GAIN = {"COMBATLOG_XPGAIN_FIRSTPERSON", "COMBATLOG_XPGAIN_FIRSTPERSON_UNNAMED"}, -- Looted Items. CHAT_MSG_LOOT = { "LOOT_ITEM_CREATED_SELF_MULTIPLE", "LOOT_ITEM_CREATED_SELF", "LOOT_ITEM_PUSHED_SELF_MULTIPLE", "LOOT_ITEM_PUSHED_SELF", "LOOT_ITEM_SELF_MULTIPLE", "LOOT_ITEM_SELF" }, -- Money. CHAT_MSG_MONEY = {"YOU_LOOT_MONEY", "LOOT_MONEY_SPLIT"}, } -- Loop through each of the events. for event, map in pairs(searchMap) do -- Remove invalid global strings. for i = #map, 1, -1 do if (not _G[map[i]]) then table.remove(map, i) end end -- Sort the global strings from most to least specific. table.sort(map, GlobalStringCompareFunc) end end -- **************************************************************************** -- Creates a map of capture functions for supported global strings. -- **************************************************************************** local function CreateSearchCaptureFuncs() searchCaptureFuncs = { -- Honor events. COMBATLOG_HONORAWARD = function (p, c) p.eventType, p.amount = "honor", c[1] end, COMBATLOG_HONORGAIN = function (p, c) p.eventType, p.sourceName, p.sourceRank, p.amount = "honor", c[1], c[2], c[3] end, -- Experience events. COMBATLOG_XPGAIN_FIRSTPERSON = function (p, c) p.eventType, p.sourceName, p.amount = "experience", c[1], c[2] end, COMBATLOG_XPGAIN_FIRSTPERSON_UNNAMED = function (p, c) p.eventType, p.amount = "experience", c[1] end, -- Reputation events. FACTION_STANDING_DECREASED = function (p, c) p.eventType, p.isLoss, p.factionName, p.amount = "reputation", true, c[1], c[2] end, FACTION_STANDING_INCREASED = function (p, c) p.eventType, p.factionName, p.amount = "reputation", c[1], c[2] end, -- Proficiency events. SKILL_RANK_UP = function (p, c) p.eventType, p.skillName, p.amount = "proficiency", c[1], c[2] end, -- Loot events. LOOT_ITEM_SELF = function (p, c) p.eventType, p.itemLink, p.amount = "loot", c[1], c[2] end, LOOT_ITEM_CREATED_SELF = function (p, c) p.eventType, p.isCreate, p.itemLink, p.amount = "loot", true, c[1], c[2] end, LOOT_MONEY_SPLIT = function (p, c) p.eventType, p.isMoney, p.moneyString = "loot", true, c[1] end, } searchCaptureFuncs["LOOT_ITEM_SELF_MULTIPLE"] = searchCaptureFuncs["LOOT_ITEM_SELF"] searchCaptureFuncs["LOOT_ITEM_CREATED_SELF_MULTIPLE"] = searchCaptureFuncs["LOOT_ITEM_CREATED_SELF"] searchCaptureFuncs["LOOT_ITEM_PUSHED_SELF"] = searchCaptureFuncs["LOOT_ITEM_CREATED_SELF"] searchCaptureFuncs["LOOT_ITEM_PUSHED_SELF_MULTIPLE"] = searchCaptureFuncs["LOOT_ITEM_CREATED_SELF"] searchCaptureFuncs["YOU_LOOT_MONEY"] = searchCaptureFuncs["LOOT_MONEY_SPLIT"] -- Print an error message for each global string that isn't found and remove it from the map. for globalStringName in pairs(searchCaptureFuncs) do if (not _G[globalStringName]) then Print("Unable to find global string: " .. globalStringName, 1, 0, 0) searchCaptureFuncs[globalStringName] = nil end end end -- **************************************************************************** -- Finds the rarest word for each global string. -- **************************************************************************** local function FindRareWords() -- Hold the number of times each word appears in all the global strings. local wordCounts = {} -- Loop through all of the supported global strings. for globalStringName in pairs(searchCaptureFuncs) do -- Strip out all of the formatting codes. local strippedGS = string.gsub(_G[globalStringName], "%%%d?%$?[sd]", "") -- Count how many times each word appears in the global string. for word in string_gmatch(strippedGS, "%w+") do wordCounts[word] = (wordCounts[word] or 0) + 1 end end -- Loop through all of the supported global strings. for globalStringName in pairs(searchCaptureFuncs) do local leastSeen, rarestWord -- Strip out all of the formatting codes. local strippedGS = string.gsub(_G[globalStringName], "%%%d?%$?[sd]", "") -- Find the rarest word in the global string. for word in string_gmatch(strippedGS, "%w+") do if (not leastSeen or wordCounts[word] < leastSeen) then leastSeen = wordCounts[word] rarestWord = word end end -- Set the rarest word. rareWords[globalStringName] = rarestWord end end -- **************************************************************************** -- Validates rare words to make sure there are no oddities caused by various -- languages. -- **************************************************************************** local function ValidateRareWords() -- Loop through all of the global strings there is a rare word entry for. for globalStringName, rareWord in pairs(rareWords) do -- Remove the entry if the rare word isn't found in the associated global string. if (not string_find(_G[globalStringName], rareWord, 1, true)) then rareWords[globalStringName] = nil end end end -- **************************************************************************** -- Converts all of the supported global strings. -- **************************************************************************** local function ConvertGlobalStrings() -- Loop through all of the supported global strings. for globalStringName in pairs(searchCaptureFuncs) do -- Get the global string converted to a lua search pattern and prepend an anchor to -- speed up searching. searchPatterns[globalStringName] = "^" .. ConvertGlobalString(globalStringName) end end -- **************************************************************************** -- Creates a map of capture functions for each supported combat log event. -- **************************************************************************** local function CreateCaptureFuncs() captureFuncs = { -- Damage events. SWING_DAMAGE = function (p, ...) p.eventType, p.amount, p.overkillAmount, p.damageType, p.resistAmount, p.blockAmount, p.absorbAmount, p.isCrit, p.isGlancing, p.isCrushing = "damage", ... end, RANGE_DAMAGE = function (p, ...) p.eventType, p.isRange, p.skillID, p.skillName, p.skillSchool, p.amount, p.overkillAmount, p.damageType, p.resistAmount, p.blockAmount, p.absorbAmount, p.isCrit, p.isGlancing, p.isCrushing, p.isOffHand = "damage", true, ... end, SPELL_DAMAGE = function (p, ...) p.eventType, p.skillID, p.skillName, p.skillSchool, p.amount, p.overkillAmount, p.damageType, p.resistAmount, p.blockAmount, p.absorbAmount, p.isCrit, p.isGlancing, p.isCrushing, p.isOffHand = "damage", ... end, SPELL_PERIODIC_DAMAGE = function (p, ...) p.eventType, p.isDoT, p.skillID, p.skillName, p.skillSchool, p.amount, p.overkillAmount, p.damageType, p.resistAmount, p.blockAmount, p.absorbAmount, p.isCrit, p.isGlancing, p.isCrushing, p.isOffHand = "damage", true, ... end, SPELL_BUILDING_DAMAGE = function (p, ...) p.eventType, p.skillID, p.skillName, p.skillSchool, p.amount, p.overkillAmount, p.damageType, p.resistAmount, p.blockAmount, p.absorbAmount, p.isCrit, p.isGlancing, p.isCrushing = "damage", ... end, DAMAGE_SHIELD = function (p, ...) p.eventType, p.isDamageShield, p.skillID, p.skillName, p.skillSchool, p.amount, p.overkillAmount, p.damageType, p.resistAmount, p.blockAmount, p.absorbAmount, p.isCrit, p.isGlancing, p.isCrushing = "damage", true, ... end, --SPELL_ABSORBED = function (p, ...) p.eventType, p.amount, p.skillID, p.skillName, p.skillSchool, p.absorbAmount = "damage", 0, ... end, --[[SPELL_ABSORBED = function (p, ...) --[dmgSpellID, dmgSpellName, dmgSpellSchool,] absorberGUID, absorberName, absorberFlags, absorberRaidFlags, absorbSkillID, absorbSkillName, absorbSkillSchool, absorbAmount local offset = 5 if type(...) == "number" then offset = 8 end -- 1st param is spellID and not a GUID p.eventType, p.amount, p.skillID, p.skillName, p.skillSchool, p.absorbAmount = "damage", 0, select(offset, ...) end,]] -- Miss events. SWING_MISSED = function (p, ...) p.eventType, p.missType, p.isOffHand, p.amount = "miss", ... end, RANGE_MISSED = function (p, ...) p.eventType, p.isRange, p.skillID, p.skillName, p.skillSchool, p.missType, p.isOffHand, p.amount = "miss", true, ... end, SPELL_MISSED = function (p, ...) p.eventType, p.skillID, p.skillName, p.skillSchool, p.missType, p.isOffHand, p.amount = "miss", ... end, SPELL_PERIODIC_MISSED = function (p, ...) p.eventType, p.skillID, p.skillName, p.skillSchool, p.missType, p.isOffHand, p.amount = "miss", ... end, DAMAGE_SHIELD_MISSED = function (p, ...) p.eventType, p.isDamageShield, p.skillID, p.skillName, p.skillSchool, p.missType, p.isOffHand, p.amount = "miss", true, ... end, SPELL_DISPEL_FAILED = function (p, ...) p.eventType, p.missType, p.skillID, p.skillName, p.skillSchool, p.extraSkillID, p.extraSkillName, p.extraSkillSchool = "miss", "RESIST", ... end, -- Heal events. SPELL_HEAL = function (p, ...) p.eventType, p.skillID, p.skillName, p.skillSchool, p.amount, p.overhealAmount, p.absorbAmount, p.isCrit = "heal", ... end, SPELL_PERIODIC_HEAL = function (p, ...) p.eventType, p.isHoT, p.skillID, p.skillName, p.skillSchool, p.amount, p.overhealAmount, p.absorbAmount, p.isCrit = "heal", true, ... end, -- Environmental events. ENVIRONMENTAL_DAMAGE = function (p, ...) p.eventType, p.hazardType, p.amount, p.overkillAmount, p.damageType, p.resistAmount, p.blockAmount, p.absorbAmount, p.isCrit, p.isGlancing, p.isCrushing = "environmental", ... end, -- Power events. SPELL_ENERGIZE = function (p, ...) p.eventType, p.isGain, p.skillID, p.skillName, p.skillSchool, p.amount, p.powerType = "power", true, ... end, SPELL_DRAIN = function (p, ...) p.eventType, p.isDrain, p.skillID, p.skillName, p.skillSchool, p.amount, p.powerType, p.extraAmount = "power", true, ... end, SPELL_LEECH = function (p, ...) p.eventType, p.isLeech, p.skillID, p.skillName, p.skillSchool, p.amount, p.powerType, p.extraAmount = "power", true, ... end, -- Interrupt events. SPELL_INTERRUPT = function (p, ...) p.eventType, p.skillID, p.skillName, p.skillSchool, p.extraSkillID, p.extraSkillName, p.extraSkillSchool = "interrupt", ... end, -- Aura events. SPELL_AURA_APPLIED = function (p, ...) p.eventType, p.skillID, p.skillName, p.skillSchool, p.auraType, p.amount = "aura", ... end, SPELL_AURA_APPLIED_DOSE = function (p, ...) p.eventType, p.isDose, p.skillID, p.skillName, p.skillSchool, p.auraType, p.amount = "aura", true, ... end, SPELL_AURA_REMOVED = function (p, ...) p.eventType, p.isFade, p.skillID, p.skillName, p.skillSchool, p.auraType, p.amount = "aura", true, ... end, SPELL_AURA_REMOVED_DOSE = function (p, ...) p.eventType, p.isFade, p.isDose, p.skillID, p.skillName, p.skillSchool, p.auraType, p.amount = "aura", true, true, ... end, -- Enchant events. ENCHANT_APPLIED = function (p, ...) p.eventType, p.skillName, p.itemID, p.itemName = "enchant", ... end, ENCHANT_REMOVED = function (p, ...) p.eventType, p.isFade, p.skillName, p.itemID, p.itemName = "enchant", true, ... end, -- Dispel events. SPELL_DISPEL = function (p, ...) p.eventType, p.skillID, p.skillName, p.skillSchool, p.extraSkillID, p.extraSkillName, p.extraSkillSchool, p.auraType = "dispel", ... end, -- Cast events. SPELL_CAST_START = function (p, ...) p.eventType, p.skillID, p.skillName, p.skillSchool = "cast", ... end, -- Kill events. PARTY_KILL = function (p, ...) p.eventType = "kill" end, -- Extra Attack events. SPELL_EXTRA_ATTACKS = function (p, ...) p.eventType, p.skillID, p.skillName, p.skillSchool, p.amount = "extraattacks", ... end, } captureFuncs["DAMAGE_SPLIT"] = captureFuncs["SPELL_DAMAGE"] captureFuncs["SPELL_PERIODIC_MISSED"] = captureFuncs["SPELL_MISSED"] captureFuncs["SPELL_PERIODIC_ENERGIZE"] = captureFuncs["SPELL_ENERGIZE"] captureFuncs["SPELL_PERIODIC_DRAIN"] = captureFuncs["SPELL_DRAIN"] captureFuncs["SPELL_PERIODIC_LEECH"] = captureFuncs["SPELL_LEECH"] captureFuncs["SPELL_STOLEN"] = captureFuncs["SPELL_DISPEL"] -- Expose the capture functions. module.captureFuncs = captureFuncs end ------------------------------------------------------------------------------- -- Event handlers. ------------------------------------------------------------------------------- -- **************************************************************************** -- Called when there is information that needs to be obtained after a delay. -- **************************************************************************** local function OnUpdateDelayedInfo(this, elapsed) -- Check if the unit map needs to be updated after a delay. if (isUnitMapStale) then -- Increment the amount of time passed since the last update. lastUnitMapUpdate = lastUnitMapUpdate + elapsed -- Check if it's time for an update. if (lastUnitMapUpdate >= UNIT_MAP_UPDATE_DELAY) then -- Update the player GUID if it isn't known yet and verify it's now known. if (not playerGUID) then playerGUID = UnitGUID("player") end if (playerGUID) then -- Erase the unit map table and mark all old units for cleanup from the class map. local now = GetTime() for guid in pairs(unitMap) do unitMap[guid] = nil classTimes[guid] = now + CLASS_HOLD_TIME end -- Loop through all of the group members and add them and their class to the maps. local unitPrefix = IsInRaid() and "raid" or "party" local numGroupMembers = GetNumGroupMembers() for i = 1, numGroupMembers do local unitID = unitPrefix .. i -- XXX: This call is returning nil for party members in certain circumstances - need to debug further. local guid = UnitGUID(unitID) if (guid ~= nil) then unitMap[guid] = unitID if (not classMap[guid]) then _, classMap[guid] = UnitClass(unitID) end classTimes[guid] = nil end end -- Loop through group members -- Add the player and player's class to the maps. unitMap[playerGUID] = "player" if (not classMap[playerGUID]) then _, classMap[playerGUID] = UnitClass("player") end classTimes[playerGUID] = nil -- Clear the unit map stale flag. isUnitMapStale = false end -- Reset the time since last update. lastUnitMapUpdate = 0 end end -- Unit map is stale. -- Check if the pet map needs to be updated after a delay. if (isPetMapStale) then -- Increment the amount of time passed since the last update. lastPetMapUpdate = lastPetMapUpdate + elapsed -- Check if it's time for an update. if (lastPetMapUpdate >= PET_UPDATE_DELAY) then -- Verify the player's pet is not in an unknown state if there is one. local petName = UnitName("pet") if (not petName or petName ~= UNKNOWN) then -- Erase the pet map table and mark all old units for cleanup from the class map. local now = GetTime() for guid in pairs(petMap) do petMap[guid] = nil classTimes[guid] = now + CLASS_HOLD_TIME end -- Loop through all of the group members and add their pets and pet's class to the maps. local unitPrefix = IsInRaid() and "raidpet" or "partypet" local numGroupMembers = GetNumGroupMembers() for i = 1, numGroupMembers do local unitID = unitPrefix .. i if (UnitExists(unitID)) then -- XXX: This call is returning nil for party members in certain circumstances - need to debug further. local guid = UnitGUID(unitID) if (guid ~= nil) then petMap[guid] = unitID if (not classMap[guid]) then _, classMap[guid] = UnitClass(unitID) end classTimes[guid] = nil end end end -- Loop through group members -- Add the player's pet and its class if there is one. Treat vehicles as the player instead of a pet. if (petName) then local unitID = "pet" local guid = UnitGUID(unitID) if (guid == UnitGUID("vehicle")) then unitID = "player" end petMap[guid] = unitID if (not classMap[guid]) then _, classMap[guid] = UnitClass(unitID) end classTimes[guid] = nil end -- Clear the pet map stale flag. isPetMapStale = false end -- Pet in known state. -- Reset the time since last update. lastPetMapUpdate = 0 end end -- Pet map is stale. -- Stop receiving updates if no more data needs to be updated. if (not isUnitMapStale and not isPetMapStale) then this:Hide() end end -- **************************************************************************** -- Called when the events the parser registered for occur. -- **************************************************************************** local function OnEvent(this, event, arg1, arg2, ...) -- Combat log events. if (event == "COMBAT_LOG_EVENT_UNFILTERED") then ParseLogMessage(arg1, arg2, ...) -- Mouseover changes. elseif (event == "UPDATE_MOUSEOVER_UNIT") then -- Map the GUID for the moused over unit to a class. local mouseoverGUID = UnitGUID("mouseover") if (not mouseoverGUID) then return end -- Ignore the GUID if its class is already known and there is no cleanup time for it. if (classMap[mouseoverGUID] and not classTimes[mouseoverGUID]) then return end -- Update the cleanup time for the GUID and map it to a class if it's not already known. classTimes[mouseoverGUID] = GetTime() + CLASS_HOLD_TIME if (not classMap[mouseoverGUID]) then _, classMap[mouseoverGUID] = UnitClass("mouseover") end -- Target changes. elseif (event == "PLAYER_TARGET_CHANGED") then -- Map the GUID for the target unit to a class. local targetGUID = UnitGUID("target") if (not targetGUID) then return end -- Ignore the GUID if its class is already known and there is no cleanup time for it. if (classMap[targetGUID] and not classTimes[targetGUID]) then return end -- Update the cleanup time for the GUID and map it to a class if it's not already known. local now = GetTime() classTimes[targetGUID] = now + CLASS_HOLD_TIME if (not classMap[targetGUID]) then _, classMap[targetGUID] = UnitClass("target") end -- Loop through all of the recent guid to class mappings and remove the old ones if enough time has passed. if (now >= classMapCleanupTime) then for guid, cleanupTime in pairs(classTimes) do if (now >= cleanupTime) then classMap[guid] = nil classTimes[guid] = nil end end classMapCleanupTime = now + CLASS_HOLD_TIME end -- Time to clean up class map. -- Party/Raid changes. elseif (event == "GROUP_ROSTER_UPDATE") then -- Set the unit map stale flag and schedule the unit map to be updated after a short delay. isUnitMapStale = true eventFrame:Show() -- Pet changes. elseif (event == "UNIT_PET") then isPetMapStale = true eventFrame:Show() -- Arena opponent changes. elseif (event == "ARENA_OPPONENT_UPDATE") then -- Map the unit id and GUID for an arena unit to a class when it's seen. if (arg2 == "seen") then local arenaGUID = UnitGUID(arg1) if (not arenaGUID) then return end arenaUnits[arg1] = arenaGUID _, classMap[arenaGUID] = UnitClass(arg1) -- Remove the mappings for an arena unit when it's cleared. elseif (arg2 == "cleared") then local arenaGUID = arenaUnits[arg1] if (not arenaGUID) then return end arenaUnits[arg1] = nil classMap[arenaGUID] = nil end -- Chat message combat events. else ParseSearchMessage(event, arg1) end end -- **************************************************************************** -- Enables parsing. -- **************************************************************************** local function Enable() -- Register for parameter style events going to the combat log. eventFrame:RegisterEvent("COMBAT_LOG_EVENT_UNFILTERED") -- Register CHAT_MSG_X search style events. for event in pairs(searchMap) do eventFrame:RegisterEvent(event) end -- Register additional events for unit and class map processing. eventFrame:RegisterEvent("GROUP_ROSTER_UPDATE") eventFrame:RegisterEvent("UNIT_PET") eventFrame:RegisterEvent("ARENA_OPPONENT_UPDATE") eventFrame:RegisterEvent("PLAYER_TARGET_CHANGED") eventFrame:RegisterEvent("UPDATE_MOUSEOVER_UNIT") -- Update the unit map and current pet information. isUnitMapStale = true isPetMapStale = true -- Start receiving updates. eventFrame:Show() end -- **************************************************************************** -- Disables the parsing. -- **************************************************************************** local function Disable() -- Stop receiving updates. eventFrame:Hide() eventFrame:UnregisterAllEvents() -- Erase the reflected skill tables. EraseTable(reflectedTimes) EraseTable(reflectedSkills) end ------------------------------------------------------------------------------- -- Initialization. ------------------------------------------------------------------------------- -- Create a frame to receive events. eventFrame = CreateFrame("Frame") eventFrame:Hide() eventFrame:SetScript("OnEvent", OnEvent) eventFrame:SetScript("OnUpdate", OnUpdateDelayedInfo) -- Get the name, GUID, and class of the player. playerName = UnitName("player") playerGUID = UnitGUID("player") -- Create various maps. CreateSearchMap() CreateSearchCaptureFuncs() CreateCaptureFuncs() -- Create the list of events that should be fully parsed. CreateFullParseList() -- Find the rarest word for each supported global string. FindRareWords() ValidateRareWords() -- Convert the supported global strings into lua search patterns. ConvertGlobalStrings() ------------------------------------------------------------------------------- -- Module interface. ------------------------------------------------------------------------------- -- Protected Constants. module.AFFILIATION_MINE = AFFILIATION_MINE module.AFFILIATION_PARTY = AFFILIATION_PARTY module.AFFILIATION_RAID = AFFILIATION_RAID module.AFFILIATION_OUTSIDER = AFFILIATION_OUTSIDER module.REACTION_FRIENDLY = REACTION_FRIENDLY module.REACTION_NEUTRAL = REACTION_NEUTRAL module.REACTION_HOSTILE = REACTION_HOSTILE module.CONTROL_HUMAN = CONTROL_HUMAN module.CONTROL_SERVER = CONTROL_SERVER module.UNITTYPE_PLAYER = UNITTYPE_PLAYER module.UNITTYPE_NPC = UNITTYPE_NPC module.UNITTYPE_PET = UNITTYPE_PET module.UNITTYPE_GUARDIAN = UNITTYPE_GUARDIAN module.UNITTYPE_OBJECT = UNITTYPE_OBJECT module.TARGET_TARGET = TARGET_TARGET module.TARGET_FOCUS = TARGET_FOCUS module.OBJECT_NONE = OBJECT_NONE -- Protected Variables. module.unitMap = unitMap module.classMap = classMap -- Protected Functions. module.RegisterHandler = RegisterHandler module.UnregisterHandler = UnregisterHandler module.TestFlagsAny = TestFlagsAny module.TestFlagsAll = TestFlagsAll module.Enable = Enable module.Disable = Disable
require 'torch' require 'nn' require 'optim' require 'image' local c = require 'trepl.colorize' if itorch then path = require 'pl.path' end require 'cifar10-data-loader' -- CUDA Import Stuff local EXCLUDE_CUDA_FLAG = false local function cudaRequires() require 'cutorch' require 'cunn' end if pcall(cudaRequires) then print('Imported cuda modules in first-cnn-arch') else print('Failed to import cuda modules in first-cnn-arch') EXCLUDE_CUDA_FLAG = true end -- Constructs and returns an inceptionModule from the paper -- "Going Deeper with Convolutional Networks", with input/output channels defined -- with the parameters as follows: -- inputChannels: the number of input channels -- outputChannels: the expected number of outputChannels -- (this parameter is only used to check the other parameters) -- reductions: a 4-element array which specifies the number of channels output -- from each 1x1 convolutional network -- (which should be smaller than the inputChannels usually...) -- expansions: a 2-element array which specifies the number of channels output -- from the 3x3 convolutional layer and -- the 5x5 convolutional layer -- ReLU activations are applied after each convolutional layer -- This module might be extended to allow for arbitrary width local function inceptionModule(inputChannels, outputChannels, reductions, expansions) computedOutputChannels = reductions[1] + expansions[1] + expansions[2] + reductions[4] if not (outputChannels == computedOutputChannels) then print("OUTPUT CHANNELS DO NOT MATCH COMPUTED OUTPUT CHANNELS") print('outputChannels: ', outputChannels) print('computedOutputChannels: ', computedOutputChannels) return nil end local inception = nn.DepthConcat(2) local column1 = nn.Sequential() column1:add(nn.SpatialConvolution(inputChannels, reductions[1], 1, 1, -- Convolution kernel 1, 1)) -- Stride column1:add(nn.ReLU(true)) inception:add(column1) local column2 = nn.Sequential() column2:add(nn.SpatialConvolution(inputChannels, reductions[2], 1, 1, 1, 1)) column2:add(nn.ReLU(true)) column2:add(nn.SpatialConvolution(reductions[2], expansions[1], 3, 3, -- Convolution kernel 1, 1)) -- Stride column2:add(nn.ReLU(true)) inception:add(column2) local column3 = nn.Sequential() column3:add(nn.SpatialConvolution(inputChannels, reductions[3], 1, 1, 1, 1)) column3:add(nn.ReLU(true)) column3:add(nn.SpatialConvolution(reductions[3], expansions[2], 5, 5, -- Convolution kernel 1, 1)) -- Stride column3:add(nn.ReLU(true)) inception:add(column3) local column4 = nn.Sequential() column4:add(nn.SpatialMaxPooling(3, 3, 1, 1)) column4:add(nn.SpatialConvolution(inputChannels, reductions[4], 1, 1, -- Convolution kernel 1, 1)) -- Stride column4:add(nn.ReLU(true)) inception:add(column4) return inception end local function convModule(inputChannels, outputChannels, bigMaxPool) local convModule = nn.Sequential() convModule:add(nn.SpatialConvolution(inputChannels, outputChannels, 3, 3, 1, 1, 1, 1)) convModule:add(nn.ReLU(true)) convModule:add(nn.Dropout(0.2)) convModule:add(nn.SpatialBatchNormalization(128)) if bigMaxPool then convModule:add(nn.SpatialMaxPooling(2, 2, 2, 2)) else convModule:add(nn.SpatialMaxPooling(2, 2, 1, 1)) end return convModule end local function wrongModule(inputChannels, width, height) local wrongModule = nn.Sequential() local linearInput = inputChannels * torch.floor((width - 3) / 3 + 1) * torch.floor((height - 3) / 3 + 1) print("Linear Input: ", linearInput) wrongModule:add(nn.SpatialAveragePooling(3, 3, 3, 3)) wrongModule:add(nn.View(linearInput)) wrongModule:add(nn.Linear(linearInput, linearInput / 2)) wrongModule:add(nn.Linear(linearInput / 2, 10)) return wrongModule end local function firstWrongArch() mainLine1 = nn.Sequential() mainLine1:add(convModule(3, 16)) mainLine1:add(convModule(16, 32, true)) mainLine2 = nn.Sequential() mainLine2:add(convModule(32, 64)) mainLine2:add(convModule(64, 128, true)) mainLine2:add(wrongModule(128, 7, 7)) split1 = nn.ConcatTable() split1:add(wrongModule(32, 15, 15)) split1:add(mainLine2) mainLine1:add(split1) return mainLine1 end -------------------------------------------------------------------------------- -- Main Runner Code------------------------------------------------------------- -------------------------------------------------------------------------------- -- Setup data loader local dataDir = 'torch-data' local maxEpoch = 200 if EXCLUDE_CUDA_FLAG then sizeRestriction = 200 maxEpoch = 5 end local trainingDataLoader = Cifar10Loader(dataDir, 'train', sizeRestriction) local opt = { netSaveDir = 'model-nets', batchSize = 128, learningRate = 1.0, weightDecay = 0.0005, momentum = 0.9, learningRateDecay = 0.00000001, maxEpoch = maxEpoch } -- Define neural network net = firstWrongArch() print("Network: ") print(net) -- Define loss function and stochastic gradient parameters and style criterion = nn.ParallelCriterion(true) crossEntropy = nn.CrossEntropyCriterion() criterion:add(crossEntropy):add(crossEntropy) -- CUDA-fy loss function, model, and data set if not EXCLUDE_CUDA_FLAG then criterion = criterion:cuda() trainingDataLoader:cuda() net = net:cuda() end -- Setup table for optimizer optimState = { learningRate = opt.learningRate, weightDecay = opt.weightDecay, momentum = opt.momentum, learningRateDecay = opt.learningRateDecay } -- Get NN parameters and set up confusion matrix parameters, gradParameters = net:getParameters() confusion = optim.ConfusionMatrix(trainingDataLoader.classes) local function train() net:training() -- Setup mini-batches local indices = torch.randperm(trainingDataLoader.data:size(1)):long():split(opt.batchSize) indices[#indices] = nil local targets = torch.Tensor(opt.batchSize) if not EXCLUDE_CUDA_FLAG then targets = targets:cuda() end print('Training Beginning....') print('Training set size: ', trainingDataLoader.data:size(1)) local tic = torch.tic() for t, v in ipairs(indices) do local inputs = trainingDataLoader.data:index(1, v) targets:copy(trainingDataLoader.labels:index(1, v)) local feval = function(x) if x ~= parameters then parameters:copy(x) end -- Zero out the gradient parameters from last iteration gradParameters:zero() local outputs = net:forward(inputs) local f = criterion:forward(outputs, targets) local df_do = criterion:backward(outputs, targets) net:backward(inputs, df_do) confusion:batchAdd(outputs, targets) return f, gradParameters end optim.sgd(feval, parameters, optimState) end confusion:updateValids() print(('Train accuracy: ' .. c.cyan'%.2f' .. ' %%\t time: %.2f s'):format( confusion.totalValid * 100, torch.toc(tic))) trainingAccuracy = confusion.totalValid * 100 confusion:zero() print('------------------------------------------------') end local function test() -- Validate data (eventually turn this into test) local testingDataLoader = Cifar10Loader(dataDir, 'validate', sizeRestriction) local classes = testingDataLoader.classes if not EXCLUDE_CUDA_FLAG then testingDataLoader.data = testingDataLoader.data:cuda() end print('Beginning Testing') print('Testing set size: ', testingDataLoader.data:size(1)) net:evaluate() for i = 1, testingDataLoader.data:size(1), opt.batchSize do local outputs if (i + opt.batchSize - 1) > testingDataLoader.data:size(1) then local endIndex = testingDataLoader.data:size(1) - i outputs = net:forward(testingDataLoader.data:narrow(1, i, endIndex)) confusion:batchAdd(outputs, testingDataLoader.labels:narrow(1, i, endIndex)) else outputs = net:forward(testingDataLoader.data:narrow(1, i, opt.batchSize)) confusion:batchAdd(outputs, testingDataLoader.labels:narrow(1, i, opt.batchSize)) end end confusion:updateValids() print('Test Accuracy: ', confusion.totalValid * 100, '%') print('------------------------------------------------') end -------------------------------------------------------------------------------- -- Runner code, main loop------------------------------------------------------- -------------------------------------------------------------------------------- print('Running for ', opt.maxEpoch, ' epochs') local globalTic = torch.tic() for i = 1, opt.maxEpoch do print('Epoch ', i) train() test() -- Visualize every 25 epochs if itorch and i % 25 == 0 then print('Visualizations: ') for j = 1, net:size() do print('\nLayer ', j) res = net:get(j).weight res = res:view(res:size(1), 1, res:size(2), res:size(3)) itorch.image(res) end end -- Save model every 50 epochs if i % 50 == 0 then local filename = paths.concat(opt.netSaveDir, 'model.net') print('==> saving model to ' .. filename) torch.save(filename, net) end end print(('Total model trained in time: %f seconds'):format(torch.toc(globalTic)))