content
stringlengths 5
1.05M
|
---|
-----------------------------------
-- Area: Caedarva Mire
-- NPC: qm9
-- Involved in quest: The Wayward Automation
-- !pos 129 1.396 -631 79
-----------------------------------
local ID = require("scripts/zones/Caedarva_Mire/IDs");
require("scripts/globals/quests");
function onTrade(player,npc,trade)
end;
function onTrigger(player,npc)
local TheWaywardAutomation = player:getQuestStatus(AHT_URHGAN,tpz.quest.id.ahtUrhgan.THE_WAYWARD_AUTOMATION);
local TheWaywardAutomationProgress = player:getCharVar("TheWaywardAutomationProgress");
if (TheWaywardAutomation == QUEST_ACCEPTED and TheWaywardAutomationProgress == 2) then
if (player:getCharVar("TheWaywardAutomationNM") >= 1) then
player:startEvent(14);-- Event ID 14 for CS after toad
elseif (not GetMobByID(ID.mob.CAEDARVA_TOAD):isSpawned()) then
SpawnMob(ID.mob.CAEDARVA_TOAD):updateClaim(player); --Caedarva toad
end
else
player:messageSpecial(ID.text.NOTHING_OUT_OF_ORDINARY);
end
end;
function onEventUpdate(player,csid,option)
end;
function onEventFinish(player,csid,option)
if (csid == 14) then
player:setCharVar("TheWaywardAutomationProgress",3);
player:setCharVar("TheWaywardAutomationNM",0);
end
end;
|
return
{
["id"]=304,
["debug"]=false,
["variables"]={
},
["nodes"]={
[1]={
["uuid"]="3ec1876f6cad4655aaefb5dfea6aed49",
["Type"]="Root",
["mark"]="",
["links"]={
[1]={
["child"]="b4846265634e4c999dac86cb19a2f1b9",
["weight"]=0,
},
},
},
[2]={
["uuid"]="b4846265634e4c999dac86cb19a2f1b9",
["Type"]="Sequence",
["mark"]="",
["links"]={
[1]={
["child"]="fe9d342dc91d4456877caa9b6ec8cac1",
["weight"]=0,
},
},
["listenCondition"]=false,
},
[3]={
["uuid"]="fe9d342dc91d4456877caa9b6ec8cac1",
["Type"]="MoveTo",
["mark"]="",
["links"]={
},
["positions"]={
[1]={["x"]=-45.86,["y"]=2.32,["z"]=34.12,},
[2]={["x"]=-33.11,["y"]=2.32,["z"]=34.12,},
},
["speed"]=1,
["loopTimes"]=-1,
},
},
}
|
local baseline = SCREEN_HEIGHT*0.39
local meterheight = SCREEN_HEIGHT*0.75
local notes = GAMESTATE:GetCurrentSteps(pn):GetRadarValues(pn):GetValue(0)
local progress = 0
local maxcombo = 0
local percent
local passflag = 0
local target = playerConfig:get_data(pn_to_profile_slot(PLAYER_1)).TargetGoal
local targetTrackerMode = playerConfig:get_data(pn_to_profile_slot(PLAYER_1)).TargetTrackerMode
local color1 = color("#4073bf")--getMainColor("highlight")
local color2 = color("#6abf40")
local color3 =color("#bf4048")
local t = Def.ActorFrame{
Name="Pacemaker",
InitCommand=function(self)
self:xy(SCREEN_WIDTH*11/12,SCREEN_CENTER_Y)
end;
JudgmentMessageCommand=function (self,msg)
if msg.Judgment == "TapNoteScore_W1" or
msg.Judgment == "TapNoteScore_W2" or
msg.Judgment == "TapNoteScore_W3" or
msg.Judgment == "TapNoteScore_W4" or
msg.Judgment == "TapNoteScore_W5" or
msg.Judgment == "TapNoteScore_Miss" then
progress = progress + 1
percent = msg.WifePercent
self:playcommand("Update")
end
if targetTrackerMode == 1 and msg.WifePBGoal ~= nil and progress <= 1 then
target = msg.WifePBGoal*100
self:queuecommand("Update2")
end
end;
--base
Def.Quad{
InitCommand=function(self)
self:zoomto(SCREEN_WIDTH/6,SCREEN_HEIGHT)
self:diffuse(.05,.05,.05,0.8)
end;
},
--current score meter
Def.Quad{
InitCommand=function(self)
self:xy(-0.03*SCREEN_WIDTH,baseline):align(0.5,1)
self:zoomto(SCREEN_WIDTH*0.05,0)
self:diffuse(color1)
self:diffusealpha(0.75)
self:glowshift():effectcolor1(0.5,0.5,0.5,0.4):effectcolor2(0.75,0.75,0.75,0.5):effectperiod(2)
end;
UpdateCommand=function (self,msg)
if percent < 0 then
self: zoomtoheight(0)
else
self:zoomtoheight(meterheight*percent/100):croptop(1-(progress/notes))
end
end
},
--target score meter
Def.Quad{
InitCommand=function(self)
self:xy(0.03*SCREEN_WIDTH,baseline):align(0.5,1)
self:zoomto(SCREEN_WIDTH*0.05,meterheight*target/100)
self:diffuse(.5,.5,.5,0.5)
end;
Update2Command=function (self,msg)
self:zoomtoheight(meterheight*target/100)
end
},
Def.Quad{
OnCommand=function(self)
self:xy(0.03*SCREEN_WIDTH,baseline):align(0.5,1)
self:zoomto(SCREEN_WIDTH*0.05-3,meterheight*target/100-1.5)
self:MaskSource()
end;
Update2Command=function (self)
self:zoomtoheight(meterheight*target/100-1.5)
end
},
Def.Quad{
InitCommand=function(self)
self:xy(0.03*SCREEN_WIDTH,baseline):align(0.5,1)
self:zoomto(SCREEN_WIDTH*0.05,meterheight*target/100)
self:diffuse(1,1,1,0.5)
self:MaskDest()
end;
UpdateCommand=function (self)
self:cropbottom(progress/notes)
end;
Update2Command=function (self,msg)
self:zoomtoheight(meterheight*target/100)
end
},
Def.Quad{
InitCommand=function(self)
self:xy(0.03*SCREEN_WIDTH,baseline):align(0.5,1)
self:zoomto(SCREEN_WIDTH*0.05,0)
self:diffuse(color2)
self:diffusealpha(0.75)
self:glowshift():effectcolor1(0.5,0.5,0.5,0.4):effectcolor2(0.75,0.75,0.75,0.5):effectperiod(2)
end;
UpdateCommand=function (self)
self:zoomtoheight(meterheight*target/100):croptop(1-(progress/notes))
end;
Update2Command=function(self)
self:diffuse(color3)
self:diffusealpha(0.5)
end
},
--label
Def.ActorFrame{
InitCommand=function(self)
self:xy(-1/24*SCREEN_WIDTH+0.7,baseline+12)
end;
Def.Quad{
InitCommand=function(self)
self:zoomto(1/12*SCREEN_WIDTH-4,15)
self:diffuse(color1):glow(0.5,0.5,0.5,0.5)
self:diffusealpha(0.7)
end;
};
Def.BitmapText{
Font="Common normal",
InitCommand=function(self)
self:settext("CURRENT SCORE")
self:zoom(0.4):maxwidth(160):y(-1)
end;
}
};
Def.ActorFrame{
InitCommand=function(self)
self:xy(1/24*SCREEN_WIDTH-0.7,baseline+12)
end;
Def.Quad{
InitCommand=function(self)
self:zoomto(1/12*SCREEN_WIDTH-4,15)
self:diffuse(color2):glow(0.5,0.5,0.5,0.5)
self:diffusealpha(0.7)
end;
Update2Command=function(self)
self:diffuse(color3)
self:diffusealpha(0.7)
end
};
Def.BitmapText{
Font="Common normal",
InitCommand=function(self)
self:settext("SET PERCENT")
self:zoom(0.4):maxwidth(160):y(-1)
end;
Update2Command=function(self)
self:settext("PERSONAL BEST")
end
}
};
--overlay
Def.ActorFrame{
--score point
Def.BitmapText{
Font="Common normal",
InitCommand=function(self)
self:settextf("%2.2f",0)
self:xy(-0.03*SCREEN_WIDTH,baseline-2):align(0.5,1):zoom(0.45)
end;
UpdateCommand=function (self,msg)
self:settextf("%2.2f",progress*percent/50)
end
};
Def.BitmapText{
Font="Common normal",
InitCommand=function(self)
self:settextf("%2.2f",0)
self:xy(0.03*SCREEN_WIDTH,baseline-2):align(0.5,1):zoom(0.45)
end;
UpdateCommand=function (self,msg)
self:settextf("%2.2f",progress*target/50)
end
};
--pass flag
LoadFont("Common normal") ..{
InitCommand=function(self)
self:xy(0,baseline-(meterheight*0.997)-2):align(0.5,1):zoom(0.5)
self:diffusealpha(0)
end;
UpdateCommand=function (self)
if progress/notes*percent>60 and passflag == 0 then
passflag = 1
self:stoptweening()
self:settext("Rank C Pass"):y(baseline-(meterheight*0.6)-3)
self:diffusealpha(0):x(SCREEN_WIDTH/6):linear(0.2):diffusealpha(1):x(0)
self:sleep(1):linear(0.2):x(SCREEN_WIDTH/6)
self:sleep(1):linear(0.2):x(SCREEN_WIDTH/6)
elseif progress/notes*percent>70 and passflag == 1 then
passflag = 2
self:stoptweening()
self:settext("Rank B Pass"):y(baseline-(meterheight*0.7)-3)
self:diffusealpha(0):x(SCREEN_WIDTH/6):linear(0.2):diffusealpha(1):x(0)
self:sleep(1):linear(0.2):x(SCREEN_WIDTH/6)
elseif progress/notes*percent>80 and passflag == 2 then
passflag = 3
self:stoptweening()
self:settext("Rank A Pass"):y(baseline-(meterheight*0.8)-3)
self:diffusealpha(0):x(SCREEN_WIDTH/6):linear(0.2):diffusealpha(1):x(0)
self:sleep(1):linear(0.2):x(SCREEN_WIDTH/6)
elseif progress/notes*percent>93 and passflag == 3 then
passflag = 4
self:stoptweening()
self:settext("Rank AA Pass"):y(baseline-(meterheight*0.93)-3)
self:diffusealpha(0):x(SCREEN_WIDTH/6):linear(0.2):diffusealpha(1):x(0)
self:sleep(1):linear(0.2):x(SCREEN_WIDTH/6)
elseif progress/notes*percent>99.7 and progress/notes*percent <99.955 and passflag == 4 then
passflag = 5
self:stoptweening()
self:settext("Rank AAA Pass"):y(baseline-(meterheight*0.997)-3)
self:diffusealpha(0):x(SCREEN_WIDTH/6):linear(0.2):diffusealpha(1):x(0)
self:sleep(1):linear(0.2):x(SCREEN_WIDTH/6)
elseif progress/notes*percent>=99.955 and progress/notes*percent <99.9935 and passflag < 6 then
passflag = 6
self:stoptweening()
self:settext("Rank AAAA Pass"):y(baseline-(meterheight*0.99955)-3)
self:diffusealpha(0):x(SCREEN_WIDTH/6):linear(0.2):diffusealpha(1):x(0)
self:sleep(1):linear(0.2):x(SCREEN_WIDTH/6)
elseif progress/notes*percent>=99.9935 and passflag < 7 then
passflag = 7
self:stoptweening()
self:settext("Rank AAAAA Pass"):y(baseline-(meterheight)-3)
self:diffusealpha(0):x(SCREEN_WIDTH/6):linear(0.2):diffusealpha(1):x(0)
self:sleep(1):linear(0.2):x(SCREEN_WIDTH/6)
end
end
},
Def.Quad{
InitCommand=function(self)
self:zoomto(SCREEN_WIDTH/6,2):y(baseline):align(0.5,0)
self:diffusealpha(0.5)
end;
},
--AAA
Def.Quad{
InitCommand=function(self)
self:zoomto(SCREEN_WIDTH/6,2):y(baseline-(meterheight*0.997)):align(0.5,1)
self:diffusealpha(0.5)
end;
UpdateCommand=function (self)
if progress/notes*percent>99.7 then
self:diffuse(1,1,0,0.7)
end
end
},
LoadFont("Common normal") ..{
InitCommand=function(self)
self:xy(-1/12*SCREEN_WIDTH+1,baseline-(meterheight*0.997)-2):align(0,1):settext("AAA"):zoom(0.4)
self:diffusealpha(0.3)
end;
UpdateCommand=function (self)
if progress/notes*percent>=99.9935 then
self:diffuse(0.5,1,1,1):settext("AAAAA")
elseif progress/notes*percent>=99.955 then
self:diffuse(0.5,1,1,1):settext("AAAA")
elseif progress/notes*percent>=99.7 then
self:diffuse(1,0.8,0.5,1)
end
end
},
--AA
Def.Quad{
InitCommand=function(self)
self:zoomto(SCREEN_WIDTH/6,2):y(baseline-(meterheight*0.93)):align(0.5,1)
self:diffusealpha(0.3)
end;
UpdateCommand=function (self)
if progress/notes*percent>93 then
self:diffuse(1,1,0,0.5)
end
end
},
LoadFont("Common normal") ..{
InitCommand=function(self)
self:xy(-1/12*SCREEN_WIDTH+1,baseline-(meterheight*0.93)-2):align(0,1):settext("AA"):zoom(0.4)
self:diffusealpha(0.3)
end;
UpdateCommand=function (self)
if progress/notes*percent>93 then
self:diffuse(0.5,1,0.5,1)
end
end
},
--A
Def.Quad{
InitCommand=function(self)
self:zoomto(SCREEN_WIDTH/6,2):y(baseline-(meterheight*0.8)):align(0.5,1)
self:diffusealpha(0.3)
end;
UpdateCommand=function (self)
if progress/notes*percent>80 then
self:diffuse(1,1,0,0.5)
end
end
},
LoadFont("Common normal") ..{
InitCommand=function(self)
self:xy(-1/12*SCREEN_WIDTH+1,baseline-(meterheight*0.8)-2):align(0,1):settext("A"):zoom(0.4)
self:diffusealpha(0.3)
end;
UpdateCommand=function (self)
if progress/notes*percent>80 then
self:diffuse(1,0.5,0.5,1)
end
end
},
--B
Def.Quad{
InitCommand=function(self)
self:zoomto(SCREEN_WIDTH/6,2):y(baseline-(meterheight*0.7)):align(0.5,1)
self:diffusealpha(0.3)
end;
UpdateCommand=function (self)
if progress/notes*percent>70 then
self:diffuse(1,1,0,0.5)
end
end
},
LoadFont("Common normal") ..{
InitCommand=function(self)
self:xy(-1/12*SCREEN_WIDTH+1,baseline-(meterheight*0.7)-2):align(0,1):settext("B"):zoom(0.4)
self:diffusealpha(0.3)
end;
UpdateCommand=function (self)
if progress/notes*percent>70 then
self:diffuse(0.4,0.5,1,1)
end
end
},
--C
Def.Quad{
InitCommand=function(self)
self:zoomto(SCREEN_WIDTH/6,2):y(baseline-(meterheight*0.6)):align(0.5,1)
self:diffusealpha(0.3)
end;
UpdateCommand=function (self)
if progress/notes*percent>60 then
self:diffuse(1,1,0,0.5)
end
end
},
LoadFont("Common normal") ..{
InitCommand=function(self)
self:xy(-1/12*SCREEN_WIDTH+1,baseline-(meterheight*0.6)-2):align(0,1):settext("C"):zoom(0.4)
self:diffusealpha(0.3)
end;
UpdateCommand=function (self)
if progress/notes*percent>60 then
self:diffuse(0.8,0.5,1,1)
end
end
},
},
}
return t
|
AddCSLuaFile("cl_init.lua")
AddCSLuaFile("shared.lua")
include("shared.lua")
ENT.BogeyDistance = 650 -- Needed for gm trainspawner
ENT.SyncTable = {
"EnableBVEmer","Ticker","KAH","KAHk","ALS","ALSk","FDepot","PassScheme","EnableBV","DisableBV","Ring","R_Program2","R_Announcer","R_Line","R_Emer","R_Program1",
"DoorSelectL","DoorSelectR","DoorBlock",
"EmerBrakeAdd","EmerBrakeRelease","EmerBrake","DoorClose","AttentionMessage","Attention","AttentionBrake","EmergencyBrake",
"SF1","SF2","SF3","SF4","SF5","SF6","SF7","SF8","SF9","SF10","SF11","SF12",
"SF13","SF14","SF15","SF16","SF17","SF18","SF19","SF20","SF21","SF22",
"SFV1","SFV2","SFV3","SFV4","SFV5","SFV6","SFV7","SFV8","SFV9","SFV10","SFV11",
"SFV12","SFV13","SFV14","SFV15","SFV16","SFV17","SFV18","SFV19","SFV20","SFV21","SFV22",
"SFV23","SFV24","SFV25","SFV26","SFV27","SFV28","SFV29","SFV30","SFV31","SFV32","SFV33",
"Stand","EmergencyCompressor","EmergencyControls","Wiper","DoorLeft","AccelRate","HornB","DoorRight",
"Pant1","Pant2","Vent1","Vent2","Vent","PassLight","CabLight","Headlights1","Headlights2",
"ParkingBrake","TorecDoors","BBER","BBE","Compressor","CabLightStrength","AppLights1","AppLights2",
"Battery", "ALSFreq",
"VityazF1", "VityazF2", "VityazF3", "VityazF4", "Vityaz1", "Vityaz4", "Vityaz7", "Vityaz2", "Vityaz5", "Vityaz8", "Vityaz0", "Vityaz3", "Vityaz6", "Vityaz9", "VityazF5", "VityazF6", "VityazF7", "VityazF8", "VityazF9",
"K29", "UAVA",
"EmerX1","EmerX2","EmerCloseDoors","EmergencyDoors",
"R_ASNPMenu","R_ASNPUp","R_ASNPDown","R_ASNPOn",
"VentHeatMode",
"RearBrakeLineIsolation","RearTrainLineIsolation",
"FrontBrakeLineIsolation","FrontTrainLineIsolation",
"PB", "GV",
}
--------------------------------------------------------------------------------
function ENT:Initialize()
-- Set model and initialize
self:SetModel("models/metrostroi_train/81-720/81-720.mdl")
self.BaseClass.Initialize(self)
self:SetPos(self:GetPos() + Vector(0,0,150))
self.Plombs = {
KAH = {true,"KAHk"},
KAHk = true,
ALS = {true,"ALSk"},
ALSk = true,
BARSBlock = true,
UAVA = true,
Init = true,
}
-- Create seat entities
self.DriverSeat = self:CreateSeat("driver",Vector(439,13,-40))
self.InstructorsSeat = self:CreateSeat("instructor",Vector(445,50,-50),Angle(0,40,0),"models/vehicles/prisoner_pod_inner.mdl")
self.InstructorsSeat2 = self:CreateSeat("instructor",Vector(435,35,-50),Angle(0,90,0),"models/vehicles/prisoner_pod_inner.mdl")
self.InstructorsSeat3 = self:CreateSeat("instructor",Vector(435,-45,-50),Angle(0,90+40,0),"models/vehicles/prisoner_pod_inner.mdl")
self.InstructorsSeat4 = self:CreateSeat("instructor",Vector(425,-25,-50),Angle(0,90,0),"models/vehicles/prisoner_pod_inner.mdl")
-- Hide seats
self.DriverSeat:SetRenderMode(RENDERMODE_TRANSALPHA)
self.DriverSeat:SetColor(Color(0,0,0,0))
self.InstructorsSeat:SetRenderMode(RENDERMODE_TRANSALPHA)
self.InstructorsSeat:SetColor(Color(0,0,0,0))
self.InstructorsSeat2:SetRenderMode(RENDERMODE_TRANSALPHA)
self.InstructorsSeat2:SetColor(Color(0,0,0,0))
self.InstructorsSeat3:SetRenderMode(RENDERMODE_TRANSALPHA)
self.InstructorsSeat3:SetColor(Color(0,0,0,0))
self.InstructorsSeat4:SetRenderMode(RENDERMODE_TRANSALPHA)
self.InstructorsSeat4:SetColor(Color(0,0,0,0))
-- Create bogeys
if Metrostroi.BogeyOldMap then
self.FrontBogey = self:CreateBogey(Vector( 350,-1,-91),Angle(0,180,0),true,"720")
self.RearBogey = self:CreateBogey(Vector(-320,1,-91),Angle(0,0,0),false,"720")
self.FrontCouple = self:CreateCouple(Vector( 448,0,-79),Angle(0,0,0),true,"717")
self.RearCouple = self:CreateCouple(Vector(-419.5-6.8,0,-79),Angle(0,180,0),false,"717")
else
self.FrontBogey = self:CreateBogey(Vector( 350,-1,-91),Angle(0,180,0),true,"720")
self.RearBogey = self:CreateBogey(Vector(-320,1,-91),Angle(0,0,0),false,"720")
self.FrontCouple = self:CreateCouple(Vector( 454 -8,0,-79),Angle(0,0,0),true,"717")
self.RearCouple = self:CreateCouple(Vector(-419-6.8+8,0,-79),Angle(0,180,0),false,"717")
end
self.FrontBogey:SetNWBool("Async",true)
self.RearBogey:SetNWBool("Async",true)
self.FrontBogey:SetNWInt("MotorSoundType",2)
self.RearBogey:SetNWInt("MotorSoundType",2)
local rand = math.random()*0.05
self.FrontBogey:SetNWFloat("SqualPitch",1.45+rand)
self.RearBogey:SetNWFloat("SqualPitch",1.45+rand)
self.FrontCouple.EKKDisconnected = true
-- Initialize key mapping
self.KeyMap = {
[KEY_W] = "PanelKVUp",
[KEY_S] = "PanelKVDown",
[KEY_1] = "PanelKV1",
[KEY_2] = "PanelKV2",
[KEY_3] = "PanelKV3",
[KEY_4] = "PanelKV4",
[KEY_5] = "PanelKV5",
[KEY_6] = "PanelKV6",
[KEY_7] = "PanelKV7",
[KEY_8] = "PanelKV8",
[KEY_9] = "KRO-",
[KEY_0] = "KRO+",
[KEY_A] = "DoorLeft",
[KEY_D] = "DoorRight",
[KEY_V] = "DoorClose",
[KEY_G] = "EnableBVSet",
[KEY_SPACE] = {
def="PBSet",
[KEY_LSHIFT] = "AttentionBrakeSet",
},
[KEY_PAD_ENTER] = "KVWrenchKV",
[KEY_EQUAL] = "R_Program1Set",
[KEY_RBRACKET] = "R_Program1Set",
[KEY_MINUS] = "R_Program2Set",
[KEY_LSHIFT] = {
def="PanelControllerUnlock",
[KEY_SPACE] = "AttentionBrakeSet",
[KEY_V] = "EmergencyDoorsToggle",
[KEY_7] = "WrenchNone",
[KEY_8] = "WrenchKRR",
[KEY_9] = "WrenchKRO9",
[KEY_0] = "WrenchKRO",
[KEY_G] = "EnableBVEmerSet",
[KEY_2] = "RingSet",
[KEY_L] = "HornEngage",
[KEY_PAD_ENTER] = "KVWrenchNone",
},
[KEY_LALT] = {
[KEY_V] = "DoorCloseToggle",
[KEY_PAD_1] = "Vityaz1Set",
[KEY_PAD_2] = "Vityaz2Set",
[KEY_PAD_3] = "Vityaz3Set",
[KEY_PAD_4] = "Vityaz4Set",
[KEY_PAD_5] = "Vityaz5Set",
[KEY_PAD_6] = "Vityaz6Set",
[KEY_PAD_7] = "Vityaz7Set",
[KEY_PAD_8] = "Vityaz8Set",
[KEY_PAD_9] = "Vityaz9Set",
[KEY_PAD_0] = "Vityaz0Set",
[KEY_PAD_DECIMAL] = "VityazF5Set",
[KEY_PAD_ENTER] = "VityazF8Set",
[KEY_UP] = "VityazF6Set",
[KEY_LEFT] = "VityazF5Set",
[KEY_DOWN] = "VityazF7Set",
[KEY_RIGHT] = "VityazF9Set",
[KEY_PAD_MINUS] = "VityazF2Set",
[KEY_PAD_PLUS] = "VityazF3Set",
[KEY_PAD_MULTIPLY] = "VityazF4Set",
[KEY_PAD_DIVIDE] = "VityazF1Set",
[KEY_SPACE] = "AttentionMessageSet",
},
[KEY_PAD_PLUS] = "EmerBrakeAddSet",
[KEY_PAD_MINUS] = "EmerBrakeReleaseSet",
[KEY_F] = "PneumaticBrakeUp",
[KEY_R] = "PneumaticBrakeDown",
[KEY_PAD_1] = "PneumaticBrakeSet1",
[KEY_PAD_2] = "PneumaticBrakeSet2",
[KEY_PAD_3] = "PneumaticBrakeSet3",
[KEY_PAD_4] = "PneumaticBrakeSet4",
[KEY_PAD_5] = "PneumaticBrakeSet5",
[KEY_PAD_6] = "PneumaticBrakeSet6",
[KEY_PAD_DIVIDE] = "EmerX1Set",
[KEY_PAD_MULTIPLY] = "EmerX2Set",
[KEY_PAD_9] = "EmerBrakeToggle",
[KEY_BACKSPACE] = "EmergencyBrakeToggle",
[KEY_L] = "HornBSet",
}
self.KeyMap[KEY_RALT] = self.KeyMap[KEY_LALT]
self.KeyMap[KEY_RSHIFT] = self.KeyMap[KEY_LSHIFT]
self.KeyMap[KEY_RCONTROL] = self.KeyMap[KEY_LCONTROL]
-- Cross connections in train wires
self.TrainWireCrossConnections = {
[4] = 3, -- Orientation F<->B
[13] = 12, -- Reverser F<->B
[38] = 37, -- Doors L<->R
}
self.InteractionZones = {
{ Pos = Vector(466, 64, 30),
Radius = 48,
ID = "CabinDoorLeft" },
{ Pos = Vector(466, 64, -30),
Radius = 48,
ID = "CabinDoorLeft" },
{ Pos = Vector(466, -60, 30),
Radius = 48,
ID = "CabinDoorRight" },
{ Pos = Vector(466, -60, -30),
Radius = 48,
ID = "CabinDoorRight" },
{ Pos = Vector(378, 39, 50),
Radius = 32,
ID = "OtsekDoor" },
{ Pos = Vector(378, 39, 11),
Radius = 32,
ID = "OtsekDoor" },
{
ID = "FrontBrakeLineIsolationToggle",
Pos = Vector(495, -22, -60), Radius = 16,
},
{
ID = "FrontTrainLineIsolationToggle",
Pos = Vector(495, 22, -60), Radius = 16,
},
{
ID = "RearBrakeLineIsolationToggle",
Pos = Vector(-470, 30, -60), Radius = 16,
},
{
ID = "RearTrainLineIsolationToggle",
Pos = Vector(-470, -30, -60), Radius = 16,
},
{
ID = "RearDoor",
Pos = Vector(-464.8,-30,0), Radius = 20,
},
{
ID = "GVToggle",
Pos = Vector(128,60,-75), Radius = 20,
},
{
ID = "AirDistributorDisconnectToggle",
Pos = Vector(-177, -66, -50), Radius = 20,
},
}
self.PassengerDoor = false
self.CabinDoorLeft = false
self.CabinDoorRight = false
self.RearDoor = false
self.OtsekDoor = false
self.WrenchMode = 0
end
function ENT:NonSupportTrigger()
self.ALS:TriggerInput("Set",1)
self.ALSk:TriggerInput("Set",1)
self.BARSBlock:TriggerInput("Set",3)
self.Plombs.ALS = nil
self.Plombs.ALSk = nil
self.Plombs.BARSBlock = nil
end
--------------------------------------------------------------------------------
function ENT:Think()
local retVal = self.BaseClass.Think(self)
local power = self.Electric.Battery80V > 62
--print(self,self.BPTI.T,self.BPTI.State)
--[[ if self.BUV.Brake > 0 then
self:SetPackedRatio("RNState", power and (Train.K2.Value>0 or Train.K3.Value>0) and self.Electric.RN > 0 and (1-self.Electric.RNState)+math.Clamp(1-(math.abs(self.Electric.Itotal)-50)/50,0,1) or 1)
else
self:SetPackedRatio("RNState", power and (Train.K2.Value>0 or Train.K3.Value>0) and self.Electric.RN > 0 and self.Electric.RNState+math.Clamp(1-(math.abs(self.Electric.Itotal)-50)/50,0,1) or 1)
end--]]
if self.BPTI.State < 0 then
self:SetPackedRatio("RNState", ((self.BPTI.RNState)-0.25)*math.Clamp((math.abs(self.Electric.Itotal/2)-30-self.Speed*2)/20,0,1))
--self:SetNW2Int("RNFreq", 13)
else--if self.BPTI.State > 0 then
self:SetPackedRatio("RNState", (0.75-self.BPTI.RNState)*math.Clamp((math.abs(self.Electric.Itotal/2)-30-self.Speed*2)/20,0,1))
--self:SetNW2Int("RNFreq", ((self.BPTI.FreqState or 0)-1/3)/(2/3)*12)
--[[ else
self:SetPackedRatio("RNState", 0)--]]
end
self:SetPackedRatio("Speed", self.Speed)
self:SetNW2Int("Wrench",self.WrenchMode)
self:SetPackedRatio("Controller",self.Panel.Controller)
self:SetPackedRatio("KRO",(self.RV.KROPosition+1)/2)
self:SetPackedRatio("KRR",(self.RV.KRRPosition+1)/2)
self:SetPackedRatio("VentCondMode",self.VentCondMode.Value/3)
self:SetPackedRatio("VentStrengthMode",self.VentStrengthMode.Value/3)
--self:SetPackedRatio("VentHeatMode",self.VentHeatMode.Value/2)
self:SetPackedRatio("BARSBlock",self.BARSBlock.Value/3)
self:SetPackedBool("BBEWork",power and self.BUV.BBE > 0)
self:SetPackedBool("WorkBeep",power)
--print(0.4+math.max(0,math.min(1,1-(self.Speed-30)/30))*0.5)
--print((80-self.Engines.Speed))
self:SetPackedBool("HeadlightsEnabled1",self.Panel.Headlights1>0)
self:SetPackedBool("HeadlightsEnabled2",self.Panel.Headlights2>0)
local headlights = self.Panel.Headlights1*0.5+self.Panel.Headlights2*0.5
local redlights = self.Panel.RedLights>0
self:SetPackedBool("BacklightsEnabled",redlights)
self:SetPackedBool("CabinEnabledEmer", self.Panel.CabLights > 0)
self:SetPackedBool("CabinEnabledFull", self.Panel.CabLights > 0.5)
self:SetPackedRatio("SalonLighting",power and (self.BUV.MainLights and 1 or self.SFV20.Value > 0.5 and 0.4) or 0)
--self:SetPackedRatio("TrainLine",7.3/16)
--self:SetPackedRatio("BrakeLine",5.2/16)
--self:SetPackedRatio("BrakeCylinder",self.AsyncInverter.PN1*1.1/6)
if self:GetWagonNumber() == 37 then
--self.BV:TriggerInput("Set",0)
end
self:SetPackedRatio("BIAccel",power and self.BARS.BIAccel or 0)
self:SetNW2Int("BISpeed",power and self.Speed or -1)--CurTime()%5*20
self:SetNW2Bool("BISpeedLimitBlink",power and self.BARS.BINoFreq > 0)
self:SetNW2Int("BISpeedLimit",power and self.BARS.SpeedLimit or 100)
self:SetNW2Int("BISpeedLimitNext",power and self.BARS.NextLimit or 100)
self:SetNW2Bool("BIForward",power and self.BARS.BIDirection >= 0)--power and (self.RV["KRO3-4"] > 0 or self.RV["KRR5-6"] > 0) and self.BARS.Speed > -0.2)
self:SetNW2Bool("BIBack",power and self.BARS.BIDirection <= 0)--power and (self.RV["KRO3-4"] > 0 or self.RV["KRR5-6"] > 0) and self.BARS.Speed < 0.2)
self:SetNW2Bool("DoorsClosed",power and self.BUKP.DoorClosed)
self:SetNW2Bool("HVoltage",power and self.BUKP.HVBad)
self:SetNW2Bool("DoorLeftLamp",self.Panel.DoorLeft>0)
self:SetNW2Bool("DoorRightLamp",self.Panel.DoorRight>0)
self:SetNW2Bool("EmerBrakeWork",self.Panel.EmerBrakeWork>0)
self:SetNW2Bool("TickerLamp",self.Panel.Ticker>0)
self:SetNW2Bool("KAHLamp",self.Panel.KAH>0)
self:SetNW2Bool("ALSLamp",self.Panel.ALS>0)
self:SetNW2Bool("PassSchemeLamp",self.Panel.PassScheme>0)
self:SetNW2Bool("R_AnnouncerLamp",self.Panel.R_Announcer>0)
self:SetNW2Bool("R_LineLamp",self.Panel.R_Line>0)
self:SetNW2Bool("AccelRateLamp",power and self.BUKP.Slope)
self:SetNW2Bool("DoorCloseLamp",self.Panel.DoorClose>0)
self:SetNW2Bool("DoorBlockLamp",self.Panel.DoorBlock>0)
self:SetPackedBool("AppLights", self.Panel.EqLights>0)
self:SetPackedRatio("LV",self.Electric.Battery80V/150)
self:SetPackedRatio("HV",self.Electric.Main750V/1000)
self:SetPackedRatio("I13",(self.Electric.I13+500)/1000)
self:SetPackedRatio("I24",(self.Electric.I24+500)/1000)
self:SetPackedBool("PassengerDoor",self.PassengerDoor)
self:SetPackedBool("CabinDoorLeft",self.CabinDoorLeft)
self:SetPackedBool("CabinDoorRight",self.CabinDoorRight)
self:SetPackedBool("RearDoor",self.RearDoor)
self:SetPackedBool("OtsekDoor",self.OtsekDoor)
self:SetPackedBool("CompressorWork",self.Pneumatic.Compressor)
self:SetPackedBool("Vent1Work",self.Electric.Vent1>0)
self:SetPackedBool("Vent2Work",self.Electric.Vent2>0)
self:SetPackedBool("RingEnabled",self.BUKP.Ring)
self:SetNW2Int("PassSchemesLED",self.PassSchemes.PassSchemeCurr)
self:SetNW2Int("PassSchemesLEDN",self.PassSchemes.PassSchemeNext)
self:SetPackedBool("PassSchemesLEDO",self.PassSchemes.PassSchemePath)
self:SetPackedBool("AnnPlay",self.Panel.AnnouncerPlaying > 0)
self:SetPackedRatio("Cran", self.Pneumatic.DriverValvePosition)
self:SetPackedRatio("BL", self.Pneumatic.BrakeLinePressure/16.0)
self:SetPackedRatio("TL", self.Pneumatic.TrainLinePressure/16.0)
self:SetPackedRatio("BC", math.min(3.2,self.Pneumatic.BrakeCylinderPressure)/6.0)
self.Engines:TriggerInput("Speed",self.Speed)
if IsValid(self.FrontBogey) and IsValid(self.RearBogey) and not self.IgnoreEngine then
local A = 2*self.Engines.BogeyMoment
self.FrontBogey.MotorForce = (24000+3000*(A < 0 and 1 or 0))--*add--35300+10000*(A < 0 and 1 or 0)
self.FrontBogey.Reversed = self.KMR2.Value > 0
self.FrontBogey.DisableSound = 0
self.RearBogey.MotorForce = (24000+3000*(A < 0 and 1 or 0))--*add--+5000--35300
self.RearBogey.Reversed = self.KMR1.Value > 0
self.RearBogey.DisableSound = 0
-- These corrections are required to beat source engine friction at very low values of motor power
local P = math.max(0,0.04449 + 1.06879*math.abs(A) - 0.465729*A^2)
if math.abs(A) > 0.4 then P = math.abs(A) end
if math.abs(A) < 0.05 then P = 0 end
if self.Speed < 10 then P = P*(1.0 + 0.5*(10.0-self.Speed)/10.0) end
self.RearBogey.MotorPower = P*0.5*((A > 0) and 1 or -1)
self.FrontBogey.MotorPower = P*0.5*((A > 0) and 1 or -1)
-- Apply brakes
self.FrontBogey.PneumaticBrakeForce = (50000.0--[[ +5000+10000--]] ) --40000
self.FrontBogey.BrakeCylinderPressure = self.Pneumatic.BrakeCylinderPressure
self.FrontBogey.ParkingBrakePressure = math.max(0,(3-self.Pneumatic.ParkingBrakePressure)/3)/2
self.FrontBogey.BrakeCylinderPressure_dPdT = -self.Pneumatic.BrakeCylinderPressure_dPdT
self.FrontBogey.DisableContacts = self.BUV.Pant
self.RearBogey.PneumaticBrakeForce = (50000.0--[[ +5000+10000--]] ) --40000
self.RearBogey.BrakeCylinderPressure = self.Pneumatic.BrakeCylinderPressure
self.RearBogey.BrakeCylinderPressure_dPdT = -self.Pneumatic.BrakeCylinderPressure_dPdT
self.RearBogey.ParkingBrakePressure = math.max(0,(3-self.Pneumatic.ParkingBrakePressure)/3)/2
self.RearBogey.DisableContacts = self.BUV.Pant
end
return retVal
end
function ENT:OnCouple(train,isfront)
if isfront and self.FrontAutoCouple then
self.FrontBrakeLineIsolation:TriggerInput("Open",1.0)
self.FrontTrainLineIsolation:TriggerInput("Open",1.0)
self.FrontAutoCouple = false
elseif not isfront and self.RearAutoCouple then
self.RearBrakeLineIsolation:TriggerInput("Open",1.0)
self.RearTrainLineIsolation:TriggerInput("Open",1.0)
self.RearAutoCouple = false
end
self.BaseClass.OnCouple(self,train,isfront)
end
function ENT:OnButtonPress(button,ply)
if string.find(button,"PneumaticBrakeSet") then
self.Pneumatic:TriggerInput("BrakeSet",tonumber(button:sub(-1,-1)))
return
end
if button == "PassengerDoor" then self.PassengerDoor = not self.PassengerDoor end
if button == "CabinDoorLeft" then self.CabinDoorLeft = not self.CabinDoorLeft end
if button == "OtsekDoor" then self.OtsekDoor = not self.OtsekDoor end
if button == "CabinDoorRight" then self.CabinDoorRight = not self.CabinDoorRight end
if button == "RearDoor" and (self.RearDoor or not self.BUV.BlockTorec) then self.RearDoor = not self.RearDoor end
if button == "DoorLeft" then
self.DoorSelectL:TriggerInput("Set",1)
self.DoorSelectR:TriggerInput("Set",0)
if self.EmergencyDoors.Value == 1 or self.DoorClose.Value == 0 then
self.DoorLeft:TriggerInput("Set",1)
end
end
if button == "DoorRight" then
self.DoorSelectL:TriggerInput("Set",0)
self.DoorSelectR:TriggerInput("Set",1)
if self.EmergencyDoors.Value == 1 or self.DoorClose.Value == 0 then
self.DoorRight:TriggerInput("Set",1)
end
end
if button == "DoorClose" then
if self.EmergencyDoors.Value == 1 then
self.EmerCloseDoors:TriggerInput("Set",1)
else
self.DoorClose:TriggerInput("Set",1-self.DoorClose.Value)
self.EmerCloseDoors:TriggerInput("Set",0)
end
end
if button == "KRO+" then
if self.WrenchMode == 1 then
self.RV:TriggerInput("KROSet",self.RV.KROPosition+1)
elseif self.WrenchMode == 2 then
self.RV:TriggerInput("KRRSet",self.RV.KRRPosition+1)
end
end
if button == "KRO-" then
if self.WrenchMode == 1 then
self.RV:TriggerInput("KROSet",self.RV.KROPosition-1)
elseif self.WrenchMode == 2 then
self.RV:TriggerInput("KRRSet",self.RV.KRRPosition-1)
end
end
if button == "WrenchKRO" or button == "WrenchKRO9" then
if self.WrenchMode == 0 then
self:PlayOnce("kro_in","cabin",1)
self.WrenchMode = 1
else
self:OnButtonPress(button == "WrenchKRO9" and "KRO-" or "KRO+")
end
end
if button == "WrenchKRR" then
if self.WrenchMode == 0 then
self:PlayOnce("krr_in","cabin",1)
self.WrenchMode = 2
end
end
if button == "WrenchNone" then
if self.WrenchMode ~= 0 then
if self.WrenchMode == 2 and self.RV.KRRPosition == 0 then
self:PlayOnce("krr_out","cabin",1,1)
self.WrenchMode = 0
elseif self.WrenchMode == 1 and self.RV.KROPosition == 0 then
self:PlayOnce("kro_out","cabin",1,1)
self.WrenchMode = 0
end
end
end
end
function ENT:OnButtonRelease(button,ply)
if string.find(button,"PneumaticBrakeSet") then
if button == "PneumaticBrakeSet1" and (self.Pneumatic.DriverValvePosition == 1) then
self.Pneumatic:TriggerInput("BrakeSet",2)
end
return
end
if button == "DoorLeft" then
self.DoorLeft:TriggerInput("Set",0)
end
if button == "DoorRight" then
self.DoorRight:TriggerInput("Set",0)
end
if button == "DoorClose" then
self.EmerCloseDoors:TriggerInput("Set",0)
end
end
|
rule {
outs = {},
ins = {},
cmds = {}
}
rule {
outs = "a",
ins = "b",
cmds = "c",
dirs = "d"
}
|
-- Code here --
|
--------------------------------------------------------------------------------
-- Module Declaration
--
local mod, CL = BigWigs:NewBoss("Trial of the King", 994, 708)
if not mod then return end
-- Xin the Weaponmaster, Haiyan the Unstoppable, Ming the Cunning, Kuai the Brute
mod:RegisterEnableMob(61884, 61445, 61444, 61442)
mod.engageId = 1442
mod.respawnTime = 15
--------------------------------------------------------------------------------
-- Initialization
--
function mod:GetOptions()
return {
119922, -- Shockwave
{-6017, "ICON"}, -- Ravage
{-6024, "ICON"}, -- Conflagrate
{120195, "ICON", "SAY", "FLASH"}, -- Meteor
{123655, "HEALER"}, -- Traumatic Blow
}, {
[119922] = -6015, -- Kuai
[-6024] = -6023, -- Haiyan
}
end
function mod:VerifyEnable(unit)
local hp = UnitHealth(unit) / UnitHealthMax(unit) * 100
if hp > 15 then
return true
end
end
function mod:OnBossEnable()
self:Log("SPELL_AURA_APPLIED", "TraumaticBlow", 123655)
self:Log("SPELL_AURA_APPLIED", "Ravage", 119946)
self:Log("SPELL_AURA_REMOVED", "RavageOver", 119946)
self:Log("SPELL_AURA_APPLIED", "Conflagrate", 120160)
self:Log("SPELL_AURA_REMOVED", "ConflagrateOver", 120160)
self:Log("SPELL_CAST_START", "Shockwave", 119922)
self:RegisterUnitEvent("UNIT_SPELLCAST_STOP", "MeteorFinished", "boss1")
self:RegisterEvent("CHAT_MSG_RAID_BOSS_EMOTE")
end
function mod:OnEngage()
self:RegisterEvent("INSTANCE_ENCOUNTER_ENGAGE_UNIT")
self:INSTANCE_ENCOUNTER_ENGAGE_UNIT()
end
--------------------------------------------------------------------------------
-- Event Handlers
--
function mod:INSTANCE_ENCOUNTER_ENGAGE_UNIT()
local mobId = self:MobId(UnitGUID("boss1"))
if mobId == 61445 then -- Haiyan the Unstoppable
self:CDBar(120195, 40) -- Meteor
elseif mobId == 61444 or mobId == 61442 then -- Ming the Cunning or Kuai the Brute
self:StopBar(120195)
end
end
function mod:TraumaticBlow(args)
self:TargetMessage(args.spellId, args.destName, "green")
self:TargetBar(args.spellId, 5, args.destName)
end
function mod:Ravage(args)
self:TargetMessage(-6017, args.destName, "yellow", nil, args.spellId)
self:TargetBar(-6017, 11, args.destName, args.spellId)
self:PrimaryIcon(-6017, args.destName)
end
function mod:RavageOver()
self:PrimaryIcon(-6017)
end
function mod:Conflagrate(args)
self:TargetMessage(-6024, args.destName, "yellow", nil, args.spellId)
self:TargetBar(-6024, 5, args.destName, args.spellId)
self:SecondaryIcon(-6024, args.destName)
end
function mod:ConflagrateOver()
self:SecondaryIcon(-6024)
end
function mod:Shockwave(args)
self:Message(args.spellId, "orange", "Alert", CL.casting:format(args.spellName), args.spellId)
self:Bar(args.spellId, 2, CL.cast:format(args.spellName), args.spellId)
end
function mod:MeteorFinished(_, _, _, spellId)
if spellId == 120195 then
self:PrimaryIcon(spellId)
end
end
function mod:CHAT_MSG_RAID_BOSS_EMOTE(_, msg, _, _, _, player)
if msg:find("meteorstorm", nil, true) then -- |TInterface\\Icons\\spell_fire_meteorstorm.blp:20|tHaiyan the Unstoppable targets |cFFFF0000PLAYER|r with a |cFFFF0000|Hspell:120195|h[Meteor]|h|r!
self:TargetMessage(120195, player, "red", "Alarm")
self:TargetBar(120195, 5, player)
self:PrimaryIcon(120195, player)
if UnitIsUnit(player, "player") then
self:Flash(120195)
self:Say(120195)
end
end
end
|
local magic = {}
local log = require('nvim-magic._log')
magic.backends = {} -- should be set during setup()
local function default_config()
return {
backends = {
default = require('nvim-magic-openai').new(),
},
use_default_keymap = true,
}
end
function magic.version()
return '0.3.2-dev'
end
function magic.setup(override)
local config = default_config()
if override then
if override.backends then
assert(type(override.backends) == 'table', 'backends must be a map of backends')
assert(type(override.backends.default) == 'table', 'backends must be a map of backends')
for name, backend in pairs(override.backends) do
assert(type(backend.complete) == 'function', 'backend ' .. name .. ' needs a complete function')
end
config.backends = override.backends
end
if override.use_default_keymap then
assert(type(override.use_default_keymap == 'boolean'), 'use_default_keymap must be a boolean')
config.use_default_keymap = override.use_default_keymap
end
end
log.fmt_debug('Got config=%s ', config)
magic.backends = config.backends
if config.use_default_keymap then
require('nvim-magic._keymaps').set_default()
log.debug('Set default keymaps')
end
end
return magic
|
local COLOR_DIV = cat.COLOR_DIV
function cat.color_rgba(r,g,b,a)
return r * COLOR_DIV,g * COLOR_DIV,b * COLOR_DIV,a * COLOR_DIV
end
function cat.color_hsv(h,s,v,a)
a = a or 255
if s <= 0 then return v,v,v end
h, s, v = h/256*6, s/255, v/255
local c = v*s
local x = (1-math.abs((h%2)-1))*c
local m,r,g,b = (v-c), 0,0,0
if h < 1 then r,g,b = c,x,0
elseif h < 2 then r,g,b = x,c,0
elseif h < 3 then r,g,b = 0,c,x
elseif h < 4 then r,g,b = 0,x,c
elseif h < 5 then r,g,b = x,0,c
else r,g,b = c,0,x
end return ((r+m)*255) * COLOR_DIV,((g+m)*255) * COLOR_DIV,((b+m)*255) * COLOR_DIV,a * COLOR_DIV
end
return function(r,g,b,a)
local color = {
r = r or 255,
g = g or 255,
b = b or 255,
a = a or 255,
}
function color:unpack()
return self.r * COLOR_DIV,self.g * COLOR_DIV,self.b * COLOR_DIV,self.a * COLOR_DIV
end
function color:to_hsv()
return cat.color_hsv(self:unpack())
end
return color
end
|
local K, C, L = unpack(select(2, ...))
if C.Skins.MinimapButtons ~= true or C.Minimap.Enable ~= true then return end
local match = string.match
local select = select
local find = string.find
local unpack = unpack
-- Skin addons icons on minimap
local buttons = {
"GameTimeFrame",
"GatherMatePin",
"HandyNotesPin",
"HelpOpenTicketButton",
"MiniMapMailFrame",
"MiniMapTrackingButton",
"QueueStatusMinimapButton",
"TimeManagerClockButton"
}
local function SkinButton(f)
if not f or f:GetObjectType() ~= "Button" then return end
for i, buttons in pairs(buttons) do
if f:GetName() ~= nil then
if f:GetName():match(buttons) then return end
end
end
f:SetPushedTexture(nil)
f:SetHighlightTexture(nil)
f:SetDisabledTexture(nil)
f:SetSize(19, 19)
for i = 1, f:GetNumRegions() do
local region = select(i, f:GetRegions())
if (region:IsVisible() or region:IsShown()) and (region:GetObjectType() == "Texture") then
local tex = tostring(region:GetTexture())
-- if tex and (tex:find("Border") or tex:find("Background") or tex:find("AlphaMask")) then
if tex and (strfind(tex, 'Border') or strfind(tex, 'Background') or strfind(tex, 'AlphaMask') or strfind(tex, 'Highlight')) then
region:SetTexture(nil)
else
region:ClearAllPoints()
region:SetInside()
region:SetTexCoord(unpack(K.TexCoords))
region:SetDrawLayer("ARTWORK")
if f:GetName() == "PS_MinimapButton" then
region.SetPoint = K.Noop
end
end
end
end
K.CreateBorder(f, 1)
f:SetBackdrop(K.BorderBackdrop)
f:SetBackdropColor(C.Media.Backdrop_Color[1], C.Media.Backdrop_Color[2], C.Media.Backdrop_Color[3], C.Media.Backdrop_Color[4])
end
local frame = CreateFrame("Frame")
frame:RegisterEvent("PLAYER_LOGIN")
frame:RegisterEvent("ZONE_CHANGED_NEW_AREA")
frame:SetScript("OnEvent", function(self, event)
if event == "PLAYER_LOGIN" then
for i = 1, Minimap:GetNumChildren() do
SkinButton(select(i, Minimap:GetChildren()))
end
end
if WIM3MinimapButton and WIM3MinimapButton:GetNumRegions() < 9 then
SkinButton(WIM3MinimapButton)
SkinButton(WIM3MinimapButton)
end
self = nil
end)
|
#!/usr/bin/lua
package.path = "../src/?.lua;" .. package.path
local epnf = require( "epnf" )
local nan, inf = 0/0, 1/0
-- luacheck: ignore _ENV protofile message import pkg enum extend option service
-- luacheck: ignore messagefield ignore extensions enumfield fieldoption msgoptionv rpc
local pg = epnf.define( function(_ENV) -- begin of grammar definition
-- some useful lexical patterns
local any = P( 1 )
local comment = ((P"//"+P"#") * (any-P"\n")^0) +
(P"/*" * (any-P"*/")^0 * P"*/") -- comments
local _ = (WS + comment)^0 -- white space
local sign = S"+-"
local digit = R"09"
local digit1 = R"19"
local octdigit = R"07"
local hexdigit = R( "09", "af", "AF" )
local decimal = P"0" + (digit1 * digit^0)
local int = C( sign^-1 * decimal ) / tonumber
local oct = P"0" * (C( octdigit^1 ) * Cc( 8 )) / tonumber
local hex = P"0" * S"xX" * (C( hexdigit^1 ) * Cc( 16 )) / tonumber
local letter = R( "az", "AZ" ) + P"_"
local charescape = P"\\" * C( S"abfnrtv\\'\"" ) / {
[ "a" ] = "\a", [ "b" ] = "\b", [ "f" ] = "\f",
[ "n" ] = "\n", [ "r" ] = "\r", [ "t" ] = "\t",
[ "v" ] = "\v", [ "\\" ] = "\\", [ "'" ] = "'",
[ '"' ] = '"'
}
local hexescape = P"\\" * S"xX" * C( hexdigit * hexdigit^-1 ) / function( s )
return string.char( tonumber( s, 16 ) )
end
local octescape = P"\\" * C( P"0"^-1 * octdigit * octdigit^-2 ) / function( s )
return string.char( tonumber( s, 8 ) )
end
local sliteral = (P'"' * Cs( (charescape + hexescape +
octescape + (any-P'"'))^0 ) * P'"') +
(P"'" * Cs( (charescape + hexescape +
octescape + (any-P"'"))^0 ) * P"'")
local bool = C( W"true" + W"false" ) / { [ "true" ] = true,
[ "false" ] = false }
local integer = hex + oct + int
local special_float = C( W"inf" + W"-inf" + W"nan" ) / {
nan = nan, inf = inf, [ "-inf" ] = -inf
}
local float = C( sign^-1 * decimal * (P"." * digit^1)^-1 *
(S"Ee" * sign^-1 * digit^1)^-1 ) / tonumber
+ special_float
local rawname = letter * (letter + digit)^0
local rel_ref = rawname * (P"." * rawname)^0
local abs_ref = P"." * rel_ref
--local ref = C( abs_ref + rel_ref )
local ref = C( P"."^-1 * rel_ref )
local oref = ((P"(" * _ * ref * _ * (P")"+E()) * C( abs_ref )^-1)
/ function( a, b ) return a .. (b or "") end) + ref
local oval = bool + integer + float + sliteral + ID + V"msgoptionv"
local empty_statement = P";" * _
local syntax = W"syntax" * _ * (P"="+E()) * _ * (W"proto2"+E()) *
_ * (P";"+E()) * _
local function csv( expr )
return expr * (P"," * _ * expr)^0
end
START "protofile"
protofile = _ * syntax^-1 * (V"message" + V"import" + V"pkg" +
V"enum" + V"extend" + V"option" + V"service" +
empty_statement)^0 * EOF()
message = W"message" * _ * (ID+E()) * _ * (P"{"+E()) * _ *
(V"messagefield" + V"enum" + V"message" + V"extensions" +
V"extend" + V"option" + empty_statement)^0 * (P"}"+E()) * _
import = W"import" * _ * (sliteral+E()) * _ * (P";"+E()) * _
pkg = W"pkg" * _ * (ref+E()) * _ * (P";"+E()) * _
enum = W"enum" * _ * (ID+E()) * _ * (P"{"+E()) * _ *
(V"enumfield" + V"option" + empty_statement)^0 * (P"}"+E()) * _
extend = W"extend" * _ * (ref+E()) * _ * (P"{"+E()) * _ *
(V"messagefield" + empty_statement)^0 * (P"}"+E()) * _
option = W"option" * _ * (oref+E()) * _ * (P"="+E()) * _ *
(oval+E()) * _ * (P";"+E()) * _
service = W"service" * _ * (ID+E()) * _ * (P"{"+E()) * _ *
(V"option" + V"rpc" + empty_statement)^0 * (P"}"+E()) * _
local fieldoptions = (P"[" * _ * csv( (V"fieldoption"+E()) * _ ) *
(P"]"+E()))^-1 * _
messagefield = C( (W"required" + W"optional" + W"repeated") ) * _ *
(ref+E()) * _ * (ID+E()) * _ * (P"="+E()) * _ *
(integer+E()) * _ * fieldoptions * (P";"+E()) * _
local ext_range = ((integer+E()) * _ * (W"to" * _ *
(integer+C( W"max" )+E()) * _)^-1) / function( s, e )
return s, e or s
end
extensions = W"extensions" * _ * csv( ext_range ) * (P";"+E()) * _
enumfield = ID * _ * (P"="+E()) * _ * (integer+E()) * _ *
fieldoptions * (P";"+E()) * _
fieldoption = oref * _ * (P"="+E()) * _ * (oval+E()) * _
msgoptionv = P"{" * _ * (ID * _ * P":" * _ * oval * _)^1 * (P"}"+E())
rpc = W"rpc" * _ * (ID+E()) * _ *
(P"("+E()) * _ * (ref+E()) * _ * (P")"+E()) * _ *
(W"returns"+E()) * _ *
(P"("+E()) * _ * (ref+E()) * _ * (P")"+E()) * _ *
((P"{" * _ *
(V"option" + empty_statement)^0 *
(P"}"+E())) + (P";"+E())) * _
end ) -- end of grammar definition
local function test( s )
local ok, ast = pcall( epnf.parsestring, pg, s )
if ok then
epnf.dumpast( ast )
else
print( ast )
end
print( ("#"):rep( 70 ) )
end
test[[
message Person {
required string name = 1;
required int32 id = 2;
optional string email = 3;
enum PhoneType {
MOBILE = 0;
HOME = 1;
WORK = 2;
}
message PhoneNumber {
required string number = 1;
optional PhoneType type = 2;
}
repeated PhoneNumber phone = 4;
}
message Person2 {
required string name = 1;
required int32 id = 2;
extensions 4 to max;
}
extend Person2 {
repeated Person.PhoneNumber phone = 4;
}
]]
|
---@diagnostic disable: undefined-global
-- language specific higlights
local lush = require("lush")
local base = require("lush_jsx.base")
local M = {}
M = lush(function()
return {
javascriptreactBraces({ base.LushJSXRedBold }),
javascriptreactFunction({ base.LushJSXAquaItalicBold }),
javascriptreactIdentifier({ base.LushJSXPurple }),
javascriptreactMember({ base.LushJSXPurpleBold }),
javascriptreactNumber({ base.LushJSXMagenta }),
javascriptreactNull({ base.LushJSXMagentaBold }),
javascriptreactParens({ base.LushJSXRedBold }),
javascriptreactImport({ base.LushJSXRedBold }),
javascriptreactExport({ base.LushJSXRedBold }),
javascriptreactClassKeyword({ base.LushJSXRedBold }),
javascriptreactClassExtends({ base.LushJSXRed }),
javascriptreactDefault({ base.LushJSXRedItalicBold }),
javascriptreactClassName({ base.LushJSXPurpleBold }),
javascriptreactClassSuperName({ base.LushJSXPurpleBold }),
javascriptreactGlobal({ base.LushJSXRedUnderline }),
javascriptreactEndColons({ base.LushJSXFg1 }),
javascriptreactFuncArg({ base.LushJSXPurpleBold }),
javascriptreactGlobalMethod({ base.LushJSXFg1 }),
javascriptreactNodeGlobal({ base.LushJSXFg1 }),
javascriptreactBOMWindowProp({ base.LushJSXFg1 }),
javascriptreactArrayMethod({ base.LushJSXPurpleItalic }),
javascriptreactArrayStaticMethod({ base.LushJSXPurpleItalic }),
javascriptreactCacheMethod({ base.LushJSXPurpleItalic }),
javascriptreactDateMethod({ base.LushJSXPurpleItalic }),
javascriptreactMathStaticMethod({ base.LushJSXPurpleItalic }),
javascriptreactProp({ base.LushJSXBlue }),
javascriptreactURLUtilsProp({ base.LushJSXBlueBold }),
javascriptreactBOMNavigatorProp({ base.LushJSXBlueBold }),
javascriptreactDOMDocMethod({ base.LushJSXPurpleItalic }),
javascriptreactDOMDocProp({ base.LushJSXBlueBold }),
javascriptreactBOMLocationMethod({ base.LushJSXPurpleItalic }),
javascriptreactBOMWindowMethod({ base.LushJSXPurpleItalic }),
javascriptreactStringMethod({ base.LushJSXPurpleItalic }),
javascriptreactVariable({ base.LushJSXAqua }),
javascriptreactClassSuper({ base.LushJSXRed }),
javascriptreactFuncKeyword({ base.LushJSXRedItalicBold }),
javascriptreactAsyncFunc({ base.LushJSXAquaItalic }),
javascriptreactClassStatic({ base.LushJSXRedItalic }),
javascriptreactOperator({ base.Operator }),
javascriptreactForOperator({ base.Repeat }),
javascriptreactYield({ base.LushJSXRedItalicBold }),
javascriptreactExceptions({ base.LushJSXError }),
javascriptreactMessage({ base.LushJSXBlue }),
javascriptreactTemplateSB({ base.LushJSXPurple }),
javascriptreactTemplateSubstitution({ base.LushJSXPurple }),
javascriptreactLabel({ base.LushJSXBlue }),
javascriptreactObjectLabel({ base.LushJSXBlue }),
javascriptreactPropertyName({ base.LushJSXBlue }),
javascriptreactLogicSymbols({ base.LushJSXRedBold }),
javascriptreactArrowFunc({ base.LushJSXRedBold }),
javascriptreactDocParamName({ base.LushJSXFg4 }),
javascriptreactDocTags({ base.LushJSXFg4 }),
javascriptreactDocNotation({ base.LushJSXFg4 }),
javascriptreactDocParamType({ base.LushJSXFg4 }),
javascriptreactDocNamedParamType({ base.LushJSXFg4 }),
javascriptreactBrackets({ base.LushJSXRedBold }),
javascriptreactDOMElemAttrs({ base.LushJSXAqua }),
javascriptreactDOMEventMethod({ base.LushJSXPurpleItalic }),
javascriptreactDOMNodeMethod({ base.LushJSXPurpleItalic }),
javascriptreactDOMStorageMethod({ base.LushJSXPurpleItalic }),
javascriptreactHeadersMethod({ base.LushJSXPurpleItalic }),
javascriptreactAsyncFuncKeyword({ base.LushJSXRedItalicBold }),
javascriptreactAwaitFuncKeyword({ base.LushJSXRedItalicBold }),
javascriptreactClassKeyword({ base.LushJSXAqua }),
javascriptreactExtendsKeyword({ base.LushJSXAqua }),
javascriptreactExportDefault({ base.LushJSXAqua }),
javascriptreactTemplateBraces({ base.LushJSXAqua }),
javascriptreactGlobalNodeObjects({ base.LushJSXBlue }),
javascriptreactGlobalObjects({ base.LushJSXBlue }),
javascriptreactObjectKey({ base.LushJSXPurpleBoldContrasted }),
javascriptreactFunction({ base.LushJSXAquaBold }),
javascriptreactFuncCall({ base.LushJSXAquaItalic }),
javascriptreactFuncParens({ base.LushJSXRedItalicBold }),
javascriptreactParens({ base.LushJSXRedBold }),
javascriptreactNull({ base.LushJSXMagentaBold }),
javascriptreactUndefined({ base.LushJSXMagentaBold }),
javascriptreactClassDefinition({ base.LushAquaBold }),
javascriptreactOperatorKeyword({ base.Operator }),
javascriptreactTagName({ base.LushJSXAquaBold }),
javascriptreactComponentName({ base.LushJSXBlueBold }),
javascriptreactCloseString({ base.LushJSXFg4 }),
javascriptreactAttrib({ base.LushJSXAqua }),
javascriptreactEqual({ base.LushJSXMagentaBold }),
}
end)
return M
|
--- Utility methods for JSON
-- @module JSONUtils
local require = require(game:GetService("ReplicatedStorage"):WaitForChild("Nevermore"))
local HttpService = game:GetService("HttpService")
local Promise = require("Promise")
local JSONUtils = {}
function JSONUtils.jsonDecode(str)
if type(str) ~= "string" then
return false, nil, "Not a string"
end
local decoded
local ok, err = pcall(function()
decoded = HttpService:JSONDecode(str)
end)
if not ok then
return false, nil, err
end
return true, decoded
end
function JSONUtils.promiseJSONDecode(str)
if type(str) ~= "string" then
return Promise.rejected("Not a string")
end
return Promise.new(function(resolve, reject)
local decoded
local ok, err = pcall(function()
decoded = HttpService:JSONDecode(str)
end)
if not ok then
reject(err)
return
else
resolve(decoded) -- May resolve to nil, but this is ok
return
end
end)
end
return JSONUtils
|
--------------------------------------------------------------------------
-- Lmod License
--------------------------------------------------------------------------
--
-- Lmod is licensed under the terms of the MIT license reproduced below.
-- This means that Lmod is free software and can be used for both academic
-- and commercial purposes at absolutely no cost.
--
-- ----------------------------------------------------------------------
--
-- Copyright (C) 2008-2018 Robert McLay
--
-- 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.
--
--------------------------------------------------------------------------
_G._DEBUG = false
local posix = require("posix")
require("strict")
require("getUname")
require("string_utils")
require("fileOps")
require("utils")
require("ProcessModuleTable")
require("pairsByKeys")
_G._DEBUG = false -- Required by the new lua posix
local TargValue = require("TargValue")
local dbg = require("Dbg"):dbg()
local STT = require("STT")
local base64 = require("base64")
local concatTbl = table.concat
local decode64 = base64.decode64
local encode64 = base64.encode64
local getenv = posix.getenv
local load = (_VERSION == "Lua 5.1") and loadstring or load
local systemG = _G
local ModuleTable = "_ModuleTable_"
local M = {}
BuildScenarioTbl = {}
TitleTbl = {}
ModuleTbl = {}
TargetList = {}
NoFamilyList = {}
HostnameTbl = {}
SettargDirTmpl = {}
TargPathLoc = "first"
function M.default_MACH()
return getUname().machName
end
function M.default_OS()
dbg.start{"BuildTarget:default_OS()"}
local name = getUname().osName
dbg.print{"name: ",name,"\n"}
dbg.fini("BuildTarget:default_OS")
return name
end
function M.default_HOST()
local masterTbl = masterTbl()
local hostTbl = masterTbl.HostTbl
local hostName = getUname().hostName
local hostA = {}
for v in hostName:split("%.") do
hostA[#hostA+1] = v
end
local result = hostA[1]
if (#hostA == 1) then
return result
end
local a = {}
for i = 1,#hostTbl do
local entry = tonumber(hostTbl[i])
if (entry <= #hostA) then
a[#a+1] = hostA[entry]
end
end
if (#a > 0) then
result = concatTbl(a,".")
end
return result
end
function M.default_BUILD_SCENARIO(tbl)
dbg.start{"BuildTarget:default_BUILD_SCENARIO()"}
local masterTbl = masterTbl()
local BuildScenarioTbl = masterTbl.BuildScenarioTbl
local stt = STT:stt()
-------------------------------------------------------
-- First look to see if there is TARG_BUILD_SCENARIO_STATE
local v = stt:getBuildScenarioState()
if (v ~= "unknown") then
dbg.print{"STATE: ",v,"\n"}
dbg.fini("BuildTarget:default_BUILD_SCENARIO")
return v
end
-------------------------------------------------------
-- Search over hostname first
local t = getUname()
local hostname = t.hostName
while (true) do
v = BuildScenarioTbl[hostname]
if (v) then
dbg.print{"hostname: ", hostname," v: ",v,"\n"}
dbg.fini("BuildTarget:default_BUILD_SCENARIO")
stt:setBuildScenarioState(v)
return v
end
local i = hostname:find("%.")
if (not i) then break end
hostname = hostname:sub(i+1)
end
-------------------------------------------------------
-- Search over machName
v = BuildScenarioTbl[t.machName] or BuildScenarioTbl[t.machFamilyName] or
BuildScenarioTbl.default
if (v) then
dbg.print{"machName v: ",v,"\n"}
stt:setBuildScenarioState(v)
dbg.fini("BuildTarget:default_BUILD_SCENARIO")
return v
end
v = "empty"
stt:setBuildScenarioState(v)
dbg.print{"default v: ",v,"\n"}
dbg.fini("BuildTarget:default_BUILD_SCENARIO")
return v
end
local function l_string2Tbl(s,tbl)
dbg.start{"l_string2Tbl(\"",s,"\", tbl)"}
local stt = STT:stt()
local stringKindTbl = masterTbl().stringKindTbl
for v in s:split("%s+") do
local kindT = stringKindTbl[v]
if (kindT == nil) then
if (v ~= "") then
stt:add2ExtraT(v)
dbg.print{"Adding \"",v,"\" to TARG_EXTRA\n"}
end
else
for kind in pairs(kindT) do
local K = "TARG_" .. kind:upper()
if (K == "TARG_BUILD_SCENARIO") then
stt:setBuildScenarioState(v)
end
dbg.print{"v: ",v," kind: ",kind," K: ",K,"\n"}
tbl[K] = TargValue:new{value=v}
end
end
end
dbg.fini("l_string2Tbl")
end
function M.buildTbl(targetTbl)
dbg.start{"BuildTarget.buildTbl(targetTbl)"}
local tbl = {}
local stt = STT:stt()
for k in pairsByKeys(targetTbl) do
local K = k:upper()
local key = "TARG_" .. K
local v = getenv(key)
dbg.print{"key: ",key,", v: ",v,"\n"}
if (v == nil) then
local ss = "default_" .. K
if (M[ss]) then
v = M[ss](tbl)
end
dbg.print{"ss: ", ss," v: ",v,"\n"}
end
if (v) then
tbl[key] = TargValue:new{value=v}
end
end
-- Always set mach
tbl.TARG_MACH = TargValue:new{value=M.default_MACH()}
tbl.TARG_MACH_DESCRIPT = TargValue:new{value=getUname().machDescript}
targetTbl.mach = -1
targetTbl.mach_descript = -1
dbg.print{"M.default_MACH(): ",M.default_MACH(),"\n"}
dbg.print{"tbl.TARG_MACH: ",tbl.TARG_MACH:display(),"\n"}
-- Always set os and os_family
local os_name = M.default_OS()
tbl.TARG_OS = TargValue:new{value=os_name}
tbl.TARG_OS_FAMILY = TargValue:new{value=os_name:gsub("-.*","")}
targetTbl.os = -1
targetTbl.os_family = -1
-- Always set host
tbl.TARG_HOST = TargValue:new{value=M.default_HOST()}
targetTbl.host = -1
-- Clear
stt:clearEnv(tbl, targetTbl)
local a = {"build_scenario","mach", "extra",}
for _,v in ipairs(a) do
if (targetTbl[v]) then
targetTbl[v] = -1
end
end
dbg.fini("BuildTarget.buildTbl")
return tbl
end
local function l_readDotFiles()
local masterTbl = masterTbl()
-------------------------------------------------------
-- Load system then user default table.
local settarg_rc = getenv("LMOD_SETTARG_RC")
if (not settarg_rc or not isFile(settarg_rc)) then
settarg_rc = pathJoin(masterTbl.execDir,"settarg_rc.lua")
end
local a = { settarg_rc,
pathJoin(getenv('HOME') or '',".settarg.lua"),
}
local projectConfig = findFileInTree(".settarg.lua")
if (projectConfig ~= a[2]) then
a[#a+1] = projectConfig
end
local SttgConfFnA = {}
local MethodMstrTbl = {}
local TitleMstrTbl = {}
local ModuleMstrTbl = {}
local stringKindTbl = {}
local familyTbl = {}
local HostTbl = {}
local SettargDirTmpl = {}
local TargPathLoc = "first"
for _, fn in ipairs(a) do
repeat
dbg.print{"fn: ",fn,"\n"}
local f = io.open(fn,"r")
if (f) then
SttgConfFnA[#SttgConfFnA+1] = fn
local whole = f:read("*all")
f:close()
if (type(whole) ~= "string") then break end
local ok
local func, msg = load(whole)
if (func) then
ok, msg = pcall(func)
else
ok = false
end
if (not ok) then
io.stderr:write("Error: Unable to load: ",fn,"\n",
" ", msg,"\n");
os.exit(1)
end
TargPathLoc = systemG.TargPathLoc
for k,v in pairs(systemG.SettargDirTemplate) do
SettargDirTmpl[k] = v
end
for k,v in pairs(systemG.BuildScenarioTbl) do
dbg.print{"BS: k: ",k," v: ",v,"\n"}
MethodMstrTbl[k] = v
end
for k,v in pairs(systemG.HostnameTbl) do
HostTbl[k] = v
end
for k,v in pairsByKeys(systemG.TitleTbl) do
dbg.print{"Title: k: ",k," v: ",v,"\n"}
TitleMstrTbl[k] = v
end
for k in pairs(systemG.ModuleTbl) do
ModuleMstrTbl[k] = systemG.ModuleTbl[k]
for _, v in ipairs(ModuleMstrTbl[k]) do
local t = stringKindTbl[v] or {}
t[k] = true
stringKindTbl[v] = t
end
end
for k in pairs(ModuleMstrTbl) do
familyTbl[k] = 1
end
for i = 1, #systemG.NoFamilyList do
local k = systemG.NoFamilyList[i]
familyTbl[k] = nil
end
end
until true
end
masterTbl.TargPathLoc = getenv("LMOD_SETTARG_TARG_PATH_LOCATION") or TargPathLoc
masterTbl.HostTbl = HostTbl
masterTbl.TitleTbl = TitleMstrTbl
masterTbl.BuildScenarioTbl = MethodMstrTbl
masterTbl.stringKindTbl = stringKindTbl
masterTbl.ModuleTbl = ModuleMstrTbl
masterTbl.targetList = systemG.TargetList
masterTbl.familyTbl = familyTbl
masterTbl.SettargDirTmpl = SettargDirTmpl
masterTbl.SttgConfFnA = SttgConfFnA
end
function M.exec(shell)
local shell_name = shell:name() or "unknown"
dbg.start{"BuildTarget.exec(\"",shell_name,")"}
local masterTbl = masterTbl()
local envVarsTbl = {}
local target = masterTbl.target or getenv('TARGET') or ''
local t = getUname()
local stt = STT:stt()
masterTbl.envVarsTbl = envVarsTbl
l_readDotFiles()
local targetList = masterTbl.targetList
local familyTbl = masterTbl.familyTbl
local targetTbl = {}
targetList[#targetList+1] = "extra"
for i,v in ipairs(targetList) do
targetTbl[v] = i
end
local tbl = M.buildTbl(targetTbl)
l_string2Tbl(concatTbl(masterTbl.pargs," ") or '',tbl)
processModuleTable(shell:getMT(), targetTbl, tbl)
tbl.TARG_BUILD_SCENARIO = TargValue:new{value=stt:getBuildScenario()}
--dbg.print{"BUILD_SCENARIO_STATE: ",stt:getBuildScenarioState(),"\n"}
-- Remove options from TARG_EXTRA
if (masterTbl.purgeFlag) then
stt:purgeExtraT()
else
stt:removeFromExtra(masterTbl.remOptions)
end
tbl.TARG_EXTRA = TargValue:new{value=stt:getEXTRA()}
local entryA = {}
local a = {}
for _,v in ipairs(targetList) do
local K = "TARG_" .. v:upper()
local KK = K .. "_FAMILY"
local entry = tbl[K]
if (not entry) then
envVarsTbl[KK] = false
else
entryA[#entryA + 1] = entry
a[#a+1] = entry:display(true) -- The true says change '/' into '-'
if (familyTbl[v]) then
local t = entry:value()
envVarsTbl[KK] = t.sn
end
end
end
for k in pairs(tbl) do
if (tbl[k]) then
envVarsTbl[k] = tbl[k]:display()
end
end
target = concatTbl(a,"_")
target = target:gsub("_+","_")
target = target:gsub("_$","")
envVarsTbl.TARG_SUMMARY = target
local SettargDirTmpl = masterTbl.SettargDirTmpl
local b = {}
for i = 1,#SettargDirTmpl do
local n = SettargDirTmpl[i]
if (n:sub(1,1) ~= "$") then
b[#b+1] = n
else
n = n:sub(2,-1)
if (n == "TARG_SUMMARY") then
b[#b+1] = target
else
b[#b+1] = getenv(n) or ""
end
end
end
envVarsTbl.TARG = concatTbl(b,"")
if (envVarsTbl.TARG:sub(1,1) == "/") then
envVarsTbl.TARG = "." .. envVarsTbl.TARG
end
local TitleTbl = masterTbl.TitleTbl
-- Remove TARG_MACH when it is the same as the host.
local mach = tbl.TARG_MACH:display()
dbg.print{"TARG_MACH:",mach,", uname mach: ",getUname().machName,"\n"}
if (mach == getUname().machName) then
for i = 1,#entryA do
local v = entryA[i]:display()
if (v == mach) then
table.remove(entryA,i)
break
end
end
end
local aa = {}
for i = 1,#entryA do
local t = entryA[i]:value()
local name = t.value or t.sn
local tname = TitleTbl[name]
local s = tname or name
if (s) then
if (tname and t.version and t.version ~= "") then
s = tname .. "/" .. t.version
end
aa[#aa+1] = s
end
end
--local aa = {}
--for _,v in ipairs(a) do
-- local _, _, name, version = v:find("([^-]*)-?(.*)")
-- if (v:len() > 0) then
-- local s = TitleTbl[name] or v
-- if (s) then
-- if (TitleTbl[name] and version ~= "" ) then
-- s = TitleTbl[name] .. "/" .. version
-- end
-- aa[#aa+1] = s
-- end
-- end
--end
local s = concatTbl(aa," "):trim()
local paren_s = ""
if (s ~= "") then
paren_s = "("..s..")"
end
envVarsTbl.TARG_TITLE_BAR = s
envVarsTbl.TARG_TITLE_BAR_PAREN = paren_s
if (masterTbl.destroyFlag) then
for k in pairs(envVarsTbl) do
envVarsTbl[k] = ""
end
-------------------------------------------------------
-- For csh users this variable must have value.
envVarsTbl.TARG_TITLE_BAR_PAREN = " "
end
if (envVarsTbl.TARG_TITLE_BAR_PAREN == "") then
envVarsTbl.TARG_TITLE_BAR_PAREN = " "
end
stt:registerVars(envVarsTbl)
local old_stt = getSTT() or ""
local new_stt = stt:serializeTbl()
if (old_stt ~= new_stt) then
envVarsTbl._SettargTable_ = new_stt
end
dbg.fini("BuildTarget.exec")
end
return M
|
local rankMineBottomView = require(ViewPath.."hall/ranklist/rankMineBottomView");
local ranklist_pin_map = require("qnFiles/qnPlist/hall/ranklist_pin")
local RankMineBottomView = class(CommonGameLayer, false);
local h_index = 0;
local getIndex = function(self)
h_index = h_index + 1;
return h_index;
end
RankMineBottomView.Delegate = {
onMineRankBtnClick = "onMineRankBtnClick",
showRewardMsgDialog = "showRewardMsgDialog",
}
RankMineBottomView.s_controls =
{
mineRankArea = getIndex(),
mineRankLeft = getIndex(),
mineRankName = getIndex(),
mineRankBtn = getIndex(),
mineRankCoins = getIndex(),
mineErrorText = getIndex(),
mineRankText = getIndex(),
headBg = getIndex(),
headView = getIndex(),
vip_corner_mark = getIndex();
};
RankMineBottomView.ctor = function(self)
super(self, rankMineBottomView);
local w, h = self.m_root:getSize();
self:setSize(w, h);
self.m_ctrl = RankMineBottomView.s_controls;
self:__initViews();
self:__initMineHeadImage();
end
RankMineBottomView.__initViews = function (self)
self:findViewById(self.s_controls.vip_corner_mark):setVisible( kUserInfoData:getIsVip());
end
RankMineBottomView.dtor = function (self)
ImageCache.getInstance():cleanRef(self);
end
RankMineBottomView.__initMineHeadImage = function(self)
local sex = kUserInfoData:getSex();
local headImg = kUserInfoData:getHallHeadBySex(sex);
self:__setMyHeadImage(headImg);
self.m_mineHeadImageUrl = kUserInfoData:getAvatar_s() or kUserInfoData:getAvatar_b();
ImageCache.getInstance():request(self.m_mineHeadImageUrl,self, self.onUpdateListHeadImage);
end
RankMineBottomView.__setMyHeadImage = function(self, image)
local headBg = self:findViewById(self.s_controls.headView);
if self.m_headImage then
headBg:removeChild(self.m_headImage);
end
delete(self.m_headImage);
self.m_headImage = new(Mask, image, "hall/common/list_head_mask.png");
headBg:addChild(self.m_headImage);
self.m_headImage:setAlign(kAlignCenter);
self.m_headImage:setLevel(-1);
end
RankMineBottomView.__onUpdateMineImage = function(self, imagePath)
self:__setMyHeadImage(imagePath);
end
RankMineBottomView.__onUpdateListHeadImage = function(self, url, imagePath)
if url == self.m_mineHeadImageUrl then
self:__onUpdateMineImage(imagePath);
end
end
RankMineBottomView.refreshMineRankInfo = function (self, data, rankType, flag)
flag = number.valueOf(flag , -2);
if table.isEmpty(data) then
self:refreshErrorTextAndRankArea(true, false);
return;
end
self:refreshErrorTextAndRankArea(false, true);
local mineLeft = self:findViewById(self.m_ctrl.mineRankLeft);
local mineName = self:findViewById(self.m_ctrl.mineRankName);
local mineBtn = self:findViewById(self.m_ctrl.mineRankBtn);
local mineBtnText = mineBtn:getChildByName("mine_getcoins_text");
local mineCoins = self:findViewById(self.m_ctrl.mineRankCoins);
local mineLeftCrown = mineLeft:getChildByName("mine_left_crown");
local mineLeftView = mineLeft:getChildByName("mine_left_rank_bg");
local mineLeftText = mineLeftView:getChildByName("mine_left_text");
local mineLeftRankNum = mineLeftView:getChildByName("mine_left_rank_num");
local miniRankTextView = self:findViewById(self.m_ctrl.mineRankText);
local nick = kUserInfoData:getNickname() or data["nick"] or "";
self.m_mineHeadImageUrl = kUserInfoData:getAvatar_s() or kUserInfoData:getAvatar_b();
local account =number.valueOf(data["account"]);
local pos = number.valueOf(data["curpos"], -1);
-- 设置头像
mineName:setText(nick, 1);
local x,_ = mineName:getPos();
local w,_ = mineName:getSize();
self:findViewById(self.s_controls.vip_corner_mark):setPos(x + w + 3);
---以下设置左侧排名区域
mineLeftCrown:setVisible(true);
mineLeftView:setVisible(false);
mineLeftText:setVisible(false);
if pos < 1 then
mineLeftCrown:setVisible(false);
mineLeftView:setVisible(true);
mineLeftText:setVisible(true);
mineLeftRankNum:setVisible(false);
elseif pos == 1 then
mineLeftCrown:setFile( ranklist_pin_map["rank_1.png"] );
elseif pos == 2 then
mineLeftCrown:setFile( ranklist_pin_map["rank_2.png"] );
elseif pos == 3 then
mineLeftCrown:setFile( ranklist_pin_map["rank_3.png"] );
else
mineLeftCrown:setVisible(false);
mineLeftView:setVisible(true);
mineLeftText:setVisible(false);
mineLeftRankNum:setVisible(true);
end
mineLeftRankNum:setText(pos);
----设置头像
ImageCache.getInstance():request(self.m_mineHeadImageUrl,self, self.__onUpdateListHeadImage);
----设置右侧信息区域
local rankInfoText = "";
local rankInfoBtnText = "快速提升排名";
local rankInfoByDay = "当前排名";
---以下设置银币和经验数
local coinHead = "昨日";
if flag == RankListConstants.eFlag.Today then
rankInfoByDay = "当前排名";
coinHead = "今日";
elseif flag == RankListConstants.eFlag.LastDay then
rankInfoByDay = "昨日排名";
end
mineBtn:setVisible(false);
local funcData = self;
local func = self.onMineRankBtnClick;
if rankType == RankListConstants.eRankType.Money then
miniRankTextView:setVisible(true);
coinHead = coinHead .. "收益" .. ":";
rankInfoBtnText = "快速提升排名";
if pos < 1 then
rankInfoText = "您未能进榜,加油!"
mineBtn:setVisible(true);
elseif pos >=1 and pos <=3 then
rankInfoText = "恭喜你,".. rankInfoByDay ..":" .. pos;
else
rankInfoText = rankInfoByDay ..":" .. pos;
mineBtn:setVisible(true);
end
elseif rankType == RankListConstants.eRankType.Exp then
miniRankTextView:setVisible(true);
coinHead = coinHead .. "经验" .. ":";
if pos < 1 then
rankInfoText = "您未能进榜,加油!"
elseif pos >=1 and pos <=3 then
rankInfoText = "恭喜你,".. rankInfoByDay ..":" .. pos;
else
rankInfoText = rankInfoByDay ..":" .. pos;
end
elseif rankType == RankListConstants.eRankType.Vip then
miniRankTextView:setVisible(true);
coinHead = coinHead .. ":";
if pos < 0 then
rankInfoText = "您未参加比赛,无排名";
elseif pos == 0 then
rankInfoText = "您未能进榜,加油!";
else
local rewardFlag = number.valueOf(data.reward);
if rewardFlag == 1 then
rankInfoText = string.concat("恭喜你,", rankInfoByDay, ":", pos);
mineBtn:setVisible(true);
else
rankInfoText = string.concat(rankInfoByDay, ":", pos);
end
end
rankInfoBtnText = "填写奖励信息";
funcData.obj = self;
funcData.data = data;
func = self.onVipMyRankBtnClick;
elseif rankType == RankListConstants.eRankType.RedEnvelope then
miniRankTextView:setVisible(true);
coinHead = "发出红包数:";
if pos < 1 then
rankInfoText = "您未能进榜,加油!"
elseif pos >=1 and pos <=3 then
rankInfoText = "恭喜你," .."目前排名:" .. pos;
else
rankInfoText = "目前排名:" .. pos;
end
else
if pos < 1 or pos > 3 then
mineBtn:setVisible(true);
end
miniRankTextView:setVisible(true);
coinHead = coinHead .. ":";
end
mineBtnText:setText(rankInfoBtnText);
miniRankTextView:setText(rankInfoText .. " ");
if account and account>0 then
if rankType == RankListConstants.eRankType.Exp then
mineCoins:setText(coinHead..account);
else
mineCoins:setText(coinHead..ToolKit.skipMoneyEx2(account));
end
else
mineCoins:setText(coinHead.."0");
end
mineBtn:setOnClick(funcData, func);
end
RankMineBottomView.onMineRankBtnClick = function(self)
self:execDelegate(RankMineBottomView.Delegate.onMineRankBtnClick);
end
RankMineBottomView.refreshErrorTextAndRankArea = function (self, errorTextIsShow, rankAreaIsShow)
self:findViewById(self.m_ctrl.mineErrorText):setVisible(errorTextIsShow);
self:findViewById(self.m_ctrl.mineRankArea):setVisible(rankAreaIsShow);
end
RankMineBottomView.onVipMyRankBtnClick = function(funcData)
if funcData then
local self = funcData.obj;
local data = funcData.data;
local tmpData = {};
tmpData.adress = data.addr;
tmpData.phone = data.tel;
tmpData.name = data.name;
self:execDelegate(RankMineBottomView.Delegate.showRewardMsgDialog, tmpData);
end
end
RankMineBottomView.s_controlConfig =
{
[RankMineBottomView.s_controls.mineRankArea] = {"mine_rank", "mine_info_container"},
[RankMineBottomView.s_controls.mineRankLeft] = {"mine_rank", "mine_info_container", "mine_left"},
[RankMineBottomView.s_controls.headView] = {"mine_rank", "mine_info_container", "mine_head"},
[RankMineBottomView.s_controls.headBg] = {"mine_rank", "mine_info_container", "mine_head", "mine_head_bg"},
[RankMineBottomView.s_controls.vip_corner_mark] = {"mine_rank", "mine_info_container","vip_corner_mark"},
[RankMineBottomView.s_controls.mineRankName] = {"mine_rank", "mine_info_container", "mine_name"},
[RankMineBottomView.s_controls.mineRankBtn] = {"mine_rank", "mine_info_container", "mine_getcoin"},
[RankMineBottomView.s_controls.mineRankCoins] = {"mine_rank", "mine_info_container", "mine_coins_num"},
[RankMineBottomView.s_controls.mineRankText] = {"mine_rank", "mine_info_container", "mine_rank_text"},
[RankMineBottomView.s_controls.mineErrorText] = {"mine_rank", "mine_error_text"},
};
RankMineBottomView.s_controlFuncMap =
{
[RankMineBottomView.s_controls.mineRankBtn] = RankMineBottomView.onMineRankBtnClick,
};
return RankMineBottomView;
|
-- Copyright (C) 2013 Piotr Gaertig
-- Naive file storage implementation for each valid chunk status code "201 Created" is returned.
-- Upload module has no contact with a backend. The client uploading the file should call the backend
-- after successfully submitting last chunk of file. Then the backend should look for file named as
-- Session-ID in the upload directory.
local setmetatable = setmetatable
local concat = table.concat
local io = io
local string = string
local error = error
local ngx = ngx
module(...)
-- local mt = { __index = _M }
local function init_file(self, ctx)
local file_path = ctx.file_path
local file
if not ctx.first_chunk then
-- file must exist for follow up chunks
file = io.open(file_path, 'r+') -- Open file for update (reading and writing).
if not file then
-- no file with preceding chunks, report we got nothing so far
return {409, "0-0/0"}
end
local size = file:seek("end")
if size < ctx.range_from then
-- missing chunk? return what we have got so far
file:close()
return {409, string.format("0-%d/%d", size - 1, ctx.range_total) }
end
-- requests may be resend with same chunk
if size ~= ctx.range_from then
file:seek("set", ctx.range_from)
end
else
-- write from scratch
file = io.open(ctx.file_path, "w") -- Truncate to zero length or create file for writing.
end
if not file then
return concat({"Failed to open file ", file_path})
end
self.file = file
end
local function close_file(self)
if self.file then
self.file:close()
end
end
local function on_body_start(self, ctx)
ctx.file_path = concat({self.dir, ctx.id}, "/")
return self:init_file(ctx)
end
local function on_abort(self)
self:close_file()
end
-- writes body data
local function on_body(self, ctx, body)
if self.file then
self.file:write(body)
end
end
local function on_body_end(self, ctx)
close_file(self)
-- return what what we have on server
return {201, string.format("0-%d/%d", ctx.range_to, ctx.range_total) }
end
function _M:new(dir)
return setmetatable({
dir = dir or '/tmp',
file = nil,
-- interface functions
on_body = on_body,
on_body_start = on_body_start,
on_body_end = on_body_end,
-- other functions
init_file = init_file,
close_file = close_file
}, _M)
end
setmetatable(_M, {
__newindex = function (_, n)
error("attempt to write to undeclared variable "..n, 2)
end,
__index = function (_, n)
error("attempt to read undeclared variable "..n, 2)
end,
})
|
-- highlight.lua
hl = require('utils').highlight
-- Make background transparent
hl('Normal', 'NONE', nil, 'NONE', nil, true)
hl('NonText', 'NONE', nil, 'NONE', nil, true)
-- -- -- set color of 80 char width column
hl('ColorColumn', '#303030', nil, '0', nil, true)
-- -- -- change color of cursor line
hl('CursorLine', '#000000', nil, '0', nil, true)
hl('CursorLineNr', '#000000', '#008000', '0', '2', true)
hl('TSString', nil, '#449944', '0', '2', true)
hl('TSVariable', nil, '#bb80bb', '0', '2', true)
-- hl('TSFunction', nil, '#f06030', '0', '2', true)
hl('TSStringRegex', nil, '#aa1111', '0', '2', true)
-- -- Vim Diff colors
hl('DiffAdd', '#000000', '#00c000', '2', '0', true)
hl('DiffChange', '#000000', '#c0c000', '2', '0', true)
hl('DiffDelete', '#000000', '#c00000', '2', '0', true)
hl('DiffDelete', '#ffffff', '#3000a0', '2', '0', true)
|
--This script contains common functions that are used in CRQs:
-- [GENIVI] SDL must retrieve the value of 'menuIcon' and 'menuTitle' parameters from .ini file
--How to use:
--1. local testCasesForMenuIconMenuTitleParameters = require('user_modules/shared_testcases/testCasesForMenuIconMenuTitleParameters')
local commonFunctions = require ('user_modules/shared_testcases/commonFunctions')
local testCasesForMenuIconMenuTitleParameters = {}
--[[@ReadCmdLine: returns output in console as result of specific shell command.
--! @parameters:
--! @cmd - shell command
--! @raw - single raw of command
--]]
function testCasesForMenuIconMenuTitleParameters:ReadCmdLine(cmd,raw)
local f = assert(io.popen(cmd, 'r'))
local s = assert(f:read('*a'))
f:close()
if raw then return s end
s = string.gsub(s, '^%s+', '')
s = string.gsub(s, '%s+$', '')
s = string.gsub(s, '[\n\r]+', ' ')
return s
end
--[[@UpdateINI - update INI file according to specified parameter
--! @parameters:
--! @type_path: absolute, relative, empty
--]]
function testCasesForMenuIconMenuTitleParameters:UpdateINI(type_path)
local icon_to_check = "default_icon.png"
local empty_menuIcon
local absolute_path = self:ReadCmdLine("pwd")
if type_path == nil then type_path = "relative" end
local menuIcon = commonFunctions:read_parameter_from_smart_device_link_ini("menuIcon")
-- By default the value of "menuIcon" must be empty and will be assigned as relative value
if ( (type_path ~= "empty") and (menuIcon == "") ) then
menuIcon = "default_icon.png"
end
if not menuIcon then
empty_menuIcon = true
print ("\27[31m ERROR: menuIcon is not found in smartDeviceLink.ini. \27[0m " )
else
icon_to_check = menuIcon
absolute_path = absolute_path .."/SDL_bin/".. menuIcon
if (type_path == "absolute") then
icon_to_check = absolute_path
commonFunctions:write_parameter_to_smart_device_link_ini("menuIcon", icon_to_check)
elseif (type_path == "empty") then
commonFunctions:write_parameter_to_smart_device_link_ini("menuIcon", "")
end
end
return empty_menuIcon, icon_to_check, absolute_path
end
--[[@CheckINI_menuTitle - read from INI file menuTitle
--! @parameters: NO
--]]
function testCasesForMenuIconMenuTitleParameters:CheckINI_menuTitle()
local result = true
local menuTitle = commonFunctions:read_parameter_from_smart_device_link_ini("menuTitle")
if not menuTitle then
print ("\27[31m ERROR: menuTitle is not found in smartDeviceLink.ini \27[0m " )
result = false
else
if (menuTitle ~= "MENU") then
print ("\27[31m ERROR: menuTitle is not equal to MENU in smartDeviceLink.ini \27[0m " )
result = false
end
end
return result
end
function testCasesForMenuIconMenuTitleParameters:ActivateAppDiffPolicyFlag(self, app_name, device_ID)
local ServerAddress = "127.0.0.1"--commonSteps:get_data_from_SDL_ini("ServerAddress")
local RequestId = self.hmiConnection:SendRequest("SDL.ActivateApp", { appID = self.applications[app_name]})
EXPECT_HMIRESPONSE(RequestId)
:Do(function(_,data)
if(data.result.isSDLAllowed == false) then
local RequestId1 = self.hmiConnection:SendRequest("SDL.GetUserFriendlyMessage", {language = "EN-US", messageCodes = {"DataConsent"}})
--hmi side: expect SDL.GetUserFriendlyMessage message response
EXPECT_HMIRESPONSE( RequestId1, {result = {code = 0, method = "SDL.GetUserFriendlyMessage"}})
:Do(function(_,_)
self.hmiConnection:SendNotification("SDL.OnAllowSDLFunctionality",
{allowed = true, source = "GUI", device = {id = device_ID, name = ServerAddress, isSDLAllowed = true}})
end)
EXPECT_HMICALL("BasicCommunication.ActivateApp")
:Do(function() self.hmiConnection:SendResponse(data.id,"BasicCommunication.ActivateApp", "SUCCESS", {}) end)
end
end)
EXPECT_NOTIFICATION("OnHMIStatus", {hmiLevel = "FULL", systemContext = "MAIN"})
end
return testCasesForMenuIconMenuTitleParameters
|
--region CXXX.lua
--Author : jefflwq
--Date : 2015/2/28
--说明 : CXXX 类
--endregion
using "Joop"
namespace "System"
{
class "CXXX" -- : CBase
{
CXXX =
function(self, ...)
--self.super(...)
--other code
end,
}
}
|
--require("compat-5.1")
System=luanet.System
WebClient=System.Net.WebClient
StreamReader=System.IO.StreamReader
Math=System.Math
print(Math:Pow(2,3))
myWebClient = WebClient()
myStream = myWebClient:OpenRead(arg[1])
sr = StreamReader(myStream)
line=sr:ReadLine()
repeat
print(line)
line=sr:ReadLine()
until not line
myStream:Close()
|
QBCore = nil
TriggerEvent('QBCore:GetObject', function(obj) QBCore = obj end)
QBCore.Functions.CreateUseableItem('bag', function(source, item)
local src = source
local User = QBCore.Functions.GetPlayer(src)
if User.Functions.GetItemByName('bagkey').amount >= 1 then
TriggerClientEvent("wht:cantaac", src)
else
TriggerClientEvent('QBCore:Notify', src, 'There\'s no key to open this bag', 'error)
end
end)
|
include("shared.lua")
local firePar = "fire_large_01"
PrecacheParticleSystem(firePar)
game.AddParticles("particles/fire_01.pcf")
function ENT:Think()
if LocalPlayer():GetPos():DistToSqr(self:GetPos()) > 15000000 then return end
if self.particleCreated then return end
self.particleCreated = true
ParticleEffectAttach(firePar, PATTACH_ABSORIGIN_FOLLOW, self, 1)
end
|
local config = require 'conf'
local BaseGui = require 'src.gui.BaseGui'
local Escape = require 'src.gui.overlays.Escape'
local Death = require 'src.gui.overlays.Death'
local PlayerInventory = require 'src.gui.overlays.PlayerInventory'
local Player = require 'src.Player'
local ClassLookup = require 'src.class.ClassLookup'
local Map = require 'src.Map'
local Camera = require 'src.Camera'
return function(playerData, mapSeed)
local game = BaseGui()
game.player = Player(playerData.spriteData, playerData.nickname, ClassLookup[playerData.class])
game.map = Map(game.player, mapSeed or love.timer.getTime())
game.camera = Camera(game.player)
game.pauseOverlay = nil
game.overlay = nil
game.paused = false
local function updateGame(self)
if KEYS.recentPressed.t then
if self.camera.following then
self.camera:setPos(
self.camera.target.hitbox.x,
self.camera.target.hitbox.y - self.camera.target.sprite.dim.height / 2
)
else
self.camera:setTarget(self.player)
end
end
self.camera.scale = self.camera.scale + self.camera.scale * MOUSE.scroll * config.camera.zoomRate
self.camera.scale =
math.min(config.camera.zoomLimits.max, math.max(config.camera.zoomLimits.min, self.camera.scale))
local cameraBox = self.camera:getViewBox()
local i
for i = 1, 9 do
if KEYS.recentPressed[tostring(i)] then
local mousePos = {}
mousePos.x, mousePos.y = love.mouse.getPosition()
local toPos = {
x = (cameraBox.x - cameraBox.width / 2) + (mousePos.x / love.graphics.getWidth()) * cameraBox.width,
y = (cameraBox.y - cameraBox.height / 2) +
(mousePos.y / love.graphics.getHeight()) * cameraBox.height
}
self.player.class:useAbility(i, {map = self.map, entity = self.player, toPos = toPos})
break
end
end
if KEYS.recentPressed.i then
if self.overlay == nil then
self.overlay = PlayerInventory(self.player.inventory)
else
self.overlay = nil
end
end
self.map:update(cameraBox)
if MOUSE.right.clicked then
local dest = {
x = (cameraBox.x - cameraBox.width / 2) +
(MOUSE.right.pos.x / love.graphics.getWidth()) * cameraBox.width,
y = (cameraBox.y - cameraBox.height / 2) +
(MOUSE.right.pos.y / love.graphics.getHeight()) * cameraBox.height
}
self.player:setDest(dest.x, dest.y)
end
self.player:update()
end
function game:resize(width, height)
if self.overlay ~= nil and self.overlay.resize then
self.overlay:resize(width, height)
end
if self.pauseOverlay ~= nil then
self.pauseOverlay:resize(width, height)
end
end
function game:update()
if not self.player.alive then
if not self.paused then
self.paused = true
self.pauseOverlay = Death()
end
elseif KEYS.recentPressed.escape then
if not self.paused then
self.pauseOverlay = Escape()
else
self.pauseOverlay = nil
end
self.paused = not self.paused
end
if not self.paused then
updateGame(self)
end
if self.overlay ~= nil then
self.overlay:update()
end
if self.pauseOverlay ~= nil then
return self.pauseOverlay:update(
{spriteData = playerData.spriteData, playerNickname = self.player.nickname, class = playerData.class}
)
end
end
function game:draw(dt)
if self.player.alive then
love.graphics.setShader()
else
love.graphics.setShader(SHADERS.blackAndWhite)
end
local cameraBox = self.camera:getViewBox()
dt = not self.paused and dt or 1
self.map:draw(dt, cameraBox)
if self.overlay ~= nil then
self.overlay:draw()
end
if self.pauseOverlay ~= nil then
self.pauseOverlay:draw()
end
end
return game
end
|
--
-- Copyright (c) 2015, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree. An additional grant
-- of patent rights can be found in the PATENTS file in the same directory.
--
-- Author: Marc'Aurelio Ranzato <[email protected]>
-- Sumit Chopra <[email protected]>
-- Michael Auli <[email protected]>
-- Wojciech Zaremba <[email protected]>
--
-- Script to create torch data set from text files of source-target pair
-- sentences. It creates the source and target dictionaries, and the train,
-- valid and test torch files.
require 'math'
require 'sys'
require 'os'
require 'torch'
require 'xlua'
local tok = paths.dofile('tokenizer.lua')
torch.manualSeed(1)
cmd = torch.CmdLine()
cmd.argseparator = '_'
cmd:text()
cmd:text('Make dictionary and datasets')
cmd:text()
cmd:text('Options:')
cmd:option('-srcDir', 'prep', 'path to pre-processed data.')
cmd:option('-dstDir', 'data', 'path to where dictionaries and datasets ' ..
'should be written.')
cmd:option('-shuff', true, 'shuffle sentences in training data or not')
cmd:option('-threshold', 3, 'remove words appearing less than threshold')
cmd:option('-isvalid', true, 'generate the validation set')
cmd:option('-istest', true, 'generate the test set')
cmd:text()
local opt = cmd:parse(arg)
if not paths.dirp(opt.dstDir) then os.execute('mkdir -p ' .. opt.dstDir) end
local config_data = {
root_path = opt.srcDir,
dest_path = opt.dstDir,
threshold = opt.threshold,
targets = {train = 'train.de-en.en',
valid = 'valid.de-en.en',
test = 'test.de-en.en'},
sources = {train = 'train.de-en.de',
valid = 'valid.de-en.de',
test = 'test.de-en.de'},
}
-- build and save the dictionaries
local tdict_path = paths.concat(opt.dstDir, 'dict.target.th7')
local sdict_path = paths.concat(opt.dstDir, 'dict.source.th7')
local target_dict, source_dict
print('-- building target dictionary')
local train_target = paths.concat(opt.srcDir, config_data.targets['train'])
target_dict = tok.build_dictionary(train_target, config_data.threshold)
torch.save(tdict_path, target_dict)
print('-- building source dictionary')
local train_source = paths.concat(opt.srcDir, config_data.sources['train'])
source_dict = tok.build_dictionary(train_source, config_data.threshold)
torch.save(sdict_path, source_dict)
-- now create the binned training data: target sentences corresponding to
-- each length of the source sentence are binned together
local train_targets_path = paths.concat(config_data.dest_path,
'train.targets.th7')
local train_sources_path = paths.concat(config_data.dest_path,
'train.sources.th7')
local valid_targets_path = paths.concat(config_data.dest_path,
'valid.targets.th7')
local valid_sources_path = paths.concat(config_data.dest_path,
'valid.sources.th7')
local test_targets_path = paths.concat(config_data.dest_path,
'test.targets.th7')
local test_sources_path = paths.concat(config_data.dest_path,
'test.sources.th7')
print('tokenizing train...')
local train_targets, train_sources = tok.tokenize(config_data, 'train',
target_dict, source_dict,
opt.shuff)
print('tokenizing valid...')
local valid_targets, valid_sources = tok.tokenize(config_data, 'valid',
target_dict, source_dict,
false)
print('tokenizing test...')
local test_targets, test_sources = tok.tokenize(config_data, 'test',
target_dict, source_dict,
false)
torch.save(train_targets_path, train_targets)
torch.save(train_sources_path, train_sources)
torch.save(valid_targets_path, valid_targets)
torch.save(valid_sources_path, valid_sources)
torch.save(test_targets_path, test_targets)
torch.save(test_sources_path, test_sources)
|
--[[ AscendScripting Script -
This software is provided as free and open source by the
staff of The AscendScripting Team.This script was
written and is protected by the GPL v2. The following
script was released by a AscendScripting Staff Member.
Please give credit where credit is due, if modifying,
redistributing and/or using this software. Thank you.
~~End of License Agreement
-- AscendScripting Staff, March 17, 2009. ]]
function GeomancerFlintdagger_OnSpawn(Unit,Event)
Unit:CastSpell(2601)
end
function GeomancerFlintdagger_OnEnterCombat(Unit,Event)
local X,Y,Z = Unit:GetX(),Unit:GetY(),Unit:GetZ()
local totem = Unit:GetCreatureNearestCoords(X,Y,Z,6111)
local plr = Unit:GetMainTank()
Unit:RegisterEvent("FireNovaTotem", 15000, 1)
Unit:RegisterEvent("Fireball", 3000, 1)
end
function FireNovaTotem(Unit,Event)
if (totem ~= nil) then
return
else
Unit:CastSpell(8499)
end
end
function Fireball(Unit,Event)
Unit:FullCastSpellOnTarget(20823,plr)
end
function GeomancerFlintdagger_OnLeaveCombat(Unit,Event)
Unit:RemoveEvents()
end
function GeomancerFlintdagger_OnDied(Unit,Event)
Unit:RemoveEvents()
end
RegisterUnitEvent(2609,18,"GeomancerFlintdagger_OnSpawn")
RegisterUnitEvent(2609,1,"GeomancerFlintdagger_OnEnterCombat")
RegisterUnitEvent(2609,2,"GeomancerFlintdagger_OnLeaveCombat")
RegisterUnitEvent(2609,4,"GeomancerFlintdagger_OnDied")
|
data:extend({
{
type = "recipe",
name = "bone-bullets",
enabled = false,
energy_required = 5,
ingredients = {{"meat-bones", 10}},
result = "bone-bullets"
},
{
type = "ammo",
name = "bone-bullets",
icon = "__TheyreMadeOutofMeat__/graphics/icons/bone-bullets.png",
icon_size = 32,
ammo_type = {
category = "bullet",
action = {
{
type = "direct",
action_delivery = {
{
type = "instant",
source_effects = {
{
type = "create-explosion",
entity_name = "explosion-gunshot"
}
},
target_effects = {
{
type = "create-entity",
entity_name = "blood-explosion-small" --"explosion-hit"
},
{
type = "damage",
damage = {amount = 7, type = "physical"}
}
}
}
}
}
}
},
magazine_size = 25,
subgroup = "ammo",
order = "a[basic-clips]-a[firearm-magazine-bone]",
stack_size = 200
}
})
|
-- MIT License
-- Copyright (c) 2018 Christian Wahl
-- 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.
-- inspired by the tuple.lua of flowscope but only filtering for tcp streams
local ffi = require "ffi"
local pktLib = require "packet"
local eth = require "proto.ethernet"
local ip4 = require "proto.ip4"
local ip6 = require "proto.ip6"
ffi.cdef [[
struct ipv4_data_tuple {
union ip4_address ip_a; // if it is a uni-directional flow then the first is src and second dst
union ip4_address ip_b;
uint16_t port_a;
uint16_t port_b;
uint8_t proto; // fixed to tcp, however it's included for completeness
uint8_t ip_version;
} __attribute__((__packed__));
struct ipv6_data_tuple {
union ip6_address ip_a; // if it is a uni-directional flow then the first is src and second dst
union ip6_address ip_b;
uint16_t port_a;
uint16_t port_b;
uint8_t proto; // fixed to tcp, however it's included for completeness
uint8_t ip_version;
} __attribute__((__packed__));
]]
local module = {}
module.flowKeys = {
"struct ipv4_data_tuple",
"struct ipv6_data_tuple"
}
module.IPv4_FLOW = 1
module.IPv6_FLOW = 2
local ipv4_tuple = {}
local ipv6_tuple = {}
local ip_string_template = "IP_tuple: {version: %s, protocol: %s, ip_a: %s, port_a: %u, ip_b: %s, port_b: %u}"
local pflang_template_bi = "%s proto \\%s and host %s and port %u and host %s and port %u" -- the first string is either a ip or ip6 (for IPv6)
local pflang_template_uni = "%s proto \\%s src host %s and src port %u and dst host %s and dst port %u" -- the first string is either a ip or ip6 (for IPv6)
-- parameter ip_version: either 4 or 6 determining the used ip_version
local function convert_protocol_number_to_string(ip_version, protocol_number)
local l4_proto = "unknown"
if ip_version == 4 and protocol_number == ip4.PROTO_TCP then
l4_proto = "tcp"
elseif ip_version == 6 and protocol_number == ip6.PROTO_TCP then
l4_proto = "tcp"
end
return l4_proto
end
local function versioned_to_string (ip_version)
local function to_string(packet)
local proto = convert_protocol_number_to_string(ip_version, packet.proto)
return ip_string_template:format(ip_version, proto, packet.ip_a:getString(), packet.port_a,packet.ip_b:getString(), packet.port_b)
end
return to_string
end
function ipv4_tuple:__tostring()
return versioned_to_string(4)(self)
end
function ipv6_tuple:__tostring()
return versioned_to_string(6)(self)
end
local function versioned_get_pflang(ip_version, template)
local l3_proto = "ip6"
if ip_version == 4 then
l3_proto = "ip"
end
local function get_pflang(packet)
local proto = convert_protocol_number_to_string(ip_version, packet.proto)
return template:format(l3_proto, proto, packet.ip_a:getString(), packet.port_a,packet.ip_b:getString(), packet.port_b)
end
return get_pflang
end
function ipv4_tuple:getPflangBi()
return versioned_get_pflang(4, pflang_template_bi)(self)
end
function ipv6_tuple:getPflangBi()
return versioned_get_pflang(6, pflang_template_bi)(self)
end
function ipv4_tuple:getPflangUni()
return versioned_get_pflang(4, pflang_template_uni)(self)
end
function ipv6_tuple:getPflangUni()
return versioned_get_pflang(6, pflang_template_uni)(self)
end
ipv4_tuple.__index = ipv4_tuple
ipv6_tuple.__index = ipv6_tuple
ffi.metatype("struct ipv4_data_tuple", ipv4_tuple)
ffi.metatype("struct ipv6_data_tuple", ipv6_tuple)
-- general functions to extract the 5 tuple
function module.extract5TupleUnidirectional(buf, keyBuf)
local eth_paket = pktLib.getEthernetPacket(buf)
local eth_type = eth_paket.eth:getType()
if eth_type == eth.TYPE_IP then
keyBuf = ffi.cast("struct ipv4_data_tuple&", keyBuf)
local packet = pktLib.getTcp4Packet(buf)
keyBuf.ip_a.uint32 = packet.ip4.src.uint32
keyBuf.ip_b.uint32 = packet.ip4.dst.uint32
keyBuf.port_a = packet.tcp:getSrcPort()
keyBuf.port_b = packet.tcp:getDstPort()
keyBuf.proto = packet.ip4:getProtocol()
keyBuf.ip_version = 4
if keyBuf.proto == ip4.PROTO_TCP then
return true, 1
end
elseif eth_type == eth.TYPE_IP6 then
keyBuf = ffi.cast("struct ipv6_data_tuple&", keyBuf)
local packet = pktLib.getTcp6Packet(buf)
keyBuf.ip_a.uint64[0] = packet.ip6.src.uint64[0]
keyBuf.ip_a.uint64[1] = packet.ip6.src.uint64[1]
keyBuf.ip_b.uint64[0] = packet.ip6.dst.uint64[0]
keyBuf.ip_b.uint64[1] = packet.ip6.dst.uint64[1]
keyBuf.port_a = packet.tcp:getSrcPort()
keyBuf.port_b = packet.tcp:getDstPort()
keyBuf.proto = packet.ip6:getProtocol()
keyBuf.ip_version = 6
if keyBuf.proto == ip6.PROTO_TCP then
return true, 2
end
end
return false
end
function module.extract5TupleBidirectional(buf, keyBuf)
local success, flow_type = module.extract5TupleUnidirectional(buf, keyBuf)
if success and flow_type == module.IPv4_FLOW then
keyBuf = ffi.cast("struct ipv4_data_tuple&", keyBuf)
if keyBuf.ip_a.uint32 < keyBuf.ip_b.uint32 then
keyBuf.ip_a.uint32, keyBuf.ip_b.uint32 = keyBuf.ip_b.uint32, keyBuf.ip_a.uint32
keyBuf.port_a, keyBuf.port_b = keyBuf.port_b, keyBuf.port_a
end
return success, flow_type
elseif success and flow_type == module.IPv6_FLOW then
if keyBuf.ip_a < keyBuf.ip_b then
keyBuf.ip_a, keyBuf.ip_b = keyBuf.ip_b:get(), keyBuf.ip_a:get()
keyBuf.port_a, keyBuf.port_b = keyBuf.port_b, keyBuf.port_a
end
return success, flow_type
end
return false
end
return module
|
local status_ok, reference = pcall(require, "nice-reference")
if not status_ok then
return
end
reference.setup({
anchor = "NW", -- Popup position anchor
relative = "cursor", -- Popup relative position
row = 1, -- Popup x position
col = 0, -- Popup y position
border = "double", -- Popup borderstyle
winblend = 0, -- Popup transaparency 0-100, where 100 is transparent
max_width = 120, -- Max width of the popup
max_height = 10, -- Max height of the popup
auto_choose = false, -- Go to reference if there is only one
})
|
choices = { "Strength", "Dexterity", "Endurance", "Perception", "Intellect", "Wisdom" }
function on_activate(parent, ability)
local cb = ability:create_callback(parent)
cb:set_on_menu_select_fn("menu_select")
local level = parent:ability_level(ability)
local menu = game:create_menu("Select an attribute to steal", cb)
for i = 1, #choices do
menu:add_choice(choices[i])
end
menu:show(parent)
end
function ai_on_activate(parent, ability)
local choice = choices[math.random(#choices)]
local selection = game:create_menu_selection(choice)
menu_select(parent, ability, nil, selection)
end
function menu_select(parent, ability, targets, selection)
parent:set_flag("__steal_attribute_type", selection:value())
local targets = parent:targets():hostile():touchable()
local targeter = parent:create_targeter(ability)
targeter:set_selection_touchable()
targeter:add_all_selectable(targets)
targeter:add_all_effectable(targets)
targeter:activate()
end
function on_target_select(parent, ability, targets)
local target = targets:first()
ability:activate(parent)
game:play_sfx("sfx/curse2")
local attr = parent:get_flag("__steal_attribute_type")
parent:clear_flag("__steal_attribute_type")
if attr == nil then return end
local anim = target:create_color_anim(1.0)
anim:set_color_sec(anim:param(1.0, -1.0),
anim:param(0.0),
anim:param(0.0),
anim:param(0.0))
anim:activate()
local hit = parent:special_attack(target, "Will", "Spell")
local duration = ability:duration()
if hit:is_miss() then
return
elseif hit:is_graze() then
duration = duration - 1
elseif hit:is_hit() then
-- do nothing
elseif hit:is_crit() then
duration = duration + 1
end
local effect = target:create_effect(ability:name(), ability:duration())
effect:set_tag("weaken")
local stats = parent:stats()
local amount = 2 + stats.intellect_bonus / 4 + stats.caster_level / 4
effect:add_attribute_bonus(attr, -amount)
local anim = target:create_particle_generator("arrow_down")
anim:set_moves_with_parent()
anim:set_position(anim:param(-0.5), anim:param(-1.5))
anim:set_particle_size_dist(anim:fixed_dist(1.0), anim:fixed_dist(1.0))
anim:set_gen_rate(anim:param(1.0))
anim:set_initial_gen(1.0)
anim:set_particle_position_dist(anim:dist_param(anim:fixed_dist(0.0)),
anim:dist_param(anim:fixed_dist(0.0), anim:fixed_dist(1.0)))
anim:set_particle_duration_dist(anim:fixed_dist(0.75))
anim:set_color(anim:param(1.0), anim:param(0.0), anim:param(0.0), anim:param(0.8))
effect:add_anim(anim)
effect:apply()
local effect = parent:create_effect(ability:name(), ability:duration())
effect:add_attribute_bonus(attr, amount)
if parent:ability_level(ability) > 1 then
if attr == "Strength" then
effect:add_attribute_bonus("Dexterity", amount / 2)
effect:add_attribute_bonus("Endurance", amount / 2)
elseif attr == "Dexterity" then
effect:add_attribute_bonus("Perception", amount / 2)
effect:add_attribute_bonus("Endurance", amount / 2)
elseif attr == "Endurance" then
effect:add_attribute_bonus("Strength", amount / 2)
effect:add_attribute_bonus("Dexterity", amount / 2)
elseif attr == "Perception" then
effect:add_attribute_bonus("Intellect", amount / 2)
effect:add_attribute_bonus("Dexterity", amount / 2)
elseif attr == "Intellect" then
effect:add_attribute_bonus("Perception", amount / 2)
effect:add_attribute_bonus("Wisdom", amount / 2)
elseif attr == "Wisdom" then
effect:add_attribute_bonus("Perception", amount / 2)
effect:add_attribute_bonus("Intellect", amount / 2)
end
end
local anim = parent:create_particle_generator("arrow_up")
anim:set_moves_with_parent()
anim:set_position(anim:param(-0.5), anim:param(-1.5))
anim:set_particle_size_dist(anim:fixed_dist(1.0), anim:fixed_dist(1.0))
anim:set_gen_rate(anim:param(1.0))
anim:set_initial_gen(1.0)
anim:set_particle_position_dist(anim:dist_param(anim:fixed_dist(0.0)),
anim:dist_param(anim:fixed_dist(0.0), anim:fixed_dist(-1.0)))
anim:set_particle_duration_dist(anim:fixed_dist(0.75))
anim:set_color(anim:param(0.0), anim:param(1.0), anim:param(0.0), anim:param(0.8))
effect:add_anim(anim)
effect:apply()
end
|
local RunService = game:GetService("RunService")
local CollectionService = game:GetService("CollectionService")
local MinkowskiSumInstance = require(script.Parent.MinkowskiSumInstance)
local TerrainModule = require(script.Parent.TerrainCollision)
local module = {}
module.hullRecords = {}
module.dynamicRecords = {}
local SKIN_THICKNESS = 0.05 --closest you can get to a wall
module.planeNum = 0
module.gridSize = 8
module.grid = {}
module.expansionSize = Vector3.new(2, 5, 2)
local debugParts = false
local corners = {
Vector3.new(0.5, 0.5, 0.5),
Vector3.new(0.5, 0.5, -0.5),
Vector3.new(-0.5, 0.5, 0.5),
Vector3.new(-0.5, 0.5, -0.5),
Vector3.new(0.5, -0.5, 0.5),
Vector3.new(0.5, -0.5, -0.5),
Vector3.new(-0.5, -0.5, 0.5),
Vector3.new(-0.5, -0.5, -0.5),
}
function module:FetchCell(x, y, z)
--store in x,z,y order
local gx = self.grid[x]
if gx == nil then
return nil
end
local gz = gx[z]
if gz == nil then
return nil
end
return gz[y]
end
function module:CreateAndFetchCell(x, y, z)
local gx = self.grid[x]
if gx == nil then
gx = {}
self.grid[x] = gx
end
local gz = gx[z]
if gz == nil then
gz = {}
gx[z] = gz
end
local gy = gz[y]
if gy == nil then
gy = {}
gz[y] = gy
end
return gy
end
function module:FindAABB(part)
local orientation = part.CFrame
local size = part.Size
local minx = math.huge
local miny = math.huge
local minz = math.huge
local maxx = -math.huge
local maxy = -math.huge
local maxz = -math.huge
for _, corner in pairs(corners) do
local vec = orientation * (size * corner)
if vec.x < minx then
minx = vec.x
end
if vec.y < miny then
miny = vec.y
end
if vec.z < minz then
minz = vec.z
end
if vec.x > maxx then
maxx = vec.x
end
if vec.y > maxy then
maxy = vec.y
end
if vec.z > maxz then
maxz = vec.z
end
end
return minx, miny, minz, maxx, maxy, maxz
end
function module:FindPointsAABB(points)
local minx = math.huge
local miny = math.huge
local minz = math.huge
local maxx = -math.huge
local maxy = -math.huge
local maxz = -math.huge
for _, vec in pairs(points) do
if vec.x < minx then
minx = vec.x
end
if vec.y < miny then
miny = vec.y
end
if vec.z < minz then
minz = vec.z
end
if vec.x > maxx then
maxx = vec.x
end
if vec.y > maxy then
maxy = vec.y
end
if vec.z > maxz then
maxz = vec.z
end
end
return minx, miny, minz, maxx, maxy, maxz
end
function module:WritePointsToHashMap(hullRecord, points)
local minx, miny, minz, maxx, maxy, maxz = self:FindPointsAABB(points)
for x = math.floor(minx / self.gridSize), math.ceil(maxx / self.gridSize) - 1 do
for z = math.floor(minz / self.gridSize), math.ceil(maxz / self.gridSize) - 1 do
for y = math.floor(miny / self.gridSize), math.ceil(maxy / self.gridSize) - 1 do
local cell = self:CreateAndFetchCell(x, y, z)
cell[hullRecord] = hullRecord
end
end
end
end
function module:WritePartToHashMap(instance, hullRecord)
local minx, miny, minz, maxx, maxy, maxz = self:FindAABB(instance)
for x = math.floor(minx / self.gridSize), math.ceil(maxx / self.gridSize) - 1 do
for z = math.floor(minz / self.gridSize), math.ceil(maxz / self.gridSize) - 1 do
for y = math.floor(miny / self.gridSize), math.ceil(maxy / self.gridSize) - 1 do
local cell = self:CreateAndFetchCell(x, y, z)
cell[instance] = hullRecord
end
end
end
--[[
if (game["Run Service"]:IsClient() and instance:GetAttribute("showdebug")) then
for x = math.floor(minx / self.gridSize), math.ceil(maxx/self.gridSize)-1 do
for z = math.floor(minz / self.gridSize), math.ceil(maxz/self.gridSize)-1 do
for y = math.floor(miny / self.gridSize), math.ceil(maxy/self.gridSize)-1 do
self:SpawnDebugGridBox(x,y,z, Color3.new(math.random(),1,1))
end
end
end
end]]
--
end
function module:RemovePartFromHashMap(instance)
local minx, miny, minz, maxx, maxy, maxz = self:FindAABB(instance)
for x = math.floor(minx / self.gridSize), math.ceil(maxx / self.gridSize) - 1 do
for z = math.floor(minz / self.gridSize), math.ceil(maxz / self.gridSize) - 1 do
for y = math.floor(miny / self.gridSize), math.ceil(maxy / self.gridSize) - 1 do
local cell = self:FetchCell(x, y, z)
if cell then
cell[instance] = nil
end
end
end
end
end
function module:FetchHullsForPoint(point)
local cell = self:FetchCell(
math.floor(point.x / self.gridSize),
math.floor(point.y / self.gridSize),
math.floor(point.z / self.gridSize)
)
local hullRecords = {}
if cell then
for _, hull in pairs(cell :: table) do
hullRecords[hull] = hull
end
end
return hullRecords
end
function module:FetchHullsForBox(min, max)
local minx = min.x
local miny = min.y
local minz = min.z
local maxx = max.x
local maxy = max.y
local maxz = max.z
if minx > maxx then
local t = minx
minx = maxx
maxx = t
end
if miny > maxy then
local t = miny
miny = maxy
maxy = t
end
if minz > maxz then
local t = minz
minz = maxz
maxz = t
end
local hullRecords = {}
--Expanded by 1, so objects right on borders will be in the appropriate query
for x = math.floor(minx / self.gridSize) - 1, math.ceil(maxx / self.gridSize) do
for z = math.floor(minz / self.gridSize) - 1, math.ceil(maxz / self.gridSize) do
for y = math.floor(miny / self.gridSize) - 1, math.ceil(maxy / self.gridSize) do
local cell = self:FetchCell(x, y, z)
if cell then
for _, hull in pairs(cell :: table) do
hullRecords[hull] = hull
end
end
local terrainHull = TerrainModule:FetchCell(x, y, z)
if terrainHull then
for _, hull in pairs(terrainHull) do
hullRecords[hull] = hull
end
end
end
end
end
return hullRecords
end
function module:GenerateConvexHullAccurate(part, expansionSize, cframe)
local debugRoot = nil
if debugParts == true and RunService:IsClient() then
debugRoot = game.Workspace.Terrain
end
local hull, counter = MinkowskiSumInstance:GetPlanesForInstance(
part,
expansionSize,
cframe,
self.planeNum,
debugRoot
)
self.planeNum = counter
return hull
end
local function Trunc(number)
return math.floor(number * 100) / 100
end
function module:GenerateSnappedCFrame(instance)
--Because roblox cannot guarentee perfect replication of part orientation and positions, we'll take what is replicated and truncate it after a certain level of precision
local snappedPosition = Vector3.new(
Trunc(instance.Position.x),
Trunc(instance.Position.y),
Trunc(instance.Position.z)
)
return CFrame.new(snappedPosition)
* CFrame.fromOrientation(
math.rad(Trunc(instance.Orientation.x)),
math.rad(Trunc(instance.Orientation.y)),
math.rad(Trunc(instance.Orientation.z))
)
end
function module:ProcessCollisionOnInstance(instance, playerSize)
if instance:IsA("BasePart") then
if instance.CanCollide == false then
return
end
if CollectionService:HasTag(instance, "Dynamic") then
local record = {}
record.instance = instance
record.hull = self:GenerateConvexHullAccurate(instance, playerSize, instance.CFrame)
record.currentCFrame = instance.CFrame
-- Weird Selene shadowing bug here
-- selene: allow(shadowing)
function record:Update()
if
((record.currentCFrame.Position - instance.CFrame.Position).magnitude < 0.00001)
and (record.currentCFrame.LookVector:Dot(instance.CFrame.LookVector) > 0.999)
then
return
end
record.hull = module:GenerateConvexHullAccurate(instance, playerSize, instance.CFrame)
record.currentCFrame = instance.CFrame
end
table.insert(module.dynamicRecords, record)
return
end
local record = {}
record.instance = instance
record.hull = self:GenerateConvexHullAccurate(instance, playerSize, self:GenerateSnappedCFrame(instance))
self:WritePartToHashMap(record.instance, record)
module.hullRecords[instance] = record
end
end
function module:SpawnDebugGridBox(x, y, z, color)
local instance = Instance.new("Part")
instance.Size = Vector3.new(self.gridSize, self.gridSize, self.gridSize)
instance.Position = (Vector3.new(x, y, z) * self.gridSize)
+ (Vector3.new(self.gridSize, self.gridSize, self.gridSize) * 0.5)
instance.Transparency = 0.75
instance.Color = color
instance.Parent = game.Workspace
instance.Anchored = true
instance.TopSurface = Enum.SurfaceType.Smooth
instance.BottomSurface = Enum.SurfaceType.Smooth
end
function module:SimpleRayTest(a, b, hull)
-- Compute direction vector for the segment
local d = b - a
-- Set initial interval to being the whole segment. For a ray, tlast should be
-- set to +FLT_MAX. For a line, additionally tfirst should be set to –FLT_MAX
local tfirst = -1
local tlast = 1
--Intersect segment against each plane
for _, p in pairs(hull) do
local denom = p.n:Dot(d)
local dist = p.ed - (p.n:Dot(a))
--Test if segment runs parallel to the plane
if denom == 0 then
-- If so, return “no intersection” if segment lies outside plane
if dist > 0 then
return nil
end
else
-- Compute parameterized t value for intersection with current plane
local t = dist / denom
if denom < 0 then
-- When entering halfspace, update tfirst if t is larger
if t > tfirst then
tfirst = t
end
else
-- When exiting halfspace, update tlast if t is smaller
if t < tlast then
tlast = t
end
end
-- Exit with “no intersection” if intersection becomes empty
if tfirst > tlast then
return nil
end
end
end
-- A nonzero logical intersection, so the segment intersects the polyhedron
return tfirst, tlast
end
function module:CheckBrushPoint(data, hullRecord)
local startsOut = false
for _, p in pairs(hullRecord.hull) do
local startDistance = data.startPos:Dot(p.n) - p.ed
if startDistance > 0 then
startsOut = true
break
end
end
if startsOut == false then
data.startSolid = true
data.allSolid = true
return
end
data.hullRecord = hullRecord
end
--Checks a brush, but doesn't handle it well if the start point is inside a brush
function module:CheckBrush(data, hullRecord)
local startFraction = -1.0
local endFraction = 1.0
local startsOut = false
local endsOut = false
local lastPlane = nil
for _, p in pairs(hullRecord.hull) do
local startDistance = data.startPos:Dot(p.n) - p.ed
local endDistance = data.endPos:Dot(p.n) - p.ed
if startDistance > 0 then
startsOut = true
end
if endDistance > 0 then
endsOut = true
end
-- make sure the trace isn't completely on one side of the brush
if startDistance > 0 and (endDistance >= SKIN_THICKNESS or endDistance >= startDistance) then
return --both are in front of the plane, its outside of this brush
end
if startDistance <= 0 and endDistance <= 0 then
--both are behind this plane, it will get clipped by another one
continue
end
if startDistance > endDistance then
-- line is entering into the brush
local fraction = (startDistance - SKIN_THICKNESS) / (startDistance - endDistance)
if fraction < 0 then
fraction = 0
end
if fraction > startFraction then
startFraction = fraction
lastPlane = p
end
else
--line is leaving the brush
local fraction = (startDistance + SKIN_THICKNESS) / (startDistance - endDistance)
if fraction > 1 then
fraction = 1
end
if fraction < endFraction then
endFraction = fraction
end
end
end
if startsOut == false then
data.startSolid = true
if endsOut == false then
--Allsolid
data.allSolid = true
return
end
end
--Update the output fraction
if startFraction < endFraction then
if startFraction > -1 and startFraction < data.fraction then
if startFraction < 0 then
startFraction = 0
end
data.fraction = startFraction
data.normal = lastPlane.n
data.planeD = lastPlane.ed
data.planeNum = lastPlane.planeNum
data.hullRecord = hullRecord
end
end
end
--Checks a brush, but is smart enough to ignore the brush entirely if the start point is inside but the ray is "exiting" or "exited"
function module:CheckBrushNoStuck(data, hullRecord)
local startFraction = -1.0
local endFraction = 1.0
local startsOut = false
local endsOut = false
local lastPlane = nil
local nearestStart = -math.huge
local nearestEnd = -math.huge
for _, p in pairs(hullRecord.hull) do
local startDistance = data.startPos:Dot(p.n) - p.ed
local endDistance = data.endPos:Dot(p.n) - p.ed
if startDistance > 0 then
startsOut = true
end
if endDistance > 0 then
endsOut = true
end
-- make sure the trace isn't completely on one side of the brush
if startDistance > 0 and (endDistance >= SKIN_THICKNESS or endDistance >= startDistance) then
return --both are in front of the plane, its outside of this brush
end
--Record the distance to this plane
nearestStart = math.max(nearestStart, startDistance)
nearestEnd = math.max(nearestEnd, endDistance)
if startDistance <= 0 and endDistance <= 0 then
--both are behind this plane, it will get clipped by another one
continue
end
if startDistance > endDistance then
-- line is entering into the brush
local fraction = (startDistance - SKIN_THICKNESS) / (startDistance - endDistance)
if fraction < 0 then
fraction = 0
end
if fraction > startFraction then
startFraction = fraction
lastPlane = p
end
else
--line is leaving the brush
local fraction = (startDistance + SKIN_THICKNESS) / (startDistance - endDistance)
if fraction > 1 then
fraction = 1
end
if fraction < endFraction then
endFraction = fraction
end
end
end
--Point started inside this brush
if startsOut == false then
data.startSolid = true
--We might be both start-and-end solid
--If thats the case, we want to pretend we never saw this brush if we are moving "out"
--This is either: we exited - or -
-- the end point is nearer any plane than the start point is
if endsOut == false and nearestEnd < nearestStart then
--Allsolid
data.allSolid = true
return
end
--Not stuck! We should pretend we never touched this brush
data.startSolid = false
return --Ignore this brush
end
--Update the output fraction
if startFraction < endFraction then
if startFraction > -1 and startFraction < data.fraction then
if startFraction < 0 then
startFraction = 0
end
data.fraction = startFraction
data.normal = lastPlane.n
data.planeD = lastPlane.ed
data.planeNum = lastPlane.planeNum
data.hullRecord = hullRecord
end
end
end
function module:PlaneLineIntersect(normal, distance, V1, V2)
local diff = V2 - V1
local denominator = normal:Dot(diff)
if denominator == 0 then
return nil
end
local u = (normal.x * V1.x + normal.y * V1.y + normal.z * V1.z + distance) / -denominator
return (V1 + u * (V2 - V1))
end
function module:Sweep(startPos, endPos)
local data = {}
data.startPos = startPos
data.endPos = endPos
data.fraction = 1
data.startSolid = false
data.allSolid = false
data.planeNum = 0
data.planeD = 0
data.normal = Vector3.new(0, 1, 0)
data.checks = 0
data.hullRecord = nil
if (startPos - endPos).magnitude > 1000 then
return data
end
debug.profilebegin("Sweep")
--calc bounds of sweep
local hullRecords = self:FetchHullsForBox(startPos, endPos)
for _, hullRecord in pairs(hullRecords) do
data.checks += 1
self:CheckBrushNoStuck(data, hullRecord)
if data.allSolid == true then
data.fraction = 0
break
end
if data.fraction < SKIN_THICKNESS then
break
end
end
--Collide with dynamic objects
if data.fraction >= SKIN_THICKNESS or data.allSolid == false then
for _, hullRecord in pairs(self.dynamicRecords) do
data.checks += 1
self:CheckBrushNoStuck(data, hullRecord)
if data.allSolid == true then
data.fraction = 0
break
end
if data.fraction < SKIN_THICKNESS then
break
end
end
end
if data.fraction < 1 then
local vec = (endPos - startPos)
data.endPos = startPos + (vec * data.fraction)
end
debug.profileend()
return data
end
function module:BoxTest(pos)
local data = {}
data.startPos = pos
data.endPos = pos
data.fraction = 1
data.startSolid = false
data.allSolid = false
data.planeNum = 0
data.planeD = 0
data.normal = Vector3.new(0, 1, 0)
data.checks = 0
data.hullRecord = nil
debug.profilebegin("PointTest")
--calc bounds of sweep
local hullRecords = self:FetchHullsForPoint(pos)
for _, hullRecord in pairs(hullRecords) do
data.checks += 1
self:CheckBrushPoint(data, hullRecord)
if data.allSolid == true then
data.fraction = 0
break
end
end
debug.profileend()
return data
end
--Call this before you try and simulate
function module:UpdateDynamicParts()
for _, record in pairs(self.dynamicRecords) do
if record.Update then
record:Update()
end
end
end
function module:MakeWorld(folder, playerSize)
self.expansionSize = playerSize
self.hulls = {}
TerrainModule:Setup(self.gridSize, playerSize)
coroutine.wrap(function()
local list = folder:GetDescendants()
local total = #folder:GetDescendants()
local done = 0
for counter = 1, total do
local instance = list[counter]
if (instance:IsA("BasePart") and instance.CanCollide == true) then
self:ProcessCollisionOnInstance(instance, playerSize)
end
done+=1
if (done > 2000) then
task.wait()
done = 0
print("Collision processing: " .. math.floor(counter/total * 100) .. "%")
end
end
print("Collision processing: 100%")
end)()
folder.DescendantAdded:Connect(function(instance)
self:ProcessCollisionOnInstance(instance, playerSize)
end)
folder.DescendantRemoving:Connect(function(instance)
local record = module.hullRecords[instance]
if record then
self:RemovePartFromHashMap(instance)
end
end)
--[[
if (game["Run Service"]:IsClient()) then
for x,row in pairs(self.grid) do
print("X is ",x)
for z,col in pairs(row) do
for y,depth in pairs(col) do
self:SpawnDebugGridBox(x,y,z, Color3.new(0.5,math.random(),0.5))
end
end
end
end
]]
--
end
return module
|
local EVTButtonPosition = 0;
local EVTButtonX = 0;
local EVTButtonY = 0;
EVTButtonPulsing = false;
local EVTButtonLocked = true;
--checks if you have a pending invite, if not, opens calendar frame
function EVTButton_OnClick()
if EVTButtonPulsing then
EVT_ShowNextInvite();
else
EVT_Toggle();
end
end
--makes initial minimap button position
function EVTButton_Init()
EVTButtonLocked = CalendarOptions["buttonLocked"];
if EVTButtonLocked then
EVTButtonPosition = 134.66365694988;
EVTButton_UpdatePosition();
else
EVTButtonX = 1472;
EVTButtonY = 835;
EVTButton_UpdatePosition();
end
EVTButtonFrame:Show();
EVTButtonDay:SetText(tostring(date("%d")));
end
--set button back to inital values (attached to minimap)
function EVTButton_Reset()
CalendarOptions["buttonLocked"] = true;
EVTButton_Init();
end
--releases buttom from control of minimap to be moved anywhere on the screen.
function EVTButton_Unlock()
DEFAULT_CHAT_FRAME:AddMessage("[EVTCalendar] Frames unlocked.", 0.8, 0.8, 0.1);
CalendarOptions["buttonLocked"] = false;
EVTButtonFrame:ClearAllPoints()
EVTButtonLocked = false;
EVTButton_SetCenter();
end
--anchors buttom to current position on screen
function EVTButton_Lock()
DEFAULT_CHAT_FRAME:AddMessage("[EVTCalendar] Frames locked.", 0.8, 0.8, 0.1);
CalendarOptions["buttonLocked"] = true;
EVTButtonLocked = true;
end
--checks if button is locked before allow dragging
function EVTButton_StartMoving()
if EVTButtonLocked == false then
EVTButtonFrame:StartMoving();
end
end
--get new position while button is being moving/dragged, or sets to minimap
function EVTButton_UpdatePosition()
if EVTButtonLocked then
EVTButtonFrame:SetPoint(
"TOPLEFT",
"Minimap",
"TOPLEFT",
54 - (82 * cos(EVTButtonPosition)),
(82 * sin(EVTButtonPosition)) - 55
);
else
EVTButtonFrame:SetPoint(
"TOPLEFT",
"UIParent",
"BOTTOMLEFT",
EVTButtonX,
EVTButtonY);
end
end
--move button to center of the screen
function EVTButton_SetCenter()
EVTButtonFrame:SetPoint(
"CENTER",
"UIParent",
"CENTER",
0,
0);
end
--displays tooltip for clock feature
function EVTButton_OnEnter()
local plus = "";
local srvHour, srvMinute, locHour, locMinute, locOffset, srvOffset, locAmpm, srvAmpm = EVT_GetCurrentTime(); --see function for definitions
if srvOffset > 0 then
plus = "+"
end
if locOffset > 0 then
plus = "+"
end
if not CalendarOptions["milFormat"] then
srvMinute = (srvMinute..srvAmpm);
locMinute = (locMinute..locAmpm);
end
srvTime = string.format("%s:%s Server", srvHour, srvMinute, plus, srvOffset);
locTime = string.format("%s:%s Local", locHour, locMinute, plus, locOffset);
curtime = (locTime .. "\n" .. srvTime);
GameTooltip:SetOwner(this, "ANCHOR_BOTTOMLEFT");
GameTooltip:SetText(curtime);
GameTooltip:Show();
end
--flash button if pending invite
function EVTButton_StartPulse()
PlaySoundFile("Sound\\interface\\iTellMessage.wav");
SetButtonPulse(EVTButton, 100, 1);
EVTButtonPulsing = true;
end
--clear pulse
function EVTButton_PulseOff()
ButtonPulse_StopPulse(EVTButton);
EVTButtonPulsing = false;
end
|
--- Describes a location
-- @classmod Location
local class = require('classes/class')
local prototype = require('prototypes/prototype')
require('prototypes/serializable')
local Location = {}
-- region serializable
function Location:serialize()
return { name = self.name, description = self.description, consecrated = self.consecrated, lighting = self.lighting }
end
function Location.deserialize(serd)
return Location._wrapped_class:new(serd)
end
function Location:context_changed(game_ctx) end
-- endregion
function Location:init()
if type(self.name) ~= 'string' then
error('Locations require names!', 3)
end
if type(self.description) ~= 'string' then
error('Locations require descriptions!', 3)
end
if type(self.consecrated) ~= 'boolean' then
error('Locations require consecrated (boolean)', 3)
end
if type(self.lighting) ~= 'string' then
error('Location requires lighting (string)', 3)
end
if self.lighting ~= 'outside' and self.lighting ~= 'inside_electricity' and self.lighting ~= 'inside_dark' then
error('Location lighting was set to \'' .. self.lighting .. '\' (unrecognized)', 3)
end
end
prototype.support(Location, 'serializable')
return class.create('Location', Location)
|
let storage = {}
let a4 = #storage.name + 1
let a = 123.45 + 2 + #storage.name + tonumber('123') + "aaa" + 1
let b = 123.45 + 2 + #storage.name + tonumber('123') + 1
|
return {
-- Packer can manage itself as an optional plugin
{'wbthomason/packer.nvim', opt = true},
-- Improve performance
{
'lewis6991/impatient.nvim',
config = "require('impatient')",
},
-- Color scheme
-- {
-- 'IMOKURI/challenger-deep-theme-vim',
-- -- config = [[vim.cmd("colorscheme challenger_deep")]],
-- },
{
'Yagua/nebulous.nvim',
config = "require'plugin.rc.nebulous-nvim'.config()",
},
-- {
-- 'rmehri01/onenord.nvim',
-- -- config = [[vim.cmd("colorscheme onenord")]],
-- },
-- Filetype
{
'nathom/filetype.nvim',
config = "require'plugin.rc.filetype-nvim'.config()",
},
-- Filetype: python
{'Vimjas/vim-python-pep8-indent', ft = {'python'}},
-- Filetype: csv
{'mechatroner/rainbow_csv', ft = {'csv'}},
-- Filetype: markdown
{
'dhruvasagar/vim-table-mode',
ft = {'markdown'},
setup = "require'plugin.rc.vim-table-mode'.setup()",
},
-- Filetype: terraform
{
'hashivim/vim-terraform',
ft = {'terraform'},
setup = "require'plugin.rc.vim-terraform'.setup()",
},
-- Filetype: Jenkinsfile
{'martinda/Jenkinsfile-vim-syntax', ft = {'Jenkinsfile'}},
-- Filetype: ansible
{
'pearofducks/ansible-vim',
ft = {'yaml', 'yaml.ansible', 'ansible_hosts', 'jinja2'},
setup = "require'plugin.rc.ansible-vim'.setup()",
},
{
'thiagoalmeidasa/vim-ansible-vault',
ft = {'yaml', 'yaml.ansible', 'ansible_host', 'jinja2'},
cmd = {'AnsibleVaultEncrypt', 'AnsibleVaultDecrypt'}
},
-- Paste image
-- Require xclip
-- {
-- 'ekickx/clipboard-image.nvim',
-- ft = {'markdown'},
-- config = "require'plugin.rc.clipboard-image'.config()",
-- },
-- Capture
{'tyru/capture.vim', cmd = {'Capture'}},
-- Sonic template
{
'mattn/vim-sonictemplate',
setup = "vim.g.sonictemplate_vim_template_dir = {string.format('%s/template', vim.fn.stdpath('config'))}",
},
-- Register
{'tversteeg/registers.nvim'},
-- Cursor line/word
{'yamatsum/nvim-cursorline'},
-- Quick highlight
{
't9md/vim-quickhl',
keys = "<Leader>m",
config = "require'plugin.rc.vim-quickhl'.config()",
},
-- Line number interval
{
'IMOKURI/line-number-interval.nvim',
after = {
"nebulous.nvim",
},
setup = "require'plugin.rc.line-number-interval'.setup()",
},
-- Git sign
{
'lewis6991/gitsigns.nvim',
event = 'BufRead',
requires = {
"nvim-lua/plenary.nvim",
},
config = "require'plugin.rc.gitsigns'.config()",
},
-- Indent Guide
{
'lukas-reineke/indent-blankline.nvim',
event = "BufReadPre",
after = {
"nvim-treesitter",
},
config = "require'plugin.rc.indent-blankline'.config()",
},
-- Suda
{
'lambdalisue/suda.vim',
setup = "vim.g.suda_smart_edit = 1",
},
-- Easy align
{
'junegunn/vim-easy-align',
cmd = {'EasyAlign'},
setup = "require'plugin.rc.easy-align'.setup()",
},
-- Comment
{
'numToStr/Comment.nvim',
config = "require'plugin.rc.comment-nvim'.config()",
},
-- Line diff
{
'AndrewRadev/linediff.vim',
cmd = {'Linediff'},
},
-- Colorizer
{
'norcalli/nvim-colorizer.lua',
cmd = {'ColorizerToggle'},
},
-- Terminal
{
'kassio/neoterm',
cmd = {
'Topen',
'Ttoggle'
},
setup = "require'plugin.rc.neoterm'.setup()",
},
-- REPL
{'IMOKURI/repl.vim'},
-- Search
{
'kevinhwang91/nvim-hlslens',
event = {'BufRead', 'BufNewFile'},
config = "require'plugin.rc.nvim-hlslens'.config()",
},
-- Clever-f
{
'rhysd/clever-f.vim',
event = {'BufRead', 'BufNewFile'},
},
-- Sandwich
{
'machakann/vim-sandwich',
event = {'BufRead', 'BufNewFile'},
},
-- Operator
{
'kana/vim-operator-replace',
requires = {
"kana/vim-operator-user",
},
config = "require'plugin.rc.operator'.config()",
},
-- Text Objects
{
'kana/vim-textobj-line',
requires = {
"kana/vim-textobj-user",
},
},
{
'vimtaku/vim-textobj-keyvalue',
requires = {
"kana/vim-textobj-user",
},
},
-- Treesitter
{
'nvim-treesitter/nvim-treesitter',
event = "BufRead",
run = ":TSUpdate",
config = "require'plugin.rc.nvim-treesitter'.config()",
},
{'nvim-treesitter/nvim-treesitter-refactor', after = "nvim-treesitter"},
{'nvim-treesitter/nvim-treesitter-textobjects', after = "nvim-treesitter"},
{'p00f/nvim-ts-rainbow', after = "nvim-treesitter"},
{'romgrk/nvim-treesitter-context', after = "nvim-treesitter"},
-- Auto completion
{
'hrsh7th/nvim-cmp',
requires = {
"lukas-reineke/cmp-under-comparator",
},
event = {
"BufReadPre",
"CmdlineEnter",
"InsertEnter"
},
config = "require'plugin.rc.nvim-cmp'.config()",
},
{"hrsh7th/cmp-buffer", after = "nvim-cmp"},
{"hrsh7th/cmp-cmdline", after = "nvim-cmp", config="require'plugin.rc.nvim-cmp'.cmdline_config()"},
{"hrsh7th/cmp-emoji", after = "nvim-cmp"},
{"hrsh7th/cmp-nvim-lsp", after = "nvim-cmp"},
{"hrsh7th/cmp-nvim-lsp-document-symbol", after = "nvim-cmp"},
{"hrsh7th/cmp-nvim-lsp-signature-help", after = "nvim-cmp"},
{"hrsh7th/cmp-nvim-lua", after = "nvim-cmp"},
{"hrsh7th/cmp-path", after = "nvim-cmp"},
{"lukas-reineke/cmp-rg", after = "nvim-cmp"},
{"onsails/lspkind-nvim", after = "nvim-cmp"},
{"ray-x/cmp-treesitter", after = "nvim-cmp"},
-- Snippet
{
'hrsh7th/vim-vsnip',
-- event = "InsertEnter",
after = {
"nvim-cmp",
},
setup = "require'plugin.rc.vim-vsnip'.setup()",
config = "require'plugin.rc.vim-vsnip'.config()",
},
{"hrsh7th/cmp-vsnip", after = {"vim-vsnip"}},
-- Auto Pairs
{
'windwp/nvim-autopairs',
-- event = "InsertEnter",
after = {
"nvim-cmp",
},
config = "require'plugin.rc.nvim-autopairs'.config()",
},
-- LSP
{'nvim-lua/lsp-status.nvim'},
{
'neovim/nvim-lspconfig',
-- event = "BufReadPre",
-- requires = {
-- "b0o/schemastore.nvim",
-- },
config = "require'plugin.rc.nvim-lspconfig'.config()",
},
{
'williamboman/nvim-lsp-installer',
after = {
"cmp-nvim-lsp",
"lsp-status.nvim",
"nvim-lspconfig",
},
config = "require'plugin.rc.nvim-lsp-installer'.config()",
},
-- Status line
{
'nvim-lualine/lualine.nvim',
requires = {
"kyazdani42/nvim-web-devicons",
},
config = "require'plugin.rc.lualine'.config()",
},
-- Session
{
'rmagatti/auto-session',
cmd = {'SaveSession', 'RestoreSession', 'DeleteSession'},
config = "require'plugin.rc.auto-session'.config()",
},
-- Fuzzy finder
{
'nvim-telescope/telescope.nvim',
event = 'BufWinEnter',
requires = {
"kyazdani42/nvim-web-devicons",
"nvim-lua/plenary.nvim",
"nvim-lua/popup.nvim",
"nvim-telescope/telescope-symbols.nvim",
},
config = "require'plugin.rc.telescope-nvim'.config()",
},
{
'nvim-telescope/telescope-frecency.nvim',
requires = {
"tami5/sql.nvim",
},
after = {
"telescope.nvim",
-- "sql.nvim",
},
config = "require'plugin.rc.telescope-nvim'.frecency()",
},
-- {
-- 'nvim-telescope/telescope-fzf-writer.nvim',
-- after = "telescope.nvim",
-- config = "require'plugin.rc.telescope-nvim'.fzf_writer()",
-- },
{
'nvim-telescope/telescope-fzy-native.nvim',
after = "telescope.nvim",
config = "require'plugin.rc.telescope-nvim'.fzy_native()",
},
{
'tamago324/telescope-sonictemplate.nvim',
after = {
"telescope.nvim",
"vim-sonictemplate",
},
config = "require'plugin.rc.telescope-nvim'.sonictemplate()",
},
}
|
---
-- FDMM Command Center Module.
-- @module FDMM_CommandCenter
env.info("---FDMM_CommandCenter Start---")
require('Territory/FDMM_Facility')
--- FDMM command center module.
fdmm.commandCenter = {}
do -- FDMMCommandCenter
--- Command center class that manages an command center facility in a territory, which acts as faction command post.
-- @type FDMMCommandCenter
-- @extends FDMMFacility
FDMMCommandCenter = {}
FDMMCommandCenter.__index = FDMMCommandCenter
setmetatable(FDMMCommandCenter, {
__index = FDMMFacility,
__call = function (cls, ...)
return cls.new(...)
end
})
--- Command center constructor.
-- @param #string name Command center name.
-- @param DCS#Vec2 centerPoint Center point of command center.
-- @param #string territoryName Territory name this command center belongs to.
-- @return #FDMMCommandCenter New instance of #FDMMCommandCenter.
function FDMMCommandCenter.new(name, centerPoint, territoryName)
local self = setmetatable(FDMMFacility.new(name, centerPoint, territoryName), FDMMCommandCenter)
-- TODO: me.
return self
end
function FDMMCommandCenter:serialize(encoder)
-- TODO: me.
end
function FDMMCommandCenter:deserialize(decoder)
-- TOD: me.
end
--- Builds command center from initial placement of map elements nearby according to setup parameters.
function FDMMCommandCenter:buildFacility()
-- TODO: me.
end
--- Gets facility type of command center.
-- @return #Enums.FacilityType Command center facility type.
function FDMMCommandCenter:getFacilityType()
return fdmm.enums.FacilityType.CommandCenter
end
end -- /FDMMCommandCenter
env.info("---FDMM_CommandCenter End---")
|
--[[
TheNexusAvenger
Project for fetching resources in ReplicatedStorage.
--]]
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local NexusProject = require(ReplicatedStorage:WaitForChild("External"):WaitForChild("NexusProject"))
--Create the project.
local Project = NexusProject.new(ReplicatedStorage)
--Load the round types.
for _,RoundData in pairs(Project:GetResource("Data.GameTypes")) do
Project:GetResource(RoundData.RoundClass)
end
--Initialize Nexus Replication's global container.
local NexusReplication = Project:GetResource("External.NexusReplication")
require(ReplicatedStorage:WaitForChild("State"):WaitForChild("TeamSelection"))
NexusReplication:GetGlobalContainer()
--[[
Clears the project after testing.
--]]
function Project:Clear()
NexusReplication:ClearInstances()
end
--Return the project.
return Project
|
-- Return if there's nothing to add on to
if ( !util ) then return end
if ( CLIENT ) then
include( "util/worldpicker.lua" )
end
--[[---------------------------------------------------------
Name: IsValidPhysicsObject
Params: <ent> <num>
Desc: Returns true if physics object is valid, false if not
-----------------------------------------------------------]]
function util.IsValidPhysicsObject( ent, num )
-- Make sure the entity is valid
if ( !ent || ( !ent:IsValid() && !ent:IsWorld() ) ) then return false end
-- This is to stop attaching to walking NPCs.
-- Although this is possible and `works', it can severly reduce the
-- performance of the server.. Plus they don't pay attention to constraints
-- anyway - so we're not really losing anything.
local MoveType = ent:GetMoveType()
if ( !ent:IsWorld() && MoveType != MOVETYPE_VPHYSICS && !( ent:GetModel() && ent:GetModel():StartWith( "*" ) ) ) then return false end
local Phys = ent:GetPhysicsObjectNum( num )
return IsValid( Phys )
end
--[[---------------------------------------------------------
Name: GetPlayerTrace( ply, dir )
Desc: Returns a generic trace table for the player
(dir is optional, defaults to the player's aim)
-----------------------------------------------------------]]
function util.GetPlayerTrace( ply, dir )
dir = dir or ply:GetAimVector()
local trace = {}
trace.start = ply:EyePos()
trace.endpos = trace.start + ( dir * ( 4096 * 8 ) )
trace.filter = ply
return trace
end
--[[---------------------------------------------------------
Name: QuickTrace( origin, offset, filter )
Desc: Quick trace
-----------------------------------------------------------]]
function util.QuickTrace( origin, dir, filter )
local trace = {}
trace.start = origin
trace.endpos = origin + dir
trace.filter = filter
return util.TraceLine( trace )
end
--[[---------------------------------------------------------
Name: tobool( in )
Desc: Turn variable into bool
-----------------------------------------------------------]]
util.tobool = tobool
--[[---------------------------------------------------------
Name: LocalToWorld( ent, lpos, bone )
Desc: Convert the local position on an entity to world pos
-----------------------------------------------------------]]
function util.LocalToWorld( ent, lpos, bone )
bone = bone or 0
if ( ent:EntIndex() == 0 ) then
return lpos
else
if ( IsValid( ent:GetPhysicsObjectNum( bone ) ) ) then
return ent:GetPhysicsObjectNum( bone ):LocalToWorld( lpos )
else
return ent:LocalToWorld( lpos )
end
end
return nil
end
--[[---------------------------------------------------------
Returns year, month, day and hour, minute, second in a formatted string.
-----------------------------------------------------------]]
function util.DateStamp()
local t = os.date( '*t' )
return t.year .. "-" .. t.month .. "-" .. t.day .. " " .. Format( "%02i-%02i-%02i", t.hour, t.min, t.sec )
end
--[[---------------------------------------------------------
Convert a string to a certain type
-----------------------------------------------------------]]
function util.StringToType( str, typename )
typename = typename:lower()
if ( typename == "vector" ) then return Vector( str ) end
if ( typename == "angle" ) then return Angle( str ) end
if ( typename == "float" ) then return tonumber( str ) end
if ( typename == "int" ) then return math.Round( tonumber( str ) ) end
if ( typename == "bool" ) then return tobool( str ) end
if ( typename == "string" ) then return tostring( str ) end
if ( typename == "entity" ) then return Entity( str ) end
MsgN( "util.StringToType: unknown type \"", typename, "\"!" )
end
--
-- Convert a type to a (nice, but still parsable) string
--
function util.TypeToString( v )
local iD = TypeID( v )
if ( iD == TYPE_VECTOR or iD == TYPE_ANGLE ) then
return string.format( "%.2f %.2f %.2f", v:Unpack() )
end
if ( iD == TYPE_NUMBER ) then
return util.NiceFloat( v )
end
return tostring( v )
end
--
-- Formats a float by stripping off extra 0's and .'s
--
-- 0.00 -> 0
-- 0.10 -> 0.1
-- 1.00 -> 1
-- 1.49 -> 1.49
-- 5.90 -> 5.9
--
function util.NiceFloat( f )
local str = string.format( "%f", f )
str = str:TrimRight( "0" )
str = str:TrimRight( "." )
return str
end
--
-- Timer
--
--
local T =
{
--
-- Resets the timer to nothing
--
Reset = function( self )
self.endtime = nil
end,
--
-- Starts the timer, call with end time
--
Start = function( self, time )
self.endtime = CurTime() + time
end,
--
-- Returns true if the timer has been started
--
Started = function( self )
return self.endtime != nil
end,
--
-- Returns true if the time has elapsed
--
Elapsed = function( self )
return self.endtime == nil || self.endtime <= CurTime()
end
}
T.__index = T
--
-- Create a new timer object
--
function util.Timer( startdelay )
startdelay = startdelay or 0
local t = {}
setmetatable( t, T )
t.endtime = CurTime() + startdelay
return t
end
local function PopStack( self, num )
if ( num == nil ) then
num = 1
elseif ( num < 0 ) then
error( string.format( "attempted to pop %d elements in stack, expected >= 0", num ), 3 )
else
num = math.floor( num )
end
local len = self[ 0 ]
if ( num > len ) then
error( string.format( "attempted to pop %u element%s in stack of length %u", num, num == 1 && "" || "s", len ), 3 )
end
return num, len
end
local STACK =
{
Push = function( self, obj )
local len = self[ 0 ] + 1
self[ len ] = obj
self[ 0 ] = len
end,
Pop = function( self, num )
local len
num, len = PopStack( self, num )
if ( num == 0 ) then
return nil
end
local newlen = len - num
self[ 0 ] = newlen
newlen = newlen + 1
local ret = self[ newlen ]
-- Pop up to the last element
for i = len, newlen, -1 do
self[ i ] = nil
end
return ret
end,
PopMulti = function( self, num )
local len
num, len = PopStack( self, num )
if ( num == 0 ) then
return {}
end
local newlen = len - num
self[ 0 ] = newlen
local ret = {}
local retpos = 0
-- Pop each element and add it to the table
-- Iterate in reverse since the stack is internally stored
-- with 1 being the bottom element and len being the top
-- But the return will have 1 as the top element
for i = len, newlen + 1, -1 do
retpos = retpos + 1
ret[ retpos ] = self[ i ]
self[ i ] = nil
end
return ret
end,
Top = function( self )
local len = self[ 0 ]
if ( len == 0 ) then
return nil
end
return self[ len ]
end,
Size = function( self )
return self[ 0 ]
end
}
STACK.__index = STACK
function util.Stack()
return setmetatable( { [ 0 ] = 0 }, STACK )
end
-- Helper for the following functions. This is not ideal but we cannot change this because it will break existing addons.
local function GetUniqueID( sid )
return util.CRC( "gm_" .. sid .. "_gm" )
end
--[[---------------------------------------------------------
Name: GetPData( steamid, name, default )
Desc: Gets the persistant data from a player by steamid
-----------------------------------------------------------]]
function util.GetPData( steamid, name, default )
name = Format( "%s[%s]", GetUniqueID( steamid ), name )
local val = sql.QueryValue( "SELECT value FROM playerpdata WHERE infoid = " .. SQLStr( name ) .. " LIMIT 1" )
if ( val == nil ) then return default end
return val
end
--[[---------------------------------------------------------
Name: SetPData( steamid, name, value )
Desc: Sets the persistant data of a player by steamid
-----------------------------------------------------------]]
function util.SetPData( steamid, name, value )
name = Format( "%s[%s]", GetUniqueID( steamid ), name )
sql.Query( "REPLACE INTO playerpdata ( infoid, value ) VALUES ( " .. SQLStr( name ) .. ", " .. SQLStr( value ) .. " )" )
end
--[[---------------------------------------------------------
Name: RemovePData( steamid, name )
Desc: Removes the persistant data from a player by steamid
-----------------------------------------------------------]]
function util.RemovePData( steamid, name )
name = Format( "%s[%s]", GetUniqueID( steamid ), name )
sql.Query( "DELETE FROM playerpdata WHERE infoid = " .. SQLStr( name ) )
end
|
slot0 = class("BackyardEffectMgr")
slot0.Ctor = function (slot0, slot1)
slot0.effectContains = slot1
slot0.effects = {}
slot0.counts = {}
end
slot0.applyEffect = function (slot0, slot1)
if slot0.effects[slot1] then
slot0.counts[slot1] = (slot0.counts[slot1] or 0) + 1
return
end
PoolMgr.GetInstance():GetPrefab("ui/" .. slot1, slot1, true, function (slot0)
if not slot0.effects or slot0.effects[] then
PoolMgr.GetInstance():ReturnPrefab("ui/" .. slot1, PoolMgr.GetInstance().ReturnPrefab, slot0)
return
end
slot0.name = slot1
setParent(slot0, slot0.effectContains)
setActive(slot0, true)
slot0.effects[] = slot0
slot1[slot0.counts] = (slot0.counts[slot0.counts] or 0) + 1
end)
end
slot0.disableEffect = function (slot0, slot1)
if not slot0.effects[slot1] then
return
end
slot0.counts[slot1] = (slot0.counts[slot1] or 0) - 1
if slot0.counts[slot1] <= 0 and findTF(slot0.effectContains, slot1) then
PoolMgr.GetInstance():ReturnPrefab("ui/" .. slot1, slot1, slot2.gameObject)
slot0.effects[slot1] = nil
end
end
slot0.ShowOrHide = function (slot0, slot1)
setActive(slot0.effectContains, slot1)
end
slot0.Destroy = function (slot0)
for slot4, slot5 in pairs(slot0.effects) do
PoolMgr.GetInstance():ReturnPrefab("ui/" .. slot4, slot4, slot5)
end
slot0.effects = nil
slot0.counts = nil
end
return slot0
|
local AST = require("lunar.ast")
local SyntaxKind = require("lunar.ast.syntax_kind")
local BaseTranspiler = require("lunar.compiler.codegen.base_transpiler")
local Transpiler = setmetatable({}, {
__index = BaseTranspiler,
})
Transpiler.__index = setmetatable({}, BaseTranspiler)
function Transpiler.new(ast)
return Transpiler.constructor(setmetatable({}, Transpiler), ast)
end
function Transpiler.constructor(self, ast)
BaseTranspiler.constructor(self)
self.footer_exports = nil
self.visitors = {
[SyntaxKind.do_statement] = self.visit_do_statement,
[SyntaxKind.if_statement] = self.visit_if_statement,
[SyntaxKind.class_statement] = self.visit_class_statement,
[SyntaxKind.while_statement] = self.visit_while_statement,
[SyntaxKind.break_statement] = self.visit_break_statement,
[SyntaxKind.return_statement] = self.visit_return_statement,
[SyntaxKind.function_statement] = self.visit_function_statement,
[SyntaxKind.variable_statement] = self.visit_variable_statement,
[SyntaxKind.range_for_statement] = self.visit_range_for_statement,
[SyntaxKind.expression_statement] = self.visit_expression_statement,
[SyntaxKind.assignment_statement] = self.visit_assignment_statement,
[SyntaxKind.generic_for_statement] = self.visit_generic_for_statement,
[SyntaxKind.repeat_until_statement] = self.visit_repeat_until_statement,
[SyntaxKind.declare_global_statement] = self.visit_declare_global_statement,
[SyntaxKind.declare_package_statement] = self.visit_declare_package_statement,
[SyntaxKind.declare_returns_statement] = self.visit_declare_returns_statement,
[SyntaxKind.import_statement] = self.visit_import_statement,
[SyntaxKind.export_statement] = self.visit_export_statement,
[SyntaxKind.prefix_expression] = self.visit_prefix_expression,
[SyntaxKind.lambda_expression] = self.visit_lambda_expression,
[SyntaxKind.member_expression] = self.visit_member_expression,
[SyntaxKind.argument_expression] = self.visit_argument_expression,
[SyntaxKind.function_expression] = self.visit_function_expression,
[SyntaxKind.unary_op_expression] = self.visit_unary_op_expression,
[SyntaxKind.binary_op_expression] = self.visit_binary_op_expression,
[SyntaxKind.nil_literal_expression] = self.visit_nil_literal_expression,
[SyntaxKind.function_call_expression] = self.visit_function_call_expression,
[SyntaxKind.table_literal_expression] = self.visit_table_literal_expression,
[SyntaxKind.number_literal_expression] = self.visit_number_literal_expression,
[SyntaxKind.string_literal_expression] = self.visit_string_literal_expression,
[SyntaxKind.boolean_literal_expression] = self.visit_boolean_literal_expression,
[SyntaxKind.variable_argument_expression] = self.visit_variable_argument_expression,
[SyntaxKind.identifier] = self.visit_identifier,
[SyntaxKind.index_expression] = self.visit_index_expression,
[SyntaxKind.type_assertion_expression] = self.visit_type_assertion_expression,
[SyntaxKind.index_field_declaration] = self.visit_index_field_declaration,
[SyntaxKind.member_field_declaration] = self.visit_member_field_declaration,
[SyntaxKind.sequential_field_declaration] = self.visit_sequential_field_declaration,
[SyntaxKind.parameter_declaration] = self.visit_parameter_declaration,
}
self.binary_op_map = {
[AST.BinaryOpKind.addition_op] = "+",
[AST.BinaryOpKind.subtraction_op] = "-",
[AST.BinaryOpKind.multiplication_op] = "*",
[AST.BinaryOpKind.division_op] = "/",
[AST.BinaryOpKind.modulus_op] = "%",
[AST.BinaryOpKind.power_op] = "^",
[AST.BinaryOpKind.concatenation_op] = "..",
[AST.BinaryOpKind.not_equal_op] = "~=",
[AST.BinaryOpKind.equal_op] = "==",
[AST.BinaryOpKind.less_than_op] = "<",
[AST.BinaryOpKind.less_or_equal_op] = "<=",
[AST.BinaryOpKind.greater_than_op] = ">",
[AST.BinaryOpKind.greater_or_equal_op] = ">=",
[AST.BinaryOpKind.and_op] = "and",
[AST.BinaryOpKind.or_op] = "or",
}
self.unary_op_map = {
[AST.UnaryOpKind.negative_op] = "-",
[AST.UnaryOpKind.not_op] = "not ",
[AST.UnaryOpKind.length_op] = "#",
}
self.ast = ast
return self
end
function Transpiler.__index:transpile()
self:visit_block(self.ast)
self:visit_footer_exports()
return self.source
end
function Transpiler.__index:visit_node(node)
local visitor = self.visitors[node.syntax_kind]
if visitor then
return visitor(self, node)
end
error(("No visitor found for SyntaxKind %d"):format(node.syntax_kind))
end
function Transpiler.__index:visit_block(block)
for _, stat in pairs(block) do
self:visit_node(stat)
end
end
function Transpiler.__index:visit_varlist(varlist)
for i, var in pairs(varlist) do
self:visit_node(var)
if i ~= (#varlist) then
self:write(", ")
end
end
end
function Transpiler.__index:visit_identlist(identlist)
for i = 1, (#identlist) do
if i > 1 then
self:write(", ")
end
self:write(identlist[i].name)
end
end
function Transpiler.__index:visit_fields(fields)
if (#fields) == 0 then
return ""
end
self:indent()
for _, field in pairs(fields) do
self:writeln()
self:iwrite()
self:visit_field_declaration(field)
self:write(",")
end
self:dedent()
end
function Transpiler.__index:visit_params(params)
for i, param in pairs(params) do
self:visit_node(param)
if i ~= (#params) then
self:write(", ")
end
end
end
function Transpiler.__index:visit_args(args)
for i, expr in pairs(args) do
self:visit_node(expr)
if i ~= (#args) then
self:write(", ")
end
end
end
function Transpiler.__index:visit_exprlist(exprlist)
for i, expr in pairs(exprlist) do
self:visit_node(expr)
if i ~= (#exprlist) then
self:write(", ")
end
end
end
function Transpiler.__index:visit_do_statement(stat)
self:iwriteln("do")
self:indent()
self:visit_block(stat.block)
self:dedent()
self:iwriteln("end")
end
function Transpiler.__index:visit_if_statement(stat)
self:iwrite("if ")
self:visit_node(stat.expr)
self:writeln(" then")
self:indent()
self:visit_block(stat.block)
self:dedent()
for _, elseif_branch in pairs(stat.elseif_branches) do
self:iwrite("elseif ")
self:visit_node(elseif_branch.expr)
self:writeln(" then")
self:indent()
self:visit_block(elseif_branch.block)
self:dedent()
end
if stat.else_branch then
self:iwriteln("else")
self:indent()
self:visit_block(stat.else_branch.block)
self:dedent()
end
self:iwriteln("end")
end
function Transpiler.__index:visit_class_statement(stat)
self:visit_block(stat:lower())
end
function Transpiler.__index:visit_while_statement(stat)
self:iwrite("while ")
self:visit_node(stat.expr)
self:writeln(" do")
self:indent()
self:visit_block(stat.block)
self:dedent()
self:iwriteln("end")
end
function Transpiler.__index:visit_break_statement(stat)
self:iwriteln("break")
end
function Transpiler.__index:visit_return_statement(stat)
self:iwrite("return")
if stat.exprlist then
self:write(" ")
self:visit_exprlist(stat.exprlist)
end
self:write("\n")
end
function Transpiler.__index:visit_function_statement(stat)
if stat.is_local then
self:iwrite("local ")
end
self:write("function ")
self:visit_node(stat.base)
self:write("(")
self:visit_params(stat.parameters)
self:writeln(")")
self:indent()
self:visit_block(stat.block)
self:dedent()
self:iwriteln("end")
end
function Transpiler.__index:visit_variable_statement(stat)
self:iwrite("local ")
self:visit_identlist(stat.identlist)
if stat.exprlist then
self:write(" = ")
self:visit_exprlist(stat.exprlist)
end
self:writeln()
end
function Transpiler.__index:visit_identifier(node)
self:write(node.name)
end
function Transpiler.__index:visit_range_for_statement(stat)
self:iwrite("for ")
self:visit_identifier(stat.identifier)
self:write(" = ")
self:visit_node(stat.start_expr)
self:write(", ")
self:visit_node(stat.end_expr)
if stat.incremental_expr then
self:write(", ")
self:visit_node(stat.incremental_expr)
end
self:writeln(" do")
self:indent()
self:visit_block(stat.block)
self:dedent()
self:iwriteln("end")
end
function Transpiler.__index:visit_expression_statement(stat)
self:iwrite()
self:visit_node(stat.expr)
self:writeln()
end
function Transpiler.__index:visit_assignment_statement(stat)
local lowered = stat:lower()
self:iwrite()
self:visit_varlist(lowered.variables)
self:write(" = ")
self:visit_exprlist(lowered.exprs)
self:writeln()
end
function Transpiler.__index:visit_generic_for_statement(stat)
self:iwrite("for ")
self:visit_identlist(stat.identifiers)
self:write(" in ")
self:visit_exprlist(stat.exprlist)
self:writeln(" do")
self:indent()
self:visit_block(stat.block)
self:dedent()
self:iwriteln("end")
end
function Transpiler.__index:visit_repeat_until_statement(stat)
self:iwriteln("repeat")
self:indent()
self:visit_block(stat.block)
self:dedent()
self:iwrite("until ")
self:visit_node(stat.expr)
self:writeln()
end
function Transpiler.__index:visit_declare_global_statement(stat)
end
function Transpiler.__index:visit_declare_package_statement(stat)
end
function Transpiler.__index:visit_declare_returns_statement(stat)
end
function Transpiler.__index:visit_import_statement(stat)
self:visit_block(stat:lower())
end
function Transpiler.__index:visit_export_statement(stat)
local assignment, identifier = stat:lower()
if (not self.footer_exports) then
self.footer_exports = {}
end
table.insert(self.footer_exports, identifier)
self:visit_node(assignment)
end
function Transpiler.__index:visit_footer_exports(stat)
if self.footer_exports then
self:iwriteln("return {")
self:indent()
for i = 1, (#self.footer_exports) do
self:iwrite()
self:visit_identifier(self.footer_exports[i])
self:writeln(",")
end
self:dedent()
self:iwriteln("}")
end
end
function Transpiler.__index:visit_prefix_expression(expr)
self:write("(")
self:visit_node(expr.expr)
self:write(")")
end
function Transpiler.__index:visit_lambda_expression(expr)
self:visit_function_expression(expr:lower())
end
function Transpiler.__index:visit_member_expression(member)
self:visit_node(member.base)
self:write(member.has_colon and ":" or ".")
self:write(member.member_identifier.name)
end
function Transpiler.__index:visit_index_expression(expr)
self:visit_node(expr.base)
self:write("[")
self:visit_node(expr.index)
self:write("]")
end
function Transpiler.__index:visit_argument_expression(arg)
self:visit_node(arg.value)
end
function Transpiler.__index:visit_function_expression(expr)
self:write("function(")
self:visit_params(expr.parameters)
self:writeln(")")
self:indent()
self:visit_block(expr.block)
self:dedent()
self:iwrite("end")
end
function Transpiler.__index:visit_nil_literal_expression(expr)
self:write("nil")
end
function Transpiler.__index:visit_function_call_expression(expr)
self:visit_node(expr.base)
self:write("(")
self:visit_args(expr.arguments)
self:write(")")
end
function Transpiler.__index:visit_unary_op_expression(expr)
self:write("(")
self:write(self.unary_op_map[expr.operator])
self:visit_node(expr.right_operand)
self:write(")")
end
function Transpiler.__index:visit_binary_op_expression(expr)
self:visit_node(expr.left_operand)
self:write(" ")
self:write(self.binary_op_map[expr.operator])
self:write(" ")
self:visit_node(expr.right_operand)
end
function Transpiler.__index:visit_table_literal_expression(expr)
self:write("{")
self:visit_fields(expr.fields)
if (#expr.fields) > 0 then
self:writeln()
self:iwrite("}")
else
self:write("}")
end
end
function Transpiler.__index:visit_number_literal_expression(expr)
self:write(tostring(expr.value))
end
function Transpiler.__index:visit_string_literal_expression(expr)
self:write(expr.value)
end
function Transpiler.__index:visit_boolean_literal_expression(expr)
self:write(tostring(expr.value))
end
function Transpiler.__index:visit_variable_argument_expression(expr)
self:write("...")
end
function Transpiler.__index:visit_type_assertion_expression(expr)
self:visit_node(expr.base)
end
function Transpiler.__index:visit_field_declaration(field)
if field.syntax_kind == SyntaxKind.sequential_field_declaration then
self:visit_sequential_field_declaration(field)
elseif field.syntax_kind == SyntaxKind.member_field_declaration then
self:visit_member_field_declaration(field)
else
self:visit_index_field_declaration(field)
end
end
function Transpiler.__index:visit_sequential_field_declaration(field)
self:visit_node(field.value)
end
function Transpiler.__index:visit_member_field_declaration(field)
self:write(field.member_identifier.name)
self:write(" = ")
self:visit_node(field.value)
end
function Transpiler.__index:visit_index_field_declaration(field)
self:write("[")
self:visit_node(field.key)
self:write("] = ")
self:visit_node(field.value)
end
function Transpiler.__index:visit_parameter_declaration(param)
self:visit_identifier(param.identifier)
end
return Transpiler
|
local animations = require "character.animations"
local rules = require "scripts.rules"
local Character = require "character.character"
local BountyHunter = Character:new()
function BountyHunter:new(o, control)
o = o or Character:new(o, control)
setmetatable(o, self)
self.__index = self
return o
end
function BountyHunter:create()
Character.create(self)
self:set_mini_skin('bounty_hunter_mini')
self:set_skin("bounty_hunter")
self.data.enemy = false
local stats = self.data.stats
stats.name = "Bounty Hunter"
rules.set_ability_scores_map(stats, {
str = 15,
dex = 13,
con = 13,
int = 13,
wis = 13,
cha = 10,
})
rules.level_up(stats)
rules.level_up(stats)
stats.inventory[1] = { code = self.name .. '_weapon', name = 'bill', type = 'weapon' }
stats.inventory[3] = { code = self.name .. '_armor', name = 'full_plate_mail', type = 'armor' }
stats.weapon = stats.inventory[1]
stats.armor = stats.inventory[3]
self.data.price = 15
end
function BountyHunter:on_interact(interactor_name)
local dialogue = {
start = {
text = "I am a bounty hunter, but I'm not above doing mercenary work.",
go_to = 'hire'
},
hire = {
text = "My price is " .. tostring(self.data.price) .. " coppers.",
options = {
{ text = "What is your speciality?", go_to = 'what' },
{ text = "Deal.", go_to = 'deal' },
{ text = "No.", go_to = 'end' },
}
},
what = {
text = "I am well armed and armored and can handle myself in the frontline.",
options = {
{ text = "Deal.", go_to = 'deal' },
{ text = "No.", go_to = 'end' },
}
},
deal = {
text = function()
if self.control:spend_money('player', self.data.price, self.name) then
self.control:set_companion(self.name)
return "You can count on me."
else
return "You cannot afford me."
end
end,
go_to = 'end'
}
}
sfml_dialogue(dialogue)
end
return BountyHunter
|
local ABP_PlayerName = nil;
local ABP_SpellBookNameToId = {};
local ABP_InventoryItemNameToId = {};
local ABP_BagItemNameToId = {};
local MAX_ACTIONS = 144;
function ABP_OnLoad()
this:RegisterEvent("VARIABLES_LOADED");
SLASH_ABP1 = "/ABP";
SlashCmdList["ABP"] = function(msg)
ABP_SlashCommand(msg);
end
end
function ABP_SaveProfile( profileName )
if ( profileName == "" ) then
return;
end;
if ( ABP_Layout[ ABP_PlayerName ][ profileName ] ~= nil ) then
ABP_Layout[ ABP_PlayerName ][ profileName ] = nil;
end
ABP_Layout[ ABP_PlayerName ][ profileName ] = {};
ABP_Layout[ ABP_PlayerName ][ profileName ][ "spells" ] = {};
ABP_Layout[ ABP_PlayerName ][ profileName ][ "macros" ] = {};
ABP_Layout[ ABP_PlayerName ][ profileName ][ "items" ] = {};
ABP_Tooltip:SetOwner(this, "ANCHOR_NONE");
local scStatus = GetCVar("autoSelfCast");
SetCVar( "autoSelfCast", 0 );
for i = 1, MAX_ACTIONS do
if ( HasAction( i ) ~= nil ) then
local macroName = GetActionText( i );
if ( macroName ~= nil ) then -- It is a macro
ABP_Layout[ ABP_PlayerName ][ profileName ][ "macros" ][ i ] = macroName;
else -- It is a spell or an item
ABP_Tooltip:ClearLines();
ABP_Tooltip:SetAction( i );
PickupAction( i );
local isASpell = CursorHasSpell();
PlaceAction( i );
if ( isASpell ) then -- It is a spell
local spellName = nil;
local rank = nil;
if (ABP_TooltipTextLeft1:IsShown()) then
spellName = ABP_TooltipTextLeft1:GetText();
end
if (ABP_TooltipTextRight1:IsShown()) then
rank = ABP_TooltipTextRight1:GetText();
end
ABP_Layout[ ABP_PlayerName ][ profileName ][ "spells" ][ i ] = {};
ABP_Layout[ ABP_PlayerName ][ profileName ][ "spells" ][ i ][ "name" ] = spellName;
ABP_Layout[ ABP_PlayerName ][ profileName ][ "spells" ][ i ][ "rank" ] = rank; -- can be text or nil
else -- It is an item
local itemName = nil;
if (ABP_TooltipTextLeft1:IsShown()) then
itemName = ABP_TooltipTextLeft1:GetText();
end
ABP_Layout[ ABP_PlayerName ][ profileName ][ "items" ][ i ] = itemName;
end
end
end
end
SetCVar( "autoSelfCast", scStatus );
DEFAULT_CHAT_FRAME:AddMessage( "Profile \""..profileName.."\" has been saved." );
end
function ABP_LoadProfile( profileName )
if ( ABP_Layout[ ABP_PlayerName ][ profileName ] == nil ) then
DEFAULT_CHAT_FRAME:AddMessage( "Profile \""..profileName.."\" has not been saved previously and cannot be loaded." );
return;
end
local scStatus = GetCVar("autoSelfCast");
SetCVar( "autoSelfCast", 0 );
-- First find ids of all spells and items because vanilla API sucks and you can't fetch spells by name.
-- Spells
for i = 1, MAX_SKILLLINE_TABS do
local name, _, offset, numSpells = GetSpellTabInfo(i);
if ( not name ) then break; end
for s = offset + 1, offset + numSpells do
local spellName, spellRank = GetSpellName( s, BOOKTYPE_SPELL );
if ( spellRank ~= "" ) then spellName = spellName.." "..spellRank; end
ABP_SpellBookNameToId[ spellName ] = s;
end
end
ABP_Tooltip:SetOwner(this, "ANCHOR_NONE");
-- Inventory (equipped) items
for i = 1, 19 do
ABP_Tooltip:ClearLines();
hasItem, _, _ = ABP_Tooltip:SetInventoryItem( "player", i );
if ( hasItem ) then
local itemName = nil;
if ( ABP_TooltipTextLeft1:IsShown() ) then
itemName = ABP_TooltipTextLeft1:GetText();
ABP_InventoryItemNameToId[ itemName ] = i;
end
end
end
-- Bag items
for i = 0, NUM_BAG_SLOTS do
for j = 1, GetContainerNumSlots( i ) do
texture, itemCount = GetContainerItemInfo( i, j );
if ( texture ) then
ABP_Tooltip:ClearLines();
ABP_Tooltip:SetBagItem( i, j );
local itemName = nil;
if ( ABP_TooltipTextLeft1:IsShown() ) then
itemName = ABP_TooltipTextLeft1:GetText();
ABP_BagItemNameToId[ itemName ] = {};
ABP_BagItemNameToId[ itemName ][ "bag" ] = i;
ABP_BagItemNameToId[ itemName ][ "slot" ] = j;
end
end
end
end
-- Place spells, items and macros on the action bars.
for i = 1, MAX_ACTIONS do
if ( ABP_Layout[ ABP_PlayerName ][ profileName ][ "spells" ][ i ] ~= nil ) then -- It is a spell
local spellName = ABP_Layout[ ABP_PlayerName ][ profileName ][ "spells" ][ i ][ "name" ];
local spellRank = ABP_Layout[ ABP_PlayerName ][ profileName ][ "spells" ][ i ][ "rank" ];
if ( spellRank ~= nil ) then spellName = spellName.." "..spellRank; end
local spellID = ABP_SpellBookNameToId[ spellName ];
if ( spellID == nil ) then
DEFAULT_CHAT_FRAME:AddMessage( "Spell \""..spellName.."\" is not learnt at the moment." );
PickupAction( i );
ClearCursor();
else
PickupSpell( spellID, BOOKTYPE_SPELL);
PlaceAction( i );
end
elseif ( ABP_Layout[ ABP_PlayerName ][ profileName ][ "macros" ][ i ] ~= nil ) then -- It is a macro
local macroIdx = GetMacroIndexByName( ABP_Layout[ ABP_PlayerName ][ profileName ][ "macros" ][ i ] );
if ( macroIdx > 0 ) then
PickupMacro( macroIdx );
PlaceAction( i );
elseif ( GetSuperMacroInfo( ABP_Layout[ ABP_PlayerName ][ profileName ][ "macros" ][ i ], "texture" ) ) then
PickupMacro( 0, ABP_Layout[ ABP_PlayerName ][ profileName ][ "macros" ][ i ] );
PlaceAction( i );
end
elseif ( ABP_Layout[ ABP_PlayerName ][ profileName ][ "items" ][ i ] ~= nil ) then -- It is an item
local itemName = ABP_Layout[ ABP_PlayerName ][ profileName ][ "items" ][ i ];
if ( ABP_InventoryItemNameToId[ itemName ] ~= nil ) then
local itemID = ABP_InventoryItemNameToId[ itemName ];
PickupInventoryItem( itemID );
PlaceAction( i );
elseif ( ABP_BagItemNameToId[ itemName ] ~= nil ) then
local bagID = ABP_BagItemNameToId[ itemName ][ "bag" ];
local slotID = ABP_BagItemNameToId[ itemName ][ "slot" ];
PickupContainerItem( bagID, slotID );
PlaceAction( i );
end
elseif ( HasAction( i ) ~= nil ) then
PickupAction( i );
ClearCursor();
end
end
SetCVar( "autoSelfCast", scStatus );
ABP_SpellBookNameToId = {}
ABP_InventoryItemNameToId = {}
ABP_BagItemNameToId = {}
DEFAULT_CHAT_FRAME:AddMessage( "Profile \""..profileName.."\" has been loaded." );
end
function hasElements( T )
local count = 0;
for _ in pairs( T ) do
count = count + 1;
break;
end
return count;
end
function ABP_ListProfiles()
if ( ABP_Layout[ ABP_PlayerName ] == nil or hasElements( ABP_Layout[ ABP_PlayerName ] ) == 0 ) then
DEFAULT_CHAT_FRAME:AddMessage( "You have no profiles saved for this character." );
return
end
DEFAULT_CHAT_FRAME:AddMessage( "This character has following profiles saved:" );
for profileName, val in pairs( ABP_Layout[ ABP_PlayerName ] ) do
DEFAULT_CHAT_FRAME:AddMessage( profileName );
end
end
function ABP_RemoveProfile( profileName )
if ( ABP_Layout[ ABP_PlayerName ][ profileName ] == nil ) then
DEFAULT_CHAT_FRAME:AddMessage( "You have no profile '"..profileName.."' saved for this character." );
return
end
ABP_Layout[ ABP_PlayerName ][ profileName ] = nil;
DEFAULT_CHAT_FRAME:AddMessage( "Profile '"..profileName.."' has been removed." );
end
function ABP_OnEvent()
if ( event == "VARIABLES_LOADED" ) then
ABP_PlayerName = UnitName("player").." of "..GetCVar("realmName");
if ( ABP_Layout == nil ) then
ABP_Layout = {};
end
if ( ABP_Layout[ ABP_PlayerName ] == nil ) then
ABP_Layout[ ABP_PlayerName ] = {};
end
if (ABP_ButtonPosition == nil) then
ABP_ButtonPosition = 60;
end
UIDropDownMenu_Initialize( getglobal( "ABP_DropDownMenu" ), ABP_DropDownMenu_OnLoad, "MENU" );
ABPButton_UpdatePosition()
end
end
function ABP_SlashCommand(msg)
if ( msg == "" ) then
DEFAULT_CHAT_FRAME:AddMessage( "ActionBarProfiles, by <Vanguard> of Kronos and Emerald Dream" );
DEFAULT_CHAT_FRAME:AddMessage( "/abp save [profileName]" );
DEFAULT_CHAT_FRAME:AddMessage( "/abp load [profileName]" );
DEFAULT_CHAT_FRAME:AddMessage( "/abp remove [profileName]" );
DEFAULT_CHAT_FRAME:AddMessage( "/abp list" );
end
for profileName in string.gfind( msg, "save (.*)" ) do
ABP_SaveProfile( profileName );
end
for profileName in string.gfind( msg, "load (.*)" ) do
ABP_LoadProfile( profileName );
end
for profileName in string.gfind( msg, "remove (.*)" ) do
ABP_RemoveProfile( profileName );
end
for profileName in string.gfind( msg, "list" ) do
ABP_ListProfiles();
end
end
-- GUI --
function ABP_DropDownMenu_OnLoad()
if ( UIDROPDOWNMENU_MENU_VALUE == "Delete menu" ) then
local title = {
text = "Select a layout to delete",
isTitle = true,
owner = this:GetParent(),
justifyH = "CENTER",
};
UIDropDownMenu_AddButton( title, UIDROPDOWNMENU_MENU_LEVEL );
for profileName, val in pairs( ABP_Layout[ ABP_PlayerName ] ) do
local entry = {
text = profileName,
value = profileName,
func = function()
ABP_RemoveProfile( this:GetText() );
end,
notCheckable = 1,
owner = this:GetParent()
};
UIDropDownMenu_AddButton( entry, UIDROPDOWNMENU_MENU_LEVEL );
end
return;
end
local title = {
text = UnitName("player").."'s action bars",
isTitle = true,
owner = this:GetParent(),
justifyH = "CENTER",
};
UIDropDownMenu_AddButton( title, UIDROPDOWNMENU_MENU_LEVEL );
for profileName, val in pairs( ABP_Layout[ ABP_PlayerName ] ) do
local entry = {
text = profileName,
func = function()
ABP_LoadProfile( this:GetText() );
end,
notCheckable = 1,
owner = this:GetParent()
};
UIDropDownMenu_AddButton( entry, UIDROPDOWNMENU_MENU_LEVEL );
end
title = {
text = "Options",
isTitle = true,
justifyH = "CENTER"
};
UIDropDownMenu_AddButton( title, UIDROPDOWNMENU_MENU_LEVEL );
local info = {
text = "Save current layout",
func = function()
StaticPopup_Show("ABP_NewProfile");
end,
notCheckable = 1,
owner = this:GetParent()
};
UIDropDownMenu_AddButton( info, UIDROPDOWNMENU_MENU_LEVEL );
info = {
text = "Delete a layout",
value = "Delete menu",
notCheckable = 1,
hasArrow = true
};
UIDropDownMenu_AddButton( info, UIDROPDOWNMENU_MENU_LEVEL );
end
function ABP_OnClick()
ToggleDropDownMenu( 1, nil, ABP_DropDownMenu, ActionBarProfiles_IconFrame, 0, 0 );
end
StaticPopupDialogs["ABP_NewProfile"] = {
text = "Enter a name under which to save the current action bars layout",
button1 = SAVE,
button2 = CANCEL,
OnAccept = function()
local profileName = getglobal( this:GetParent():GetName().."EditBox" ):GetText();
ABP_SaveProfile( profileName );
getglobal( this:GetParent():GetName().."EditBox" ):SetText("");
end,
EditBoxOnEnterPressed = function()
local profileName = this:GetText();
ABP_SaveProfile( profileName );
this:SetText("");
local parent = this:GetParent();
parent:Hide();
end,
timeout = 0,
whileDead = true,
hideOnEscape = true,
hasEditBox = true,
preferredIndex = 3
}
-- Positioning (Stole this part of code from Atlas addon) --
local ABP_ButtonRadius = 78;
function ABPButton_UpdatePosition()
ActionBarProfiles_IconFrame:SetPoint(
"TOPLEFT",
"Minimap",
"TOPLEFT",
54 - ( ABP_ButtonRadius * cos( ABP_ButtonPosition ) ),
( ABP_ButtonRadius * sin( ABP_ButtonPosition ) ) - 55
);
end
function ABPButton_BeingDragged()
local xpos,ypos = GetCursorPosition()
local xmin,ymin = Minimap:GetLeft(), Minimap:GetBottom()
xpos = xmin-xpos/UIParent:GetScale()+70
ypos = ypos/UIParent:GetScale()-ymin-70
ABPButton_SetPosition(math.deg(math.atan2(ypos,xpos)));
end
function ABPButton_SetPosition(v)
if(v < 0) then
v = v + 360;
end
ABP_ButtonPosition = v;
ABPButton_UpdatePosition();
end
|
local keywordHandler = KeywordHandler:new()
local npcHandler = NpcHandler:new(keywordHandler)
NpcSystem.parseParameters(npcHandler)
function onCreatureAppear(cid) npcHandler:onCreatureAppear(cid) end
function onCreatureDisappear(cid) npcHandler:onCreatureDisappear(cid) end
function onCreatureSay(cid, type, msg) npcHandler:onCreatureSay(cid, type, msg) end
function onThink() npcHandler:onThink() end
local voices = { {text = 'Gems and jewellery! Best prices in town!'} }
npcHandler:addModule(VoiceModule:new(voices))
local function creatureSayCallback(cid, type, msg)
if not npcHandler:isFocused(cid) then
return false
end
local player = Player(cid)
if msgcontains(msg, "addon") or msgcontains(msg, "outfit") or msgcontains(msg, "hat") then
local addonProgress = player:getStorageValue(Storage.OutfitQuest.Citizen.AddonHat)
if addonProgress < 1 then
npcHandler:say("Pretty, isn't it? My friend Amber taught me how to make it, but I could help you with one if you like. What do you say?", cid)
npcHandler.topic[cid] = 1
elseif addonProgress == 1 then
npcHandler:say("Oh, you're back already? Did you bring a legion helmet, 100 chicken feathers and 50 honeycombs?", cid)
npcHandler.topic[cid] = 2
elseif addonProgress == 2 then
npcHandler:say('Pretty hat, isn\'t it?', cid)
end
return true
end
if npcHandler.topic[cid] == 1 then
if msgcontains(msg, 'yes') then
player:setStorageValue(Storage.OutfitQuest.Ref, math.max(0, player:getStorageValue(Storage.OutfitQuest.Ref)) + 1)
player:setStorageValue(Storage.OutfitQuest.Citizen.AddonHat, 1)
player:setStorageValue(Storage.OutfitQuest.Citizen.MissionHat, 1)
npcHandler:say('Okay, here we go, listen closely! I need a few things... a basic hat of course, maybe a legion helmet would do. Then about 100 chicken feathers... and 50 honeycombs as glue. That\'s it, come back to me once you gathered it!', cid)
else
npcHandler:say('Aw, I guess you don\'t like feather hats. No big deal.', cid)
end
npcHandler.topic[cid] = 0
elseif npcHandler.topic[cid] == 2 then
if msgcontains(msg, 'yes') then
if player:getItemCount(2480) < 1 then
npcHandler:say('Sorry, but I can\'t see a legion helmet.', cid)
elseif player:getItemCount(5890) < 100 then
npcHandler:say('Sorry, but you don\'t enough chicken feathers.', cid)
elseif player:getItemCount(5902) < 50 then
npcHandler:say('Sorry, but you don\'t have enough honeycombs.', cid)
else
npcHandler:say('Great job! That must have taken a lot of work. Okay, you put it like this... then glue like this... here!', cid)
player:getPosition():sendMagicEffect(CONST_ME_MAGIC_BLUE)
player:removeItem(2480, 1)
player:removeItem(5902, 50)
player:removeItem(5890, 100)
player:addOutfitAddon(136, 2)
player:addOutfitAddon(128, 2)
player:setStorageValue(Storage.OutfitQuest.Ref, math.min(0, player:getStorageValue(Storage.OutfitQuest.Ref) - 1))
player:setStorageValue(Storage.OutfitQuest.Citizen.MissionHat, 0)
player:setStorageValue(Storage.OutfitQuest.Citizen.AddonHat, 2)
end
else
npcHandler:say('Maybe another time.', cid)
end
npcHandler.topic[cid] = 0
end
return true
end
keywordHandler:addKeyword({'job'}, StdModule.say, {npcHandler = npcHandler, text = 'I am a jeweler. Maybe you want to have a look at my wonderful offers.'})
keywordHandler:addKeyword({'name'}, StdModule.say, {npcHandler = npcHandler, text = 'I am Hanna.'})
npcHandler:setMessage(MESSAGE_GREET, 'Oh, please come in, |PLAYERNAME|. What do you need? Have a look at my wonderful {offers} in gems and jewellery.')
npcHandler:setMessage(MESSAGE_FAREWELL, 'Good bye.')
npcHandler:setMessage(MESSAGE_WALKAWAY, 'Good bye.')
npcHandler:setCallback(CALLBACK_MESSAGE_DEFAULT, creatureSayCallback)
npcHandler:addModule(FocusModule:new())
|
-- Copyright (c) 2020 Trevor Redfern
--
-- This software is released under the MIT License.
-- https://opensource.org/licenses/MIT
local quest_files = moonpie.utility.files.find("assets/quests/", "lua$", "_spec.lua$")
local quests = moonpie.collections.list:new()
for _, v in ipairs(quest_files) do
if string.find(v, "init.lua") == nil then
local rp = string.gsub(v, "%.lua", "")
rp = string.gsub(rp, "/", ".")
quests:add(require(rp))
end
end
return quests
|
-- Call with return values
local function a(a, b)
return a+b
end
local function b()
return 1, 2
end
print(a(b()))
print(a(1, b()))
|
EFFECT.Mat = Material("effects/select_ring")
function EFFECT:Init(data)
local size = 8
self:SetCollisionBounds(Vector(-size, -size, -size), Vector(size, size, size))
local Pos = data:GetOrigin() + data:GetNormal() * 2
self:SetPos(Pos)
-- This 0.01 is a hack.. to prevent the angle being weird and messing up when we change it back to a normal
self:SetAngles(data:GetNormal():Angle() + Angle(0.01, 0.01, 0.01))
self:SetParentPhysNum(data:GetAttachment())
if (IsValid(data:GetEntity())) then
self:SetParent(data:GetEntity())
end
self.Pos = data:GetOrigin()
self.Normal = data:GetNormal()
self.Speed = math.Rand(0.5, 1.5)
self.Size = 4
self.Alpha = 255
self.Life = 0.5
end
function EFFECT:Think()
self.Alpha = self.Alpha - FrameTime() * 255 * 5 * self.Speed
self.Size = self.Size + FrameTime() * 256 * self.Speed
if (self.Alpha < 0) then return false end
return true
end
function EFFECT:Render()
if (self.Alpha < 1) then return end
render.SetMaterial(self.Mat)
render.DrawQuadEasy(self:GetPos(), self:GetAngles():Forward(), self.Size, self.Size, Color(math.Rand(10, 150), math.Rand(170, 220), math.Rand(240, 255), self.Alpha))
end
|
--* This Document is AutoGenerate by OrangeFilter, Don't Change it! *
---@meta
---
---[4.9.8]binary data[parent:]
---
---@class OF_ParamBinary
---
---[4.9.8]name string
---
---@field name string
---
---[4.9.8]binray width
---
---@field width int
---
---[4.9.8]binray height
---
---@field height int
---
---[4.9.8]binray byte array
---
---@field data ByteArray#bytearray
---
---[4.9.8]binray byte length
---
---@field dataLength int
---
---[4.9.8]texture format
---
---@field format int
OF_ParamBinary = {}
---
---[4.9.8]constructor, no param
---
--- @nodiscard
function OF_ParamBinary:new() end
return OF_ParamBinary
|
local helpers = require('test.functional.helpers')(after_each)
local Screen = require('test.functional.ui.screen')
local clear = helpers.clear
local exec = helpers.exec
local feed = helpers.feed
before_each(clear)
describe('statusline', function()
local screen
before_each(function()
screen = Screen.new(50, 7)
screen:attach()
end)
it('is updated in cmdline mode when using window-local statusline vim-patch:8.2.2737', function()
screen:set_default_attr_ids({
[1] = {bold = true, foreground = Screen.colors.Blue}, -- NonText
[2] = {bold = true, reverse = true}, -- StatusLine
[3] = {reverse = true}, -- StatusLineNC
})
exec([[
setlocal statusline=-%{mode()}-
split
setlocal statusline=+%{mode()}+
]])
screen:expect([[
^ |
{1:~ }|
{2:+n+ }|
|
{1:~ }|
{3:-n- }|
|
]])
feed(':')
screen:expect([[
|
{1:~ }|
{2:+c+ }|
|
{1:~ }|
{3:-c- }|
:^ |
]])
end)
it('truncated item does not cause off-by-one highlight vim-patch:8.2.4929', function()
screen:set_default_attr_ids({
[1] = {bold = true, foreground = Screen.colors.Blue}, -- NonText
[2] = {foreground = Screen.colors.Blue}, -- User1
[3] = {background = Screen.colors.Red, foreground = Screen.colors.White}, -- User2
})
exec([[
set laststatus=2
hi! link User1 Directory
hi! link User2 ErrorMsg
set statusline=%.5(%1*ABC%2*DEF%1*GHI%)
]])
screen:expect([[
^ |
{1:~ }|
{1:~ }|
{1:~ }|
{1:~ }|
{3:<F}{2:GHI }|
|
]])
end)
end)
|
modifier_take_damage = class(Modifier)
LinkLuaModifier("modifier_take_damage", modifier_take_damage)
function modifier_take_damage:OnCreated ()
--Debug.Log('I was created? Cool!')
end
function modifier_take_damage:OnAttached()
self:AddTimer(0.5,"0.5s timer")
if(self:GetCaster():GetId() == self:GetParent():GetId()) then
--Debug.Log("modifier_take_damage:OnAttached() is caster -> setting aura")
self:SetAuraRadius(20)
else
--Debug.Log("modifier_take_damage:OnAttached() is not caster -> so auras work?")
end
end
function modifier_take_damage:AddTimer(seconds, description)
self.timerHandler = self.timerHandler or {}
local ticket=TimerRequestBus.Broadcast.ScheduleTimer(seconds,description)
local handler=TimerNotificationBus.Connect(self,ticket)
table.insert(self.timerHandler, handler)
end
function modifier_take_damage:OnTimerFinished(description)
--Debug.Log("OnTimerFinished "..description)
local damage = Damage();
damage.type = Damage.DAMAGE_TYPE_PHYSICAL;
damage.damage = self:GetAbility():GetSpecialValue("damage");
self:GetParent():ApplyDamage(damage)
self:AddTimer(0.5,"0.5s timer")
end
|
Notifier = {}
function Notifier:child()
self.__index = self
return setmetatable({ base = self }, self)
end
function Notifier:new()
self.__index = self
return setmetatable({}, self)
end
function Notifier:notify_results(results)
error('notify_results is not implemented')
end
return Notifier
|
module 'mock'
local enumSpawnMethod = _ENUM_V {
'root',
'sibling',
'child',
'parent_sibling'
}
CLASS: ProtoSpawner ( Component )
:MODEL{
Field 'proto' :asset('proto');
Field 'spawnName' :string();
Field 'showIcon' :boolean();
'----';
Field 'copyLoc' :boolean();
Field 'copyRot' :boolean();
Field 'copyScl' :boolean();
'----';
Field 'autoSpawn' :boolean();
Field 'destroyOnSpawn' :boolean();
Field 'spawnMethod' :enum( enumSpawnMethod )
-- Field 'spawnAsChild' :boolean();
}
:META{
category = 'spawner'
}
registerComponent( 'ProtoSpawner', ProtoSpawner )
registerEntityWithComponent( 'ProtoSpawner', ProtoSpawner )
function ProtoSpawner:__init()
self.proto = false
self.autoSpawn = true
self.showIcon = true
self.destroyOnSpawn = true
self.spawnAsChild = false
self.copyLoc = true
self.copyScl = false
self.copyRot = false
self.spawnMethod = 'sibling'
self.spawnName = ''
end
function ProtoSpawner:onStart( ent )
if self.autoSpawn then
self:spawn()
end
end
function ProtoSpawner:spawnOne( ox, oy, oz )
local ent = self._entity
local instance
if self.proto then
instance = createProtoInstance( self.proto )
if instance then
instance:setName( self.spawnName )
local spawnMethod = self.spawnMethod
if spawnMethod == 'child' then
if self.copyLoc then instance:setLoc( 0,0,0 ) end
if self.copyRot then instance:setRot( 0,0,0 ) end
if self.copyScl then instance:setScl( 1,1,1 ) end
if ox then
instance:addLoc( ox, oy, oz )
end
ent:addChild( instance )
elseif spawnMethod == 'sibling' then
if self.copyLoc then instance:setLoc( ent:getLoc() ) end
if self.copyRot then instance:setRot( ent:getRot() ) end
if self.copyScl then instance:setScl( ent:getScl() ) end
if ox then
instance:addLoc( ox, oy, oz )
end
ent:addSibling( instance )
elseif spawnMethod == 'parent_sibling' then
if ent.parent then
ent:forceUpdate()
ent.parent:forceUpdate()
if self.copyLoc then
local x, y, z
if ent.parent.parent then
x, y, z = ent.parent.parent:worldToModel( ent:getWorldLoc() )
else
x, y, z = ent:getWorldLoc()
end
instance:setLoc( x, y, z )
instance:forceUpdate()
end
if self.copyRot then instance:setRot( ent:getRot() ) end
if self.copyScl then instance:setScl( ent:getScl() ) end
if ox then
instance:addLoc( ox, oy, oz )
end
ent.parent:addSibling( instance )
else --as root
ent:forceUpdate()
if self.copyLoc then instance:setLoc( ent:getWorldLoc() ) end
if self.copyRot then instance:setRot( ent:getRot() ) end
if self.copyScl then instance:setScl( ent:getScl() ) end
if ox then
instance:addLoc( ox, oy, oz )
end
instance:forceUpdate()
ent:getScene():addEntity( instance )
end
elseif spawnMethod == 'root' then
ent:forceUpdate()
if self.copyLoc then instance:setLoc( ent:getWorldLoc() ) end
if self.copyRot then instance:setRot( ent:getRot() ) end
if self.copyScl then instance:setScl( ent:getScl() ) end
if ox then
instance:addLoc( ox, oy, oz )
end
instance:forceUpdate()
ent:getScene():addEntity( instance )
end
end
--FIXME:remove this non-generic code
if ent:isInstance( 'EWMapObject' ) then
instance:setFloor( ent:getFloor() )
end
end
return instance
end
function ProtoSpawner:spawn()
if not self.proto then return end
local result = { self:onSpawn() }
self:postSpawn()
return unpack( result )
end
function ProtoSpawner:onSpawn()
return self:spawnOne()
end
function ProtoSpawner:postSpawn()
if self.destroyOnSpawn then
self._entity:destroy()
end
end
--------------------------------------------------------------------
--EDITOR Support
function ProtoSpawner:onBuildGizmo()
if not self.showIcon then return end
local giz = mock_edit.IconGizmo( 'spawn.png' )
return giz
end
|
--[[
Manager.lua
Plugin manager UI support.
--]]
local Manager, dbg = Object:newClass{ className = 'Manager' }
--- Constructor for extending class.
--
function Manager:newClass( t )
return Object.newClass( self, t )
end
--- Constructor for new instance.
--
function Manager:new( t )
local o = Object.new( self, t )
return o
end
--- Initialize global preferences.
--
function Manager:_initGlobalPrefs()
if app:isVerbose() then
app:setGlobalPref( 'infoSynopsis', "Logging verbosely" )
else
app:setGlobalPref( 'infoSynopsis', "Logging is limited" )
end
app:initGlobalPref( 'infoSynopsis', "" )
app:initGlobalPref( 'username', "" ) -- works out same as -Anonymous-, but without showing as that.
app:initGlobalPref( 'globalTestData', "initial global test data" )
end
--- Initialize local preferences for specified preset.
--
function Manager:_initPrefs( presetName )
-- note: verbose-logging pref is initialized as part of framework proper.
app:initPref( 'testData', "initial test data", presetName )
app:initPref( 'promptToSaveMetadata', 0, presetName )
end
--- Static method for initializing preferences: both global and non-global.
--
-- @usage Global preferences used by framework are initialized in init-framework.<br>
-- (I don't think framework is using any non-global preferences at the moment).
-- This function is for initializing preferencea used by application.
-- @usage Must be called from init module, so preferences are initialized without having to visit plugin manager.
-- @usage Extended classes should always call this after initializing extended preferences.
--
function Manager.initPrefs()
if Manager.manager == nil then
Manager.manager = objectFactory:newObject( 'Manager' )
end
Manager.manager:_initGlobalPrefs()
if app.prefMgr then
local presetNames = app.prefMgr:getPresetNames() -- including 'Default'.
for i, presetName in ipairs( presetNames ) do
--Debug.logn( presetName )
Manager.manager:_initPrefs( presetName )
end
else
Manager.manager:_initPrefs( nil )
end
end
--- Preference change handler.
--
-- <p>Handles change to preferences that are associated with a property table in the plugin manager UI.<br>
-- Examples: adv-dbg-ena, pref-set-name.</p>
--
-- @param _prefs Preferences associated with value change.
-- @param key raw preference key - not suitable for direct comparison to global pref names.
-- @param value New preference value.
-- @param call
--
-- @usage *** IMPORTANT: The base class method is critical and must be called by derived class.
-- @usage Changed items are typically changed via the UI and are bound directly to lr-prefs.
-- <br>props are not bound to prefs explicitly/directly, but need to be reloaded if the pref set name changes.
--
function Manager:prefChangeHandlerMethod( _id, _prefs, key, value, call )
app:call( Call:new{ name="prefChangeHandlerMethod", async=true, guard=App.guardSilent, main=function( call ) -- ###1 async?
assert( prefs == _prefs, "pref change handler method is for prefs only" )
local name = app:getGlobalPrefName( key )
-- dbg( "Pref Changed: ", str:format( "^1: ^2", key, str:to( value ) ) )
if name == 'advDbgEna' then
if value then
if app:getGlobalPref( 'classDebugEnable' ) then
app:setGlobalPref( "classDebugSynopsis", "Active" )
else
app:setGlobalPref( "classDebugSynopsis", "Inactive" )
end
if app:isRelease() then
app:show{ info="Advanced debugging is normally done by plugin author, or under plugin author's direction." }
end
Debug.init( true )
elseif value ~= nil then
app:setGlobalPref( "classDebugSynopsis", "" )
Debug.init( false )
end
elseif name == 'classDebugEnable' then
if value then
if app:getGlobalPref( 'advDbgEna' ) then
app:setGlobalPref( "classDebugSynopsis", "Active" )
else
app:setGlobalPref( "classDebugSynopsis", "" )
end
else
if app:getGlobalPref( 'advDbgEna' ) then
app:setGlobalPref( "classDebugSynopsis", "Inactive" )
else
app:setGlobalPref( "classDebugSynopsis", "" )
end
end
--[[ *** save for reference:
elseif name == 'presetName' then
assert( self.props, "no props to load preset into" )
--app:presetNameChange( self.props, key, value ) -
--]]
elseif name == 'logVerbose' then
app.logr:enable{ verbose = value }
if value then
app:setGlobalPref( 'infoSynopsis', "Logging verbosely" )
else
app:setGlobalPref( 'infoSynopsis', "Logging is limited" )
end
else
-- ?
end
end, finale=function( call )
--
end } )
end
--- Plugin manager property change handler.
--
-- @usage Handles changes to property table for UI elements that are NOT specifically/directly bound to a lr-preference.
-- @usage By default, this method simply sets the corresponding preference which may be from a named set, or the unnamed (default) set.
-- @usage *** IMPORTANT: Derived class may need to call base class method, or at a minimum, make sure changed prefs are set.
--
function Manager:propChangeHandlerMethod( props, name, value )
app:setPref( name, value )
end
--- Start dialog method.
--
-- @usage *** IMPORTANT: The base class method is critical and must be called by derived class,
-- <br>AFTER initializing all the pref values, so they get loaded into props.
--
function Manager:startDialogMethod( props )
self.props = props
-- dbg("loading props corresponding to set ", app:getGlobalPref( 'presetName' ) )
app:switchPreset( props )
view:setObserver( prefs, app:getGlobalPrefKey( 'advDbgEna' ), Manager, Manager.prefChangeHandler )
view:setObserver( prefs, app:getGlobalPrefKey( 'classDebugEnable' ), Manager, Manager.prefChangeHandler )
--view:setObserver( prefs, app:getGlobalPrefKey( 'presetName' ), Manager, Manager.prefChangeHandler ) - *** save for reference.
view:setObserver( prefs, app:getGlobalPrefKey( 'logVerbose' ), Manager, Manager.prefChangeHandler )
if props ~= prefs then
for k in props:pairs() do
dbg( "Manager registering property observer for:", k )
-- *** Save for a while: props:addObserver( k, Manager.propChangeLegacyHandler ) -- the old way - possible to get redundent change handling, or worse
-- if user clicks another plugin, then back to this one, it will add another observer.
view:setObserver( props, k, Manager, Manager.propChangeHandler ) -- the new way - only one call to change handler per change.
end
end
end
--- Sections for top of dialog method.
--
-- @usage Derived class is free to call to include standard sections, or override completely...
--
function Manager:sectionsForTopOfDialogMethod( vf, props )
self.props = props
local infoSection = { bind_to_object = prefs }
local compatStr = app:getCompatibilityString()
infoSection.title = app:getPluginName()
-- infoSection.synopsis = compatStr
infoSection.synopsis = bind{ key=app:getGlobalPrefKey( 'infoSynopsis' ), object=prefs }
infoSection.spacing = vf:label_spacing()
infoSection[#infoSection + 1] =
vf:row {
vf:static_text {
title = compatStr,
},
vf:static_text {
title = 'Author: ' .. app:getAuthor(),
},
vf:static_text {
title = "Author's Website: " .. app:getAuthorsWebsite(),
},
}
infoSection[#infoSection + 1] = vf:spacer{ height=5 }
-- BEGIN CONDITIONAL buyPlugin
local buyUrl = app:getInfo( "buyUrl" ) or false
-- get rid of button if copy is licensed?
if buyUrl then
infoSection[#infoSection + 1] =
vf:row {
vf:push_button {
title = "Buy " .. app:getPluginName(),
font = "<system/bold>",
width = share( "button_width" ),
action = function( button )
app:call( Call:new{ name = "Buy", main=function()
LrHttp.openUrlInBrowser( buyUrl )
end } )
end
},
vf:static_text {
title = str:format( "Go to website with purchasing info..." ),
},
}
end
-- END CONDITIONAL buyPlugin
-- BEGIN CONDITIONAL donate
local donateUrl = app:getInfo( "donateUrl" ) or false
if donateUrl then
infoSection[#infoSection + 1] =
vf:row {
vf:push_button {
title = "Donate",
font = "<system/bold>",
width = share( "button_width" ),
action = function( button )
app:call( Call:new{ name = "Buy", main=function()
LrHttp.openUrlInBrowser( donateUrl )
end } )
end
},
vf:static_text {
title = str:format( "Go to website with donation information and donation link.\nTo donate more than $1 - use the 'Quantity' field - thank you!\nDonations assure continued support for the plugins you use, and more plugins...\n(not to mention being a great way to simply express your appreciation)" ),
},
}
end
-- END CONDITIONAL donate
if buyUrl or donateUrl then
infoSection[#infoSection + 1] = vf:spacer{ height=5 }
infoSection[#infoSection + 1] = vf:separator{ fill_horizontal = 1 }
end
infoSection[#infoSection + 1] = vf:spacer{ height=5 }
infoSection[#infoSection + 1] =
vf:row {
vf:push_button {
title = "Reset Warning Dialogs",
width = share( "button_width" ),
action = function( button )
app:resetWarningDialogs()
app:show{ info="Warning dialogs have been reset." }
end
},
vf:static_text {
title = LOC( '$$$/X=Show ^1 dialog boxes previously marked "Do Not Show".', app:getAppName() ),
},
}
local cbRow = {}
-- BEGIN CONDITIONAL updateOption
if app:getInfo( "xmlRpcUrl" ) then
infoSection[#infoSection + 1] =
vf:row {
vf:push_button {
title = "Check for Update",
width = share( "button_width" ),
action = function( button )
app:checkForUpdate()
end
},
vf:static_text {
title = str:format( "Check for newer version of ^1 via the internet.", app:getPluginName() ),
},
}
infoSection[#infoSection + 1] =
vf:row {
vf:push_button {
title = "Update Plugin",
width = share( "button_width" ),
action = function( button )
app:updatePlugin()
end
},
vf:static_text {
title = str:fmtAmp( "Update plugin to newer version (must be downloaded && unzipped already).", app:getPluginName() ),
},
}
end
-- END CONDITIONAL updateOption
infoSection[#infoSection + 1] =
vf:row {
vf:push_button {
title = "View Logs",
width = share( "button_width" ),
action = function( button )
app:showLogFile()
end
},
vf:static_text {
title = str:format( "Show log file using default app." ),
},
}
infoSection[#infoSection + 1] =
vf:row {
vf:push_button {
title = "Clear Logs",
width = share( "button_width" ),
action = function( button )
app:call( Call:new{ name=button.title, async=true, guard=App.guardSilent, main=function( call )
app:clearLogFile()
end } )
end
},
vf:static_text {
title = str:format( "Clear log file by moving it to trash." ),
},
}
-- BEGIN CONDITIONAL problemReportOption
local problemReportOption = app:getInfo( 'problemReportOption' )
if problemReportOption == nil then
problemReportOption = true
end
if problemReportOption then
infoSection[#infoSection + 1] =
vf:row {
vf:push_button {
title = "Report Problem", -- "Send Logs to " .. app:getAuthor(),
width = share( "button_width" ),
action = function( button )
app:call( Call:new{ name = "Send log file", guard = App.guardVocal, main = function( context , ... )
local contents, message = app:getLogFileContents()
if contents then
local ok = dialog:putTextOnClipboard{ title="Copy Log Contents To Clipboard", contents=contents }
if ok then
LrHttp.openUrlInBrowser( "mailto:[email protected]?subject=" .. app:getPluginName() .. " - Problem Report" .. "&body=Replace this text with the contents of the log file, which should still be on the clipboard, which you can paste by clicking anywhere in the body of the email, then pressing " .. app:getCtrlKeySeq( 'V' ) .. ". Then, make sure you include a detailed explanation of the problem you've encountered, and if possible - the steps that will be required for me to reproduce the problem. There should be a dialog box open in Lightroom with more instructions..." ) -- Drive-by (does not wait).
app:show{ info="Your browser should have opened your mailer with a new email message to send.\n\nIf you haven't already done so, please paste the log contents from the clipboard into the body of the email (first click anywhere in the body of the email, then press ^1), then send.", app:getCtrlKeySeq( 'V' ) }
else
--
end
else
app:show{ error="Unable to get log contents, error message: ^1", message }
end
end, finale = function( call, status, message )
if status then
else
app:show{ error="Unable to send logs, error message: ^1", message }
end
end } )
end
},
vf:static_text {
title = str:fmt( "Report problem with ^1 to ^2.", app:getPluginName(), app:getAuthor() ),
},
}
end
-- END CONDITIONAL problemReportOption
-- BEGIN CONDITIONAL updateOption
if app:getInfo( "xmlRpcUrl" ) then
if gbl:getValue( "xmlRpc" ) then
if xmlRpc.url then
cbRow[#cbRow + 1] =
vf:checkbox {
title = "Check for updates upon startup.",
value = app:getGlobalPrefBinding( 'autoUpdateCheck' ),
}
else
error( "xml-rpc url must be specified in init.lua" )
end
else
error( "xml-rpc object must be instantiated to support update-option - hint: define url in config file." )
end
end
-- END CONDITIONAL updateOption
infoSection[#infoSection + 1] = vf:spacer{ height=5 }
cbRow[#cbRow + 1] =
vf:checkbox {
title = "Verbose Logging",
value = app:getGlobalPrefBinding( 'logVerbose' ),
}
-- BEGIN CONDITIONAL updateOption
if app:getInfo( "xmlRpcUrl" ) then
cbRow[#cbRow + 1] = vf:spacer{ fill_horizontal = 1 }
cbRow[#cbRow + 1] =
vf:push_button {
title = "Uninstall",
width = share 'width_button_2',
tooltip = "Uninstall " .. app:getPluginName(),
action = function( button )
app:uninstallPlugin()
end
}
end
-- END CONDITIONAL updateOption
infoSection[#infoSection + 1] = vf:row( cbRow )
infoSection[#infoSection + 1] = vf:row {
vf:static_text {
--width = share 'button_width',
title = "Log Folder",
},
vf:edit_field {
-- bind_to_object is prefs
value = app:getGlobalPrefBinding( 'logDir' ),
width_in_chars = 45,
tooltip = "Enter path or browse for directory in which to store log file; leave blank and Lightroom will choose for you (documents folder).",
},
vf:spacer {
-- bind_to_object is prefs
width = 1,
fill_horizontal= 1,
},
vf:push_button {
title = "Browse",
width = share 'width_button_2',
action = function( button )
app:call( Call:new{ name=button.title, async=true, guard=App.guardVocal, main=function( call )
call.dfltDir = LrPathUtils.child( cat:getDir(), "Logs" )
if not LrFileUtils.exists( call.dfltDir ) then
LrFileUtils.createAllDirectories( call.dfltDir )
call.okToDelete = true -- wasn't existing - just created (must check other things too though, since user could populate and/or choose while dialog open).
end
local logDir = dia:selectFolder(
{ title = "Choose 'Logs' folder in catalog directory (recommended), or choose preferred location for plugin log files.",
canCreateDirectories = true, -- this is for a button to create dir - not seen on Windows, maybe Mac.
initialDirectory = call.dfltDir,
-- prompt = "Choose", - not supported by folder chooser.
} )
if logDir and logDir ~= app:getGlobalPref( 'logDir' ) then
app:show{ info="^1 will store log files in '^2' directory once plugin is reloaded or Lightroom is restarted.",
app:getAppName(),
logDir,
}
app:setGlobalPref( 'logDir', logDir )
end
end, finale=function( call )
if call.okToDelete and app:getGlobalPref( 'logDir' ) ~= call.dfltDir and LrFileUtils.isEmptyDirectory( call.dfltDir ) then
LrFileUtils.delete( call.dfltDir )
end
end } )
end,
},
}
-- C L A S S D E B U G
local advDbgSection
--if not app:isRelease() then
if true then -- I suppose it cant hurt anything too much(?)
advDbgSection = { bind_to_object = prefs }
advDbgSection.title = "Debug"
advDbgSection.synopsis = bind {
keys = { app:getGlobalPrefKey( 'advDbgEna' ), app:getGlobalPrefKey( 'classDebugEnable' ) },
bind_to_object=prefs,
transform = function()
if app:getGlobalPref( 'advDbgEna' ) then
if app:getGlobalPref( 'classDebugEnable' ) then
return "Restricted"
else
return "Enabled"
end
else
return "Disabled"
end
end
}
advDbgSection.spacing = vf:label_spacing()
advDbgSection[#advDbgSection + 1] =
vf:row {
vf:push_button {
title = "Reset Selected Warnings",
action = function( button )
app:call( Call:new{ name=button.title, async=true, guard=App.guardSilent, main=function( call )
local items = {}
local lookup = {}
local enaPfx = "actionPrefKey_enabled_"
local answerPfx = "actionPrefKey_answer_"
local friendlyPfx = "actionPrefKey_friendly_"
local enaPfxLen = enaPfx:len()
local friendlyPfxLen = friendlyPfx:len()
for k, v in app:getGlobalPrefPairs() do -- works with pref-mgr or none
if str:isStartingWith( k, enaPfx ) and v then -- apk enabled.
local friendlySfx = k:sub( enaPfxLen + 1 )
local friendlyKey = friendlyPfx .. friendlySfx
local enaName = enaPfx .. friendlySfx
local ansName = answerPfx .. friendlySfx
local friendlyName = friendlyPfx .. friendlySfx
local friendly = app:getGlobalPref( friendlyName )
items[#items + 1] = friendly
local sfx = k:sub( enaPfxLen + 1 )
lookup[friendly] = { enaName, ansName, friendlyName }
end
end
if #items > 0 then
local item = dia:getComboBoxSelection{
title = "Reset Selected Warnings",
subtitle = 'Select warning prompt to be reset...',
items = items,
}
if item then
local t = lookup[item]
if t then
app:setGlobalPref( t[1], false ) -- disable
app:setGlobalPref( t[2], "" ) -- kill answer.
app:setGlobalPref( t[3], "" ) -- kill friendly string.
app:show{ info="'^1' prompt has been reset.", item }
else
error( "no item lookup" )
end
-- else canceled.
end
else
app:show{ info="No warnings to reset." }
end
end } )
end,
},
vf:static_text {
title = "Reset selected warning, if you can figure out which one..."
},
}
advDbgSection[#advDbgSection + 1] = vf:spacer{ height=5 }
advDbgSection[#advDbgSection + 1] =
vf:row {
vf:checkbox {
title = "Enable Advanced Debug",
value = app:getGlobalPrefBinding( 'advDbgEna' ),
},
vf:push_button {
title = "Clear Log",
enabled = app:getGlobalPrefBinding( 'advDbgEna' ),
action = function( button )
app:clearDebugLog() -- wrapped internally
end,
},
vf:push_button {
title = "Show Log",
enabled = app:getGlobalPrefBinding( 'advDbgEna' ),
action = function( button )
app:showDebugLog() -- wrapped internally.
end,
},
vf:push_button {
title = "Debug Script",
enabled = app:getGlobalPrefBinding( 'advDbgEna' ),
action = function( button )
app:call( Call:new { name='Debug Script', async=true, guard=App.guardVocal, main=function( call )
if gbl:getValue( "DebugScript" ) then
DebugScript.showWindow()
else
app:show{ error="DebugScript.lua has not been loaded." }
end
end } )
end,
},
vf:push_button {
title = "Debug Options",
enabled = app:getGlobalPrefBinding( 'advDbgEna' ),
tooltip = "set an editor for displaying files...",
action = function( button )
app:call( Call:new { name='Debug Script', async=true, guard=App.guardVocal, main=function( call )
Debug.showOptionsWindow()
end } )
end
},
}
advDbgSection[#advDbgSection + 1] = vf:spacer { height = 5 }
advDbgSection[#advDbgSection + 1] =
vf:checkbox {
value = app:getGlobalPrefBinding( 'classDebugEnable' ),
enabled = app:getGlobalPrefBinding( 'advDbgEna' ),
title = "Restrict debugging to selected classes only:",
}
advDbgSection[#advDbgSection + 1] = vf:separator { fill_horizontal = 1 }
local items = Object.getClassItems()
local columns = 3
local rowItems = {}
for i = 1, #items do
repeat
local fullClassName = items[i]
-- dbg( "Item: ", fullClassName )
local propKey = Object.classRegistry[fullClassName].propKey
app:initGlobalPref( propKey, false )
rowItems[#rowItems + 1] = vf:checkbox {
title = fullClassName,
value = app:getGlobalPrefBinding( propKey ),
enabled = LrBinding.andAllKeys( app:getGlobalPrefKey( 'classDebugEnable' ), app:getGlobalPrefKey( 'advDbgEna' ) ),
width = share( "col_width" ),
}
if #rowItems == columns then
advDbgSection[#advDbgSection + 1] = vf:row( rowItems )
rowItems = {}
end
until true
end
if #rowItems > 0 then
advDbgSection[#advDbgSection + 1] = vf:row( rowItems )
end
advDbgSection[#advDbgSection + 1] = vf:spacer{ height = 10 }
advDbgSection[#advDbgSection + 1] =
vf:row {
vf:static_text {
title = "User:",
},
vf:edit_field {
value = app:getGlobalPrefBinding( 'username' ), -- plugin user name.
width_in_chars = 10,
tooltip = "In case plugin has user-specific programming - leave blank if you don't know what to enter.",
},
vf:spacer{ width = 5 },
vf:static_text {
title = "Lightroom Toolkit ID: ",
},
vf:static_text {
title = app:getInfo( "LrToolkitIdentifier" )
},
}
end
if advDbgSection and #advDbgSection then
return { infoSection, advDbgSection }
else
return { infoSection }
end
end
--- Sections for bottom of dialog method.
--
-- @usage *** Required for named preference set support - must be called in derived class if named preferences are to be supported and this method is overridden.
--
function Manager:sectionsForBottomOfDialogMethod( vf, props )
self.props = props -- property table changes when switching plugins in plugin manager.
local sections = {}
if gbl:getValue( 'metadataManager' ) then
if app:getInfo( 'LrMetadataProvider' ) and gbl:getValue( 'CustomMetadata' ) ~= nil and gbl:getValue( 'custMeta' ) ~= nil then
-- good
else
app:error( "metadata manager not configured properly" )
end
local metaSection = { bind_to_object = props }
sections[#sections + 1] = metaSection
metaSection.title = "Metadata Manager"
-- metaSection.synopsis = "Controls (no settings)" -- bind{ key=app:getGlobalPrefKey( 'blahBlah' ), object=prefs }
metaSection.spacing = vf:label_spacing()
metaSection[#metaSection + 1] =
vf:row {
vf:push_button {
title = "Save Custom Metadata",
width = share 'button_width',
action = function( button )
custMeta:save()
end,
},
vf:static_text {
title = "Saves custom metadata from catalog to individual files.",
},
}
metaSection[#metaSection + 1] =
vf:row {
vf:push_button {
title = "Read Custom Metadata",
width = share 'button_width',
action = function( button )
custMeta:read()
end,
},
vf:static_text {
title = "Reads custom metadata from saved files to catalog.",
},
}
--[[ *** doesn't see right to be in plugin manager.
metaSection[#metaSection + 1] =
vf:row {
vf:push_button {
title = "Sync Custom Metadata",
width = share 'button_width',
action = function( button )
custMeta:manualSync()
end,
},
vf:static_text {
title = "Copies custom metadata from most selected photo to other selected photos.",
},
}
--]]
end
if Preferences ~= nil then
local appSection = { bind_to_object = props }
sections[#sections + 1] = appSection
appSection.title = "Preset Manager"
appSection.synopsis = bind{ key=app:getGlobalPrefKey( 'presetName' ), object=prefs }
appSection.spacing = vf:label_spacing()
if app:isAdvDbgEna() then
appSection[#appSection + 1] =
vf:row {
vf:push_button {
title = "Clear All Settings",
props = props,
action = function( button )
app:call( Call:new{ name=button.title, async = false, main = function()
local info = "*** Click 'Clear All' to thoroughly wipe all settings associated with this plugin, or click 'Reset Globals' to just reset global preferences to factory default values.\n \nNote: No preference support files will be deleted, and only in the case of 'Reset Globals' - no preset settings will be affected."
local answer = app:show{ info=info, buttons={ dia:btn( "Clear All", 'ok' ), dia:btn( "Reset Globals", 'other' ) } }
if answer == 'ok' then
app:clearAllPrefs( button.props ) -- and load properties with default set.
app:show{ info="All settings have been cleared - *** IMPORTANT: you must reload plugin now to avoid problems (consider re-enabling advanced debug first)." }
elseif answer == 'other' then
app.prefMgr:loadGlobalDefaults()
app:show{ info="Global preference settings have been reset to factory defaults - named and un-named preset settings were unaffected, however you may have to re-select." }
elseif answer == 'cancel' then
-- dbg( "Canceled" )
else
error( "whats the answer?" )
end
end } )
end
},
vf:static_text {
title = str:format( 'Clear All ^1 settings (or just reset globals to factory defaults).', app:getAppName() ),
},
}
end
appSection[#appSection + 1] = vf:spacer{ height = 3 }
local presetTb
if app.prefMgr:isBackedByFile() then
presetTb = "Preset selection defines basic settings, as visible in 'Plug-in Manager',\nas well as advanced settings in \"backing file\"."
else
presetTb = "Preset selection defines settings as seen in other sections of 'Plug-in Manager'"
end
if true then -- new way
appSection[#appSection + 1] = vf:row {
vf:static_text {
title = "Preset: ",
},
app.prefMgr:makePresetPopup {
props = props,
valueBindTo = prefs,
valueKey = app:getGlobalPrefKey( 'presetName' ),
callback = function( v )
-- popup assures preset name change triggers the callback.
app.prefMgr:switchPreset( self.props )
end
},
vf:static_text {
title = presetTb,
},
}
else -- save for a while
appSection[#appSection + 1] =
vf:row {
vf:edit_field {
bind_to_object = prefs,
value = app:getGlobalPrefBinding( 'presetName' ),
width = share( 'pref_set_button_width' ),
},
vf:static_text {
title = str:format( 'Enter preset name - to be created if not already existing, else loaded.\n(You must enter something other than \'Default\' to edit advanced settings)' ),
},
}
appSection[#appSection + 1] =
vf:row {
vf:push_button {
title = 'Select Preset',
width = share( 'pref_set_button_width' ),
props = props,
action = function( button )
app:call( Call:new{ name = button.title, async=true, guard = App.guardSilent, main=function( call )
local items = app.prefMgr:getPresetNames() -- *** Gui-mngr and the pref-mgr are friends.
if #items > 1 then
local param = {}
param.title = 'Choose Preset'
param.subtitle = 'Choose a preset to load settings'
param.items = items
local sel,msg = dialog:getComboBoxSelection( param )
-- dbg( "sel", sel )
if sel then
local presetName = app.prefMgr:getPresetName()
if presetName == sel then
local presetKey = app:getGlobalPrefKey( 'presetName' )
--Debug.pause( presetKey )
app:presetNameChange( button.props, presetKey, sel ) -- force a change to be processed, so config file is reloaded.
else
--Debug.pause( sel )
app:setGlobalPref( 'presetName', sel ) -- change handler takes it from here.
end
end
else
app:show{ warning="There are no presets other than 'Default' - try entering a name in the preset name box..." }
end
end } )
end
},
vf:static_text {
title = str:format( 'Choose preset by name and load corresponding settings.' ),
},
}
appSection[#appSection + 1] =
vf:row {
vf:push_button {
title = 'Delete Preset',
enabled = bind{ key=app:getGlobalPrefKey( 'presetName' ), bind_to_object=prefs, transform=function( value, fromModel )
if str:is( value ) and value ~= 'Default' then
return true
else
return false
end
end },
width = share( 'pref_set_button_width' ),
props = props,
action = function( button )
app:call( Call:new{ name='Delete Pref Preset', main = function()
app:deletePrefPreset( button.props )
end } )
end
},
vf:static_text {
title = str:format( 'Delete this preset and all settings associated with it.\n(the \'Default\' preset can not be deleted)' ),
},
}
appSection[#appSection + 1] =
vf:row {
vf:push_button {
title = 'Load Factory Defaults',
width = share( 'pref_set_button_width' ),
props = props,
action = function( button )
app:call( Call:new{ name='Delete Pref Preset', main = function()
local presetName = app.prefMgr:getPresetName()
if dialog:isOk( str:fmt( "Overwrite ^1 settings with factory defaults?", presetName ) ) then
app.prefMgr:loadDefaults( button.props ) -- nothing returned.
app:show{ info="Defaults were successfully loaded.", actionPrefKey="Default preferences loaded" }
end
end } )
end
},
vf:static_text {
title = str:format( 'Reset settings for this preset to factory default values.' ),
},
}
if app.prefMgr and app.prefMgr:isBackedByFile() then -- use app method?
appSection[#appSection + 1] =
vf:row {
vf:push_button {
title = 'Edit Advanced Settings',
width = share( 'pref_set_button_width' ),
props = props,
enabled = LrView.bind {
key = app:getGlobalPrefKey( 'presetName' ),
bind_to_object = prefs,
transform = function( val, toUi )
if app.prefMgr:getPresetName() == 'Default' then
return false
else
return true
end
end,
},
action = function( button )
app:call( Call:new{ name=button.title, async=true, main = function()
assert( app.prefMgr:getPresetName() ~= 'Default', "config file edit button shouldn't be enabled for default preset" )
local file, name = app.prefMgr:getPrefSupportFile()
if fso:existsAsFile( file ) then
app:show{ info="In a moment, '^1' will open in the default app for you to edit. After editing, be sure to click the 'Reload Advanced Settings' button (or reload plugin).",
subs = { file },
actionPrefKey = "Reminder to reload after editing advanced settings" }
app:openFileInDefaultApp( file, true ) -- true => prompt before and after opening.
else
app:show{ error="Not existing: ^1", file } -- Its created when the set is created, and each time when switching sets - so simple error here OK.
end
end } )
end
},
vf:static_text {
title = str:format( 'Edit plugin configuration file corresponding to this preset.\n(if this is disabled/greyed-out, then you need to enter a preset name above)' ),
},
}
appSection[#appSection + 1] =
vf:row {
vf:push_button {
title = 'Reload Advanced Settings',
width = share( 'pref_set_button_width' ),
props = props,
action = function( button )
app:call( Call:new{ name=button.title, main = function()
-- make this single method: ###1
local file, name = app.prefMgr:getPrefSupportFile()
local presetName = app.prefMgr:getPresetName()
if fso:existsAsFile( file ) then
app.prefMgr:loadPrefFile( file ) -- load props used to do this (throws error if probs).
assert( name == LrPathUtils.leafName( file ), "Preset file naming anomaly" )
local dir = LrPathUtils.parent( file )
app:show{ info="Reloaded advanced settings for ^1 preset, by re-reading preset backing file: ^2", presetName, file }
else
app:show{ error="Unable to reload advanced settings for ^1, preset backing file not found:\n^2", presetName, file } -- Its created when the set is created, and each time when switching sets - so simple error here OK.
end
end } )
end
},
vf:static_text {
title = str:format( 'Reload recently edited plugin configuration file.\n(be sure to click this after editing advanced settings)' ),
},
}
end
end
appSection[#appSection + 1] = vf:spacer{ height = 5 }
appSection[#appSection + 1] =
vf:row {
vf:push_button {
title = "|<",
action = function( button )
app:call( Call:new{ name="First preset", async=false, guard=App.guardSilent, main=function( call )
-- Note: handling @10/Oct/2012 4:32 assures default preset is always first, and other preset-names are sorted alphabetically: ascending.
app:setGlobalPref( 'presetName', 'Default' )
end } )
end
},
vf:push_button {
title = "<",
action = function( button )
app:call( Call:new{ name="Previous preset", async=false, guard=App.guardSilent, main=function( call )
local presetName = app.prefMgr:getPresetName()
local presetNames = app.prefMgr:getPresetNames()
local targetIndex
for i, name in ipairs( presetNames ) do
if name == presetName then
targetIndex = i - 1
break
end
end
if targetIndex then
if targetIndex > 0 then
app:setGlobalPref( 'presetName', presetNames[targetIndex] )
end
end
end } )
end
},
vf:push_button {
title = ">",
action = function( button )
app:call( Call:new{ name="Next preset", async=false, guard=App.guardSilent, main=function( call )
local presetName = app.prefMgr:getPresetName()
local presetNames = app.prefMgr:getPresetNames()
local targetIndex
for i, name in ipairs( presetNames ) do
if name == presetName then
targetIndex = i + 1
break
end
end
if targetIndex then
if targetIndex <= #presetNames then
app:setGlobalPref( 'presetName', presetNames[targetIndex] )
--else
-- app:setGlobalPref( 'presetName', 'Default' )
end
--else
-- app:setGlobalPref( 'presetName', 'Default' )
end
end } )
end
},
vf:push_button {
title = ">|",
action = function( button )
app:call( Call:new{ name="Last preset", async=false, guard=App.guardSilent, main=function( call )
local presetNames = app.prefMgr:getPresetNames()
local index = #presetNames
while not str:is( presetNames[index] ) and ( index > 1 ) do
Debug.pause( "No preset at " .. str:to( index ) )
index = index - 1
end
if str:is( presetNames[index] ) then
app:setGlobalPref( 'presetName', presetNames[index] )
else
Debug.logn( "No last preset found" )
end
end } )
end
},
vf:static_text {
title = "First, Previous, Next, Last preset..."
},
}
end
return sections
end
--- Called when dialog box is being exited for whatever reason.
--
-- <p>Typically a good place to make sure settings have been saved.</p>
--
-- @usage The base method just saves everything - override to descriminate.
--
function Manager:endDialogMethod( props )
-- dbg( "End-of-dialog, saving properties..." )
local count = 0
self.props = props
assert( props ~= prefs, "how can prefs be props?" )
for k,v in props:pairs() do
if app:isVerbose() then
-- dbg( "Saving: ", str:format( "^1 ^2: ^3", app:getGlobalPref( 'presetName' ), str:to( k ), str:to( v ) ) )
end
if str:isStartingWith( k, '_global_' ) then -- why would properties have -global- in them? - isn't that just for prefs???
dbg( "What's this globally prefixed key doing in the manager properties?:", k ) -- this isn't happening - perhaps it was before the -global- handling was debugged.
else
count = count + 1
dbg( "Saving manager property as pref, name: ", k, " value: ", str:to( v ) )
app:setPref( k, v )
end
end
-- dbg( "End-of-dialog, properties saved: ", str:to( count ) )
end
-- *** Save as reminder (the concept is used elsewhere, but not the method).
-- Set property and yield, so change handler can run.
--
--function Manager:setPropAndYield( name, value )
-- self.props[name] = value
-- LrTasks.yield()
--end
---------------------------------------------------------------------------------
--- Preference change handler.
--
-- Static function required by Lightroom.
-- Derived classes should override method instead.
--
function Manager.prefChangeHandler( _id, _prefs, name, value )
assert( Manager.manager ~= nil, "Manager nil" )
app:call( Call:new{ name="mgrPrefChgHdlr", async = true, guard = App.guardSilent, main = function( call ) -- Made async 28/Nov/2011 9:57 ###4 - delete this comment if no problems by 2013
-- @13/May/2012 3:15 I had a problem, but maybe had to do with multiple instances of plugin running - prompt to switch to created preset was preceding the prompt to create the preset!
-- switching back to synchronous caused a different problem - preferences support file seemed to have disappeared (probably before it was created..
Manager.manager:prefChangeHandlerMethod( _id, _prefs, name, value, call )
end } )
end
--- Property change handler.
--
-- Static function required by Lightroom.
-- Derived classes should override method instead.
--
function Manager.propChangeHandler( id, props, name, value )
assert( Manager.manager ~= nil, "Manager nil" )
-- Debug.pause( id, props, name, value )
app:call( Call:new{ name="mgrPropChgHdlr", async = true, guard = App.guardSilent, main = function( call ) -- ditto ###4
--[[ *** save for posterity: its really not the default prefs that need to be protected, its the default backing file that must remain virginal (so plugin update does not overwrite).
if app.prefMgr then
local presetName = app.prefMgr:getPresetName()
if presetName == 'Default' then
local r = app:getPref( name ) -- restore previous value.
if r ~= value then
app:show{ warning="A recent code change no longer permits changing the default (un-named) preferences. Please use a named preset for all customized preferences (hint: enter a name in Preset Manager section).\n \nPrevious value will be restored: '^1'.", str:to( r ) }
props[name] = r -- restore previous value.
return
end
end
end--]]
-- fall-through => either preferences are un-managed, or property represents a named preset preference.
Manager.manager:propChangeHandlerMethod( props, name, value, call ) -- ID is not passed through, for backward compatibility.
-- only value I can think of in having the id would be to remove the listener, and so far that hasn't been needed.
-- Anyway, the 'id' is 'Manager'.
end } )
end
--- Called when dialog box is being initialized for plugin.
--
-- Static function simply creates an appropriate manager instance
-- and dispatches its start-dialog method.
--
-- Derived classes should override methods, not static functions.
--
function Manager.startDialog( props )
if Manager.manager == nil then
Manager.manager = objectFactory:newObject( 'Manager', { props=props } )
end
Manager.manager:startDialogMethod( props )
end
--- Called when dialog box is being exited for whatever reason.
--
-- Static function required by Lightroom.
-- Derived classes should override method instead.
--
function Manager.endDialog( props )
-- assert( Manager.manager ~= nil, "Manager nil" )
if Manager.manager then
Manager.manager:endDialogMethod( props )
-- else let it go - usually means there was an error loading it upon init or start-dialog.
end
end
--- Create top section of dialog.
--
-- Static function required by Lightroom.
-- Derived classes should override method instead.
--
function Manager.sectionsForTopOfDialog( vf, props )
if Manager.manager == nil then -- this is never necessary when everything is in straight, but allows for a much more intelligible error message.
Manager.manager = objectFactory:newObject( 'Manager', { props=props } )
end
assert( Manager.manager ~= nil, "Manager nil" )
return Manager.manager:sectionsForTopOfDialogMethod( vf, props )
end
--- Create bottom section with settings.
--
-- Static function required by Lightroom.
-- Derived classes should override method instead.
--
function Manager.sectionsForBottomOfDialog( vf, props )
if Manager.manager == nil then -- this is never necessary when everything is in straight, but allows for a much more intelligible error message.
Manager.manager = objectFactory:newObject( 'Manager', { props=props } )
end
assert( Manager.manager ~= nil, "Manager nil" )
return Manager.manager:sectionsForBottomOfDialogMethod( vf, props )
end
return Manager
|
-- ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
function lure.rom.newInlineBoxObject( pParamTable )
local self = lure.rom.newBoxObject( {nodeType=1, boxType=2, formatingContext=2, nodeDesc="ROMInlineBoxNode"} )
--===================================================================
-- PROPERTIES =
--===================================================================
self.layoutResponse = lure.rom.newLayoutResponseObject()
---------------------------------------------------------------------
--====================================================================
-- METHODS =
--====================================================================
self.layout = function()
--lure.throw(1, "callling layout on node: " .. tostring(self.nodeDesc) .. "(FC:".. tostring(self.formatingContext) .." BT:".. tostring(self.boxType) .." NT:".. tostring(self.nodeType) ..")")
self.layoutResponse.clear()
self.computedStyle.display = lure.rom.computeBoxRenderStyleDisplay( self )
self.computedStyle.position = lure.rom.computeBoxRenderStylePosition( self )
self.computedStyle.backgroundColor = lure.rom.computeBoxRenderStyleBackgroundColor( self )
self.computedStyle.top = lure.rom.computeBoxRenderStyleTop( self )
self.computedStyle.left = lure.rom.computeBoxRenderStyleLeft( self )
self.computedStyle.width = lure.rom.computeBoxRenderStyleWidth( self )
--do child layouts
lure.rom.layout.doInlineChildLayouts( self )
self.computedStyle.height = lure.rom.computeBoxRenderStyleHeight( self )
self.layoutResponse.type = 3
return self.layoutResponse
end
---------------------------------------------------------------------
return self
end
-- ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
|
return {
name = "attack_or_patrol",
desc = "demo hahaha",
parent_name = "",
keys = {
{
name = "OriginPosition",
desc = "",
is_static = false,
type = 5,
type_class_name = "",
},
{
name = "TargetActor",
desc = "x2 haha",
is_static = false,
type = 10,
type_class_name = "",
},
{
name = "AcceptableRadius",
desc = "x3 haha",
is_static = false,
type = 3,
type_class_name = "",
},
{
name = "CurChooseSkillId",
desc = "x4 haha",
is_static = false,
type = 2,
type_class_name = "",
},
},
}
|
modifier_template = class({})
--------------------------------------------------------------------------------
-- Classifications
function modifier_template:IsHidden()
return false
end
function modifier_template:IsDebuff()
return false
end
function modifier_template:IsStunDebuff()
return false
end
function modifier_template:GetAttributes()
return MODIFIER_ATRRIBUTE_XX + MODIFIER_ATRRIBUTE_YY
end
function modifier_template:IsPurgable()
return true
end
--------------------------------------------------------------------------------
-- Aura
function modifier_template:IsAura()
return true
end
function modifier_template:GetModifierAura()
return "modifier_template_effect"
end
function modifier_template:GetAuraRadius()
return float
end
function modifier_template:GetAuraSearchTeam()
return DOTA_UNIT_TARGET_TEAM_XX
end
function modifier_template:GetAuraSearchType()
return DOTA_UNIT_TARGET_XX + DOTA_UNIT_TARGET_YY + ...
end
function modifier_template:GetAuraEntityReject( hEntity )
if IsServer() then
end
return false
end
--------------------------------------------------------------------------------
-- Initializations
function modifier_template:OnCreated( kv )
-- references
self.special_value = self:GetAbility():GetSpecialValueFor( "special_value" ) -- special value
-- Start interval
self:StartIntervalThink( self.interval )
self:OnIntervalThink()
end
function modifier_template:OnRefresh( kv )
end
function modifier_template:OnDestroy( kv )
end
--------------------------------------------------------------------------------
-- Modifier Effects
function modifier_template:DeclareFunctions()
local funcs = {
MODIFIER_PROPERTY_XX,
MODIFIER_EVENT_YY,
}
return funcs
end
--------------------------------------------------------------------------------
-- Status Effects
function modifier_template:CheckState()
local state = {
[MODIFIER_STATE_XX] = true,
}
return state
end
--------------------------------------------------------------------------------
-- Interval Effects
function modifier_template:OnIntervalThink()
end
--------------------------------------------------------------------------------
-- Graphics & Animations
function modifier_template:GetEffectName()
return "particles/string/here.vpcf"
end
function modifier_template:GetEffectAttachType()
return PATTACH_ABSORIGIN_FOLLOW
end
function modifier_template:PlayEffects()
-- Get Resources
local particle_cast = "string"
local sound_cast = "string"
-- Get Data
-- Create Particle
local effect_cast = ParticleManager:CreateParticle( particle_cast, PATTACH_NAME, hOwner )
ParticleManager:SetParticleControl( effect_cast, iControlPoint, vControlVector )
ParticleManager:SetParticleControlEnt(
effect_cast,
iControlPoint,
hTarget,
PATTACH_NAME,
"attach_name",
vOrigin, -- unknown
bool -- unknown, true
)
ParticleManager:SetParticleControlForward( effect_cast, iControlPoint, vForward )
SetParticleControlOrientation( effect_cast, iControlPoint, vForward, vRight, vUp )
ParticleManager:ReleaseParticleIndex( effect_cast )
-- buff particle
self:AddParticle(
nFXIndex,
bDestroyImmediately,
bStatusEffect,
iPriority,
bHeroEffect,
bOverheadEffect
)
-- Create Sound
EmitSoundOnLocationWithCaster( vTargetPosition, sound_location, self:GetCaster() )
EmitSoundOn( sound_target, target )
end
|
-- Use of this source code is governed by the Apache 2.0 license; see COPYING.
module(..., package.seeall)
local usage = require("program.snabbmark.README_inc")
local basic_apps = require("apps.basic.basic_apps")
local pci = require("lib.hardware.pci")
local ethernet = require("lib.protocol.ethernet")
local lib = require("core.lib")
local ffi = require("ffi")
local C = ffi.C
local pmu = require('lib.pmu')
local has_pmu_counters, err = pmu.is_available()
if not has_pmu_counters then
io.stderr:write('No PMU available: '..err..'\n')
else
pmu.setup()
end
function run (args)
local command = table.remove(args, 1)
if command == 'basic1' and #args == 1 then
basic1(unpack(args))
elseif command == 'nfvconfig' and #args == 3 then
nfvconfig(unpack(args))
elseif command == 'solarflare' and #args >= 2 and #args <= 3 then
solarflare(unpack(args))
elseif command == 'intel1g' and #args >= 2 and #args <= 3 then
intel1g(unpack(args))
elseif command == 'esp' and #args >= 2 then
esp(unpack(args))
elseif command == 'hash' and #args <= 1 then
hash(unpack(args))
elseif command == 'ctable' and #args == 0 then
ctable(unpack(args))
elseif command == 'checksum' and #args == 0 then
checksum_bench(unpack(args))
else
print(usage)
main.exit(1)
end
end
function gbits (bps)
return (bps * 8) / (1024^3)
end
function basic1 (npackets)
npackets = tonumber(npackets) or error("Invalid number of packets: " .. npackets)
local c = config.new()
-- Simple topology:
-- .------.
-- Source ---> Tee Sink
-- `------'
-- Source generates packets, Tee duplicates them, Sink receives
-- both duplicates.
config.app(c, "Source", basic_apps.Source)
config.app(c, "Tee", basic_apps.Tee)
config.app(c, "Sink", basic_apps.Sink)
config.link(c, "Source.tx -> Tee.rx")
config.link(c, "Tee.tx1 -> Sink.rx1")
config.link(c, "Tee.tx2 -> Sink.rx2")
engine.configure(c)
local start = C.get_monotonic_time()
timer.activate(timer.new("null", function () end, 1e6, 'repeating'))
while link.stats(engine.app_table.Source.output.tx).txpackets < npackets do
engine.main({duration = 0.01, no_report = true})
end
local finish = C.get_monotonic_time()
local runtime = finish - start
local packets = link.stats(engine.app_table.Source.output.tx).txpackets
engine.report()
print()
print(("Processed %.1f million packets in %.2f seconds (rate: %.1f Mpps)."):format(packets / 1e6, runtime, packets / runtime / 1e6))
end
function nfvconfig (confpath_x, confpath_y, nloads)
local nfvconfig = require("program.snabbnfv.nfvconfig")
nloads = tonumber(nloads)
or error("Invalid number of iterations: " .. nloads)
local pciaddr = lib.getenv("SNABB_PCI0")
if not pciaddr then
print("SNABB_PCI0 not set.")
os.exit(engine.test_skipped_code)
end
local load_times, apply_times = {}, {}
for i=1, nloads do
-- Load and apply confpath_x.
engine.configure(nfvconfig.load(confpath_x, pciaddr, "/dev/null"))
-- Measure loading y.
local start_load = C.get_monotonic_time()
local c = nfvconfig.load(confpath_y, pciaddr, "/dev/null")
local end_load = C.get_monotonic_time()
-- Measure apply x -> y.
local start_apply = C.get_monotonic_time()
engine.configure(c)
local end_apply = C.get_monotonic_time()
-- Push results.
table.insert(load_times, end_load - start_load)
table.insert(apply_times, end_apply - start_apply)
end
engine.report()
print()
-- Print results.
local load_mean, load_max = sumf(unpack(load_times))/#load_times, math.max(unpack(load_times))
print("load_mean:", ("%.4fs"):format(load_mean))
print("load_max:", ("%.4fs"):format(load_max))
local apply_mean, apply_max = sumf(unpack(apply_times))/#apply_times, math.max(unpack(apply_times))
print("apply_mean:", ("%.4fs"):format(apply_mean))
print("apply_max:", ("%.4fs"):format(apply_max))
-- Overall score is load_mean+apply_mean per second.
print("score: ", ("%.2f"):format(1/(apply_mean + load_mean)))
end
function sumf(a, ...) return a and a + sumf(...) or 0 end
Source = {}
function Source:new(size)
return setmetatable({}, {__index=Source})
end
function Source:pull()
for _, o in ipairs(self.output) do
for i = 1, engine.pull_npackets do
local p = packet.allocate()
ffi.copy(p.data, self.to_mac_address, 6)
ffi.copy(p.data + 6, self.from_mac_address, 6)
p.length = self.size
link.transmit(o, p)
end
end
end
function Source:set_packet_addresses(from_mac_address, to_mac_address)
self.from_mac_address, self.to_mac_address = from_mac_address, to_mac_address
print(string.format("Sending from %02x:%02x:%02x:%02x:%02x:%02x to %02x:%02x:%02x:%02x:%02x:%02x",
self.from_mac_address[0],
self.from_mac_address[1],
self.from_mac_address[2],
self.from_mac_address[3],
self.from_mac_address[4],
self.from_mac_address[5],
self.to_mac_address[0],
self.to_mac_address[1],
self.to_mac_address[2],
self.to_mac_address[3],
self.to_mac_address[4],
self.to_mac_address[5]))
end
function Source:set_packet_size(size)
self.size = size
end
function solarflare (npackets, packet_size, timeout)
npackets = tonumber(npackets) or error("Invalid number of packets: " .. npackets)
packet_size = tonumber(packet_size) or error("Invalid packet size: " .. packet_size)
if timeout then
timeout = tonumber(timeout) or error("Invalid timeout: " .. timeout)
end
local function load_driver ()
return require("apps.solarflare.solarflare").SolarFlareNic
end
local status, SolarFlareNic = pcall(load_driver)
if not status then
print(SolarFlareNic)
os.exit(engine.test_skipped_code)
end
local pciaddr0 = lib.getenv("SNABB_PCI_SOLARFLARE0") or lib.getenv("SNABB_PCI0")
local pciaddr1 = lib.getenv("SNABB_PCI_SOLARFLARE1") or lib.getenv("SNABB_PCI1")
local send_device = pciaddr0 and pci.device_info(pciaddr0)
local receive_device = pciaddr1 and pci.device_info(pciaddr1)
if not send_device
or send_device.driver ~= 'apps.solarflare.solarflare'
or not receive_device
or receive_device.driver ~= 'apps.solarflare.solarflare'
then
print("SNABB_PCI_SOLARFLARE[0|1]/SNABB_PCI[0|1] not set or not suitable.")
os.exit(engine.test_skipped_code)
end
print(string.format("Sending through %s (%s), receiving through %s (%s)",
send_device.interface, send_device.pciaddress,
receive_device.interface, receive_device.pciaddress))
local c = config.new()
-- Topology:
-- Source -> Solarflare NIC#1 => Solarflare NIC#2 -> Sink
config.app(c, "source", Source)
config.app(c, send_device.interface, SolarFlareNic, {ifname=send_device.interface, mac_address = ethernet:pton("02:00:00:00:00:01")})
config.app(c, receive_device.interface, SolarFlareNic, {ifname=receive_device.interface, mac_address = ethernet:pton("02:00:00:00:00:02")})
config.app(c, "sink", basic_apps.Sink)
config.link(c, "source.tx -> " .. send_device.interface .. ".rx")
config.link(c, receive_device.interface .. ".tx -> sink.rx")
engine.configure(c)
engine.app_table.source:set_packet_addresses(engine.app_table[send_device.interface].mac_address,
engine.app_table[receive_device.interface].mac_address)
engine.app_table.source:set_packet_size(packet_size)
engine.Hz = false
local start = C.get_monotonic_time()
timer.activate(timer.new("null", function () end, 1e6, 'repeating'))
local n = 0
local n_max
if timeout then
n_max = timeout * 100
end
while link.stats(engine.app_table.source.output.tx).txpackets < npackets
and (not timeout or n < n_max)
do
engine.main({duration = 0.01, no_report = true})
n = n + 1
end
local finish = C.get_monotonic_time()
local runtime = finish - start
local packets = link.stats(engine.app_table.source.output.tx).txpackets
engine.report()
engine.app_table[send_device.interface]:report()
engine.app_table[receive_device.interface]:report()
print()
print(("Processed %.1f million packets in %.2f seconds (rate: %.1f Mpps, %.2f Gbit/s)."):format(packets / 1e6,
runtime, packets / runtime / 1e6,
gbits(packets * packet_size / runtime)))
if link.stats(engine.app_table.source.output.tx).txpackets < npackets then
print("Packets lost. Test failed!")
main.exit(1)
end
end
function intel1g (npackets, packet_size, timeout)
npackets = tonumber(npackets) or error("Invalid number of packets: " .. npackets)
packet_size = tonumber(packet_size) or error("Invalid packet size: " .. packet_size)
if timeout then
timeout = tonumber(timeout) or error("Invalid timeout: " .. timeout)
end
local function load_driver ()
return require("apps.intel.intel1g").Intel1g
end
local status, Intel1gNic = pcall(load_driver)
if not status then
print(Intel1gNic)
os.exit(engine.test_skipped_code)
end
local pciaddr0 = lib.getenv("SNABB_PCI0")
local pciaddr1 = lib.getenv("SNABB_PCI1")
local send_device = pciaddr0 and pci.device_info(pciaddr0)
local receive_device = pciaddr1 and pci.device_info(pciaddr1)
print("send_device= ", send_device, " receive_device= ", receive_device)
if not send_device
or send_device.driver ~= 'apps.intel.intel1g'
or not receive_device
or receive_device.driver ~= 'apps.intel.intel1g'
then
print("SNABB_PCI[0|1] not set, or not suitable Intel i210/i350 NIC.")
os.exit(engine.test_skipped_code)
end
send_device.interface= "tx1GE"
receive_device.interface= "rx1GE"
print(string.format("Sending through %s (%s), receiving through %s (%s)",
send_device.interface, send_device.pciaddress,
receive_device.interface, receive_device.pciaddress))
local c = config.new()
-- Topology:
-- Source -> Intel1g NIC#1 => Intel1g NIC#2 -> Sink
config.app(c, "source", Source)
--config.app(c, send_device.interface, Intel1gNic, {ifname=send_device.interface, mac_address = ethernet:pton("02:00:00:00:00:01")})
--config.app(c, receive_device.interface, Intel1gNic, {ifname=receive_device.interface, mac_address = ethernet:pton("02:00:00:00:00:02")})
config.app(c, send_device.interface, Intel1gNic, {pciaddr=pciaddr0})
config.app(c, receive_device.interface, Intel1gNic, {pciaddr=pciaddr1, rxburst=512})
config.app(c, "sink", basic_apps.Sink)
config.link(c, "source.tx -> " .. send_device.interface .. ".input")
config.link(c, receive_device.interface .. ".output -> sink.rx")
engine.configure(c)
--engine.app_table.source:set_packet_addresses(engine.app_table[send_device.interface].mac_address,
-- engine.app_table[receive_device.interface].mac_address)
engine.app_table.source:set_packet_addresses(ethernet:pton("02:00:00:00:00:01"),
ethernet:pton("02:00:00:00:00:02"))
engine.app_table.source:set_packet_size(packet_size)
engine.Hz = false
local start = C.get_monotonic_time()
timer.activate(timer.new("null", function () end, 1e6, 'repeating'))
local n = 0
local n_max
if timeout then
n_max = timeout * 100
end
while link.stats(engine.app_table.source.output.tx).txpackets < npackets
and (not timeout or n < n_max)
do
engine.main({duration = 0.01, no_report = true})
n = n + 1
end
local finish = C.get_monotonic_time()
local runtime = finish - start
local txpackets = link.stats(engine.app_table.source.output.tx).txpackets
local rxpackets = link.stats(engine.app_table.sink.input.rx).rxpackets
engine.report()
engine.app_table[send_device.interface]:report()
engine.app_table[receive_device.interface]:report()
print()
print(("Processed %.1f million packets in %.2f seconds (rate: %.1f Mpps, %.2f Gbit/s, %.2f %% packet loss)."):format(
txpackets / 1e6, runtime,
txpackets / runtime / 1e6,
((txpackets * packet_size * 8) / runtime) / (1024*1024*1024),
(txpackets - rxpackets) *100 / txpackets
))
if link.stats(engine.app_table.source.output.tx).txpackets < npackets then
print("Packets lost. Test failed!")
main.exit(1)
end
end
function esp (npackets, packet_size, mode, direction, aead)
aead = aead or "aes-gcm-16-icv"
local esp = require("lib.ipsec.esp")
local ethernet = require("lib.protocol.ethernet")
local ipv6 = require("lib.protocol.ipv6")
local datagram = require("lib.protocol.datagram")
npackets = assert(tonumber(npackets), "Invalid number of packets: " .. npackets)
packet_size = assert(tonumber(packet_size), "Invalid packet size: " .. packet_size)
local payload_size = packet_size - ethernet:sizeof() - ipv6:sizeof()
local payload = ffi.new("uint8_t[?]", payload_size)
local d = datagram:new(packet.allocate())
local ip = ipv6:new({})
ip:payload_length(payload_size)
d:payload(payload, payload_size)
d:push(ip)
if not (mode == "tunnel") then
local eth = ethernet:new({type=0x86dd})
d:push(eth)
end
local plain = d:packet()
local conf = { spi = 0x0,
aead = aead,
key = "00112233445566778899AABBCCDDEEFF"..
"00112233445566778899AABBCCDDEEFF",
salt = "00112233"}
local enc, dec = esp.encrypt:new(conf), esp.decrypt:new(conf)
local encap, decap
if mode == "tunnel" then
encap = function (p) return enc:encapsulate_tunnel(p, 41) end
decap = function (p) return (dec:decapsulate_tunnel(p)) end
else
encap = function (p) return enc:encapsulate_transport6(p) end
decap = function (p) return dec:decapsulate_transport6(p) end
end
if direction == "encapsulate" then
local function test_encapsulate ()
for i = 1, npackets do
packet.free(encap(packet.clone(plain)))
end
end
local start = C.get_monotonic_time()
if has_pmu_counters then
pmu.profile(test_encapsulate)
else
test_encapsulate()
end
local finish = C.get_monotonic_time()
local bps = (packet_size * npackets) / (finish - start)
print(("Encapsulation (packet size = %d): %.2f Gbit/s")
:format(packet_size, gbits(bps)))
else
local encapsulated = encap(packet.clone(plain))
local function test_decapsulate ()
for i = 1, npackets do
packet.free(decap(packet.clone(encapsulated)))
dec.seq.no = 0
dec.window[0] = 0
end
end
local start = C.get_monotonic_time()
if has_pmu_counters then
pmu.profile(test_decapsulate)
else
test_decapsulate()
end
local finish = C.get_monotonic_time()
local bps = (packet_size * npackets) / (finish - start)
print(("Decapsulation (packet size = %d): %.2f Gbit/s")
:format(packet_size, gbits(bps)))
end
end
local function measure(f, iterations)
local set
if has_pmu_counters then set = pmu.new_counter_set() end
local start = C.get_time_ns()
if has_pmu_counters then pmu.switch_to(set) end
local res = f(iterations)
if has_pmu_counters then pmu.switch_to(nil) end
local stop = C.get_time_ns()
local ns = tonumber(stop-start)
local cycles = nil
if has_pmu_counters then cycles = pmu.to_table(set).cycles end
return cycles, ns, res
end
local function test_perf(f, iterations, what)
require('jit').flush()
io.write(tostring(what or f)..': ')
io.flush()
local cycles, ns, res = measure(f, iterations)
if cycles then
cycles = cycles/iterations
io.write(('%.2f cycles, '):format(cycles))
end
ns = ns/iterations
io.write(('%.2f ns per iteration (result: %s)\n'):format(
ns, tostring(res)))
return res
end
function hash (key_size)
if key_size then
key_size = assert(tonumber(key_size))
else
key_size = 4
end
local value_t = ffi.typeof("uint8_t[$]", key_size)
local band = require('bit').band
local fill = require('ffi').fill
local function baseline_hash(ptr) return ptr[0] end
local murmur = require('lib.hash.murmur').MurmurHash3_x86_32:new()
local function murmur_hash(v)
return murmur:hash(v, key_size, 0ULL).u32[0]
end
local lib_siphash = require('lib.hash.siphash')
local sip_hash_1_2_opts = { size=key_size, c=1, d=2 }
local sip_hash_2_4_opts = { size=key_size, c=2, d=4 }
local function test_scalar_hash(iterations, hash)
local value = ffi.new(ffi.typeof('uint8_t[$]', key_size))
local result
for i=1,iterations do
fill(value, key_size, band(i, 255))
result = hash(value)
end
return result
end
local function test_parallel_hash(iterations, hash, width)
local value = ffi.new('uint8_t[?]', key_size*width)
local result = ffi.new('uint32_t[?]', width)
for i=1,iterations,width do
fill(value, key_size*width, band(i+width-1, 255))
hash(value, result)
end
return result[width-1]
end
local function hash_tester(hash)
return function(iterations)
return test_scalar_hash(iterations, hash)
end
end
local function sip_hash_tester(opts, width)
local opts = lib.deepcopy(opts)
opts.size = key_size
if width > 1 then
opts.width = width
local hash = lib_siphash.make_multi_hash(opts)
return function(iterations)
return test_parallel_hash(iterations, hash, width)
end
else
return hash_tester(lib_siphash.make_hash(opts))
end
end
test_perf(hash_tester(baseline_hash), 1e8, 'baseline')
test_perf(hash_tester(murmur_hash), 1e8, 'murmur hash (32 bit)')
for _, opts in ipairs({{c=1,d=2}, {c=2,d=4}}) do
for _, width in ipairs({1,2,4,8}) do
test_perf(sip_hash_tester(opts, width), 1e8,
string.format('sip hash c=%d,d=%d (x%d)',
opts.c, opts.d, width))
end
end
end
function ctable ()
local ctable = require('lib.ctable')
local bnot = require('bit').bnot
local ctab = ctable.new(
{ key_type = ffi.typeof('uint32_t[2]'),
value_type = ffi.typeof('int32_t[5]') })
local occupancy = 2e6
ctab:resize(occupancy / 0.4 + 1)
local function test_insertion(count)
local k = ffi.new('uint32_t[2]');
local v = ffi.new('int32_t[5]');
for i = 1,count do
k[0], k[1] = i, i
for j=0,4 do v[j] = bnot(i) end
ctab:add(k, v)
end
end
local function test_lookup_ptr(count)
local k = ffi.new('uint32_t[2]');
local result = ctab.entry_type()
for i = 1, count do
k[0], k[1] = i, i
result = ctab:lookup_ptr(k)
end
return result
end
local function test_lookup_and_copy(count)
local k = ffi.new('uint32_t[2]');
local result = ctab.entry_type()
for i = 1, count do
k[0], k[1] = i, i
ctab:lookup_and_copy(k, result)
end
return result
end
test_perf(test_insertion, occupancy, 'insertion (40% occupancy)')
test_perf(test_lookup_ptr, occupancy, 'lookup_ptr (40% occupancy)')
test_perf(test_lookup_and_copy, occupancy, 'lookup_and_copy (40% occupancy)')
local stride = 1
repeat
local streamer = ctab:make_lookup_streamer(stride)
local function test_lookup_streamer(count)
local result
for i = 1, count, stride do
local n = math.min(stride, count-i+1)
for j = 0, n-1 do
streamer.entries[j].key[0] = i + j
streamer.entries[j].key[1] = i + j
end
streamer:stream()
result = streamer.entries[n-1].value[0]
end
return result
end
-- Note that "result" is part of the value, not an index into
-- the table, and so we expect the results to be different from
-- ctab:lookup().
test_perf(test_lookup_streamer, occupancy,
'streaming lookup, stride='..stride)
stride = stride * 2
until stride > 256
end
function checksum_bench ()
require("lib.checksum_h")
local checksum = require('arch.checksum').checksum
local function create_packet (size)
local pkt = {
data = ffi.new("uint8_t[?]", size),
length = size
}
for i=0,size-1 do
pkt.data[i] = math.random(255)
end
return pkt
end
local function test_perf (f, iterations, what)
require('jit').flush()
io.write(tostring(what or f)..': ')
io.flush()
local cycles, ns, res = measure(f, iterations)
if cycles then
cycles = cycles/iterations
io.write(('%.2f cycles, '):format(cycles))
end
ns = ns/iterations
io.write(('%.2f ns per iteration (result: %s)'):format(
ns, tostring(res)))
return res, ns
end
local function benchmark_report (size, mpps)
local times = mpps*10^6
local pkt = create_packet(size)
local header = "Size=%d bytes; MPPS=%d M"
local _, ns = test_perf(function(times)
local ret
for i=1,times do ret = C.cksum_generic(pkt.data, pkt.length, 0) end
return ret
end, times, "C: "..header:format(size, mpps))
print(('; %.2f ns per byte'):format(ns/size))
local _, ns = test_perf(function(times)
local ret
for i=1,times do ret = checksum(pkt.data, pkt.length, 0) end
return ret
end, times, "ASM: "..header:format(size, mpps))
print(('; %.2f ns per byte'):format(ns/size))
end
benchmark_report(44, 14.4)
benchmark_report(550, 2)
benchmark_report(1516, 1)
end
|
bSecure.Steam = {}
|
import "CoreLibs/object"
import "CoreLibs/graphics"
import "CoreLibs/sprites"
import "CoreLibs/timer"
local menu = import "ui.lua"
local State = import "game_state.lua"
local gfx = playdate.graphics
local state = State.read()
local function render(view)
gfx.clear(gfx.kColorWhite)
if not view then
return
end
for i, column in ipairs(view) do
for j, cell in ipairs(column) do
local x, y = (j-1)*state.cell_size, (i-1)*state.cell_size
if cell then
gfx.setColor(gfx.kColorBlack)
else
gfx.setColor(gfx.kColorWhite)
end
gfx.fillRect(x, y, state.cell_size, state.cell_size)
gfx.setColor(gfx.kColorWhite)
gfx.drawRect(x, y, state.cell_size, state.cell_size)
end
end
menu:update(state)
end
gfx.clear(gfx.kColorWhite)
function playdate.update()
render(state:view())
playdate.timer.updateTimers()
end
function playdate.AButtonUp()
state.timer:remove()
state.cells = nil
playdate.timer.new(2, function()
state:start()
end)
end
function playdate.BButtonUp()
state.menu = not state.menu
if state.menu then
playdate.inputHandlers.push(menu:input_handlers(state))
else
playdate.inputHandlers.pop()
if state.did_change then
state.timer:remove()
state.cells = nil
state.cell_size = state.next_cell_info.cell_size or state.cell_size
state.columns = state.next_cell_info.columns or state.columns
state.rows = state.next_cell_info.rows or state.rows
state.next_cell_info = {}
state:unpause()
playdate.datastore.write(state:raw())
end
end
end
function playdate.cranked(change, acceleratedChange)
state.total_crank_change = (state.total_crank_change or 0) + change
if state.total_crank_change > 3.6 then
state.total_crank_change = 0
state:tick(true)
elseif state.total_crank_change < -3.6 then
state.total_crank_change = 0
state:tick(false)
end
end
function playdate.crankDocked()
state:unpause()
end
function playdate.crankUndocked()
state:pause()
end
if state.menu then
playdate.inputHandlers.push(menu:input_handlers(state))
end
state:start()
if not playdate.isCrankDocked() then
state:pause()
end
|
---- Copyright(c) Cragon. All rights reserved.
--
--ForestPartyCommon {}
--
--function ForestPartyCommon:new(o, com_common)
-- o = o or {}
-- setmetatable(o, self)
-- self.__index = self
-- self.BetCountDownSound = "ForestPartyBetCountDown"
-- self.ComCommon = com_common
-- self.ComBanker = self.ComCommon:GetChild("ComBanker").asCom
-- self.ComCountDown = self.ComCommon:GetChild("ComCountDown").asCom
-- self.ComSelfGold = self.ComCommon:GetChild("ComPlayerGold").asCom
-- self.GBtnBeBanker = self.ComCommon:GetChild("BtnBeBanker").asButton
-- self.GBtnBeBanker.onClick:Add(
-- function()
-- self:onClickBtnBeBanker()
-- end
-- )
-- self.GBtnNotBeBanker = self.ComCommon:GetChild("BtnNotBeBanker").asButton
-- self.GBtnNotBeBanker.onClick:Add(
-- function()
-- self:onClickBtnNotBeBanker()
-- end
-- )
-- self.GBtnBetRepeat = self.ComCommon:GetChild("BtnBetRepet").asButton
-- self.GBtnBetRepeat.onClick:Add(
-- function()
-- self:onClickBtnBetRepeat()
-- end
-- )
-- self.GTextSelfGold = self.ComSelfGold:GetChild("TextSelfGold").asTextField
-- self.GTextSelfClearGold = self.ComSelfGold:GetChild("TextSelfClearGold").asTextField
-- self.GTextSelfGoldWanOrYi = self.ComSelfGold:GetChild("TextSelfGoldWanOrYi").asTextField
-- self.GTextSelfClearGoldWanOrYi = self.ComSelfGold:GetChild("TextSelfClearGoldWanOrYi").asTextField
-- self.GTextCountDown = self.ComCountDown:GetChild("TextCount").asTextField
-- self.GListRewardHistory = self.ComCommon:GetChild("ListRewardHistory").asList
-- self.TransitionClearGold = self.ComSelfGold:GetTransition("TransitionClearGold")
-- local btn_chat = self.ComCommon:("BtnChat").asButton
-- btn_chat.onClick:Add(
-- function()
-- self:onClickBtnChat()
-- end
-- )
-- local btn_info = self.ComCommon:("BtnInfo").asButton
-- btn_info.onClick:Add(
-- function()
-- self:onClickBtnInfo()
-- end
-- )
-- local btn_shop = self.ComCommon:("BtnShop").asButton
-- btn_shop.onClick:Add(
-- function()
-- self:onClickBtnShop()
-- end
-- )
-- local btn_betChange = self.ComCommon:GetChild("BtnBetChange").asButton
-- self.GTextBetValue = btn_betChange:GetChild("TextBetValue").asTextField
-- btn_betChange.onClick:Add(
-- function()
-- self:onClickBtnBetOperateChange()
-- end
-- )
-- local btn_betRepeatAutoOrManual = self.ComCommon:GetChild("BtnBetRepeatAutoOrManual").asButton
-- self.ControllerBetAutoOrManual = btn_betRepeatAutoOrManual:GetController("ControllerBetAutoOrManual")
-- btn_betRepeatAutoOrManual.onClick:Add(
-- function()
-- self:onClickBtnBetRepeatAutoOrManual()
-- end
-- )
-- self.ForestPartyBanker = ForestPartyBanker:new(nil, self.ComBanker)
-- self.CountDownTime = -1
-- self.HasPlayCountDown1 = false
-- self.HasPlayCountDown2 = false
-- self.HasPlayCountDown3 = false
-- self:init()
-- return o
--end
--
--function ForestPartyCommon:init()
-- local lamp_record = ControllerForestParty.ListLotteryRecord
-- for key value in pairs(lamp_record) do
-- self:addLotteryRecord(value, false)
-- end
-- self.GBtnNotBeBanker.visible = ControllerForestParty.IsBankPlayer
-- self.GBtnBetRepeat.enabled = table.getn(ControllerForestParty.MapSelfBetPot) == 0
-- local self_gold = ControllerActor.Def.PropGoldAcc:get()
-- self:setSelfGold(self_gold)
-- self:setBetOperate()
-- self:setBetRepeatIsAutoOrManual()
-- self:SetBankerInfo()
--end
--
--function ForestPartyCommon:HandleEvent(ev)
-- if (ev.EventName == "EvEntityForestPartyBetState")
-- then
-- self.HasPlayCountDown1 = false
-- self.HasPlayCountDown2 = false
-- self.HasPlayCountDown3 = false
-- self.GBtnBetRepeat.enabled = true
-- self.TweenGListRewardHistory:Kill()
-- local lamp_record = {}
-- lamp_record = ControllerForestParty.ListLotteryRecord
-- self.GListRewardHistory:RemoveChildrenToPool()
-- for key value in pairs(lamp_record) do
-- self:addLotteryRecord(value, false)
-- end
--
-- self:SetBankerInfo()
-- else
-- if (ev.EventName == "EvEntityForestPartyGameEnd")
-- then
-- self.GBtnBetRepeat.enabled = false
-- else
-- if (ev.EventName == "EvEntityForestPartyUpdateAutoBetState")
-- then
-- self:setBetRepeatIsAutoOrManual()
-- else
-- if (ev.EventName == "EvEntityForestPartyUpdateBetOperate")
-- then
-- self:setBetOperate()
-- else
-- if (ev.EventName == "EvEntityForestPartyForbiddenBtnBetRepeat")
-- then
-- self.GBtnBetRepeat.enabled = false
-- else
-- if (ev.EventName == "EvEntityForestPartyBuyItem")
-- then
-- self:playerBuyItem(ev.map_items)
-- else
-- if (ev.EventName == "EvEntityGoldChanged")
-- then
-- self.setSelfGold(ev.gold_acc)
-- end
-- end
--
-- function ForestPartyCommon:Update(elapsed_tm)
-- if (self.CountDownTime == -1)
-- then
-- return
-- else
-- then
-- self.CountDownTime = self.CountDownTime - elapsed_tm
-- local text_time = string.format(%u, CS.System.Math.Ceiling(self.CountDownTime))
-- if (text_time == 3 and self.HasPlayCountDown3 == false)
-- then
-- CS.Casinos.CasinosContext.Instance:Play(self.BetCountDownSound, CS.Casinos._eSoundLayer.LayerNormal)
-- self.HasPlayCountDown3 = true
-- end
-- if (text_time == 2 and self.HasPlayCountDown2 == false)
-- then
-- CS.Casinos.CasinosContext.Instance:Play(self.BetCountDownSound, CS.Casinos._eSoundLayer.LayerNormal)
-- self.HasPlayCountDown2 = true
-- end
-- if (text_time == 1 and self.HasPlayCountDown1 == false)
-- then
-- CS.Casinos.CasinosContext.Instance:Play(self.BetCountDownSound, CS.Casinos._eSoundLayer.LayerNormal)
-- self.HasPlayCountDown1 = true
-- end
-- self.GTextCountDown.text = tostring(text_time)
-- end
-- end
--
-- function ForestPartyCommon:SetBankerInfo()
-- self.ForestPartyBanker:SetBankerInfo()
-- self.GBtnNotBeBanker.visible = ControllerForestParty.IsBankPlayer
-- end
--
-- function ForestPartyCommon:PlayClearGoldTransition()
-- local self_winlose_gold = ControllerForestParty.SelfWinLoseGold
-- if (self_winlose_gold < 10000)
-- then
-- self.GTextSelfClearGoldWanOrYi.text = ""
-- self.GTextSelfClearGold.text = tostring(self_winlose_gold)
-- else
-- then
-- if (self_winlose_gold < 100000000)
-- then
-- self.GTextSelfClearGoldWanOrYi.text = "��"
-- else
-- then
-- self.GTextSelfClearGoldWanOrYi.text = "��"
-- end
-- self.GTextSelfClearGold.text = CS.Casinos.CasinosContext.Instance.UiChipShowHelper:getGoldShowStr(self_winlose_gold, CS.Casinos.CasinosContext.Instance.LanMgr.LanBase)
-- end
-- self.TransitionClearGold:Play(3, 0, nil)
-- end
--
-- function ForestPartyCommon:StopClearGoldTransition()
-- self.TransitionClearGold:Stop(true, false)
-- self.GTextSelfClearGold.text = ""
-- self.GTextSelfClearGoldWanOrYi.text = ""
-- end
--
-- function ForestPartyCommon:StartCoutDown()
-- local time = ControllerForestParty.BetLeftTime
-- self.CountDownTime = time
-- end
--
-- function ForestPartyCommon:StopCoutDown()
-- self.CountDownTime = -1
-- self.GTextCountDown.text = ""
-- end
--
-- function ForestPartyCommon:addLotteryRecord(record, use_transition)
-- local com_record = self.GListRewardHistory:GetFromPool(CS.FairyGUI.UIPackage.GetItemURL("ForestParty", "ComRewardHistory")).asCom
-- self.GListRewardHistory:AddChildAt(com_record, 0)
-- local loader_icon = com_record:GetChild("LoaderIcon").asLoader
-- local str_res_name
-- if (record.LotteryType == CS.Casinos.LotteryType.Normal)
-- then
-- str_res_name = record.AnimalType.ToString() .. record.BlockColor.ToString()
-- else
-- then
-- str_res_name = record.LotteryType.ToString()
-- end
-- loader_icon.url = CS.FairyGUI.UIPackage.GetItemURL("ForestParty", "HistoryRecord" .. str_res_name)
-- if (use_transition)
-- then
-- local transition_rotate = com_record:GetTransition("TransitionRotate");
-- transition_rotate:Play(
-- function ()
-- if (self.GListRewardHistory.numChildren >= 11)
-- then
-- self.TweenGListRewardHistory = self.GListRewardHistory:TweenMoveX(self.GListRewardHistory.x + com_record.width, 0.3).OnComplete(
-- function ()
-- self.GListRewardHistory:RemoveChildToPoolAt(10)
-- self.GListRewardHistory.x = self.GListRewardHistory.x - com_record.width
-- end
-- )
-- end
-- end
-- )
-- end
-- end
--
-- function ForestPartyCommon:setSelfGold(self_gold)
-- if (self_gold < 10000)
-- then
-- self.GTextSelfGoldWanOrYi.text = ""
-- else
-- if (self_gold < 100000000)
-- then
-- self.GTextSelfGoldWanOrYi.text = "��"
-- else
-- then
-- self.GTextSelfGoldWanOrYi.text = "��"
-- end
-- local str_self_gold = CS.Casinos.CasinosContext.Instance.UiChipShowHelper:getGoldShowStr(self_gold, CS.Casinos.CasinosContext.Instance.LanMgr.LanBase)
-- self.GTextSelfGold.text = str_self_gold
-- end
--
-- function ForestPartyCommon:setBetOperate()
-- local bet_index = ControllerForestParty.BetOprateIndex
-- local map_betoperate = ControllerForestParty.MapBetOperate
-- local bet_value = map_betoperate[bet_index]
-- self.GTextBetValue.text = tostring(bet_value)
-- self.GTextBetValue.text = CS.Casinos.CasinosContext.Instance.UiChipShowHelper:getGoldShowStr(bet_value, CS.Casinos.CasinosContext.Instance.LanMgr.LanBase, true, 0)
-- end
--
-- function ForestPartyCommon:setBetRepeatIsAutoOrManual()
-- local is_auto_bet_repeate = ControllerForestParty.IsAutoBetRepeate
-- if (is_auto_bet_repeate)
-- then
-- self.ControllerBetAutoOrManual.SetSelectedIndex = 0
-- else
-- then
-- self.ControllerBetAutoOrManual.SetSelectedIndex = 1
-- end
-- end
--
-- function ForestPartyCommon:onClickBtnBeBanker()
-- local view_mgr = ViewMgr:new(nil)
-- local ev = view_mgr:getEv("EvUiForestPartyBeBanker")
-- if (ev == nil)
-- then
-- ev = EvUiForestPartyBeBanker:new(nil)
-- end
-- view_mgr:senEv(ev)
-- end
--
-- function ForestPartyCommon:onClickBtnNotBeBanker()
-- local view_mgr = ViewMgr:new(nil)
-- local ev = view_mgr:getEv("EvUiForestPartyNotBeBanker")
-- if (ev == nil)
-- then
-- ev = EvUiForestPartyNotBeBanker:new(nil)
-- end
-- view_mgr:senEv(ev)
-- end
--
-- function ForestPartyCommon:onClickBtnBetOperateChange()
-- local view_mgr = ViewMgr:new(nil)
-- local ev = view_mgr:getEv("EvUiForestPartyChangeBetOperate")
-- if (ev == nil)
-- then
-- ev = EvUiForestPartyChangeBetOperate:new(nil)
-- end
-- view_mgr:senEv(ev)
-- end
--
-- function ForestPartyCommon:onClickBtnBetRepeatAutoOrManual()
-- local view_mgr = ViewMgr:new(nil)
-- local ev = view_mgr:getEv("EvUiForestPartyChangeBetRepeatState")
-- if (ev == nil)
-- then
-- ev = EvUiForestPartyChangeBetRepeatState:new(nil)
-- end
-- view_mgr:senEv(ev)
-- end
--
-- function ForestPartyCommon:onClickBtnChat()
-- local view_mgr = ViewMgr:new(nil)
-- local ui_chat = view_mgr.createView("Chat")
-- ui_chat:init(_eUiChatType.DesktopH)
-- end
--
-- function ForestPartyCommon:onClickBtnInfo()
-- local view_mgr = ViewMgr:new(nil)
-- view_mgr.createView("ForestPartyInfo")
-- end
--
-- function ForestPartyCommon:onClickBtnShop()
-- local view_mgr = ViewMgr:new(nil)
-- view_mgr.createView("Shop")
-- end
--
-- function ForestPartyCommon:onClickBtnBetRepeat()
-- local view_mgr = ViewMgr:new(nil)
-- local ev = view_mgr:getEv("EvUiForestPartyBetRepeat")
-- if (ev == nil)
-- then
-- ev = EvUiForestPartyBetRepeat:new(nil)
-- end
-- view_mgr:senEv(ev)
-- end
--
-- function ForestPartyCommon:playerBuyItem(map_items)
-- if (map_items == nil)
-- then
-- return
-- end
-- local eb_data_mgr = CasinosContext.Instance.EbDataMgr
-- foreach(var
-- i in map_items)
-- {
-- Item item = new Item(eb_data_mgr, null, i.Value);
-- if (item.UnitLink.UnitType == UnitType.MagicExpression)
-- {
-- if (i.Key.Equals(CoPlayer.CoPlayerForestParty.BankerData.PlayerInfoCommon.PlayerGuid))
-- {
-- sendBankerMagicExp(item.TbDataItem.Id);
-- }
-- }
-- }
-- end
--
-- function ForestPartyCommon:sendBankerMagicExp(exp_tbid)
-- TbDataUnitMagicExpression tb_magicexp = CasinosContext.Instance.EbDataMgr.GetData<TbDataUnitMagicExpression>(exp_tbid)
-- if (tb_magicexp == null)
-- {
-- return ;
-- }
-- Vector3 from_pos = Vector3.zero + new Vector3(Screen.width, Screen.height)
-- Vector3 to_pos = ComBanker.position + new Vector3(ComBanker.width / 2, ComBanker.height / 2)
-- var ui_pool = CasinosContext.Instance.UiMgr.getUi<UiPool>()
-- var item_magicsender = ui_pool.getMagicExpSender()
-- item_magicsender.sendMagicExp(from_pos, to_pos, exp_tbid)
-- end
--
--
--
|
object_mobile_dressed_meatlump_hideout_male_04 = object_mobile_shared_dressed_meatlump_hideout_male_04:new {
}
ObjectTemplates:addTemplate(object_mobile_dressed_meatlump_hideout_male_04, "object/mobile/dressed_meatlump_hideout_male_04.iff")
|
local Path = require "plenary.path"
local path = Path.path
describe("Path", function()
it("should find valid files", function()
local p = Path:new "README.md"
assert(p.filename == "README.md", p.filename)
assert.are.same(p.filename, "README.md")
end)
describe("absolute", function()
it(".absolute()", function()
local p = Path:new { "README.md", sep = "/" }
assert.are.same(p:absolute(), vim.fn.fnamemodify("README.md", ":p"))
end)
it("can determine absolute paths", function()
local p = Path:new { "/home/asdfasdf/", sep = "/" }
assert(p:is_absolute(), "Is absolute")
assert(p:absolute() == p.filename)
end)
it("can determine non absolute paths", function()
local p = Path:new { "./home/tj/", sep = "/" }
assert(not p:is_absolute(), "Is absolute")
end)
it("will normalize the path", function()
local p = Path:new { "lua", "..", "README.md", sep = "/" }
assert.are.same(p:absolute(), vim.fn.fnamemodify("README.md", ":p"))
end)
end)
it("can join paths by constructor or join path", function()
assert.are.same(Path:new("lua", "plenary"), Path:new("lua"):joinpath "plenary")
end)
it("can join paths with /", function()
assert.are.same(Path:new("lua", "plenary"), Path:new "lua" / "plenary")
end)
it("can join paths with paths", function()
assert.are.same(Path:new("lua", "plenary"), Path:new("lua", Path:new "plenary"))
end)
it("inserts slashes", function()
assert.are.same("lua" .. path.sep .. "plenary", Path:new("lua", "plenary").filename)
end)
describe(".exists()", function()
it("finds files that exist", function()
assert.are.same(true, Path:new("README.md"):exists())
end)
it("returns false for files that do not exist", function()
assert.are.same(false, Path:new("asdf.md"):exists())
end)
end)
describe(".is_dir()", function()
it("should find directories that exist", function()
assert.are.same(true, Path:new("lua"):is_dir())
end)
it("should return false when the directory does not exist", function()
assert.are.same(false, Path:new("asdf"):is_dir())
end)
it("should not show files as directories", function()
assert.are.same(false, Path:new("README.md"):is_dir())
end)
end)
describe(".is_file()", function()
it("should not allow directories", function()
assert.are.same(true, not Path:new("lua"):is_file())
end)
it("should return false when the file does not exist", function()
assert.are.same(true, not Path:new("asdf"):is_file())
end)
it("should show files as file", function()
assert.are.same(true, Path:new("README.md"):is_file())
end)
end)
describe(":new", function()
it("can be called with or without colon", function()
-- This will work, cause we used a colon
local with_colon = Path:new "lua"
local no_colon = Path.new "lua"
assert.are.same(with_colon, no_colon)
end)
end)
describe(":make_relative", function()
it("can take absolute paths and make them relative to the cwd", function()
local p = Path:new { "lua", "plenary", "path.lua" }
local absolute = vim.loop.cwd() .. path.sep .. p.filename
local relative = Path:new(absolute):make_relative()
assert.are.same(relative, p.filename)
end)
it("can take absolute paths and make them relative to a given path", function()
local root = path.sep == "\\" and "c:\\" or "/"
local r = Path:new { root, "home", "prime" }
local p = Path:new { "aoeu", "agen.lua" }
local absolute = r.filename .. path.sep .. p.filename
local relative = Path:new(absolute):make_relative(r.filename)
assert.are.same(relative, p.filename)
end)
it("can take double separator absolute paths and make them relative to the cwd", function()
local p = Path:new { "lua", "plenary", "path.lua" }
local absolute = vim.loop.cwd() .. path.sep .. path.sep .. p.filename
local relative = Path:new(absolute):make_relative()
assert.are.same(relative, p.filename)
end)
it("can take double separator absolute paths and make them relative to a given path", function()
local root = path.sep == "\\" and "c:\\" or "/"
local r = Path:new { root, "home", "prime" }
local p = Path:new { "aoeu", "agen.lua" }
local absolute = r.filename .. path.sep .. path.sep .. p.filename
local relative = Path:new(absolute):make_relative(r.filename)
assert.are.same(relative, p.filename)
end)
it("can take absolute paths and make them relative to a given path with trailing separator", function()
local root = path.sep == "\\" and "c:\\" or "/"
local r = Path:new { root, "home", "prime" }
local p = Path:new { "aoeu", "agen.lua" }
local absolute = r.filename .. path.sep .. p.filename
local relative = Path:new(absolute):make_relative(r.filename .. path.sep)
assert.are.same(relative, p.filename)
end)
it("can take absolute paths and make them relative to the root directory", function()
local root = path.sep == "\\" and "c:\\" or "/"
local p = Path:new { "home", "prime", "aoeu", "agen.lua" }
local absolute = root .. p.filename
local relative = Path:new(absolute):make_relative(root)
assert.are.same(relative, p.filename)
end)
it("can take absolute paths and make them relative to themselves", function()
local root = path.sep == "\\" and "c:\\" or "/"
local p = Path:new { root, "home", "prime", "aoeu", "agen.lua" }
local relative = Path:new(p.filename):make_relative(p.filename)
assert.are.same(relative, ".")
end)
it("should not truncate if path separator is not present after cwd", function()
local cwd = "tmp" .. path.sep .. "foo"
local p = Path:new { "tmp", "foo_bar", "fileb.lua" }
local relative = Path:new(p.filename):make_relative(cwd)
assert.are.same(p.filename, relative)
end)
it("should not truncate if path separator is not present after cwd and cwd ends in path sep", function()
local cwd = "tmp" .. path.sep .. "foo" .. path.sep
local p = Path:new { "tmp", "foo_bar", "fileb.lua" }
local relative = Path:new(p.filename):make_relative(cwd)
assert.are.same(p.filename, relative)
end)
end)
describe(":normalize", function()
it("can take path that has one character directories", function()
local orig = "/home/j/./p//path.lua"
local final = Path:new(orig):normalize()
assert.are.same(final, "/home/j/p/path.lua")
end)
it("can take paths with double separators change them to single separators", function()
local orig = "/lua//plenary/path.lua"
local final = Path:new(orig):normalize()
assert.are.same(final, "/lua/plenary/path.lua")
end)
-- this may be redundant since normalize just calls make_relative which is tested above
it("can take absolute paths with double seps" .. "and make them relative with single seps", function()
local orig = "/lua//plenary/path.lua"
local final = Path:new(orig):normalize()
assert.are.same(final, "/lua/plenary/path.lua")
end)
it("can remove the .. in paths", function()
local orig = "/lua//plenary/path.lua/foo/bar/../.."
local final = Path:new(orig):normalize()
assert.are.same(final, "/lua/plenary/path.lua")
end)
it("can normalize relative paths", function()
assert.are.same(Path:new("lua/plenary/path.lua"):normalize(), "lua/plenary/path.lua")
end)
it("can normalize relative paths containing ..", function()
assert.are.same(Path:new("lua/plenary/path.lua/../path.lua"):normalize(), "lua/plenary/path.lua")
end)
it("can normalize relative paths with initial ..", function()
local p = Path:new "../lua/plenary/path.lua"
p._cwd = "/tmp/lua"
assert.are.same("lua/plenary/path.lua", p:normalize())
end)
it("can normalize relative paths to absolute when initial .. count matches cwd parts", function()
local p = Path:new "../../tmp/lua/plenary/path.lua"
p._cwd = "/tmp/lua"
assert.are.same("/tmp/lua/plenary/path.lua", p:normalize())
end)
it("can normalize ~ when file is within home directory (trailing slash)", function()
local home = "/home/test/"
local p = Path:new { home, "./test_file" }
p.path.home = home
p._cwd = "/tmp/lua"
assert.are.same("~/test_file", p:normalize())
end)
it("can normalize ~ when file is within home directory (no trailing slash)", function()
local home = "/home/test"
local p = Path:new { home, "./test_file" }
p.path.home = home
p._cwd = "/tmp/lua"
assert.are.same("~/test_file", p:normalize())
end)
it("handles usernames with a dash at the end", function()
local home = "/home/mattr-"
local p = Path:new { home, "test_file" }
p.path.home = home
p._cwd = "/tmp/lua"
assert.are.same("~/test_file", p:normalize())
end)
it("handles filenames with the same prefix as the home directory", function()
local p = Path:new "/home/test.old/test_file"
p.path.home = "/home/test"
assert.are.same("/home/test.old/test_file", p:normalize())
end)
end)
describe(":shorten", function()
it("can shorten a path", function()
local long_path = "/this/is/a/long/path"
local short_path = Path:new(long_path):shorten()
assert.are.same(short_path, "/t/i/a/l/path")
end)
it("can shorten a path's components to a given length", function()
local long_path = "/this/is/a/long/path"
local short_path = Path:new(long_path):shorten(2)
assert.are.same(short_path, "/th/is/a/lo/path")
-- without the leading /
long_path = "this/is/a/long/path"
short_path = Path:new(long_path):shorten(3)
assert.are.same(short_path, "thi/is/a/lon/path")
-- where len is greater than the length of the final component
long_path = "this/is/an/extremely/long/path"
short_path = Path:new(long_path):shorten(5)
assert.are.same(short_path, "this/is/an/extre/long/path")
end)
it("can shorten a path's components when excluding parts", function()
local long_path = "/this/is/a/long/path"
local short_path = Path:new(long_path):shorten(nil, { 1, -1 })
assert.are.same(short_path, "/this/i/a/l/path")
-- without the leading /
long_path = "this/is/a/long/path"
short_path = Path:new(long_path):shorten(nil, { 1, -1 })
assert.are.same(short_path, "this/i/a/l/path")
-- where excluding positions greater than the number of parts
long_path = "this/is/an/extremely/long/path"
short_path = Path:new(long_path):shorten(nil, { 2, 4, 6, 8 })
assert.are.same(short_path, "t/is/a/extremely/l/path")
-- where excluding positions less than the negation of the number of parts
long_path = "this/is/an/extremely/long/path"
short_path = Path:new(long_path):shorten(nil, { -2, -4, -6, -8 })
assert.are.same(short_path, "this/i/an/e/long/p")
end)
it("can shorten a path's components to a given length and exclude positions", function()
local long_path = "/this/is/a/long/path"
local short_path = Path:new(long_path):shorten(2, { 1, -1 })
assert.are.same(short_path, "/this/is/a/lo/path")
long_path = "this/is/a/long/path"
short_path = Path:new(long_path):shorten(3, { 2, -2 })
assert.are.same(short_path, "thi/is/a/long/pat")
long_path = "this/is/an/extremely/long/path"
short_path = Path:new(long_path):shorten(5, { 3, -3 })
assert.are.same(short_path, "this/is/an/extremely/long/path")
end)
end)
describe("mkdir / rmdir", function()
it("can create and delete directories", function()
local p = Path:new "_dir_not_exist"
p:rmdir()
assert(not p:exists(), "After rmdir, it should not exist")
p:mkdir()
assert(p:exists())
p:rmdir()
assert(not p:exists())
end)
it("fails when exists_ok is false", function()
local p = Path:new "lua"
assert(not pcall(p.mkdir, p, { exists_ok = false }))
end)
it("fails when parents is not passed", function()
local p = Path:new("impossible", "dir")
assert(not pcall(p.mkdir, p, { parents = false }))
assert(not p:exists())
end)
it("can create nested directories", function()
local p = Path:new("impossible", "dir")
assert(pcall(p.mkdir, p, { parents = true }))
assert(p:exists())
p:rmdir()
Path:new("impossible"):rmdir()
assert(not p:exists())
assert(not Path:new("impossible"):exists())
end)
end)
describe("touch", function()
it("can create and delete new files", function()
local p = Path:new "test_file.lua"
assert(pcall(p.touch, p))
assert(p:exists())
p:rm()
assert(not p:exists())
end)
it("does not effect already created files but updates last access", function()
local p = Path:new "README.md"
local last_atime = p:_stat().atime.sec
local last_mtime = p:_stat().mtime.sec
local lines = p:readlines()
assert(pcall(p.touch, p))
print(p:_stat().atime.sec > last_atime)
print(p:_stat().mtime.sec > last_mtime)
assert(p:exists())
assert.are.same(lines, p:readlines())
end)
it("does not create dirs if nested in none existing dirs and parents not set", function()
local p = Path:new { "nested", "nested2", "test_file.lua" }
assert(not pcall(p.touch, p, { parents = false }))
assert(not p:exists())
end)
it("does create dirs if nested in none existing dirs", function()
local p1 = Path:new { "nested", "nested2", "test_file.lua" }
local p2 = Path:new { "nested", "asdf", ".hidden" }
local d1 = Path:new { "nested", "dir", ".hidden" }
assert(pcall(p1.touch, p1, { parents = true }))
assert(pcall(p2.touch, p2, { parents = true }))
assert(pcall(d1.mkdir, d1, { parents = true }))
assert(p1:exists())
assert(p2:exists())
assert(d1:exists())
Path:new({ "nested" }):rm { recursive = true }
assert(not p1:exists())
assert(not p2:exists())
assert(not d1:exists())
assert(not Path:new({ "nested" }):exists())
end)
end)
describe("rename", function()
it("can rename a file", function()
local p = Path:new "a_random_filename.lua"
assert(pcall(p.touch, p))
assert(p:exists())
assert(pcall(p.rename, p, { new_name = "not_a_random_filename.lua" }))
assert.are.same("not_a_random_filename.lua", p.filename)
p:rm()
end)
it("can handle an invalid filename", function()
local p = Path:new "some_random_filename.lua"
assert(pcall(p.touch, p))
assert(p:exists())
assert(not pcall(p.rename, p, { new_name = "" }))
assert(not pcall(p.rename, p))
assert.are.same("some_random_filename.lua", p.filename)
p:rm()
end)
it("can move to parent dir", function()
local p = Path:new "some_random_filename.lua"
assert(pcall(p.touch, p))
assert(p:exists())
assert(pcall(p.rename, p, { new_name = "../some_random_filename.lua" }))
assert.are.same(vim.loop.fs_realpath(Path:new("../some_random_filename.lua"):absolute()), p:absolute())
p:rm()
end)
it("cannot rename to an existing filename", function()
local p1 = Path:new "a_random_filename.lua"
local p2 = Path:new "not_a_random_filename.lua"
assert(pcall(p1.touch, p1))
assert(pcall(p2.touch, p2))
assert(p1:exists())
assert(p2:exists())
assert(not pcall(p1.rename, p1, { new_name = "not_a_random_filename.lua" }))
assert.are.same(p1.filename, "a_random_filename.lua")
p1:rm()
p2:rm()
end)
end)
describe("copy", function()
it("can copy a file", function()
local p1 = Path:new "a_random_filename.rs"
local p2 = Path:new "not_a_random_filename.rs"
assert(pcall(p1.touch, p1))
assert(p1:exists())
assert(pcall(p1.copy, p1, { destination = "not_a_random_filename.rs" }))
assert.are.same(p1.filename, "a_random_filename.rs")
assert.are.same(p2.filename, "not_a_random_filename.rs")
p1:rm()
p2:rm()
end)
it("can copy to parent dir", function()
local p = Path:new "some_random_filename.lua"
assert(pcall(p.touch, p))
assert(p:exists())
assert(pcall(p.copy, p, { destination = "../some_random_filename.lua" }))
assert(pcall(p.exists, p))
p:rm()
Path:new(vim.loop.fs_realpath "../some_random_filename.lua"):rm()
end)
it("cannot copy an existing file if override false", function()
local p1 = Path:new "a_random_filename.rs"
local p2 = Path:new "not_a_random_filename.rs"
assert(pcall(p1.touch, p1))
assert(pcall(p2.touch, p2))
assert(p1:exists())
assert(p2:exists())
assert(pcall(p1.copy, p1, { destination = "not_a_random_filename.rs", override = false }))
assert.are.same(p1.filename, "a_random_filename.rs")
assert.are.same(p2.filename, "not_a_random_filename.rs")
p1:rm()
p2:rm()
end)
it("fails when copying folders non-recursively", function()
local src_dir = Path:new "src"
src_dir:mkdir()
src_dir:joinpath("file1.lua"):touch()
local trg_dir = Path:new "trg"
local status = xpcall(function()
src_dir:copy { destination = trg_dir, recursive = false }
end, function() end)
-- failed as intended
assert(status == false)
src_dir:rm { recursive = true }
end)
it("can copy directories recursively", function()
-- vim.tbl_flatten doesn't work here as copy doesn't return a list
local flatten
flatten = function(ret, t)
for _, v in pairs(t) do
if type(v) == "table" then
flatten(ret, v)
else
table.insert(ret, v)
end
end
end
-- setup directories
local src_dir = Path:new "src"
local trg_dir = Path:new "trg"
src_dir:mkdir()
-- set up sub directory paths for creation and testing
local sub_dirs = { "sub_dir1", "sub_dir1/sub_dir2" }
local src_dirs = { src_dir }
local trg_dirs = { trg_dir }
-- {src, trg}_dirs is a table with all directory levels by {src, trg}
for _, dir in ipairs(sub_dirs) do
table.insert(src_dirs, src_dir:joinpath(dir))
table.insert(trg_dirs, trg_dir:joinpath(dir))
end
-- generate {file}_{level}.lua on every directory level in src
-- src
-- ├── file1_1.lua
-- ├── file2_1.lua
-- ├── .file3_1.lua
-- └── sub_dir1
-- ├── file1_2.lua
-- ├── file2_2.lua
-- ├── .file3_2.lua
-- └── sub_dir2
-- ├── file1_3.lua
-- ├── file2_3.lua
-- └── .file3_3.lua
local files = { "file1", "file2", ".file3" }
for _, file in ipairs(files) do
for level, dir in ipairs(src_dirs) do
local p = dir:joinpath(file .. "_" .. level .. ".lua")
assert(pcall(p.touch, p, { parents = true, exists_ok = true }))
assert(p:exists())
end
end
for _, hidden in ipairs { true, false } do
-- override = `false` should NOT copy as it was copied beforehand
for _, override in ipairs { true, false } do
local success = src_dir:copy { destination = trg_dir, recursive = true, override = override, hidden = hidden }
-- the files are already created because we iterate first with `override=true`
-- hence, we test here that no file ops have been committed: any value in tbl of tbls should be false
if not override then
local file_ops = {}
flatten(file_ops, success)
-- 3 layers with at at least 2 and at most 3 files (`hidden = true`)
local num_files = not hidden and 6 or 9
assert(#file_ops == num_files)
for _, op in ipairs(file_ops) do
assert(op == false)
end
else
for _, file in ipairs(files) do
for level, dir in ipairs(trg_dirs) do
local p = dir:joinpath(file .. "_" .. level .. ".lua")
-- file 3 is hidden
if not (file == files[3]) then
assert(p:exists())
else
assert(p:exists() == hidden)
end
end
end
end
-- only clean up once we tested that we dont want to copy
-- if `override=true`
if not override then
trg_dir:rm { recursive = true }
end
end
end
src_dir:rm { recursive = true }
end)
end)
describe("parents", function()
it("should extract the ancestors of the path", function()
local p = Path:new(vim.loop.cwd())
local parents = p:parents()
assert(vim.tbl_islist(parents))
for _, parent in pairs(parents) do
assert.are.same(type(parent), "string")
end
end)
it("should return itself if it corresponds to path.root", function()
local p = Path:new(Path.path.root(vim.loop.cwd()))
assert.are.same(p:parent(), p)
end)
end)
describe("read parts", function()
it("should read head of file", function()
local p = Path:new "LICENSE"
local data = p:head()
local should = [[MIT License
Copyright (c) 2020 TJ DeVries
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:]]
assert.are.same(should, data)
end)
it("should read the first line of file", function()
local p = Path:new "LICENSE"
local data = p:head(1)
local should = [[MIT License]]
assert.are.same(should, data)
end)
it("head should max read whole file", function()
local p = Path:new "LICENSE"
local data = p:head(1000)
local should = [[MIT License
Copyright (c) 2020 TJ DeVries
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.]]
assert.are.same(should, data)
end)
it("should read tail of file", function()
local p = Path:new "LICENSE"
local data = p:tail()
local should = [[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.]]
assert.are.same(should, data)
end)
it("should read the last line of file", function()
local p = Path:new "LICENSE"
local data = p:tail(1)
local should = [[SOFTWARE.]]
assert.are.same(should, data)
end)
it("tail should max read whole file", function()
local p = Path:new "LICENSE"
local data = p:tail(1000)
local should = [[MIT License
Copyright (c) 2020 TJ DeVries
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.]]
assert.are.same(should, data)
end)
end)
describe("readbyterange", function()
it("should read bytes at given offset", function()
local p = Path:new "LICENSE"
local data = p:readbyterange(13, 10)
local should = "Copyright "
assert.are.same(should, data)
end)
it("supports negative offset", function()
local p = Path:new "LICENSE"
local data = p:readbyterange(-10, 10)
local should = "SOFTWARE.\n"
assert.are.same(should, data)
end)
end)
end)
-- function TestPath:testIsDir()
-- end
-- function TestPath:testCanBeCalledWithoutColon()
-- end
-- -- @sideeffect
-- function TestPath:testMkdir()
-- end
|
#!/usr/bin/env luajit
local ENABLE_LOG = false
-- Mesh Wizard for Team THOR
-- Accumulate lidar readings into an image for mesh viewing
-- (c) Stephen McGill, Seung Joon Yi, 2013, 2014
dofile'../include.lua'
local libMesh = require'libMesh'
local si = require'simple_ipc'
local mpack = require'msgpack.MessagePack'.pack
local munpack = require('msgpack.MessagePack')['unpack']
local Body = require'Body'
local ffi = require'ffi'
require'vcm'
require'hcm'
local sin, cos = require'math'.sin, require'math'.cos
local T = require'Transform'
local pillar_ch = si.new_publisher('pillars')
local polar_interval = 15 * DEG_TO_RAD
local function find_pillars(xyz, polar)
local xyz_com, xyz_world = xyz[1], xyz[2]
local rho, theta = unpack(polar)
local pillars = {}
local interval = polar_interval + theta[1]
local xymin
local rmin = math.huge
for i, a in ipairs(theta) do
local xyz = xyz_com[i]
local xyzw = xyz_world[i]
local r = rho[i]
if a<interval then
-- Filter too close, too far and ground
if r<rmin and r>0.24 and r<5 and xyzw[3]>0 then
xymin = {xyz[1], xyz[2]}
rmin = r
-- elseif not xymin then
-- rmin = math.huge
-- xymin = {xyz[1], xyz[2]}
end
else
if xymin then table.insert(pillars, xymin) end
xymin = nil
rmin = math.huge
interval = interval + polar_interval
end
end
if xymin then table.insert(pillars, xymin) end
pillar_ch:send(mpack(pillars))
--[[
print('Sending pillars', #pillars)
for i,p in ipairs(pillars) do
print(p[2], p[1])
end
--]]
end
local Thead = T.trans(0,0,0.282)
local function head3d(meta, scan)
local scan_fl = ffi.cast('float*', scan)
local mid = meta.n / 2 * meta.res
local angles, rho = {}, {}
for i=1,meta.n do
table.insert(angles, i * meta.res - mid)
table.insert(rho, scan_fl[i-1])
end
local xyz = {}
for i,a in ipairs(angles) do
table.insert(xyz, {rho[i] * cos(a), rho[i] * sin(a), 0.1})
end
local xyz_actuated = {}
local Tact = T.rotY(meta.angle[2]) * T.rotZ(meta.angle[1])
for i,p in ipairs(xyz) do
table.insert(xyz_actuated, Tact * p)
end
local xyz_head = {}
for i,p in ipairs(xyz_actuated) do
table.insert(xyz_head, Thead * p)
end
local xyz_com = {}
local Twaist = T.rotZ(meta.qWaist[1])
for i, p in ipairs(xyz_head) do
table.insert(xyz_com, Twaist*p)
end
local rho_com = {}
local theta_com = {}
for i, p in ipairs(xyz_com) do
table.insert(theta_com, math.atan2(p[2], p[1]))
table.insert(rho_com, math.sqrt(math.pow(p[2],2), math.pow(p[1],2)))
end
local Tworld = T.from_flat(meta.tfG16)
local xyz_world = {}
for i, p in ipairs(xyz_com) do
table.insert(xyz_world, Tworld*p)
end
return {xyz_com, xyz_world}, {rho_com, theta_com}
end
local Tchest = T.trans(0.05, 0, 0.09)
local function chest3d(meta, scan)
local scan_fl = ffi.cast('float*', scan)
local xyz = {}
for i,a in ipairs(angles) do
local r = scan_fl[i] + 0.02
table.insert(xyz, {r * sin(a), r * cos(a), 0})
end
local Tcom = Tchest * T.rotZ(meta.a) * T.rotX(math.pi/2)
local xyz_com = {}
for i, p in ipairs(xyz) do
table.insert(xyz_com, Tcom*p)
end
local Tworld = T.from_flat(meta.tfG16)
local xyz_world = {}
for i, p in ipairs(xyz_com) do
table.insert(xyz_world, Tworld*p)
end
return xyz_world, xyz_com
end
local function entry()
end
local np = 0
local function update(meta, scan)
local points
-- Form 3D coordinates
if meta.id=='lidar0' then
--points = chest3d(meta, scan)
elseif meta.id=='lidar1' then
local xyz, polar = head3d(meta, scan)
find_pillars(xyz, polar)
end
--[[
if np<1 then
for i,p in ipairs(points) do
print(i, unpack(p))
end
end
--]]
np = np + 1
end
local function exit()
end
-- If required from Webots, return the table
if ... and type(...)=='string' then
return {entry=entry, update=update, exit=exit}
end
local poller
local function cb(skt)
local idx = poller.lut[skt]
local mdata, ranges = unpack(skt:recv_all())
local meta = munpack(mdata)
update(meta, ranges)
end
local lidar0_ch = si.new_subscriber'lidar0'
local lidar1_ch = si.new_subscriber'lidar1'
lidar0_ch.callback = cb
lidar1_ch.callback = cb
poller = si.wait_on_channels({lidar1_ch})
-- Cleanly exit on Ctrl-C
local signal = require'signal'.signal
local running = true
local function shutdown()
io.write('Shutdown!\n')
poller:stop()
end
signal("SIGINT", shutdown)
signal("SIGTERM", shutdown)
poller:start()
if ENABLE_LOG then
logger0:stop()
logger1:stop()
end
|
--[[---------------------------------------------------------------------------
Messages
---------------------------------------------------------------------------]]
local function ccTell(ply, args)
local target = DarkRP.findPlayer(args[1])
if target then
local msg = ""
for n = 2, #args do
msg = msg .. args[n] .. " "
end
net.Start("AdminTell")
net.WriteString(msg)
net.Send(target)
if ply:EntIndex() == 0 then
DarkRP.log("Console did admintell \"" .. msg .. "\" on " .. target:SteamName(), Color(30, 30, 30))
else
DarkRP.log(ply:Nick() .. " (" .. ply:SteamID() .. ") did admintell \"" .. msg .. "\" on " .. target:SteamName(), Color(30, 30, 30))
end
else
DarkRP.notify(ply, 1, 4, DarkRP.getPhrase("could_not_find", tostring(args[1])))
end
end
DarkRP.definePrivilegedChatCommand("admintell", "DarkRP_AdminCommands", ccTell)
local function ccTellAll(ply, args)
net.Start("AdminTell")
net.WriteString(args)
net.Broadcast()
if ply:EntIndex() == 0 then
DarkRP.log("Console did admintellall \"" .. args .. "\"", Color(30, 30, 30))
else
DarkRP.log(ply:Nick() .. " (" .. ply:SteamID() .. ") did admintellall \"" .. args .. "\"", Color(30, 30, 30))
end
end
DarkRP.definePrivilegedChatCommand("admintellall", "DarkRP_AdminCommands", ccTellAll)
|
-- This script template has each of the script entry point functions.
-- They are described in detail in VR-Forces Configuration Guide.
-- Some basic VRF Utilities defined in a common module.
require "vrfutil"
-- Global Variables. Global variables get saved when a scenario gets checkpointed.
-- They get re-initialized when a checkpointed scenario is loaded.
-- Task Parameters Available in Script
-- taskParameters.visitTime Type: Real
-- taskParameters.maxVisitDistance Type: Real Unit: meters - Maximum distance from which to deviate from normal movement to visit an interst point.
-- taskParameters.visitLiklihood Type: Integer - Percent liklihood that an entity will choose to visit a point that it passes near.
local thePointOfInterestType="16:0:0:1:1:0:0"
-- Points on this list have already been processed and are not elegable for visiting.
myPointsToIgnore={}
myPointToVisit=nil
mySubtaskId = -1
myVisitEndTime = 0
myVisitStage = nil
-- Called when reactive task is enabled or changes to the enabled state.
function checkInit()
-- Set the tick period for this script while checking.
vrf:setTickPeriod(2)
end
-- Remove points from the ignore list if they are sufficently far away, so the entity can consider visiting them again later.
function expireIgnorePoints()
for i, point in ipairs(myPointsToIgnore) do
if (not point:isValid() or
this:getLocation3D():distanceToLocation3D(point:getLocation3D()) > taskParameters.maxVisitDistance * 1.5) then
table.remove(myPointsToIgnore, i)
end
end
end
-- Return a nearby elegible point of interest or nil.
function findVisitPoint()
local nearPoi = vrf:getSimObjectsNearWithFilter(this:getLocation3D(), taskParameters.maxVisitDistance,
{types={thePointOfInterestType}, ignore=myPointsToIgnore})
if (#nearPoi > 0) then
local visitPoint = nearPoi[math.random(#nearPoi)]
return visitPoint
end
return nil
end
-- Called each tick period for this script while enabled but not in the active state.
function check()
local visitPoint = findVisitPoint()
if (visitPoint ~= nil) then
table.insert(myPointsToIgnore, visitPoint)
if (math.random(100) <= taskParameters.visitLiklihood) then
myPointToVisit = visitPoint
return true
end
end
expireIgnorePoints()
return false
end
-- Called when the task first starts. Never called again.
function init()
-- Set the tick period for this script.
vrf:setTickPeriod(0.5)
mySubtaskId = vrf:startSubtask("move-to", {control_point=myPointToVisit, at_distance=(math.random(20)/10 + 1)})
myVisitStage = "move-to"
end
-- Called each tick while this task is active.
function tick()
if (myVisitStage == "move-to") then
if (mySubtaskId >= 0) then
if (vrf:isSubtaskRunning(mySubtaskId) == false) then
mySubtaskId = vrf:startSubtask("Civilian_Idle", {})
-- Visit teh point for the specified visit time +/- 50%
myVisitEndTime = vrf:getSimulationTime() + taskParameters.visitTime / 2 + math.random(taskParameters.visitTime)
myVisitStage = "visiting"
end
end
elseif (myVisitStage == "visiting") then
if (vrf:getSimulationTime() >= myVisitEndTime) then
mySubtaskId = -1
myVisitPoint = nil
vrf:setTickPeriod(2)
vrf:endTask(true)
end
end
-- endTask() causes the current task to end once the current tick is complete. tick() will not be called again.
-- Wrap it in an appropriate test for completion of the task.
end
-- Called when this task is being suspended, likely by a reaction activating.
function suspend()
-- By default, halt all subtasks and other entity tasks started by this task when suspending.
vrf:stopAllSubtasks()
vrf:stopAllTasks()
end
-- Called when this task is being resumed after being suspended.
function resume()
-- By default, simply call init() to start the task over.
init()
end
-- Called immediately before a scenario checkpoint is saved when
-- this task is active.
-- It is typically not necessary to add code to this function.
function saveState()
end
-- Called immediately after a scenario checkpoint is loaded in which
-- this task is active.
-- It is typically not necessary to add code to this function.
function loadState()
end
-- Called when this task is ending, for any reason.
-- It is typically not necessary to add code to this function.
function shutdown()
end
-- Called whenever the entity receives a text report message while
-- this task is active.
-- message is the message text string.
-- sender is the SimObject which sent the message.
function receiveTextMessage(message, sender)
end
-- Called when a reactive task is disabled (check will no longer called)
-- It is typically not necessary to add code to this function.
function disable()
end
|
-- ?? helps with all the warnings spam
local vim = vim
local utils = require('rust-tools.utils.utils')
local M = {}
local function get_params()
return vim.lsp.util.make_position_params()
end
local latest_buf_id = nil
-- parse the lines from result to get a list of the desirable output
-- Example:
-- // Recursive expansion of the eprintln macro
-- // ============================================
-- {
-- $crate::io::_eprint(std::fmt::Arguments::new_v1(&[], &[std::fmt::ArgumentV1::new(&(err),std::fmt::Display::fmt),]));
-- }
local function parse_lines(t)
local ret = {}
local name = t.name
local text = "// Recursive expansion of the " .. name .. " macro"
table.insert(ret, "// " .. string.rep("=", string.len(text) - 3))
table.insert(ret, text)
table.insert(ret, "// " .. string.rep("=", string.len(text) - 3))
table.insert(ret, "")
local expansion = t.expansion
for string in string.gmatch(expansion, "([^\n]+)") do
table.insert(ret, string)
end
return ret
end
local function handler(_, _, result, _, _, _)
-- echo a message when result is nil (meaning no macro under cursor) and
-- exit
if result == nil then
vim.api.nvim_out_write("No macro under cursor!\n")
return;
end
-- check if a buffer with the latest id is already open, if it is then
-- delete it and continue
utils.delete_buf(latest_buf_id)
-- create a new buffer
latest_buf_id = vim.api.nvim_create_buf(true, true)
-- split the window to create a new buffer and set it to our window
utils.split(true, latest_buf_id)
-- set filetpe to rust for syntax highlighting
vim.api.nvim_buf_set_option(latest_buf_id, "filetype" ,"rust")
-- set the file name to [EXPANSION].rs ( copying vscode )
vim.api.nvim_buf_set_name(latest_buf_id, "[EXPANSION].rs")
-- write the expansion content to the buffer
vim.api.nvim_buf_set_lines(latest_buf_id, 0, 0, false, parse_lines(result))
-- make the new buffer smaller
utils.resize(true, "-25")
end
-- Sends the request to rust-analyzer to get cargo.tomls location and open it
function M.expand_macro()
vim.lsp.buf_request(0, "rust-analyzer/expandMacro", get_params(), handler)
end
return M
|
---@class CS.UnityEngine.AnimatorControllerParameter
---@field public name string
---@field public nameHash number
---@field public type number
---@field public defaultFloat number
---@field public defaultInt number
---@field public defaultBool boolean
---@type CS.UnityEngine.AnimatorControllerParameter
CS.UnityEngine.AnimatorControllerParameter = { }
---@return CS.UnityEngine.AnimatorControllerParameter
function CS.UnityEngine.AnimatorControllerParameter.New() end
---@return boolean
---@param o CS.System.Object
function CS.UnityEngine.AnimatorControllerParameter:Equals(o) end
---@return number
function CS.UnityEngine.AnimatorControllerParameter:GetHashCode() end
return CS.UnityEngine.AnimatorControllerParameter
|
-----------------------------------
-- Area: Dynamis-Xarcabard
-----------------------------------
require("scripts/globals/keyitems")
require("scripts/globals/dynamis")
require("scripts/globals/zone")
-----------------------------------
zones = zones or {}
zones[tpz.zone.DYNAMIS_XARCABARD] =
{
text =
{
ITEM_CANNOT_BE_OBTAINED = 6382, -- You cannot obtain the <item>. Come back after sorting your inventory.
ITEM_OBTAINED = 6388, -- Obtained: <item>.
GIL_OBTAINED = 6389, -- Obtained <number> gil.
KEYITEM_OBTAINED = 6391, -- Obtained key item: <keyitem>.
CONQUEST_BASE = 7055, -- Tallying conquest results...
DYNAMIS_TIME_BEGIN = 7214, -- The sands of the <item> have begun to fall. You have <number> minutes (Earth time) remaining in Dynamis.
DYNAMIS_TIME_EXTEND = 7215, -- our stay in Dynamis has been extended by <number> minute[/s].
DYNAMIS_TIME_UPDATE_1 = 7216, -- ou will be expelled from Dynamis in <number> [second/minute] (Earth time).
DYNAMIS_TIME_UPDATE_2 = 7217, -- ou will be expelled from Dynamis in <number> [seconds/minutes] (Earth time).
DYNAMIS_TIME_EXPIRED = 7219, -- The sands of the hourglass have emptied...
OMINOUS_PRESENCE = 7230, -- You feel an ominous presence, as if something might happen if you possessed <item>.
ANIMATED_KNUCKLES_DIALOG = 7297, -- I am known as the Fists of Mystics. Come, show me your fighting spirit.
ANIMATED_DAGGER_DIALOG = 7329, -- I am called the Ornate Blade. Now, show me your strength.
ANIMATED_LONGSWORD_DIALOG = 7361, -- People have named me the Holy Blade. I will try thy resolution.
ANIMATED_CLAYMORE_DIALOG = 7393, -- I am the Intricate Blade. Show me the depths of your fury!
ANIMATED_TABAR_DIALOG = 7425, -- Me, axe. Runaeic, Axe. You, die?
ANIMATED_GREATAXE_DIALOG = 7457, -- I have been given the title of Seraphic Axe. Will you attempt to survive my love?
ANIMATED_SPEAR_DIALOG = 7489, -- I am the Stellar Spear. It is time to test your courage.
ANIMATED_SCYTHE_DIALOG = 7521, -- I am known as the Tenebrous Scythe. Overwhelm me with your greed for power.
ANIMATED_KUNAI_DIALOG = 7553, -- I am called the Demoniac Blade. Allow me to witness your technique.
ANIMATED_TACHI_DIALOG = 7585, -- I am the Divine Blade. I demand a test of your will.
ANIMATED_HAMMER_DIALOG = 7617, -- People have named me the Heavenly Hammer. I will test your might to its very limits.
ANIMATED_STAFF_DIALOG = 7649, -- I am called the Celestial Staff. I will glimpse into your mind's eye...
ANIMATED_LONGBOW_DIALOG = 7681, -- I am known as the Snarled Bow. I will measure the limits of your determination.
ANIMATED_GUN_DIALOG = 7713, -- I am known as the Ethereal Rifle. Do you realize my incredible value?
ANIMATED_HORN_DIALOG = 7745, -- I am called the Mysterial Horn. Show me your true intentions.
ANIMATED_SHIELD_DIALOG = 7777, -- I am Aegis, the impervious shield of everlasting.
PRISON_OF_SOULS_HAS_SET_FREE = 7809, -- e prison of souls has set free its captive spirits!
},
mob =
{
TIME_EXTENSION =
{
{minutes = 10, ki = tpz.ki.CRIMSON_GRANULES_OF_TIME, mob = 17330531},
{minutes = 10, ki = tpz.ki.AZURE_GRANULES_OF_TIME, mob = 17330532},
{minutes = 10, ki = tpz.ki.AMBER_GRANULES_OF_TIME, mob = 17330533},
{minutes = 10, ki = tpz.ki.ALABASTER_GRANULES_OF_TIME, mob = 17330534},
{minutes = 20, ki = tpz.ki.OBSIDIAN_GRANULES_OF_TIME, mob = 17330535},
},
REFILL_STATUE =
{
{
{mob = 17330230, eye = dynamis.eye.RED }, -- Adamantking_Effigy
{mob = 17330231, eye = dynamis.eye.GREEN},
},
{
{mob = 17330240, eye = dynamis.eye.RED }, -- Adamantking_Effigy
{mob = 17330241, eye = dynamis.eye.BLUE },
},
{
{mob = 17330248, eye = dynamis.eye.RED }, -- Serjeant_Tombstone
{mob = 17330249, eye = dynamis.eye.GREEN},
},
{
{mob = 17330256, eye = dynamis.eye.RED }, -- Serjeant_Tombstone
{mob = 17330257, eye = dynamis.eye.BLUE },
},
{
{mob = 17330273, eye = dynamis.eye.RED }, -- Avatar_Icon
{mob = 17330274, eye = dynamis.eye.GREEN},
},
{
{mob = 17330285, eye = dynamis.eye.RED }, -- Avatar_Icon
{mob = 17330286, eye = dynamis.eye.BLUE },
},
{
{mob = 17330471, eye = dynamis.eye.RED }, -- Goblin_Replica
{mob = 17330472, eye = dynamis.eye.GREEN},
},
{
{mob = 17330483, eye = dynamis.eye.RED }, -- Goblin_Replica
{mob = 17330484, eye = dynamis.eye.BLUE },
},
},
YING = 17330183,
COUNT_ZAEBOS_PH = {[17330376] = 17330377}, -- Kindred_Warrior
DUKE_GOMORY_PH = {[17330303] = 17330304}, -- Kindred_Monk
PRINCE_SEERE_PH = {[17330331] = 17330332}, -- Kindred_White_Mage
MARQUIS_ORIAS_PH = {[17330333] = 17330343}, -- Kindred_Black_Mage
DUKE_BERITH_PH = {[17330352] = 17330353}, -- Kindred_Red_Mage
COUNT_RAUM_PH = {[17330314] = 17330315}, -- Kindred_Thief
MARQUIS_SABNAK_PH = {[17330359] = 17330360}, -- Kindred_Paladin
DUKE_SCOX_PH = {[17330427] = 17330417}, -- Kindred_Dark_Knight
MARQUIS_ANDRAS_PH = {[17330388] = 17330390}, -- Kindred_Beastmaster
MARQUIS_DECARABIA_PH = {[17330222] = 17330223}, -- Kindred_Bard
MARQUIS_CIMERIES_PH = {[17330414] = 17330415}, -- Kindred_Ranger
COUNT_VINE_PH = {[17330439] = 17330440}, -- Kindred_Samurai
MARQUIS_GAMYGYN_PH = {[17330450] = 17330451}, -- Kindred_Ninja
KING_ZAGAN_PH = {[17330418] = 17330430}, -- Kindred_Dragoon
MARQUIS_NEBIROS_PH = {[17330479] = 17330481}, -- Kindred_Summoner
},
npc =
{
QM =
{
[17330780] =
{
param = {3358, 3429, 3430, 3431, 3432, 3433},
trade =
{
{item = 3358, mob = 17330177}, -- Dynamis Lord
{item = {3429, 3430, 3431, 3432, 3433}, mob = 17330191}, -- Arch Dynamis Lord
}
},
[17330781] = {trade = {{item = 3400, mob = 17330185}}}, -- Duke Haures
[17330782] = {trade = {{item = 3401, mob = 17330186}}}, -- Marquis Caim
[17330783] = {trade = {{item = 3402, mob = 17330188}}}, -- Baron Avnas
[17330784] = {trade = {{item = 3403, mob = 17330189}}}, -- Count Haagenti
[17330785] = {trade = {{item = 3364, mob = 17330199}}}, -- Animated Knuckles
[17330786] = {trade = {{item = 3365, mob = 17330200}}}, -- Animated Dagger
[17330787] = {trade = {{item = 3366, mob = 17330201}}}, -- Animated Longsword
[17330788] = {trade = {{item = 3367, mob = 17330202}}}, -- Animated Claymore
[17330789] = {trade = {{item = 3368, mob = 17330203}}}, -- Animated Tabar
[17330790] = {trade = {{item = 3369, mob = 17330204}}}, -- Animated Great Axe
[17330791] = {trade = {{item = 3371, mob = 17330205}}}, -- Animated Spear
[17330792] = {trade = {{item = 3370, mob = 17330206}}}, -- Animated Scythe
[17330793] = {trade = {{item = 3372, mob = 17330207}}}, -- Animated Kunai
[17330794] = {trade = {{item = 3373, mob = 17330208}}}, -- Animated Tachi
[17330795] = {trade = {{item = 3374, mob = 17330209}}}, -- Animated Hammer
[17330796] = {trade = {{item = 3375, mob = 17330210}}}, -- Animated Staff
[17330797] = {trade = {{item = 3376, mob = 17330211}}}, -- Animated Longbow
[17330798] = {trade = {{item = 3377, mob = 17330212}}}, -- Animated Gun
[17330799] = {trade = {{item = 3378, mob = 17330213}}}, -- Animated Horn
[17330800] = {trade = {{item = 3379, mob = 17330214}}}, -- Animated Shield
},
},
}
return zones[tpz.zone.DYNAMIS_XARCABARD]
|
-- Copyright 2016 Yat Hin Wong
local raycast = {}
local camera = {}
local rsin, rcos -- ray sine and cosine
local function tableConcat(t1, t2)
for i=1, #t2 do
t1[#t1+1] = t2[i]
end
return t1
end
-- finds the next grid intersection
local function step(rise, run, x, y, inverted)
if run == 0 then
return {length2 = math.huge}
end
local dx = run > 0 and math.floor(x+1)-x or math.ceil(x-1)-x
local dy = dx * (rise/run)
return {x = inverted and y + dy or x + dx,
y = inverted and x + dx or y + dy,
length2 = dx * dx + dy * dy}
end
-- checks wall presence and sets eventual height and distance from player
local function inspect(step, shiftX, shiftY, distance, offset)
local dx = rcos < 0 and shiftX or 0
local dy = rsin < 0 and shiftY or 0
step.height = map.get(step.x - dx, step.y - dy)
step.distance = distance + math.sqrt(step.length2)
if shiftX > 0 then
step.shading = rcos < 0 and 2 or 0
else
step.shading = rsin < 0 and 2 or 1
end
step.offset = offset - math.floor(offset)
return step
end
-- casts a ray and checks if it encounters a wall
local function cast(origin)
local stepX = step(rsin, rcos, origin.x, origin.y, false)
local stepY = step(rcos, rsin, origin.y, origin.x, true)
local nextStep = stepX.length2 < stepY.length2 and
inspect(stepX, 1, 0, origin.distance, stepX.y) or
inspect(stepY, 0, 1, origin.distance, stepY.x)
if nextStep.distance > camera.range then
return {origin}
else
return tableConcat({origin}, cast(nextStep))
end
end
-- draws a rectangle for each raycast
local function drawColumn(column, ray, angle)
local left = math.floor(column * camera.spacing)
local width = math.ceil(camera.spacing)
for i,step in ipairs(ray) do
if step.height > 0 then
local z = step.distance * math.cos(angle)
local height = camera.height * step.height / z
local top = camera.height / 2 * (1 + 1 / z) - height
local factor = math.max(150 - (math.max(step.distance + step.shading, 0)*255/15),0)
love.graphics.setColor(255, 255, 255, factor)
love.graphics.rectangle("fill", left, top, width, height)
return
end
end
end
function raycast.init(w, h, res, fl, range)
camera.width = w
camera.height = h
camera.resolution = res
camera.spacing = camera.width / camera.resolution
camera.focalLength = fl
camera.range = range
end
function raycast.draw()
for column = 0, camera.resolution-1 do
local x = column / camera.resolution - 0.5
local angle = math.atan2(x, camera.focalLength)
rsin = math.sin(player.direction + angle)
rcos = math.cos(player.direction + angle)
local ray = cast({x = player.x, y = player.y, height = 0, distance = 0})
drawColumn(column, ray, angle)
end
end
return raycast
|
local json = require('arken.json')
local url = require('arken.net.url')
local test = {}
test.should_return_table_of_parse = function()
local result = url.parseQuery("val1=123&val2=strval")
assert(type(result) == 'table')
assert(result.val1 == '123', json.encode(result))
assert(result.val2 == 'strval', json.encode(result))
end
test.should_return_value_of_query_with_data_format = function()
local result = url.parseQuery("date1=01%2F10%2F2018&date2=31%2F10%2F2018&x=36&y=4")
assert(type(result) == 'table')
assert(result.date1 == '01/10/2018', result.date1)
assert(result.date2 == '31/10/2018', result.date2)
end
test.should_return_table_if_nil = function()
local result = url.parseQuery(nil)
assert(type(result) == 'table')
end
test.should_return_table_if_empty_string = function()
local result = url.parseQuery('')
assert(type(result) == 'table')
end
test.should_return_multiple_table = function()
local result = url.parseQuery("form[val1]=123&form[val2]=strval")
assert(type(result) == 'table')
assert(type(result.form) == 'table')
assert(result.form.val1 == '123', json.encode(result))
assert(result.form.val2 == 'strval', json.encode(result))
end
test.should_return_converting_param_with_array = function()
local result = url.parseQuery("val%5B1%5D=val1&val%5B2%5D=val2&val%5B3%5D=val3")
assert(type(result.val) == "table", json.encode(result))
assert(result.val['1'] == "val1", result.val[1])
end
test.should_return_array_query = function()
local result = url.parseQuery("var[]=1234&var[]=2345&var[]=9876")
assert(result.var[1] == '1234', result.var[1] )
assert(result.var[2] == '2345', result.var[2] )
assert(result.var[3] == '9876', result.var[3] )
end
test.should_return_hash_and_hash_query = function()
local result = url.parseQuery("var[1234][id]=1234&var[1234][name]=John")
assert(result.var['1234'].id == '1234')
assert(result.var['1234'].name == 'John')
end
test.should_return_hash_and_hash_query_and_empty_var = function()
local result = url.parseQuery("var[1234][id]=1234&var[1234][name]=John&var[2345][id]=&var[2345][name]=")
assert(result.var['2345'].id == '')
assert(result.var['2345'].name == '')
end
test.should_return_hash_and_array_query = function()
local result = url.parseQuery("var[1234][]=1234&var[1234][]=John")
assert(result.var['1234'][1] == '1234')
assert(result.var['1234'][2] == 'John')
end
test.should_return_array_inside_array = function()
local result = url.parseQuery("var[][]=1234&var[][]=John")
assert(result.var[1][1] == '1234')
assert(result.var[2][1] == 'John')
end
test.should_return_array_with_array_encoded = function()
local query = "data=11%2F11%2F2018&deposito_id%5B%5D=11&deposito_id%5B%5D=21&deposito_id%5B%5D=2&deposito_id%5B%5D=3&deposito_id%5B%5D=4&deposito_id%5B%5D=1&tabela_id=1&codigo=&produto=&familia_id=&fabricante_id=&descricao=true&total_estoque=true&venda=true&exportar=&x=22&y=10"
local result = url.parseQuery(query)
assert( type(result.deposito_id) == 'table', json.encode(result.deposito_id))
assert( result.deposito_id[1] == '11', result.deposito_id[1])
end
return test
|
hslk_conf = function(conf)
F6_CONF_SET(conf)
end
hslk_ability = function(_v)
_v = F6V_A(_v)
_v._id = SLK_ID(_v)
SLK_GO_SET(_v)
return _v
end
hslk_ability_empty = function(_v)
_v._parent = "Aamk"
_v._type = "empty"
_v.levels = _v.levels or 1
_v.hero = _v.hero or 0
local data = {}
for _ = 1, _v.levels do
table.insert(data, 0)
end
_v.DataA = data
_v.DataB = data
_v.DataC = data
_v = F6V_A(_v)
_v._id = SLK_ID(_v)
SLK_GO_SET(_v)
return _v
end
hslk_ability_ring = function(_v)
_v._parent = "Aamk"
_v._type = "ring"
_v.levels = _v.levels or 1
_v.hero = _v.hero or 0
local data = {}
for _ = 1, _v.levels do
table.insert(data, 0)
end
_v.DataA = data
_v.DataB = data
_v.DataC = data
_v = F6V_A(_v)
_v._id = SLK_ID(_v)
SLK_GO_SET(_v)
return _v
end
hslk_unit = function(_v)
_v = F6V_U(_v)
_v._id = SLK_ID(_v)
SLK_GO_SET(_v)
return _v
end
hslk_hero = function(_v)
_v._parent = "Hpal"
_v._type = "hero"
_v = F6V_U(_v)
_v._id = SLK_ID(_v)
SLK_GO_SET(_v)
return _v
end
hslk_courier = function(_v)
_v._parent = "ogru"
_v._type = "courier"
_v.type = "Peon"
_v.weapsOn = 0
_v.abilList = F6V_COURIER_SKILL()
_v = F6V_U(_v)
_v._id = SLK_ID(_v)
SLK_GO_SET(_v)
return _v
end
hslk_item_synthesis = function(formula)
CONST_UBERTIP_SYNTHESIS_REGISTER(formula)
end
hslk_item = function(_v)
_v = F6V_I(_v)
_v._id = SLK_ID(_v)
if (type(_v._shadow) == "boolean" and true == _v._shadow) then
local _vs = F6V_I_SHADOW(table.clone(_v))
_vs._id = SLK_ID(_vs)
_v._shadow_id = _vs._id
_vs._shadow_id = _v._id
SLK_GO_SET(_v)
SLK_GO_SET(_vs)
else
SLK_GO_SET(_v)
end
return _v
end
hslk_item_fleeting = function(Name, file, modelScale, moveHeight)
if (Name == nil or file == nil or modelScale == nil or moveHeight == nil) then
return
end
local _v = {
_parent = "ogru",
_type = "system",
EditorSuffix = "",
Name = Name,
special = 1,
abilList = "Avul,Aloc",
upgrade = "",
collision = 0.00,
modelScale = modelScale,
file = file,
unitShadow = "",
Art = "",
movetp = "",
moveHeight = moveHeight,
spd = 0,
turnRate = 0.1,
weapsOn = 0,
race = "other",
fused = 0,
sight = 0,
nsight = 0,
}
_v = F6V_U(_v)
_v._id = SLK_ID(_v)
SLK_GO_SET(_v)
return _v
end
hslk_buff = function(_v)
_v = F6V_B(_v)
_v._id = SLK_ID(_v)
SLK_GO_SET(_v)
return _v
end
hslk_upgrade = function(_v)
_v = F6V_UP(_v)
_v._id = SLK_ID(_v)
SLK_GO_SET(_v)
return _v
end
|
--world quest tracker object
local WorldQuestTracker = WorldQuestTrackerAddon
if (not WorldQuestTracker) then
return
end
--framework
local DF = _G ["DetailsFramework"]
if (not DF) then
print ("|cFFFFAA00World Quest Tracker: framework not found, if you just installed or updated the addon, please restart your client.|r")
return
end
--localization
local L = LibStub ("AceLocale-3.0"):GetLocale ("WorldQuestTrackerAddon", true)
if (not L) then
return
end
local ff = WorldQuestTrackerFinderFrame
local rf = WorldQuestTrackerRareFrame
local _
local GetQuestsForPlayerByMapID = C_TaskQuest.GetQuestsForPlayerByMapID
local QuestMapFrame_IsQuestWorldQuest = QuestMapFrame_IsQuestWorldQuest or QuestUtils_IsQuestWorldQuest
local GetNumQuestLogRewardCurrencies = GetNumQuestLogRewardCurrencies
local GetQuestLogRewardInfo = GetQuestLogRewardInfo
local GetQuestLogRewardCurrencyInfo = GetQuestLogRewardCurrencyInfo
local GetQuestLogRewardMoney = GetQuestLogRewardMoney
local GetQuestTagInfo = GetQuestTagInfo
local GetNumQuestLogRewards = GetNumQuestLogRewards
local GetQuestInfoByQuestID = C_TaskQuest.GetQuestInfoByQuestID
local MapRangeClamped = DF.MapRangeClamped
local FindLookAtRotation = DF.FindLookAtRotation
local GetDistance_Point = DF.GetDistance_Point
local triggerScheduledWidgetUpdate = function (timerObject)
local widget = timerObject.widget
local questID = widget.questID
if (not widget:IsShown()) then
return
end
if (HaveQuestRewardData (questID)) then
--is a zone widget placed in the world hub
if (widget.IsWorldZoneQuestButton) then
WorldQuestTracker.SetupWorldQuestButton (widget, true)
--is a square button in the world map
elseif (widget.IsWorldQuestButton) then
WorldQuestTracker.UpdateWorldWidget (widget, true)
--is a zone widget placed in the zone
elseif (widget.IsZoneQuestButton) then
WorldQuestTracker.SetupWorldQuestButton (widget, true)
--is a zone widget placed in the taxi map
elseif (widget.IsTaxiQuestButton) then
WorldQuestTracker.SetupWorldQuestButton (widget, true)
--is a zone widget placed in the zone summary frame
elseif (widget.IsZoneSummaryButton) then
WorldQuestTracker.SetupWorldQuestButton (widget, true)
end
else
WorldQuestTracker.CheckQuestRewardDataForWidget (widget, false, true)
end
end
function WorldQuestTracker.CheckQuestRewardDataForWidget (widget, noScheduleRefresh, noRequestData)
local questID = widget.questID
if (not questID) then
return false
end
if (not HaveQuestRewardData (questID)) then
--if this is from a re-schedule it already requested the data
if (not noRequestData) then
--ask que server for the reward data
C_TaskQuest.RequestPreloadRewardData (questID)
end
if (not noScheduleRefresh) then
local timer = C_Timer.NewTimer (1, triggerScheduledWidgetUpdate)
timer.widget = widget
return false, true
end
return false
end
return true
end
function WorldQuestTracker.HaveDataForQuest (questID)
return HaveQuestData (questID) and HaveQuestRewardData (questID)
end
--return the list of quests on the tracker
function WorldQuestTracker.GetTrackedQuests()
return WorldQuestTracker.QuestTrackList
end
--does the the zone have world quests?
function WorldQuestTracker.ZoneHaveWorldQuest (mapID)
--print (WorldQuestTracker.MapData, WorldQuestTracker.MapData.WorldQuestZones)
return WorldQuestTracker.MapData.WorldQuestZones [mapID or WorldQuestTracker.GetCurrentMapAreaID()]
end
--is a argus zone?
function WorldQuestTracker.IsArgusZone (mapID)
if (WorldQuestTracker.MapData.ZoneIDs.ANTORAN == mapID) then
return true
elseif (WorldQuestTracker.MapData.ZoneIDs.KROKUUN == mapID) then
return true
elseif (WorldQuestTracker.MapData.ZoneIDs.MCCAREE == mapID) then
return true
end
end
--is the current map zone a world quest hub?
function WorldQuestTracker.IsWorldQuestHub (mapID)
return WorldQuestTracker.MapData.QuestHubs [mapID]
end
--is the current map a quest hub? (wait why there's two same functions?)
function WorldQuestTracker.IsCurrentMapQuestHub()
local currentMap = WorldQuestTracker.GetCurrentMapAreaID()
return WorldQuestTracker.MapData.QuestHubs [currentMap]
end
--return if the zone is a quest hub or if a common zone
function WorldQuestTracker.GetCurrentZoneType()
if (WorldQuestTracker.ZoneHaveWorldQuest (WorldQuestTracker.GetCurrentMapAreaID())) then
return "zone"
elseif (WorldQuestTracker.IsWorldQuestHub (WorldMapFrame.mapID) or WorldQuestTracker.IsCurrentMapQuestHub()) then
return "world"
end
end
function WorldQuestTracker.GetMapInfo (uiMapId)
if (not uiMapId) then
uiMapId = C_Map.GetBestMapForUnit ("player")
if (uiMapId) then
return C_Map.GetMapInfo (uiMapId)
else
--print ("C_Map.GetBestMapForUnit ('player1'): returned NIL")
end
else
return C_Map.GetMapInfo (uiMapId)
end
end
function WorldQuestTracker.GetMapName (uiMapId)
local mapInfo = C_Map.GetMapInfo (uiMapId)
if (mapInfo) then
local mapName = mapInfo and mapInfo.name or "wrong map id"
return mapName
else
return "wrong map id"
end
end
--verifica se pode mostrar os widgets de broken isles
function WorldQuestTracker.CanShowWorldMapWidgets (noFade)
if (WorldQuestTracker.IsWorldQuestHub (WorldMapFrame.mapID) or WorldQuestTracker.IsCurrentMapQuestHub()) then
if (noFade) then
WorldQuestTracker.UpdateWorldQuestsOnWorldMap()
else
WorldQuestTracker.UpdateWorldQuestsOnWorldMap (false, true)
end
else
WorldQuestTracker.HideWorldQuestsOnWorldMap()
end
end
--return which are the current bounty quest id selected
function WorldQuestTracker.GetCurrentBountyQuest()
return WorldQuestTracker.DataProvider.bountyQuestID or 0
end
--return a map table with quest ids as key and true as value
function WorldQuestTracker.GetAllWorldQuests_Ids()
local allQuests, dataUnavaliable = {}, false
for mapId, configTable in pairs (WorldQuestTracker.mapTables) do
--local taskInfo = GetQuestsForPlayerByMapID (mapId, 1007)
local taskInfo = GetQuestsForPlayerByMapID (mapId)
if (taskInfo and #taskInfo > 0) then
for i, info in ipairs (taskInfo) do
local questID = info.questId
if (HaveQuestData (questID)) then
local isWorldQuest = QuestMapFrame_IsQuestWorldQuest (questID)
if (isWorldQuest) then
allQuests [questID] = true
if (not HaveQuestRewardData (questID)) then
C_TaskQuest.RequestPreloadRewardData (questID)
end
end
else
dataUnavaliable = true
end
end
else
dataUnavaliable = true
end
end
return allQuests, dataUnavaliable
end
--pega o nome da zona
function WorldQuestTracker.GetZoneName (mapID)
if (not mapID) then
return ""
end
local mapInfo = WorldQuestTracker.GetMapInfo (mapID)
return mapInfo and mapInfo.name or ""
end
--8.0 doesnt work
function WorldQuestTracker.IsASubLevel()
--local level, x1 = GetCurrentMapDungeonLevel()
--[[
if (level and level > 0 and x1) then
x1 = floor (x1)
--vindicar antoran
if (level == 5 and floor (x1) == 8479) then
return true
end
--vindicar krokuun
if (level == 1 and floor (x1) == 1302) then
return true
end
--vindicar mccree
if (level == 3 and floor (x1) == 9689) then
return true
end
end
--]]
--if (level and level > 0 and x1 and level < 8) then
-- return true
--end
end
function WorldQuestTracker.GetOrLoadQuestData (questID, canCache, dontCatchAP)
local data = WorldQuestTracker.CachedQuestData [questID]
if (data) then
return unpack (data)
end
local tagID, tagName, worldQuestType, rarity, isElite, tradeskillLineIndex, allowDisplayPastCritical = GetQuestTagInfo (questID)
local gold, goldFormated = WorldQuestTracker.GetQuestReward_Gold (questID)
local rewardName, rewardTexture, numRewardItems = WorldQuestTracker.GetQuestReward_Resource (questID)
local title, factionID, tagID, tagName, worldQuestType, rarity, isElite, tradeskillLineIndex = WorldQuestTracker.GetQuest_Info (questID)
local itemName, itemTexture, itemLevel, quantity, quality, isUsable, itemID, isArtifact, artifactPower, isStackable, stackAmount
if (not dontCatchAP) then
itemName, itemTexture, itemLevel, quantity, quality, isUsable, itemID, isArtifact, artifactPower, isStackable, stackAmount = WorldQuestTracker.GetQuestReward_Item (questID)
end
if (WorldQuestTracker.CanCacheQuestData and canCache) then
WorldQuestTracker.CachedQuestData [questID] = {title, factionID, tagID, tagName, worldQuestType, rarity, isElite, tradeskillLineIndex, tagID, tagName, worldQuestType, rarity, isElite, tradeskillLineIndex, allowDisplayPastCritical, gold, goldFormated, rewardName, rewardTexture, numRewardItems, itemName, itemTexture, itemLevel, quantity, quality, isUsable, itemID, isArtifact, artifactPower, isStackable, stackAmount}
end
return title, factionID, tagID, tagName, worldQuestType, rarity, isElite, tradeskillLineIndex, tagID, tagName, worldQuestType, rarity, isElite, tradeskillLineIndex, allowDisplayPastCritical, gold, goldFormated, rewardName, rewardTexture, numRewardItems, itemName, itemTexture, itemLevel, quantity, quality, isUsable, itemID, isArtifact, artifactPower, isStackable, stackAmount
end
function WorldQuestTracker.GetCurrentStandingMapAreaID()
if (C_Map) then
local mapId = C_Map.GetBestMapForUnit ("player")
if (mapId) then
return mapId
else
return 0
end
else
return GetCurrentMapAreaID()
end
end
--return the current map the map is showing
function WorldQuestTracker.GetCurrentMapAreaID()
--local mapID = WorldQuestTracker.DataProvider:GetMap():GetMapID()
local mapID = WorldMapFrame.mapID
if (mapID) then
return mapID
else
if (C_Map) then
local mapId = C_Map.GetBestMapForUnit ("player")
if (mapId) then
return mapId
else
return 0
end
else
return GetCurrentMapAreaID()
end
end
end
function WorldQuestTracker.CanShowQuest (info)
local canShowQuest = WorldQuestTracker.DataProvider:ShouldShowQuest (info)
return canShowQuest
--return not WorldQuestTracker.DataProvider.focusedQuestID and not WorldQuestTracker.DataProvider:IsQuestSuppressed(info.questId);
--return canShowQuest
end
-- ~filter
function WorldQuestTracker.GetQuestFilterTypeAndOrder (worldQuestType, gold, rewardName, itemName, isArtifact, stackAmount, numRewardItems, rewardTexture)
local filter, order
--[=[
/run for key, value in pairs (_G) do if type(key) == "string" and key:find ("LE_QUEST_TAG") then print (key, value) end end
LE_QUEST_TAG_TYPE_PVP = 3
LE_QUEST_TAG_TYPE_PET_BATTLE = 4
LE_QUEST_TAG_TYPE_NORMAL = 2
LE_QUEST_TAG_TYPE_PROFESSION = 1
LE_QUEST_TAG_TYPE_DUNGEON = 6
LE_QUEST_TAG_TYPE_RAID = 8
LE_QUEST_TAG_TYPE_TAG = 0
LE_QUEST_TAG_TYPE_BOUNTY = 5
LE_QUEST_TAG_TYPE_INVASION = 7
LE_QUEST_TAG_TYPE_INVASION_WRAPPER = 11
--]=]
--debug
if (worldQuestType == LE_QUEST_TAG_TYPE_NORMAL) then
-- print (LE_QUEST_TAG_TYPE_NORMAL, gold, rewardName, itemName, isArtifact, stackAmount, numRewardItems, rewardTexture)
end
if (worldQuestType == LE_QUEST_TAG_TYPE_PET_BATTLE) then
return FILTER_TYPE_PET_BATTLES, WorldQuestTracker.db.profile.sort_order [WQT_QUESTTYPE_PETBATTLE]
elseif (worldQuestType == LE_QUEST_TAG_TYPE_PVP) then
return FILTER_TYPE_PVP, WorldQuestTracker.db.profile.sort_order [WQT_QUESTTYPE_PVP]
elseif (worldQuestType == LE_QUEST_TAG_TYPE_PROFESSION) then
return FILTER_TYPE_PROFESSION, WorldQuestTracker.db.profile.sort_order [WQT_QUESTTYPE_PROFESSION]
elseif (worldQuestType == LE_QUEST_TAG_TYPE_DUNGEON) then
filter = FILTER_TYPE_DUNGEON
order = WorldQuestTracker.db.profile.sort_order [WQT_QUESTTYPE_DUNGEON]
end
if (gold and gold > 0) then
order = WorldQuestTracker.db.profile.sort_order [WQT_QUESTTYPE_GOLD]
filter = FILTER_TYPE_GOLD
end
--print (rewardName, rewardTexture)
if (rewardName) then
--print (rewardName, rewardTexture) --reputation token
--resources
if (WorldQuestTracker.MapData.ResourceIcons [rewardTexture]) then
order = WorldQuestTracker.db.profile.sort_order [WQT_QUESTTYPE_RESOURCE]
filter = FILTER_TYPE_GARRISON_RESOURCE
--reputation
elseif (WorldQuestTracker.MapData.ReputationIcons [rewardTexture]) then
order = WorldQuestTracker.db.profile.sort_order [WQT_QUESTTYPE_REPUTATION]
filter = FILTER_TYPE_REPUTATION_TOKEN
--trade skill
elseif (WorldQuestTracker.MapData.TradeSkillIcons [rewardTexture]) then
order = WorldQuestTracker.db.profile.sort_order [WQT_QUESTTYPE_TRADE]
filter = FILTER_TYPE_TRADESKILL
end
end
if (isArtifact) then
order = WorldQuestTracker.db.profile.sort_order [WQT_QUESTTYPE_APOWER]
filter = FILTER_TYPE_ARTIFACT_POWER
elseif (itemName) then
if (stackAmount > 1) then
order = WorldQuestTracker.db.profile.sort_order [WQT_QUESTTYPE_TRADE]
filter = FILTER_TYPE_TRADESKILL
else
order = WorldQuestTracker.db.profile.sort_order [WQT_QUESTTYPE_EQUIPMENT]
filter = FILTER_TYPE_EQUIPMENT
end
end
--> if dungeons are disabled, override the quest type to dungeon
if (worldQuestType == LE_QUEST_TAG_TYPE_DUNGEON) then
if (not WorldQuestTracker.db.profile.filters [FILTER_TYPE_DUNGEON]) then
filter = FILTER_TYPE_DUNGEON
end
end
if (not filter) then
filter = FILTER_TYPE_GARRISON_RESOURCE
order = 9
end
return filter, order
end
--create a tooltip scanner
local GameTooltipFrame = CreateFrame ("GameTooltip", "WorldQuestTrackerScanTooltip", nil, "GameTooltipTemplate")
local GameTooltipFrameTextLeft1 = _G ["WorldQuestTrackerScanTooltipTextLeft2"]
local GameTooltipFrameTextLeft2 = _G ["WorldQuestTrackerScanTooltipTextLeft3"]
local GameTooltipFrameTextLeft3 = _G ["WorldQuestTrackerScanTooltipTextLeft4"]
local GameTooltipFrameTextLeft4 = _G ["WorldQuestTrackerScanTooltipTextLeft5"]
--attempt to get the item level of the item
function WorldQuestTracker.RewardRealItemLevel (questID)
GameTooltipFrame:SetOwner (WorldFrame, "ANCHOR_NONE")
--GameTooltipFrame:SetHyperlink (itemLink)
GameTooltipFrame:SetQuestLogItem ("reward", 1, questID)
local Text = GameTooltipFrameTextLeft1:GetText() or GameTooltipFrameTextLeft2:GetText() or ""
local itemLevel = tonumber (Text:match ("%d+"))
return itemLevel or 1
end
--try to guess the amount of artifact power the item can give �rtifact ~artifact
--asia
function WorldQuestTracker.RewardIsArtifactPowerAsian (itemLink) -- thanks @yuk6196 on curseforge
GameTooltipFrame:SetOwner (WorldFrame, "ANCHOR_NONE")
GameTooltipFrame:SetHyperlink (itemLink)
local text = GameTooltipFrameTextLeft1:GetText()
if (text and text:match ("|cFFE6CC80")) then
local power = GameTooltipFrameTextLeft3:GetText()
if (power) then
local n = tonumber (power:match ("[%d.]+"))
if (power:find (SECOND_NUMBER)) then
n = n * 10000
elseif (power:find (THIRD_NUMBER)) then
n = n * 100000000
elseif (power:find (FOURTH_NUMBER)) then
n = n * 1000000000000
end
return true, n or 0
end
end
local text2 = GameTooltipFrameTextLeft2:GetText()
if (text2 and text2:match ("|cFFE6CC80")) then
local power = GameTooltipFrameTextLeft4:GetText()
if (power) then
local n = tonumber (power:match ("[%d.]+"))
if (power:find (SECOND_NUMBER)) then
n = n * 10000
elseif (power:find (THIRD_NUMBER)) then
n = n * 100000000
elseif (power:find (FOURTH_NUMBER)) then
n = n * 1000000000000
end
return true, n or 0
end
end
end
--german
function WorldQuestTracker.RewardIsArtifactPowerGerman (itemLink) -- thanks @Superanuki on curseforge
local w1, w2, w3, w4 = "Millionen", "Million", "%d+,%d+", "([^,]+),([^,]+)" --works for German
if (WorldQuestTracker.GameLocale == "ptBR") then
w1, w2, w3, w4 = "milh", "milh", "%d+,%d+", "([^,]+).([^,]+)" --@tercio 11 october 2017: replaced the dot with a comma on "%d+,%d+"
elseif (WorldQuestTracker.GameLocale == "frFR") then
w1, w2, w3, w4 = "million", "million", "%d+,%d+", "([^,]+),([^,]+)"
end
GameTooltipFrame:SetOwner (WorldFrame, "ANCHOR_NONE")
GameTooltipFrame:SetHyperlink (itemLink)
local text = GameTooltipFrameTextLeft1:GetText()
if (text and text:match ("|cFFE6CC80")) then
local power = GameTooltipFrameTextLeft3:GetText()
if (power) then
if (power:find (w1) or power:find (w2)) then
local n=power:match(w3)
if n then
local one,two=n:match(w4) n=one.."."..two
end
n = tonumber (n)
if (not n) then
n = power:match (" %d+ ") --thanks @Arwarld_ on curseforge - ticket #427
n = tonumber (n)
if (n) then
n=n..".0"
n = tonumber (n)
end
end
if (n) then
n = n * 1000000
return true, n or 0
end
end
if (WorldQuestTracker.GameLocale == "frFR") then
power = power:gsub ("%s", ""):gsub ("%p", ""):match ("%d+")
else
power = power:gsub ("%p", ""):match ("%d+")
end
power = tonumber (power)
return true, power or 0
end
end
local text2 = GameTooltipFrameTextLeft2:GetText()
if (text2 and text2:match ("|cFFE6CC80")) then
local power = GameTooltipFrameTextLeft4:GetText()
if (power) then
if (power:find (w1) or power:find (w2)) then
local n=power:match(w3)
if n then
local one,two=n:match(w4) n=one.."."..two
end
n = tonumber (n)
if (not n) then
n = power:match (" %d+ ")
n = tonumber (n)
n=n..".0"
n = tonumber (n)
end
if (n) then
n = n * 1000000
return true, n or 0
end
end
if (WorldQuestTracker.GameLocale == "frFR") then
power = power:gsub ("%s", ""):gsub ("%p", ""):match ("%d+")
else
power = power:gsub ("%p", ""):match ("%d+")
end
power = tonumber (power)
return true, power or 0
end
end
end
-- /run for a, b in pairs (_G) do if(b=="Artifact Power") then print (a, b) end end
--global
function WorldQuestTracker.RewardIsArtifactPower (itemLink)
if (WorldQuestTracker.GameLocale == "koKR" or WorldQuestTracker.GameLocale == "zhTW" or WorldQuestTracker.GameLocale == "zhCN") then
return WorldQuestTracker.RewardIsArtifactPowerAsian (itemLink)
elseif (WorldQuestTracker.GameLocale == "deDE" or WorldQuestTracker.GameLocale == "ptBR" or WorldQuestTracker.GameLocale == "frFR") then
return WorldQuestTracker.RewardIsArtifactPowerGerman (itemLink)
end
GameTooltipFrame:SetOwner (WorldFrame, "ANCHOR_NONE")
GameTooltipFrame:SetHyperlink (itemLink)
local text = GameTooltipFrameTextLeft1:GetText()
local power = GameTooltipFrameTextLeft3:GetText()
if ((text and text:match ("|cFFE6CC80")) or (power and power:match (ARTIFACT_POWER))) then
if (power) then
if (power:find (SECOND_NUMBER)) then
local n = power:match (" %d+%.%d+ ")
n = tonumber (n)
if (not n) then
n = power:match (" %d+ ")
n = tonumber (n)
end
if (n) then
n = n * 1000000
return true, n or 0
end
elseif (power:find (THIRD_NUMBER)) then
local n = power:match (" %d+%.%d+ ")
n = tonumber (n)
if (not n) then
n = power:match (" %d+ ")
n = tonumber (n)
end
if (n) then
n = n * 1000000000
return true, n or 0
end
end
if (WorldQuestTracker.GameLocale == "frFR") then
power = power:gsub ("%s", ""):gsub ("%p", ""):match ("%d+")
else
power = power:gsub ("%p", ""):match ("%d+")
end
power = tonumber (power)
return true, power or 0
end
end
local text2 = GameTooltipFrameTextLeft2:GetText() --thanks @Prejudice182 on curseforge
if (text2 and text2:match ("|cFFE6CC80")) then
local power = GameTooltipFrameTextLeft4:GetText()
if (power) then
if (power:find (SECOND_NUMBER)) then
local n = power:match (" %d+%.%d+ ")
n = tonumber (n)
if (not n) then
n = power:match (" %d+ ")
n = tonumber (n)
end
if (n) then
n = n * 1000000
return true, n or 0
end
end
if (WorldQuestTracker.GameLocale == "frFR") then
power = power:gsub ("%s", ""):gsub ("%p", ""):match ("%d+")
else
power = power:gsub ("%p", ""):match ("%d+")
end
power = tonumber (power)
return true, power or 0
end
end
end
--gold amount
function WorldQuestTracker.GetQuestReward_Gold (questID)
local gold = GetQuestLogRewardMoney (questID) or 0
local formated
if (gold > 10000000) then
formated = gold / 10000 --remove os zeros
formated = string.format ("%.1fK", formated / 1000)
else
formated = floor (gold / 10000)
end
return gold, formated
end
--resource amount
function WorldQuestTracker.GetQuestReward_Resource (questID)
local numQuestCurrencies = GetNumQuestLogRewardCurrencies (questID)
if (numQuestCurrencies == 2) then
for i = 1, numQuestCurrencies do
local name, texture, numItems = GetQuestLogRewardCurrencyInfo (i, questID)
--legion invasion quest
if (texture and
(
(type (texture) == "number" and texture == 132775) or
(type (texture) == "string" and (texture:find ("inv_datacrystal01") or texture:find ("inv_misc_summonable_boss_token")))
)
) then -- [[Interface\Icons\inv_datacrystal01]]
--BFA invasion quest (this check will force it to get the second reward
elseif (not WorldQuestTracker.MapData.IgnoredRewardTexures [texture]) then
return name, texture, numItems
end
end
else
for i = 1, numQuestCurrencies do
local name, texture, numItems = GetQuestLogRewardCurrencyInfo (i, questID)
return name, texture, numItems
end
end
end
--local ItemTooltipScan = CreateFrame ("GameTooltip", "WQTItemTooltipScan", UIParent, "EmbeddedItemTooltip")
local ItemTooltipScan = CreateFrame ("GameTooltip", "WQTItemTooltipScan", UIParent, "InternalEmbeddedItemTooltipTemplate")
ItemTooltipScan.texts = {
_G ["WQTItemTooltipScanTooltipTextLeft1"],
_G ["WQTItemTooltipScanTooltipTextLeft2"],
_G ["WQTItemTooltipScanTooltipTextLeft3"],
_G ["WQTItemTooltipScanTooltipTextLeft4"],
}
ItemTooltipScan.patern = ITEM_LEVEL:gsub ("%%d", "(%%d+)") --from LibItemUpgradeInfo-1.0
--pega o premio item da quest
function WorldQuestTracker.GetQuestReward_Item (questID)
if (not HaveQuestData (questID)) then
return
end
--artifact power - 8.0 version
local numQuestCurrencies = GetNumQuestLogRewardCurrencies (questID)
if (numQuestCurrencies == 1) then
--is artifact power?
local name, texture, numItems = GetQuestLogRewardCurrencyInfo (1, questID)
if (texture == 1830317 or texture == 2065624) then
--[=[
--the taxi map tooltip is adding the reward to the world map quest tooltip
GameTooltip_AddQuestRewardsToTooltip (WorldMapTooltip, questID)
local amount
local t2 = WorldMapTooltipTooltipTextLeft2 and WorldMapTooltipTooltipTextLeft2:GetText()
if (t2) then
amount = tonumber (t2:match (" %d+ "))
end
if (WorldMapTooltip:IsShown()) then
local owner = WorldMapTooltip:GetOwner()
if (owner and owner.UpdateTooltip) then
owner:UpdateTooltip()
end
end
--]=]
--return name, texture, 0, 1, 1, false, 0, true, amount or 0, false, 1
--numItems are now given the amount of azerite (BFA 17-09-2018), no more tooltip scan required
return name, texture, 0, 1, 1, false, 0, true, numItems or 0, false, 1
end
end
local numQuestRewards = GetNumQuestLogRewards (questID)
if (numQuestRewards > 0) then
local itemName, itemTexture, quantity, quality, isUsable, itemID = GetQuestLogRewardInfo (1, questID)
if (itemID) then
local itemName, itemLink, itemRarity, itemLevel, itemMinLevel, itemType, itemSubType, itemStackCount, itemEquipLoc, itemTexture, itemSellPrice, itemClassID, itemSubClassID = GetItemInfo (itemID)
if (itemName) then
EmbeddedItemTooltip_SetItemByQuestReward (ItemTooltipScan, 1, questID)
for i = 1, 4 do
local text = ItemTooltipScan.texts [i]:GetText()
if (text and text ~= "") then
local ilvl = tonumber (text:match (ItemTooltipScan.patern))
if (ilvl) then
itemLevel = ilvl
break
end
end
end
local icon = WorldQuestTracker.MapData.EquipmentIcons [itemEquipLoc]
if (not icon and itemClassID == 3 and itemSubClassID == 11) then
icon = WorldQuestTracker.MapData.EquipmentIcons ["Relic"]
end
if (icon and not WorldQuestTracker.db.profile.use_old_icons) then
itemTexture = icon
end
local isArtifact, artifactPower = WorldQuestTracker.RewardIsArtifactPower (itemLink)
local hasUpgrade = WorldQuestTracker.RewardRealItemLevel (questID)
itemLevel = itemLevel > hasUpgrade and itemLevel or hasUpgrade
if (isArtifact) then
return itemName, itemTexture, itemLevel, quantity, quality, isUsable, itemID, true, artifactPower, itemStackCount > 1, itemStackCount
else
--Returning an equipment
return itemName, itemTexture, itemLevel, quantity, quality, isUsable, itemID, false, 0, itemStackCount > 1, itemStackCount
end
else
--ainda n�o possui info do item
return
end
else
--ainda n�o possui info do item
return
end
end
end
|
do
local _class_0
local _base_0 = {
get = function(self, x, y)
return self.tiles[x][y]
end,
add_actor = function(self, actor)
local id = self:_id()
actor.id = id
actor.grid = self
self.actors[id] = actor
local tile = self.tiles[actor.x][actor.y]
tile:insert(actor)
return id
end,
update = function(self)
for _, actor in pairs(self.actors) do
actor:update()
end
end,
draw = function(self)
for x = 1, self.width do
for y = 1, self.height do
self.tiles[x][y]:draw()
end
end
end,
add_actor_at_position = function(self, x, y, actor)
actor.x, actor.y = x, y
return self:add_actor(actor)
end,
move_actor = function(self, x, y, id)
local a = self.actors[id]
self.tiles[a.x][a.y]:remove(a)
self.tiles[x][y]:insert(a)
a.x, a.y = x, y
end,
remove_actor = function(self, id)
local a = self.actors[id]
self.tiles[a.x][a.y]:remove(a)
self.actors[id] = nil
end,
_id = function(self)
self.next_id = self.next_id + 1
return self.next_id
end
}
_base_0.__index = _base_0
_class_0 = setmetatable({
__init = function(self, width, height, tile_class)
self.next_id = 0
self.width = width
self.height = height
self.actors = { }
self.tiles = { }
for x = 1, width do
self.tiles[x] = { }
for y = 1, height do
self.tiles[x][y] = tile_class(x, y)
end
end
end,
__base = _base_0,
__name = "Grid"
}, {
__index = _base_0,
__call = function(cls, ...)
local _self_0 = setmetatable({}, _base_0)
cls.__init(_self_0, ...)
return _self_0
end
})
_base_0.__class = _class_0
Grid = _class_0
return _class_0
end
|
local t =
Def.ActorFrame {
Def.Sprite {
Texture = NOTESKIN:GetPath("_down", "tap mine"),
Frames = Sprite.LinearFrames(8, 1)
}
}
return t
|
--------------------------------------------------------------------------------
-- Handler.......... : onLimitFPS
-- Author........... :
-- Description...... :
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
function ApplicationRuntimeOptions.onLimitFPS ( nTargetFPS )
--------------------------------------------------------------------------------
this.fFPSlimit ( nTargetFPS )
--------------------------------------------------------------------------------
end
--------------------------------------------------------------------------------
|
Ambi.Cache = Ambi.Cache or {}
-- ---------------------------------------------------------------------------------------------------------------------------------------------------------
local Gen = Ambi.General
local Fetch, isstring, isnumber, print, file = http.Fetch, isstring, isnumber, print, file
local crc = util.CRC
local MIN_SIZE_FILE = 2
file.CreateDir( 'ambi/cache' )
-- ---------------------------------------------------------------------------------------------------------------------------------------------------------
function Ambi.Cache.CacheURL( sPath, sURL, nAttempts, bNotRewrite ) -- Old
if nAttempts and ( nAttempts == 0 ) then return end
if not sPath or not isstring( sPath ) then return end
if not sURL or not isstring( sURL ) then return end
if not nAttempts or not isnumber( nAttempts ) or ( nAttempts < 0 ) or ( nAttempts >= 256 ) then Gen.Error( 'Cache', 'CacheURL | nAttempts is not valid or very long/small' ) return end
nAttempts = nAttempts or 1
Fetch( sURL, function( sBody, nSize )
if bNotRewrite and file.Exists( sPath, 'DATA' ) then
local hash_body, hash_file = util.CRC( sBody ), util.CRC( file.Read( sPath, 'DATA' ) )
if ( hash_body == hash_file ) then return end
end
file.Write( 'ambi/cache/'..sPath, sBody )
end )
timer.Simple( 0.55, function()
if ( ( file.Size( sPath, 'DATA' ) or 0 ) > MIN_SIZE_FILE ) then return end
Ambi.Cache.CacheURL( sPath, sURL, nAttempts - 1 )
end )
end
function Ambi.Cache.GetCacheFile( sPath ) -- Old
return '../data/ambi/cache/'..sPath
end
-- Выше два устаревших метода (до 28.04.2022), которые не будут обновляться!
-- ------------------------------------------------------------------------------------------------------------------------------
function Ambi.Cache.Add( sPath, sURL )
if not sPath or not isstring( sPath ) then return end
if not sURL or not isstring( sURL ) then return end
local path = 'ambi/cache/'..sPath
Fetch( sURL, function( sBody, nSize )
file.Write( path, sBody )
local file = file.Read( path )
hook.Call( '[Ambi.Cache.Added]', nil, file, sPath, sURL )
timer.Simple( 0.25, function()
local hash1 = crc( file or '' )
local hash2 = crc( sBody )
if ( hash1 == hash2 ) then return end
Ambi.Cache.Add( sPath, sURL )
end )
end )
end
function Ambi.Cache.Get( sPath )
return '../data/ambi/cache/'..sPath
end
function Ambi.Cache.Material( sPath )
return Material( '../data/ambi/cache/'..sPath )
end
|
---
--- Generated by EmmyLua(https://github.com/EmmyLua)
--- Created by thsheep.
--- DateTime: 2018/5/22 上午9:25
--- 这个lua脚本是为了代替集群中不支持的multi事务;保证在获取的同时删除
---
local result = redis.call('zrange', KEYS[1], 0, 0)
local element = result[1]
if element then
redis.call('zremrangebyrank', KEYS[1], 0, 0)
return element
else
return nil
end
|
-- tilemapper v0.0.5
-- Depends on:
-- - json.lua (https://github.com/rxi/json.lua)
-- - classic.lua (https://github.com/rxi/classic)
-- - bump.lua (https://github.com/kikito/bump.lua)
local json = require("lib.json")
local Tilemapper = Class:extend()
local Layer = Class:extend()
function Layer:new(tiles, name)
self.tiles = tiles
self.name = name
end
local TileLayer = Layer:extend()
function TileLayer:new(tiles, name, tileset, size, spacing, padding)
TileLayer.super.new(self, tiles, name)
self.type = "tile"
self.tileset = love.graphics.newImage(tileset)
self.size = size
local quadInfo = {}
for i = 1, #tiles do
local tile = tiles[i]
if not quadInfo[tile.t] then
quadInfo[tile.t] = tile.src
end
end
local quads = {}
for k, info in pairs(quadInfo) do
quads[k] = love.graphics.newQuad(
info[1], info[2], size, size, self.tileset:getWidth(),
self.tileset:getHeight())
end
self.quads = quads
end
local IntGrid = Layer:extend()
function IntGrid:new(tiles, name, size)
IntGrid.super.new(self, tiles, name)
self.type = "int"
self.size = size
end
local AutoLayer = Layer:extend()
function AutoLayer:new(tiles, name, tileset, size, spacing, padding)
AutoLayer.super.new(self, tiles, name)
self.type = "auto"
self.tileset = love.graphics.newImage(tileset)
self.size = size
local quadInfo = {}
for i = 1, #tiles do
local tile = tiles[i]
if not quadInfo[tile.t] then
quadInfo[tile.t] = tile.src
end
end
local quads = {}
for k, info in pairs(quadInfo) do
quads[k] = love.graphics.newQuad(
info[1], info[2], size, size, self.tileset:getWidth(),
self.tileset:getHeight())
end
self.quads = quads
end
local function getIntGrid(layer, _, options)
local width = layer.__cWid
local grid = layer.intGridCsv
local collisions = options and options.collisions or {}
local tiles = {}
local size = layer.__gridSize
for i = 0, #grid - 1 do
if grid[i + 1] > 0 then
local v = grid[i + 1]
if collisions[v] then
local y = math.floor(i / width)
local x = i - y * width
tiles[#tiles + 1] = {
x = x * size,
y = y * size,
v = v,
h = size,
w = size,
}
end
end
end
return IntGrid(tiles, layer.__identifier, size)
end
local function getAutoLayer(layer, root, options, tilesets)
local tilesetPath = root .. layer.__tilesetRelPath
local tileset = tilesets[layer.__tilesetDefUid]
if options and options.aseprite then
tilesetPath = tilesetPath:gsub("aseprite", "png")
end
return AutoLayer(
layer.autoLayerTiles, layer.__identifier, tilesetPath,
layer.__gridSize, tileset.spacing, tileset.padding)
end
local function getTileLayer(layer, root, options, tilesets)
local tilesetPath = root .. layer.__tilesetRelPath
local tileset = tilesets[layer.__tilesetDefUid]
if options and options.aseprite then
tilesetPath = tilesetPath:gsub("aseprite", "png")
end
return TileLayer(
layer.gridTiles, layer.__identifier, tilesetPath, layer.__gridSize,
tileset.spacing, tileset.padding)
end
local function getEntities(layer)
local instances = layer.entityInstances
local entities = {}
for i = 1, #instances do
local entity = instances[i]
if not entities[entity.__identifier] then
entities[entity.__identifier] = {}
end
local entity_obj = {
x = entity.px[1],
y = entity.px[2],
w = entity.width,
h = entity.height,
}
local _fields = entity.fieldInstances
for j = 1, #_fields do
local field = _fields[j]
entity_obj[field.__identifier] = field.__value
end
entities[entity.__identifier][#entities[entity.__identifier] + 1] =
entity_obj
end
entities.name = layer.__identifier
entities.grid_size = layer.__gridSize
return entities
end
local layerTypes = {
AutoLayer = getAutoLayer,
IntGrid = getIntGrid,
Entities = getEntities,
Tiles = getTileLayer,
}
local function getLayer(_layer, root, options, tilesets)
local layer = {}
local getLayerByType = layerTypes[_layer.__type]
if getLayerByType then
layer = getLayerByType(_layer, root, options, tilesets)
else
layer.name = _layer.__identifier
end
return layer
end
local function getLayers(_layers, root, options, tilesets)
local layers = {}
for i = 1, #_layers do
local _layer = _layers[i]
local layer = getLayer(_layer, root, options, tilesets)
layers[layer.name] = layer
end
return layers
end
local function getNeighbours(level, levelsByUid)
local _neighbours = level.__neighbours
local neighbours = {}
for i = 1, #_neighbours do
local neighbour = _neighbours[i]
neighbours[neighbour.dir] = levelsByUid[neighbour.levelUid]
end
return neighbours
end
local function getLevel(_level, root, options, tilesets, levelsByUid)
local level = getLayers(_level.layerInstances, root, options, tilesets)
for _, field in ipairs(_level.fieldInstances or {}) do
level[field.__identifier] = field.__value
end
level.name = _level.identifier
level.width = _level.pxWid
level.height = _level.pxHei
level.next = getNeighbours(_level, levelsByUid)
return level
end
local function getLevels(_levels, root, options, tilesets, levelsByUid)
local levels = {}
for i = 1, #_levels do
local _level = _levels[i]
local level = getLevel(_level, root, options, tilesets, levelsByUid)
levels[level.name] = level
end
return levels
end
function Tilemapper:new(path, options)
local root = path:gsub("[^/]+.ldtk", "")
local data = love.filesystem.read(path)
local raw = json.decode(data)
local _levels = raw.levels
local _tilesets = raw.defs.tilesets
local tilesets = {}
for i = 1, #_tilesets do
local tileset = _tilesets[i]
tilesets[tileset.uid] = {
padding = tileset.padding,
spacing = tileset.spacing,
}
end
local levelsByUid = {}
for i = 1, #_levels do
local level = _levels[i]
levelsByUid[level.uid] = level.identifier
end
local levels = getLevels(_levels, root, options, tilesets, levelsByUid)
self.levels = levels
end
function IntGrid:addCollisions(world)
local tiles = self.tiles
for i = 1, #tiles do
local tile = tiles[i]
world:add(tile, tile.x, tile.y, tile.w, tile.h)
end
end
function Tilemapper:addCollisions()
local layers = self.active
for _, layer in pairs(layers) do
local meta = getmetatable(layer)
if meta and meta.addCollisions then
layer:addCollisions(self.world)
end
end
end
function IntGrid:removeCollisions(world)
local tiles = self.tiles
for i = 1, #tiles do
local tile = tiles[i]
world:remove(tile)
end
end
function Tilemapper:removeCollisions()
local layers = self.active
for _, layer in pairs(layers) do
local meta = getmetatable(layer)
if meta and meta.addCollisions then
layer:removeCollisions(self.world)
end
end
end
function AutoLayer:draw()
local tiles = self.tiles
for i = 1, #tiles do
local tile = tiles[i]
love.graphics.draw(self.tileset, self.quads[tile.t], tile.px[1], tile.px[2])
end
end
function TileLayer:draw()
local tiles = self.tiles
for i = 1, #tiles do
local tile = tiles[i]
love.graphics.draw(self.tileset, self.quads[tile.t], tile.px[1], tile.px[2])
end
end
function Tilemapper:loadLevel(name, world)
if not self.world and world then
self.world = world
end
if not self.levels[name] then
return false
end
self.current = name
if self.active then
self:removeCollisions()
end
self.active = self.levels[self.current]
self:addCollisions()
end
function Tilemapper:nextLevel(dir)
local nextLevel = self.active.next[dir]
if not nextLevel then
return false
end
self:loadLevel(self.active.next[dir])
end
local function get_sorted_keys(t)
local keys = {}
for k in pairs(t) do
table.insert(keys, k)
end
table.sort(keys)
return keys
end
function Tilemapper:draw()
local layers = self.active
for _, k in ipairs(get_sorted_keys(layers)) do
local layer = layers[k]
local meta = getmetatable(layer)
if meta and meta.draw then
layer:draw()
end
end
end
return Tilemapper
|
local STRINGS = GLOBAL.STRINGS
local strings = {
CHARACTER_ABOUTME =
{
miotan = "Mio cames from another world, where nightmare is everywhere.",
},
CHARACTER_BIOS =
{
miotan =
{
{ title = "Birthday", desc = "July 17" },
{ title = "Favorite Food", desc = "None" }
}
},
CHARACTER_DESCRIPTIONS =
{
miotan = "*World treats her differently.\n*Friend of nightmare.",
},
CHARACTER_NAMES =
{
miotan = "Mio",
},
CHARACTER_QUOTES =
{
miotan = "\"If I could eat nightmare!\"",
},
CHARACTER_TITLES =
{
miotan = "The Nightmare Eater",
},
CHARACTERS =
{
MIOTAN =
{
DESCRIBE = {
NIGHTMAREFUEL = "How I LOVE it!"
}
}
},
NAMES =
{
MIOTAN = "Mio",
},
SKIN_DESCRIPTIONS =
{
miotan_classic = "Mio's V1 skin!",
miotan_none = "Mio cames from another world, where nightmare is everywhere.",
},
SKIN_NAMES =
{
lantern_mio = "Camping Lamp",
miotan_classic = "Classic",
miotan_none = "Mio",
yellowamulet_heart = "Glowing Heart"
}
}
|
TOOL.Category = "Lite Tools"
TOOL.Name = "#tool.lite_rotate.name"
TOOL.Information = {
{name = "left"},
{name = "reload"}
}
TOOL.ClientConVar["pitch"] = "0"
TOOL.ClientConVar["yaw"] = "0"
TOOL.ClientConVar["roll"] = "0"
TOOL.ClientConVar["undo"] = "1"
if CLIENT then
language.Add("tool.lite_rotate.name", "Rotate")
language.Add("tool.lite_rotate.desc", "Rotate a prop.")
language.Add("tool.lite_rotate.left", "Rotate the prop to the provided settings.")
language.Add("tool.lite_rotate.reload", "Reset the prop.")
language.Add("tool.lite_rotate.pitch", "Rotate Pitch")
language.Add("tool.lite_rotate.pitch.help", "The pitch to rotate to.")
language.Add("tool.lite_rotate.yaw", "Rotate Yaw")
language.Add("tool.lite_rotate.yaw.help", "The yaw to rotate to.")
language.Add("tool.lite_rotate.roll", "Rotate Roll")
language.Add("tool.lite_rotate.roll.help", "The roll to rotate to.")
language.Add("tool.lite_rotate.undo", "Register Undo")
language.Add("tool.lite_rotate.undo.help", "Add this action to your undo list.")
end
function TOOL:ValidateEntity(entity)
if not IsValid(entity) then return false end
if entity:IsPlayer() then return false end
return true
end
function TOOL:RotateEntity(trace, rotate)
local ent = trace.Entity
local oldAng = ent:GetAngles()
ent:SetAngles(Angle(rotate.p or 0, rotate.y or 0, rotate.r or 0))
ent:GetPhysicsObject():EnableMotion(false)
if self:GetClientNumber("undo") == 1 then
undo.Create("lite_rotate")
undo.SetPlayer(self:GetOwner())
undo.AddFunction( function(_, ent, oldAng)
if not IsValid(ent) then return end
ent:SetAngles(oldAng)
end, ent, oldAng)
undo.Finish()
end
end
function TOOL:LeftClick(trace)
if CLIENT then return true end
if not self:ValidateEntity(trace.Entity) then return end
self:RotateEntity(trace, {p = math.Clamp(self:GetClientNumber("pitch"), 0, 360), y = math.Clamp(self:GetClientNumber("yaw"), 0, 360), r = math.Clamp(self:GetClientNumber("roll"), 0, 360)})
return true
end
function TOOL:Reload(trace)
if CLIENT then return true end
if not self:ValidateEntity(trace.Entity) then return end
self:RotateEntity(trace, {p = 0, y = 0, r = 0})
end
function TOOL.BuildCPanel(panel)
panel:AddControl("Header", {Text = "#tool.lite_rotate.name", Description = "#tool.lite_rotate.desc"})
panel:AddControl("Slider", {Label = "#tool.lite_rotate.pitch", Command = "lite_rotate_pitch", Type = "Int", Min = 0, Max = 360})
panel:AddControl("Slider", {Label = "#tool.lite_rotate.yaw", Command = "lite_rotate_yaw", Type = "Int", Min = 0, Max = 360})
panel:AddControl("Slider", {Label = "#tool.lite_rotate.roll", Command = "lite_rotate_roll", Type = "Int", Min = 0, Max = 360})
panel:AddControl("Checkbox", {Label = "#tool.lite_rotate.undo", Command = "lite_rotate_undo"})
end
|
function onEvent(name, value1, value2)
if name == 'Phantom Chica' then
if value1 == '1' then
objectPlayAnimation('cha', 'idc', true)
playSound('jumpscare', 1)
doTweenAlpha('chacha', 'cha', 0, 2, 'linear')
end
end
end
|
function RemoveItemFromTable(tbl, keyname, keyvalue)
for i,v in ipairs(tbl) do
if (v[keyname] == keyvalue) then
-- If the current table category name is the one we are looking for then
-- remove the category from the table.
table.remove(tbl, i);
break;
end
end
end
RemoveItemFromTable(VehicleSpawnerManager.vehicleCategories, "category", "tractor")
local newItem = {
category = "tractor",
classes =
{
{
class = "placeholder12", contents = "RandomF100TruckContents",
skins =
{
},
},
},
initialMinVehicles = 10,
abandonedTimer = 604800,
abandonedRespawnTimer = 900,
destroyedTimer = 30,
destroyedRespawnTimer = 900,
}
table.insert(VehicleSpawnerManager.vehicleCategories, newItem)
|
---This module provides some kafka functions
local kafka
---produces a kafka message
---@param broker string brokers address
---@param topic string name of the topic
---@param key any key of the new message. If not specified a random key is generated
---@param message any the message. If not specified a random message is generated
---@param headers? table optional headers
---@param partition? number the partition to write that message. If not specified a random partition is selected
---@param timeout? number after timeout is expired the function will abort
function kafka.produce(broker, topic, key, message, headers, partition, timeout) end
return kafka
|
--[[
$ | networking
EXPORTS
sock
]]
require'$'
sock = require'sock'
thread = sock.thread
resume = sock.resume
suspend = sock.suspend
transfer = sock.transfer
cofinish = sock.cofinish
cowrap = sock.cowrap
yield = sock.yield
currentthread = sock.currentthread
threadenv = sock.threadenv
getthreadenv = sock.getthreadenv
getownthreadenv= sock.getownthreadenv
onthreadfinish = sock.onthreadfinish
sleep_until = sock.sleep_until
sleep = sock.sleep
sleep_job = sock.sleep_job
runat = sock.runat
runafter = sock.runafter
runevery = sock.runevery
runagainevery = sock.runagainevery
|
local addon, private = ...
local strsplit = private.strsplit
local strtrim = private.strtrim
-- Rift v.2.6 changed the artifact IDs for fished up artifact sets
local OLD_SETS = {
["Driftwood"] = { ["I49FE125D94B450C6,EED062C24C308EF2,,,,,,"] = true, ["I0DC44F90D0BC4787,BB7605865B44A983,,,,,,"] = true, ["I6C66F1C03879432E,ED8F79A6CD9E8450,,,,,,"] = true, ["I2A2E7B6845DDA971,A8B4328DF9144E6E,,,,,,"] = true, ["I3E0903AA6B70386E,77C8795CD58745B3,,,,,,"] = true, ["I38ABA458F9BA47AE,3F85B8894294A90B,,,,,,"] = true, ["I1B06BFC58F8FB8B6,C3D4B3086A374CBE,,,,,,"] = true, ["I3E387EEC930111B3,CBC1EFE4B51FF338,,,,,,"] = true, },
["Moldy Tomes"] = { ["I393CBAF0A39E58F5,6F51E14A45A2D2D6,,,,,,"] = true, ["I6E3EA352E646635E,27BD8D4E2008A184,,,,,,"] = true, ["I6E3EA35362A9904A,BCAED33087DE1234,,,,,,"] = true, ["I6E3EA3547848714D,B51177EE74F95DD5,,,,,,"] = true, ["I6E3EA355DD80D985,CFE3A5995A49D5DD,,,,,,"] = true, ["I6E3EA356D1EAD2AC,EFC6E9A3CD7B3AD9,,,,,,"] = true, ["I6E3EA357C602BEC5,E30B365413A435A7,,,,,,"] = true, ["I6E3EA3587F5F4CE4,BA3D5EA4EB7F12C8,,,,,,"] = true, },
["Fish Scales"] = { ["I12296E3BA7DA2D15,CFD2B6FA4AEDAEC0,,,,,,"] = true, ["I675F8D847764DE8A,6AF1D4D7FA77AAD3,,,,,,"] = true, ["I605A8F62224C11EF,E0BC4342DDBD62D0,,,,,,"] = true, ["I077A8097DEF0988C,F01782871FB9312E,,,,,,"] = true, ["I458A4B0ECDD00122,FDBF1AA5B720ADC8,,,,,,"] = true, ["I087394629EE54463,DCB38982BDD4A8AF,,,,,,"] = true, ["I6CFDEF6184007847,57E53A403CBFFA30,,,,,,"] = true, ["I22316F62A65A8AD3,F3984CCB26F8D593,,,,,,"] = true, },
["One Man's Junk"] = { ["I23D4E4B751BD5C1B,21BB158D6ACAF9B2,,,,,,"] = true, ["I760598F29DC6B1C3,17D0212B0A7EBDE0,,,,,,"] = true, ["I48BF84D56F48D79C,090532C2E5D7DE4C,,,,,,"] = true, ["I47A9BC127B9A4B85,21A7EA9121718047,,,,,,"] = true, ["I10E49ABB65162142,2EE3F771F9FF46BF,,,,,,"] = true, ["I06576611870FFCC3,DA234184A204CD45,,,,,,"] = true, ["I6E3EA355DD80D985,CFE3A5995A49D5DD,,,,,,"] = true, ["I0D0AFDC2124EC31E,BFDE81A82496F914,,,,,,"] = true, },
["Dormant Runeshards"] = { ["I754EED43906533EC,5B17B0AFECBD6B41,,,,,,"] = true, ["I754EED44ABD873C7,50365AA8FCE37E80,,,,,,"] = true, ["I754EED45823C7824,246C527EDF33479E,,,,,,"] = true, ["I754EED467FC8C287,EB6B323D39A8D8A5,,,,,,"] = true, ["I754EED47AD85DAB6,1A51B9BC403D5A56,,,,,,"] = true, ["I754EED485FBC9E82,3523E767A58D4F0F,,,,,,"] = true, ["I754EED49870677F0,EC752B850CA66442,,,,,,"] = true, ["I754EED4A65391EA0,4A25521C28E4C74A,,,,,,"] = true, },
["Vestments of the Necromancer"] = { ["I42D0C4218B96ED02,FF705A7A631DEBA5,,,,,,"] = true, ["I3909350592A3EE62,45E86FCAB28255B0,,,,,,"] = true, ["I4602CFECE2FD6951,BC8BA95D6247C7CF,,,,,,"] = true, ["I754EED45823C7824,246C527EDF33479E,,,,,,"] = true, ["I065766125EA0E37D,157C16BF3C9B4E12,,,,,,"] = true, ["I1313D8C781F0AD82,2C9B16C58FDBC469,,,,,,"] = true, ["I0CE9550170A6DCCC,65985C05CA96996B,,,,,,"] = true, ["I6E3EA3587F5F4CE4,BA3D5EA4EB7F12C8,,,,,,"] = true, },
["Empty Treasure Chests"] = { ["I0657660D1B6C10C4,1AE9BBC5CE85617F,,,,,,"] = true, ["I0657660E92A686EA,CD72BA6B0F28316E,,,,,,"] = true, ["I0657660FAD6D9B63,AE11CFCF07DF3DFC,,,,,,"] = true, ["I065766107B27658E,C820EA6F16A782CD,,,,,,"] = true, ["I06576611870FFCC3,DA234184A204CD45,,,,,,"] = true, ["I065766125EA0E37D,157C16BF3C9B4E12,,,,,,"] = true, ["I06576613B483F3AC,17C7A205D6FF53D1,,,,,,"] = true, ["I547A414F8C8D93C6,4FAC67AD7B068910,,,,,,"] = true, },
["Rings That Were Once Lost"] = { ["I0EF2614C954537EA,D7E6DDF64F197518,,,,,,"] = true, ["I4602CFEA4EB0C95C,1C29F5A6059D0B08,,,,,,"] = true, ["I4602CFEB85B3FA0E,2F521B0DFD60C29D,,,,,,"] = true, ["I4602CFECE2FD6951,BC8BA95D6247C7CF,,,,,,"] = true, ["I4602CFED9A563D43,0C084FA6E902C5C8,,,,,,"] = true, ["I4602CFEE38BD7A43,D18D1412659EBCBB,,,,,,"] = true, ["I4602CFEF7A0565E0,E67E59F3CD742D6B,,,,,,"] = true, ["I4602CFF08E346886,DB9C809E5D9A40A9,,,,,,"] = true, },
["Already-used Treasure Map"] = { ["I23A32AF95177C788,12C9654F3430F351,,,,,,"] = true, ["I52EABA80ACB9C91B,414DCB46C65C20BE,,,,,,"] = true, ["I52EABA8191DD4446,720DA97116ED3791,,,,,,"] = true, ["I52EABA82C3AFC1A7,0D28A80463A85749,,,,,,"] = true, ["I52EABA839EBB21C1,1F2AFF196F051E72,,,,,,"] = true, ["I52EABA847089918C,17381490DBA3DB36,,,,,,"] = true, ["I52EABA85C4C650F0,293A6BA5E700A25F,,,,,,"] = true, ["I52EABA865A048404,47511763A9475967,,,,,,"] = true, },
["Aqua Flora"] = { ["I7D7145A5AB28DE15,47DBBC8766E299E4,,,,,,"] = true, ["I7D7145A669C81E08,1BFEAA707D72902E,,,,,,"] = true, ["I7D7145A7A89F25EB,5CDD273CEA3A121F,,,,,,"] = true, ["I7D7145A873923253,0BC3AEBC70CD8D33,,,,,,"] = true, ["I7D7145A93C39E1B0,07154246BA6205A9,,,,,,"] = true, ["I7D7145AAD341DE3D,15D297FAE8C91120,,,,,,"] = true, ["I7D7145AB91F8EC04,4692F973395A27F3,,,,,,"] = true, ["I7D7145ACA60008EE,2907EDB1BB355819,,,,,,"] = true, },
["Discarded Bottles, Vials, and Flasks"] = { ["I4FF776D16156033B,11474D67CC9AF6E1,,,,,,"] = true, ["I70BE9A6E5437CE23,3FC9610D01E6C81A,,,,,,"] = true, ["I78769CF1A15B9851,35DADF6EE47882A7,,,,,,"] = true, ["I42D0C4218B96ED02,FF705A7A631DEBA5,,,,,,"] = true, ["I23D4E4B751BD5C1B,21BB158D6ACAF9B2,,,,,,"] = true, ["I760598F29DC6B1C3,17D0212B0A7EBDE0,,,,,,"] = true, ["I67EECBA739027F84,3CCB7A7349C11C8F,,,,,,"] = true, ["I585AE40C1256F306,7A8CB841EBF1874A,,,,,,"] = true, },
["Mysterious Crystals"] = { ["I29FCD16D56338603,0F0F4512C343A598,,,,,,"] = true, ["I6908D9F890320D26,FD95DD445842E4E6,,,,,,"] = true, ["I6908D9F991188A48,06C85DC309AC7E7F,,,,,,"] = true, ["I6908D9FA57A4F7C4,B26A6730B34A3DE1,,,,,,"] = true, ["I6908D9FB4ED67F4F,F5D08344D14CBFA5,,,,,,"] = true, ["I6908D9FC6FEDDC2F,D66F155ACA03CC33,,,,,,"] = true, ["I6908D9FD376888EE,CB8D3C055A295C23,,,,,,"] = true, ["I6908D9FE6255DC3E,0EF35819782BDDE7,,,,,,"] = true, },
["Exotic Aqua Flora"] = { ["I11CBCBFE667A0A0D,E77B03C005DCF82C,,,,,,"] = true, ["I60D7DFC371E24D14,FFE6B5E31F9EA6CA,,,,,,"] = true, ["I60D7DFC4A717CCB6,EDFF68B854ECA77A,,,,,,"] = true, ["I60D7DFC51BDA8C3F,0002431BE0496EA4,,,,,,"] = true, ["I60D7DFC663B925C3,0D5E52915BD24418,,,,,,"] = true, ["I60D7DFC75BE43ADE,3C31D02396A4E5BB,,,,,,"] = true, ["I60D7DFC83580991A,E7D3D990C043286C,,,,,,"] = true, ["I60D7DFC9324FD35F,F9D630A54B9FEF96,,,,,,"] = true, },
["Discarded Armor Pieces"] = { ["I390935000ADB542B,248E42CF4E9AE6BA,,,,,,"] = true, ["I3909350152568437,11F2E9FC2652BF66,,,,,,"] = true, ["I3909350272926FBF,20B0C2FE54B9CADD,,,,,,"] = true, ["I3909350369C47A98,32B296C5E0160EB7,,,,,,"] = true, ["I390935044E2BB320,E372F83F30A7258A,,,,,,"] = true, ["I3909350592A3EE62,45E86FCAB28255B0,,,,,,"] = true, ["I390935062DD799CE,E8BA1F53822C6433,,,,,,"] = true, ["I390935071620EF13,0B991089EAE8DD32,,,,,,"] = true, },
["Discarded Weapons"] = { ["I3B9CE8F564E8EDB3,8F45AFD5AF3D8F14,,,,,,"] = true, ["I48BF84D56F48D79C,090532C2E5D7DE4C,,,,,,"] = true, ["I08AD2D0BB67F319E,37427E71C004309B,,,,,,"] = true, ["I47A9BC127B9A4B85,21A7EA9121718047,,,,,,"] = true, ["I75690B0077A1CE81,0BFC1A1F73032965,,,,,,"] = true, ["I2EDDEAACB1DD9670,0745BE79BAA17524,,,,,,"] = true, ["I0CE9550170A6DCCC,65985C05CA96996B,,,,,,"] = true, ["I0D0AFDC2124EC31E,BFDE81A82496F914,,,,,,"] = true, },
["Natural Aquatic Treasures"] = { ["I7D7145A873923253,0BC3AEBC70CD8D33,,,,,,"] = true, ["I7D7145AAD341DE3D,15D297FAE8C91120,,,,,,"] = true, ["I0DC44F90D0BC4787,BB7605865B44A983,,,,,,"] = true, ["I3E0903AA6B70386E,77C8795CD58745B3,,,,,,"] = true, ["I5E799C855949B9BF,0A5685242A560A2D,,,,,,"] = true, ["I11CBCBFE667A0A0D,E77B03C005DCF82C,,,,,,"] = true, ["I6D5E3DF65BB672DC,9F0EA9DDBF8C0C83,,,,,,"] = true, ["I60D7DFC83580991A,E7D3D990C043286C,,,,,,"] = true, ["I3E387EEC930111B3,CBC1EFE4B51FF338,,,,,,"] = true, },
["Shiny Pebbles"] = { ["I026C820C4B4D6528,1A99964A1AF50FD3,,,,,,"] = true, ["I18B59441D9859072,260686EE75ED7851,,,,,,"] = true, ["I2078B461369FDC13,1998DDF926400648,,,,,,"] = true, ["I3DC7D88146BDFBD5,009E4BD022F058D3,,,,,,"] = true, ["I5E799C855949B9BF,0A5685242A560A2D,,,,,,"] = true, ["I6A8DB4DF590F8611,D4C93986701140C9,,,,,,"] = true, ["I6D5E3DF65BB672DC,9F0EA9DDBF8C0C83,,,,,,"] = true, ["I6F9A86D28ABB3CC1,586E63C355285A5C,,,,,,"] = true, },
["Keys to Nothing"] = { ["I66AF4C267C42F07A,3F45DAD9B3F30F52,,,,,,"] = true, ["I4137967492142B72,090AF056B03E25DC,,,,,,"] = true, ["I551D9B165448B781,213DA512F3EF37C2,,,,,,"] = true, ["I5ED17D0752D1F50A,205387060FAE5410,,,,,,"] = true, ["I10E49ABB65162142,2EE3F771F9FF46BF,,,,,,"] = true, ["I636CCB5CC14AB78A,2B033AE9854DD856,,,,,,"] = true, ["I1313D8C781F0AD82,2C9B16C58FDBC469,,,,,,"] = true, ["I2BDCF333216DAE69,882ECEB863AA0824,,,,,,"] = true, },
}
local NEW_SETS = {
["Driftwood"] = { ["I49FE125D5238A315,EED062C24C308EF2,,,,,,"] = true, ["I0DC44F906F672114,BB7605865B44A983,,,,,,"] = true, ["I6C66F1C0179D41DF,ED8F79A6CD9E8450,,,,,,"] = true, ["I2A2E7B682B404B2B,A8B4328DF9144E6E,,,,,,"] = true, ["I3E0903AA1C34C321,77C8795CD58745B3,,,,,,"] = true, ["I38ABA4587C01870C,3F85B8894294A90B,,,,,,"] = true, ["I1B06BFC55D4F4C14,C3D4B3086A374CBE,,,,,,"] = true, ["I3E387EEC6C68D8C6,CBC1EFE4B51FF338,,,,,,"] = true, },
["Moldy Tomes"] = { ["I393CBAF046174F14,6F51E14A45A2D2D6,,,,,,"] = true, ["I6E3EA3526ECA65E8,27BD8D4E2008A184,,,,,,"] = true, ["I6E3EA3534D3EC0CF,BCAED33087DE1234,,,,,,"] = true, ["I6E3EA3543BB696AE,B51177EE74F95DD5,,,,,,"] = true, ["I6E3EA3557C602B49,CFE3A5995A49D5DD,,,,,,"] = true, ["I6E3EA35656709E00,EFC6E9A3CD7B3AD9,,,,,,"] = true, ["I6E3EA35769B58C9C,E30B365413A435A7,,,,,,"] = true, ["I6E3EA35830C1D23E,BA3D5EA4EB7F12C8,,,,,,"] = true, },
["Fish Scales"] = { ["I12296E3B581C813A,CFD2B6FA4AEDAEC0,,,,,,"] = true, ["I675F8D8469BEF529,6AF1D4D7FA77AAD3,,,,,,"] = true, ["I605A8F620DE0E812,E0BC4342DDBD62D0,,,,,,"] = true, ["I077A809763D4037D,F01782871FB9312E,,,,,,"] = true, ["I458A4B0E6798DA7C,FDBF1AA5B720ADC8,,,,,,"] = true, ["I087394624C8186C0,DCB38982BDD4A8AF,,,,,,"] = true, ["I6CFDEF61246B566F,57E53A403CBFFA30,,,,,,"] = true, ["I22316F6242709BE5,F3984CCB26F8D593,,,,,,"] = true, },
["One Man's Junk"] = { ["I23D4E4B70A4E6652,21BB158D6ACAF9B2,,,,,,"] = true, ["I760598F25CED4E12,17D0212B0A7EBDE0,,,,,,"] = true, ["I48BF84D52B8534C9,090532C2E5D7DE4C,,,,,,"] = true, ["I47A9BC12012B0531,21A7EA9121718047,,,,,,"] = true, ["I10E49ABB2D31733B,2EE3F771F9FF46BF,,,,,,"] = true, ["I065766117217D8C5,DA234184A204CD45,,,,,,"] = true, ["I6E3EA3557C602B49,CFE3A5995A49D5DD,,,,,,"] = true, ["I0D0AFDC207BEADE8,BFDE81A82496F914,,,,,,"] = true, },
["Dormant Runeshards"] = { ["I754EED432A3596BA,5B17B0AFECBD6B41,,,,,,"] = true, ["I754EED4443FDB41D,50365AA8FCE37E80,,,,,,"] = true, ["I754EED456FB674A5,246C527EDF33479E,,,,,,"] = true, ["I754EED4669ACDD8D,EB6B323D39A8D8A5,,,,,,"] = true, ["I754EED477DCFD41F,1A51B9BC403D5A56,,,,,,"] = true, ["I754EED482988A86F,3523E767A58D4F0F,,,,,,"] = true, ["I754EED491755702E,EC752B850CA66442,,,,,,"] = true, ["I754EED4A174F6DBB,4A25521C28E4C74A,,,,,,"] = true, },
["Vestments of the Necromancer"] = { ["I42D0C42115DAB168,FF705A7A631DEBA5,,,,,,"] = true, ["I390935052C66724F,45E86FCAB28255B0,,,,,,"] = true, ["I4602CFEC7E569D14,BC8BA95D6247C7CF,,,,,,"] = true, ["I754EED456FB674A5,246C527EDF33479E,,,,,,"] = true, ["I0657661250DF8F69,157C16BF3C9B4E12,,,,,,"] = true, ["I1313D8C70F0A7E98,2C9B16C58FDBC469,,,,,,"] = true, ["I0CE95501094AC44E,65985C05CA96996B,,,,,,"] = true, ["I6E3EA35830C1D23E,BA3D5EA4EB7F12C8,,,,,,"] = true, },
["Empty Treasure Chests"] = { ["I0657660D0A71A0AE,1AE9BBC5CE85617F,,,,,,"] = true, ["I0657660E1807660F,CD72BA6B0F28316E,,,,,,"] = true, ["I0657660F575DD173,AE11CFCF07DF3DFC,,,,,,"] = true, ["I06576610055C4414,C820EA6F16A782CD,,,,,,"] = true, ["I065766117217D8C5,DA234184A204CD45,,,,,,"] = true, ["I0657661250DF8F69,157C16BF3C9B4E12,,,,,,"] = true, ["I065766134C6889B5,17C7A205D6FF53D1,,,,,,"] = true, ["I547A414F3B61FA24,4FAC67AD7B068910,,,,,,"] = true, },
["Rings That Were Once Lost"] = { ["I0EF2614C57CA7488,D7E6DDF64F197518,,,,,,"] = true, ["I4602CFEA0E3DAA76,1C29F5A6059D0B08,,,,,,"] = true, ["I4602CFEB3B689DAC,2F521B0DFD60C29D,,,,,,"] = true, ["I4602CFEC7E569D14,BC8BA95D6247C7CF,,,,,,"] = true, ["I4602CFED39865A09,0C084FA6E902C5C8,,,,,,"] = true, ["I4602CFEE0935CF61,D18D1412659EBCBB,,,,,,"] = true, ["I4602CFEF59BE5848,E67E59F3CD742D6B,,,,,,"] = true, ["I4602CFF04353D879,DB9C809E5D9A40A9,,,,,,"] = true, },
["Already-used Treasure Map"] = { ["I23A32AF921229A84,12C9654F3430F351,,,,,,"] = true, ["I52EABA8044197852,414DCB46C65C20BE,,,,,,"] = true, ["I52EABA811F83D349,720DA97116ED3791,,,,,,"] = true, ["I52EABA8243BA07D7,0D28A80463A85749,,,,,,"] = true, ["I52EABA83397898B7,1F2AFF196F051E72,,,,,,"] = true, ["I52EABA840DC4E5B5,17381490DBA3DB36,,,,,,"] = true, ["I52EABA857D611708,293A6BA5E700A25F,,,,,,"] = true, ["I52EABA8642CCCA5E,47511763A9475967,,,,,,"] = true, },
["Aqua Flora"] = { ["I7D7145A5545DE34C,47DBBC8766E299E4,,,,,,"] = true, ["I7D7145A65742B519,1BFEAA707D72902E,,,,,,"] = true, ["I7D7145A72BC9D83D,5CDD273CEA3A121F,,,,,,"] = true, ["I7D7145A84F0807B6,0BC3AEBC70CD8D33,,,,,,"] = true, ["I7D7145A913D84AC2,07154246BA6205A9,,,,,,"] = true, ["I7D7145AA6F4005F5,15D297FAE8C91120,,,,,,"] = true, ["I7D7145AB1EB6F9C0,4692F973395A27F3,,,,,,"] = true, ["I7D7145AC38B41650,2907EDB1BB355819,,,,,,"] = true, },
["Discarded Bottles, Vials, and Flasks"] = { ["I4FF776D13337C510,11474D67CC9AF6E1,,,,,,"] = true, ["I70BE9A6E0DC226D1,3FC9610D01E6C81A,,,,,,"] = true, ["I78769CF12481C848,35DADF6EE47882A7,,,,,,"] = true, ["I42D0C42115DAB168,FF705A7A631DEBA5,,,,,,"] = true, ["I23D4E4B70A4E6652,21BB158D6ACAF9B2,,,,,,"] = true, ["I760598F25CED4E12,17D0212B0A7EBDE0,,,,,,"] = true, ["I67EECBA724FBA008,3CCB7A7349C11C8F,,,,,,"] = true, ["I585AE40C0194CCC6,7A8CB841EBF1874A,,,,,,"] = true, },
["Mysterious Crystals"] = { ["I29FCD16D0F174BC7,0F0F4512C343A598,,,,,,"] = true, ["I6908D9F8562BCB23,FD95DD445842E4E6,,,,,,"] = true, ["I6908D9F92078F532,06C85DC309AC7E7F,,,,,,"] = true, ["I6908D9FA07B6FFC9,B26A6730B34A3DE1,,,,,,"] = true, ["I6908D9FB27CDA650,F5D08344D14CBFA5,,,,,,"] = true, ["I6908D9FC5E8130DF,D66F155ACA03CC33,,,,,,"] = true, ["I6908D9FD1E3E7F16,CB8D3C055A295C23,,,,,,"] = true, ["I6908D9FE0365836F,0EF35819782BDDE7,,,,,,"] = true, },
["Exotic Aqua Flora"] = { ["I11CBCBFE04D08A67,E77B03C005DCF82C,,,,,,"] = true, ["I60D7DFC33A33E71B,FFE6B5E31F9EA6CA,,,,,,"] = true, ["I60D7DFC42FAF94C5,EDFF68B854ECA77A,,,,,,"] = true, ["I60D7DFC505370227,0002431BE0496EA4,,,,,,"] = true, ["I60D7DFC6315AA03E,0D5E52915BD24418,,,,,,"] = true, ["I60D7DFC739D3C7B3,3C31D02396A4E5BB,,,,,,"] = true, ["I60D7DFC811C9B9AC,E7D3D990C043286C,,,,,,"] = true, ["I60D7DFC90449EAE1,F9D630A54B9FEF96,,,,,,"] = true, },
["Discarded Armor Pieces"] = { ["I390935000381EC69,248E42CF4E9AE6BA,,,,,,"] = true, ["I39093501433F3A9F,11F2E9FC2652BF66,,,,,,"] = true, ["I390935022CB7BB52,20B0C2FE54B9CADD,,,,,,"] = true, ["I390935034CCEE527,32B296C5E0160EB7,,,,,,"] = true, ["I3909350419F61C09,E372F83F30A7258A,,,,,,"] = true, ["I390935052C66724F,45E86FCAB28255B0,,,,,,"] = true, ["I3909350627CC0CD8,E8BA1F53822C6433,,,,,,"] = true, ["I39093507069FED65,0B991089EAE8DD32,,,,,,"] = true, },
["Discarded Weapons"] = { ["I3B9CE8F51DC6144B,8F45AFD5AF3D8F14,,,,,,"] = true, ["I48BF84D52B8534C9,090532C2E5D7DE4C,,,,,,"] = true, ["I08AD2D0B4C7111B5,37427E71C004309B,,,,,,"] = true, ["I47A9BC12012B0531,21A7EA9121718047,,,,,,"] = true, ["I75690B0022B0F962,0BFC1A1F73032965,,,,,,"] = true, ["I2EDDEAAC722DE4E2,0745BE79BAA17524,,,,,,"] = true, ["I0CE95501094AC44E,65985C05CA96996B,,,,,,"] = true, ["I0D0AFDC207BEADE8,BFDE81A82496F914,,,,,,"] = true, },
["Natural Aquatic Treasures"] = { ["I7D7145A84F0807B6,0BC3AEBC70CD8D33,,,,,,"] = true, ["I7D7145AA6F4005F5,15D297FAE8C91120,,,,,,"] = true, ["I0DC44F906F672114,BB7605865B44A983,,,,,,"] = true, ["I3E0903AA1C34C321,77C8795CD58745B3,,,,,,"] = true, ["I5E799C851228F0E3,0A5685242A560A2D,,,,,,"] = true, ["I11CBCBFE04D08A67,E77B03C005DCF82C,,,,,,"] = true, ["I6D5E3DF6263F4F1C,9F0EA9DDBF8C0C83,,,,,,"] = true, ["I60D7DFC811C9B9AC,E7D3D990C043286C,,,,,,"] = true, ["I3E387EEC6C68D8C6,CBC1EFE4B51FF338,,,,,,"] = true, },
["Shiny Pebbles"] = { ["I026C820C15375FAA,1A99964A1AF50FD3,,,,,,"] = true, ["I18B5944170B74046,260686EE75ED7851,,,,,,"] = true, ["I2078B461168D56BA,1998DDF926400648,,,,,,"] = true, ["I3DC7D8810A00F0B4,009E4BD022F058D3,,,,,,"] = true, ["I5E799C851228F0E3,0A5685242A560A2D,,,,,,"] = true, ["I6A8DB4DF3F5467B1,D4C93986701140C9,,,,,,"] = true, ["I6D5E3DF6263F4F1C,9F0EA9DDBF8C0C83,,,,,,"] = true, ["I6F9A86D229499AF2,586E63C355285A5C,,,,,,"] = true, },
["Keys to Nothing"] = { ["I66AF4C260D5A239F,3F45DAD9B3F30F52,,,,,,"] = true, ["I413796747F747843,090AF056B03E25DC,,,,,,"] = true, ["I551D9B1637B3C283,213DA512F3EF37C2,,,,,,"] = true, ["I5ED17D073FE95A83,205387060FAE5410,,,,,,"] = true, ["I10E49ABB2D31733B,2EE3F771F9FF46BF,,,,,,"] = true, ["I636CCB5C5A52F9FA,2B033AE9854DD856,,,,,,"] = true, ["I1313D8C70F0A7E98,2C9B16C58FDBC469,,,,,,"] = true, ["I2BDCF3331666FC4D,882ECEB863AA0824,,,,,,"] = true, },
}
-- Migrate existing data to the new artifact IDs
function private.MigrateArtifacts(Indy)
for artifactSet, newArtifactSetTable in pairs(NEW_SETS) do
-- The second portion of the artifact ID is unchanged
if OLD_SETS[artifactSet] ~= nil then
for newArtifactId, _ in pairs(newArtifactSetTable) do
-- Get the unchanged portion of the new id
local newSplitId = strsplit(",", newArtifactId)
-- Get the old artifact IDs
for oldArtifactId, _ in pairs(OLD_SETS[artifactSet]) do
local oldSplitId = strsplit(",", oldArtifactId)
if Indy.artifactTable[oldArtifactId] ~= nil and oldSplitId[2] == newSplitId[2] then
Indy.artifactTable[newArtifactId] = Indy.artifactTable[oldArtifactId]
Indy.artifactTable[oldArtifactId] = nil
break
end
end
end
end
end
end
|
local Concord = require("lib.concord")
local Cpml = require("lib.cpml")
local Controllable = Concord.component(function(e)
e.velocity = Cpml.vec3(0, 0, 0)
e.turnVelocity = Cpml.vec3(0, 0, 0)
e.friction = 10
e.turnFriction = 50
end)
return Controllable
|
return {InstCall_regs_readAddress=805339136,InstCall_regs_len=1024,InstCall_regs_writeAddress=805347328}
|
-- NOT DISABLEABLE
data:extend({
{
type = "recipe-category",
name = "tsp-evaporation"
},
{
type = "recipe-category",
name = "tsp-recycle-solar-items"
},
{
type = "recipe",
name = "tsp-molten-salt",
enabled = false,
category = "crafting-with-fluid",
energy_required = 20,
ingredients = {{type="fluid", name="water", amount=25}},
result = "tsp-molten-salt"
},
{
type = "recipe",
name = "tsp-molten-salt2",
enabled = false,
emissions_multiplier = 0,
category = "tsp-evaporation",
energy_required = 20,
ingredients = {{type = "fluid", name = "water", amount = 25}},
hidden = true,
results = {{type = "item" , name = "tsp-molten-salt", amount = 1}}
},
{
type = "recipe",
name = "tsp-recycler",
enabled = false,
energy_required = 2,
ingredients =
{
{"iron-plate", 10},
{"iron-gear-wheel", 10},
{"electronic-circuit",5},
},
result = "tsp-recycler",
},
{
type = "recipe",
name = "tsp-basic-heat-pipe",
enabled = false,
energy_required = 2,
ingredients =
{
{"iron-plate", 3},
{"copper-plate", 3}
},
result = "tsp-basic-heat-pipe",
},
{
type = "recipe",
name = "tsp-recycle-basic-heat-pipe",
icon = "__base__/graphics/icons/heat-pipe.png",
icon_size = 64,
subgroup = "energy",
enabled = true,
hidden = true,
category = "tsp-recycle-solar-items",
energy_required = 1,
ingredients = {{"tsp-basic-heat-pipe",1}},
results = {
{"iron-plate", 3},
{"copper-plate", 3}
},
},
{
type = "recipe",
name = "tsp-molten-salt-heat-accumulator",
enabled = false,
energy_required = 5,
ingredients = {{"steel-plate", 5}, {"tsp-basic-heat-pipe", 4}, {"tsp-molten-salt",20}},
result = "tsp-molten-salt-heat-accumulator"
},
{
type = "recipe",
name = "tsp-recycle-Heat-Accumulator",
enabled = true,
icon = "__thermal-solar-power__/graphics/icons/heat-accumulator1.png",
icon_size = 32,
subgroup = "energy",
energy_required = 1,
hidden = true,
category = "tsp-recycle-solar-items",
ingredients = {{"tsp-molten-salt-heat-accumulator",1}},
results = {{"steel-plate", 5}, {"iron-plate", 12},{"copper-plate", 12}}
},
{
type = "recipe",
name = "tsp-molten-salt-heat-accumulator2",
enabled = false,
energy_required = 5,
ingredients = {{"tsp-molten-salt-heat-accumulator", 2},{"steel-plate",6},{"heat-pipe",2},{"tsp-molten-salt",40}},
result = "tsp-molten-salt-heat-accumulator2"
},
{
type = "recipe",
name = "tsp-recycle-Heat-Accumulator2",
enabled = true,
icon = "__thermal-solar-power__/graphics/icons/heat-accumulator2.png",
icon_size = 32,
subgroup = "energy",
energy_required = 1,
hidden = true,
category = "tsp-recycle-solar-items",
ingredients = {{"tsp-molten-salt-heat-accumulator2",1}},
results = {{"steel-plate", 36}, {"iron-plate", 24},{"copper-plate", 64},}
},
{
type = "recipe",
name = "tsp-molten-salt-heat-accumulator3",
enabled = false,
energy_required = 5,
ingredients = {{"tsp-molten-salt-heat-accumulator2", 2},{"steel-plate",10},{"heat-pipe",2},{"tsp-molten-salt",60}},
result = "tsp-molten-salt-heat-accumulator3"
},
{
type = "recipe",
name = "tsp-recycle-Heat-Accumulator3",
enabled = true,
icon = "__thermal-solar-power__/graphics/icons/heat-accumulator3.png",
icon_size = 32,
subgroup = "energy",
energy_required = 1,
hidden = true,
category = "tsp-recycle-solar-items",
ingredients = {{"tsp-molten-salt-heat-accumulator3",1}},
results = {{"steel-plate", 102}, {"iron-plate", 48},{"copper-plate", 168},}
},
{
type = "recipe",
name = "tsp-salt-evaporation-pond",
enabled = false,
energy_required = 5,
ingredients = {{"iron-plate", 10}, {"copper-plate", 10}, {"pipe",5}},
result = "tsp-salt-evaporation-pond"
},
{
type = "recipe",
name = "tsp-thermal-solar-panel",
enabled = false,
energy_required = 5,
ingredients = {{"iron-plate", 4}, {"copper-plate", 10}, {"tsp-basic-heat-pipe",4}},
result = "tsp-thermal-solar-panel"
},
{
type = "recipe",
name = "tsp-thermal-solar-panel2",
enabled = false,
energy_required = 7,
ingredients = {{"steel-plate", 2}, {"tsp-thermal-solar-panel", 1}, {"electronic-circuit",2},{"tsp-molten-salt",15}},
result = "tsp-thermal-solar-panel2"
},
{
type = "recipe",
name = "tsp-thermal-solar-panel3",
enabled = false,
energy_required = 7,
ingredients = {{"steel-plate", 4}, {"tsp-thermal-solar-panel2", 1},{"tsp-molten-salt",30}},
result = "tsp-thermal-solar-panel3"
},
{
type = "recipe",
name = "tsp-thermal-solar-panel4",
enabled = false,
energy_required = 7,
ingredients = {{"steel-plate", 6}, {"tsp-thermal-solar-panel3", 1},{"tsp-molten-salt",40}},
result = "tsp-thermal-solar-panel4"
},
{
type = "recipe",
name = "tsp-recycle-solar-panel",
icon = "__thermal-solar-power__/graphics/icons/solar-panel1.png",
icon_size = 32,
subgroup = "energy",
enabled = true,
hidden = true,
category = "tsp-recycle-solar-items",
energy_required = 1,
ingredients = {{"tsp-thermal-solar-panel", 1}},
results = {{"iron-plate", 16}, {"copper-plate", 22},},
},
{
type = "recipe",
name = "tsp-recycle-solar-panel2",
icon = "__thermal-solar-power__/graphics/icons/solar-panel2.png",
icon_size = 32,
subgroup = "energy",
enabled = true,
hidden = true,
category = "tsp-recycle-solar-items",
energy_required = 1,
ingredients = {{"tsp-thermal-solar-panel2", 1}},
results = {{"steel-plate", 2},{"electronic-circuit",2},{"iron-plate", 16}, {"copper-plate", 22},},
},
{
type = "recipe",
name = "tsp-recycle-solar-panel3",
enabled = true,
icon = "__thermal-solar-power__/graphics/icons/solar-panel3.png",
icon_size = 32,
subgroup = "energy",
energy_required = 1,
hidden = true,
category = "tsp-recycle-solar-items",
ingredients = {{"tsp-thermal-solar-panel3", 1}},
results = {{"steel-plate", 6},{"electronic-circuit",2},{"iron-plate", 16}, {"copper-plate", 22},},
},
{
type = "recipe",
name = "tsp-recycle-solar-panel4",
enabled = true,
icon = "__thermal-solar-power__/graphics/icons/solar-panel4.png",
icon_size = 32,
subgroup = "energy",
energy_required = 1,
hidden = true,
category = "tsp-recycle-solar-items",
ingredients = {{"tsp-thermal-solar-panel4", 1}},
results = {{"steel-plate", 12},{"electronic-circuit",2},{"iron-plate", 16}, {"copper-plate", 22},},
},
})
-- ALL HEAT EXCHANGER
if settings.startup["heat-exchanger-enabled"].value then
data:extend({
{
type = "recipe",
name = "tsp-basic-heat-exchanger",
enabled = false,
energy_required = 5,
ingredients =
{
{"iron-plate", 20},
{"copper-plate", 50},
{"pipe",10}
},
result = "tsp-basic-heat-exchanger",
},
{
type = "recipe",
name = "tsp-recycle-heat-exchanger",
enabled = true,
icon = "__thermal-solar-power__/graphics/icons/heat-boiler1.png",
icon_size = 32,
subgroup = "energy",
energy_required = 1,
hidden = true,
category = "tsp-recycle-solar-items",
ingredients = {{"tsp-basic-heat-exchanger", 1}},
results = {{"iron-plate", 20}, {"copper-plate", 50},{"pipe",10},},
},
{
type = "recipe",
name = "tsp-basic-heat-exchanger2",
enabled = false,
energy_required = 5,
ingredients =
{
{"tsp-basic-heat-exchanger", 1},
{"steel-plate",10}
},
result = "tsp-basic-heat-exchanger2",
},
{
type = "recipe",
name = "tsp-recycle-heat-exchanger2",
enabled = true,
icon = "__thermal-solar-power__/graphics/icons/heat-boiler2.png",
icon_size = 32,
subgroup = "energy",
energy_required = 1,
hidden = true,
category = "tsp-recycle-solar-items",
ingredients = {{"tsp-basic-heat-exchanger2", 1}},
results = {{"steel-plate",10},{"iron-plate", 20}, {"copper-plate", 50},{"pipe",10},},
},
})
if not mods["bobpower"] then
data:extend({
{
type = "recipe",
name = "tsp-basic-heat-exchanger3",
enabled = false,
energy_required = 5,
ingredients =
{
{"tsp-basic-heat-exchanger2", 1},
{"steel-plate",10}
},
result = "tsp-basic-heat-exchanger3",
},
{
type = "recipe",
name = "tsp-recycle-heat-exchanger3",
enabled = true,
icon = "__thermal-solar-power__/graphics/icons/heat-boiler3.png",
icon_size = 32,
subgroup = "energy",
energy_required = 1,
hidden = true,
category = "tsp-recycle-solar-items",
ingredients = {{"tsp-basic-heat-exchanger3", 1}},
results = {{"steel-plate",20},{"iron-plate", 20}, {"copper-plate", 50},{"pipe",10},},
},
{
type = "recipe",
name = "tsp-basic-heat-exchanger4",
enabled = false,
energy_required = 5,
ingredients =
{
{"tsp-basic-heat-exchanger3", 1},
{"plastic-bar",10}
},
result = "tsp-basic-heat-exchanger4",
},
{
type = "recipe",
name = "tsp-recycle-heat-exchanger4",
enabled = true,
icon = "__thermal-solar-power__/graphics/icons/heat-boiler4.png",
icon_size = 32,
subgroup = "energy",
energy_required = 1,
hidden = true,
category = "tsp-recycle-solar-items",
ingredients = {{"tsp-basic-heat-exchanger4", 1}},
results = {{"plastic-bar",10},{"steel-plate",20},{"iron-plate", 20}, {"copper-plate", 50},{"pipe",10},},
},
})
end
end
-- ALL STEAM TURBINES
if settings.startup["steam-turbines-enabled"].value and not mods["bobpower"] then
data:extend({
{
type = "recipe",
name = "tsp-steam-engine-2",
enabled = false,
energy_required = 5,
ingredients =
{
{"steam-engine", 1},
{"pipe",5},
{"steel-plate",10}
},
result = "tsp-steam-engine-2",
},
{
type = "recipe",
name = "tsp-recycle-steam-engine-2",
enabled = true,
icon = "__base__/graphics/icons/steam-engine.png",
icon_size = 64,
subgroup = "energy",
energy_required = 1,
hidden = true,
category = "tsp-recycle-solar-items",
ingredients = {{"tsp-steam-engine-2", 1}},
results = {{"steel-plate",10},{"pipe",5},{"iron-plate",10},{"iron-gear-wheel",8}},
},
{
type = "recipe",
name = "tsp-steam-engine-3",
enabled = false,
energy_required = 5,
ingredients =
{
{"tsp-steam-engine-2", 1},
{"electronic-circuit",1},
{"steel-plate",10}
},
result = "tsp-steam-engine-3",
},
{
type = "recipe",
name = "tsp-recycle-steam-engine-3",
enabled = true,
icon = "__base__/graphics/icons/steam-engine.png",
icon_size = 64,
subgroup = "energy",
energy_required = 1,
hidden = true,
category = "tsp-recycle-solar-items",
ingredients = {{"tsp-steam-engine-3", 1}},
results = {{"steel-plate",20},{"electronic-circuit",1},{"pipe",5},{"iron-plate",10},{"iron-gear-wheel",8}},
},
{
type = "recipe",
name = "tsp-steam-engine-4",
enabled = false,
energy_required = 5,
ingredients =
{
{"tsp-steam-engine-3", 1},
{"electronic-circuit",1},
{"steel-plate",10}
},
result = "tsp-steam-engine-4",
},
{
type = "recipe",
name = "tsp-recycle-steam-engine-4",
enabled = true,
icon = "__base__/graphics/icons/steam-engine.png",
icon_size = 64,
subgroup = "energy",
energy_required = 1,
hidden = true,
category = "tsp-recycle-solar-items",
ingredients = {{"tsp-steam-engine-4", 1}},
results = {{"steel-plate",30},{"electronic-circuit",2},{"pipe",5},{"iron-plate",10},{"iron-gear-wheel",8}},
},
})
end
|
print("Hello World")
---[[
-- Application object.
local app = {}
app.Url = ""
print("1")
-- Open TextBox to enter URL to Lua code to run.
app.OpenUrlTextBox = function(self)
mosync.SysOpenTextBox(
"Enter URL",
"http://divineprog.se/", mosync.MA_TB_TYPE_URL, 255,
function(url)
if nil == url then
print("URL: nil!")
else
print("URL: " .. url)
self.Url = url
self:LoadAndRun()
end
end)
end
print("2")
-- Load and run Lua code from current URL.
app.LoadAndRun = function(self)
-- Check that Url has some data.
if #self.Url < 4 then
return
end
-- Load the code and evaluate it.
self:LoadUrl(self.Url, function(code)
if nil == code then
print("Could not get Lua code")
else
self:EvalLuaCode(code)
end
end)
end
print("3")
app.LoadUrl = function(self, url, callbackFun)
local connection = mosync.Connection:HttpCreate()
connection:WhenDone(function(data, result)
if nil == data then
print("Could not download data from:")
print(url)
callbackFun(nil)
else
-- Zero terminate C string buffer and get a Lua string.
mosync.SysBufferSetByte(data, result, 0)
local text = mosync.SysBufferToString(data)
mosync.SysFree(data)
callbackFun(text)
end
connection:Close()
end)
connection:Get(url)
end
print("4")
app.EvalLuaCode = function(self, code)
local fun, parseError = loadstring(code)
if nil == fun then
print("Lua Parse Error:")
print(parseError)
mosync.maMessageBox("Lua Error", parseError)
return
end
-- Hide the native UI and show the MoSync drawing screen.
maWidgetScreenShow(MAW_CONSTANT_MOSYNC_SCREEN_HANDLE)
-- Evaluate the code using a protected call.
local result, runtimeError = pcall(fun)
if false == result then
print("Lua Runtime Error:")
print(runtimeError)
mosync.maMessageBox("Lua Error", runtimeError)
end
end
print("5")
----[[
mosync.EventMonitor:OnKeyDown(function(key)
if mosync.MAK_BACK == key or mosync.MAK_0 == key then
mosync.EventMonitor:ExitEventLoop()
elseif mosync.MAK_1 == key then
app:OpenUrlTextBox()
elseif mosync.MAK_2 == key then
app:LoadAndRun()
end
end)
print("6")
--]]
--[[
ProgramInfo = {
ProgramName = "LuaPlayground",
Version = 1,
Date = "2011-02-21",
Author = "Mikael Kindborg",
Licence = "MIT",
Comment = "Client that runs MobileLua programs."
}
-- Program: LuaPlayground.lua
-- Author: Mikael Kindborg
-- Description: Lua browser/editor
----------------------------------------------
-- Highjack the keydown function --
----------------------------------------------
-- The global application state.
GApplicationState = "RunningApplicationCode"
-- Create and call a closure that sets up a custom
-- keydown functon. We "highjack" the system onKeyDown
-- function with our own function. This prevents the
-- programmer from blocking/replacing the exit on back
-- behaviour.
System.onKeyDown = (function()
-- "Instance variable" that refers to the user set
-- keydown function.
local userKeyDownFun = nil
-- Set the keydown function that exits on back and
-- calls the user set keydown function.
System.onKeyDown(function(keyCode, nativeKeyCode)
-- Always exit on MAK-BACK so that the user always
-- can quit the program, even if "evil" code tries
-- to prevent it.
if MAK_BACK == keyCode then
if "RunningUserCode" == GApplicationState then
maWidgetScreenShow(TabScreen)
GApplicationState = "RunningApplicationCode"
else
maExit(0)
end
end
-- If there is a user set keydown function we call it.
if nil ~= userKeyDownFun then
userKeyDownFun(keyCode, nativeKeyCode)
end
end)
-- This is our custom onKeyDown function.
return function(keyDownFun)
userKeyDownFun = keyDownFun
end
end)()
----------------------------------------------
-- Helper functions --
----------------------------------------------
-- Helper function for parsing out the Lua code in a text.
-- The code is within "-- MOBILELUA BEGIN --" and
-- "-- MOBILELUA END --" tags.
function ParseTextWithEmbeddedLuaCode(text)
local startTag = "-- MOBILELUA BEGIN"
local stopTag = "-- MOBILELUA END"
local start = text:find(startTag, 0)
local stop = text:find(stopTag, start)
if nil == start or nil == stop then
return nil
else
local code = text:sub(start, stop + stopTag:len())
return code
end
end
function EvaluateCode(data)
print("Evaluate code: "..data)
-- Parse out the script.
local code = ParseTextWithEmbeddedLuaCode(data)
print("EvaluateCode 1")
if nil == code then
-- Assume it is a Lua program without tags.
code = data
print("EvaluateCode 2")
end
-- Parse the code.
print("EvaluateCode 3")
local fun, parseError = loadstring(code)
print("EvaluateCode 4")
if nil == fun then
print("Lua Parse Error "..parseError)
maMessageBox("Lua Error", parseError)
else
print("EvaluateCode 5")
-- Hide the native UI and show the MoSync drawing screen.
maWidgetScreenShow(MAW_CONSTANT_MOSYNC_SCREEN_HANDLE)
-- Evaluate the code using a protected call.
local result, runtimeError = pcall(fun)
if false == result then
print("Lua Runtime Error "..runtimeError)
maWidgetScreenShow(TabScreen)
maMessageBox("Lua Error", runtimeError)
else
GApplicationState = "RunningUserCode"
end
end
end
function LoadAndRunFromUrl(url)
-- Function called on download complete.
local loadAndRunScriptFun = function(data)
if nil == data then
maMessageBox("Could not download code", url)
else
EvaluateCode(data)
end
end
-- Start the download.
System.downloadText(url, loadAndRunScriptFun)
end
----------------------------------------------
-- User interface creation --
----------------------------------------------
-- Create the screen width url field and list of program urls.
function CreateLoadProgramScreen()
end
--]]
|
local base64 = require("mbedtls").base64
local spec = require("test.spec").new()
spec:describe("check class", function()
assert(base64 ~= nil)
assert(base64.class == "base64")
end)
spec:describe("enocde (small)", function()
assert(base64 ~= nil)
local input = [[lua base64 encode test]]
local expected = [[bHVhIGJhc2U2NCBlbmNvZGUgdGVzdA==]]
local output = base64.encode(input)
assert(#output == #expected)
assert(output == expected)
end)
spec:describe("decode (small)", function()
assert(base64 ~= nil)
local expected = [[lua base64 encode test]]
local input = [[bHVhIGJhc2U2NCBlbmNvZGUgdGVzdA==]]
local output = base64.decode(input)
assert(#output == #expected)
assert(output == expected)
end)
spec:describe("enocde (1000 chars)", function()
assert(base64 ~= nil)
local input = string.rep("a", 1000)
local expected = [[YWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYQ==]]
local output = base64.encode(input)
assert(#output == #expected)
assert(output == expected)
end)
spec:describe("decode (1000 chars)", function()
assert(base64 ~= nil)
local expected = string.rep("a", 1000)
local input = [[YWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYQ==]]
local output = base64.decode(input)
assert(#output == #expected)
assert(output == expected)
end)
spec:run()
collectgarbage()
|
local Types = require(script.Parent.Parent.Types)
type Array<T> = Types.Array<T>
local function loadChildren(parent: Instance)
local modules: Array<any> = {}
for _, child in parent:GetChildren() do
if child:IsA("ModuleScript") then
table.insert(modules, require(child :: ModuleScript))
end
end
return modules
end
return loadChildren
|
local S = mobs.intllib
-- custom particle effects
local effect = function(
pos, amount, texture, min_size, max_size, radius, gravity, glow)
radius = radius or 2
min_size = min_size or 0.5
max_size = max_size or 1
gravity = gravity or -10
glow = glow or 0
minetest.add_particlespawner({
amount = amount,
time = 0.25,
minpos = pos,
maxpos = pos,
minvel = {x = -radius, y = -radius, z = -radius},
maxvel = {x = radius, y = radius, z = radius},
minacc = {x = 0, y = gravity, z = 0},
maxacc = {x = -20, y = gravity, z = 15},
minexptime = 0.1,
maxexptime = 1,
minsize = min_size,
maxsize = max_size,
texture = texture,
glow = glow,
})
end
-- Sand Monster by PilzAdam
mobs:register_mob("mobs_monster:sand_monster", {
type = "monster",
passive = false,
attack_type = "dogfight",
pathfinding = true,
--specific_attack = {"player", "mobs_npc:npc"},
--ignore_invisibility = true,
reach = 2,
damage = 1,
hp_min = 4,
hp_max = 20,
armor = 100,
collisionbox = {-0.4, -1, -0.4, 0.4, 0.8, 0.4},
visual = "mesh",
mesh = "mobs_sand_monster.b3d",
textures = {
{"mobs_sand_monster.png"},
{"mobs_sand_monster2.png"},
},
blood_texture = "default_desert_sand.png",
makes_footstep_sound = true,
sounds = {
random = "mobs_sandmonster",
},
walk_velocity = 1.5,
run_velocity = 4,
view_range = 8, --15
jump = true,
floats = 0,
drops = {
{name = "default:desert_sand", chance = 1, min = 3, max = 5},
},
water_damage = 3,
lava_damage = 4,
light_damage = 0,
fear_height = 4,
animation = {
speed_normal = 15,
speed_run = 15,
stand_start = 0,
stand_end = 39,
walk_start = 41,
walk_end = 72,
run_start = 74,
run_end = 105,
punch_start = 74,
punch_end = 105,
},
immune_to = {
{"default:shovel_wood", 3}, -- shovels deal more damage to sand monster
{"default:shovel_stone", 3},
{"default:shovel_bronze", 4},
{"default:shovel_steel", 4},
{"default:shovel_mese", 5},
{"default:shovel_diamond", 7},
},
--[[
custom_attack = function(self, p)
local pos = self.object:get_pos()
minetest.add_item(pos, "default:sand")
end,
]]
on_die = function(self, pos)
pos.y = pos.y + 0.5
mobs:effect(pos, 30, "mobs_sand_particles.png", .1, 2, 3, 5)
pos.y = pos.y + 0.25
mobs:effect(pos, 30, "mobs_sand_particles.png", .1, 2, 3, 5)
end,
--[[
on_rightclick = function(self, clicker)
local tool = clicker:get_wielded_item()
local name = clicker:get_player_name()
if tool:get_name() == "default:sand" then
self.owner = name
self.type = "npc"
mobs:force_capture(self, clicker)
end
end,
]]
})
if not mobs.custom_spawn_monster then
mobs:spawn({
name = "mobs_monster:sand_monster",
nodes = {"default:desert_sand"},
chance = 7000,
active_object_count = 2,
min_height = 0,
})
end
mobs:register_egg("mobs_monster:sand_monster", S("Sand Monster"), "default_desert_sand.png", 1)
mobs:alias_mob("mobs:sand_monster", "mobs_monster:sand_monster") -- compatibility
|
ITEM.name = "Makarov"
ITEM.description = "A Russian steel-framed police pistol that fires 9x18 Makarov."
ITEM.model = "models/weapons/ethereal/w_makarov.mdl"
ITEM.class = "cw_kk_ins2_makarov"
ITEM.weaponCategory = "secondary"
ITEM.width = 2
ITEM.height = 1
ITEM.price = 400
ITEM.weight = 2
|
local uv = require 'couv'
local Buffer = uv.Buffer
local exports = {}
exports['uv.fs.open.sync.OK'] = function(test)
local fd = uv.fs.open('couv.lua', 'r', '0666')
test.is_number(fd)
uv.fs.close(fd)
-- try to close twice
local ok, err = pcall(uv.fs.close, fd)
test.ok(not ok)
test.equal(string.sub(err, -string.len('EBADF'), -1), 'EBADF')
test.done()
end
exports['uv.fs.open.sync.ENOENT'] = function(test)
local ok, err = pcall(function()
uv.fs.open('not_exist_file', 'r', '0666')
end)
test.ok(not ok)
test.equal(string.sub(err, -string.len('ENOENT'), -1), 'ENOENT')
test.done()
end
exports['uv.fs.open.async.OK'] = function(test)
coroutine.wrap(function()
local fd = uv.fs.open('couv.lua', 'r', '0666')
test.is_number(fd)
uv.fs.close(fd)
test.done()
end)()
uv.run()
end
exports['uv.fs.open.async.ENOENT'] = function(test)
coroutine.wrap(function()
local ok, err = pcall(function()
uv.fs.open('not_exist_file', 'r', '0666')
end)
test.ok(not ok)
test.equal(string.sub(err, -string.len('ENOENT'), -1), 'ENOENT')
test.done()
end)()
uv.run()
end
exports['uv.fs.stat.sync'] = function(test)
local stat = uv.fs.stat('Makefile')
test.ok(stat)
test.ok(stat:isFile())
test.done()
end
exports['uv.fs.stat.async'] = function(test)
coroutine.wrap(function()
local stat = uv.fs.stat('couv.lua')
test.ok(stat:isFile())
test.done()
end)()
uv.run()
end
exports['uv.fs.write_and_read.sync'] = function(test)
local path = '_test_uv.fs.write_and_read.sync'
local fd = uv.fs.open(path, 'w', '0666')
local str = 'Hello, libuv!\n'
local n = uv.fs.write(fd, str)
test.equal(n, #str)
uv.fs.close(fd)
fd = uv.fs.open(path, 'r')
local buf = Buffer.new(#str)
n = uv.fs.read(fd, buf)
test.equal(buf:toString(), str)
uv.fs.close(fd)
uv.fs.unlink(path)
test.done()
end
exports['uv.fs.write_and_read.async'] = function(test)
coroutine.wrap(function()
local path = '_test_uv.fs.write_and_read.async'
local fd = uv.fs.open(path, 'w', '0666')
local str = 'Hello, libuv!\n'
local n = uv.fs.write(fd, str)
test.equal(n, #str)
uv.fs.close(fd)
fd = uv.fs.open(path, 'r')
local buf = Buffer.new(#str)
n = uv.fs.read(fd, buf)
test.equal(buf:toString(), str)
uv.fs.close(fd)
uv.fs.unlink(path)
test.done()
end)()
uv.run()
end
exports['uv.fs.unlink.sync'] = function(test)
local path = '_test_uv.fs.unlink.sync'
local fd = uv.fs.open(path, 'w', '0666')
uv.fs.close(fd)
uv.fs.unlink(path)
test.ok(true)
test.done()
end
exports['uv.fs.unlink.async'] = function(test)
coroutine.wrap(function()
local path = '_test_uv.fs.unlink.async'
local fd = uv.fs.open(path, 'w', '0666')
uv.fs.close(fd)
uv.fs.unlink(path)
test.ok(true)
test.done()
end)()
uv.run()
end
exports['uv.fs.mkdir_rmdir.sync'] = function(test)
local path = '_test_fs_mkdir_rmdir.sync'
uv.fs.mkdir(path)
local stat = uv.fs.stat(path)
test.ok(stat:isDirectory())
uv.fs.rmdir(path)
test.done()
end
exports['uv.fs.mkdir_rmdir.async'] = function(test)
coroutine.wrap(function()
local path = '_test_fs_mkdir_rmdir.async'
uv.fs.mkdir(path)
local stat = uv.fs.stat(path)
test.ok(stat:isDirectory())
uv.fs.rmdir(path)
test.done()
end)()
uv.run()
end
exports['uv.fs.rename_dir.sync'] = function(test)
local oldPath = '_test_fs_rename_dir.sync.old'
local newPath = '_test_fs_rename_dir.sync.new'
test.ok(not uv.fs.exists(oldPath))
test.ok(not uv.fs.exists(newPath))
uv.fs.mkdir(oldPath)
test.ok(uv.fs.exists(oldPath))
test.ok(not uv.fs.exists(newPath))
uv.fs.rename(oldPath, newPath)
test.ok(not uv.fs.exists(oldPath))
test.ok(uv.fs.exists(newPath))
uv.fs.rmdir(newPath)
test.done()
end
exports['uv.fs.rename_dir.async'] = function(test)
coroutine.wrap(function()
local oldPath = '_test_fs_rename_dir.async.old'
local newPath = '_test_fs_rename_dir.async.new'
test.ok(not uv.fs.exists(oldPath))
test.ok(not uv.fs.exists(newPath))
uv.fs.mkdir(oldPath)
test.ok(uv.fs.exists(oldPath))
test.ok(not uv.fs.exists(newPath))
uv.fs.rename(oldPath, newPath)
test.ok(not uv.fs.exists(oldPath))
test.ok(uv.fs.exists(newPath))
uv.fs.rmdir(newPath)
test.done()
end)()
uv.run()
end
exports['uv.fs.ftruncate.sync'] = function(test)
local path = '_test_fs_ftruncate.sync'
local fd = uv.fs.open(path, 'w', '0666')
local str = 'Hello, libuv!\n'
local n = uv.fs.write(fd, str)
uv.fs.ftruncate(fd, 5)
local stat = uv.fs.stat(path)
test.equal(stat:size(), 5)
uv.fs.ftruncate(fd)
stat = uv.fs.stat(path)
test.equal(stat:size(), 0)
uv.fs.close(fd)
uv.fs.unlink(path)
test.done()
end
exports['uv.fs.ftruncate.async'] = function(test)
coroutine.wrap(function()
local path = '_test_fs_ftruncate.async'
local fd = uv.fs.open(path, 'w', '0666')
local str = 'Hello, libuv!\n'
local n = uv.fs.write(fd, str)
uv.fs.ftruncate(fd, 5)
local stat = uv.fs.stat(path)
test.equal(stat:size(), 5)
uv.fs.ftruncate(fd)
stat = uv.fs.stat(path)
test.equal(stat:size(), 0)
uv.fs.close(fd)
uv.fs.unlink(path)
test.done()
end)()
uv.run()
end
return exports
|
local M = {}
local vim = vim
local loop = vim.loop
local api = vim.api
M.items = {}
M.callback = false
-- onDirScanned handler for vim.loop
local function onDirScanned(_, data)
if data then
local function iter()
return vim.loop.fs_scandir_next(data)
end
for name, type in iter do
table.insert(M.items, {type = type, name=name})
end
end
M.callback = true
end
local fileTypesMap = setmetatable({
file = "(file)",
directory = "(dir)",
char = "(char)",
link = "(link)",
block = "(block)",
fifo = "(pipe)",
socket = "(socket)"
}, {__index = function()
return '(unknown)'
end
})
M.getCompletionItems = function(prefix, score_func)
local complete_items = {}
for _, val in ipairs(M.items) do
local score = score_func(prefix, val.name)
if score < #prefix/3 or #prefix == 0 then
table.insert(complete_items, {
word = val.name,
kind = 'Path',
menu = fileTypesMap[val.type],
score = score,
icase = 1,
dup = 1,
empty = 1,
})
end
end
return complete_items
end
M.getCallback = function()
return M.callback
end
M.triggerFunction = function()
local pos = api.nvim_win_get_cursor(0)
local line = api.nvim_get_current_line()
local line_to_cursor = line:sub(1, pos[2])
local keyword
if vim.v.completed_item ~= nil and vim.v.completed_item.kind == 'Path' and
line_to_cursor:find(vim.v.completed_item.word) then
keyword = M.keyword..vim.v.completed_item.word..'/'
else
M.keyword = nil
keyword = line_to_cursor:match("[^%s\"\']+%S*/?$")
end
if keyword ~= nil and keyword ~= '/' then
local index = string.find(keyword:reverse(), '/')
if index == nil then index = keyword:len() + 1 end
local length = string.len(keyword) - index + 1
keyword = string.sub(keyword, 1, length)
end
local path = vim.fn.expand('%:p:h')
if keyword ~= nil then
local expanded_keyword = vim.fn.glob(keyword)
local home = vim.fn.expand("$HOME")
if expanded_keyword:sub(1, 1) == '/' or string.find(expanded_keyword, home) ~= nil then
path = expanded_keyword
else
path = vim.fn.expand('%:p:h')
path = path..'/'..keyword
end
end
M.keyword = keyword
M.items = {}
loop.fs_scandir(path, onDirScanned)
end
return M
|
-- addBuilding
-- Author: datvm
-- DateCreated: 1/23/2019 5:22:35 PM
--------------------------------------------------------------
print("OP Building Loaded!")
function ESOAddB(iPlayer, iCityID)
local pPlayer = Players[iPlayer]
local pBuilding = GameInfo.Buildings["BUILDING_OP_BUILDING"].Index
if pPlayer:IsHuman() then
local pCity = pPlayer:GetCities():FindID(iCityID)
local pCityPlotIndex = Map.GetPlot(pCity:GetX(), pCity:GetY()):GetIndex()
local pCityBuildings = pCity:GetBuildings()
local pCityBuildQ = pCity:GetBuildQueue()
if not pCityBuildings:HasBuilding(pBuilding) then
pCityBuildQ:CreateIncompleteBuilding(pBuilding, pCityPlotIndex, 100)
end
end
end
Events.CityTileOwnershipChanged.Add(ESOAddB)
|
-- sampswap v0.1.0
--
--
-- llllllll.co/t/sampswap
--
--
--
-- ▼ instructions below ▼
--
-- E1 selects a track
-- E2 selects a parameter
-- E3 modifies parameter
-- K2 generates track
-- K3 toggles playing
include("sampswap/lib/utils")
UI=require("ui")
if not string.find(package.cpath,"/home/we/dust/code/sampswap/lib/") then
package.cpath=package.cpath..";/home/we/dust/code/sampswap/lib/?.so"
end
json=require("cjson")
local lattice_=require("lattice")
sample_=include("sampswap/lib/sample")
-- local crowseq=include("sampswap/lib/crowseq")
engine.name="Sampswap"
SENDOSC="/home/we/dust/data/sampswap/sendosc"
WORKDIR="/tmp/sampswap/"
NRTREADY="/tmp/nrt-scready"
PROGRESSFILE="/tmp/sampswap/progress"
INSTALLINGFILE="/tmp/sampswap_installing"
shift=false
global_progress_file_exists=false
global_installing_file_exists=true
function init()
loading=true
samplei=1
sample=nil
current_tempo=clock.get_tempo()
lattice=lattice_:new()
lattice_beats=-1
pattern=lattice:new_pattern{
action=function(t)
if global_installing_file_exists then
do return end
end
loading=not util.file_exists(NRTREADY)
if sample==nil then
sample={}
for i=1,4 do
sample[i]=sample_:new{id=i}
end
params:default()
for i=1,4 do
sample[i]:default()
end
end
lattice_beats=lattice_beats+1
local tozero={}
if sample~=nil then
for i,smpl in ipairs(sample) do
if smpl:update_beat(lattice_beats) then
table.insert(tozero,i)
end
end
end
if #tozero==1 then
engine.tozero1(tozero[1])
elseif #tozero==2 then
engine.tozero2(tozero[1],tozero[2])
elseif #tozero==3 then
engine.tozero3(tozero[1],tozero[2],tozero[3])
end
global_progress_file_exists=util.file_exists(PROGRESSFILE)
if global_progress_file_exists then
progress_current=tonumber(util.os_capture("tail -n1 "..PROGRESSFILE))
else
progress_current=nil
end
end,
division=1/4
}
-- if norns.crow.connected() then
-- cs=crowseq:new()
-- crowpattern=lattice:new_pattern{
-- action=function(t)
-- cs:emit()
-- end,
-- division=1/16,
-- }
-- end
lattice:start()
-- startup scripts
startup_clock=clock.run(function()
os.execute(_path.code.."sampswap/lib/install.sh 2>&1 | tee /tmp/sampswap.log &")
end)
clock_redraw=clock.run(function()
while true do
clock.sleep(1/10)
if global_installing_file_exists then
global_installing_file_exists=util.file_exists(INSTALLINGFILE)
else
if sample~=nil and sample[samplei]~=nil then
sample[samplei]:update()
end
end
redraw()
end
end)
end
function enc(k,d)
if loading then
do return end
end
if d>0 then
d=1
elseif d<0 then
d=-1
end
if k==1 then
samplei=util.clamp(samplei+d,1,4)
elseif k==2 then
for i=1,4 do
sample[i]:option_sel_delta(samplei,d)
end
elseif k==3 then
sample[samplei]:option_set_delta(d)
end
end
function key(k,z)
if k==1 then
shift=z==1
elseif k==2 and z==1 then
if loading then
do return end
end
sample[samplei]:swap()
elseif k==3 and z==1 then
if shift then
lattice_beats=-1
lattice:hard_restart()
else
sample[samplei]:toggle_playing()
end
end
end
function redraw()
screen.clear()
screen.aa(0)
if global_installing_file_exists then
screen.move(64,32)
screen.text_center("installing sampswap...")
else
if sample~=nil and sample[samplei]~=nil then
sample[samplei]:redraw(sample,progress_current)
end
end
screen.update()
end
function cleanup()
print("cleaning up script...")
os.execute("/home/we/dust/code/sampswap/lib/cleanup.sh")
if lattice~=nil then
if lattice.superclock_id~=nil then
print("canceling lattice clock")
clock.cancel(lattice.superclock_id)
end
end
if sample~=nil then
for _,smpl in ipairs(sample) do
if smpl.cmd_clock~=nil then
clock.cancel(smpl.cmd_clock)
end
end
end
if clock_redraw~=nil then
clock.cancel(clock_redraw)
end
if startup_clock~=nil then
clock.cancel(startup_clock)
end
print("finished cleaning")
end
|
--[[------------------------------------------------------
# Very fast xml parser
The parser does not return information on comments, declarations,
doctypes and pi nodes. These are validly parsed but not returned.
This module is part of [lubyk](http://lubyk.org) project.
Install with [luarocks](http://luarocks.org) or [luadist](http://luadist.org).
$ luarocks install xml or luadist install xml
Dump a table to xml example:
local xml = require 'xml'
--]]------------------------------------------------------
local core = require 'xml.core'
local lub = require 'lub'
local lib = core.Parser
-- ## Parser types
-- The following constants can be used with #new when creating a parser.
-- Depending on the type, the parser behavior is different. The default type is
-- Default.
-- Default parser type. Translates xml entities (needs to make an internal
-- copy of the lua string).
-- lib.Default
-- Same as default but trims leading and trailing whitespace.
-- lib.TrimWhitespace
-- Faster then default, does not translate xml entities. Parses data nodes.
-- lib.NonDestructive
-- Like xml.NonDestructive but does not parse data nodes.
-- lib.Fastest
-- Create a new parser. `type` flag is optional. If you are using the default
-- parser, you can simply use [xml.parse](xml.html#parse).
-- Usage example:
--
-- local xml = require 'xml'
-- local parser = xml.Parser(xml.Parser.Fastest)
-- function lib.new(type)
-- Parse an xml string and return a Lua table. See [lua/xml](xml.html)
-- for the format of the returned table. Usage:
--
-- local data = parser:parse(some_xml_string)
-- --> lua table
-- function lib:parse(str)
-- Parse xml from file `path` and return a Lua table. See [lua/xml](xml.html)
-- for the format of the returned table. Usage:
--
-- local data = parser:load(path_to_file)
-- --> lua table
function lib:load(path)
return self:parse(lub.content(path))
end
return lib
|
--Automatically generated by SWGEmu Spawn Tool v0.12 loot editor.
carbine_ee3 = {
minimumLevel = 0,
maximumLevel = -1,
customObjectName = "Ee3 carbine",
directObjectTemplate = "object/weapon/ranged/carbine/carbine_ee3.iff",
craftingValues = {
{"mindamage",56,90,0},
{"maxdamage",91,163,0},
{"attackspeed",5.3,3.7,1},
{"woundchance",8,16,0},
{"roundsused",30,65,0},
{"hitpoints",750,1500,0},
{"zerorangemod",-35,-35,0},
{"maxrangemod",-50,-50,0},
{"midrange",40,40,0},
{"midrangemod",5,15,0},
{"attackhealthcost",33,18,0},
{"attackactioncost",52,28,0},
{"attackmindcost",26,14,0},
},
customizationStringNames = {},
customizationValues = {},
-- randomDotChance: The chance of this weapon object dropping with a random dot on it. Higher number means less chance. Set to 0 to always have a random dot.
randomDotChance = 800,
junkDealerTypeNeeded = JUNKWEAPONS,
junkMinValue = 25,
junkMaxValue = 45
}
addLootItemTemplate("carbine_ee3", carbine_ee3)
|
-- 获取参数
local requestIDKey = KEYS[1]
local currentRequestID = ARGV[1]
-- 判断requestID一致性
if redis.call('hget',KEYS[1],'lockKey') == currentRequestID
then
-- requestID相同,重入次数自减
local currentCount = redis.call('hincrby',KEYS[1],'lockCount',-1)
if currentCount == 0
then
-- 重入次数为0,删除锁
redis.call('del',KEYS[1])
return 1
else
return 0 end
else
return 0 end
|
--; ============================================================
--; Lua Weather
--; ============================================================
function setWeatherInput()
SKIN:Bang('!CommandMeasure MeterSkinInputWeather "ExecuteBatch 1"')
end
function setWeatherApply()
SKIN:Bang('!RefreshGroup WeatherCast')
end
function openLocation()
SKIN:Bang('https://weather.codes')
end
--; ============================================================
hoverSelect = {
["Over"] = {
colorCode = "255,215,0",
colorWeather = "255,215,0",
colorApply = "255,215,0"
},
["Leave"] = {
colorCode = "255,255,255",
colorWeather = "255,255,255",
colorApply = "255,255,255"
}
}
function setWeatherCode(selectedHover)
SKIN:Bang('!SetOption MeterWeatherActive FontColor "' .. hoverSelect[selectedHover]['colorCode'] .. '"')
SKIN:Bang('!Update')
end
function setWeatherInsert(selectedHover)
SKIN:Bang('!SetOption MeterLocationActive FontColor "' .. hoverSelect[selectedHover]['colorWeather'] .. '"')
SKIN:Bang('!Update')
end
function setHoverWeatherApply(selectedHover)
SKIN:Bang('!SetOption MeterApplyButton FontColor "' .. hoverSelect[selectedHover]['colorApply'] .. '"')
SKIN:Bang('!Update')
end
|
local Keys = {
["ESC"] = 322, ["F1"] = 288, ["F2"] = 289, ["F3"] = 170, ["F5"] = 166, ["F6"] = 167, ["F7"] = 168, ["F8"] = 169, ["F9"] = 56, ["F10"] = 57,
["~"] = 243, ["1"] = 157, ["2"] = 158, ["3"] = 160, ["4"] = 164, ["5"] = 165, ["6"] = 159, ["7"] = 161, ["8"] = 162, ["9"] = 163, ["-"] = 84, ["="] = 83, ["BACKSPACE"] = 177,
["TAB"] = 37, ["Q"] = 44, ["W"] = 32, ["E"] = 38, ["R"] = 45, ["T"] = 245, ["Y"] = 246, ["U"] = 303, ["P"] = 199, ["["] = 39, ["]"] = 40, ["ENTER"] = 18,
["CAPS"] = 137, ["A"] = 34, ["S"] = 8, ["D"] = 9, ["F"] = 23, ["G"] = 47, ["H"] = 74, ["K"] = 311, ["L"] = 182,
["LEFTSHIFT"] = 21, ["Z"] = 20, ["X"] = 73, ["C"] = 26, ["V"] = 0, ["B"] = 29, ["N"] = 249, ["M"] = 244, [","] = 82, ["."] = 81,
["LEFTCTRL"] = 36, ["LEFTALT"] = 19, ["SPACE"] = 22, ["RIGHTCTRL"] = 70,
["HOME"] = 213, ["PAGEUP"] = 10, ["PAGEDOWN"] = 11, ["DELETE"] = 178,
["LEFT"] = 174, ["RIGHT"] = 175, ["TOP"] = 27, ["DOWN"] = 173,
["NENTER"] = 201, ["N4"] = 108, ["N5"] = 60, ["N6"] = 107, ["N+"] = 96, ["N-"] = 97, ["N7"] = 117, ["N8"] = 61, ["N9"] = 118
}
ESX = nil
local InAction = false
Citizen.CreateThread(function()
while ESX == nil do
TriggerEvent('esx:getSharedObject', function(obj) ESX = obj end)
Citizen.Wait(0)
end
end)
Citizen.CreateThread(function()
while true do
Citizen.Wait(5)
for i=1, #Config.revList do
local revID = Config.revList[i]
local distance = GetDistanceBetweenCoords(GetEntityCoords(PlayerPedId()), revID.coords.x, revID.coords.y, revID.coords.z, true)
if distance < Config.MaxDistance and InAction == false then
if not Config.AlwaysAllow then
ESX.TriggerServerCallback('revivescript:getConnectedEMS', function(amount)
if amount < Config.ServiceCount then
ESX.Game.Utils.DrawText3D({ x = revID.coords.x, y = revID.coords.y, z = revID.coords.z + 1 }, revID.text, 1.2, 2)
--DrawText3D({ x = revID.coords.x, y = revID.coords.y, z = revID.coords.z}, 'Test: ' .. revID.text)
if IsControlJustReleased(0, Keys['E']) then
revActive(revID.coords.x, revID.coords.y, revID.coords.z, revID.heading, revID)
end
end
end)
else
ESX.Game.Utils.DrawText3D({ x = revID.coords.x, y = revID.coords.y, z = revID.coords.z + 1 }, revID.text, 1.2, 2)
--DrawText3D({ x = revID.coords.x, y = revID.coords.y, z = revID.coords.z}, 'Test: ' .. revID.text)
if IsControlJustReleased(0, Keys['E']) then
revActive(revID.coords.x, revID.coords.y, revID.coords.z, revID.heading, revID)
end
end
end
end
end
end)
function RespawnPed(ped, coords, heading)
SetEntityCoordsNoOffset(ped, 321.97, -590.64, 43.28, false, false, false, true)
NetworkResurrectLocalPlayer(321.97, -590.64, 43.28, 157.03, true, false)
SetPlayerInvincible(ped, false)
TriggerEvent('playerSpawned', 321.97, -590.64, 43.28)
ClearPedBloodDamage(ped)
end
function revActive(x, y, z, heading, source)
ESX.TriggerServerCallback('revivescript:checkMoney', function(hasEnoughMoney)
if hasEnoughMoney then
InAction = true
Citizen.CreateThread(function ()
Citizen.Wait(5)
local health = GetEntityHealth(PlayerPedId())
if (health < 300) then
if InAction == true then
local formattedCoords = {
x = 321.97,
y = -590.64,
z = 43.28
}
local playerID = ESX.Game.GetPlayerServerId
ESX.SetPlayerData('lastPosition', formattedCoords)
ESX.SetPlayerData('loadout', {})
TriggerServerEvent('esx_ambulancejob:revive', playerID)
TriggerServerEvent('revivescript:pay')
RespawnPed(PlayerPedId(), formattedCoords, 157.03)
TriggerServerEvent('esx:updateLastPosition', formattedCoords)
StopScreenEffect('DeathFailOut')
DoScreenFadeIn(800)
ESX.ShowNotification('You have been revived.')
ClearPedTasks(GetPlayerPed(-1))
FreezeEntityPosition(GetPlayerPed(-1), false)
SetEntityCoords(GetPlayerPed(-1), x + 1.0, y, z)
InAction = false
end
elseif (health == 200) then
ESX.ShowNotification('You do not need medical attention')
end
end)
else
ESX.ShowNotification('You do not have $' .. Config.Price .. ' to pay doctors.')
end
end)
end
Citizen.CreateThread(function()
while true do
Citizen.Wait(0)
SetPlayerHealthRechargeMultiplier(PlayerId(), 0.0)
end
end)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.