content
stringlengths 5
1.05M
|
|---|
--[[
MIT License
Copyright (c) [2021] [Juan de la Parra - DLP Wings]
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. ]]
-- Config
local fuelAlarmL = 30 --Default 30%
local fuelAlarmR = 30 --Default 30%
local fuelAlarmRepeat = 10000 --milliseconds
-- App variables
local sensorIdL = 0
local sensorIdR = 0
local demoMode = false
local demoModeCtrl
local resetReminder
local resetReminderFile
local resetDoneL = false
local resetDoneR = false
local booleanSelect = {"Yes", "No"}
local inputControls = {"P1", "P2", "P3", "P4"}
--Alarm
local fuelAlarmFile
local fuelAlarmPlayedL = false
local fuelAlarmPlayedR = false
local alarmVoice = true
local fuelAlarmArmedL = false
local fuelAlarmArmedR = false
local lastAlarmL = 0
local lastAlarmR = 0
--Telemetry Variables
local RPMValueL = 0
local EGTValueL = 0
local ECUVValueL = 0
local EcuBattValueL = 0
local FuelValueL = 0
local StatusCodeL = 0
local MessageCodeL = 0
local RPMValueR = 0
local EGTValueR = 0
local ECUVValueR = 0
local EcuBattValueR = 0
local FuelValueR = 0
local StatusCodeR = 0
local MessageCodeR = 0
-- Create an arrow
local renShape=lcd.renderer()
local largeHandle = {
{ 1, -46},
{ -1, -46},
{-3, -18},
{ 0, -18},
{ 3, -18}
}
local alarmHandle = {
{ 5, -48},
{ -5, -48},
{ 0, -36}
}
local mediumHandle = {
{ 1, -39},
{ -1, -39},
{-3, -16},
{ 0, -16},
{ 3, -16}
}
local smallHandle = {
{ 1, -25},
{ -1, -25},
{-2, -10},
{ 0, -10},
{ 2, -10}
}
local flameOutCodes = {
[12] = true, --"No RX"
[15] = true, --"Failsafe"
[19] = true, --"Turbine Comm Error"
[22] = true, --"Low RPM"
[23] = true --"RPM Sensor Error"
}
local jcLogo
local sensorsAvailable = {}
local flameOutL = false
local flameOutR = false
local flameOutResetL = false
local flameOutResetR = false
local flameOutTC_Enabled = false
local flameOutFileL
local flameOutFileR
local flameOutRepeat = 3000
local lastFlameOutRepeat = 0
local inputThrottle = 4
local inputThrottlePos = -95
collectgarbage()
local function drawShape(col, row, shape, rotation)
local sinShape = math.sin(rotation)
local cosShape = math.cos(rotation)
renShape:reset()
for index, point in pairs(shape) do
renShape:addPoint(
col + (point[1] * cosShape - point[2] * sinShape + 0.5),
row + (point[1] * sinShape + point[2] * cosShape + 0.5)
)
end
renShape:renderPolygon()
end
--Form functions
local function sensorChangedL(value)
if(value and value >=0) then
sensorIdL=sensorsAvailable[value].id
else
sensorIdL = 0
end
system.pSave("SensorIdL",sensorIdL)
end
local function sensorChangedR(value)
if(value and value >=0) then
sensorIdR=sensorsAvailable[value].id
else
sensorIdR = 0
end
system.pSave("SensorIdR",sensorIdR)
end
local function inputThrottleChanged(value)
inputThrottle = value
print(inputThrottle)
system.pSave("inputThrottle",inputThrottle)
end
local function inputThrottlePosChanged(value)
inputThrottlePos = value
system.pSave("inputThrottlePosChanged",inputThrottlePos)
end
local function fuelAlarmChanged(value)
fuelAlarmL = value
system.pSave("FuelAlarm",value)
end
local function fuelAlarmRepeatChanged(value)
fuelAlarmRepeat = value*1000
system.pSave("FuelAlarmRepeat",fuelAlarmRepeat)
end
local function flameOutFileLChanged(value)
flameOutFileL=value
system.pSave("flameOutFileL",value)
end
local function flameOutFileRChanged(value)
flameOutFileR=value
system.pSave("flameOutFileR",value)
end
local function flameOutRepeatChanged(value)
flameOutRepeat = value*1000
system.pSave("flameOutRepeat",flameOutRepeat)
end
local function fuelAlarmFileChanged(value)
fuelAlarmFile=value
system.pSave("FuelAlarmFile",value)
end
local function resetReminderFileChanged(value)
resetReminderFile=value
system.pSave("ResetReminderFile",value)
end
local function alarmVoiceValueChanged(value)
alarmVoice = value
system.pSave("AlarmVoice",alarmVoice)
end
local function resetReminderChanged(value)
resetReminder = value
system.pSave("ResetReminder",resetReminder)
end
local function demoModeChanged(value)
demoMode = not value
form.setValue(demoModeCtrl,demoMode)
if demoMode then system.pSave("DemoMode",1) else system.pSave("DemoMode",0) end
end
local function decodeStatus(statusID)
if statusID == 10 then return "Stop"
elseif statusID == 20 then return "Glow Test"
elseif statusID == 30 then return "Starter Test"
elseif statusID == 31 then return "Prime Fuel"
elseif statusID == 32 then return "Prime Burner"
elseif statusID == 40 then return "Manual Cooling"
elseif statusID == 41 then return "Auto Cooling"
elseif statusID == 51 then return "Igniter Heat"
elseif statusID == 52 then return "Ignition"
elseif statusID == 53 then return "Preheat"
elseif statusID == 54 then return "Switchover"
elseif statusID == 55 then return "To Idle"
elseif statusID == 56 then return "Running"
elseif statusID == 62 then return "Stop Error"
else return "No Data"
end
end
local function decodeMessage(messageID)
if messageID == 1 then return "Ignition Error"
elseif messageID == 2 then return "Preheat Error"
elseif messageID == 3 then return "Switchover Error"
elseif messageID == 4 then return "Starter Motor Error"
elseif messageID == 5 then return "To Idle Error"
elseif messageID == 6 then return "Acceleration Error"
elseif messageID == 7 then return "Igniter Bad"
elseif messageID == 8 then return "Min Pump Ok"
elseif messageID == 9 then return "Max Pump Ok"
elseif messageID == 10 then return "Low RX Battery"
elseif messageID == 11 then return "Low ECU Battery"
elseif messageID == 12 then return "No RX"
elseif messageID == 13 then return "Trim Down"
elseif messageID == 14 then return "Trim Up"
elseif messageID == 15 then return "Failsafe"
elseif messageID == 16 then return "Full"
elseif messageID == 17 then return "RX Setup Error"
elseif messageID == 18 then return "Temp Sensor Error"
elseif messageID == 19 then return "Turbine Comm Error"
elseif messageID == 20 then return "Max Temp"
elseif messageID == 21 then return "Max Amperes"
elseif messageID == 22 then return "Low RPM"
elseif messageID == 23 then return "RPM Sensor Error"
elseif messageID == 24 then return "Max Pump"
else return "No Data"
end
end
local function checkDemoMode()
if demoMode then
FuelValueL = 100*((system.getInputs( "P5" ) + 1.0)/2)
FuelValueR = 100*((system.getInputs( "P6" ) + 1.0)/2)
RPMValueL = math.floor((((system.getInputs( "P4" ) + 1.0)/2)*150) * 1000)
RPMValueR = math.floor((((system.getInputs( "P2" ) + 1.0)/2)*150) * 1000)
EGTValueL = 1000*((system.getInputs( "P7" ) + 1.0)/2)
EGTValueR = 1000*((system.getInputs( "P7" ) + 1.0)/2)
EcuBattValueL = 100*((system.getInputs( "P8" ) + 1.0)/2)
EcuBattValueR = 100*((system.getInputs( "P8" ) + 1.0)/2)
ECUVValueL = 12.6*((system.getInputs( "P8" ) + 1.0)/2)
ECUVValueR = 12.6*((system.getInputs( "P8" ) + 1.0)/2)
StatusCodeL = system.getInputs( "SB" )
StatusCodeR = system.getInputs( "SC" )
if StatusCodeL == 0 then
StatusCodeL = 62
MessageCodeL = 22
end
if StatusCodeR == 0 then
StatusCodeR = 62
MessageCodeR = 23
end
if StatusCodeL == 1 then
StatusCodeL = 56
MessageCodeL = 9
end
if StatusCodeL == -1 then
StatusCodeL = 10
MessageCodeL = 13
end
if StatusCodeR == 1 then
StatusCodeR = 56
MessageCodeR = 9
end
if StatusCodeR == -1 then
StatusCodeR = 10
MessageCodeR = 13
end
end
end
local function checkFuelAlarmFlags()
if(StatusCodeL == 56 and FuelValueL > fuelAlarmL) then fuelAlarmArmedL = true end
if(StatusCodeR == 56 and FuelValueR > fuelAlarmR) then fuelAlarmArmedR = true end
if(StatusCodeL == 10 or MessageCodeL == 13) then
fuelAlarmArmedL = false
fuelAlarmPlayedL = false
resetDoneL = false
flameOutResetL = false
end
if(StatusCodeR == 10 or MessageCodeR == 13) then
fuelAlarmArmedR = false
fuelAlarmPlayedR = false
resetDoneR = false
flameOutResetR = false
end
end
local function checkFuelAlarm()
if (fuelAlarmL ~= 0 and FuelValueL ~= -1) then
if(fuelAlarmArmedL and FuelValueL <= fuelAlarmL) then
if fuelAlarmRepeat == 0 and fuelAlarmPlayedL then
--Prevent further repetitions
elseif system.getTimeCounter() - lastAlarmL > fuelAlarmRepeat then
if fuelAlarmFile ~= "" then system.playFile(fuelAlarmFile,AUDIO_QUEUE) end
if alarmVoice then system.playNumber(FuelValueL,0,"%") end
system.messageBox("Warning: LOW FUEL LEFT TANK",3)
lastAlarmL = system.getTimeCounter()
fuelAlarmPlayedL = true
end
end
end
if (fuelAlarmR ~= 0 and FuelValueR ~= -1) then
if(fuelAlarmArmedR and FuelValueR <= fuelAlarmR) then
if fuelAlarmRepeat == 0 and fuelAlarmPlayedR then
--Prevent further repetitions
elseif system.getTimeCounter() - lastAlarmR > fuelAlarmRepeat then
if fuelAlarmFile ~= "" then system.playFile(fuelAlarmFile,AUDIO_QUEUE) end
if alarmVoice then system.playNumber(FuelValueL,0,"%") end
system.messageBox("Warning: LOW FUEL RIGHT TANK",3)
lastAlarmR = system.getTimeCounter()
fuelAlarmPlayedR = true
end
end
end
end
local function checkReminderAlert()
local showMsg = false
if(StatusCodeL == 56 and resetReminder == 1) then
if (resetDoneL == false and FuelValueL < 95) then
showMsg = true
if resetReminderFile ~= "" then system.playFile(resetReminderFile,AUDIO_QUEUE) end
resetDoneL = true
else
resetDoneL = true
end
end
if(StatusCodeR == 56 and resetReminder == 1) then
if (resetDoneR == false and FuelValueR < 95) then
showMsg = true
if resetReminderFile ~= "" then system.playFile(resetReminderFile,AUDIO_QUEUE) end
resetDoneR = true
else
resetDoneR = true
end
end
if showMsg then
system.messageBox("Reset fuel consumption!",5)
end
end
local function flameOutAlarm()
local t_hold = (inputThrottlePos/100)
local inputCtrl
if inputThrottle == 1 then
inputCtrl = "P1"
elseif inputThrottle == 2 then
inputCtrl = "P2"
elseif inputThrottle == 3 then
inputCtrl = "P3"
elseif inputThrottle == 4 then
inputCtrl = "P4"
end
if flameOutCodes[MessageCodeL] then
flameOutL = true
end
if flameOutCodes[MessageCodeR] then
flameOutR = true
end
if flameOutL or flameOutR then
--Alert flameout
if t_hold < 0 then
if system.getInputs(inputCtrl) > t_hold and flameOutTC_Enabled == false then
system.setControl(1,1,0,0)
elseif system.getInputs(inputCtrl) <= t_hold then
system.setControl(1,-1,0,0)
end
else
if system.getInputs(inputCtrl) < t_hold and flameOutTC_Enabled == false then
system.setControl(1,1,0,0)
elseif system.getInputs(inputCtrl) >= t_hold then
system.setControl(1,-1,0,0)
end
end
flameOutTC_Enabled = true
end
if flameOutTC_Enabled then
if system.getTimeCounter() - lastFlameOutRepeat > flameOutRepeat and flameOutRepeat > 0 then
if flameOutL then
system.messageBox("Left engine flameout!",2)
if flameOutFileL ~= "" then system.playFile(flameOutFileL,AUDIO_QUEUE) end
--print("Left Flameout")
elseif flameOutR then
system.messageBox("Right engine flameout!",2)
if flameOutFileR ~= "" then system.playFile(flameOutFileR,AUDIO_QUEUE) end
--print("Right Flameout")
end
lastFlameOutRepeat = system.getTimeCounter()
end
end
end
local function resetFlameOutStatus()
if (StatusCodeL == 56 or MessageCodeL == 13) and flameOutResetL == false then
flameOutL = false
flameOutResetL = true
end
if (StatusCodeR == 56 or MessageCodeR == 13) and flameOutResetR == false then
flameOutR = false
flameOutResetR = true
end
if flameOutL == false and flameOutR == false then
system.setControl(1,-1,0,0)
flameOutTC_Enabled = false
end
end
local function initSettingsForm(formID)
sensorsAvailable = {}
local available = system.getSensors();
local list={}
local curIndexL=-1
local curIndexR=-1
for index,sensor in ipairs(available) do
if(sensor.param == 0) then
list[#list+1] = sensor.label
sensorsAvailable[#sensorsAvailable+1] = sensor
if(sensor.id==sensorIdL ) then
curIndexL=#sensorsAvailable
end
if(sensor.id==sensorIdR ) then
curIndexR=#sensorsAvailable
end
end
end
-- sensor select
form.addRow(2)
form.addLabel({label="Select left sensor",width=140})
form.addSelectbox (list, curIndexL,true,sensorChangedL,{width=170})
form.addRow(2)
form.addLabel({label="Select right sensor",width=140})
form.addSelectbox (list, curIndexR,true,sensorChangedR,{width=170})
form.addSpacer(100,10)
form.addLabel({label="Alarms",font=FONT_BOLD})
form.addRow(3)
form.addLabel({label="Fuel warning [%]", width=130})
form.addLabel({label="(0=Disabled)", width=80, font=FONT_MINI})
form.addIntbox(fuelAlarmL,0,99,30,0,1,fuelAlarmChanged)
form.addRow(2)
form.addLabel({label=" File",width=190})
form.addAudioFilebox(fuelAlarmFile or "",fuelAlarmFileChanged)
form.addRow(2)
form.addLabel({label=" Repeat every [s]", width=190})
form.addIntbox(fuelAlarmRepeat/1000,0,60,10,0,1,fuelAlarmRepeatChanged,{width=120})
form.addRow(2)
form.addLabel({label=" Announce value by voice", width=240})
form.addSelectbox (booleanSelect, alarmVoice,false,alarmVoiceValueChanged)
form.addRow(2)
form.addLabel({label="Fuel consumption reset reminder", width=240})
form.addSelectbox (booleanSelect, resetReminder,false,resetReminderChanged)
form.addRow(2)
form.addLabel({label=" File",width=190})
form.addAudioFilebox(resetReminderFile or "",resetReminderFileChanged)
--form.addSpacer(100,10)
--form.addLabel({label="Engine Flameout Alarm",font=FONT_BOLD})
form.addRow(2)
form.addLabel({label="L engine flameout file",width=190})
form.addAudioFilebox(flameOutFileL or "",flameOutFileLChanged)
form.addRow(2)
form.addLabel({label="R engine flameout file",width=190})
form.addAudioFilebox(flameOutFileR or "",flameOutFileRChanged)
form.addRow(2)
form.addLabel({label=" Repeat every [s]", width=190})
form.addIntbox(flameOutRepeat/1000,0,10,3,0,1,flameOutRepeatChanged,{width=120})
form.addSpacer(100,10)
form.addLabel({label="Engine Flameout Throttle Cut",font=FONT_BOLD})
form.addRow(2)
form.addLabel({label="Throttle input control", width=170})
form.addSelectbox(inputControls,inputThrottle, false,inputThrottleChanged,{width=140})
form.addRow(2)
form.addLabel({label="Throttle regain position", width=210})
form.addIntbox(inputThrottlePos,-100,100,-95,0,1,inputThrottlePosChanged,{width=100})
--form.addInputbox(switch, true, function(value) print(value) end)
--form.addRow(1)
--form.addLabel({label="- Make shure input control is selected as PROPORTIONAL", font=FONT_MINI})
form.addLabel({label=" To enable:", font=FONT_MINI})
form.addRow(1)
form.addLabel({label="- Set Throttle Cut SW to 'User Applications/FSW'", font=FONT_MINI})
form.addRow(1)
form.addLabel({label=" and desired output value in: 'Menu > Advanced -", font=FONT_MINI})
form.addRow(1)
form.addLabel({label=" Properties > Other Model Options'", font=FONT_MINI})
form.addRow(1)
form.addLabel({label="- In case of engine flameout Throttle Cut will be engaged,", font=FONT_MINI})
form.addRow(1)
form.addLabel({label=" move stick immediately to position set above to regain ", font=FONT_MINI})
form.addRow(1)
form.addLabel({label=" throttle control", font=FONT_MINI})
form.addRow(1)
form.addLabel({label="- Always make sure everything works as expected", font=FONT_MINI})
form.addRow(1)
form.addLabel({label=" before actually flying your model.", font=FONT_MINI})
form.addRow(1)
form.addLabel({label="- Jet Central is not in any way responsible for", font=FONT_MINI})
form.addRow(1)
form.addLabel({label=" any injuries and/or damage while using this feature.", font=FONT_MINI})
--form.addLabel({label="", font=FONT_MINI})
--[[ form.addSpacer(100,10)
form.addLabel({label="Alternating display",font=FONT_BOLD})
form.addRow(2)
form.addLabel({label="Show RPM", width=190})
form.addSelectbox (booleanSelect, alternateRPM,false,alternateRPMChanged)
form.addRow(2)
form.addLabel({label="Show EGT [°C]", width=190})
form.addSelectbox (booleanSelect, alternateEGT,false,alternateEGTChanged)
form.addRow(2)
form.addLabel({label="Show ECU batt [V]", width=190})
form.addSelectbox (booleanSelect, alternateBattV,false,alternateBattVChanged)
form.addRow(2)
form.addLabel({label="Show ECU batt [%]", width=190})
form.addSelectbox (booleanSelect, alternateBatt,false,alternateBattChanged)
form.addRow(2)
form.addLabel({label="Change display every [s]", width=190})
form.addIntbox(alternatingDelay/100,10,100,30,1,1,alternatingDelayChanged,{width=120})
]]
--Demo Mode
form.addSpacer(100,10)
form.addRow(2)
form.addLabel({label="Demo mode enabled", width=274})
demoModeCtrl = form.addCheckbox(demoMode,demoModeChanged)
collectgarbage()
end
local function printFullDisplay(width, height)
local lbl, val
lcd.drawImage(0, 0, jcLogo)
lcd.setColor(0x22,0x2B,0x00,255)
lbl = decodeStatus(StatusCodeL)
lcd.drawText(62 - (lcd.getTextWidth(FONT_NORMAL,lbl))/2,121 ,lbl,FONT_NORMAL)
lbl = decodeMessage(MessageCodeL)
lcd.drawText(62 - (lcd.getTextWidth(FONT_MINI,lbl))/2,138 ,lbl,FONT_MINI)
lbl = decodeStatus(StatusCodeR)
lcd.drawText(260 - (lcd.getTextWidth(FONT_NORMAL,lbl))/2,121 ,lbl,FONT_NORMAL)
lbl = decodeMessage(MessageCodeR)
lcd.drawText(260 - (lcd.getTextWidth(FONT_MINI,lbl))/2,138 ,lbl,FONT_MINI)
lcd.setColor(0xFF,0x55,0x55,255)
drawShape(159, (56), alarmHandle, math.rad(220+fuelAlarmL*1.2))
drawShape(159, (56), alarmHandle, math.rad(140-fuelAlarmR*1.2))
lcd.setColor(240,240,240,255)
--Fuel Gauge
val=FuelValueL
lbl = string.format("%d%%", val)
if val == -1 then
lbl = "_"
val=-10
end
drawShape(159, (56), largeHandle, math.rad(220+val*1.2))
lcd.drawText((160 - (lcd.getTextWidth(FONT_BOLD,lbl))/2),72 ,lbl,FONT_BOLD)
val=FuelValueR
lbl = string.format("%d%%", val)
if val == -1 then
lbl = "_"
val=-10
end
drawShape(159, (56), largeHandle, math.rad(140-val*1.2))
lcd.drawText((160 - (lcd.getTextWidth(FONT_BOLD,lbl))/2),86 ,lbl,FONT_BOLD)
--RPM Gauge
val = RPMValueL
if val == -1 then
lbl = "_"
val=-20
else
val=math.floor(RPMValueL/1000)
lbl = string.format("%d", val)
end
drawShape(56, (63), mediumHandle, math.rad(220+val*0.8))
lcd.drawText((57 - (lcd.getTextWidth(FONT_NORMAL,lbl))/2),74 ,lbl,FONT_NORMAL)
val = RPMValueR
if val == -1 then
lbl = "_"
val=-20
else
val=math.floor(RPMValueR/1000)
lbl = string.format("%d", val)
end
drawShape(56, (63), mediumHandle, math.rad(140-val*0.8))
lcd.drawText((57 - (lcd.getTextWidth(FONT_NORMAL,lbl))/2),88 ,lbl,FONT_NORMAL)
--EGT Gauge
val=EGTValueL
lbl = string.format("%d", val)
if val == -1 then
lbl = "_"
val=-160
end
drawShape(242, 78, smallHandle, math.rad(220 + val/10))
lcd.drawText((243 - (lcd.getTextWidth(FONT_MINI,lbl))/2), 85, lbl, FONT_MINI)
val=EGTValueR
lbl = string.format("%d", val)
if val == -1 then
lbl = "_"
val=-160
end
drawShape(242, 78, smallHandle, math.rad(140 - val/10))
lcd.drawText((243 - (lcd.getTextWidth(FONT_MINI,lbl))/2), 95, lbl, FONT_MINI)
--Batt Gauge
val=EcuBattValueL
lbl = string.format("%.1fv", ECUVValueL)
if val == -1 then
lbl = "_"
val=-12
end
drawShape(284, 32, smallHandle, math.rad(220+val*1.2))
lcd.drawText((287 - (lcd.getTextWidth(FONT_MINI,lbl))/2), 37, lbl, FONT_MINI)
val=EcuBattValueR
lbl = string.format("%.1fv", ECUVValueR)
if val == -1 then
lbl = "_"
val=-12
end
drawShape(284, 32, smallHandle, math.rad(140-val*1.2))
lcd.drawText((287 - (lcd.getTextWidth(FONT_MINI,lbl))/2), 47, lbl, FONT_MINI)
collectgarbage()
end
local function init()
-- sensor id
sensorIdL = system.pLoad("SensorIdL",0)
sensorIdR = system.pLoad("SensorIdR",0)
if sensorIdL == 0 then
local available = system.getSensors()
for index,sensor in ipairs(available) do
if((sensor.id & 0xFFFFFF) == 0x4CA40C) then -- Fill default sensor ID
sensorIdL = sensor.id
break
end
end
end
if sensorIdR == 0 then
local available = system.getSensors()
for index,sensor in ipairs(available) do
if((sensor.id & 0xFFFFFF) == 0x52A40C) then -- Fill default sensor ID
sensorIdR = sensor.id
break
end
end
end
--Load Settings
inputThrottle = system.pLoad("inputThrottle",4)
inputThrottlePos = system.pLoad("inputThrottlePos",-95)
flameOutFileL = system.pLoad("flameOutFileL","")
flameOutFileR = system.pLoad("flameOutFileR","")
flameOutRepeat = system.pLoad("flameOutRepeat",3000)
fuelAlarmL = system.pLoad("FuelAlarm",30)
fuelAlarmR = system.pLoad("FuelAlarm",30)
fuelAlarmFile = system.pLoad("FuelAlarmFile","")
fuelAlarmRepeat = system.pLoad("FuelAlarmRepeat",10000)
demoMode = system.pLoad("DemoMode",0)
if demoMode == 0 then demoMode = false else demoMode = true end
alarmVoice = system.pLoad("AlarmVoice", 1)
resetReminder = system.pLoad("ResetReminder",1)
resetReminderFile = system.pLoad("ResetReminderFile","")
system.registerTelemetry( 1, "Jet Central Twin HDT", 4, printFullDisplay)
system.registerForm(1,MENU_TELEMETRY,"Jet Central Twin HDT",initSettingsForm,nil,nil)
system.registerControl(1,"Flameout Switch","FSW")
system.setControl(1,-1,0,0)
jcLogo = lcd.loadImage("Apps/JetCentral/CFTwin.png")
collectgarbage()
end
local function loop()
local sensor
-- RPM
sensor = system.getSensorByID(sensorIdL,1)
if( sensor and sensor.valid ) then RPMValueL = sensor.value else RPMValueL = -1 end
sensor = system.getSensorByID(sensorIdR,1)
if( sensor and sensor.valid ) then RPMValueR = sensor.value else RPMValueR = -1 end
-- EGT
sensor = system.getSensorByID(sensorIdL,2)
if( sensor and sensor.valid ) then EGTValueL = sensor.value else EGTValueL = -1 end
sensor = system.getSensorByID(sensorIdR,2)
if( sensor and sensor.valid ) then EGTValueR = sensor.value else EGTValueR = -1 end
-- EcuV
sensor = system.getSensorByID(sensorIdL,3)
if( sensor and sensor.valid ) then ECUVValueL = sensor.value else ECUVValueL = -1 end
sensor = system.getSensorByID(sensorIdR,3)
if( sensor and sensor.valid ) then ECUVValueR = sensor.value else ECUVValueR = -1 end
-- EcuBatt
sensor = system.getSensorByID(sensorIdL,5)
if( sensor and sensor.valid ) then EcuBattValueL = sensor.value else EcuBattValueL = -1 end
sensor = system.getSensorByID(sensorIdR,5)
if( sensor and sensor.valid ) then EcuBattValueR = sensor.value else EcuBattValueR = -1 end
-- Fuel
sensor = system.getSensorByID(sensorIdL,6)
if( sensor and sensor.valid ) then FuelValueL = sensor.value else FuelValueL = -1 end
sensor = system.getSensorByID(sensorIdR,6)
if( sensor and sensor.valid ) then FuelValueR = sensor.value else FuelValueR = -1 end
-- Status
sensor = system.getSensorByID(sensorIdL,8)
if( sensor and sensor.valid ) then StatusCodeL = sensor.value else StatusCodeL = 0 end
sensor = system.getSensorByID(sensorIdR,8)
if( sensor and sensor.valid ) then StatusCodeR = sensor.value else StatusCodeR = 0 end
-- Message
sensor = system.getSensorByID(sensorIdL,9)
if( sensor and sensor.valid ) then MessageCodeL = sensor.value else MessageCodeL = 0 end
sensor = system.getSensorByID(sensorIdR,9)
if( sensor and sensor.valid ) then MessageCodeR = sensor.value else MessageCodeR = 0 end
checkDemoMode()
checkFuelAlarmFlags()
checkReminderAlert()
resetFlameOutStatus()
checkFuelAlarm()
flameOutAlarm()
collectgarbage()
end
return {init=init, loop=loop, author="DLPWings", version="1.00",name="Jet Central Twin HDT"}
|
#!/usr/bin/lua
-- Implements an automaton by Elliott Hird.
-- Not sure what it was supposed to do...
m = {}
x = 0
while 1 do
m[m[0] or 0] = x
x = m[(m[0] or 0) + 1]
m[0] = x
end
|
function make_heavy_gunshot_sounds(volume)
return
{
{
filename = "__base__/sound/fight/heavy-gunshot-1.ogg",
volume = 0.45
},
{
filename = "__base__/sound/fight/heavy-gunshot-2.ogg",
volume = 0.45
},
{
filename = "__base__/sound/fight/heavy-gunshot-3.ogg",
volume = 0.45
},
{
filename = "__base__/sound/fight/heavy-gunshot-4.ogg",
volume = 0.45
}
}
end
function make_light_gunshot_sounds(volume)
return
{
{
filename = "__base__/sound/fight/light-gunshot-1.ogg",
volume = 0.3
},
{
filename = "__base__/sound/fight/light-gunshot-2.ogg",
volume = 0.3
},
{
filename = "__base__/sound/fight/light-gunshot-3.ogg",
volume = 0.3
}
}
end
|
function match(match, _M)
local _ = _M.new_ip;
local ip = _"10.20.30.40";
assert_equal(match(ip, _"10.0.0.0", 8), true);
assert_equal(match(ip, _"10.0.0.0", 16), false);
assert_equal(match(ip, _"10.0.0.0", 24), false);
assert_equal(match(ip, _"10.0.0.0", 32), false);
assert_equal(match(ip, _"10.20.0.0", 8), true);
assert_equal(match(ip, _"10.20.0.0", 16), true);
assert_equal(match(ip, _"10.20.0.0", 24), false);
assert_equal(match(ip, _"10.20.0.0", 32), false);
assert_equal(match(ip, _"0.0.0.0", 32), false);
assert_equal(match(ip, _"0.0.0.0", 0), true);
assert_equal(match(ip, _"0.0.0.0"), false);
assert_equal(match(ip, _"10.0.0.0", 255), false, "excessive number of bits");
assert_equal(match(ip, _"10.0.0.0", -8), true, "negative number of bits");
assert_equal(match(ip, _"10.0.0.0", -32), true, "negative number of bits");
assert_equal(match(ip, _"10.0.0.0", 0), true, "zero bits");
assert_equal(match(ip, _"10.0.0.0"), false, "no specified number of bits (differing ip)");
assert_equal(match(ip, _"10.20.30.40"), true, "no specified number of bits (same ip)");
assert_equal(match(_"127.0.0.1", _"127.0.0.1"), true, "simple ip");
assert_equal(match(_"8.8.8.8", _"8.8.0.0", 16), true);
assert_equal(match(_"8.8.4.4", _"8.8.0.0", 16), true);
end
function parse_cidr(parse_cidr, _M)
local new_ip = _M.new_ip;
assert_equal(new_ip"0.0.0.0", new_ip"0.0.0.0")
local function assert_cidr(cidr, ip, bits)
local parsed_ip, parsed_bits = parse_cidr(cidr);
assert_equal(new_ip(ip), parsed_ip, cidr.." parsed ip is "..ip);
assert_equal(bits, parsed_bits, cidr.." parsed bits is "..tostring(bits));
end
assert_cidr("0.0.0.0", "0.0.0.0", nil);
assert_cidr("127.0.0.1", "127.0.0.1", nil);
assert_cidr("127.0.0.1/0", "127.0.0.1", 0);
assert_cidr("127.0.0.1/8", "127.0.0.1", 8);
assert_cidr("127.0.0.1/32", "127.0.0.1", 32);
assert_cidr("127.0.0.1/256", "127.0.0.1", 256);
assert_cidr("::/48", "::", 48);
end
function new_ip(new_ip)
local v4, v6 = "IPv4", "IPv6";
local function assert_proto(s, proto)
local ip = new_ip(s);
if proto then
assert_equal(ip and ip.proto, proto, "protocol is correct for "..("%q"):format(s));
else
assert_equal(ip, nil, "address is invalid");
end
end
assert_proto("127.0.0.1", v4);
assert_proto("::1", v6);
assert_proto("", nil);
assert_proto("abc", nil);
assert_proto(" ", nil);
end
function commonPrefixLength(cpl, _M)
local new_ip = _M.new_ip;
local function assert_cpl6(a, b, len, v4)
local ipa, ipb = new_ip(a), new_ip(b);
if v4 then len = len+96; end
assert_equal(cpl(ipa, ipb), len, "common prefix length of "..a.." and "..b.." is "..len);
assert_equal(cpl(ipb, ipa), len, "common prefix length of "..b.." and "..a.." is "..len);
end
local function assert_cpl4(a, b, len)
return assert_cpl6(a, b, len, "IPv4");
end
assert_cpl4("0.0.0.0", "0.0.0.0", 32);
assert_cpl4("255.255.255.255", "0.0.0.0", 0);
assert_cpl4("255.255.255.255", "255.255.0.0", 16);
assert_cpl4("255.255.255.255", "255.255.255.255", 32);
assert_cpl4("255.255.255.255", "255.255.255.255", 32);
assert_cpl6("::1", "::1", 128);
assert_cpl6("abcd::1", "abcd::1", 128);
assert_cpl6("abcd::abcd", "abcd::", 112);
assert_cpl6("abcd::abcd", "abcd::abcd:abcd", 96);
end
|
--[[
Copyright (c) 2014, Robert 'Bobby' Zenz
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
--]]
-- Get the base path.
local base_path = minetest.get_modpath(minetest.get_current_modname())
-- Instance utils
dofile(base_path .. "/arraymanipulator.lua")
dofile(base_path .. "/blockedcache.lua")
dofile(base_path .. "/color.lua")
dofile(base_path .. "/directmapmanipulator.lua")
dofile(base_path .. "/list.lua")
dofile(base_path .. "/mapmanipulator.lua")
dofile(base_path .. "/noisemanager.lua")
-- Static utils
dofile(base_path .. "/arrayutil.lua")
dofile(base_path .. "/blockutil.lua")
dofile(base_path .. "/constants.lua")
dofile(base_path .. "/entityutil.lua")
dofile(base_path .. "/facedirutil.lua")
dofile(base_path .. "/fisheryates.lua")
dofile(base_path .. "/interpolate.lua")
dofile(base_path .. "/inventoryutil.lua")
dofile(base_path .. "/itemutil.lua")
dofile(base_path .. "/log.lua")
dofile(base_path .. "/mathutil.lua")
dofile(base_path .. "/minetestex.lua")
dofile(base_path .. "/numberutil.lua")
dofile(base_path .. "/nodeutil.lua")
dofile(base_path .. "/nodeboxutil.lua")
dofile(base_path .. "/objectrefutil.lua")
dofile(base_path .. "/pathutil.lua")
dofile(base_path .. "/posutil.lua")
dofile(base_path .. "/random.lua")
dofile(base_path .. "/rotationutil.lua")
dofile(base_path .. "/scheduler.lua")
dofile(base_path .. "/settings.lua")
dofile(base_path .. "/stopwatch.lua")
dofile(base_path .. "/stringutil.lua")
dofile(base_path .. "/tableutil.lua")
dofile(base_path .. "/tango.lua")
dofile(base_path .. "/textureutil.lua")
dofile(base_path .. "/transform.lua")
dofile(base_path .. "/wallmountedutil.lua")
|
cubedispenser = class:new()
function cubedispenser:init(x, y, r)
--PHYSICS STUFF
self.cox = x
self.coy = y
self.x = x-1
self.y = y-1
self.speedy = 0
self.speedx = 0
self.width = 2
self.height = 2
self.static = true
self.active = true
self.category = 7
self.mask = {true, false, false, false, false, false, false, false, true}
self.r = r
self.timer = cubedispensertime
self.inputactive = false
self.boxexists = false
self.box = nil
end
function cubedispenser:input(t)
if t == "on" or t == "toggle" then
if self.boxexists then
self.boxexists = false
self:removebox()
end
if self.timer == cubedispensertime then
self.timer = 0
end
end
end
function cubedispenser:link()
self.outtable = {}
if #self.r > 2 then
for j, w in pairs(outputs) do
for i, v in pairs(objects[w]) do
if tonumber(self.r[4]) == v.cox and tonumber(self.r[5]) == v.coy then
v:addoutput(self)
if entityquads[map[v.cox][v.coy][2]].t == "box" then
self.boxexists = true
end
end
end
end
end
end
function cubedispenser:update(dt)
if self.timer < cubedispensertime then
self.timer = self.timer + dt
if self.timer > 0.1 and self.timer <= 0.4 and self.active == true then
self.active = false
elseif self.timer > 0.4 and self.timer <= 0.6 and self.active == false then
self.active = true
elseif self.timer > 0.6 and self.boxexists == false then
local temp = box:new(self.cox+.5, self.coy)
table.insert(objects["box"], temp)
self.box = temp
objects["box"][#objects["box"]]:addoutput(self)
self.boxexists = true
elseif self.timer > 1 then
self.timer = 1
end
end
return false
end
function cubedispenser:draw()
love.graphics.draw(cubedispenserimg, math.floor((self.cox-xscroll-1)*16*scale), (self.coy-1.5)*16*scale, 0, scale, scale, 0, 0)
end
function cubedispenser:removebox()
if self.box then
self.box.userect.delete = true
self.box.destroying = true
end
end
|
local ui = require 'lib.LoveUIView'
local Button = ui.Button
local View = ui.View
local ObjectCollection = ui.extends(View,"ObjectCollection")
local unselect, select
function ObjectCollection.new(nRow,nCol,x,y,width,height)
local self = ObjectCollection.newObject(x,y,width,height)
self.nRow = nRow
self.nCol = nCol
self.q = nRow*nCol
self.borderColor = {0,0,0,0}
return self
end
function ObjectCollection:prepareButtons(images,target)
self.pages = {{}}
local lastPage = self.pages[#self.pages]
local q
local ew = self.width/self.nCol
local eh = ew
--local eh = self.height/self.nRow
for i,v in pairs(images) do
q = #lastPage
if q>=self.q then
lastPage = {}
table.insert(self.pages,lastPage)
q=0
end
--print(q, self.nRow, self.nCol)
local b = Button.new(5+(q%self.nCol)*ew,5+math.floor((q+self.q*(#self.pages-1))/self.nCol)*eh,ew-10,eh-10)
b.image = v
b.id = i
b.borderColor = {150,150,150}
b.borderWidth = 2
b:addTarget(function (button)
if self.selected then
local s = self.selected
unselect(self)
if s~=button then
select(self,button)
end
else
select(self,button)
end
target(button)
end)
table.insert(lastPage,b)
end
self.content = {width = ew*self.nCol, height = eh*((#self.pages-1)*self.nRow+math.floor(#lastPage/self.nCol))}
self.point = 0
self.contentView = View.new(0,0,self.content.width,self.content.height)
self.contentView.borderColor = {0,0,255}
self:addSubView(self.contentView)
--
for i,v in ipairs(self.pages) do
for j,w in ipairs(v) do
self.contentView:addSubView(w)
end
end
end
function ObjectCollection:cancelSelection()
unselect(self)
end
function unselect(self)
self.selected.borderColor = {150,150,150}
self.selected = nil
end
function select(self,but)
self.selected = but
self.selected:bringToFront()
self.selected.borderColor = {255,0,0}
end
function ObjectCollection:target(button)
end
function ObjectCollection:mousemoved(x,y,dx,dy)
--self:super_mousemoved(x-self.x,y-self.y,dx,dy)
self:super_mousemoved(x,y,dx,dy)
--if self:containsPoint(x,y) then
if love.mouse.isDown(1) then
self:scroll(1.5*dy)
end
--end
end
function ObjectCollection:wheelmoved(dx,dy,x,y)
if self:containsPoint(x,y) then
self:scroll(10*dy)
end
end
function ObjectCollection:scroll(v)
self.point = math.min(math.max(self.point+v,self.height-self.content.height),0)
self.contentView.y = self.point
end
return ObjectCollection
|
#! /usr/local/bin/lua
-----------------------------------------------------------------------------
-- Copyright (c) 2013, Benjamin Heath (benjamin.joel.heath@gmail.com)
-- All rights reserved.
--
-- Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
--
-- Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
-- Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
--
--THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
-- Famml
-- A program to convert MML to 6502 assembly that is compatible with Shiru's FamiTone and ca65.
-- FamiTone is a public domain audio driver for NES development.
--
-- For more information on MML, see http://en.wikipedia.org/wiki/Music_Macro_Language
-- Also see http://www.nullsleep.com/treasure/mck_guide/
-- For more information on 6502 assembly, see http://www.atariarchives.org/mlb/
-- For more information on FamiTone, see its announcement in the nesdev forums at http://forums.nesdev.com/viewtopic.php?t=7329
-- Also see Shiru's tutorial and Chase game, http://shiru.untergrund.net/articles/programming_nes_games_in_c.htm
-- For more information on ca65, see http://www.cc65.org
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
-- For reference, the following is copied from FamiTone's "formats.txt" by Shiru
--
-- Envelope format:
--
-- <127 is a number of repeats of previous output value
-- 127 is end of an envelope, next byte is new offset in envelope
-- 128..255 is output value + 192 (it is in -64..63 range)
--
-- Envelopes can't be longer than 255 bytes
--
--
-- Stream format:
--
-- %00nnnnnn is a note (0..59 are octaves 1-5, 63 note stop)
-- %01iiiiii is an instrument number (0 is default, silence)
-- %10rrrrrr is a empty rows (up to 63)
-- %11eeeeee is a special tag or effect
-- eeeeee $01..19 speed
-- %11111110 is end of the stream, two next bytes are new pointer
-- %11111111 is a reference (next two bytes of absolute address, and number of rows)
--
-- No octaves on Noise channel, it is always 0..15; no instruments and octaves on DPCM channel, it is always one octave
--
--
-- Sound effect format:
--
-- <16 is a remapped register number followed by a byte of data
-- >=16 is a number of frames to skip before reading next block of data - 16 (16 if next frame is not empty)
-- 255 is end of the effect
--
-- Sound effect data can't be longer than 255 bytes
--
-- Registers are remapped:
--
-- $4000 00
-- $4002 01
-- $4003 02
-- $4004 03
-- $4006 04
-- $4007 05
-- $4008 06
-- $400a 07
-- $400b 08
-- $400c 09
-- $400e 0a
--
--
-- RAM usage:
--
-- $00 frame counter, used to count time between rows
-- $01 current song speed
-- $02 instruments offset LSB
-- $03 instruments offset MSB
-- $04 previous MSB of Pulse 1
-- $05 previous MSB of Pulse 2
--
-- $06 channel 1 repeat counter (counts empty rows)
-- $07 channel 1 current note
-- $08 channel 1 current instrument
-- $09 channel 1 current duty
-- $0a channel 1 pointer LSB
-- $0b channel 1 pointer MSB
-- $0c channel 1 return LSB
-- $0d channel 1 return MSB
-- $0e channel 1 reference length counter (counts rows before return)
--
-- $0f channel 2 repeat counter
-- $10 channel 2 current note
-- $11 channel 2 current instrument
-- $12 channel 2 current duty
-- $13 channel 2 pointer LSB
-- $14 channel 2 pointer MSB
-- $15 channel 2 return LSB
-- $16 channel 2 return MSB
-- $17 channel 2 reference length counter
--
-- $18 channel 3 repeat counter
-- $19 channel 3 current note
-- $1a channel 3 current instrument
-- $1b channel 3 current duty
-- $1c channel 3 pointer LSB
-- $1d channel 3 pointer MSB
-- $1e channel 3 return LSB
-- $1f channel 3 return MSB
-- $20 channel 3 reference length counter
--
-- $21 channel 4 repeat counter
-- $22 channel 4 current note
-- $23 channel 4 current instrument
-- $24 channel 4 current duty
-- $25 channel 4 pointer LSB
-- $26 channel 4 pointer MSB
-- $27 channel 4 return LSB
-- $28 channel 4 return MSB
-- $29 channel 4 reference length counter
--
-- $2a channel 5 repeat counter
-- $2b channel 5 current note
-- $2c channel 5 current instrument
-- $2d channel 5 current duty
-- $2e channel 5 pointer LSB
-- $2f channel 5 pointer MSB
-- $30 channel 5 return LSB
-- $31 channel 5 return MSB
-- $32 channel 5 reference length counter
--
-- $33 channel 1 volume envelope output
-- $34 channel 1 volume envelope repeat counter
-- $35 channel 1 volume envelope address LSB
-- $36 channel 1 volume envelope address MSB
-- $37 channel 1 volume envelope pointer
-- $38 channel 1 arpeggio envelope output
-- $39 channel 1 arpeggio envelope repeat counter
-- $3a channel 1 arpeggio envelope address LSB
-- $3b channel 1 arpeggio envelope address MSB
-- $3c channel 1 arpeggio envelope pointer
-- $3d channel 1 pitch envelope output
-- $3e channel 1 pitch envelope repeat counter
-- $3f channel 1 pitch envelope address LSB
-- $40 channel 1 pitch envelope address MSB
-- $41 channel 1 pitch envelope pointer
--
-- $42 channel 2 volume envelope output
-- $43 channel 2 volume envelope repeat counter
-- $44 channel 2 volume envelope address LSB
-- $45 channel 2 volume envelope address MSB
-- $46 channel 2 volume envelope pointer
-- $47 channel 2 arpeggio envelope output
-- $48 channel 2 arpeggio envelope repeat counter
-- $49 channel 2 arpeggio envelope address LSB
-- $4a channel 2 arpeggio envelope address MSB
-- $4b channel 2 arpeggio envelope pointer
-- $4c channel 2 pitch envelope output
-- $4d channel 2 pitch envelope repeat counter
-- $4e channel 2 pitch envelope address LSB
-- $4f channel 2 pitch envelope address MSB
-- $50 channel 2 pitch envelope pointer
--
-- $51 channel 3 volume envelope output
-- $52 channel 3 volume envelope repeat counter
-- $53 channel 3 volume envelope address LSB
-- $54 channel 3 volume envelope address MSB
-- $55 channel 3 volume envelope pointer
-- $56 channel 3 arpeggio envelope output
-- $57 channel 3 arpeggio envelope repeat counter
-- $58 channel 3 arpeggio envelope address LSB
-- $59 channel 3 arpeggio envelope address MSB
-- $5a channel 3 arpeggio envelope pointer
-- $5b channel 3 pitch envelope output
-- $5c channel 3 pitch envelope repeat counter
-- $5d channel 3 pitch envelope address LSB
-- $5e channel 3 pitch envelope address MSB
-- $5f channel 3 pitch envelope pointer
--
-- $60 channel 4 volume envelope output
-- $61 channel 4 volume envelope repeat counter
-- $62 channel 4 volume envelope address LSB
-- $63 channel 4 volume envelope address MSB
-- $64 channel 4 volume envelope pointer
-- $65 channel 4 arpeggio envelope output
-- $66 channel 4 arpeggio envelope repeat counter
-- $67 channel 4 arpeggio envelope address LSB
-- $68 channel 4 arpeggio envelope address MSB
-- $69 channel 4 arpeggio envelope pointer
--
-- $6a DPCM table pointer LSB
-- $6b DPCM table pointer LSB
-- $6c DPCM sound effect active
-- $6d Sound effects data LSB
-- $6e Sound effects data MSB
-- $6f PAL adjust counter
--
-- $70 Main output buffer (11 bytes)
--
-- $7c Sound effect stream 1 repeat counter
-- $7d Sound effect stream 1 pointer LSB
-- $7e Sound effect stream 1 pointer MSB
-- $7f Sound effect stream 1 offset
-- $80 Sound effect stream 1 output buffer (11 bytes)
--
-- $8b Sound effect stream 2 repeat counter
-- $8c Sound effect stream 2 pointer LSB
-- $8d Sound effect stream 2 pointer MSB
-- $8e Sound effect stream 2 offset
-- $8f Sound effect stream 2 output buffer (11 bytes)
--
-- $9a Sound effect stream 3 repeat counter
-- $9b Sound effect stream 3 pointer LSB
-- $9c Sound effect stream 3 pointer MSB
-- $9d Sound effect stream 3 offset
-- $9e Sound effect stream 3 output buffer (11 bytes)
--
-- $a9 Sound effect stream 4 repeat counter
-- $aa Sound effect stream 4 pointer LSB
-- $ab Sound effect stream 4 pointer MSB
-- $ac Sound effect stream 4 offset
-- $ad Sound effect stream 4 output buffer (11 bytes)
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
-- For reference, the following is copied from the level music for Shiru's sample NES game, Chase.
-- mus_level_module:
-- .word @chn0,@chn1,@chn2,@chn3,@chn4,music_instruments
-- .byte $03
--
-- @chn0:
-- @chn0_0:
-- ; $47 = instrument #7
-- ; $18 = B, second octave
-- ; $80 = empty row
-- ; $1a = C#, third octave
-- ; $8a = 10 empty rows
-- .byte $47,$18,$80,$18,$80,$1a,$8a
-- @chn0_loop:
-- @chn0_1:
-- ; $8f = 15 empty rows
-- .byte $8f
-- ; $fe = end
-- .byte $fe
-- .word @chn0_loop
--
-- @chn1:
-- @chn1_0:
-- .byte $48,$18,$80,$18,$80,$1a,$8a
-- @chn1_loop:
-- @chn1_1:
-- .byte $8f
-- .byte $fe
-- .word @chn1_loop
--
-- @chn2:
-- @chn2_0:
-- .byte $41,$18,$80,$18,$80,$49,$18,$41,$1a,$81,$3f,$86
-- @chn2_loop:
-- @chn2_1:
-- .byte $8f
-- .byte $fe
-- .word @chn2_loop
--
-- @chn3:
-- @chn3_0:
-- .byte $46,$0f,$80,$0f,$80,$49,$0b,$80,$42,$0f,$88
-- @chn3_loop:
-- @chn3_1:
-- .byte $8f
-- .byte $fe
-- .word @chn3_loop
--
-- @chn4:
-- @chn4_0:
-- .byte $8f
-- @chn4_loop:
-- @chn4_1:
-- .byte $8f
-- .byte $fe
-- .word @chn4_loop
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
-- And finally, a sample sound effect from Shiru's game, Chase.
-- sfx0:
-- .byte $00,$7f
-- .byte $01,$ab
-- .byte $02,$01
-- .byte $13
-- .byte $01,$3f
-- .byte $13
-- .byte $01,$1c
-- .byte $13
-- .byte $01,$d5
-- .byte $02,$00
-- .byte $13
-- .byte $01,$9f
-- .byte $13
-- .byte $01,$8e
-- .byte $13
-- .byte $00,$74
-- .byte $01,$ab
-- .byte $02,$01
-- .byte $13
-- .byte $01,$3f
-- .byte $13
-- .byte $01,$1c
-- .byte $13
-- .byte $01,$d5
-- .byte $02,$00
-- .byte $13
-- .byte $01,$9f
-- .byte $13
-- .byte $01,$8e
-- .byte $13
-- .byte $00,$71
-- .byte $01,$ab
-- .byte $02,$01
-- .byte $13
-- .byte $01,$3f
-- .byte $13
-- .byte $01,$1c
-- .byte $13
-- .byte $01,$d5
-- .byte $02,$00
-- .byte $13
-- .byte $01,$9f
-- .byte $13
-- .byte $01,$8e
-- .byte $13
-- .byte $00,$30
-- .byte $ff
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
-- The idea for this program, famml, is to take mml from either stdin or a text file,
-- and translate it to 6502 assembly which is compatible with FamiTone as well as the assembler, ca65.
-- However, it need not be specific to ca65. Allowance can easily be made for other assemblers.
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
-- config_ca65_famitone()
-- Returns an interface for output to ca65 and FamiTone
-----------------------------------------------------------------------------
local function config_ca65_famitone()
local asm_comment="; "
local asm_byte="\t.byte "
local asm_word="\t.word "
local asm_label=function(name) return name..":" end
local asm_clabel=function(name) return "@"..name..":" end
-----------------------------------------------------------------------------
-- asm_assembly()
-- Returns an interface for adding to and writing the assembly output
-----------------------------------------------------------------------------
local function asm_assembly()
local asm = {
__code = {},
__code_size = 0,
-----------------------------------------------------------------------------
-- asm:add_cheap_label(name)
-----------------------------------------------------------------------------
add_cheap_label = function(asm, name)
local clabel = asm.__code[#asm.__code].clabel
if string.len(clabel) > 0 then
clabel = asm_clabel(name)
else
clabel = asm_clabel(name).."\n"..clabel
end
asm.__code[#asm.__code].clabel = clabel
end,
-----------------------------------------------------------------------------
-- asm:add_comment(comment)
-----------------------------------------------------------------------------
add_comment = function(asm, comment)
asm.__code[#asm.__code].comment = asm_comment..comment
end,
-----------------------------------------------------------------------------
-- asm:add_label(name)
-----------------------------------------------------------------------------
add_label = function(asm, name)
local label = asm.__code[#asm.__code].label
if string.len(label) > 0 then
label = asm_label(name).."\n"..label
else
label = asm_label(name)
end
asm.__code[#asm.__code].label = label
end,
-----------------------------------------------------------------------------
-- asm:add_line()
-----------------------------------------------------------------------------
add_line = function(asm)
row = {label="",clabel="",command="",args="",comment="",nargs=0,maxargs=10,}
table.insert(asm.__code, row)
end,
-----------------------------------------------------------------------------
-- asm:place_byte(n)
-- Use the assembler's byte directive, such as .byte or db
-----------------------------------------------------------------------------
place_byte = function(asm, n)
local line = asm.__code[#asm.__code]
if line.command == "" then
line.command = asm_byte
if type(n) == "number" then
line.args = line.args.."$"..string.format("%x",n)
elseif type(n) == "string" then
line.args = line.args.."$"..n
end
goto code_size
elseif line.command == asm_byte then
if type(n) == "number" then
line.args = line.args..", $"..string.format("%x",n)
elseif type(n) == "string" then
line.args = line.args..", $"..n
end
goto code_size
else
asm:add_line()
return asm:place_byte(n)
end
::code_size::
asm.__code_size = asm.__code_size + 1
line.nargs = line.nargs+1
if line.nargs == line.maxargs then
asm:add_line()
line.nargs = 0
end
end,
-----------------------------------------------------------------------------
-- asm:size()
-- Return the number of bytes
-----------------------------------------------------------------------------
size = function(asm)
return asm.__code_size
end,
-----------------------------------------------------------------------------
-- asm:write()
-- Returns a string with all the lines of code, ready to print.
-----------------------------------------------------------------------------
write = function(asm)
local s = ""
for k,v in pairs(asm.__code) do
local list = {v.label, v.clabel, v.command, v.args, v.comment}
for k,v in pairs(list) do
if string.len(v) > 0 then
s = s..v
if k == 3 or k == 4 then s = s.."\t" end
end
end
s = s .. "\n"
end
return s
end,
set_instrument = function(asm, n)
asm:place_byte(n + 64)
end,
} --asm = { stuff }
asm:add_line()
return asm
end --asm_assembly()
return {
asm = {
byte = asm_byte,
word = asm_word,
comment = asm_comment,
clabel = asm_clabel,
label = asm_label,
assembly = asm_assembly,
},
driver = {
-----------------------------------------------------------------------------
-- check_envelope(asm)
-- Validate this code before calling asm:write()
-----------------------------------------------------------------------------
check_envelope = function(assembly)
if assembly:size() > 255 then
return "FamiTone allows envelopes up to 255 bytes."
end
end,
-----------------------------------------------------------------------------
-- envelope_entry(num)
-- Given a numeric envelope entry (num), return a string formatted for this driver
-----------------------------------------------------------------------------
envelope_entry = function(num) return string.format("%x", (num+192)) end,
-----------------------------------------------------------------------------
-- envelope_end()
-- Return this audio driver's indicator for the end of an envelope
-----------------------------------------------------------------------------
envelope_end = function() return string.format("%x", 127) end,
rest = 63,
} --driver
}
end
-----------------------------------------------------------------------------
-- create_context()
-- A context has a configuration and a method to translate input to assembly code.
-----------------------------------------------------------------------------
local function create_context(config)
function validate_config(config)
return config
end
return {
config = validate_config(config),
validate_config = validate_config,
input = {},
output = "",
outfile = io.stdout,
assemblies = {},
-----------------------------------------------------------------------------
-- translate(context)
-- Reads from context.input and writes to context.output
-- Returns context,err
-----------------------------------------------------------------------------
translate = function(context)
-----------------------------------------------------------------------------
-- Validate and process the input as a Lua table with proper members
-----------------------------------------------------------------------------
local function validate_input(context)
-----------------------------------------------------------------------------
-- Capture commands from a channel
-----------------------------------------------------------------------------
local function capture_commands(context, channel)
local function docommand(context, command, asm)
local notes = {c=0, d=2, e=4, f=5, g=7, a=9, b=11}
local n = 0
local notelen = channel.notelen
for note in string.gmatch(command, "<*>*[cdefgab%-]#*%.*%d*") do
for octup in string.gmatch(note, ">") do
channel.octave = channel.octave+1
end
for octdown in string.gmatch(note, "<") do
channel.octave = channel.octave-1
end
for sharp in string.gmatch(command, "[cdfga]#") do
n = n+1
end
for sharperror in string.gmatch(command, "[be]#") do
error("There is no B# or E#.")
end
for len in string.gmatch(note, "[cdefgab](%d*)") do
notelen = tonumber(len)
end
for rest in string.gmatch(note, "%-") do
goto onrest
end
note,_ = string.gsub(note, "[<>#%.%d]", "") -- strip out the extra characters
n = 12 * channel.octave + notes[note]
break
::onrest::
n = context.config.driver.rest
end
asm:place_byte(n)
return asm
end
local function getcommands(context, channel)
local asm = context.config.asm.assembly()
asm:set_instrument(channel.instrument)
table.insert(context.assemblies, asm)
capture = "(@*>*<*[ivabcdefg%-]#*%.*%d*)"
asm = context.config.asm.assembly()
for command in string.gmatch(channel.commands, capture) do
asm = docommand(context, command, asm)
end
table.insert(context.assemblies, asm)
end
getcommands(context, channel)
end -- capture_commands()
assert(type(context) == "table", "context should be a table.")
assert(type(context.input) == "table", "context.input should be a table.")
if context.input.title then
local err = "title should be a string."
assert(type(context.input.title) == "string", err)
-- Add a label for this assembly module based on title
local asm = context.config.asm.assembly()
local s,_ = string.gsub(context.input.title, "%s+", "_")
-- TODO: Delete all punctuation from s
asm:add_label(s)
table.insert(context.assemblies, asm)
else
-- No title? Go with "fammlNNNNNNN"
local asm = context.config.asm.assembly()
math.randomseed(os.time())
asm:add_label("famml"..tostring(math.random(0,1000000)))
table.insert(context.assemblies, asm)
end
if context.input.composer then
local err = "composer should be a string."
assert(type(context.input.composer) == "string", err)
end
if context.input.programmer then
local err = "programmer should be a string."
assert(type(context.input.programmer) == "string", err)
end
if context.input.audiotype then
local atype = context.input.audiotype
local err = "audiotype should be \"music\" or \"sound\"."
assert(atype == "music" or atype == "sound", err)
else
context.input.audiotype = "music"
end
if context.input.channels then
local err = "channels should be a table."
assert(type(context.input.channels) == "table", err)
-----------------------------------------------------------------------------
-- validate_channel()
-----------------------------------------------------------------------------
local function validate_channel(key, channel)
local err = "channel '"..tostring(key).."' should be a table."
assert(type(channel) == "table", err)
if channel.octave then
local err = "octave should be a number."
assert(type(channel.octave) == "number", err)
-- TODO: Shouldn't octave be validated by config?
local err = "octave should be >= 0."
assert(channel.octave >= 0, err)
else
channel.octave = 4
end
if channel.notelen then
local err = "notelen should be a number."
assert(type(channel.notelen) == "number", err)
-- TODO: Shouldn't notelen be validated by config?
else
channel.notelen = 4
end
if channel.instrument then
local err = "instrument should be a number."
assert(type(channel.instrument) == "number", err)
else
channel.instrument = 1
end
if channel.commands then
local err = "commands should be a string."
assert(type(channel.commands) == "string", err)
channel.commands = string.lower(channel.commands)
capture_commands(context, channel)
end
end --validate_channel()
if context.input.audiotype == "music" then
for k,v in pairs(context.input.channels) do
validate_channel(k,v)
end
elseif context.input.audiotype == "sound" then
validate_channel(1, context.input.channels[1])
end
end
return context
end -- validate_input()
-----------------------------------------------------------------------------
-- Write assembly to output string
-----------------------------------------------------------------------------
local function output_assembly(context)
for k,asm in pairs(context.assemblies) do
context.output = context.output..asm:write()
end
return context
end --output_assembly()
validate_input(context)
output_assembly(context)
return context
end, --translate()
}
end --create_context()
-----------------------------------------------------------------------------
-- help()
-- Just show some friendly information about the program. :)
-----------------------------------------------------------------------------
local function help()
print("Create chiptune music for 8-bit systems with Lua.\n")
print("Usage: famml input.lua -c config.lua -o output")
print("Pipe usage: cat input.lua | famml -p -c config.lua -o output")
print(" -c Load a configuration script")
print(" -h See this help screen")
print(" -o Redirect output to a file (default: stdout)")
print(" -p Accept input from a pipe")
end
-----------------------------------------------------------------------------
-- cli()
-- cli() handles the command-line interface
-----------------------------------------------------------------------------
local function cli()
-----------------------------------------------------------------------------
-- checkparams(context)
-- checkparams validates the parameters in arg
-----------------------------------------------------------------------------
function checkparams(context)
for i,v in pairs(arg) do
if v == "-h" then help() return end
if v == "-o" then
if i == #arg then
error("Output file expected after -o")
elseif v == arg[1] then
error("Cannot read from and write to the same file.")
end
end
end
return context
end
-----------------------------------------------------------------------------
-- Process the parameters, including pipe and interactive mode
-----------------------------------------------------------------------------
function readinput(context)
for i,v in pairs(arg) do
if v == "-p" then
-- Pipe mode!
context.input = load(io.read("*all"))
context.input = context.input()
elseif v == "-o" then
if arg[i+1] then
context.outfile = io.open(arg[i+1], "w")
assert(context.outfile, "Could not open output file '"..arg[i+1].."'")
end
elseif v == "-c" then
if arg[i+1] then
context.config = context.validate_config(dofile(arg[i+1]))
end
else
-- All other options are checked. If this far, then arg[1] is input file.
if i == 1 then
local f = io.open(arg[1])
assert(f,"Could not open input file '"..arg[1].."'. Expected input file as first argument.")
context.input = load(f:read("*all"))
f:close()
context.input = context.input()
end
end
end
return context
end
-----------------------------------------------------------------------------
-- Now to the meat of the function
-----------------------------------------------------------------------------
context = create_context(config_ca65_famitone())
if not checkparams(context) then return end
readinput(context)
context:translate()
context.outfile:write(context.output)
if not context.outfile == io.stdout then context.outfile:close() end
end
-----------------------------------------------------------------------------
-- If this script is loaded from the command line without parameters, it should just help().
-- If it is run from dofile, it should return an interface to famml
-----------------------------------------------------------------------------
if arg == nil then
return {
config_ca65_famitone=config_ca65_famitone,
create_context=create_context,
}
elseif #arg <= 0 then
return help()
else
return cli()
end
|
local Native = require('lib.stdlib.native')
---@class LeaderBoard : Agent
local LeaderBoard = class('LeaderBoard', require('lib.stdlib.oop.agent'))
---destructor
---@return void
function LeaderBoard:destructor()
--@debug@
checkobject(self, LeaderBoard, 'destructor', 'self')
--@end-debug@
return Native.DestroyLeaderboard(getUd(self))
end
---<**_DEPRECATED_**> destroy
---@return void
function LeaderBoard:destroy()
--@debug@
deprecated('LeaderBoard.destroy', 'LeaderBoard.delete')
--@end-debug@
return self:delete()
end
---<static> create
---@return LeaderBoard
function LeaderBoard:create()
return LeaderBoard:fromUd(Native.CreateLeaderboard())
end
---display
---@param show boolean
---@return void
function LeaderBoard:display(show)
--@debug@
checkobject(self, LeaderBoard, 'display', 'self')
checktype(show, 'boolean', 'display', 1)
--@end-debug@
return Native.LeaderboardDisplay(getUd(self), show)
end
---isDisplayed
---@return boolean
function LeaderBoard:isDisplayed()
--@debug@
checkobject(self, LeaderBoard, 'isDisplayed', 'self')
--@end-debug@
return Native.IsLeaderboardDisplayed(getUd(self))
end
---getItemCount
---@return integer
function LeaderBoard:getItemCount()
--@debug@
checkobject(self, LeaderBoard, 'getItemCount', 'self')
--@end-debug@
return Native.LeaderboardGetItemCount(getUd(self))
end
---setSizeByItemCount
---@param count integer
---@return void
function LeaderBoard:setSizeByItemCount(count)
--@debug@
checkobject(self, LeaderBoard, 'setSizeByItemCount', 'self')
checktype(count, 'integer', 'setSizeByItemCount', 1)
--@end-debug@
return Native.LeaderboardSetSizeByItemCount(getUd(self), count)
end
---addItem
---@param label string
---@param value integer
---@param p Player
---@return void
function LeaderBoard:addItem(label, value, p)
--@debug@
checkobject(self, LeaderBoard, 'addItem', 'self')
checktype(label, 'string', 'addItem', 1)
checktype(value, 'integer', 'addItem', 2)
checkobject(p, require('lib.stdlib.oop.player'), 'addItem', 3)
--@end-debug@
return Native.LeaderboardAddItem(getUd(self), label, value, getUd(p))
end
---removeItem
---@param index integer
---@return void
function LeaderBoard:removeItem(index)
--@debug@
checkobject(self, LeaderBoard, 'removeItem', 'self')
checktype(index, 'integer', 'removeItem', 1)
--@end-debug@
return Native.LeaderboardRemoveItem(getUd(self), index)
end
---removePlayerItem
---@param p Player
---@return void
function LeaderBoard:removePlayerItem(p)
--@debug@
checkobject(self, LeaderBoard, 'removePlayerItem', 'self')
checkobject(p, require('lib.stdlib.oop.player'), 'removePlayerItem', 1)
--@end-debug@
return Native.LeaderboardRemovePlayerItem(getUd(self), getUd(p))
end
---clear
---@return void
function LeaderBoard:clear()
--@debug@
checkobject(self, LeaderBoard, 'clear', 'self')
--@end-debug@
return Native.LeaderboardClear(getUd(self))
end
---sortItemsByValue
---@param ascending boolean
---@return void
function LeaderBoard:sortItemsByValue(ascending)
--@debug@
checkobject(self, LeaderBoard, 'sortItemsByValue', 'self')
checktype(ascending, 'boolean', 'sortItemsByValue', 1)
--@end-debug@
return Native.LeaderboardSortItemsByValue(getUd(self), ascending)
end
---sortItemsByPlayer
---@param ascending boolean
---@return void
function LeaderBoard:sortItemsByPlayer(ascending)
--@debug@
checkobject(self, LeaderBoard, 'sortItemsByPlayer', 'self')
checktype(ascending, 'boolean', 'sortItemsByPlayer', 1)
--@end-debug@
return Native.LeaderboardSortItemsByPlayer(getUd(self), ascending)
end
---sortItemsByLabel
---@param ascending boolean
---@return void
function LeaderBoard:sortItemsByLabel(ascending)
--@debug@
checkobject(self, LeaderBoard, 'sortItemsByLabel', 'self')
checktype(ascending, 'boolean', 'sortItemsByLabel', 1)
--@end-debug@
return Native.LeaderboardSortItemsByLabel(getUd(self), ascending)
end
---hasPlayerItem
---@param p Player
---@return boolean
function LeaderBoard:hasPlayerItem(p)
--@debug@
checkobject(self, LeaderBoard, 'hasPlayerItem', 'self')
checkobject(p, require('lib.stdlib.oop.player'), 'hasPlayerItem', 1)
--@end-debug@
return Native.LeaderboardHasPlayerItem(getUd(self), getUd(p))
end
---getPlayerIndex
---@param p Player
---@return integer
function LeaderBoard:getPlayerIndex(p)
--@debug@
checkobject(self, LeaderBoard, 'getPlayerIndex', 'self')
checkobject(p, require('lib.stdlib.oop.player'), 'getPlayerIndex', 1)
--@end-debug@
return Native.LeaderboardGetPlayerIndex(getUd(self), getUd(p))
end
---setLabel
---@param label string
---@return void
function LeaderBoard:setLabel(label)
--@debug@
checkobject(self, LeaderBoard, 'setLabel', 'self')
checktype(label, 'string', 'setLabel', 1)
--@end-debug@
return Native.LeaderboardSetLabel(getUd(self), label)
end
---getLabelText
---@return string
function LeaderBoard:getLabelText()
--@debug@
checkobject(self, LeaderBoard, 'getLabelText', 'self')
--@end-debug@
return Native.LeaderboardGetLabelText(getUd(self))
end
---setLabelColor
---@param red integer
---@param green integer
---@param blue integer
---@param alpha integer
---@return void
function LeaderBoard:setLabelColor(red, green, blue, alpha)
--@debug@
checkobject(self, LeaderBoard, 'setLabelColor', 'self')
checktype(red, 'integer', 'setLabelColor', 1)
checktype(green, 'integer', 'setLabelColor', 2)
checktype(blue, 'integer', 'setLabelColor', 3)
checktype(alpha, 'integer', 'setLabelColor', 4)
--@end-debug@
return Native.LeaderboardSetLabelColor(getUd(self), red, green, blue, alpha)
end
---setValueColor
---@param red integer
---@param green integer
---@param blue integer
---@param alpha integer
---@return void
function LeaderBoard:setValueColor(red, green, blue, alpha)
--@debug@
checkobject(self, LeaderBoard, 'setValueColor', 'self')
checktype(red, 'integer', 'setValueColor', 1)
checktype(green, 'integer', 'setValueColor', 2)
checktype(blue, 'integer', 'setValueColor', 3)
checktype(alpha, 'integer', 'setValueColor', 4)
--@end-debug@
return Native.LeaderboardSetValueColor(getUd(self), red, green, blue, alpha)
end
---setStyle
---@param showLabel boolean
---@param showNames boolean
---@param showValues boolean
---@param showIcons boolean
---@return void
function LeaderBoard:setStyle(showLabel, showNames, showValues, showIcons)
--@debug@
checkobject(self, LeaderBoard, 'setStyle', 'self')
checktype(showLabel, 'boolean', 'setStyle', 1)
checktype(showNames, 'boolean', 'setStyle', 2)
checktype(showValues, 'boolean', 'setStyle', 3)
checktype(showIcons, 'boolean', 'setStyle', 4)
--@end-debug@
return Native.LeaderboardSetStyle(getUd(self), showLabel, showNames, showValues, showIcons)
end
---setItemValue
---@param item integer
---@param val integer
---@return void
function LeaderBoard:setItemValue(item, val)
--@debug@
checkobject(self, LeaderBoard, 'setItemValue', 'self')
checktype(item, 'integer', 'setItemValue', 1)
checktype(val, 'integer', 'setItemValue', 2)
--@end-debug@
return Native.LeaderboardSetItemValue(getUd(self), item, val)
end
---setItemLabel
---@param item integer
---@param val string
---@return void
function LeaderBoard:setItemLabel(item, val)
--@debug@
checkobject(self, LeaderBoard, 'setItemLabel', 'self')
checktype(item, 'integer', 'setItemLabel', 1)
checktype(val, 'string', 'setItemLabel', 2)
--@end-debug@
return Native.LeaderboardSetItemLabel(getUd(self), item, val)
end
---setItemStyle
---@param item integer
---@param showLabel boolean
---@param showValue boolean
---@param showIcon boolean
---@return void
function LeaderBoard:setItemStyle(item, showLabel, showValue, showIcon)
--@debug@
checkobject(self, LeaderBoard, 'setItemStyle', 'self')
checktype(item, 'integer', 'setItemStyle', 1)
checktype(showLabel, 'boolean', 'setItemStyle', 2)
checktype(showValue, 'boolean', 'setItemStyle', 3)
checktype(showIcon, 'boolean', 'setItemStyle', 4)
--@end-debug@
return Native.LeaderboardSetItemStyle(getUd(self), item, showLabel, showValue, showIcon)
end
---setItemLabelColor
---@param item integer
---@param red integer
---@param green integer
---@param blue integer
---@param alpha integer
---@return void
function LeaderBoard:setItemLabelColor(item, red, green, blue, alpha)
--@debug@
checkobject(self, LeaderBoard, 'setItemLabelColor', 'self')
checktype(item, 'integer', 'setItemLabelColor', 1)
checktype(red, 'integer', 'setItemLabelColor', 2)
checktype(green, 'integer', 'setItemLabelColor', 3)
checktype(blue, 'integer', 'setItemLabelColor', 4)
checktype(alpha, 'integer', 'setItemLabelColor', 5)
--@end-debug@
return Native.LeaderboardSetItemLabelColor(getUd(self), item, red, green, blue, alpha)
end
---setItemValueColor
---@param item integer
---@param red integer
---@param green integer
---@param blue integer
---@param alpha integer
---@return void
function LeaderBoard:setItemValueColor(item, red, green, blue, alpha)
--@debug@
checkobject(self, LeaderBoard, 'setItemValueColor', 'self')
checktype(item, 'integer', 'setItemValueColor', 1)
checktype(red, 'integer', 'setItemValueColor', 2)
checktype(green, 'integer', 'setItemValueColor', 3)
checktype(blue, 'integer', 'setItemValueColor', 4)
checktype(alpha, 'integer', 'setItemValueColor', 5)
--@end-debug@
return Native.LeaderboardSetItemValueColor(getUd(self), item, red, green, blue, alpha)
end
return LeaderBoard
|
--[[
Which of the following are valid numerals? What are their values?
.0e12
.e12
0.0e
0x12
0xABFG
0xA
FFFF
0xFFFFFFFF
0x
0x1P10
0.1e1
0x01.1
]]
local numerals = {
".0e12",
".e12",
"0.0e",
"0x12",
"0xABFG",
"0xA",
"FFFF",
"0xFFFFFFFF",
"0x",
"0x1P10",
"0.1e1",
"0x0.1p1"
}
for _, value in pairs(numerals) do
local asNumber = tonumber(value)
if asNumber then
print(value .. " => " .. tostring(asNumber))
else
print(value .. " is not a valid numeral")
end
end
--[[
.0e12 => 0
.e12 is not a valid numeral
0.0e is not a valid numeral
0x12 => 18
0xABFG is not a valid numeral
0xA => 10
FFFF is not a valid numeral
0xFFFFFFFF => 4294967295
0x is not a valid numeral
0x1P10 => 1024
0.1e1 => 1
0x0.1p1 => 0.125
]]
|
-- Toggle Hammerspoon Console
hs.hotkey.bind({"cmd", "alt", "ctrl"}, 'y', hs.toggleConsole)
|
bj_PI = 3.14159265358979323846
bj_E = 2.71828182845904523536
bj_CELLWIDTH = 128.0
bj_CLIFFHEIGHT = 128.0
bj_UNIT_FACING = 270.0
bj_RADTODEG = 180.0 / bj_PI
bj_DEGTORAD = bj_PI / 180.0
bj_TEXT_DELAY_QUEST = 20.00
bj_TEXT_DELAY_QUESTUPDATE = 20.00
bj_TEXT_DELAY_QUESTDONE = 20.00
bj_TEXT_DELAY_QUESTFAILED = 20.00
bj_TEXT_DELAY_QUESTREQUIREMENT = 20.00
bj_TEXT_DELAY_MISSIONFAILED = 20.00
bj_TEXT_DELAY_ALWAYSHINT = 12.00
bj_TEXT_DELAY_HINT = 12.00
bj_TEXT_DELAY_SECRET = 10.00
bj_TEXT_DELAY_UNITACQUIRED = 15.00
bj_TEXT_DELAY_UNITAVAILABLE = 10.00
bj_TEXT_DELAY_ITEMACQUIRED = 10.00
bj_TEXT_DELAY_WARNING = 12.00
bj_QUEUE_DELAY_QUEST = 5.00
bj_QUEUE_DELAY_HINT = 5.00
bj_QUEUE_DELAY_SECRET = 3.00
bj_HANDICAP_EASY = 60.00
bj_GAME_STARTED_THRESHOLD = 0.01
bj_WAIT_FOR_COND_MIN_INTERVAL = 0.10
bj_POLLED_WAIT_INTERVAL = 0.10
bj_POLLED_WAIT_SKIP_THRESHOLD = 2.00
bj_MAX_INVENTORY = 6
bj_MAX_PLAYERS = 12
bj_PLAYER_NEUTRAL_VICTIM = 13
bj_PLAYER_NEUTRAL_EXTRA = 14
bj_MAX_PLAYER_SLOTS = 16
bj_MAX_SKELETONS = 25
bj_MAX_STOCK_ITEM_SLOTS = 11
bj_MAX_STOCK_UNIT_SLOTS = 11
bj_MAX_ITEM_LEVEL = 10
bj_TOD_DAWN = 6.00
bj_TOD_DUSK = 18.00
bj_MELEE_STARTING_TOD = 8.00
bj_MELEE_STARTING_GOLD_V0 = 750
bj_MELEE_STARTING_GOLD_V1 = 500
bj_MELEE_STARTING_LUMBER_V0 = 200
bj_MELEE_STARTING_LUMBER_V1 = 150
bj_MELEE_STARTING_HERO_TOKENS = 1
bj_MELEE_HERO_LIMIT = 3
bj_MELEE_HERO_TYPE_LIMIT = 1
bj_MELEE_MINE_SEARCH_RADIUS = 2000
bj_MELEE_CLEAR_UNITS_RADIUS = 1500
bj_MELEE_CRIPPLE_TIMEOUT = 120.00
bj_MELEE_CRIPPLE_MSG_DURATION = 20.00
bj_MELEE_MAX_TWINKED_HEROES_V0 = 3
bj_MELEE_MAX_TWINKED_HEROES_V1 = 1
bj_CREEP_ITEM_DELAY = 0.50
bj_STOCK_RESTOCK_INITIAL_DELAY = 120
bj_STOCK_RESTOCK_INTERVAL = 30
bj_STOCK_MAX_ITERATIONS = 20
bj_MAX_DEST_IN_REGION_EVENTS = 64
bj_CAMERA_MIN_FARZ = 100
bj_CAMERA_DEFAULT_DISTANCE = 1650
bj_CAMERA_DEFAULT_FARZ = 5000
bj_CAMERA_DEFAULT_AOA = 304
bj_CAMERA_DEFAULT_FOV = 70
bj_CAMERA_DEFAULT_ROLL = 0
bj_CAMERA_DEFAULT_ROTATION = 90
bj_RESCUE_PING_TIME = 2.00
bj_NOTHING_SOUND_DURATION = 5.00
bj_TRANSMISSION_PING_TIME = 1.00
bj_TRANSMISSION_IND_RED = 255
bj_TRANSMISSION_IND_BLUE = 255
bj_TRANSMISSION_IND_GREEN = 255
bj_TRANSMISSION_IND_ALPHA = 255
bj_TRANSMISSION_PORT_HANGTIME = 1.50
bj_CINEMODE_INTERFACEFADE = 0.50
bj_CINEMODE_GAMESPEED = MAP_SPEED_NORMAL
bj_CINEMODE_VOLUME_UNITMOVEMENT = 0.40
bj_CINEMODE_VOLUME_UNITSOUNDS = 0.00
bj_CINEMODE_VOLUME_COMBAT = 0.40
bj_CINEMODE_VOLUME_SPELLS = 0.40
bj_CINEMODE_VOLUME_UI = 0.00
bj_CINEMODE_VOLUME_MUSIC = 0.55
bj_CINEMODE_VOLUME_AMBIENTSOUNDS = 1.00
bj_CINEMODE_VOLUME_FIRE = 0.60
bj_SPEECH_VOLUME_UNITMOVEMENT = 0.25
bj_SPEECH_VOLUME_UNITSOUNDS = 0.00
bj_SPEECH_VOLUME_COMBAT = 0.25
bj_SPEECH_VOLUME_SPELLS = 0.25
bj_SPEECH_VOLUME_UI = 0.00
bj_SPEECH_VOLUME_MUSIC = 0.55
bj_SPEECH_VOLUME_AMBIENTSOUNDS = 1.00
bj_SPEECH_VOLUME_FIRE = 0.60
bj_SMARTPAN_TRESHOLD_PAN = 500
bj_SMARTPAN_TRESHOLD_SNAP = 3500
bj_MAX_QUEUED_TRIGGERS = 100
bj_QUEUED_TRIGGER_TIMEOUT = 180.00
bj_CAMPAIGN_INDEX_T = 0
bj_CAMPAIGN_INDEX_H = 1
bj_CAMPAIGN_INDEX_U = 2
bj_CAMPAIGN_INDEX_O = 3
bj_CAMPAIGN_INDEX_N = 4
bj_CAMPAIGN_INDEX_XN = 5
bj_CAMPAIGN_INDEX_XH = 6
bj_CAMPAIGN_INDEX_XU = 7
bj_CAMPAIGN_INDEX_XO = 8
bj_CAMPAIGN_OFFSET_T = 0
bj_CAMPAIGN_OFFSET_H = 1
bj_CAMPAIGN_OFFSET_U = 2
bj_CAMPAIGN_OFFSET_O = 3
bj_CAMPAIGN_OFFSET_N = 4
bj_CAMPAIGN_OFFSET_XN = 0
bj_CAMPAIGN_OFFSET_XH = 1
bj_CAMPAIGN_OFFSET_XU = 2
bj_CAMPAIGN_OFFSET_XO = 3
bj_MISSION_INDEX_T00 = bj_CAMPAIGN_OFFSET_T * 1000 + 0
bj_MISSION_INDEX_T01 = bj_CAMPAIGN_OFFSET_T * 1000 + 1
bj_MISSION_INDEX_H00 = bj_CAMPAIGN_OFFSET_H * 1000 + 0
bj_MISSION_INDEX_H01 = bj_CAMPAIGN_OFFSET_H * 1000 + 1
bj_MISSION_INDEX_H02 = bj_CAMPAIGN_OFFSET_H * 1000 + 2
bj_MISSION_INDEX_H03 = bj_CAMPAIGN_OFFSET_H * 1000 + 3
bj_MISSION_INDEX_H04 = bj_CAMPAIGN_OFFSET_H * 1000 + 4
bj_MISSION_INDEX_H05 = bj_CAMPAIGN_OFFSET_H * 1000 + 5
bj_MISSION_INDEX_H06 = bj_CAMPAIGN_OFFSET_H * 1000 + 6
bj_MISSION_INDEX_H07 = bj_CAMPAIGN_OFFSET_H * 1000 + 7
bj_MISSION_INDEX_H08 = bj_CAMPAIGN_OFFSET_H * 1000 + 8
bj_MISSION_INDEX_H09 = bj_CAMPAIGN_OFFSET_H * 1000 + 9
bj_MISSION_INDEX_H10 = bj_CAMPAIGN_OFFSET_H * 1000 + 10
bj_MISSION_INDEX_H11 = bj_CAMPAIGN_OFFSET_H * 1000 + 11
bj_MISSION_INDEX_U00 = bj_CAMPAIGN_OFFSET_U * 1000 + 0
bj_MISSION_INDEX_U01 = bj_CAMPAIGN_OFFSET_U * 1000 + 1
bj_MISSION_INDEX_U02 = bj_CAMPAIGN_OFFSET_U * 1000 + 2
bj_MISSION_INDEX_U03 = bj_CAMPAIGN_OFFSET_U * 1000 + 3
bj_MISSION_INDEX_U05 = bj_CAMPAIGN_OFFSET_U * 1000 + 4
bj_MISSION_INDEX_U07 = bj_CAMPAIGN_OFFSET_U * 1000 + 5
bj_MISSION_INDEX_U08 = bj_CAMPAIGN_OFFSET_U * 1000 + 6
bj_MISSION_INDEX_U09 = bj_CAMPAIGN_OFFSET_U * 1000 + 7
bj_MISSION_INDEX_U10 = bj_CAMPAIGN_OFFSET_U * 1000 + 8
bj_MISSION_INDEX_U11 = bj_CAMPAIGN_OFFSET_U * 1000 + 9
bj_MISSION_INDEX_O00 = bj_CAMPAIGN_OFFSET_O * 1000 + 0
bj_MISSION_INDEX_O01 = bj_CAMPAIGN_OFFSET_O * 1000 + 1
bj_MISSION_INDEX_O02 = bj_CAMPAIGN_OFFSET_O * 1000 + 2
bj_MISSION_INDEX_O03 = bj_CAMPAIGN_OFFSET_O * 1000 + 3
bj_MISSION_INDEX_O04 = bj_CAMPAIGN_OFFSET_O * 1000 + 4
bj_MISSION_INDEX_O05 = bj_CAMPAIGN_OFFSET_O * 1000 + 5
bj_MISSION_INDEX_O06 = bj_CAMPAIGN_OFFSET_O * 1000 + 6
bj_MISSION_INDEX_O07 = bj_CAMPAIGN_OFFSET_O * 1000 + 7
bj_MISSION_INDEX_O08 = bj_CAMPAIGN_OFFSET_O * 1000 + 8
bj_MISSION_INDEX_O09 = bj_CAMPAIGN_OFFSET_O * 1000 + 9
bj_MISSION_INDEX_O10 = bj_CAMPAIGN_OFFSET_O * 1000 + 10
bj_MISSION_INDEX_N00 = bj_CAMPAIGN_OFFSET_N * 1000 + 0
bj_MISSION_INDEX_N01 = bj_CAMPAIGN_OFFSET_N * 1000 + 1
bj_MISSION_INDEX_N02 = bj_CAMPAIGN_OFFSET_N * 1000 + 2
bj_MISSION_INDEX_N03 = bj_CAMPAIGN_OFFSET_N * 1000 + 3
bj_MISSION_INDEX_N04 = bj_CAMPAIGN_OFFSET_N * 1000 + 4
bj_MISSION_INDEX_N05 = bj_CAMPAIGN_OFFSET_N * 1000 + 5
bj_MISSION_INDEX_N06 = bj_CAMPAIGN_OFFSET_N * 1000 + 6
bj_MISSION_INDEX_N07 = bj_CAMPAIGN_OFFSET_N * 1000 + 7
bj_MISSION_INDEX_N08 = bj_CAMPAIGN_OFFSET_N * 1000 + 8
bj_MISSION_INDEX_N09 = bj_CAMPAIGN_OFFSET_N * 1000 + 9
bj_MISSION_INDEX_XN00 = bj_CAMPAIGN_OFFSET_XN * 1000 + 0
bj_MISSION_INDEX_XN01 = bj_CAMPAIGN_OFFSET_XN * 1000 + 1
bj_MISSION_INDEX_XN02 = bj_CAMPAIGN_OFFSET_XN * 1000 + 2
bj_MISSION_INDEX_XN03 = bj_CAMPAIGN_OFFSET_XN * 1000 + 3
bj_MISSION_INDEX_XN04 = bj_CAMPAIGN_OFFSET_XN * 1000 + 4
bj_MISSION_INDEX_XN05 = bj_CAMPAIGN_OFFSET_XN * 1000 + 5
bj_MISSION_INDEX_XN06 = bj_CAMPAIGN_OFFSET_XN * 1000 + 6
bj_MISSION_INDEX_XN07 = bj_CAMPAIGN_OFFSET_XN * 1000 + 7
bj_MISSION_INDEX_XN08 = bj_CAMPAIGN_OFFSET_XN * 1000 + 8
bj_MISSION_INDEX_XN09 = bj_CAMPAIGN_OFFSET_XN * 1000 + 9
bj_MISSION_INDEX_XN10 = bj_CAMPAIGN_OFFSET_XN * 1000 + 10
bj_MISSION_INDEX_XH00 = bj_CAMPAIGN_OFFSET_XH * 1000 + 0
bj_MISSION_INDEX_XH01 = bj_CAMPAIGN_OFFSET_XH * 1000 + 1
bj_MISSION_INDEX_XH02 = bj_CAMPAIGN_OFFSET_XH * 1000 + 2
bj_MISSION_INDEX_XH03 = bj_CAMPAIGN_OFFSET_XH * 1000 + 3
bj_MISSION_INDEX_XH04 = bj_CAMPAIGN_OFFSET_XH * 1000 + 4
bj_MISSION_INDEX_XH05 = bj_CAMPAIGN_OFFSET_XH * 1000 + 5
bj_MISSION_INDEX_XH06 = bj_CAMPAIGN_OFFSET_XH * 1000 + 6
bj_MISSION_INDEX_XH07 = bj_CAMPAIGN_OFFSET_XH * 1000 + 7
bj_MISSION_INDEX_XH08 = bj_CAMPAIGN_OFFSET_XH * 1000 + 8
bj_MISSION_INDEX_XH09 = bj_CAMPAIGN_OFFSET_XH * 1000 + 9
bj_MISSION_INDEX_XU00 = bj_CAMPAIGN_OFFSET_XU * 1000 + 0
bj_MISSION_INDEX_XU01 = bj_CAMPAIGN_OFFSET_XU * 1000 + 1
bj_MISSION_INDEX_XU02 = bj_CAMPAIGN_OFFSET_XU * 1000 + 2
bj_MISSION_INDEX_XU03 = bj_CAMPAIGN_OFFSET_XU * 1000 + 3
bj_MISSION_INDEX_XU04 = bj_CAMPAIGN_OFFSET_XU * 1000 + 4
bj_MISSION_INDEX_XU05 = bj_CAMPAIGN_OFFSET_XU * 1000 + 5
bj_MISSION_INDEX_XU06 = bj_CAMPAIGN_OFFSET_XU * 1000 + 6
bj_MISSION_INDEX_XU07 = bj_CAMPAIGN_OFFSET_XU * 1000 + 7
bj_MISSION_INDEX_XU08 = bj_CAMPAIGN_OFFSET_XU * 1000 + 8
bj_MISSION_INDEX_XU09 = bj_CAMPAIGN_OFFSET_XU * 1000 + 9
bj_MISSION_INDEX_XU10 = bj_CAMPAIGN_OFFSET_XU * 1000 + 10
bj_MISSION_INDEX_XU11 = bj_CAMPAIGN_OFFSET_XU * 1000 + 11
bj_MISSION_INDEX_XU12 = bj_CAMPAIGN_OFFSET_XU * 1000 + 12
bj_MISSION_INDEX_XU13 = bj_CAMPAIGN_OFFSET_XU * 1000 + 13
bj_MISSION_INDEX_XO00 = bj_CAMPAIGN_OFFSET_XO * 1000 + 0
bj_CINEMATICINDEX_TOP = 0
bj_CINEMATICINDEX_HOP = 1
bj_CINEMATICINDEX_HED = 2
bj_CINEMATICINDEX_OOP = 3
bj_CINEMATICINDEX_OED = 4
bj_CINEMATICINDEX_UOP = 5
bj_CINEMATICINDEX_UED = 6
bj_CINEMATICINDEX_NOP = 7
bj_CINEMATICINDEX_NED = 8
bj_CINEMATICINDEX_XOP = 9
bj_CINEMATICINDEX_XED = 10
bj_ALLIANCE_UNALLIED = 0
bj_ALLIANCE_UNALLIED_VISION = 1
bj_ALLIANCE_ALLIED = 2
bj_ALLIANCE_ALLIED_VISION = 3
bj_ALLIANCE_ALLIED_UNITS = 4
bj_ALLIANCE_ALLIED_ADVUNITS = 5
bj_ALLIANCE_NEUTRAL = 6
bj_ALLIANCE_NEUTRAL_VISION = 7
bj_KEYEVENTTYPE_DEPRESS = 0
bj_KEYEVENTTYPE_RELEASE = 1
bj_KEYEVENTKEY_LEFT = 0
bj_KEYEVENTKEY_RIGHT = 1
bj_KEYEVENTKEY_DOWN = 2
bj_KEYEVENTKEY_UP = 3
bj_TIMETYPE_ADD = 0
bj_TIMETYPE_SET = 1
bj_TIMETYPE_SUB = 2
bj_CAMERABOUNDS_ADJUST_ADD = 0
bj_CAMERABOUNDS_ADJUST_SUB = 1
bj_QUESTTYPE_REQ_DISCOVERED = 0
bj_QUESTTYPE_REQ_UNDISCOVERED = 1
bj_QUESTTYPE_OPT_DISCOVERED = 2
bj_QUESTTYPE_OPT_UNDISCOVERED = 3
bj_QUESTMESSAGE_DISCOVERED = 0
bj_QUESTMESSAGE_UPDATED = 1
bj_QUESTMESSAGE_COMPLETED = 2
bj_QUESTMESSAGE_FAILED = 3
bj_QUESTMESSAGE_REQUIREMENT = 4
bj_QUESTMESSAGE_MISSIONFAILED = 5
bj_QUESTMESSAGE_ALWAYSHINT = 6
bj_QUESTMESSAGE_HINT = 7
bj_QUESTMESSAGE_SECRET = 8
bj_QUESTMESSAGE_UNITACQUIRED = 9
bj_QUESTMESSAGE_UNITAVAILABLE = 10
bj_QUESTMESSAGE_ITEMACQUIRED = 11
bj_QUESTMESSAGE_WARNING = 12
bj_SORTTYPE_SORTBYVALUE = 0
bj_SORTTYPE_SORTBYPLAYER = 1
bj_SORTTYPE_SORTBYLABEL = 2
bj_CINEFADETYPE_FADEIN = 0
bj_CINEFADETYPE_FADEOUT = 1
bj_CINEFADETYPE_FADEOUTIN = 2
bj_REMOVEBUFFS_POSITIVE = 0
bj_REMOVEBUFFS_NEGATIVE = 1
bj_REMOVEBUFFS_ALL = 2
bj_REMOVEBUFFS_NONTLIFE = 3
bj_BUFF_POLARITY_POSITIVE = 0
bj_BUFF_POLARITY_NEGATIVE = 1
bj_BUFF_POLARITY_EITHER = 2
bj_BUFF_RESIST_MAGIC = 0
bj_BUFF_RESIST_PHYSICAL = 1
bj_BUFF_RESIST_EITHER = 2
bj_BUFF_RESIST_BOTH = 3
bj_HEROSTAT_STR = 0
bj_HEROSTAT_AGI = 1
bj_HEROSTAT_INT = 2
bj_MODIFYMETHOD_ADD = 0
bj_MODIFYMETHOD_SUB = 1
bj_MODIFYMETHOD_SET = 2
bj_UNIT_STATE_METHOD_ABSOLUTE = 0
bj_UNIT_STATE_METHOD_RELATIVE = 1
bj_UNIT_STATE_METHOD_DEFAULTS = 2
bj_UNIT_STATE_METHOD_MAXIMUM = 3
bj_GATEOPERATION_CLOSE = 0
bj_GATEOPERATION_OPEN = 1
bj_GATEOPERATION_DESTROY = 2
bj_GAMECACHE_BOOLEAN = 0
bj_GAMECACHE_INTEGER = 1
bj_GAMECACHE_REAL = 2
bj_GAMECACHE_UNIT = 3
bj_GAMECACHE_STRING = 4
bj_ITEM_STATUS_HIDDEN = 0
bj_ITEM_STATUS_OWNED = 1
bj_ITEM_STATUS_INVULNERABLE = 2
bj_ITEM_STATUS_POWERUP = 3
bj_ITEM_STATUS_SELLABLE = 4
bj_ITEM_STATUS_PAWNABLE = 5
bj_ITEMCODE_STATUS_POWERUP = 0
bj_ITEMCODE_STATUS_SELLABLE = 1
bj_ITEMCODE_STATUS_PAWNABLE = 2
bj_MINIMAPPINGSTYLE_SIMPLE = 0
bj_MINIMAPPINGSTYLE_FLASHY = 1
bj_MINIMAPPINGSTYLE_ATTACK = 2
bj_CORPSE_MAX_DEATH_TIME = 8.00
bj_CORPSETYPE_FLESH = 0
bj_CORPSETYPE_BONE = 1
bj_ELEVATOR_BLOCKER_CODE = "DTep"
bj_ELEVATOR_CODE01 = "DTrf"
bj_ELEVATOR_CODE02 = "DTrx"
bj_ELEVATOR_WALL_TYPE_ALL = 0
bj_ELEVATOR_WALL_TYPE_EAST = 1
bj_ELEVATOR_WALL_TYPE_NORTH = 2
bj_ELEVATOR_WALL_TYPE_SOUTH = 3
bj_ELEVATOR_WALL_TYPE_WEST = 4
bj_MELEE_MAX_TWINKED_HEROES = 0
bj_slotControlReady = false
bj_mapInitialPlayableArea = nil
bj_mapInitialCameraBounds = nil
bj_forLoopAIndex = 0
bj_forLoopBIndex = 0
bj_forLoopAIndexEnd = 0
bj_forLoopBIndexEnd = 0
bj_slotControlReady = false
bj_gameStartedTimer = nil
bj_gameStarted = false
bj_isSinglePlayer = false
bj_dncSoundsDay = nil
bj_dncSoundsNight = nil
bj_dayAmbientSound = nil
bj_nightAmbientSound = nil
bj_dncSoundsDawn = nil
bj_dncSoundsDusk = nil
bj_dawnSound = nil
bj_duskSound = nil
bj_useDawnDuskSounds = true
bj_dncIsDaytime = false
bj_rescueSound = nil
bj_questDiscoveredSound = nil
bj_questUpdatedSound = nil
bj_questCompletedSound = nil
bj_questFailedSound = nil
bj_questHintSound = nil
bj_questSecretSound = nil
bj_questItemAcquiredSound = nil
bj_questWarningSound = nil
bj_victoryDialogSound = nil
bj_defeatDialogSound = nil
bj_rescueUnitBehavior = nil
bj_rescueChangeColorUnit = true
bj_rescueChangeColorBldg = true
bj_cineSceneEndingTimer = nil
bj_cineSceneLastSound = nil
bj_cineSceneBeingSkipped = nil
bj_cineModePriorSpeed = MAP_SPEED_NORMAL
bj_cineModePriorFogSetting = false
bj_cineModePriorMaskSetting = false
bj_cineModeAlreadyIn = false
bj_cineModePriorDawnDusk = false
bj_cineModeSavedSeed = 0
bj_cineFadeFinishTimer = nil
bj_cineFadeContinueTimer = nil
bj_cineFadeContinueRed = 0
bj_cineFadeContinueGreen = 0
bj_cineFadeContinueBlue = 0
bj_cineFadeContinueTrans = 0
bj_cineFadeContinueDuration = 0
bj_cineFadeContinueTex = ""
|
-- Copyright (c) 2021 Trevor Redfern
--
-- This software is released under the MIT License.
-- https://opensource.org/licenses/MIT
describe("game.ui.create_character.basic_information", function()
local BasicInformation = require "game.ui.create_character.basic_information"
local Character = require "game.rules.character"
local Attributes = require "game.rules.character.attributes"
local testStates = require "test_helpers.test_states"
local biWidget
before_each(function()
biWidget = BasicInformation {
character = testStates.basicPlayer(),
buyPoints = 15
}
end)
it("renders a table", function()
assert.is_table(biWidget)
end)
it("updates the character name has it changes", function()
local character = { }
local bi = BasicInformation { character = character }
local nameBox = bi:findByID("characterName")
assert.component_dispatches(
Character.actions.setName(character, "Foobar"),
function()
nameBox:setText("Foobar")
end
)
end)
it("sets the minimum and maximum for the attribute spinners", function()
local intelligenceSpinner = biWidget:findByID("INTELLIGENCESpinner")
assert.equals(3, intelligenceSpinner.minimum)
assert.equals(12, intelligenceSpinner.maximum)
end)
it("dispatches to increase intelligence attribute", function()
local spinner = biWidget:findByID("INTELLIGENCESpinner")
assert.component_dispatches(Character.actions.buyAttributePoint(
biWidget.character, Attributes.intelligence), function()
spinner:increase()
end)
end)
it("adds point when points are subtracted", function()
local spinner = biWidget:findByID("INTELLIGENCESpinner")
assert.component_dispatches(Character.actions.sellAttributePoint(
biWidget.character, Attributes.intelligence), function()
spinner:decrease()
end)
end)
end)
|
-- Simple test for QLink status
local modem = peripheral.find("modem")
modem.open(6464)
modem.transmit(6464,6464,{sType = "requestStatus"})
local t = os.startTimer(2)
while true do
local e = {os.pullEvent()}
if e[1] == "modem_message" then
if e[3] == 6464 then
if type(e[5]) == "table" then
if e[5].sType then
if e[5].sType == "status" then
print("C64 Status: "..e[5].sContents)
end
end
end
end
elseif e[1] == "timer" then
print("C64 Status:")
print("Error: Could not connect to server")
break
end
end
|
#!/usr/bin/lua
-- Sidef executor in Lua
String = setmetatable({
__index = function(self, i)
return String[i]
end,
concat = function(self, arg)
return String(self.value .. arg.value)
end,
say = function(self)
self:concat(String("\n")):print();
end,
print = function(self)
io.write(self.value);
end,
},
{
__call = function(self, val)
return setmetatable({value = val}, String)
end
});
function execute_expr(statement)
local self_obj = statement['self'];
if (type(self_obj) == "table" and getmetatable(self_obj) == nil) then
self_obj = execute(self_obj);
end
if (statement['call'] ~= nil) then
for i = 1, #(statement['call']) do
local call = statement['call'][i];
local meth = call['method'];
if (call['arg'] ~= nil) then
local args = {};
local call_args = call['arg'];
for i = 1, #call_args do
local arg = call_args[i];
if (type(arg) == "table" and getmetatable(arg) == nil) then
arg = execute_expr(arg);
end
args[i] = arg;
end
self_obj = self_obj[meth](self_obj, unpack(args));
else
self_obj = self_obj[meth](self_obj);
end
end
end
return self_obj;
end
function execute(structure)
local results = {};
for i = 1, #(structure['main']) do
local statement = structure['main'][i];
results[i] = execute_expr(statement);
end
return results[#results];
end
local ast = {
main = {
{
call = {{method = "print"}},
self = {
main = {
{
call = {{method = "concat", arg = {{self = String("llo")}}}},
self = String("he"),
}
},
}
},
{
call = {{method = "say"}},
self = String(" world!");
},
}
}
execute(ast);
|
-- based on https://github.com/cheapie/mail
laptop.register_app("mail", {
app_name = "Mail",
app_icon = "laptop_email_letter.png",
app_info = "Send Electronic Mail",
formspec_func = function(app, mtos)
local cloud = mtos.bdev:get_app_storage('cloud', 'mail')
if not cloud then
mtos:set_app("mail:nonet")
return false
end
if not mtos.sysram.current_player then
mtos:set_app() -- no player. Back to launcher
return false
end
if not cloud[mtos.sysram.current_player] then
mtos:set_app("mail:newplayer")
return false
end
local account = cloud[mtos.sysram.current_player]
account.selected_box = account.selected_box or "inbox"
account.selected_index = nil -- will be new determinated by selectedmessage
local box = account[account.selected_box] -- inbox or outbox
app.app_info = app.app_info.." - Welcome "..mtos.sysram.current_player
local formspec =
mtos.theme:get_tableoptions()..
"tablecolumns[" ..
"image,align=center,1="..mtos.theme:get_texture('laptop_mail.png')..",2="..mtos.theme:get_texture('laptop_mail_read.png')..";".. --icon column
"color;".. -- subject and date color
"text;".. -- subject
"text,padding=1.5;".. -- sender
"text,padding=1.5,align=right]".. -- date
"table[0,0.5;7.5,8.2;message;"
if box and box[1] then
for idx,message in ipairs(box) do
if idx > 1 then
formspec = formspec..','
end
-- set read/unread status
if account.selected_box == "sentbox" then
formspec = formspec .. "2,"..mtos.theme.muted_textcolor.."," -- sent are always read
elseif not message.is_read then
formspec = formspec .. "1,"..mtos.theme.table_textcolor.."," -- unread
else
formspec = formspec .. "2,"..mtos.theme.muted_textcolor.."," -- read
end
-- set subject
if not message.subject or message.subject == "" then
formspec = formspec .. "(No Subject),"
elseif string.len(message.subject) > 30 then
formspec = formspec .. minetest.formspec_escape(string.sub(message.subject,1,27)) .. "...,"
else
formspec = formspec .. minetest.formspec_escape(message.subject) .. ","
end
-- set sender or receiver
if account.selected_box == "inbox" then
formspec = formspec..minetest.formspec_escape(message.sender or "") .."," -- body
else
formspec = formspec..minetest.formspec_escape(message.receiver or "") .."," -- body
end
-- set date
formspec = formspec .. os.date("%c", message.time) -- timestamp
-- handle marked line
if account.selectedmessage and
message.sender == account.selectedmessage.sender and
message.subject == account.selectedmessage.subject and
message.time == account.selectedmessage.time and
message.body == account.selectedmessage.body then
account.selected_index = idx
end
end
formspec = formspec .. ";"..(account.selected_index or "").."]"
else
formspec = formspec .. ",,No Mail :(]"
end
-- toggle inbox/sentbox
if account.selected_box == "inbox" then
formspec = formspec .. mtos.theme:get_image_button('0,9;1,1', 'minor', 'switch_sentbox', 'laptop_mail_sentbox.png', '', 'Show Sent Messages')
else
formspec = formspec .. mtos.theme:get_image_button('0,9;1,1', 'minor', 'switch_inbox', 'laptop_mail_received.png', '', 'Show Received Messages')
end
formspec = formspec .. mtos.theme:get_image_button('1.7,9;1,1', 'minor', 'new', 'laptop_email_new.png', '', 'New Message')
if account.newmessage then
formspec = formspec .. mtos.theme:get_image_button('2.7,9;1,1', 'minor', 'continue', 'laptop_email_edit.png', '', 'Continue Last Message')
end
if account.selectedmessage then
formspec = formspec ..
mtos.theme:get_image_button('3.7,9;1,1', 'minor', 'reply', 'laptop_email_reply.png', '', 'Reply')..
mtos.theme:get_image_button('4.7,9;1,1', 'minor', 'forward', 'laptop_email_forward.png', '', 'Forward')..
mtos.theme:get_image_button('5.7,9;1,1', 'minor', 'delete', 'laptop_email_trash.png', '', 'Delete')
if account.selected_box == "inbox" then
if not account.selectedmessage.is_read then
formspec = formspec .. mtos.theme:get_image_button('6.7,9;1,1', 'minor', 'markread', 'laptop_mail_read_button.png', '', 'Mark Message as Read')
else
formspec = formspec .. mtos.theme:get_image_button('6.7,9;1,1', 'minor', 'markunread', 'laptop_mail_button.png', '', 'Mark Message as Unread')
end
end
formspec = formspec .. mtos.theme:get_image_button('8,9;1,1', 'minor', 'print', 'laptop_printer_button.png', '', 'Print Email')
if account.selected_box == "inbox" then
formspec = formspec .. mtos.theme:get_label('8,0.5', "From: "..(account.selectedmessage.sender or ""))
else
formspec = formspec .. mtos.theme:get_label('8,0.5', "To: "..(account.selectedmessage.receiver or ""))
end
formspec = formspec .. mtos.theme:get_label('8,1', "Subject: "..(account.selectedmessage.subject or ""))..
mtos.theme:get_tableoptions(false).."tablecolumns[text]table[8,1.55;6.85,7.15;preview_bg;]"..
"textarea[8.35,1.6;6.8,8.25;;"..minetest.colorize(mtos.theme.table_textcolor, minetest.formspec_escape(account.selectedmessage.body) or "")..";]"
end
return formspec
end,
receive_fields_func = function(app, mtos, sender, fields)
if mtos.sysram.current_player ~= mtos.sysram.last_player then
mtos:set_app() -- wrong player. Back to launcher
return
end
local cloud = mtos.bdev:get_app_storage('cloud', 'mail')
local account = cloud[mtos.sysram.current_player]
if not account then
mtos:set_app() -- wrong player. Back to launcher
return
end
account.selected_box = account.selected_box or "inbox"
local box = account[account.selected_box] -- inbox or outbox
-- Set read status if 2 seconds selected
if account.selected_index and account.selectedmessage and account.selected_box == "inbox" and
account.selected_timestamp and (os.time() - account.selected_timestamp) > 1 then
account.selectedmessage.is_read = true
end
-- process input
if fields.message then
local event = minetest.explode_table_event(fields.message)
account.selectedmessage = box[event.row]
if account.selectedmessage then
account.selected_index = event.row
account.selected_timestamp = os.time()
else
account.selected_index = nil
end
elseif fields.new then
account.newmessage = {}
mtos:set_app("mail:compose")
elseif fields.continue then
mtos:set_app("mail:compose")
elseif fields.switch_sentbox then
account.selected_box = "sentbox"
account.selectedmessage = nil
elseif fields.switch_inbox then
account.selected_box = "inbox"
account.selectedmessage = nil
elseif account.selected_index then
if fields.delete then
table.remove(box, account.selected_index)
account.selectedmessage = nil
elseif fields.reply then
account.newmessage = {}
account.newmessage.receiver = account.selectedmessage.sender
account.newmessage.subject = "Re: "..(account.selectedmessage.subject or "")
account.newmessage.body = "Type your reply here."..string.char(10)..string.char(10).."--Original message follows--"..string.char(10)..(account.selectedmessage.body or "")
mtos:set_app("mail:compose")
elseif fields.forward then
account.newmessage = {}
account.newmessage.subject = "Fw: "..(account.selectedmessage.subject or "")
account.newmessage.body = "Type your reply here."..string.char(10)..string.char(10).."--Original message follows--"..string.char(10)..(account.selectedmessage.body or "")
mtos:set_app("mail:compose")
elseif fields.markread then
account.selectedmessage.is_read = true
elseif fields.markunread then
account.selectedmessage.is_read = false
account.selected_timestamp = nil
elseif fields.print then
mtos:print_file_dialog({
label = account.selectedmessage.subject,
author = account.selectedmessage.sender,
timestamp = account.selectedmessage.time,
text = account.selectedmessage.body,
})
end
end
end
})
laptop.register_view("mail:newplayer", {
formspec_func = function(app, mtos)
return mtos.theme:get_label('1,3', "No mail account for player "..mtos.sysram.current_player.. " found. Do you like to create a new account?")..
mtos.theme:get_button('1,4;3,1', 'major', 'create', 'Create Account')
end,
receive_fields_func = function(app, mtos, sender, fields)
if mtos.sysram.current_player ~= mtos.sysram.last_player then
mtos:set_app() -- wrong player. Back to launcher
return
end
if fields.create then
local cloud = mtos.bdev:get_app_storage('cloud', 'mail')
cloud[mtos.sysram.current_player] = {
inbox = {},
sentbox = {}
}
app:back_app()
elseif fields.os_back then
app:exit_app()
end
end
})
laptop.register_view("mail:nonet", {
formspec_func = function(app, mtos)
return mtos.theme:get_label('1,3', "NO NETWORK CONNECTION")
end,
receive_fields_func = function(app, mtos, sender, fields)
app:exit_app()
end
})
-- Write new mail
laptop.register_view("mail:compose", {
formspec_func = function(app, mtos)
local cloud = mtos.bdev:get_app_storage('cloud', 'mail')
local account = cloud[mtos.sysram.current_player]
account.newmessage = account.newmessage or {}
local message = account.newmessage
local formspec = "background[0,0.4;8,2.4;"..mtos.theme.contrast_background.."]"..
mtos.theme:get_label("0.25,2", "Subject:", "contrast").."field[2.7,2;5,1;subject;;"..minetest.formspec_escape(message.subject or "").."]"..
"background[0,3.05;7.95,3.44;"..mtos.theme.contrast_background.."]"..
"textarea[0.25,3;8,4;body;;"..minetest.formspec_escape(message.body or "").."]"..
mtos.theme:get_button("0,8;2,1", "major", "send", "Send message")..
mtos.theme:get_label("0.25,0.75", "Receiver:", "contrast").."dropdown[2.4,0.75;5.2,1;receiver;"
local sortedtab = {}
for playername,_ in pairs(cloud) do
table.insert(sortedtab, playername)
end
table.sort(sortedtab)
local selected_idx
for idx, playername in ipairs(sortedtab) do
formspec = formspec..',' .. minetest.formspec_escape(playername)
if playername == message.receiver then
selected_idx = idx+1 -- +1 because of empty entry
end
end
formspec = formspec .. ";"..(selected_idx or "").."]"
if message.receiver and not cloud[message.receiver] then
formspec = formspec..mtos.theme:get_label('2.3,8', "invalid receiver player")
end
return formspec
end,
receive_fields_func = function(app, mtos, sender, fields)
if mtos.sysram.current_player ~= mtos.sysram.last_player then
mtos:set_app() -- wrong player. Back to launcher
return
end
local cloud = mtos.bdev:get_app_storage('cloud', 'mail')
local account = cloud[mtos.sysram.current_player]
account.newmessage = account.newmessage or {}
local message = account.newmessage
message.receiver = fields.receiver or message.receiver
message.sender = mtos.sysram.current_player
message.time = os.time()
message.subject = fields.subject or message.subject
message.body = fields.body or message.body
if fields.send and message.receiver and cloud[message.receiver] then
table.insert(cloud[message.receiver].inbox, message)
table.insert(account.sentbox, table.copy(message))
account.newmessage = nil
app:back_app()
end
end
})
|
return {
size = { w = 17, h = 11 },
cells = {
{0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0},
{1,1,1,0,0,0,0,0,1,0,0,0,0,0,1,1,1},
{1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},
{1,1,1,0,0,0,0,0,1,0,0,0,0,0,1,1,1},
{0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,1,1,1,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,1,1,1,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,1,1,1,0,0,0,0,0,0,0},
},
start_position = { x = 9, y = 10 },
start_shape = 'triangle',
enemies = {
{ shape = 'triangle',
position = { x = 6, y = 7 }
},
{ shape = 'triangle',
position = { x = 2, y = 7 }
},
{ shape = 'square',
position = { x = 12, y = 7 }
},
{ shape = 'pentagon',
position = { x = 16, y = 7 }
},
{ shape = 'circle',
position = { x = 9, y = 5 }
},
{ shape = 'circle',
position = { x = 9, y = 2 }
},
},
intermission = {
background = 'shape_triangle.png',
s_color = {96/256, 122/256, 143/256, 0},
o_color = {191/256, 44/256, 172/256, 0},
dialog = {
"<other>Hey Shape.</>",
"<other>Do you thing love can take <big>shape</> on the battlefield?</>",
"<shape>What are you talking about?</>",
"<other>You see, there's this girl...</>",
"<shape>Why are you talking to me about this?</>",
"<shape>I'm about to end you all.</>",
"<other>Well, I just thought...</>",
"<shape>Just leave me alone.</>",
"<other>That's is. Now I'm mad.</>",
"<other>You're toast Shape!</>",
"<other>You're toast and you don't even know it!</>"
}
}
}
|
speed = 1
cameraSpeed = math.pi / 8
rot = math.pi / 2
light = tracer.SpotLight(tracer.Color(1, 1, 1), tracer.Vec(2, 5, 0), tracer.Vec(0, 0, 0), math.pi / 12, math.pi / 9)
tracer.scene:addLight(light)
function tick(dt)
local obj = tracer.scene:getObject(3)
obj.transform = obj.transform * tracer.Mat.fromRotationZ(dt * speed)
obj.transform = tracer.Mat.fromTranslation(tracer.Vec(-dt * speed, 0, 0)) * obj.transform
local m = tracer.Mat.fromTranslation(tracer.Vec(0, -1, 0)) * obj.transform
local pos = m:mul(tracer.Vec(0, 0, 0))
light.direction = pos - light.position
local cam = tracer.scene.camera
local mat = tracer.Mat.fromTranslation(tracer.Vec(0, 0, -6)) * tracer.Mat.fromRotationY(rot) * tracer.Mat.fromTranslation(tracer.Vec(0, 0, 8))
cam.position = mat:mul(tracer.Vec(0, 0, 0))
tracer.scene.camera = cam
rot = rot - dt * cameraSpeed
end
|
if not file.Exists("ghomes_system/mails/", "DATA") then
file.CreateDir("ghomes_system/mails/")
end
util.AddNetworkString("ghomes_requestlastmail")
util.AddNetworkString("ghomes_writenote")
util.AddNetworkString("ghomes_newmail")
ghomes.mail = ghomes.mail or {}
function ghomes.mail.savemail(sid)
local target = "ghomes_system/mails/" .. sid .. ".txt"
file.Write(target, util.TableToJSON(ghomes.mail[sid], true))
end
function ghomes.mail.restoremails()
for k, v in pairs(file.Find("ghomes_system/mails/*", "DATA")) do
local trg = string.Left(v, 17)
ghomes.mail[trg] = util.JSONToTable(file.Read("ghomes_system/mails/" .. v))
end
end
net.Receive("ghomes_requestlastmail", function(len, ply)
local sid = ply:SteamID64()
net.Start("ghomes_requestlastmail")
net.WriteTable(ghomes.mail[sid][1] or {})
table.remove(ghomes.mail[sid], 1)
ghomes.mail.savemail(sid)
net.Send(ply)
end)
net.Receive("ghomes_writenote", function(len, ply)
local target = net.ReadString()
local _message = net.ReadString()
--local anon = net.ReadBool()
if not ply.lastwrotenote then
ply.lastwrotenote = CurTime()
else
if CurTime() - ply.lastwrotenote < 60 then -- stop spamming u cunt
ghomes.wrapper.notify(ply, 1, 4, Format("You need to wait another %i seconds before writing a message/mail", 60 - (CurTime() - ply.lastwrotenote) ))
return
end
end
ply.lastwrotenote = CurTime()
if string.len(_message) > 1024 then return end -- fuck off mate
target = util.SteamIDTo64(target)
if not ghomes.mail[target] then
ghomes.mail[target] = {}
end
local message = {}
/*if anon then
message.author = "???"
else*/
message.author = ply:Nick()
--end
message.text = _message
table.insert(ghomes.mail[target], message)
ghomes.mail.savemail(target)
local plytrg = player.GetBySteamID64(target)
if plytrg then
net.Start("ghomes_newmail")
net.WriteUInt(#ghomes.mail[target], 7)
net.Send(plytrg)
end
end)
|
--[[************************************************************
Stdlib written by Jason Lee Copyright (c) 2018
This software is free to use. You can modify it and
redistribute it under the terms of the MIT license.
--************************************************************]]
return function(thread)
local API={
_version={0,3,9};
enum={
object_type={
property={};
};
};
root_functions={
math={
floor=math.floor;
ceil=math.ceil;
asin=math.asin;
sin=math.sin;
cos=math.cos;
tan=math.tan;
rad=math.rad;
deg=math.deg;
sqrt=math.sqrt;
exp=math.exp;
abs=math.abs;
random=math.random;
max=math.max;
min=math.min;
pi=math.pi;
};
string={
len=string.len;
sub=string.sub;
gsub=string.gsub;
match=string.match;
gmatch=string.gmatch;
format=string.format;
upper=string.upper;
lower=string.lower;
byte=string.byte;
char=string.char;
find=string.find;
};
table={
unpack=unpack;
insert=table.insert;
remove=table.remove;
sort=table.sort;
};
coroutine={
create=coroutine.create;
resume=coroutine.resume;
yield=coroutine.yield;
status=coroutine.status;
};
};
}
if _VERSION=="Lua 5.3" then
API.root_functions.table.unpack=table.unpack
end
function API:group_tables(...) --Indexes must be integral!
local tables={...}
local grouped_table=API:copy(tables[1])
for i=2,#tables do
for _,object in pairs(tables[i]) do
grouped_table[#grouped_table+1]=object
end
end
return grouped_table
end
function API:replace_string(current_text,point,text)
local current_length=API.root_functions.string.len(current_text)
local new_length=API.root_functions.string.len(text)
if current_length<point+new_length then
for i=current_length,point+new_length do
current_text=current_text.." "
current_length=current_length+1
end
end
return API.root_functions.string.sub(current_text,0,point-1)..text..API.root_functions.string.sub(current_text,point+new_length,current_length)
end
function API:rotate_point(point,origin,angle)
local s=API.root_functions.math.sin(API.root_functions.math.rad(angle))
local c=API.root_functions.math.cos(API.root_functions.math.rad(angle))
point.x,point.y=point.x-origin.x,point.y-origin.y
return {x=(point.x*c-point.y*s)+origin.x,y=(point.x*s+point.y*c)+origin.y}
end
function API:lerp_number(start,goal,percent) return start+((goal-start)*percent) end
function API:magnitude(a,b) return API.root_functions.math.sqrt((a-b)^2) end
function API:round(num,decimal_place)
local mult=10^(decimal_place or 0)
return API.root_functions.math.floor(num*mult+0.5)/mult
end
function API:round_multiple(num,multiple)
if multiple==0 then return num end
local remainder=num%multiple
if remainder==0 then return num end
return num+multiple-remainder;
end
function API:clamp(val,min_val,max_val)
if val<min_val or val~=val then
val=min_val
elseif val>max_val then
val=max_val
end
return val
end
function API:partition(array,left,right,p_index,get_value)
local p_value=get_value(array[p_index])
array[p_index],array[right]=array[right],array[p_index]
local stored_index=left
for i=left,right-1 do
if get_value(array[i])<=p_value then
array[i],array[stored_index]=array[stored_index],array[i]
stored_index=stored_index+1
end
array[stored_index],array[right]=array[right],array[stored_index]
end
return stored_index
end
function API:quick_sort(array,left,right,get_value)
get_value=get_value or function(object) return object end
if right>left then
local p_new_index=API:partition(array,left,right,left,get_value)
API:quick_sort(array,left,p_new_index-1,get_value)
API:quick_sort(array,p_new_index+1,right,get_value)
end
end
function API:set_program_environment(program,object_name,value)
if type(program)=="function" then
local environment=getfenv(program)
environment[object_name]=value
setfenv(program,environment)
elseif type(program)=="table" then
for _,object in pairs(program) do
if type(object)=="function" then
local environment=getfenv(object)
environment[object_name]=value
setfenv(object,environment)
end
end
end
end
function API:set_program_environment_table_list(program,list)
for object_name,value in pairs(list) do
API:set_program_environment(program,object_name,value)
end
end
function API:limit(value,min,max)
if value<min then
value=min
elseif value>max then
value=max
end
end
function API:copy(object,deep)
local object_copy={}
for k,v in pairs(object) do
if deep==true and type(v)=="table" then
v=self:copy(v,deep)
end
object_copy[k]=v
end
return object_copy
end
function API:delete(object,deep)
for k,v in pairs(object) do
if deep==true and type(v)=="table" then
API:delete(v,deep)
end
object[k]=nil
end
end
function API:get_parent_directory(path,parent_index)
if path==nil then return "" end
parent_index=parent_index or 1
local current_index=0
local path_length=API.root_functions.string.len(path)
local parent_length=0
for i=1,path_length do
if current_index<parent_index then
local char=API.root_functions.string.sub(path,path_length+1-i,path_length+1-i)
if char=="/" or char=="\\" then
current_index=current_index+1
parent_length=path_length+1-i
end
else
break
end
end
return API.root_functions.string.sub(path,1,parent_length)
end
function API:create_properties_table(properties)
function properties:extract()
local extracted={}
for i,v in pairs(properties) do
if type(v)=="table" then
extracted[i]=v.value
end
end
return extracted
end
return properties
end
function API:create_name_space(env)
env()
end
function API:merge_tables(...)
local tables={...}
local new_table={}
for _,current_table in pairs(tables) do
for i,v in pairs(current_table) do
if new_table[i]==nil then
new_table[i]=v
end
end
end
return new_table
end
function API:find(t,value)
local indexes={}
for i,v in pairs(t) do
if v==value then
indexes[#indexes+1]=i
end
end
return indexes
end
return API
end
|
local neu = {} -- neuron functions
neu.new = function (data)
local input_amount = data.input_amount or 25
local output_amount = data.output_amount or 4
local layers_amount = data.layers_amount or 4
local layer_breadth = data.breadth or 4
local header = {input_amount=input_amount, -- input nodes
output_amount=output_amount, -- output nodes
layers_amount=layers_amount, -- how many hidden layers do we have
layer_breadth=layer_breadth} -- amount nodes in the hidden layer
local layers = {}
for i = 1, layers_amount do
local nodes = {}
for j = 1, layer_breadth do
local weights = {}
local connections_amount = (i==1) and input_amount or layer_breadth
for k = 1, connections_amount do
table.insert(weights, {n=2*math.random()-1, -- real from -1 to 1
ii=2*math.random()-1,
ij=2*math.random()-1,
ik=2*math.random()-1})
end
table.insert(nodes, {weights=weights})
nodes.bias = {n=2*math.random()-1, -- real from -1 to 1
ii=2*math.random()-1,
ij=2*math.random()-1,
ik=2*math.random()-1}
end
table.insert (layers, {nodes = nodes})
end
local output_nodes = {}
for i = 1, output_amount do
-- local node = {}
local weights = {}
for k = 1, layer_breadth do
table.insert(weights, {n=2*math.random()-1, -- real from -1 to 1
ii=2*math.random()-1,
ij=2*math.random()-1,
ik=2*math.random()-1})
end
-- table.insert(node, {weights=weights})
table.insert (output_nodes, {weights=weights})
output_nodes.bias = {n=2*math.random()-1, -- real from -1 to 1
ii=2*math.random()-1,
ij=2*math.random()-1,
ik=2*math.random()-1}
end
return layers, output_nodes
end
neu.activation = function (a) -- from -inf to +inf
if type (a) == "table" then
-- activation for table
for letter, value in pairs (a) do
local n = a[letter] or 0
local result = 2 * math.sin(math.pi * n)
if (result > 2) or (result < -2) then
result = 0
end
a[letter] = result
end
return a
else
local result = 2 * math.sin(math.pi * a)
if (result > 2) or (result < -2) then
result = 0
end
return result
end
end
neu.complex_multiplicate = function (a, b, bool)
-- complex numbers: a = {n, i, j, k}, b = {n, i, j, k}
-- n is real part of real number
-- i, j, k imaginary parts of real number
if not type (a) == "table" then a = {n=a, i=0, j=0, k=0} end
if not type (b) == "table" then b = {n=b, i=0, j=0, k=0} end
local c = {}
c.n = a.n * b.n -- 1
if bool then -- experimental
c.n = a.n * b.n -- 1
c.n = c.n - a.i * b.i -- 9
c.n = c.n - a.i * b.j
c.n = c.n - a.i * b.k
c.n = c.n - a.j * b.i
c.n = c.n - a.j * b.j
c.n = c.n - a.j * b.k
c.n = c.n - a.k * b.i
c.n = c.n - a.k * b.j
c.n = c.n - a.k * b.k
--
c.i = a.n * b.i -- 6
c.i = c.i + a.i * b.n
c.j = a.n * b.j
c.j = c.j + a.j * b.n
c.k = a.n * b.k
c.k = c.k + a.k * b.n
else -- real Quaternion
c.n = a.n * b.n -- 1
c.n = c.n - a.i * b.i -- 3
c.n = c.n - a.j * b.j
c.n = c.n - a.k * b.k
c.i = a.n * b.i -- 12
c.i = c.i + a.i * b.n
c.i = c.i + a.j * b.k
c.i = c.i - a.k * b.j
c.j = a.n * b.j
c.j = c.j + a.j * b.n
c.j = c.j + a.k * b.i
c.j = c.j - a.i * b.k
c.k = a.n * b.k
c.k = c.k + a.k * b.n
c.k = c.k + a.i * b.j
c.k = c.k - a.j * b.i
end
return c
end
neu.complex_subtraction = function (a, b)
if not type (a) == "table" then a = {n=a, i=0, j=0, k=0} end
if not type (b) == "table" then b = {n=b, i=0, j=0, k=0} end
local c = {}
for letter, v in pairs (a) do
local s = b[letter] or 0
c[letter] = v-s
end
return c
end
neu.complex_subtraction = function (a)
if not type (a) == "table" then a = {n=a, i=0, j=0, k=0} end
return neu.complex_multiplicate (a, a)
end
neu.get_cost = function (output_must, output_is)
local cost = 0
for output_node, output_value in pairs (output_is) do
cost = cost + neu.complex_square(neu.complex_subtraction(output_is, output_must)).n
end
end
return neu
|
--- === cp.apple.finalcutpro.cmd.Commands ===
---
--- The list of available commands (depending on search and/or [CommandGroup](cp.apple.finalcutpro.cmd.CommandGroups.md])
--- that can be mapped to a keyboard shortcut.
local require = require
--- local log = require "hs.logger".new "Commands"
local fn = require "cp.fn"
local ax = require "cp.fn.ax"
local chain = fn.chain
local Button = require "cp.ui.Button"
local Group = require "cp.ui.Group"
local Row = require "cp.ui.Row"
local ScrollArea = require "cp.ui.ScrollArea"
local Table = require "cp.ui.Table"
local TextField = require "cp.ui.TextField"
local Commands = ScrollArea:subclass("cp.apple.finalcutpro.cmd.Commands")
--- cp.apple.finalcutpro.cmd.Commands.matches(element) -> boolean
--- Function
--- Checks if the element matches the criteria for this class.
---
--- Parameters:
--- * element - An `axuielementObject` to check.
---
--- Returns:
--- * `true` if the element matches the criteria for this class.
Commands.static.matches = ax.matchesIf(ScrollArea.matches, chain // ax.childMatching(Table.matches))
function Commands:initialize(parent, uiFinder)
ScrollArea.initialize(
self, parent, uiFinder,
Table:withHeaderOf(
-- Example of using a basic cp.ui.Group:
-- Group:containing(Button, Button, Button)
-- Using the custom `Commands.Header`
Commands.Header
):withRowsOf(
-- Example of using cp.ui.Row:
-- Row:containing(TextField, TextField, TextField)
-- Using the custom `Commands.Row`
Commands.Row
)
)
end
--- === cp.apple.finalcutpro.cmd.Commands.Header ===
---
--- The header of the Commands.
Commands.Header = Group:subclass("cp.apple.finalcutpro.cmd.Commands.Header")
function Commands.Header:initialize(parent, uiFinder)
Group.initialize(self, parent, uiFinder, Button, Button, Button)
end
--- cp.apple.finalcutpro.cmd.Commands.Header.command <cp.ui.Button>
--- Field
--- The `Button` that can be pressed to sort by "Command". Pressing more than
--- once will alternate between ascending and descending.
function Commands.Header.lazy.value:command()
return self.children[1]
end
--- cp.apple.finalcutpro.cmd.Commands.Header.modifiers <cp.ui.Button>
--- Field
--- The `Button` that can be pressed to sort by "Modifiers". Pressing more than
--- once will alternate between ascending and descending.
function Commands.Header.lazy.value:modifiers()
return self.children[2]
end
--- cp.apple.finalcutpro.cmd.Commands.Header.key <cp.ui.Button>
--- Field
--- The `Button` that can be pressed to sort by "Key". Pressing more than
--- once will alternate between ascending and descending.
function Commands.Header.lazy.value:key()
return self.children[3]
end
--- === cp.apple.finalcutpro.cmd.Commands.Row ===
Commands.Row = Row:subclass("cp.apple.finalcutpro.cmd.Commands.Row")
function Commands.Row:initialize(parent, uiFinder)
Row.initialize(self, parent, uiFinder, TextField, TextField, TextField)
end
--- cp.apple.finalcutpro.cmd.Commands.Row.command <cp.ui.TextField>
--- Field
--- The command [TextField](cp.ui.TextField.md) (read-only).
function Commands.Row.lazy.value:command()
return self.children[1]
end
--- cp.apple.finalcutpro.cmd.Commands.Row.modifiers <cp.ui.TextField>
--- Field
--- The modifiers [TextField](cp.ui.TextField.md) (read-only)
function Commands.Row.lazy.value:modifiers()
return self.children[2]
end
--- cp.apple.finalcutpro.cmd.Commands.Row.key <cp.ui.TextField>
--- Field
--- The key [TextField](cp.ui.TextField.md) (read-only).
function Commands.Row.lazy.value:key()
return self.children[3]
end
return Commands
|
local logger = require "logger"
local SDL = require "SDL"
-- Calculo tablas para acelerar el acceso al video del Spectrum
-- arrays de words
-- Given the vertical coordinate of a pixel, gives the starting memory address for the pixels of the corresponding
-- pixel row.
local D_PixelAddressArray = {}
for y = 0, 191 do
D_PixelAddressArray[y] = 0x4000 + ((y >> 6) << 11) + (((y >> 3) & 0x07) << 5) + ((y & 0x07) << 8)
end
-- Given the vertical coordinate of a pixel, gives the starting memory address for the attributes of the corresponding
-- character row.
local D_AttribArray = {}
for y = 0, 191 do
D_AttribArray[y] = 0x5800 + ((y >> 3) << 5)
end
-- Attribute matrix [32,24]
local D_Atributos = {}
for i = 0,31 do
D_Atributos[i] = {}
end
--BYTE D_Atributos[32][24];
-- hack para saber si algo cambio en la pantalla, muy berreta
local dirty_pixels = {}
local dirty_attributes = {}
for i = 0, 191 do
dirty_attributes[i] = {}
end
---
-- TODO: Move this to a 'model' module. This values change with the machine type
--
local M_lineasBordeSup = 64
local M_lineasBordeInf = 56
local M_anchoBordeDer = 48
local M_anchoBordeIzq = 48
-- 24 bit colours
-- BRIGHT disabled
local colours_bright_off = {}
colours_bright_off[0] = (0x00000000);
colours_bright_off[1] = 159;
colours_bright_off[2] = (223<<16);
colours_bright_off[3] = ((224<<16)|(176));
colours_bright_off[4] = (208<<8);
colours_bright_off[5] = ((208<<8)|(208));
colours_bright_off[6] = ((207<<16)|(207<<8));
colours_bright_off[7] = ((192<<16)|(199<<8)|(192));
-- BRIGHT enabled
local colours_bright_on = {}
colours_bright_on[0] = (0x00000000);
colours_bright_on[1] = 175;
colours_bright_on[2] = (239<<16);
colours_bright_on[3] = ((255<<16)|(223));
colours_bright_on[4] = (239<<8);
colours_bright_on[5] = ((248<<8)|(255));
colours_bright_on[6] = ((255<<16)|(248<<8));
colours_bright_on[7] = ((255<<16)|(248<<8)|(255));
local display = {}
-- the one and only renderer
local rdr
display.flash_on = false
display.flash_counter = 0
display.machine = nil
local function draw_entire_screen_no_border (cpu)
local read_mem_byte_internal = display.machine.memory.read_mem_byte_internal
local D_tinta, D_papel
for y = 0, 23 do
for x = 0, 31 do
D_Atributos[x][y] = read_mem_byte_internal(cpu, x + D_AttribArray[y << 3])
end
end
for y = 0, 191 do
local linea = y >> 3
for x = 0, 31 do
local D_Attrib = D_Atributos[x][linea]
local D_PixelGroup = read_mem_byte_internal(cpu, x + D_PixelAddressArray[y])
if display.flash_on or (D_Attrib & 0x80 ~= 0) then -- flash?
D_tinta = (D_Attrib & 0x38) >> 3
D_papel = D_Attrib & 0x07
else
D_tinta = D_Attrib & 0x07
D_papel = (D_Attrib & 0x38) >> 3
end
-- Bright ON ?
local foreground, background
if D_Attrib & 0x40 ~= 0 then
foreground = colours_bright_on[D_tinta]
background = colours_bright_on[D_papel]
else
foreground = colours_bright_off[D_tinta]
background = colours_bright_off[D_papel]
end
-- If the pixels or the attributes of this 8x1 line have changed, repaint
if dirty_pixels[x + D_PixelAddressArray[y]] ~= D_PixelGroup or
dirty_attributes[x][y] ~= D_Attrib
then
dirty_pixels[x + D_PixelAddressArray[y]] = D_PixelGroup
dirty_attributes[x][y] = D_Attrib
for i = 7, 0, -1 do
if D_PixelGroup & (1 << i) ~= 0 then
rdr:setDrawColor(foreground)
else
rdr:setDrawColor(background)
end
rdr:drawPoint({x=x * 8 + 7 - i, y=y})
end
end
end
end
rdr:present()
end
local function draw_entire_screen_with_border (cpu)
local color_borde = display.machine.ports.port_fe & 0x07
local read_mem_byte_internal = display.machine.memory.read_mem_byte_internal
rdr:setDrawColor(colours_bright_off[color_borde])
for y = 0, M_lineasBordeSup - 1 do
rdr:drawLine({x1 = 0, y1 = y, x2 = M_anchoBordeIzq + 256 + M_anchoBordeDer, y2 = y})
end
local D_tinta, D_papel
for y = 0, 23 do
for x = 0, 31 do
D_Atributos[x][y] = read_mem_byte_internal(cpu, x + D_AttribArray[y << 3])
end
end
for y = 0, 191 do
local linea = y >> 3
rdr:setDrawColor(colours_bright_off[color_borde])
rdr:drawLine({x1 = 0, y1 = y + M_lineasBordeSup, x2 = M_anchoBordeIzq - 1, y2 = y + M_lineasBordeSup})
for x = 0, 31 do
local D_Attrib = D_Atributos[x][linea]
local D_PixelGroup = read_mem_byte_internal(cpu, x + D_PixelAddressArray[y])
-- TODO: flash does not work with the dirty attributes stuff
if display.flash_on and (D_Attrib & 0x80 ~= 0) then -- flash?
D_tinta = (D_Attrib & 0x38) >> 3
D_papel = D_Attrib & 0x07
else
D_tinta = D_Attrib & 0x07
D_papel = (D_Attrib & 0x38) >> 3
end
-- Bright ON ?
local foreground, background
if D_Attrib & 0x40 ~= 0 then
foreground = colours_bright_on[D_tinta]
background = colours_bright_on[D_papel]
else
foreground = colours_bright_off[D_tinta]
background = colours_bright_off[D_papel]
end
-- If the pixels or the attributes of this 8x1 line have changed, repaint
if dirty_pixels[x + D_PixelAddressArray[y] ] ~= D_PixelGroup or
dirty_attributes[x][y] ~= D_Attrib
then
dirty_pixels[x + D_PixelAddressArray[y] ] = D_PixelGroup
dirty_attributes[x][y] = D_Attrib
-- draw the background
rdr:setDrawColor(background)
rdr:drawLine({x1 = x * 8 + M_anchoBordeIzq, y1 = y + M_lineasBordeSup,
x2 = x * 8 + 7 + M_anchoBordeIzq, y2 = y + M_lineasBordeSup})
-- plot the foreground
local points = {}
rdr:setDrawColor(foreground)
for i = 7, 0, -1 do
if D_PixelGroup & (1 << i) ~= 0 then
points[#points + 1] = {x = x * 8 + 7 - i + M_anchoBordeIzq, y = y + M_lineasBordeSup}
else
end
end
rdr:drawPoints(points)
end
end
rdr:setDrawColor(colours_bright_off[color_borde])
rdr:drawLine({x1 = M_anchoBordeIzq + 256, y1 = y + M_lineasBordeSup, x2 = M_anchoBordeIzq + 256 + M_anchoBordeDer, y2 = y + M_lineasBordeSup})
end
rdr:setDrawColor(colours_bright_off[color_borde])
for y = 0, M_lineasBordeInf do
local offset = M_lineasBordeSup + 192
rdr:drawLine({x1 = 0, y1 = offset + y, x2 = M_anchoBordeIzq + 256 + M_anchoBordeDer, y2 = offset + y})
end
rdr:present()
end
--display.draw_screen = draw_entire_screen_no_border
display.draw_screen = draw_entire_screen_with_border
---
--
function display.initialize (win)
local err
rdr, err = SDL.createRenderer(win, 0, 1)
if not rdr then
error(err)
end
end
---
-- Signal that attributes needs to be reversed.
function display.toggle_flash ()
dirty_pixels = {}
display.flash_on = not display.flash_on
end
function display.set_machine (machine)
display.machine = machine
end
return display
|
--[[
Asset Loader and Manager
]]
local lib
local asset
asset = {
sound_directory = "asset/sound/",
image_directory = "asset/image/",
font_directory = "asset/font/",
loaded = {},
get = function(self, name)
return self.loaded[name]
end,
play_sound = function(self, name)
self.loaded[name]:stop()
self.loaded[name]:play()
end,
load_image = function(self, name, filename)
local image = love.graphics.newImage(self.image_directory .. filename)
self.loaded[name] = image
return image
end,
load_sound = function(self, name, filename, type)
local sound = love.audio.newSource(self.sound_directory .. filename, type or "static")
self.loaded[name] = sound
return sound
end,
load_world_sound = function(self, name, filename)
local sound = love.audio.newSource(self.sound_directory .. filename, "static")
sound:setDistance(50, 500)
sound:setRolloff(0.2)
sound:setPosition(0, 0, 0)
self.loaded[name] = sound
return sound
end,
load_font = function(self, name, size)
local font = love.graphics.newFont(size)
self.loaded[name] = font
return font
end,
load_font_file = function(self, name, path, size)
local font = love.graphics.newFont(self.font_directory .. path, size)
self.loaded[name] = font
return font
end,
init = function(self, engine)
lib = engine.lib
end
}
return asset
|
bt.register_action("SetWaypointHere", {
tick = function(node, data)
local pos = {x= data.pos.x, y= data.pos.y, z= data.pos.z}
data.waypoints[node.wpname] = pos
return "success"
end,
ctor = function(name)
return {
wpname=name or "_"
}
end,
})
bt.register_action("SetWaypoint", {
tick = function(node, data)
if data.targetPos == nil then
return "failed"
end
local pos = {x= data.targetPos.x, y= data.targetPos.y, z= data.targetPos.z}
data.waypoints[node.wpname] = pos
return "success"
end,
ctor = function(name)
return {
wpname=name or "_"
}
end,
})
bt.register_action("GetWaypoint", {
tick = function(node, data)
if data.waypoints[node.wpname] == nil then
return "failed"
end
local wp = data.waypoints[node.wpname]
data.targetPos = {
x = wp.x,
y = wp.y,
z = wp.z,
}
return "success"
end,
ctor = function(name)
return {
wpname=name or "_"
}
end,
})
bt.register_action("SetGroupWaypoint", {
tick = function(node, data)
if data.targetPos == nil or data.groupID == nil or mobehavior.groupData[data.groupID] == nil then
return "failed"
end
local pos = {x= data.targetPos.x, y= data.targetPos.y, z= data.targetPos.z}
mobehavior.groupData[data.groupID].waypoints[node.wpname] = pos
return "success"
end,
ctor = function(name)
return {
wpname=name or "_"
}
end,
})
bt.register_action("GetGroupWaypoint", {
tick = function(node, data)
if data.groupID == nil
or mobehavior.groupData[data.groupID] == nil
or mobehavior.groupData[data.groupID].waypoints == nil
or mobehavior.groupData[data.groupID].waypoints[node.wpname] == nil then
-- debug -- print(dump(mobehavior.groupData[data.groupID]))
-- debug -- print("! failed to find group ("..data.groupID..") waypoint " .. node.wpname .. "\n")
return "failed"
end
local wp = mobehavior.groupData[data.groupID].waypoints[node.wpname]
data.targetPos = {
x = wp.x,
y = wp.y,
z = wp.z,
}
return "success"
end,
ctor = function(name)
return {
wpname=name or "_"
}
end,
})
bt.register_action("CreatePathHere", {
tick = function(node, data)
if data.pos == nil then
return "failed"
end
local pos = {x= data.pos.x, y= data.pos.y, z= data.pos.z}
data.paths[node.pname] = {pos}
return "success"
end,
ctor = function(name) return { pname=name or "_" } end,
})
bt.register_action("CreatePath", {
tick = function(node, data)
if data.targetPos == nil then
return "failed"
end
local pos = {x= data.targetPos.x, y= data.targetPos.y, z= data.targetPos.z}
data.paths[node.pname] = {pos}
return "success"
end,
ctor = function(name) return { pname=name or "_" } end,
})
bt.register_action("AddPathNodeHere", {
tick = function(node, data)
if data.pos == nil then
return "failed"
end
local pos = {x= data.pos.x, y= data.pos.y, z= data.pos.z}
table.insert(data.paths[node.pname], pos)
return "success"
end,
ctor = function(name) return { pname=name or "_" } end,
})
bt.register_action("AddPathNode", {
tick = function(node, data)
if data.targetPos == nil then
return "failed"
end
local pos = {x= data.targetPos.x, y= data.targetPos.y, z= data.targetPos.z}
table.insert(data.paths[node.pname], pos)
return "success"
end,
ctor = function(name) return { pname=name or "_" } end,
})
bt.register_action("PointsAlongPath", {
tick = function(node, data)
if data.paths[node.pname] == nil then
return "failed"
end
local path = data.paths[node.pname]
if not node.initialized then
node.cur_pos = vector.round(path[1])
node.next_seg = 2
node.done = false
node.initialized = true
node.cur_dist = 0
node.dist = distance3(path[1], path[2])
end
if node.done then
node.initialized = false
return "failed"
end
data.targetPos = vcopy(node.cur_pos)
local dir = vector.normalize(
vector.subtract(
path[node.next_seg],
path[node.next_seg - 1]
)
)
while true do
local next_pos = vector.round(
vector.add(
path[node.next_seg - 1],
vector.multiply(dir, node.cur_dist)
)
)
node.cur_dist = node.cur_dist + 1
if node.cur_dist - 0.1 > node.dist then
if #path <= node.next_seg then
node.done = true
else
node.next_seg = node.next_seg + 1
node.cur_dist = 0
node.dist = distance3(path[node.next_seg-1], path[node.next_seg])
end
end
if not vector.equals(node.cur_pos, next_pos) then
node.cur_pos = next_pos
break
end
end
return "success"
end,
ctor = function(name)
return {
pname=name or "_",
cur_pos = {x=0, y=0, z=0},
next_seg = 2,
done = false,
initialized = false,
}
end,
})
bt.register_action("PointsAlongPath2", {
tick = function(node, data)
if data.paths[node.pname] == nil then
return "failed"
end
local path = data.paths[node.pname]
if not node.initialized then
node.cur_pos = vector.round(path[1])
node.next_seg = 2
node.done = false
node.initialized = true
node.cur_dist = 0
node.dist = distance3(path[1], path[2])
end
if node.done then
node.initialized = false
return "failed"
end
data.targetPos = vcopy(node.cur_pos)
local dir = vector.normalize(
vector.subtract(
path[node.next_seg],
path[node.next_seg - 1]
)
)
while true do
local next_pos = vector.round(
vector.add(
path[node.next_seg - 1],
vector.multiply(dir, node.cur_dist)
)
)
node.cur_dist = node.cur_dist + 1
if node.cur_dist > node.dist then
if #path <= node.next_seg then
node.done = true
else
node.next_seg = node.next_seg + 1
node.cur_dist = 0
node.dist = distance3(path[node.next_seg-1], path[node.next_seg])
end
end
if not (node.cur_pos.x == next_pos.x and node.cur_pos.z == next_pos.z) then
node.cur_pos = next_pos
break
end
end
return "success"
end,
ctor = function(name)
return {
pname=name or "_",
cur_pos = {x=0, y=0, z=0},
next_seg = 2,
done = false,
initialized = false,
}
end,
})
|
local path = "games/common/game_result/anim/coin_rotate_pin.png"
local coin_rotate_pin_map = {
["9.png"] = {
file=path,
x=2,y=2,
width=70,height=70,
rotated=false
},
["2.png"] = {
file=path,
x=74,y=2,
width=70,height=70,
rotated=false
},
["4.png"] = {
file=path,
x=146,y=2,
width=70,height=70,
rotated=false
},
["7.png"] = {
file=path,
x=2,y=74,
width=70,height=70,
rotated=false
},
["1.png"] = {
file=path,
x=74,y=74,
width=70,height=70,
rotated=false
},
["8.png"] = {
file=path,
x=146,y=74,
width=70,height=70,
rotated=false
},
["5.png"] = {
file=path,
x=2,y=146,
width=70,height=70,
rotated=false
},
["10.png"] = {
file=path,
x=74,y=146,
width=70,height=70,
rotated=false
},
["3.png"] = {
file=path,
x=146,y=146,
width=70,height=70,
rotated=false
},
["6.png"] = {
file=path,
x=218,y=2,
width=70,height=70,
rotated=false
},
["11.png"] = {
file=path,
x=290,y=2,
width=70,height=70,
rotated=false
},
}
return coin_rotate_pin_map
|
#!/usr/bin/env tarantool
local tap = require('tap')
local popen = require('popen')
local process_timeout = require('process_timeout')
local fio = require('fio')
local clock = require('clock')
local fiber = require('fiber')
--
-- gh-2717: tarantool console quit on sigint.
--
local file_read_timeout = 60.0
local file_read_interval = 0.2
local file_open_timeout = 60.0
local prompt = 'tarantool> '
local TARANTOOL_PATH = arg[-1]
local test = tap.test('gh-2717-no-quit-sigint')
test:plan(6)
local cmd = 'ERRINJ_STDIN_ISATTY=1 ' .. TARANTOOL_PATH .. ' -i 2>&1'
local ph = popen.new({cmd}, {
shell = true,
setsid = true,
group_signal = true,
stdout = popen.opts.PIPE,
stderr = popen.opts.DEVNULL,
stdin = popen.opts.PIPE,
})
assert(ph, 'process is not up')
local start_time = clock.monotonic()
local time_quota = 10.0
local output = ''
while output:find(prompt) == nil
and clock.monotonic() - start_time < time_quota do
output = output .. ph:read({timeout = 1.0})
end
assert(clock.monotonic() - start_time < time_quota, 'time_quota is violated')
ph:signal(popen.signal.SIGINT)
while output:find(prompt .. '^C\n---\n...\n\n' .. prompt) == nil and
clock.monotonic() - start_time < time_quota do
local data = ph:read({timeout = 1.0})
if data ~= nil then
output = output .. data
end
end
assert(clock.monotonic() - start_time < time_quota, 'time_quota is violated')
test:unlike(ph:info().status.state, popen.state.EXITED,
'SIGINT doesn\'t kill tarantool in interactive mode')
test:like(output, prompt .. '^C\n---\n...\n\n' .. prompt,
'Ctrl+C discards the input and calls the new prompt')
ph:shutdown({stdin = true})
ph:close()
--
-- gh-2717: testing daemonized tarantool on signaling INT
-- and nested console output.
--
local log_file = fio.abspath('tarantool.log')
local pid_file = fio.abspath('tarantool.pid')
local xlog_file = fio.abspath('00000000000000000000.xlog')
local snap_file = fio.abspath('00000000000000000000.snap')
local sock = fio.abspath('tarantool.soc')
local user_grant = ' box.schema.user.grant(\'guest\', \'super\')'
local arg = ' -e \"box.cfg{pid_file=\''
.. pid_file .. '\', log=\'' .. log_file .. '\', listen=\'unix/:'
.. sock .. '\'}' .. user_grant .. '\"'
start_time = clock.monotonic()
time_quota = 10.0
os.remove(log_file)
os.remove(pid_file)
os.remove(xlog_file)
os.remove(snap_file)
local ph_server = popen.shell(TARANTOOL_PATH .. arg, 'r')
local f = process_timeout.open_with_timeout(log_file, file_open_timeout)
assert(f, 'error while opening ' .. log_file)
cmd = 'ERRINJ_STDIN_ISATTY=1 ' .. TARANTOOL_PATH .. ' -i 2>&1'
local ph_client = popen.new({cmd}, {
shell = true,
setsid = true,
group_signal = true,
stdout = popen.opts.PIPE,
stderr = popen.opts.DEVNULL,
stdin = popen.opts.PIPE,
})
assert(ph_client, 'the nested console is not up')
ph_client:write('require("console").connect(\'unix/:' .. sock .. '\')\n')
local client_data = ''
while string.endswith(client_data, 'unix/:' .. sock .. '>') == nil
and clock.monotonic() - start_time < time_quota do
local cur_data = ph_client:read({timeout = 3.0})
if cur_data ~= nil and cur_data ~= '' then
client_data = client_data .. cur_data
end
end
assert(clock.monotonic() - start_time < time_quota, 'time_quota is violated')
start_time = clock.monotonic()
ph_client:signal(popen.signal.SIGINT)
test:unlike(ph_client:info().status.state, popen.state.EXITED,
'SIGINT doesn\'t kill nested tarantool in interactive mode')
while string.endswith(client_data, 'C\n---\n...\n\nunix/:' .. sock .. '>') == nil
and clock.monotonic() - start_time < time_quota do
local cur_data = ph_client:read({timeout = 3.0})
if cur_data ~= nil and cur_data ~= '' then
client_data = client_data .. cur_data
end
end
assert(clock.monotonic() - start_time < time_quota, 'time_quota is violated')
ph_server:signal(popen.signal.SIGINT)
local status = ph_server:wait(nil, popen.signal.SIGINT)
test:unlike(status.state, popen.state.ALIVE,
'SIGINT terminates tarantool in daemon mode')
start_time = clock.monotonic()
local data = ''
while data:match('got signal 2') == nil
and clock.monotonic() - start_time < time_quota do
data = data .. process_timeout.read_with_timeout(f,
file_read_timeout,
file_read_interval)
end
assert(data:match('got signal 2'), 'there is no one note about SIGINT')
assert(clock.monotonic() - start_time < time_quota, 'time_quota is violated')
f:close()
ph_server:close()
ph_client:close()
os.remove(log_file)
os.remove(pid_file)
os.remove(xlog_file)
os.remove(snap_file)
--
-- Testing case when the client and instance are called in the same console.
--
cmd = 'ERRINJ_STDIN_ISATTY=1 ' .. TARANTOOL_PATH .. ' -i 2>&1'
ph = popen.new({cmd}, {
shell = true,
setsid = true,
group_signal = true,
stdout = popen.opts.PIPE,
stderr = popen.opts.DEVNULL,
stdin = popen.opts.PIPE,
})
assert(ph, 'process is not up')
start_time = clock.monotonic()
time_quota = 10.0
output = ''
while output:find(prompt) == nil
and clock.monotonic() - start_time < time_quota do
data = ph:read({timeout = 1.0})
if data ~= nil then
output = output .. data
end
end
assert(clock.monotonic() - start_time < time_quota, 'time_quota is violated')
prompt = 'unix/:' .. sock .. '> '
ph:write('_ = require(\'console\').listen(\'' .. sock .. '\')\n',
{timeout = 1.0})
ph:write('_ = require(\'console\').connect(\'' .. sock .. '\')\n',
{timeout = 1.0})
fiber.sleep(0.2)
ph:signal(popen.signal.SIGINT)
start_time = clock.monotonic()
while string.endswith(output, prompt .. '^C\n---\n...\n\n' .. prompt) == false
and clock.monotonic() - start_time < time_quota do
local data = ph:read({timeout = 1.0})
if data ~= nil then
output = output .. data
end
end
assert(clock.monotonic() - start_time < time_quota, 'time_quota is violated')
test:ok(string.endswith(output, prompt .. '^C\n---\n...\n\n' .. prompt),
'Ctrl+C discards the input and calls the new prompt')
test:unlike(ph:info().status.state, popen.state.EXITED,
'SIGINT doesn\'t kill tarantool in interactive mode')
ph:shutdown({stdin = true})
ph:close()
os.exit(test:check() and 0 or 1)
|
-- See LICENSE for terms
local options
local mod_GlobalDomeCount
local mod_RespectIncubator
local mod_BypassNoNurseries
local mod_UltimateNursery
-- fired when settings are changed/init
local function ModOptions()
mod_GlobalDomeCount = options:GetProperty("GlobalDomeCount")
mod_RespectIncubator = options:GetProperty("RespectIncubator")
mod_BypassNoNurseries = options:GetProperty("BypassNoNurseries")
mod_UltimateNursery = options:GetProperty("UltimateNursery")
end
-- load default/saved settings
function OnMsg.ModsReloaded()
options = CurrentModOptions
ModOptions()
end
-- fired when option is changed
function OnMsg.ApplyModOptions(id)
if id ~= CurrentModId then
return
end
ModOptions()
end
local Max = Max
local orig_SpawnChild = Dome.SpawnChild
function Dome:SpawnChild(...)
-- hi Ski
if mod_RespectIncubator and self.IncubatorReloc then
return orig_SpawnChild(self, ...)
end
local class = mod_UltimateNursery and "UltimateNursery" or "Nursery"
local objs_g = (self.city or UICity).labels[class]
local objs
-- not global so use dome count
if mod_GlobalDomeCount then
objs = objs_g
else
objs = self.labels[class]
end
-- no nursery so abort
if not objs then
-- if there's no nurseries at all and then send back orig func
if not objs_g and mod_BypassNoNurseries then
return orig_SpawnChild(self, ...)
end
return
end
-- cut down copy of function Dome:GetFreeLivingSpace()
local used = 0
local capacity = 0
for i = 1, #objs do
local obj = objs[i]
if not obj.destroyed then
capacity = capacity + (obj.capacity - obj.closed)
used = used + (#obj.colonists + #obj.reserved)
end
end
local free_space = Max(0, capacity - used)
--~ print(free_space,ChoGGi.ComFuncs.RetName(self))
-- fire up the babby factory
if free_space > 0 then
return orig_SpawnChild(self, ...)
end
end
|
return {
name = "phantom-token",
fields = {{
config = {
type = "record",
fields = {
{ introspection_endpoint = { type = "string", required = true } },
{ client_id = { type = "string", required = true } },
{ client_secret = { type = "string", required = true } },
{ token_cache_seconds = { type = "number", required = true, default = 0 } },
{ scope = { type = "string", required = false } },
{ verify_ssl = { type = "boolean", required = true, default = true } },
{ trusted_web_origins = { type = "array", required = false, default = {}, elements = { type = "string" } } },
}
}}
}
}
|
function loop(n)
local ret = ""
local last = ""
for i = 2, n do
ret = last.."ret"..i
last = "last"..i
end
return ret
end
local N = 1000000
print(loop(N))
|
--[[
Mock version of ContextActionService so we can simulate input.
Because this is all tested from studio and we need it to be automatic, this
allows us to fake key presses and other input types so that we're fairly
certain everything will work in a live game.
]]
local t = require(script.Parent.t)
local types = require(script.Parent.types)
local MockContextActionService = {
_actions = {},
}
function MockContextActionService:BindActionAtPriority(name, callback, createTouchButton, priority, ...)
self._actions[name] = {
name = name,
callback = callback,
createTouchButton = createTouchButton,
priority = priority,
inputTypes = { ... }
}
end
function MockContextActionService:UnbindAction(name)
self._actions[name] = nil
end
function MockContextActionService:GetActionsForInputType(inputType)
local actions = {}
for _, action in pairs(self._actions) do
for _, otherInputType in ipairs(action.inputTypes) do
if inputType == otherInputType then
table.insert(actions, action)
end
end
end
return actions
end
local SimulateInputCheck = t.tuple(
types.InputType,
t.optional(t.array(t.enum(Enum.UserInputState)))
)
function MockContextActionService:SimulateInput(inputType, inputStates)
assert(SimulateInputCheck(inputType, inputStates))
inputStates = inputStates or {
Enum.UserInputState.Begin,
Enum.UserInputState.End
}
local actions = self:GetActionsForInputType(inputType)
for _, action in ipairs(actions) do
for _, inputState in ipairs(inputStates) do
-- Fake InputObject so we can check what the state was
local inputObject = {
UserInputState = inputState,
}
action.callback(action.name, inputState, inputObject)
end
end
end
function MockContextActionService:SimulateInputBegin(inputType)
assert(types.InputType(inputType))
self:SimulateInput(inputType, { Enum.UserInputState.Begin })
end
function MockContextActionService:SimulateInputEnd(inputType)
assert(types.InputType(inputType))
self:SimulateInput(inputType, { Enum.UserInputState.End })
end
return MockContextActionService
|
ruRU_questgiver_greeting = {
[""..st_c..", eh? i am krazek, baron revilgaz's secretary. i know everything about the goings on in this jungle and beyond. perhaps you'd be interested in knowing the going price on oil in ratchet? no? looking for work, maybe? i can help you there."] = ""..ST_C..", а? Я Кразек, секретарь барона Ревилгаза. Я знаю все, что происходит в этих джунглях и за их пределами. Возможно, тебе будет интересно узнать цену на нефть в Кабестане? Нет? Может быть, ты ищешь работу? Я могу помочь тебе здесь.",
["a foul corruption has crept into westfall. while i was upholding my duty on the battlefields of lordaeron these honest farms were overrun and made into hide-outs for thugs and murderers. the people's militia needs your help."] = "Проклятая коррупция прокралась в Западный Край. Пока я нес свою службу на полях сражений Лордерона, эти фермы были захвачены и превращены в убежища бандитов и убийц. Народному ополчению нужна твоя помощь.",
["ah, you there! i have tasks to give, and i need not waste time explaining their crucial nature. listen close."] = "А вот и ты! У меня есть для тебя несколько задач, но нет времени на их разъяснение. Так что слушай внимательно.",
["corruption sneaks into nature's grove. the forest must be protected at all costs."] = "Порча пробирается в рощу природы. Лес должен быть защищен любой ценой.",
["curse that brewers' league! they have access to all the best ingredients, while we're stuck here grubbing for grain and hops!"] = "Проклятая лига пивоваров! У них есть все лучшие ингредиенты, в то время как мы застряли здесь с зерном и шишками хмеля!",
["dark forces encroach upon our borders, ancient taints resurface, and new evils emerge to topple the delicate balance of the land. in times of such darkness, we all must be vigilant."] = "Темные силы посягают на наши границы, возрождается древняя зараза, появляется новое зло желающее разрушить тонкий баланс земли. В эти темные времена мы все должны быть бдительны.",
["don't let the heat bother you. in the badlands, heat is the least of your worries."] = "Не позволяй жаре беспокоить себя. В Бесплодных землях она наименьшая из проблем.",
["for our people to survive, we must study the ways of nature and learn its secrets."] = "Чтобы выжили наши люди, мы должны изучить пути природы и познать ее секреты.",
["greetings, "..st_c.."! fine day for hunting, wouldn't you say? i've been having more than a little luck with boars, myself. perhaps you'd like a shot?"] = "Приветствую, "..ST_C.."! Прекрасный день для охоты, не правда ли? У меня не большие проблемы с кабанами. Не желаешь поохотиться?",
["greetings, "..st_c..". be wary as you travel east toward the bulwark. recent surveillance reports indicate increased scourge activity in that area, so exercise caution."] = "Приветствую тебя, "..ST_C..". Если ты направишься в Бастион, то будь "..ST_G("осторожен", "осторожна")..". Недавние отчеты разведки указывают на увеличение активности Плети в этом районе.",
["greetings, "..ST_G("lad", "lass")..". i'm grelin whitebeard. i'm here to examine the threat posed by the growing numbers of trolls in coldridge valley. what have i found? it's a bit troubling..."] = "Привет. Я Грелин Белобород. Здесь я изучаю угрозу, исходящую от растущего числа троллей в Холодной долине. Что я нашел? Это и беспокоит...",
["hello there, "..st_c..". normally i'd be out on the beat looking after the folk of stormwind, but a lot of the stormwind guards are fighting in the other lands. so here i am, deputized and offering bounties when i'd rather be on patrol..."] = "Приветствую тебя, "..ST_C..". Обычно я присматриваю за народом Штормграда, но в это тяжелое время, многие наши стражники ушли на сражения в другие края. И вот теперь, вместо того чтобы вести патруль, я как заместитель, предлагаю вознаграждение за оказанную помощь...",
["hello! the spirits say you here to aid my chief. say it loud, they do."] = "Привет! Духи говорят что ты "..ST_G("пришел", "пришла").." чтобы оказать помощь.",
["hello, "..st_n..". perhaps you have some time to chat?"] = "Привет, "..ST_N..". У тебя не найдется времени поговорить?",
["hello, citizen. you look like a "..ST_G("man", "woman").." with a purpose - do you have business with the stormwind army?"] = "Приветствую, "..ST_G("гражданин", "гражданка")..". Ты не выглядишь "..ST_G("праздным", "праздной").." зевакой. Что за дело привело тебя в Армию Штормграда?",
["hey there, friend. my name's remy. i'm from redridge to the east, and came here looking for business, looking for business. you got any...got any??"] = "Послушай "..ST_G("приятель", "приятельница")..". Меня зовут Реми. Я с востока Красногорья, а сюда пришел за делом, да, за делом. У тебя не найдется дела? Не найдется?",
["how perfect of you to come by, "..st_c..". my name is lotwil veriatus, founding member of the enlightened assembly of arcanology, alchemy, and engineering sciences: we seek to blend the intelligent sciences of azeroth together into one comprehensive school."] = "Как хорошо, что ты здесь, "..ST_C..".\n\nМеня зовут Лотвиль Вериатус и я состою в Просвещенной Ассамблее Чародейства, Алхимии и Технических Наук. Мы стремимся объединить интеллектуальные науки Азерота в одну общеобразовательную школу.",
["i hope you're well, all things considered. sit for a spell, and hear my tale. it's a tragedy, of course, but one i hope will end in revenge!"] = "Учитывая все обстоятельства, надеюсь, ты хорошо себя чувствуешь.\n\nПрисаживайся и выслушай мой рассказ, трагедию, которая я надеюсь закончиться местью!",
["i welcome you back, "..st_n.."."] = "Приветствую тебя, "..ST_N..".",
["if i can get the proper ingredients, we can create some explosives that will not only allow me to damage the venture's co.'s operations, but also cause a distraction. i know you're impressed, but it gets better... i'll tell you more soon enough."] = "Если я заполучу все необходимые ингредиенты, я смогу создать взрывчатку, которая не только нанесет урон Торговой Компании, но еще и отвлечет ее.\n\nЯ знаю что тебя это впечатлило, но еще лучше... обо всем остальном я расскажу тебе позже.",
["if we are to make our place in this world, then we will do so through study, and through the will to ignore our fading human instincts."] = "Если мы хотим занять свое место в этом мире, мы должны заниматься исследованиями, а также игнорировать наши угасающие человеческие инстинкты.",
["information... with our scouts and agents, we control the flow of information in lordaeron. scourge movements, their holdings, all underneath our watchful eyes..."] = "Информация... Благодаря нашим разведчикам и агентам мы контролируем поток информации в Лордероне. Передвижение Плети, их запасы, все под нашим бдительным оком...",
["my family boasts the finest collection of jewelry and objects of fine art among all the nobles of stormwind! and we are always wishing to increase the size our collection..."] = "Моя семья может похвастаться лучшей коллекцией ювелирных изделий и предметами искусства среди всех дворян Штормграда!\n\nИ мы всегда жаждем расширить свою коллекцию...",
["nothing but trouble in these parts. i tried to tell that fool saldean to get out while he still could but he won't hear of it. but i ain't no fool. verna and i are gonna mosey on out as soon as we get this wagon fixed."] = "В этих краях нет ничего кроме неприятностей. Я пытался сказать этому глупцу Сальдену чтобы он уходил пока может, но он не хотел и слышать об этом. Но я не глупец, как только мы с Верной починим эту повозку, сразу уедем отсюда.",
["some people wonder what we're doing out here in the desert. well... if i told you, then you'd stay and try to make our profits!"] = "Некоторые задаются вопросом, чем мы занимаемся здесь, в пустыне. Что ж... если я расскажу тебе, тогда ты останешься здесь и попытаешься получить от этого нашу прибыль!",
["something i can help you with, "..st_n.."? there's a shipment i've got to see to otherwise."] = "Я чем-то могу помочь тебе, "..ST_N.."? А то меня ждет партия товара.",
["sometimes i think there's a big gray cloud in the sky, just raining down bad luck upon us. first, we're driven off our land, and now we can't even get out of westfall. everything's a mess. something needs to be done."] = "Иногда мне кажется, что в небе есть огромное серое облако, которое льет на нас дождем невезенья. Сперва у нас отобрали нашу землю, а теперь мы даже не можем выбраться из Западного Края. Все это неправильно и с этим нужно что-то делать.",
["the dark lady has put forth the challenge. it is up to us to meet it."] = "Темная Госпожа поставила нам задачу, и мы должны решить ее.",
["the dark lady has put the challenge forth. now it is up to the royal apothecary society to develop a new plague. we shall bring arthas and his wretched army to their knees."] = "Темная Госпожа поручила Королевскому фармацевтическому обществу разработать новую чуму. Мы поставим Артаса и его мерзкую армию на колени.",
["the land, the water and the sky are all as one. it is your eyes that deceive you with such separation. the earthmother is all those things and more."] = "Земля, вода и небо едины. Разделение существует только в твоих глазах. Мать-Земля заключает в себя все, и даже более этого.",
["the name's bilgewhizzle, and i am the chief engineer of the gadgetzan water company. what can i assist you with?"] = "Меня зовут Чепухастер и я главный инженер компании \"Воды Прибамбасска\". Чем я могу помочь тебе?",
["the scarlet crusade is encroaching on our homeland. the foolish zealots do not realize that the loyal servants of the dark lady shall see to their demise."] = "Алый орден вторгся в наши земли. Эти глупые фанатики еще не понимают, что верные слуги Темной Госпожи увидят их кончину.",
["the wind whispers to those who listen... do you hear it?"] = "Ветер шепчет тем, кто слушает...\n\nТы слышишь его?",
["there is something you wish to discuss, "..st_c.."... come, sit by me."] = "Есть кое-что, что нужно обсудить, "..ST_C.."... проходи, присаживайся.",
["this cauldron churns with thick, green bubbles. skulls, bones and organs of unknown creatures swim within its viscous broth... and rising lazily to the surface are the skulls of two, once mighty trolls: gan'zulah and nezzliok."] = "Котел бурлит большими зелеными пузырями. Черепа, кости, органы неизвестных существ плавают внутри этого вязкого бульона...\n\nНа поверхность лениво всплывают черепа двух некогда могучих троллей, Ган'зулаха и Неззилока.",
["this sty's a little shy of comfy, but it has history, so stonard must be important to someone. i'd gamble that's why we stay here. it sure ain't for the view--it don't even look like home."] = "Здесь конечно тот еще свинушник, но у этого места есть своя история, и должно быть Каменор очень значим для кого-то. Я люблю приключения и поэтому остановился здесь, в месте, которое даже домом назвать сложно...",
["thrall paid me and my boys well for helping out with the construction of orgrimmar, so i decided to set up a port here. we do most of our business through booty bay and baron revilgaz."] = "Тралл заплатил мне и моим ребятам за помощь в строительстве Оргриммара, так что я решил основать здесь порт. В основном мы обделываем делишки в Пиратской Бухте, через барона Ревилгаза.",
["throm'ka, "..st_c..". there is little time for talk and much work to be done."] = "Тром'ка, "..ST_C.."! Так мало времени для разговоров и так много работы предстоит сделать.",
["we elves have a long history. let us hope this history does not return to haunt us."] = "У нас эльфов большая история. Будем надеяться, что она никогда не повторится, и не будет преследовать нас.",
["we may not be in open war with the alliance, but blood is still shed between us."] = "Может мы и не в открытой войне с Альянсом, но между нами все еще льется кровь.",
["we're here to make a profit. and having our goods stolen is no way to make a profit."] = "Мы здесь ради прибыли, а украденные товары этому не способствуют.",
["welcome to our humble abode! it's always nice to see a friendly face. and what strong arms you have. my husband and i are always looking for help around the farm. now that most the good folk have left, it's hard to find an able body to help out."] = "Добро пожаловать в наш скромный обитель! Всегда приятно видеть дружелюбное лицо. Какое у тебя крепкое оружие, а нам с мужем всегда нужна помощь в округе нашей фермы, ведь теперь, когда большинство людей ушло, сложно найти кого-то, кто способен помочь.",
["well, hello there. you seem like you wouldn't be opposed to making some coin, hm? i can tell from the look in your eyes. i am mogul kebok, overseer of operations in azeroth, and if it is riches you seek, perhaps i can make arrangements."] = "Ну, привет. Судя по твоим глазам, ты не откажешься от лишних звенящих монет, а? Я Могул Кебок, контролирую все операции в Азероте, и если ты ищешь богатства, возможно, мы сможем договориться.",
["well, if it isn't a young, bristling "..st_c..", no doubt drawn here by talk of my exploits in fields of battle! no time for stories now, for there are great, important deeds that need doing! so if you're looking for glory, then luck shines on you today..."] = "Ну, кто это, как не "..ST_C..", что рвется на поле брани со всем юным пылом? Несомненно, тебя привлекли сюда слухи о моих подвигах.\n\nСейчас не время для замшелых историй, но время для великих и доблестных свершений! Если ты ищешь славы, то сегодня удача улыбнулась тебе.",
["what what?!? we all have profit to make... and we won't do it by standing idle."] = "Что-что?! Мы все получаем прибыль, занимаясь... и останься мы без дела, у нас ничего этого не будет.",
["yes yes yes! you're just the "..st_r.." i'm looking for! sit! we have much to discuss!!"] = "Да, да, да! Именно тебя мне и нужно, "..ST_R.."!\n\nПрисаживайся! Нам нужно многое обсудить!",
["you will be tested many times by the darkness that surrounds our lands, "..st_n..". but to ensure you are always prepared, we will often ask tasks of you so you are at the height of your own power. go with the light, and remain virtuous."] = "Ты не однократно будешь проходить испытания во тьме, окружающей наши земли, "..ST_N..". Но чтобы ты всегда "..ST_G("был", "была").." наготове и сила твоя не ослабла, мы будем часто поручать тебе задания.\n\nСтупай со Светом и оставайся "..ST_G("добродетельным", "добродетельной")..".",
}
|
return {
whitelist_globals = {
['.'] = {
'instance', 'accessors', 'properties', 'include', 'parent', 'static', 'meta', 'missing_property', 'super', 'new'
},
["spec"] = {
'it', 'describe', 'before_each', 'before', 'after', 'after_each',
'raise', 'spy', 'context', 'setup', 'teardown', 'moon'
}
}
}
|
local config = {}
function config.nvim_lsp()
require('modules.completion.lspconfig')
end
function config.telescope()
if not packer_plugins['plenary.nvim'].loaded then
vim.cmd [[packadd plenary.nvim]]
vim.cmd [[packadd popup.nvim]]
end
require('telescope').setup {
defaults = {
layout_config = {prompt_position = "top"},
sorting_strategy = 'ascending',
file_previewer = require'telescope.previewers'.vim_buffer_cat.new,
grep_previewer = require'telescope.previewers'.vim_buffer_vimgrep.new,
qflist_previewer = require'telescope.previewers'.vim_buffer_qflist.new,
file_ignore_patterns = { "node_modules", "vendor" },
},
extensions = { }
}
end
function config.smart_input()
require('smartinput').setup {
['go'] = { ';',':=',';' }
}
end
function config.vim_cursorwod()
vim.api.nvim_command('augroup user_plugin_cursorword')
vim.api.nvim_command('autocmd!')
vim.api.nvim_command('autocmd FileType NvimTree,lspsagafinder,dashboard,vista let b:cursorword = 0')
vim.api.nvim_command('autocmd WinEnter * if &diff || &pvw | let b:cursorword = 0 | endif')
vim.api.nvim_command('autocmd InsertEnter * let b:cursorword = 0')
vim.api.nvim_command('autocmd InsertLeave * let b:cursorword = 1')
vim.api.nvim_command('augroup END')
end
return config
|
local mod = DBM:NewMod(1470, "DBM-Party-Legion", 10, 707)
local L = mod:GetLocalizedStrings()
mod:SetRevision(("$Revision: 15190 $"):sub(12, -3))
mod:SetCreatureID(95888)
mod:SetEncounterID(1818)
mod:SetZone()
mod:RegisterCombat("combat")
mod:RegisterEventsInCombat(
"SPELL_CAST_START 213576 213583 197251 213685 197422",
"SPELL_AURA_APPLIED 205004",
"SPELL_AURA_REMOVED 206567 197422",
"UNIT_SPELLCAST_SUCCEEDED boss1"
)
local warnDeepeningShadows = mod:NewSpellAnnounce(213583, 4)
local warnVengeance = mod:NewSpellAnnounce(205004, 4)
local specWarnKick = mod:NewSpecialWarningSpell(197251, "Tank", nil, nil, 3, 2)
local specWarnDeepeningShadows = mod:NewSpecialWarningMoveTo(213583, nil, DBM_CORE_AUTO_SPEC_WARN_OPTIONS.spell:format(213583), nil, 3, 6)
local specWarnHiddenStarted = mod:NewSpecialWarningSpell(192750, nil, nil, nil, 2)
local specWarnHiddenOver = mod:NewSpecialWarningEnd(192750)
local specWarnCreepingDoom = mod:NewSpecialWarningDodge(197422, nil, nil, nil, 2)
local specWarnVengeance = mod:NewSpecialWarningMoveTo(205004, nil, DBM_CORE_AUTO_SPEC_WARN_OPTIONS.spell:format(205004), nil, 3, 6)
local timerKickCD = mod:NewCDTimer(16, 197251, nil, "Tank", nil, 5, nil, DBM_CORE_TANK_ICON)--16-42
local timerDeepeningShadowsCD = mod:NewCDTimer(30.5, 213576, nil, nil, nil, 3)
local timerCreepingDoom = mod:NewBuffActiveTimer(35, 197422, nil, nil, nil, 6)--35-40
local timerVengeanceCD = mod:NewCDTimer(35, 205004, nil, nil, nil, 1)--35-40
local voiceKick = mod:NewVoice(197251, "Tank")--carefly
local voiceDeepeningShadows = mod:NewVoice(213576)--"213576"--New Voice
local voiceVengeance = mod:NewVoice(205004)--"205004"--New Voice
local voiceCreepingDoom = mod:NewVoice(197422)--stilldanger, keepmove
function mod:OnCombatStart(delay)
timerKickCD:Start(8.3-delay)
--timerDeepeningShadowsCD:Start(10.5-delay)
end
function mod:SPELL_CAST_START(args)
local spellId = args.spellId
if spellId == 213576 or spellId == 213583 then
if ExtraActionBarFrame:IsShown() then--Has light
specWarnDeepeningShadows:Show(args.spellName)
voiceDeepeningShadows:Play("213576")
else
warnDeepeningShadows:Show()
end
timerDeepeningShadowsCD:Start()
elseif spellId == 197251 then
specWarnKick:Show()
voiceKick:Play("carefly")
timerKickCD:Start()
elseif spellId == 197422 then--First creeping doom
specWarnCreepingDoom:Show()
voiceCreepingDoom:Play("stilldanger")
voiceCreepingDoom:Schedule(2, "keepmove")
timerKickCD:Stop()
timerDeepeningShadowsCD:Stop()
timerCreepingDoom:Start()
elseif spellId == 213685 then--Second creeping doom
specWarnCreepingDoom:Show()
voiceCreepingDoom:Play("stilldanger")
voiceCreepingDoom:Schedule(2, "keepmove")
end
end
function mod:SPELL_AURA_APPLIED(args)
if args.spellId == 205004 then
if ExtraActionBarFrame:IsShown() then--Has light
specWarnVengeance:Show(args.spellName)
voiceVengeance:Play(205004)
else
warnVengeance:Show()
end
timerVengeanceCD:Start()
end
end
function mod:SPELL_AURA_REMOVED(args)
local spellId = args.spellId
if spellId == 206567 then
specWarnHiddenOver:Show()
--timerVengeanceCD:Start(14)
timerKickCD:Start(15.5)--15-20
timerDeepeningShadowsCD:Start(20)--20-25
elseif spellId == 197422 then
timerVengeanceCD:Start(10)
timerKickCD:Start(20)--Small sample
end
end
function mod:UNIT_SPELLCAST_SUCCEEDED(uId, _, _, spellGUID)
local spellId = tonumber(select(5, strsplit("-", spellGUID)), 10)
if spellId == 203416 then--Shadowstep. Faster than 206567 applied
timerDeepeningShadowsCD:Stop()
timerKickCD:Stop()
specWarnHiddenStarted:Show()
end
end
|
local base_total = 0;
local credit_total = 0;
local avail_total = 0;
function handle_record(record)
local prefix = record:get("PFX_SYMBOL");
local suffix = record:get("SFX_SYMBOL");
local balance = record:get("Balance");
local credit = record:get("CreditLimit");
local available = record:get("AvailableCredit");
local InterestRate = record:get("InterestRate");
record:set("Balance", prefix .. string.format("%.2f", balance) .. suffix);
record:set("Credit", prefix .. string.format("%.2f", credit) .. suffix);
record:set("Available", prefix .. string.format("%.2f", available) .. suffix);
record:set("InterestRate", prefix .. string.format("%.2f", InterestRate) .. suffix);
base_total = base_total + record:get("BaseBal");
credit_total = credit_total + record:get("CreditLimit");
avail_total = avail_total + record:get("AvailableCredit");
end
function complete(result)
result:set("Base_Total", base_total);
result:set("Credit_Total", credit_total);
result:set("Avail_Total", avail_total);
end
|
hook.Add('PostCleanupMap', 'BGN_ResetAllGlobalTablesAndVariables', function()
bgNPC:ClearActorsConfig()
bgNPC.actors = {}
bgNPC.factors = {}
bgNPC.npcs = {}
bgNPC.fnpcs = {}
end)
cvars.AddChangeCallback('bgn_enable', function(convar_name, value_old, value_new)
if tonumber(value_new) == 0 then
bgNPC:ClearActorsConfig()
end
end)
|
--[[
AutoHideController.lua
@Author : DengSir (tdaddon@163.com)
@Link : https://dengsir.github.io
]]
local MAJOR, MINOR = 'AutoHideController', 2
local GUI = LibStub('tdGUI-1.0')
local AutoHideController, oldminor, ns = GUI:NewClass(MAJOR, MINOR, 'Frame')
if not AutoHideController then return end
LibStub('AceTimer-3.0'):Embed(AutoHideController)
ns._Objects = ns._Objects or {}
ns.ESCHandler = ns.ESCHandler or CreateFrame('Frame', nil, UIParent)
ns.ESCHandler:Hide()
ns.ESCHandler:SetScript('OnKeyDown', function(self, key)
local found = false
if key == GetBindingKey('TOGGLEGAMEMENU') then
for object in pairs(ns._Objects) do
if object:IsVisible() then
object:OnTimer()
found = true
end
end
self:Hide()
end
self:SetPropagateKeyboardInput(not found)
end)
function AutoHideController:Constructor()
self:SetScript('OnUpdate', self.OnUpdate)
self:SetScript('OnHide', self.OnTimer)
self:SetScript('OnShow', self.OnShow)
ns._Objects[self] = true
end
function AutoHideController:GetOwner()
return self:GetParent():GetOwner()
end
function AutoHideController:IsOwnerVisible()
return self:GetOwner() and self:GetOwner():IsVisible()
end
function AutoHideController:IsOwnerOver()
return self:GetOwner() and self:GetOwner():IsMouseOver()
end
function AutoHideController:IsMenuOver()
return self:GetParent():IsMouseOver()
end
function AutoHideController:OnUpdate(elapsed)
if self:Fire('OnUpdateCheck') then
return self:OnTimer()
end
self.updater = (self.updater or 0) - elapsed
if self.updater > 0 then
return
end
self.updater = 0.5
if self:IsOwnerOver() or self:IsMenuOver() then
self:CancelTimer()
else
self:StartTimer()
end
end
function AutoHideController:OnTimer()
self:GetParent():Hide()
self:CancelTimer()
end
function AutoHideController:CancelTimer()
if self.timer then
self.timer:Cancel()
self.timer = nil
end
end
function AutoHideController:StartTimer()
if not self.timer then
self.timer = C_Timer.NewTimer(self:GetAutoHideDelay(), function() self:OnTimer() end)
end
end
function AutoHideController:OnShow()
ns.ESCHandler:Show()
end
function AutoHideController:SetAutoHideDelay(delay)
self.autoHideDelay = delay
end
function AutoHideController:GetAutoHideDelay()
return self.autoHideDelay or 1.5
end
|
local ssl_fixtures = require "spec.fixtures.ssl"
local helpers = require "spec.helpers"
local cjson = require "cjson"
for _, strategy in helpers.each_strategy() do
describe("/certificates with DB: #" .. strategy, function()
local client
lazy_setup(function()
helpers.get_db_utils(strategy, {
"certificates",
"vaults_beta",
})
assert(helpers.start_kong {
database = strategy,
vaults = "env",
})
client = assert(helpers.admin_client(10000))
local res = client:put("/vaults-beta/test-vault", {
headers = { ["Content-Type"] = "application/json" },
body = {
name = "env",
},
})
assert.res_status(200, res)
end)
after_each(function()
if client then
client:close()
end
end)
lazy_teardown(function()
helpers.stop_kong()
end)
it("create certificates with cert and key as secret", function()
finally(function()
helpers.unsetenv("CERT")
helpers.unsetenv("KEY")
end)
helpers.setenv("CERT", ssl_fixtures.cert)
helpers.setenv("KEY", ssl_fixtures.key)
local res, err = client:post("/certificates", {
body = {
cert = "{vault://test-vault/cert}",
key = "{vault://test-vault/key}",
},
headers = { ["Content-Type"] = "application/json" },
})
assert.is_nil(err)
local body = assert.res_status(201, res)
local certificate = cjson.decode(body)
assert.not_nil(certificate.key)
assert.not_nil(certificate.cert)
end)
end)
end
|
-- Credits: Darklord (Dota 12v12)
DisableHelp = DisableHelp or {}
RegisterCustomEventListener("set_disable_help", function(data)
local to = data.to;
if PlayerResource:IsValidPlayerID(to) then
local playerId = data.PlayerID;
local disable = data.disable == 1
PlayerResource:SetUnitShareMaskForPlayer(playerId, to, 4, disable)
local disableHelp = CustomNetTables:GetTableValue("disable_help", tostring(playerId)) or {}
disableHelp[tostring(to)] = disable
CustomNetTables:SetTableValue("disable_help", tostring(playerId), disableHelp)
end
end)
local disabledModifiers = {
modifier_imba_keeper_of_the_light_recall = true,
modifier_imba_rattletrap_hookshot = true,
modifier_imba_tidehunter_gush_surf = true,
}
function DisableHelp.ModifierGainedFilter(filterTable)
if disabledModifiers[filterTable.name_const] then
local parent = EntIndexToHScript(filterTable.entindex_parent_const)
local caster = EntIndexToHScript(filterTable.entindex_caster_const)
local ability = EntIndexToHScript(filterTable.entindex_ability_const)
if PlayerResource:IsDisableHelpSetForPlayerID(parent:GetPlayerOwnerID(), caster:GetPlayerOwnerID()) then
ability:EndCooldown()
ability:RefundManaCost()
DisplayError(caster:GetPlayerOwnerID(), "dota_hud_error_target_has_disable_help")
return false
end
end
end
local disabledAbilities = {
imba_bane_nightmare = true,
imba_bloodseeker_bloodrage = true,
imba_crystal_maiden_frostbite = true,
imba_chen_holy_persuasion = true,
imba_earth_spirit_boulder_smash = true,
imba_earth_spirit_geomagnetic_grip = true,
imba_earth_spirit_petrify = true,
imba_keeper_of_the_light_recall = true,
imba_kunkka_x_marks_the_spot = true,
imba_obsidian_destroyer_astral_imprisonment = true, -- form change
imba_outworld_devourer_astral_imprisonment = true, -- form change
imba_oracle_fates_edict = true,
imba_oracle_purifying_flames = true,
imba_puck_phase_shift = true,
imba_pugna_decrepify = true,
imba_rubick_telekinesis = true,
imba_vengefulspirit_nether_swap = true,
imba_winter_wyvern_cold_embrace = true,
imba_weaver_time_lapse = true,
imba_wisp_tether = true,
imba_pudge_dismember = true,
imba_brewmaster_primal_split = true,
-- items
item_imba_force_staff = true,
item_imba_hurricane_pike = true,
item_imba_lance_of_longinus = true,
item_imba_wand_of_the_brine = true,
}
function DisableHelp.ExecuteOrderFilter(orderType, ability, target, unit)
if (
orderType == DOTA_UNIT_ORDER_CAST_TARGET and
ability and
target and
unit and
disabledAbilities[ability:GetAbilityName()] and
PlayerResource:IsDisableHelpSetForPlayerID(target:GetPlayerOwnerID(), unit:GetPlayerOwnerID())
) then
DisplayError(unit:GetPlayerOwnerID(), "dota_hud_error_target_has_disable_help")
return false
end
end
|
object_mobile_dressed_dark_jedi_male_zab_02 = object_mobile_shared_dressed_dark_jedi_male_zab_02:new {
}
ObjectTemplates:addTemplate(object_mobile_dressed_dark_jedi_male_zab_02, "object/mobile/dressed_dark_jedi_male_zab_02.iff")
|
local api = vim.api
local empty_3f = vim.tbl_isempty
local contains_3f = vim.tbl_contains
local map = vim.tbl_map
local min = math.min
local max = math.max
local ceil = math.ceil
local function inc(x)
return (x + 1)
end
local function dec(x)
return (x - 1)
end
local function clamp(val, min0, max0)
if (val < min0) then
return min0
elseif (val > max0) then
return max0
elseif "else" then
return val
else
return nil
end
end
local function last(tbl)
return tbl[#tbl]
end
local function echo(msg)
vim.cmd("redraw")
return api.nvim_echo({{msg}}, false, {})
end
local function replace_keycodes(s)
return api.nvim_replace_termcodes(s, true, false, true)
end
local _3cbackspace_3e = replace_keycodes("<bs>")
local _3cctrl_v_3e = replace_keycodes("<c-v>")
local function get_motion_force(mode)
local _2_
if mode:match("o") then
_2_ = mode:sub(-1)
else
_2_ = nil
end
if (nil ~= _2_) then
local last_ch = _2_
if ((last_ch == _3cctrl_v_3e) or (last_ch == "V") or (last_ch == "v")) then
return last_ch
else
return nil
end
else
return nil
end
end
local function operator_pending_mode_3f()
return string.match(api.nvim_get_mode().mode, "o")
end
local function change_operation_3f()
return (operator_pending_mode_3f() and (vim.v.operator == "c"))
end
local function get_cursor_pos()
return {vim.fn.line("."), vim.fn.col(".")}
end
local function same_pos_3f(_6_, _8_)
local _arg_7_ = _6_
local l1 = _arg_7_[1]
local c1 = _arg_7_[2]
local _arg_9_ = _8_
local l2 = _arg_9_[1]
local c2 = _arg_9_[2]
return ((l1 == l2) and (c1 == c2))
end
local function char_at_pos(_10_, _12_)
local _arg_11_ = _10_
local line = _arg_11_[1]
local byte_col = _arg_11_[2]
local _arg_13_ = _12_
local char_offset = _arg_13_["char-offset"]
local line_str = vim.fn.getline(line)
local char_idx = vim.fn.charidx(line_str, dec(byte_col))
local char_nr = vim.fn.strgetchar(line_str, (char_idx + (char_offset or 0)))
if (char_nr ~= -1) then
return vim.fn.nr2char(char_nr)
else
return nil
end
end
local function leftmost_editable_wincol()
local view = vim.fn.winsaveview()
vim.cmd("norm! 0")
local wincol = vim.fn.wincol()
vim.fn.winrestview(view)
if ("\9" == string.sub(vim.fn.getline("."), 1, 1)) then
return (wincol - dec(vim.o.tabstop))
else
return wincol
end
end
local function get_fold_edge(lnum, reverse_3f)
local _16_
local _17_
if reverse_3f then
_17_ = vim.fn.foldclosed
else
_17_ = vim.fn.foldclosedend
end
_16_ = _17_(lnum)
if (_16_ == -1) then
return nil
elseif (nil ~= _16_) then
local fold_edge = _16_
return fold_edge
else
return nil
end
end
local function maparg_expr(name, mode)
local rhs = vim.fn.maparg(name, mode)
local ok_3f, eval_rhs = pcall(vim.fn.eval, rhs)
if (ok_3f and (type(eval_rhs) == "string")) then
return eval_rhs
else
return rhs
end
end
local opts
do
local safe_labels = {"s", "f", "n", "u", "t", "/", "F", "L", "N", "H", "G", "M", "U", "T", "?", "Z"}
local labels = {"s", "f", "n", "j", "k", "l", "o", "i", "w", "e", "h", "g", "u", "t", "m", "v", "c", "a", ".", "z", "/", "F", "L", "N", "H", "G", "M", "U", "T", "?", "Z"}
opts = {ignore_case = false, exit_after_idle_msecs = {labeled = nil, unlabeled = 1000}, override_x = true, override_s = true, override_motion = true, grey_out_search_area = true, highlight_unique_chars = true, match_only_the_start_of_same_char_seqs = true, jump_on_partial_input_safety_timeout = 400, substitute_chars = {["\13"] = "\194\172"}, safe_labels = safe_labels, labels = labels, cycle_group_fwd_key = "<space>", cycle_group_bwd_key = "<tab>", limit_ft_matches = 4, repeat_ft_with_target_char = false}
end
local deprecated_opts = {"jump_to_first_match", "instant_repeat_fwd_key", "instant_repeat_bwd_key", "x_mode_prefix_key", "full_inclusive_prefix_key"}
local function get_deprec_msg(arg_fields)
local msg = {{"ligthspeed.nvim\n", "Question"}, {"You are trying to set or access deprecated fields in the "}, {"opts", "Visual"}, {" table:\n\n"}}
local field_names
do
local tbl_15_auto = {}
local i_16_auto = #tbl_15_auto
for _, field in ipairs(arg_fields) do
local val_17_auto = {("\9" .. field .. "\n")}
if (nil ~= val_17_auto) then
i_16_auto = (i_16_auto + 1)
do end (tbl_15_auto)[i_16_auto] = val_17_auto
else
end
end
field_names = tbl_15_auto
end
local msg_for_instant_repeat_keys = {{"There are dedicated "}, {"<Plug>", "Visual"}, {" keys available for native-like "}, {";", "Visual"}, {" and "}, {",", "Visual"}, {" functionality now, "}, {"that can also be used for instant repeat only, if you prefer. See "}, {":h lightspeed-custom-mappings", "Visual"}, {"."}}
local msg_for_x_prefix = {{"Use "}, {"<Plug>Lightspeed_x", "Visual"}, {" and "}, {"<Plug>Lightspeed_X", "Visual"}, {" instead."}}
local spec_messages = {jump_to_first_match = {{"The plugin implements \"smart\" auto-jump now, that you can fine-tune via "}, {"opts.labels", "Visual"}, {" and "}, {"opts.safe_labels", "Visual"}, {". See "}, {":h lightspeed-config", "Visual"}, {" for details."}}, instant_repeat_fwd_key = msg_for_instant_repeat_keys, instant_repeat_bwd_key = msg_for_instant_repeat_keys, x_mode_prefix_key = msg_for_x_prefix, full_inclusive_prefix_key = msg_for_x_prefix}
for _, field_name_chunk in ipairs(field_names) do
table.insert(msg, field_name_chunk)
end
table.insert(msg, {"\n"})
for field, spec_msg in pairs(spec_messages) do
if contains_3f(arg_fields, field) then
table.insert(msg, {(field .. "\n"), "IncSearch"})
for _, chunk in ipairs(spec_msg) do
table.insert(msg, chunk)
end
table.insert(msg, {"\n\n"})
else
end
end
return msg
end
do
local guard
local function _23_(t, k)
if contains_3f(deprecated_opts, k) then
return api.nvim_echo(get_deprec_msg({k}), true, {})
else
return nil
end
end
guard = _23_
setmetatable(opts, {__index = guard, __newindex = guard})
end
local function normalize_opts(opts0)
local deprecated_arg_opts = {}
for k, v in pairs(opts0) do
if contains_3f(deprecated_opts, k) then
table.insert(deprecated_arg_opts, k)
do end (opts0)[k] = nil
else
end
end
if not empty_3f(deprecated_arg_opts) then
api.nvim_echo(get_deprec_msg(deprecated_arg_opts), true, {})
else
end
return opts0
end
local function set_plug_keys()
local plug_keys = {{"<Plug>Lightspeed_s", "sx:go(false)"}, {"<Plug>Lightspeed_S", "sx:go(true)"}, {"<Plug>Lightspeed_x", "sx:go(false, true)"}, {"<Plug>Lightspeed_X", "sx:go(true, true)"}, {"<Plug>Lightspeed_f", "ft:go(false)"}, {"<Plug>Lightspeed_F", "ft:go(true)"}, {"<Plug>Lightspeed_t", "ft:go(false, true)"}, {"<Plug>Lightspeed_T", "ft:go(true, true)"}, {"<Plug>Lightspeed_;_sx", "sx:go(false, nil, 'cold')"}, {"<Plug>Lightspeed_,_sx", "sx:go(true, nil, 'cold')"}, {"<Plug>Lightspeed_;_ft", "ft:go(false, nil, 'cold')"}, {"<Plug>Lightspeed_,_ft", "ft:go(true, nil, 'cold')"}}
for _, _27_ in ipairs(plug_keys) do
local _each_28_ = _27_
local lhs = _each_28_[1]
local rhs_call = _each_28_[2]
for _0, mode in ipairs({"n", "x", "o"}) do
api.nvim_set_keymap(mode, lhs, ("<cmd>lua require'lightspeed'." .. rhs_call .. "<cr>"), {noremap = true, silent = true})
end
end
for _, _29_ in ipairs({{"<Plug>Lightspeed_dotrepeat_s", "sx:go(false, false, 'dot')"}, {"<Plug>Lightspeed_dotrepeat_S", "sx:go(true, false, 'dot')"}, {"<Plug>Lightspeed_dotrepeat_x", "sx:go(false, true, 'dot')"}, {"<Plug>Lightspeed_dotrepeat_X", "sx:go(true, true, 'dot')"}, {"<Plug>Lightspeed_dotrepeat_f", "ft:go(false, false, 'dot')"}, {"<Plug>Lightspeed_dotrepeat_F", "ft:go(true, false, 'dot')"}, {"<Plug>Lightspeed_dotrepeat_t", "ft:go(false, true, 'dot')"}, {"<Plug>Lightspeed_dotrepeat_T", "ft:go(true, true, 'dot')"}}) do
local _each_30_ = _29_
local lhs = _each_30_[1]
local rhs_call = _each_30_[2]
api.nvim_set_keymap("o", lhs, ("<cmd>lua require'lightspeed'." .. rhs_call .. "<cr>"), {noremap = true, silent = true})
end
return nil
end
local function set_default_keymaps()
local default_keymaps = {{"n", "f", "<Plug>Lightspeed_f"}, {"n", "F", "<Plug>Lightspeed_F"}, {"x", "f", "<Plug>Lightspeed_f"}, {"x", "F", "<Plug>Lightspeed_F"}, {"o", "f", "<Plug>Lightspeed_f"}, {"o", "F", "<Plug>Lightspeed_F"}, {"n", "t", "<Plug>Lightspeed_t"}, {"n", "T", "<Plug>Lightspeed_T"}, {"x", "t", "<Plug>Lightspeed_t"}, {"x", "T", "<Plug>Lightspeed_T"}, {"o", "t", "<Plug>Lightspeed_t"}, {"o", "T", "<Plug>Lightspeed_T"}, {"n", ";", "<Plug>Lightspeed_;_ft"}, {"x", ";", "<Plug>Lightspeed_;_ft"}, {"o", ";", "<Plug>Lightspeed_;_ft"}, {"n", ",", "<Plug>Lightspeed_,_ft"}, {"x", ",", "<Plug>Lightspeed_,_ft"}, {"o", ",", "<Plug>Lightspeed_,_ft"}}
local override_x_keymaps = {{"o", "x", "<Plug>Lightspeed_x"}, {"o", "X", "<Plug>Lightspeed_X"}}
local override_s_keymaps = {{"n", "s", "<Plug>Lightspeed_s"}, {"n", "S", "<Plug>Lightspeed_S"}, {"x", "s", "<Plug>Lightspeed_s"}, {"x", "S", "<Plug>Lightspeed_S"}, {"o", "z", "<Plug>Lightspeed_s"}, {"o", "Z", "<Plug>Lightspeed_S"}}
if opts.override_motion then
for _, _31_ in ipairs(default_keymaps) do
local _each_32_ = _31_
local mode = _each_32_[1]
local lhs = _each_32_[2]
local rhs = _each_32_[3]
if ((vim.fn.mapcheck(lhs, mode) == "") and (vim.fn.hasmapto(rhs, mode) == 0)) then
api.nvim_set_keymap(mode, lhs, rhs, {silent = true})
else
end
end
else
end
if opts.override_x then
for _, _35_ in ipairs(override_x_keymaps) do
local _each_36_ = _35_
local mode = _each_36_[1]
local lhs = _each_36_[2]
local rhs = _each_36_[3]
if ((vim.fn.mapcheck(lhs, mode) == "") and (vim.fn.hasmapto(rhs, mode) == 0)) then
api.nvim_set_keymap(mode, lhs, rhs)
else
end
end
else
end
if opts.override_s then
for _, _39_ in ipairs(override_s_keymaps) do
local _each_40_ = _39_
local mode = _each_40_[1]
local lhs = _each_40_[2]
local rhs = _each_40_[3]
if ((vim.fn.mapcheck(lhs, mode) == "") and (vim.fn.hasmapto(rhs, mode) == 0)) then
api.nvim_set_keymap(mode, lhs, rhs, {silent = true})
else
end
end
return nil
else
return nil
end
end
local function setup(user_opts)
opts = setmetatable(normalize_opts(user_opts), {__index = opts})
set_plug_keys()
return set_default_keymaps()
end
local hl
local function _43_(self, hl_group, line, startcol, endcol)
return api.nvim_buf_add_highlight(0, self.ns, hl_group, line, startcol, endcol)
end
local function _44_(self, line, col, opts0)
return api.nvim_buf_set_extmark(0, self.ns, line, col, opts0)
end
local function _45_(self)
return api.nvim_buf_clear_namespace(0, self.ns, 0, -1)
end
hl = {group = {label = "LightspeedLabel", ["label-distant"] = "LightspeedLabelDistant", ["label-overlapped"] = "LightspeedLabelOverlapped", ["label-distant-overlapped"] = "LightspeedLabelDistantOverlapped", shortcut = "LightspeedShortcut", ["shortcut-overlapped"] = "LightspeedShortcutOverlapped", ["masked-ch"] = "LightspeedMaskedChar", ["unlabeled-match"] = "LightspeedUnlabeledMatch", ["one-char-match"] = "LightspeedOneCharMatch", ["unique-ch"] = "LightspeedUniqueChar", ["pending-op-area"] = "LightspeedPendingOpArea", greywash = "LightspeedGreyWash", cursor = "LightspeedCursor"}, ns = api.nvim_create_namespace(""), ["add-hl"] = _43_, ["set-extmark"] = _44_, cleanup = _45_}
local function init_highlight(force_3f)
local bg = vim.o.background
local groupdefs
local _47_
do
local _46_ = bg
if (_46_ == "light") then
_47_ = "#f02077"
elseif true then
local _ = _46_
_47_ = "#ff2f87"
else
_47_ = nil
end
end
local _52_
do
local _51_ = bg
if (_51_ == "light") then
_52_ = "#ff4090"
elseif true then
local _ = _51_
_52_ = "#e01067"
else
_52_ = nil
end
end
local _57_
do
local _56_ = bg
if (_56_ == "light") then
_57_ = "#399d9f"
elseif true then
local _ = _56_
_57_ = "#99ddff"
else
_57_ = nil
end
end
local _62_
do
local _61_ = bg
if (_61_ == "light") then
_62_ = "Blue"
elseif true then
local _ = _61_
_62_ = "Cyan"
else
_62_ = nil
end
end
local _67_
do
local _66_ = bg
if (_66_ == "light") then
_67_ = "#59bdbf"
elseif true then
local _ = _66_
_67_ = "#79bddf"
else
_67_ = nil
end
end
local _72_
do
local _71_ = bg
if (_71_ == "light") then
_72_ = "Cyan"
elseif true then
local _ = _71_
_72_ = "Blue"
else
_72_ = nil
end
end
local _77_
do
local _76_ = bg
if (_76_ == "light") then
_77_ = "#cc9999"
elseif true then
local _ = _76_
_77_ = "#b38080"
else
_77_ = nil
end
end
local _82_
do
local _81_ = bg
if (_81_ == "light") then
_82_ = "#272020"
elseif true then
local _ = _81_
_82_ = "#f3ecec"
else
_82_ = nil
end
end
local _87_
do
local _86_ = bg
if (_86_ == "light") then
_87_ = "Black"
elseif true then
local _ = _86_
_87_ = "White"
else
_87_ = nil
end
end
groupdefs = {{hl.group.label, {guifg = _47_, ctermfg = "Red", guibg = "NONE", ctermbg = "NONE", gui = "bold,underline", cterm = "bold,underline"}}, {hl.group["label-overlapped"], {guifg = _52_, ctermfg = "Magenta", guibg = "NONE", ctermbg = "NONE", gui = "underline", cterm = "underline"}}, {hl.group["label-distant"], {guifg = _57_, ctermfg = _62_, guibg = "NONE", ctermbg = "NONE", gui = "bold,underline", cterm = "bold,underline"}}, {hl.group["label-distant-overlapped"], {guifg = _67_, ctermfg = _72_, gui = "underline", cterm = "underline"}}, {hl.group.shortcut, {guibg = "#f00077", ctermbg = "Red", guifg = "#ffffff", ctermfg = "White", gui = "bold,underline", cterm = "bold,underline"}}, {hl.group["one-char-match"], {guibg = "#f00077", ctermbg = "Red", guifg = "#ffffff", ctermfg = "White", gui = "bold", cterm = "bold"}}, {hl.group["masked-ch"], {guifg = _77_, ctermfg = "DarkGrey", guibg = "NONE", ctermbg = "NONE", gui = "NONE", cterm = "NONE"}}, {hl.group["unlabeled-match"], {guifg = _82_, ctermfg = _87_, guibg = "NONE", ctermbg = "NONE", gui = "bold", cterm = "bold"}}, {hl.group["pending-op-area"], {guibg = "#f00077", ctermbg = "Red", guifg = "#ffffff", ctermfg = "White"}}, {hl.group.greywash, {guifg = "#777777", ctermfg = "Grey", guibg = "NONE", ctermbg = "NONE", gui = "NONE", cterm = "NONE"}}}
for _, _91_ in ipairs(groupdefs) do
local _each_92_ = _91_
local group = _each_92_[1]
local attrs = _each_92_[2]
local attrs_str
local _93_
do
local tbl_15_auto = {}
local i_16_auto = #tbl_15_auto
for k, v in pairs(attrs) do
local val_17_auto = (k .. "=" .. v)
if (nil ~= val_17_auto) then
i_16_auto = (i_16_auto + 1)
do end (tbl_15_auto)[i_16_auto] = val_17_auto
else
end
end
_93_ = tbl_15_auto
end
attrs_str = table.concat(_93_, " ")
local function _95_()
if force_3f then
return ""
else
return "default "
end
end
vim.cmd(("highlight " .. _95_() .. group .. " " .. attrs_str))
end
for _, _96_ in ipairs({{hl.group["unique-ch"], hl.group["unlabeled-match"]}, {hl.group["shortcut-overlapped"], hl.group.shortcut}, {hl.group.cursor, "Cursor"}}) do
local _each_97_ = _96_
local from_group = _each_97_[1]
local to_group = _each_97_[2]
local function _98_()
if force_3f then
return ""
else
return "default "
end
end
vim.cmd(("highlight " .. _98_() .. "link " .. from_group .. " " .. to_group))
end
return nil
end
local function grey_out_search_area(reverse_3f)
local _let_99_ = map(dec, get_cursor_pos())
local curline = _let_99_[1]
local curcol = _let_99_[2]
local _let_100_ = {dec(vim.fn.line("w0")), dec(vim.fn.line("w$"))}
local win_top = _let_100_[1]
local win_bot = _let_100_[2]
local function _102_()
if reverse_3f then
return {{win_top, 0}, {curline, curcol}}
else
return {{curline, inc(curcol)}, {win_bot, -1}}
end
end
local _let_101_ = _102_()
local start = _let_101_[1]
local finish = _let_101_[2]
return vim.highlight.range(0, hl.ns, hl.group.greywash, start, finish)
end
local function highlight_range(hl_group, _103_, _105_, _107_)
local _arg_104_ = _103_
local startline = _arg_104_[1]
local startcol = _arg_104_[2]
local start = _arg_104_
local _arg_106_ = _105_
local endline = _arg_106_[1]
local endcol = _arg_106_[2]
local _end = _arg_106_
local _arg_108_ = _107_
local motion_force = _arg_108_["motion-force"]
local inclusive_motion_3f = _arg_108_["inclusive-motion?"]
local hl_range
local function _109_(start0, _end0, end_inclusive_3f)
return vim.highlight.range(0, hl.ns, hl_group, start0, _end0, nil, end_inclusive_3f)
end
hl_range = _109_
local _110_ = motion_force
if (_110_ == _3cctrl_v_3e) then
local _let_111_ = {min(startcol, endcol), max(startcol, endcol)}
local startcol0 = _let_111_[1]
local endcol0 = _let_111_[2]
for line = startline, endline do
hl_range({line, startcol0}, {line, endcol0}, true)
end
return nil
elseif (_110_ == "V") then
return hl_range({startline, 0}, {endline, -1})
elseif (_110_ == "v") then
return hl_range(start, _end, not inclusive_motion_3f)
elseif (_110_ == nil) then
return hl_range(start, _end, inclusive_motion_3f)
else
return nil
end
end
local function echo_no_prev_search()
return echo("no previous search")
end
local function echo_not_found(s)
return echo(("not found: " .. s))
end
local function push_cursor_21(direction)
local function _114_()
local _113_ = direction
if (_113_ == "fwd") then
return "W"
elseif (_113_ == "bwd") then
return "bW"
else
return nil
end
end
return vim.fn.search("\\_.", _114_())
end
local function get_restore_virtualedit_autocmd()
return ("autocmd " .. "CursorMoved,WinLeave,BufLeave,InsertEnter,CmdlineEnter,CmdwinEnter" .. " * ++once set virtualedit=" .. vim.o.virtualedit)
end
local function force_matchparen_refresh()
vim.cmd("silent! doautocmd matchparen CursorMoved")
return vim.cmd("silent! doautocmd matchup_matchparen CursorMoved")
end
local function cursor_before_eof_3f()
return ((vim.fn.line(".") == vim.fn.line("$")) and (vim.fn.virtcol(".") == dec(vim.fn.virtcol("$"))))
end
local function jump_to_21_2a(target, _116_)
local _arg_117_ = _116_
local mode = _arg_117_["mode"]
local reverse_3f = _arg_117_["reverse?"]
local inclusive_motion_3f = _arg_117_["inclusive-motion?"]
local add_to_jumplist_3f = _arg_117_["add-to-jumplist?"]
local adjust = _arg_117_["adjust"]
local op_mode_3f = string.match(mode, "o")
local motion_force = get_motion_force(mode)
local restore_virtualedit_autocmd = get_restore_virtualedit_autocmd()
if add_to_jumplist_3f then
vim.cmd("norm! m`")
else
end
vim.fn.cursor(target)
adjust()
if not op_mode_3f then
force_matchparen_refresh()
else
end
local adjusted_pos = get_cursor_pos()
if (op_mode_3f and not reverse_3f and inclusive_motion_3f) then
local _120_ = motion_force
if (_120_ == nil) then
if not cursor_before_eof_3f() then
push_cursor_21("fwd")
else
vim.cmd("set virtualedit=onemore")
vim.cmd("norm! l")
vim.cmd(restore_virtualedit_autocmd)
end
elseif (_120_ == "V") then
elseif (_120_ == _3cctrl_v_3e) then
elseif (_120_ == "v") then
push_cursor_21("bwd")
else
end
else
end
return adjusted_pos
end
local function get_onscreen_lines(_124_)
local _arg_125_ = _124_
local reverse_3f = _arg_125_["reverse?"]
local skip_folds_3f = _arg_125_["skip-folds?"]
local lines = {}
local wintop = vim.fn.line("w0")
local winbot = vim.fn.line("w$")
local lnum = vim.fn.line(".")
while true do
local _126_
if reverse_3f then
_126_ = (lnum >= wintop)
else
_126_ = (lnum <= winbot)
end
if not _126_ then break end
local fold_edge = get_fold_edge(lnum, reverse_3f)
if (skip_folds_3f and fold_edge) then
local _128_
if reverse_3f then
_128_ = dec
else
_128_ = inc
end
lnum = _128_(fold_edge)
else
lines[lnum] = vim.fn.getline(lnum)
local _130_
if reverse_3f then
_130_ = dec
else
_130_ = inc
end
lnum = _130_(lnum)
end
end
return lines
end
local function get_horizontal_bounds(_133_)
local _arg_134_ = _133_
local match_width = _arg_134_["match-width"]
local textoff = (vim.fn.getwininfo(vim.fn.win_getid())[1].textoff or dec(leftmost_editable_wincol()))
local offset_in_win = vim.fn.wincol()
local offset_in_editable_win = (offset_in_win - textoff)
local left_bound = (vim.fn.virtcol(".") - dec(offset_in_editable_win))
local window_width = api.nvim_win_get_width(0)
local right_edge = (left_bound + dec((window_width - textoff)))
local right_bound = (right_edge - dec(match_width))
return {left_bound, right_bound}
end
local function onscreen_match_positions(pattern, reverse_3f, _135_)
local _arg_136_ = _135_
local to_eol_3f = _arg_136_["to-eol?"]
local ft_search_3f = _arg_136_["ft-search?"]
local limit = _arg_136_["limit"]
local view = vim.fn.winsaveview()
local cpo = vim.o.cpo
local opts0
if reverse_3f then
opts0 = "b"
else
opts0 = ""
end
local stopline
local function _138_()
if reverse_3f then
return "w0"
else
return "w$"
end
end
stopline = vim.fn.line(_138_())
local cleanup
local function _139_()
vim.fn.winrestview(view)
vim.o.cpo = cpo
return nil
end
cleanup = _139_
local _141_
if ft_search_3f then
_141_ = 1
else
_141_ = 2
end
local _let_140_ = get_horizontal_bounds({["match-width"] = _141_})
local left_bound = _let_140_[1]
local right_bound = _let_140_[2]
local function skip_to_fold_edge_21()
local _143_
local _144_
if reverse_3f then
_144_ = vim.fn.foldclosed
else
_144_ = vim.fn.foldclosedend
end
_143_ = _144_(vim.fn.line("."))
if (_143_ == -1) then
return "not-in-fold"
elseif (nil ~= _143_) then
local fold_edge = _143_
vim.fn.cursor(fold_edge, 0)
local function _146_()
if reverse_3f then
return 1
else
return vim.fn.col("$")
end
end
vim.fn.cursor(0, _146_())
return "moved-the-cursor"
else
return nil
end
end
local function skip_to_next_in_window_pos_21()
local _local_148_ = get_cursor_pos()
local line = _local_148_[1]
local col = _local_148_[2]
local from_pos = _local_148_
local _149_
if (col < left_bound) then
if reverse_3f then
if (dec(line) >= stopline) then
_149_ = {dec(line), right_bound}
else
_149_ = nil
end
else
_149_ = {line, left_bound}
end
elseif (col > right_bound) then
if reverse_3f then
_149_ = {line, right_bound}
else
if (inc(line) <= stopline) then
_149_ = {inc(line), left_bound}
else
_149_ = nil
end
end
else
_149_ = nil
end
if (nil ~= _149_) then
local to_pos = _149_
if (from_pos ~= to_pos) then
vim.fn.cursor(to_pos)
return "moved-the-cursor"
else
return nil
end
else
return nil
end
end
vim.o.cpo = cpo:gsub("c", "")
local match_count = 0
local function recur(match_at_curpos_3f)
if (limit and (match_count >= limit)) then
return cleanup()
else
local _157_
local function _158_()
if match_at_curpos_3f then
return "c"
else
return ""
end
end
_157_ = vim.fn.searchpos(pattern, (opts0 .. _158_()), stopline)
if ((_G.type(_157_) == "table") and ((_157_)[1] == 0) and true) then
local _ = (_157_)[2]
return cleanup()
elseif ((_G.type(_157_) == "table") and (nil ~= (_157_)[1]) and (nil ~= (_157_)[2])) then
local line = (_157_)[1]
local col = (_157_)[2]
local pos = _157_
if ft_search_3f then
match_count = (match_count + 1)
return pos
else
local _159_ = skip_to_fold_edge_21()
if (_159_ == "moved-the-cursor") then
return recur(false)
elseif (_159_ == "not-in-fold") then
if (vim.wo.wrap or (function(_160_,_161_,_162_) return (_160_ <= _161_) and (_161_ <= _162_) end)(left_bound,col,right_bound) or to_eol_3f) then
match_count = (match_count + 1)
return pos
else
local _163_ = skip_to_next_in_window_pos_21()
if (_163_ == "moved-the-cursor") then
return recur(true)
elseif true then
local _ = _163_
return cleanup()
else
return nil
end
end
else
return nil
end
end
else
return nil
end
end
end
return recur
end
local function highlight_cursor(_3fpos)
local _let_170_ = (_3fpos or get_cursor_pos())
local line = _let_170_[1]
local col = _let_170_[2]
local pos = _let_170_
local ch_at_curpos = (char_at_pos(pos, {}) or " ")
return hl["set-extmark"](hl, dec(line), dec(col), {virt_text = {{ch_at_curpos, hl.group.cursor}}, virt_text_pos = "overlay", hl_mode = "combine"})
end
local function handle_interrupted_change_op_21()
echo("")
local curcol = vim.fn.col(".")
local endcol = vim.fn.col("$")
local _3fright
if (not vim.o.insertmode and (curcol > 1) and (curcol < endcol)) then
_3fright = "<RIGHT>"
else
_3fright = ""
end
return api.nvim_feedkeys(replace_keycodes(("<C-\\><C-G>" .. _3fright)), "n", true)
end
local function doau_when_exists(event)
if vim.fn.exists(("#User#" .. event)) then
return vim.cmd(("doautocmd <nomodeline> User " .. event))
else
return nil
end
end
local function enter(mode)
doau_when_exists("LightspeedEnter")
local _173_ = mode
if (_173_ == "ft") then
return doau_when_exists("LightspeedFtEnter")
elseif (_173_ == "sx") then
return doau_when_exists("LightspeedSxEnter")
else
return nil
end
end
local function get_input(_3ftimeout)
local esc_keycode = 27
local char_available_3f
local function _175_()
return (0 ~= vim.fn.getchar(1))
end
char_available_3f = _175_
local getchar_timeout
local function _176_()
if vim.wait(_3ftimeout, char_available_3f, 100) then
return vim.fn.getchar(0)
else
return nil
end
end
getchar_timeout = _176_
local ok_3f, ch = nil, nil
local function _178_()
if _3ftimeout then
return getchar_timeout
else
return vim.fn.getchar
end
end
ok_3f, ch = pcall(_178_())
if (ok_3f and (ch ~= esc_keycode)) then
if (type(ch) == "number") then
return vim.fn.nr2char(ch)
else
return ch
end
else
return nil
end
end
local function set_dot_repeat(cmd, _3fcount)
local op = vim.v.operator
local change
if (op == "c") then
change = replace_keycodes("<c-r>.<esc>")
else
change = nil
end
local seq = (op .. (_3fcount or "") .. cmd .. (change or ""))
pcall(vim.fn["repeat#setreg"], seq, vim.v.register)
return pcall(vim.fn["repeat#set"], seq, -1)
end
local function get_plug_key(search_mode, reverse_3f, x_2ft_3f, repeat_invoc)
local function _183_()
local _182_ = repeat_invoc
if (_182_ == "dot") then
return "dotrepeat_"
elseif true then
local _ = _182_
return ""
else
return nil
end
end
local function _186_()
local _185_ = {search_mode, not not reverse_3f, not not x_2ft_3f}
if ((_G.type(_185_) == "table") and ((_185_)[1] == "ft") and ((_185_)[2] == false) and ((_185_)[3] == false)) then
return "f"
elseif ((_G.type(_185_) == "table") and ((_185_)[1] == "ft") and ((_185_)[2] == true) and ((_185_)[3] == false)) then
return "F"
elseif ((_G.type(_185_) == "table") and ((_185_)[1] == "ft") and ((_185_)[2] == false) and ((_185_)[3] == true)) then
return "t"
elseif ((_G.type(_185_) == "table") and ((_185_)[1] == "ft") and ((_185_)[2] == true) and ((_185_)[3] == true)) then
return "T"
elseif ((_G.type(_185_) == "table") and ((_185_)[1] == "sx") and ((_185_)[2] == false) and ((_185_)[3] == false)) then
return "s"
elseif ((_G.type(_185_) == "table") and ((_185_)[1] == "sx") and ((_185_)[2] == true) and ((_185_)[3] == false)) then
return "S"
elseif ((_G.type(_185_) == "table") and ((_185_)[1] == "sx") and ((_185_)[2] == false) and ((_185_)[3] == true)) then
return "x"
elseif ((_G.type(_185_) == "table") and ((_185_)[1] == "sx") and ((_185_)[2] == true) and ((_185_)[3] == true)) then
return "X"
else
return nil
end
end
return ("<Plug>Lightspeed_" .. _183_() .. _186_())
end
local function get_repeat_action(_in, search_mode, x_2ft_3f, instant_repeat_3f, from_reverse_cold_repeat_3f, _3ftarget_char)
local mode
if (vim.fn.mode() == "n") then
mode = "n"
else
mode = "x"
end
local in_mapped_to = maparg_expr(_in, mode)
local repeat_plug_key = ("<Plug>Lightspeed_;_" .. search_mode)
local revert_plug_key = ("<Plug>Lightspeed_,_" .. search_mode)
local _189_
if from_reverse_cold_repeat_3f then
_189_ = revert_plug_key
else
_189_ = repeat_plug_key
end
if ((_in == _3cbackspace_3e) or ((search_mode == "ft") and opts.repeat_ft_with_target_char and (_in == _3ftarget_char)) or ((in_mapped_to == get_plug_key(search_mode, false, x_2ft_3f)) or (in_mapped_to == _189_))) then
return "repeat"
else
local _191_
if from_reverse_cold_repeat_3f then
_191_ = repeat_plug_key
else
_191_ = revert_plug_key
end
if (instant_repeat_3f and ((_in == "\9") or ((in_mapped_to == get_plug_key(search_mode, true, x_2ft_3f)) or (in_mapped_to == _191_)))) then
return "revert"
else
return nil
end
end
end
local ft = {state = {dot = {["in"] = nil}, cold = {["in"] = nil, ["reverse?"] = nil, ["t-mode?"] = nil}}}
ft.go = function(self, reverse_3f, t_mode_3f, repeat_invoc)
local mode = api.nvim_get_mode().mode
local op_mode_3f = mode:match("o")
local dot_repeatable_op_3f = (op_mode_3f and (vim.v.operator ~= "y"))
local instant_repeat_3f = (type(repeat_invoc) == "table")
local instant_state
if instant_repeat_3f then
instant_state = repeat_invoc
else
instant_state = nil
end
local reverted_instant_repeat_3f
do
local t_195_ = instant_state
if (nil ~= t_195_) then
t_195_ = (t_195_)["reverted?"]
else
end
reverted_instant_repeat_3f = t_195_
end
local cold_repeat_3f = (repeat_invoc == "cold")
local dot_repeat_3f = (repeat_invoc == "dot")
local invoked_as_reverse_3f = reverse_3f
local reverse_3f0
if cold_repeat_3f then
local function _197_(_241)
if invoked_as_reverse_3f then
return not _241
else
return _241
end
end
reverse_3f0 = _197_(self.state.cold["reverse?"])
else
reverse_3f0 = reverse_3f
end
local t_mode_3f0
if cold_repeat_3f then
t_mode_3f0 = self.state.cold["t-mode?"]
else
t_mode_3f0 = t_mode_3f
end
local count
if reverted_instant_repeat_3f then
count = 0
else
count = vim.v.count1
end
local count0
if (instant_repeat_3f and t_mode_3f0) then
count0 = inc(count)
else
count0 = count
end
local function get_num_of_matches_to_be_highlighted()
local _203_ = opts.limit_ft_matches
local function _204_()
local group_limit = _203_
return (group_limit > 0)
end
if ((nil ~= _203_) and _204_()) then
local group_limit = _203_
local matches_left_behind
local function _206_()
local _205_ = instant_state
if (nil ~= _205_) then
local _207_ = (_205_).stack
if (nil ~= _207_) then
return #_207_
else
return _207_
end
else
return _205_
end
end
matches_left_behind = (_206_() or 0)
local eaten_up = (matches_left_behind % group_limit)
local remaining = (group_limit - eaten_up)
if (remaining == 0) then
return group_limit
else
return remaining
end
elseif true then
local _ = _203_
return 0
else
return nil
end
end
if not instant_repeat_3f then
enter("ft")
else
end
if not repeat_invoc then
echo("")
highlight_cursor()
vim.cmd("redraw")
else
end
local _214_
if instant_repeat_3f then
_214_ = instant_state["in"]
elseif dot_repeat_3f then
_214_ = self.state.dot["in"]
elseif cold_repeat_3f then
_214_ = self.state.cold["in"]
else
local _215_
local function _216_()
local res_2_auto
do
res_2_auto = get_input()
end
hl:cleanup()
return res_2_auto
end
local function _217_()
if change_operation_3f() then
handle_interrupted_change_op_21()
else
end
do
end
doau_when_exists("LightspeedFtLeave")
doau_when_exists("LightspeedLeave")
return nil
end
_215_ = (_216_() or _217_())
if (_215_ == _3cbackspace_3e) then
local function _219_()
if change_operation_3f() then
handle_interrupted_change_op_21()
else
end
do
echo_no_prev_search()
end
doau_when_exists("LightspeedFtLeave")
doau_when_exists("LightspeedLeave")
return nil
end
_214_ = (self.state.cold["in"] or _219_())
elseif (nil ~= _215_) then
local _in = _215_
_214_ = _in
else
_214_ = nil
end
end
if (nil ~= _214_) then
local in1 = _214_
local to_eol_3f = (in1 == "\13")
if not repeat_invoc then
self.state.cold = {["in"] = in1, ["reverse?"] = reverse_3f0, ["t-mode?"] = t_mode_3f0}
else
end
local jump_pos = nil
local match_count = 0
do
local next_pos
local function _224_()
if reverse_3f0 then
return "nWb"
else
return "nW"
end
end
next_pos = vim.fn.searchpos("\\_.", _224_())
local pattern
if to_eol_3f then
pattern = "\\n"
else
local function _225_()
if opts.ignore_case then
return "\\c"
else
return "\\C"
end
end
pattern = ("\\V" .. _225_() .. in1:gsub("\\", "\\\\"))
end
local limit = (count0 + get_num_of_matches_to_be_highlighted())
for _227_ in onscreen_match_positions(pattern, reverse_3f0, {["ft-search?"] = true, limit = limit}) do
local _each_228_ = _227_
local line = _each_228_[1]
local col = _each_228_[2]
local pos = _each_228_
if not ((match_count == 0) and cold_repeat_3f and t_mode_3f0 and same_pos_3f(pos, next_pos)) then
if (match_count <= dec(count0)) then
jump_pos = pos
else
if not op_mode_3f then
hl["add-hl"](hl, hl.group["one-char-match"], dec(line), dec(col), col)
else
end
end
match_count = (match_count + 1)
else
end
end
end
if (not reverted_instant_repeat_3f and ((match_count == 0) or ((match_count == 1) and instant_repeat_3f and t_mode_3f0))) then
if change_operation_3f() then
handle_interrupted_change_op_21()
else
end
do
echo_not_found(in1)
end
doau_when_exists("LightspeedFtLeave")
doau_when_exists("LightspeedLeave")
return nil
else
if not reverted_instant_repeat_3f then
local function _233_()
if t_mode_3f0 then
local function _234_()
if reverse_3f0 then
return "fwd"
else
return "bwd"
end
end
push_cursor_21(_234_())
if (to_eol_3f and not reverse_3f0 and mode:match("n")) then
return push_cursor_21("fwd")
else
return nil
end
else
return nil
end
end
jump_to_21_2a(jump_pos, {mode = mode, ["reverse?"] = reverse_3f0, ["inclusive-motion?"] = true, ["add-to-jumplist?"] = not instant_repeat_3f, adjust = _233_})
else
end
if op_mode_3f then
do
if dot_repeatable_op_3f then
self.state.dot = {["in"] = in1}
set_dot_repeat(replace_keycodes(get_plug_key("ft", reverse_3f0, t_mode_3f0, "dot")), count0)
else
end
end
doau_when_exists("LightspeedFtLeave")
doau_when_exists("LightspeedLeave")
return nil
else
highlight_cursor()
vim.cmd("redraw")
local _239_
local function _240_()
local res_2_auto
do
res_2_auto = get_input(opts.exit_after_idle_msecs.unlabeled)
end
hl:cleanup()
return res_2_auto
end
local function _241_()
do
end
doau_when_exists("LightspeedFtLeave")
doau_when_exists("LightspeedLeave")
return nil
end
_239_ = (_240_() or _241_())
if (nil ~= _239_) then
local in2 = _239_
local stack
local function _243_()
local t_242_ = instant_state
if (nil ~= t_242_) then
t_242_ = (t_242_).stack
else
end
return t_242_
end
stack = (_243_() or {})
local from_reverse_cold_repeat_3f
if instant_repeat_3f then
from_reverse_cold_repeat_3f = instant_state["from-reverse-cold-repeat?"]
else
from_reverse_cold_repeat_3f = (cold_repeat_3f and invoked_as_reverse_3f)
end
local _246_ = get_repeat_action(in2, "ft", t_mode_3f0, instant_repeat_3f, from_reverse_cold_repeat_3f, in1)
if (_246_ == "repeat") then
table.insert(stack, get_cursor_pos())
return ft:go(reverse_3f0, t_mode_3f0, {["in"] = in1, stack = stack, ["reverted?"] = false, ["from-reverse-cold-repeat?"] = from_reverse_cold_repeat_3f})
elseif (_246_ == "revert") then
do
local _247_ = table.remove(stack)
if (nil ~= _247_) then
vim.fn.cursor(_247_)
else
end
end
return ft:go(reverse_3f0, t_mode_3f0, {["in"] = in1, stack = stack, ["reverted?"] = true, ["from-reverse-cold-repeat?"] = from_reverse_cold_repeat_3f})
elseif true then
local _ = _246_
do
vim.fn.feedkeys(in2, "i")
end
doau_when_exists("LightspeedFtLeave")
doau_when_exists("LightspeedLeave")
return nil
else
return nil
end
else
return nil
end
end
end
else
return nil
end
end
do
local deprec_msg = {{"ligthspeed.nvim", "Question"}, {": You're trying to access deprecated fields in the lightspeed.ft table.\n"}, {"There are dedicated <Plug> keys available for native-like "}, {";", "Visual"}, {" and "}, {",", "Visual"}, {" functionality now.\n"}, {"See "}, {":h lightspeed-custom-mappings", "Visual"}, {"."}}
local function _254_(t, k)
if ((k == "instant-repeat?") or (k == "prev-t-like?")) then
return api.nvim_echo(deprec_msg, true, {})
else
return nil
end
end
setmetatable(ft, {__index = _254_})
end
local function highlight_unique_chars(reverse_3f)
local unique_chars = {}
local _let_256_ = get_horizontal_bounds({["match-width"] = 2})
local left_bound = _let_256_[1]
local right_bound = _let_256_[2]
local _let_257_ = get_cursor_pos()
local curline = _let_257_[1]
local curcol = _let_257_[2]
for lnum, line in pairs(get_onscreen_lines({["reverse?"] = reverse_3f, ["skip-folds?"] = true})) do
local on_curline_3f = (lnum == curline)
local startcol
if (on_curline_3f and not reverse_3f) then
startcol = inc(curcol)
else
startcol = 1
end
local endcol
if (on_curline_3f and reverse_3f) then
endcol = dec(curcol)
else
endcol = #line
end
for col = startcol, endcol do
if (vim.wo.wrap or ((col >= left_bound) and (col <= right_bound))) then
local ch = line:sub(col, col)
local ch0
if opts.ignore_case then
ch0 = ch:lower()
else
ch0 = ch
end
local _262_
do
local _261_ = unique_chars[ch0]
if (nil ~= _261_) then
local pos_already_there = _261_
_262_ = false
elseif true then
local _ = _261_
_262_ = {lnum, col}
else
_262_ = nil
end
end
unique_chars[ch0] = _262_
else
end
end
end
for ch, pos in pairs(unique_chars) do
local _267_ = pos
if ((_G.type(_267_) == "table") and (nil ~= (_267_)[1]) and (nil ~= (_267_)[2])) then
local lnum = (_267_)[1]
local col = (_267_)[2]
hl["add-hl"](hl, hl.group["unique-ch"], dec(lnum), dec(col), col)
else
end
end
return nil
end
local function get_targets(input, reverse_3f)
local targets = {}
local to_eol_3f = (input == "\13")
local prev_match = {}
local added_prev_match_3f = nil
local pattern
if to_eol_3f then
pattern = "\\n"
else
local function _269_()
if opts.ignore_case then
return "\\c"
else
return "\\C"
end
end
pattern = ("\\V" .. _269_() .. input:gsub("\\", "\\\\") .. "\\_.")
end
for _271_ in onscreen_match_positions(pattern, reverse_3f, {["to-eol?"] = to_eol_3f}) do
local _each_272_ = _271_
local line = _each_272_[1]
local col = _each_272_[2]
local pos = _each_272_
if to_eol_3f then
table.insert(targets, {pos = pos, pair = {"\n", ""}})
else
local ch1 = char_at_pos(pos, {})
local ch2 = (char_at_pos(pos, {["char-offset"] = 1}) or "\13")
local to_pre_eol_3f = (ch2 == "\13")
local overlaps_prev_match_3f
local _273_
if reverse_3f then
_273_ = dec
else
_273_ = inc
end
overlaps_prev_match_3f = ((line == prev_match.line) and (col == _273_(prev_match.col)))
local same_char_triplet_3f = (overlaps_prev_match_3f and (ch2 == prev_match.ch2))
local overlaps_prev_target_3f = (overlaps_prev_match_3f and added_prev_match_3f)
prev_match = {line = line, col = col, ch2 = ch2}
if (same_char_triplet_3f and (added_prev_match_3f or opts.match_only_the_start_of_same_char_seqs)) then
added_prev_match_3f = false
else
local target = {pos = pos, pair = {ch1, ch2}}
local prev_target = last(targets)
local match_width = 2
local touches_prev_target_3f
do
local _275_ = prev_target
if ((_G.type(_275_) == "table") and ((_G.type((_275_).pos) == "table") and (nil ~= ((_275_).pos)[1]) and (nil ~= ((_275_).pos)[2]))) then
local prev_line = ((_275_).pos)[1]
local prev_col = ((_275_).pos)[2]
local function _277_()
local col_delta
if reverse_3f then
col_delta = (prev_col - col)
else
col_delta = (col - prev_col)
end
return (col_delta <= match_width)
end
touches_prev_target_3f = ((line == prev_line) and _277_())
else
touches_prev_target_3f = nil
end
end
if to_pre_eol_3f then
target["squeezed?"] = true
else
end
if touches_prev_target_3f then
local _280_
if reverse_3f then
_280_ = target
else
_280_ = prev_target
end
_280_["squeezed?"] = true
else
end
if overlaps_prev_target_3f then
local _283_
if reverse_3f then
_283_ = prev_target
else
_283_ = target
end
_283_["overlapped?"] = true
else
end
table.insert(targets, target)
added_prev_match_3f = true
end
end
end
if next(targets) then
return targets
else
return nil
end
end
local function populate_sublists(targets)
targets["sublists"] = {}
if opts.ignore_case then
local function _289_(self, k)
return rawget(self, k:lower())
end
setmetatable(targets.sublists, {__index = _289_})
else
end
for _, _291_ in ipairs(targets) do
local _each_292_ = _291_
local _each_293_ = _each_292_["pair"]
local _0 = _each_293_[1]
local ch2 = _each_293_[2]
local target = _each_292_
local k
if opts.ignore_case then
k = ch2:lower()
else
k = ch2
end
if not targets.sublists[k] then
targets["sublists"][k] = {}
else
end
table.insert(targets.sublists[k], target)
end
return nil
end
local function get_labels(sublist, to_eol_3f)
if to_eol_3f then
sublist["autojump?"] = false
else
end
if (not opts.safe_labels or empty_3f(opts.safe_labels)) then
if (sublist["autojump?"] == nil) then
sublist["autojump?"] = false
else
end
return opts.labels
elseif (not opts.labels or empty_3f(opts.labels)) then
if (sublist["autojump?"] == nil) then
sublist["autojump?"] = true
else
end
return opts.safe_labels
else
local _299_ = sublist["autojump?"]
if (_299_ == true) then
return opts.safe_labels
elseif (_299_ == false) then
return opts.labels
elseif (_299_ == nil) then
sublist["autojump?"] = (not operator_pending_mode_3f() and (dec(#sublist) <= #opts.safe_labels))
return get_labels(sublist)
else
return nil
end
end
end
local function set_labels(targets, to_eol_3f)
for _, sublist in pairs(targets.sublists) do
if (#sublist > 1) then
local labels = get_labels(sublist, to_eol_3f)
for i, target in ipairs(sublist) do
local _302_
if not (sublist["autojump?"] and (i == 1)) then
local _303_
local function _305_()
if sublist["autojump?"] then
return dec(i)
else
return i
end
end
_303_ = (_305_() % #labels)
if (_303_ == 0) then
_302_ = last(labels)
elseif (nil ~= _303_) then
local n = _303_
_302_ = labels[n]
else
_302_ = nil
end
else
_302_ = nil
end
target["label"] = _302_
end
else
end
end
return nil
end
local function set_label_states_for_sublist(sublist, _311_)
local _arg_312_ = _311_
local group_offset = _arg_312_["group-offset"]
local labels = get_labels(sublist)
local _7clabels_7c = #labels
local offset = (group_offset * _7clabels_7c)
local primary_start
local function _313_()
if sublist["autojump?"] then
return 2
else
return 1
end
end
primary_start = (offset + _313_())
local primary_end = (primary_start + dec(_7clabels_7c))
local secondary_end = (primary_end + _7clabels_7c)
for i, target in ipairs(sublist) do
local _314_
if target.label then
if ((i < primary_start) or (i > secondary_end)) then
_314_ = "inactive"
elseif (i <= primary_end) then
_314_ = "active-primary"
else
_314_ = "active-secondary"
end
else
_314_ = nil
end
target["label-state"] = _314_
end
return nil
end
local function set_label_states(targets)
for _, sublist in pairs(targets.sublists) do
set_label_states_for_sublist(sublist, {["group-offset"] = 0})
end
return nil
end
local function set_shortcuts_and_populate_shortcuts_map(targets)
targets["shortcuts"] = {}
local potential_2nd_inputs
do
local tbl_12_auto = {}
for ch2, _ in pairs(targets.sublists) do
local _317_, _318_ = ch2, true
if ((nil ~= _317_) and (nil ~= _318_)) then
local k_13_auto = _317_
local v_14_auto = _318_
tbl_12_auto[k_13_auto] = v_14_auto
else
end
end
potential_2nd_inputs = tbl_12_auto
end
local labels_used_up_as_shortcut = {}
for _, _320_ in ipairs(targets) do
local _each_321_ = _320_
local label = _each_321_["label"]
local label_state = _each_321_["label-state"]
local target = _each_321_
if (label_state == "active-primary") then
if not ((potential_2nd_inputs)[label] or labels_used_up_as_shortcut[label]) then
target["shortcut?"] = true
targets.shortcuts[label] = target
labels_used_up_as_shortcut[label] = true
else
end
else
end
end
return nil
end
local function set_beacon(_324_, _repeat)
local _arg_325_ = _324_
local _arg_326_ = _arg_325_["pos"]
local _ = _arg_326_[1]
local col = _arg_326_[2]
local _arg_327_ = _arg_325_["pair"]
local ch1 = _arg_327_[1]
local ch2 = _arg_327_[2]
local label = _arg_325_["label"]
local label_state = _arg_325_["label-state"]
local squeezed_3f = _arg_325_["squeezed?"]
local overlapped_3f = _arg_325_["overlapped?"]
local shortcut_3f = _arg_325_["shortcut?"]
local target = _arg_325_
local to_eol_3f = ((ch1 == "\n") and (ch2 == ""))
local _let_328_ = get_horizontal_bounds({["match-width"] = 1})
local left_bound = _let_328_[1]
local right_bound = _let_328_[2]
local function _330_(_241)
return (opts.substitute_chars[_241] or _241)
end
local _let_329_ = map(_330_, {ch1, ch2})
local ch10 = _let_329_[1]
local ch20 = _let_329_[2]
local masked_char_24 = {ch20, hl.group["masked-ch"]}
local label_24 = {label, hl.group.label}
local shortcut_24 = {label, hl.group.shortcut}
local distant_label_24 = {label, hl.group["label-distant"]}
local overlapped_label_24 = {label, hl.group["label-overlapped"]}
local overlapped_shortcut_24 = {label, hl.group["shortcut-overlapped"]}
local overlapped_distant_label_24 = {label, hl.group["label-distant-overlapped"]}
do
local _331_ = label_state
if (_331_ == nil) then
if not (_repeat or to_eol_3f) then
if overlapped_3f then
target.beacon = {1, {{ch20, hl.group["unlabeled-match"]}}}
else
target.beacon = {0, {{(ch10 .. ch20), hl.group["unlabeled-match"]}}}
end
else
target.beacon = nil
end
elseif (_331_ == "active-primary") then
if to_eol_3f then
if (vim.wo.wrap or ((col <= right_bound) and (col >= left_bound))) then
target.beacon = {0, {shortcut_24}}
elseif (col > right_bound) then
target.beacon = {dec((right_bound - col)), {shortcut_24, {">", hl.group["one-char-match"]}}}
elseif (col < left_bound) then
target.beacon = {0, {{"<", hl.group["one-char-match"]}, shortcut_24}, "left-off"}
else
target.beacon = nil
end
elseif _repeat then
local _335_
if squeezed_3f then
_335_ = 1
else
_335_ = 2
end
target.beacon = {_335_, {shortcut_24}}
elseif shortcut_3f then
if overlapped_3f then
target.beacon = {1, {overlapped_shortcut_24}}
else
if squeezed_3f then
target.beacon = {0, {masked_char_24, shortcut_24}}
else
target.beacon = {2, {shortcut_24}}
end
end
elseif overlapped_3f then
target.beacon = {1, {overlapped_label_24}}
elseif squeezed_3f then
target.beacon = {0, {masked_char_24, label_24}}
else
target.beacon = {2, {label_24}}
end
elseif (_331_ == "active-secondary") then
if to_eol_3f then
if (vim.wo.wrap or ((col <= right_bound) and (col >= left_bound))) then
target.beacon = {0, {distant_label_24}}
elseif (col > right_bound) then
target.beacon = {dec((right_bound - col)), {distant_label_24, {">", hl.group["unlabeled-match"]}}}
elseif (col < left_bound) then
target.beacon = {0, {{"<", hl.group["unlabeled-match"]}, distant_label_24}, "left-off"}
else
target.beacon = nil
end
elseif _repeat then
local _341_
if squeezed_3f then
_341_ = 1
else
_341_ = 2
end
target.beacon = {_341_, {distant_label_24}}
elseif overlapped_3f then
target.beacon = {1, {overlapped_distant_label_24}}
elseif squeezed_3f then
target.beacon = {0, {masked_char_24, distant_label_24}}
else
target.beacon = {2, {distant_label_24}}
end
elseif (_331_ == "inactive") then
target.beacon = nil
else
target.beacon = nil
end
end
return nil
end
local function set_beacons(target_list, _345_)
local _arg_346_ = _345_
local _repeat = _arg_346_["repeat"]
for _, target in ipairs(target_list) do
set_beacon(target, _repeat)
end
return nil
end
local function light_up_beacons(target_list, _3fstart_idx)
for i = (_3fstart_idx or 1), #target_list do
local _let_347_ = target_list[i]
local _let_348_ = _let_347_["pos"]
local line = _let_348_[1]
local col = _let_348_[2]
local beacon = _let_347_["beacon"]
local _349_ = beacon
if ((_G.type(_349_) == "table") and (nil ~= (_349_)[1]) and (nil ~= (_349_)[2]) and true) then
local offset = (_349_)[1]
local chunks = (_349_)[2]
local _3fleft_off_3f = (_349_)[3]
local _350_
if _3fleft_off_3f then
_350_ = 0
else
_350_ = nil
end
hl["set-extmark"](hl, dec(line), dec((col + offset)), {virt_text = chunks, virt_text_pos = "overlay", virt_text_win_col = _350_})
else
end
end
return nil
end
local function get_target_with_active_primary_label(target_list, input)
local res = nil
for _, _353_ in ipairs(target_list) do
local _each_354_ = _353_
local label = _each_354_["label"]
local label_state = _each_354_["label-state"]
local target = _each_354_
if res then break end
if ((label == input) and (label_state == "active-primary")) then
res = target
else
end
end
return res
end
local function ignore_input_until_timeout(char_to_ignore)
local _356_ = get_input(opts.jump_on_partial_input_safety_timeout)
if (nil ~= _356_) then
local input = _356_
if (input ~= char_to_ignore) then
return vim.fn.feedkeys(input, "i")
else
return nil
end
else
return nil
end
end
local sx = {state = {dot = {in1 = nil, in2 = nil, in3 = nil}, cold = {in1 = nil, in2 = nil, ["reverse?"] = nil, ["x-mode?"] = nil}}}
sx.go = function(self, reverse_3f, x_mode_3f, repeat_invoc)
local mode = api.nvim_get_mode().mode
local op_mode_3f = mode:match("o")
local change_op_3f = (op_mode_3f and (vim.v.operator == "c"))
local delete_op_3f = (op_mode_3f and (vim.v.operator == "d"))
local dot_repeatable_op_3f = (op_mode_3f and (vim.v.operator ~= "y"))
local instant_repeat_3f = (type(repeat_invoc) == "table")
local instant_state
if instant_repeat_3f then
instant_state = repeat_invoc
else
instant_state = nil
end
local cold_repeat_3f = (repeat_invoc == "cold")
local dot_repeat_3f = (repeat_invoc == "dot")
local invoked_as_reverse_3f = reverse_3f
local reverse_3f0
if cold_repeat_3f then
local function _360_(_241)
if invoked_as_reverse_3f then
return not _241
else
return _241
end
end
reverse_3f0 = _360_(self.state.cold["reverse?"])
else
reverse_3f0 = reverse_3f
end
local x_mode_3f0
if cold_repeat_3f then
x_mode_3f0 = self.state.cold["x-mode?"]
else
x_mode_3f0 = x_mode_3f
end
local new_search_3f = not repeat_invoc
local backspace_repeat_3f = nil
local to_eol_3f = nil
local to_pre_eol_3f = nil
local function get_first_input()
if instant_repeat_3f then
return instant_state.in1
elseif dot_repeat_3f then
return self.state.dot.in1
elseif cold_repeat_3f then
return self.state.cold.in1
else
local _364_
local function _365_()
local res_2_auto
do
res_2_auto = get_input()
end
hl:cleanup()
return res_2_auto
end
local function _366_()
if change_operation_3f() then
handle_interrupted_change_op_21()
else
end
do
end
doau_when_exists("LightspeedSxLeave")
doau_when_exists("LightspeedLeave")
return nil
end
_364_ = (_365_() or _366_())
if (_364_ == _3cbackspace_3e) then
backspace_repeat_3f = true
new_search_3f = false
local function _368_()
if change_operation_3f() then
handle_interrupted_change_op_21()
else
end
do
echo_no_prev_search()
end
doau_when_exists("LightspeedSxLeave")
doau_when_exists("LightspeedLeave")
return nil
end
return (self.state.cold.in1 or _368_())
elseif (nil ~= _364_) then
local _in = _364_
return _in
else
return nil
end
end
end
local function update_state_2a(in1)
local function _374_(_372_)
local _arg_373_ = _372_
local cold = _arg_373_["cold"]
local dot = _arg_373_["dot"]
if new_search_3f then
if cold then
local _375_ = cold
_375_["in1"] = in1
_375_["x-mode?"] = x_mode_3f0
_375_["reverse?"] = reverse_3f0
self.state.cold = _375_
else
end
if dot then
if dot_repeatable_op_3f then
do
local _377_ = dot
_377_["in1"] = in1
_377_["x-mode?"] = x_mode_3f0
self.state.dot = _377_
end
return nil
else
return nil
end
else
return nil
end
else
return nil
end
end
return _374_
end
local jump_to_21
do
local first_jump_3f = true
local function _381_(target, _3fto_pre_eol_3f)
local to_pre_eol_3f0 = (_3fto_pre_eol_3f or to_pre_eol_3f)
local adjusted_pos
local function _382_()
if to_eol_3f then
if op_mode_3f then
return push_cursor_21("fwd")
else
return nil
end
elseif to_pre_eol_3f0 then
if (op_mode_3f and x_mode_3f0) then
return push_cursor_21("fwd")
else
return nil
end
elseif x_mode_3f0 then
push_cursor_21("fwd")
if reverse_3f0 then
return push_cursor_21("fwd")
else
return nil
end
else
return nil
end
end
adjusted_pos = jump_to_21_2a(target, {mode = mode, ["reverse?"] = reverse_3f0, ["inclusive-motion?"] = (x_mode_3f0 and not reverse_3f0), ["add-to-jumplist?"] = (first_jump_3f and not instant_repeat_3f), adjust = _382_})
first_jump_3f = false
return adjusted_pos
end
jump_to_21 = _381_
end
local function highlight_new_curpos_and_op_area(from_pos, to_pos)
local motion_force = get_motion_force(mode)
local blockwise_3f = (motion_force == _3cctrl_v_3e)
local function _388_()
if reverse_3f0 then
return to_pos
else
return from_pos
end
end
local _let_387_ = _388_()
local startline = _let_387_[1]
local startcol = _let_387_[2]
local start = _let_387_
local function _390_()
if reverse_3f0 then
return from_pos
else
return to_pos
end
end
local _let_389_ = _390_()
local _ = _let_389_[1]
local endcol = _let_389_[2]
local _end = _let_389_
local top_left = {startline, min(startcol, endcol)}
local new_curpos
if op_mode_3f then
if blockwise_3f then
new_curpos = top_left
else
new_curpos = start
end
else
new_curpos = to_pos
end
if not change_op_3f then
highlight_cursor(new_curpos)
else
end
if op_mode_3f then
highlight_range(hl.group["pending-op-area"], map(dec, start), map(dec, _end), {["motion-force"] = motion_force, ["inclusive-motion?"] = (x_mode_3f0 and not reverse_3f0)})
else
end
return vim.cmd("redraw")
end
local function get_sublist(targets, ch)
local _395_ = targets.sublists[ch]
if (nil ~= _395_) then
local sublist = _395_
local _let_396_ = sublist
local _let_397_ = _let_396_[1]
local _let_398_ = _let_397_["pos"]
local line = _let_398_[1]
local col = _let_398_[2]
local rest = (function (t, k) local mt = getmetatable(t) if "table" == type(mt) and mt.__fennelrest then return mt.__fennelrest(t, k) else return {(table.unpack or unpack)(t, k)} end end)(_let_396_, 2)
local target_tail = {line, inc(col)}
local prev_pos = vim.fn.searchpos("\\_.", "nWb")
local cursor_touches_first_target_3f = same_pos_3f(target_tail, prev_pos)
if (cold_repeat_3f and x_mode_3f0 and reverse_3f0 and cursor_touches_first_target_3f) then
if not empty_3f(rest) then
return rest
else
return nil
end
else
return sublist
end
else
return nil
end
end
local function get_last_input(sublist, start_idx)
local next_group_key = replace_keycodes(opts.cycle_group_fwd_key)
local prev_group_key = replace_keycodes(opts.cycle_group_bwd_key)
local function recur(group_offset, initial_invoc_3f)
local _402_
if (cold_repeat_3f or backspace_repeat_3f) then
_402_ = "cold"
elseif instant_repeat_3f then
_402_ = "instant"
else
_402_ = nil
end
set_beacons(sublist, {["repeat"] = _402_})
do
if (opts.grey_out_search_area and not (cold_repeat_3f or instant_repeat_3f or to_eol_3f)) then
grey_out_search_area(reverse_3f0)
else
end
do
light_up_beacons(sublist, start_idx)
end
highlight_cursor()
vim.cmd("redraw")
end
local _405_
do
local res_2_auto
do
local function _406_()
if initial_invoc_3f then
return opts.exit_after_idle_msecs.labeled
else
return nil
end
end
res_2_auto = get_input(_406_())
end
hl:cleanup()
_405_ = res_2_auto
end
if (nil ~= _405_) then
local input = _405_
if (sublist["autojump?"] and opts.labels and not empty_3f(opts.labels)) then
return {input, 0}
elseif (((input == next_group_key) or (input == prev_group_key)) and not instant_repeat_3f) then
local labels = get_labels(sublist)
local num_of_groups = ceil((#sublist / #labels))
local max_offset = dec(num_of_groups)
local group_offset_2a
local _408_
do
local _407_ = input
if (_407_ == next_group_key) then
_408_ = inc
elseif true then
local _ = _407_
_408_ = dec
else
_408_ = nil
end
end
group_offset_2a = clamp(_408_(group_offset), 0, max_offset)
set_label_states_for_sublist(sublist, {["group-offset"] = group_offset_2a})
return recur(group_offset_2a)
else
return {input, group_offset}
end
else
return nil
end
end
return recur(0, true)
end
enter("sx")
if not repeat_invoc then
echo("")
if (opts.grey_out_search_area and not (cold_repeat_3f or instant_repeat_3f or to_eol_3f)) then
grey_out_search_area(reverse_3f0)
else
end
do
if opts.highlight_unique_chars then
highlight_unique_chars(reverse_3f0)
else
end
end
highlight_cursor()
vim.cmd("redraw")
else
end
local _417_ = get_first_input()
if (nil ~= _417_) then
local in1 = _417_
local _
to_eol_3f = (in1 == "\13")
_ = nil
local from_pos = get_cursor_pos()
local update_state = update_state_2a(in1)
local prev_in2
if instant_repeat_3f then
prev_in2 = instant_state.in2
elseif (cold_repeat_3f or backspace_repeat_3f) then
prev_in2 = self.state.cold.in2
elseif dot_repeat_3f then
prev_in2 = self.state.dot.in2
else
prev_in2 = nil
end
local _419_
local function _421_()
local t_420_ = instant_state
if (nil ~= t_420_) then
t_420_ = (t_420_).sublist
else
end
return t_420_
end
local function _423_()
if change_operation_3f() then
handle_interrupted_change_op_21()
else
end
do
echo_not_found((in1 .. (prev_in2 or "")))
end
doau_when_exists("LightspeedSxLeave")
doau_when_exists("LightspeedLeave")
return nil
end
_419_ = (_421_() or get_targets(in1, reverse_3f0) or _423_())
if ((_G.type(_419_) == "table") and ((_G.type((_419_)[1]) == "table") and ((_G.type(((_419_)[1]).pair) == "table") and true and (nil ~= (((_419_)[1]).pair)[2]))) and ((_419_)[2] == nil)) then
local _0 = (((_419_)[1]).pair)[1]
local ch2 = (((_419_)[1]).pair)[2]
local only = (_419_)[1]
if (new_search_3f or (ch2 == prev_in2)) then
do
if dot_repeatable_op_3f then
set_dot_repeat(replace_keycodes(get_plug_key("sx", reverse_3f0, x_mode_3f0, "dot")))
else
end
update_state({cold = {in2 = ch2}, dot = {in2 = ch2, in3 = opts.labels[1]}})
local to_pos = jump_to_21(only.pos, (ch2 == "\13"))
if new_search_3f then
local res_2_auto
do
highlight_new_curpos_and_op_area(from_pos, to_pos)
res_2_auto = ignore_input_until_timeout(ch2)
end
hl:cleanup()
else
end
end
doau_when_exists("LightspeedSxLeave")
doau_when_exists("LightspeedLeave")
return nil
else
if change_operation_3f() then
handle_interrupted_change_op_21()
else
end
do
echo_not_found((in1 .. prev_in2))
end
doau_when_exists("LightspeedSxLeave")
doau_when_exists("LightspeedLeave")
return nil
end
elseif (nil ~= _419_) then
local targets = _419_
if not instant_repeat_3f then
local _429_ = targets
populate_sublists(_429_)
set_labels(_429_, to_eol_3f)
set_label_states(_429_)
else
end
if (new_search_3f and not to_eol_3f) then
do
local _431_ = targets
set_shortcuts_and_populate_shortcuts_map(_431_)
set_beacons(_431_, {["repeat"] = nil})
end
if (opts.grey_out_search_area and not (cold_repeat_3f or instant_repeat_3f or to_eol_3f)) then
grey_out_search_area(reverse_3f0)
else
end
do
light_up_beacons(targets)
end
highlight_cursor()
vim.cmd("redraw")
else
end
local _434_
local function _435_()
if to_eol_3f then
return ""
else
return nil
end
end
local function _436_()
local res_2_auto
do
res_2_auto = get_input()
end
hl:cleanup()
return res_2_auto
end
local function _437_()
if change_operation_3f() then
handle_interrupted_change_op_21()
else
end
do
end
doau_when_exists("LightspeedSxLeave")
doau_when_exists("LightspeedLeave")
return nil
end
_434_ = (prev_in2 or _435_() or _436_() or _437_())
if (nil ~= _434_) then
local in2 = _434_
local _439_
do
local t_440_ = targets.shortcuts
if (nil ~= t_440_) then
t_440_ = (t_440_)[in2]
else
end
_439_ = t_440_
end
if ((_G.type(_439_) == "table") and ((_G.type((_439_).pair) == "table") and true and (nil ~= ((_439_).pair)[2]))) then
local _0 = ((_439_).pair)[1]
local ch2 = ((_439_).pair)[2]
local shortcut = _439_
do
if dot_repeatable_op_3f then
set_dot_repeat(replace_keycodes(get_plug_key("sx", reverse_3f0, x_mode_3f0, "dot")))
else
end
update_state({cold = {in2 = ch2}, dot = {in2 = ch2, in3 = in2}})
jump_to_21(shortcut.pos, (ch2 == "\13"))
end
doau_when_exists("LightspeedSxLeave")
doau_when_exists("LightspeedLeave")
return nil
elseif true then
local _0 = _439_
to_pre_eol_3f = (in2 == "\13")
update_state({cold = {in2 = in2}})
local _443_
local function _445_()
local t_444_ = instant_state
if (nil ~= t_444_) then
t_444_ = (t_444_).sublist
else
end
return t_444_
end
local function _447_()
if change_operation_3f() then
handle_interrupted_change_op_21()
else
end
do
echo_not_found((in1 .. in2))
end
doau_when_exists("LightspeedSxLeave")
doau_when_exists("LightspeedLeave")
return nil
end
_443_ = (_445_() or get_sublist(targets, in2) or _447_())
if ((_G.type(_443_) == "table") and (nil ~= (_443_)[1]) and ((_443_)[2] == nil)) then
local only = (_443_)[1]
do
if dot_repeatable_op_3f then
set_dot_repeat(replace_keycodes(get_plug_key("sx", reverse_3f0, x_mode_3f0, "dot")))
else
end
update_state({dot = {in2 = in2, in3 = opts.labels[1]}})
jump_to_21(only.pos)
end
doau_when_exists("LightspeedSxLeave")
doau_when_exists("LightspeedLeave")
return nil
elseif ((_G.type(_443_) == "table") and (nil ~= (_443_)[1])) then
local first = (_443_)[1]
local sublist = _443_
local autojump_3f = sublist["autojump?"]
local curr_idx
local function _451_()
local t_450_ = instant_state
if (nil ~= t_450_) then
t_450_ = (t_450_).idx
else
end
return t_450_
end
local function _453_()
if autojump_3f then
return 1
else
return 0
end
end
curr_idx = (_451_() or _453_())
local from_reverse_cold_repeat_3f
if instant_repeat_3f then
from_reverse_cold_repeat_3f = instant_state["from-reverse-cold-repeat?"]
else
from_reverse_cold_repeat_3f = (cold_repeat_3f and invoked_as_reverse_3f)
end
if (autojump_3f and not instant_repeat_3f) then
jump_to_21(first.pos)
else
end
local _456_
local function _457_()
if (dot_repeat_3f and self.state.dot.in3) then
return {self.state.dot.in3, 0}
else
return nil
end
end
local function _458_()
if change_operation_3f() then
handle_interrupted_change_op_21()
else
end
do
end
doau_when_exists("LightspeedSxLeave")
doau_when_exists("LightspeedLeave")
return nil
end
_456_ = (_457_() or get_last_input(sublist, inc(curr_idx)) or _458_())
if ((_G.type(_456_) == "table") and (nil ~= (_456_)[1]) and (nil ~= (_456_)[2])) then
local in3 = (_456_)[1]
local group_offset = (_456_)[2]
local _460_
if not (op_mode_3f or (group_offset > 0)) then
_460_ = get_repeat_action(in3, "sx", x_mode_3f0, instant_repeat_3f, from_reverse_cold_repeat_3f)
else
_460_ = nil
end
if (nil ~= _460_) then
local action = _460_
local idx
do
local _462_ = action
if (_462_ == "repeat") then
idx = min(inc(curr_idx), #targets)
elseif (_462_ == "revert") then
idx = max(dec(curr_idx), 1)
else
idx = nil
end
end
jump_to_21(sublist[idx].pos)
return sx:go(reverse_3f0, x_mode_3f0, {in1 = in1, in2 = in2, sublist = sublist, idx = idx, ["from-reverse-cold-repeat?"] = from_reverse_cold_repeat_3f})
elseif true then
local _1 = _460_
local _464_ = get_target_with_active_primary_label(sublist, in3)
if (nil ~= _464_) then
local target = _464_
do
if dot_repeatable_op_3f then
set_dot_repeat(replace_keycodes(get_plug_key("sx", reverse_3f0, x_mode_3f0, "dot")))
else
end
local _466_
if (group_offset > 0) then
_466_ = nil
else
_466_ = in3
end
update_state({dot = {in2 = in2, in3 = _466_}})
jump_to_21(target.pos)
end
doau_when_exists("LightspeedSxLeave")
doau_when_exists("LightspeedLeave")
return nil
elseif true then
local _2 = _464_
if autojump_3f then
do
if dot_repeatable_op_3f then
set_dot_repeat(replace_keycodes(get_plug_key("sx", reverse_3f0, x_mode_3f0, "dot")))
else
end
vim.fn.feedkeys(in3, "i")
end
doau_when_exists("LightspeedSxLeave")
doau_when_exists("LightspeedLeave")
return nil
else
if change_operation_3f() then
handle_interrupted_change_op_21()
else
end
do
end
doau_when_exists("LightspeedSxLeave")
doau_when_exists("LightspeedLeave")
return nil
end
else
return nil
end
else
return nil
end
else
return nil
end
else
return nil
end
else
return nil
end
else
return nil
end
else
return nil
end
else
return nil
end
end
local temporary_editor_opts = {["vim.wo.conceallevel"] = 0, ["vim.wo.scrolloff"] = 0, ["vim.bo.modeline"] = false}
local saved_editor_opts = {}
local function save_editor_opts()
for opt, _ in pairs(temporary_editor_opts) do
local _let_479_ = vim.split(opt, ".", true)
local _0 = _let_479_[1]
local scope = _let_479_[2]
local name = _let_479_[3]
local _480_
if (opt == "vim.wo.scrolloff") then
_480_ = api.nvim_eval("&l:scrolloff")
else
_480_ = _G.vim[scope][name]
end
saved_editor_opts[opt] = _480_
end
return nil
end
local function set_editor_opts(opts0)
for opt, val in pairs(opts0) do
local _let_482_ = vim.split(opt, ".", true)
local _ = _let_482_[1]
local scope = _let_482_[2]
local name = _let_482_[3]
_G.vim[scope][name] = val
end
return nil
end
local function set_temporary_editor_opts()
return set_editor_opts(temporary_editor_opts)
end
local function restore_editor_opts()
return set_editor_opts(saved_editor_opts)
end
init_highlight()
vim.cmd("augroup lightspeed_reinit_highlight\n autocmd!\n autocmd ColorScheme * lua require'lightspeed'.init_highlight()\n augroup end")
vim.cmd("augroup lightspeed_editor_opts\n autocmd!\n autocmd User LightspeedEnter lua require'lightspeed'.save_editor_opts(); require'lightspeed'.set_temporary_editor_opts()\n autocmd User LightspeedLeave lua require'lightspeed'.restore_editor_opts()\n augroup end")
return {opts = opts, setup = setup, ft = ft, sx = sx, save_editor_opts = save_editor_opts, set_temporary_editor_opts = set_temporary_editor_opts, restore_editor_opts = restore_editor_opts, init_highlight = init_highlight, set_default_keymaps = set_default_keymaps}
|
local tablex = require "pl.tablex"
local pretty = require "pl.pretty"
local utils = require "kong.tools.utils"
local cjson = require "cjson"
local setmetatable = setmetatable
local re_find = ngx.re.find
local concat = table.concat
local insert = table.insert
local assert = assert
local ipairs = ipairs
local pairs = pairs
local pcall = pcall
local floor = math.floor
local type = type
local next = next
local time = ngx.time
local null = ngx.null
local max = math.max
local sub = string.sub
local Schema = {}
Schema.__index = Schema
local validation_errors = {
-- general message
ERROR = "Validation error: %s",
-- types
ARRAY = "expected an array",
SET = "expected a set",
MAP = "expected a map",
RECORD = "expected a record",
STRING = "expected a string",
NUMBER = "expected a number",
BOOLEAN = "expected a boolean",
INTEGER = "expected an integer",
FUNCTION = "expected a function",
-- validations
BETWEEN = "value should be between %d and %d",
LEN_EQ = "length must be %d",
LEN_MIN = "length must be at least %d",
LEN_MAX = "length must be at most %d",
MATCH = "invalid value: %s",
NOT_MATCH = "invalid value: %s",
MATCH_ALL = "invalid value: %s",
MATCH_NONE = "invalid value: %s",
MATCH_ANY = "invalid value: %s",
STARTS_WITH = "should start with: %s",
ONE_OF = "expected one of: %s",
TIMESTAMP = "expected a valid timestamp",
UUID = "expected a valid UUID",
VALIDATION = "failed validating: %s",
-- field presence
NOT_NULLABLE = "field is not nullable",
BAD_INPUT = "expected an input table",
REQUIRED = "required field missing",
NO_FOREIGN_DEFAULT = "will not generate a default value for a foreign field",
UNKNOWN = "unknown field",
-- entity checks
REQUIRED_FOR_ENTITY_CHECK = "field required for entity check",
ENTITY_CHECK = "failed entity check: %s(%s)",
ENTITY_CHECK_N_FIELDS = "entity check requires %d fields",
CHECK = "entity check failed",
CONDITIONAL = "failed conditional validation",
AT_LEAST_ONE_OF = "at least one of these fields must be non-empty: %s",
ONLY_ONE_OF = "only one of these fields must be non-empty: %s",
-- schema error
SCHEMA_NO_DEFINITION = "expected a definition table",
SCHEMA_NO_FIELDS = "error in schema definition: no 'fields' table",
SCHEMA_MISSING_ATTRIBUTE = "error in schema definition: missing attribute",
SCHEMA_BAD_REFERENCE = "schema refers to an invalid foreign entity: %s",
SCHEMA_TYPE = "invalid type: %s",
-- primary key errors
NOT_PK = "not a primary key",
MISSING_PK = "missing primary key",
}
Schema.valid_types = {
array = true,
set = true,
string = true,
number = true,
boolean = true,
integer = true,
foreign = true,
map = true,
record = true,
}
local uuid_regex = "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$"
local function make_length_validator(err, fn)
return function(value, n, field)
local len = #value
if field.type == "map" then
for _ in pairs(value) do
len = len + 1
end
end
if fn(len, n) then
return true
end
return nil, validation_errors[err]:format(n)
end
end
--- Validator functions available for schemas.
-- A validator can only affect one field.
-- Each validation is registered in a schema field definition as
-- a key-value pair. The key is the validation name and the value
-- is an optional argument (by convention, `true` if the argument
-- is to be ignored). Each validation function takes as inputs
-- the value to be validated and the argument given in the schema
-- definition. The function should return true or nil,
-- optionally followed by an error message. If the error message
-- is not given, the validation name (in uppercase) is used as
-- a key in `validation_errors` to get a message. If it was not
-- registered, a generic fallback error message is produced with
-- `validation_errors.VALIDATION`.
Schema.validators = {
between = function(value, limits)
if value < limits[1] or value > limits[2] then
return nil, validation_errors.BETWEEN:format(limits[1], limits[2])
end
return true
end,
len_eq = make_length_validator("LEN_EQ", function(len, n)
return len == n
end),
len_min = make_length_validator("LEN_MIN", function(len, n)
return len >= n
end),
len_max = make_length_validator("LEN_MAX", function(len, n)
return len <= n
end),
match = function(value, pattern)
local m = value:match(pattern)
if not m then
return nil, validation_errors.MATCH:format(value)
end
return true
end,
not_match = function(value, pattern)
local m = value:match(pattern)
if m then
return nil, validation_errors.NOT_MATCH:format(value)
end
return true
end,
match_all = function(value, list)
for i = 1, #list do
local m = value:match(list[i].pattern)
if not m then
return nil, list[i].err
end
end
return true
end,
match_none = function(value, list)
for i = 1, #list do
local m = value:match(list[i].pattern)
if m then
return nil, list[i].err
end
end
return true
end,
match_any = function(value, arg)
for _, pattern in ipairs(arg.patterns) do
local m = value:match(pattern)
if m then
return true
end
end
return nil, arg.err
end,
starts_with = function(value, expected)
-- produces simpler error messages than 'match'
if sub(value, 1, #expected) ~= expected then
return nil, validation_errors.STARTS_WITH:format(expected)
end
return true
end,
one_of = function(value, options)
for _, option in ipairs(options) do
if value == option then
return true
end
end
return nil, validation_errors.ONE_OF:format(concat(options, ", "))
end,
timestamp = function(value)
return value > 0 or nil
end,
uuid = function(value)
if #value ~= 36 then
return nil
end
return re_find(value, uuid_regex, "ioj") and true or nil
end,
custom_validator = function(value, fn)
return fn(value)
end
}
Schema.validators_order = {
"one_of",
-- type-dependent
"timestamp",
"uuid",
"between",
-- strings (1/2)
"len_eq",
"len_min",
"len_max",
-- strings (2/2)
"starts_with",
"not_match",
"match_none",
"match",
"match_all",
"match_any",
-- other
"custom_validator",
}
--- Returns true if a field is non-empty (with emptiness defined
-- for strings and aggregate values).
-- This function is defined as `is_nonempty` rather than the more intuitive
-- `is_empty` because the former has a less fuzzy definition:
-- being non-empty clearly excludes null and nil values.
-- @param value a value, which may be `ngx.null` or `nil`.
local function is_nonempty(value)
if value == nil
or value == null
or (type(value) == "table" and not next(value))
or (type(value) == "string" and value == "") then
return false
end
return true
end
--- Returns true if a table is a sequence
-- @param t a table to be checked
-- @return `true` if `t` is a sequence, otherwise returns false.
local function is_sequence(t)
if type(t) ~= "table" then
return false
end
local m, c = 0, 0
for k, _ in pairs(t) do
c = c + 1
if t[c] == nil then
return false
end
if type(k) ~= "number" or k < 0 or floor(k) ~= k then
return false
end
m = max(m, k)
end
return c == m
end
--- Produce a nicely quoted list:
-- Given `{"foo", "bar", "baz"}` and `"or"`, produces
-- `"'foo', 'bar', 'baz'"`.
-- @param words an array of strings.
-- @return The string of quoted words.
local function quoted_list(words)
local msg = {}
for _, word in ipairs(words) do
insert(msg, ("'%s'"):format(word))
end
return concat(msg, ", ")
end
local function merge_field(base, overrides)
local field = {}
for k,v in pairs(base) do
field[k] = v
end
for k,v in pairs(overrides) do
field[k] = v
end
return field
end
--- Entity checkers are cross-field validation rules.
-- An entity checker is implemented as an entry in this table,
-- containing a mandatory field `fn`, the checker function,
-- and an optional field `field_sources`.
--
-- An entity checker is used in a schema by adding an entry to
-- the `entity_checks` array of a schema table. Entries
-- in `entity_checks` are tables with a single key, named
-- after the entity checker; its value is the "entity check
-- argument". For example:
--
-- entity_checks = {
-- { only_one_of = { "field_a", "field_b" } },
-- },
--
-- The `fn` function which implements an entity checker receives
-- three arguments: a projection of the entity containing only
-- the relevant fields to this checker, the entity check argument,
-- and the schema table. This ensures that the entity checker
-- does _not_ have access by default to the entire entity being
-- checked. This allows us to enable/disable entity checkers on
-- partial updates.
--
-- To specify which fields are relevant to this checker, one
-- uses the `field_sources`. It is an array of strings, which
-- are key names to the entity check argument (see the `conditional`
-- entity checker for an example of its use).
-- If `field_sources` is not present, it is assumed that the
-- entity check argument is an array of field names, and that
-- all of them need to be present for the entity checker to run.
-- (this is the case, for example, of `only_one_of` in the example
-- above: this checker forces both fields to be given, and the
-- implementation of the checker will demand that only one is
-- non-empty).
Schema.entity_checkers = {
at_least_one_of = {
run_with_missing_fields = true,
fn = function(entity, field_names)
for _, name in ipairs(field_names) do
if is_nonempty(entity[name]) then
return true
end
end
return nil, quoted_list(field_names)
end,
},
only_one_of = {
fn = function(entity, field_names)
local found = false
local ok = false
for _, name in ipairs(field_names) do
if is_nonempty(entity[name]) then
if not found then
found = true
ok = true
else
ok = false
end
end
end
if ok then
return true
end
return nil, quoted_list(field_names)
end,
},
--- Conditional validation: if the first field passes the given validator,
-- then run the validator against the second field.
-- Example:
-- ```
-- conditional = { if_field = "policy",
-- if_match = { match = "^redis$" },
-- then_field = "redis_host",
-- then_match = { required = true } }
-- ```
conditional = {
field_sources = { "if_field", "then_field" },
fn = function(entity, arg, schema)
local if_value = entity[arg.if_field]
local then_value = entity[arg.then_field]
local if_merged = merge_field(schema.fields[arg.if_field], arg.if_match)
local ok, _ = Schema.validate_field(schema, if_merged, if_value)
if not ok then
return true
end
-- Handle `required`
if arg.then_match.required == true and then_value == null then
local field_errors = { [arg.then_field] = validation_errors.REQUIRED }
return nil, validation_errors.CONDITIONAL, field_errors
end
local then_merged = merge_field(schema.fields[arg.then_field], arg.then_match)
local err
ok, err = Schema.validate_field(schema, then_merged, then_value)
if not ok then
local field_errors = { [arg.then_field] = err }
return nil, validation_errors.CONDITIONAL, field_errors
end
return true
end,
},
}
-- Forward declaration
local validate_fields
--- Validate the field according to the schema.
-- For aggregate values, validate each field recursively.
-- @param self The complete schema object.
-- @param field The schema definition for the field.
-- @param value The value to be checked (may be ngx.null).
-- @return true if the field validates correctly;
-- nil and an error message on failure.
function Schema:validate_field(field, value)
if value == null then
if field.nullable == false then
return nil, validation_errors.NOT_NULLABLE
else
return true
end
end
if field.type == "array" then
if not is_sequence(value) then
return nil, validation_errors.ARRAY
end
if not field.elements then
return nil, validation_errors.SCHEMA_MISSING_ATTRIBUTE:format("elements")
end
field.elements.nullable = false
for _, v in ipairs(value) do
local ok, err = self:validate_field(field.elements, v)
if not ok then
return nil, err
end
end
for k, _ in pairs(value) do
if type(k) ~= "number" then
return nil, validation_errors.ARRAY
end
end
elseif field.type == "set" then
if not is_sequence(value) then
return nil, validation_errors.SET
end
if not field.elements then
return nil, validation_errors.SCHEMA_MISSING_ATTRIBUTE:format("elements")
end
field.elements.nullable = false
local set = {}
for _, v in ipairs(value) do
if not set[v] then
local ok, err = self:validate_field(field.elements, v)
if not ok then
return nil, err
end
set[v] = true
end
end
elseif field.type == "map" then
if type(value) ~= "table" then
return nil, validation_errors.MAP
end
if not field.keys then
return nil, validation_errors.SCHEMA_MISSING_ATTRIBUTE:format("keys")
end
if not field.values then
return nil, validation_errors.SCHEMA_MISSING_ATTRIBUTE:format("values")
end
field.keys.nullable = false
field.values.nullable = false
for k, v in pairs(value) do
local ok, err
ok, err = self:validate_field(field.keys, k)
if not ok then
return nil, err
end
ok, err = self:validate_field(field.values, v)
if not ok then
return nil, err
end
end
elseif field.type == "record" then
if type(value) ~= "table" then
return nil, validation_errors.RECORD
end
if not field.fields then
return nil, validation_errors.SCHEMA_MISSING_ATTRIBUTE:format("fields")
end
local subschema = Schema.new(field)
-- TODO return nested table or string?
local copy = subschema:process_auto_fields(value, "insert")
local ok, err = subschema:validate(copy)
if not ok then
return nil, err
end
elseif field.type == "foreign" then
local ok, errs = field.schema:validate_primary_key(value, true)
if not ok then
-- TODO check with GUI team if they need prefer information
-- of failed components of a compound foreign key
-- as a nested table or just as a flat string.
return nil, errs
end
elseif field.type == "integer" then
if not (type(value) == "number"
and value == floor(value)
and value ~= 1/0
and value ~= -1/0) then
return nil, validation_errors.INTEGER
end
elseif field.type == "string" then
if type(value) ~= "string" then
return nil, validation_errors.STRING
end
-- empty strings are not accepted by default
if not field.len_min then
field.len_min = 1
end
elseif field.type == "function" then
-- TODO: this type should only be used/visible from the
-- metachema to validate the 'custom_validator'
if type(value) ~= "function" then
return nil, validation_errors.FUNCTION
end
elseif self.valid_types[field.type] then
if type(value) ~= field.type then
return nil, validation_errors[field.type:upper()]
end
else
return nil, validation_errors.SCHEMA_TYPE:format(field.type)
end
for _, k in ipairs(Schema.validators_order) do
if field[k] then
local ok, err = self.validators[k](value, field[k], field)
if not ok then
return nil, err
or validation_errors[k:upper()]
or validation_errors.VALIDATION:format(k)
end
end
end
return true
end
--- Produce a default value for a given field.
-- @param field The field definition table.
-- @return A default value. All fields are nullable by default and return
-- `ngx.null`, unless explicitly configured not to with `nullable = false`,
-- in which case they return a type-specific default.
-- If a default value cannot be produced (due to circumstances that
-- will produce errors later on validation), it simply returns `nil`.
local function default_value(field)
if field.nullable ~= false then
return null
end
if field.type == "array" or field.type == "set"
or field.type == "map" or field.type == "record" then
return {}
elseif field.type == "number" or field.type == "integer" then
return 0
elseif field.type == "boolean" then
return false
elseif field.type == "string" then
return ""
end
-- For cases that will produce a validation error, just return nil
return nil
end
--- Merge the contents of a table into another. Numeric keys
-- are appended sequentially, string keys take over their slots.
-- For example:
-- `merge_into_table({ [1] = 2, a = 3 }, { [1] = 4, a = 5, b = 6 }`
-- produces `{ [1] = 2, [2] = 4, a = 5, b = 6 }`
-- @param dst The destination table
-- @param src The source table
local function merge_into_table(dst, src)
for k,v in pairs(src) do
if type(k) == "number" then
insert(dst, v)
else
dst[k] = v
end
end
end
--- Given missing field named `k`, with definition `field`,
-- fill its slot in `entity` with an appropriate default value,
-- if possible.
-- @param k The field name.
-- @param field The field definition table.
-- @param entity The entity object where key `k` is missing.
local function handle_missing_field(k, field, entity)
if field.default ~= nil then
entity[k] = field.default
return
end
-- If `required`, it will fail later.
-- If `nilable` (metaschema only), a default value is not necessary.
if field.required or field.nilable then
return
end
entity[k] = default_value(field)
end
--- Validate fields of a table, individually, against the schema.
-- @param self The schema
-- @param input The input table.
-- @return Two arguments: the first is true on success and nil on failure.
-- The second is a table containing all errors, indexed numerically for
-- general errors, and by field name for field errors.
-- In all cases, the input table is untouched.
validate_fields = function(self, input)
assert(type(input) == "table", validation_errors.BAD_INPUT)
local errors = {}
for k, v in pairs(input) do
local field = self.fields[k]
if field then
field = (field.type == "self") and input or field
local _
_, errors[k] = self:validate_field(field, v)
else
errors[k] = validation_errors.UNKNOWN
end
end
if next(errors) then
return nil, errors
end
return true, errors
end
--- Runs an entity check, making sure it has access to all fields it asked for,
-- and that it only has access to the fields it asked for.
-- It will call `self.entity_checkers[name]` giving it a subset of `input`,
-- based on the list of fields given at `schema.entity_checks[name].fields`.
-- @param self The schema table
-- @param name The name of the entity check
-- @param input The whole input entity.
-- @param arg The argument table of the entity check declaration
-- @return True on success, or nil followed by an error message and a table
-- of field-specific errors.
local function run_entity_check(self, name, input, arg)
local ok = true
local check_input = {}
local field_errors = {}
local checker = self.entity_checkers[name]
local fields_to_check = {}
if checker.field_sources then
for _, source in ipairs(checker.field_sources) do
local v = arg[source]
if type(v) == "string" then
insert(fields_to_check, v)
elseif type(v) == "table" then
for _, fname in ipairs(v) do
insert(fields_to_check, fname)
end
end
end
else
fields_to_check = arg
end
local all_nil = true
for _, fname in ipairs(fields_to_check) do
if input[fname] == nil then
if not checker.run_with_missing_fields then
local err = validation_errors.REQUIRED_FOR_ENTITY_CHECK
field_errors[fname] = err
ok = false
end
else
all_nil = false
end
check_input[fname] = input[fname]
end
-- Don't run check if none of the fields are present (update)
if all_nil then
return true
end
if not ok then
return nil, nil, field_errors
end
local err
ok, err, field_errors = checker.fn(check_input, arg, self)
if ok then
return true
end
err = validation_errors[name:upper()]:format(err)
if not err then
local data = pretty.write({ name = arg }):gsub("%s+", " ")
err = validation_errors.ENTITY_CHECK:format(name, data)
end
return nil, err, field_errors
end
--- Runs the schema's custom `self.check()` function.
-- It requires the full entity to be present.
-- TODO hopefully deprecate this function.
-- @param self The schema table
-- @param name The name of the entity check
-- @param entity_errors The current array of entity errors.
-- @param field_errors The current table of accumulated field errors.
-- the array with check errors if any
local function run_self_check(self, input, entity_errors, field_errors)
local ok = true
for fname, field in self:each_field() do
if input[fname] == nil and not field.nilable then
local err = validation_errors.REQUIRED_FOR_ENTITY_CHECK:format(fname)
field_errors[fname] = err
ok = false
end
end
if not ok then
return nil
end
local err
ok, err = self.check(input)
if ok then
return
end
if type(err) == "string" then
insert(entity_errors, err)
elseif type(err) == "table" then
for k, v in pairs(err) do
if type(k) == "number" then
insert(entity_errors, v)
else
field_errors[k] = v
end
end
else
insert(entity_errors, validation_errors.CHECK)
end
end
--- Run entity checks over the whole table.
-- This includes the custom `check` function.
-- In case of any errors, add them to the errors table.
-- @param self The schema
-- @param input The input table.
-- @return True on success; nil, the table of entity check errors
-- (where keys are the entity check names with string values or
-- "check" and an array of self-check error strings)
-- and the table of field errors otherwise.
local function run_entity_checks(self, input)
local entity_errors = {}
local field_errors = {}
if self.entity_checks then
for _, check in ipairs(self.entity_checks) do
local check_name = next(check)
local _, err, f_errs = run_entity_check(self, check_name, input, check[check_name])
insert(entity_errors, err)
if f_errs then
merge_into_table(field_errors, f_errs)
end
end
end
if self.check then
run_self_check(self, input, entity_errors, field_errors)
end
if next(entity_errors) or next(field_errors) then
return nil, entity_errors, field_errors
end
return true
end
--- Ensure that a given table contains only the primary-key
-- fields of the entity and that their fields validate.
-- @param pk A table with primary-key fields only.
-- @param ignore_others If true, the function will ignore non-primary key
-- entries.
-- @return True on success; nil, error message and error table otherwise.
function Schema:validate_primary_key(pk, ignore_others)
local pk_set = {}
local errors = {}
for _, k in ipairs(self.primary_key) do
pk_set[k] = true
local field = self.fields[k]
local v = pk[k]
if not v then
errors[k] = validation_errors.MISSING_PK
elseif (field.required or field.auto) and v == null then
errors[k] = validation_errors.REQUIRED
else
local _
_, errors[k] = self:validate_field(field, v)
end
end
if not ignore_others then
for k, _ in pairs(pk) do
if not pk_set[k] then
errors[k] = validation_errors.NOT_PK
end
end
end
if next(errors) then
return nil, errors
end
return true
end
local Set_mt = {
__index = function(set, key)
for i, val in ipairs(set) do
if key == val then
return i
end
end
end
}
--- Sets (or replaces) metatable of an array:
-- 1. array is a proper sequence, but empty, `cjson.empty_array_mt`
-- will be used as a metatable of the returned array.
-- 2. otherwise no modifications are made to input parameter.
-- @param array The table containing an array for which to apply the metatable.
-- @return input table (with metatable, see above)
local function make_array(array)
if is_sequence(array) and #array == 0 then
return setmetatable(array, cjson.empty_array_mt)
end
return array
end
--- Sets (or replaces) metatable of a set and removes duplicates:
-- 1. set is a proper sequence, but empty, `cjson.empty_array_mt`
-- will be used as a metatable of the returned set.
-- 2. set a proper sequence, and has values, `Set_mt`
-- will be used as a metatable of the returned set.
-- 3. otherwise no modifications are made to input parameter.
-- @param set The table containing a set for which to apply the metatable.
-- @return input table (with metatable, see above)
local function make_set(set)
if not is_sequence(set) then
return set
end
local count = #set
if count == 0 then
return setmetatable(set, cjson.empty_array_mt)
end
local o = {}
local s = {}
local j = 0
for i = 1, count do
local v = set[i]
if not s[v] then
j = j + 1
o[j] = v
s[v] = true
end
end
return setmetatable(o, Set_mt)
end
--- Given a table, update its fields whose schema
-- definition declares them as `auto = true`,
-- based on its CRUD operation context.
-- This function encapsulates various "smart behaviors"
-- for value creation and update.
-- @param input The table containing data to be processed.
-- @param context a string describing the CRUD context:
-- valid values are: "insert", "update"
-- @return A new table, with the auto fields containing
-- appropriate updated values.
function Schema:process_auto_fields(input, context)
local output = tablex.deepcopy(input)
local now = time()
for key, field in self:each_field() do
if field.auto then
if field.uuid and context == "insert" then
output[key] = utils.uuid()
elseif field.uuid and context == "upsert" and output[key] == nil then
output[key] = utils.uuid()
elseif (key == "created_at" and (context == "insert" or
context == "upsert")) or
(key == "updated_at" and (context == "insert" or
context == "upsert" or
context == "update")) then
output[key] = now
end
end
local field_value = output[key]
if field_value ~= nil then
local field_type = field.type
if field_type == "array" then
output[key] = make_array(field_value)
elseif field_type == "set" then
output[key] = make_set(field_value)
end
elseif context ~= "update" then
handle_missing_field(key, field, output)
end
end
return output
end
--- Validate a table against the schema, ensuring that the entity is complete.
-- It validates fields for their attributes,
-- and runs the global entity checks against the entire table.
-- @param input The input table.
-- @param full_check If true, demands entity table to be complete.
-- If false, accepts missing `required` fields when those are not
-- needed for global checks.
-- @return True on success.
-- On failure, it returns nil and a table containing all errors,
-- indexed by field name for field errors, plus an "@entity" key
-- containing entity-checker and self-check errors.
-- This is an example of what an error table looks like:
-- {
-- ["name"] = "...error message...",
-- ["service"] = {
-- ["id"] = "...error message...",
-- }
-- ["@entity"] = {
-- "error message from at_least_one_of",
-- "error message from other entity validators",
-- "first error message from self-check function",
-- "second error message from self-check function",
-- }
-- }
-- In all cases, the input table is untouched.
function Schema:validate(input, full_check)
if full_check == nil then
full_check = true
end
local _, field_errors = validate_fields(self, input)
for name, field in self:each_field() do
if field.required
and (input[name] == null
or (full_check and input[name] == nil)) then
field_errors[name] = validation_errors.REQUIRED
end
end
local ok, entity_errors, f_errs
ok, entity_errors, f_errs = run_entity_checks(self, input)
if not ok then
if next(entity_errors) then
field_errors["@entity"] = entity_errors
end
merge_into_table(field_errors, f_errs)
end
if next(field_errors) then
return nil, field_errors
end
return true
end
--- Validate a table against the schema, ensuring that the entity is complete.
-- It validates fields for their attributes,
-- and runs the global entity checks against the entire table.
-- @param input The input table.
-- @return True on success.
-- On failure, it returns nil and a table containing all errors,
-- indexed numerically for general errors, and by field name for field errors.
-- In all cases, the input table is untouched.
function Schema:validate_insert(input)
return self:validate(input, true)
end
-- Validate a table against the schema, accepting a partial entity.
-- It validates fields for their attributes, but accepts missing `required`
-- fields when those are not needed for global checks,
-- and runs the global checks against the entire table.
-- @param input The input table.
-- @return True on success.
-- On failure, it returns nil and a table containing all errors,
-- indexed numerically for general errors, and by field name for field errors.
-- In all cases, the input table is untouched.
function Schema:validate_update(input)
-- Monkey-patch some error messages to make it clearer why they
-- apply during an update. This avoids propagating update-awareness
-- all the way down to the entity checkers (which would otherwise
-- defeat the whole purpose of the mechanism).
local rfec = validation_errors.REQUIRED_FOR_ENTITY_CHECK
local aloo = validation_errors.AT_LEAST_ONE_OF
validation_errors.REQUIRED_FOR_ENTITY_CHECK = rfec .. " when updating"
validation_errors.AT_LEAST_ONE_OF = "when updating, " .. aloo
local ok, err, err_t = self:validate(input, false)
-- Restore the original error messages
validation_errors.REQUIRED_FOR_ENTITY_CHECK = rfec
validation_errors.AT_LEAST_ONE_OF = aloo
return ok, err, err_t
end
--- Validate a table against the schema, ensuring that the entity is complete.
-- It validates fields for their attributes,
-- and runs the global entity checks against the entire table.
-- @param input The input table.
-- @return True on success.
-- On failure, it returns nil and a table containing all errors,
-- indexed numerically for general errors, and by field name for field errors.
-- In all cases, the input table is untouched.
function Schema:validate_upsert(input)
return self:validate(input, true)
end
--- An iterator for schema fields.
-- Returns a function to be used in `for` loops,
-- which produces the key and the field table,
-- as in `for field_name, field_data in self:each_field() do`
-- @return the iteration function
function Schema:each_field()
local i = 1
return function()
local item = self.fields[i]
if not self.fields[i] then
return nil
end
local key = next(item)
local field = item[key]
i = i + 1
return key, field
end
end
--- Produce a string error message based on the table of errors
-- produced by the `validate` function.
-- @param errors The table of errors.
-- @return A string representing the errors, or nil if there
-- were no errors or a table was not given.
function Schema:errors_to_string(errors)
if not errors or type(errors) ~= "table" or not next(errors) then
return nil
end
local msgs = {}
-- General errors first
if errors["@entity"] then
for _, err in pairs(errors["@entity"]) do
insert(msgs, err)
end
end
for _, err in ipairs(errors) do
insert(msgs, err)
end
-- Field-specific errors
for k, err in pairs(errors) do
if k ~= "@entity" then
if type(err) == "table" then
err = self:errors_to_string(err)
end
if type(k) == "string" then
insert(msgs, k..": "..err)
end
end
end
local summary = concat(msgs, "; ")
return validation_errors.ERROR:format(summary)
end
--- Given a field of type `"foreign"`, returns the schema object for it.
-- @param field A field definition table
-- @return A schema object, or nil and an error message.
local function get_foreign_schema_for_field(field)
local ref = field.reference
if not ref then
return nil, validation_errors.SCHEMA_MISSING_ATTRIBUTE:format(ref)
end
-- TODO add support for non-core entities
local pok, def = pcall(require, "kong.db.schema.entities." .. ref)
if not (pok and def) then
return nil, validation_errors.SCHEMA_BAD_REFERENCE:format(ref)
end
-- FIXME we really shouldn't be creating schema objects each
-- time, but rather getting schema objects from the modules,
-- instead of bare schema definition tables.
return Schema.new(def)
end
--- Cycle-aware table copy.
-- To be replaced by tablex.deepcopy() when it supports cycles.
local function copy(t, c, cache)
if type(t) ~= "table" then
return t
end
cache = cache or {}
c = c or {}
for k, v in pairs(t) do
local kk, vv = k, v
if type(k) == "table" then
if cache[k] then
kk = cache[k]
else
kk = {}
cache[k] = kk
copy(k, kk, cache)
end
end
if type(v) == "table" then
if cache[v] then
vv = cache[v]
else
vv = {}
cache[v] = vv
copy(v, vv, cache)
end
end
c[kk] = vv
end
return c
end
--- Instatiate a new schema from a definition.
-- @param definition A table with attributes describing
-- fields and other information about a schema.
-- @return The object implementing the schema matching
-- the given definition.
function Schema.new(definition)
if not definition then
return nil, validation_errors.SCHEMA_NO_DEFINITION
end
if not definition.fields then
return nil, validation_errors.SCHEMA_NO_FIELDS
end
local self = copy(definition)
setmetatable(self, Schema)
-- Also give access to fields by name
for key, field in self:each_field() do
self.fields[key] = field
if field.type == "foreign" then
local err
field.schema, err = get_foreign_schema_for_field(field)
if not field.schema then
return nil, err
end
end
end
return self
end
function Schema.define(tbl)
return setmetatable(tbl, {
__call = function(t, arg)
arg = arg or {}
for k,v in pairs(t) do
if not arg[k] then
arg[k] = v
end
end
return arg
end
})
end
return Schema
|
local tileTemplates = require('src/tileTemplates')
local key = require('src/ents/key')
local TILE_NAMES = {}
TILE_NAMES['02550255'] = tileTemplates.WALL
TILE_NAMES['00255255'] = tileTemplates.DESTRUCTABLE
TILE_NAMES['2552550255'] = tileTemplates.WARP_LEFT
TILE_NAMES['0255255255'] = tileTemplates.WARP_RIGHT
TILE_NAMES['2550255255'] = tileTemplates.SWITCH
TILE_NAMES['255200255255'] = tileTemplates.SWITCHABLE
TILE_NAMES['25500255'] = tileTemplates.TURRET
TILE_NAMES['128128128255'] = tileTemplates.DECOR
TILE_NAMES['0128255255'] = tileTemplates.KEY_HINT
TILE_NAMES['0255128255'] = tileTemplates.RECEPTOR
TILE_NAMES['128255255255'] = tileTemplates.KEYABLE
TILE_NAMES['12800255'] = tileTemplates.ZAP
local pixelToTile = function (pixel, x, y)
local tile = nil
local template = TILE_NAMES[pixel]
if template then
tile = template:reify(x, y)
else
tile = tileTemplates.EMPTY:reify(x, y)
end
return tile
end
return function (levelPath)
local img = love.graphics.newImage(levelPath)
local data = img:getData()
local width = img:getWidth()
local height = img:getHeight()
local levelMap = {}
levelMap.map = {}
levelMap.ents = {}
for i = 0, (width-1) do
for j = 0, (height-1) do
local r, g, b, a = data:getPixel(i, j)
local pixel = table.concat{r, g, b, a}
local t = pixelToTile(pixel, i, j)
table.insert(levelMap.map, t)
if t.tile == 'keyHint' then
table.insert(levelMap.ents, key(t.x * 32, t.y * 32))
end
end
end
return levelMap
end
|
-- @Author:pandayu
-- @Version:1.0
-- @DateTime:2018-09-09
-- @Project:pandaCardServer CardGame
-- @Contact: QQ:815099602
local _M = function(role,data)
role.activitylist:refresh()
return 0
end
return _M
|
-- Resource Metadata
fx_version 'cerulean'
games { 'rdr3', 'gta5' }
author 'SC-Dev'
description 'Fblock Zone'
version '1.0.0'
client_scripts {
'fblock.lua',
}
|
--// options for objectivetracker //--
local _, ns = ...
local L = ns.L
local LUI = LolzenUI.L
local f = CreateFrame("Frame")
f:RegisterEvent("ADDON_LOADED")
f:SetScript("OnEvent", function(self, event, addon)
if addon == "LolzenUI_Options" and LolzenUIcfg.modules["objectivetracker"] == true then
local title = ns.createTitle("objectivetracker")
local about = ns.createDescription("objectivetracker", LUI["desc_objectivetracker"])
local aboutBG = ns.createBackground("objectivetracker", 600, 132)
aboutBG:SetPoint("TOPLEFT", about, "BOTTOMLEFT", -4, -14)
aboutBG:SetFrameLevel(1)
local cb1 = ns.createCheckBox("objectivetracker", "combatcollapse", "|cff5599ff"..L["objective_autocollapse"].."|r", LolzenUIcfg.objectivetracker["objectivetracker_combatcollapse"])
cb1:SetPoint("TOPLEFT", about, "BOTTOMLEFT", 0, -20)
cb1:SetScript("OnClick", function(self)
LolzenUIcfg.objectivetracker["objectivetracker_combatcollapse"] = cb1:GetChecked()
end)
local cb1_desc = ns.createFontstring("objectivetracker", L["objective_autocollapse_desc"])
cb1_desc:SetPoint("TOPLEFT", cb1, "BOTTOMLEFT", 4, 0)
local cb2 = ns.createCheckBox("objectivetracker", "logincollapse", "|cff5599ff"..L["objective_auto_collapse_login"].."|r", LolzenUIcfg.objectivetracker["objectivetracker_logincollapse"])
cb2:SetPoint("TOPLEFT", cb1_desc, "BOTTOMLEFT", -4, -8)
cb2:SetScript("OnClick", function(self)
LolzenUIcfg.objectivetracker["objectivetracker_logincollapse"] = cb2:GetChecked()
end)
local cb2_desc = ns.createFontstring("objectivetracker", L["objective_auto_collapse_login_desc"])
cb2_desc:SetPoint("TOPLEFT", cb2, "BOTTOMLEFT", 4, 0)
local cb3 = ns.createCheckBox("objectivetracker", "dungeoncollapse", "|cff5599ff"..L["objective_auto_collapse_dungeon"].."|r", LolzenUIcfg.objectivetracker["objectivetracker_dungeoncollapse"])
cb3:SetPoint("TOPLEFT", cb2_desc, "BOTTOMLEFT", -4, -8)
cb3:SetScript("OnClick", function(self)
LolzenUIcfg.objectivetracker["objectivetracker_dungeoncollapse"] = cb3:GetChecked()
end)
local cb3_desc = ns.createFontstring("objectivetracker", L["objective_auto_collapse_dungeon_desc"])
cb3_desc:SetPoint("TOPLEFT", cb3, "BOTTOMLEFT", 4, 0)
local header2BG = ns.createBackground("objectivetracker", 600, 70)
header2BG:SetPoint("TOPLEFT", cb3_desc, "BOTTOMLEFT", -8, -8)
header2BG:SetFrameLevel(1)
local pos_x_text = ns.createFontstring("objectivetracker", L["PosX"]..":")
pos_x_text:SetPoint("TOPLEFT", cb3_desc, "BOTTOMLEFT", 0, -20)
local pos_x = ns.createInputbox("objectivetracker", 30, 20, LolzenUIcfg.objectivetracker["objectivetracker_posx"])
pos_x:SetPoint("LEFT", pos_x_text, "RIGHT", 10, 0)
pos_x:SetScript("OnEscapePressed", function(self)
self:SetText(self.oldText)
self:ClearFocus()
end)
pos_x:SetScript("OnEnterPressed", function(self)
LolzenUIcfg.objectivetracker["objectivetracker_posx"] = tonumber(pos_x:GetText())
self.oldText = self:GetText()
LolzenUI.setOTPos()
end)
pos_x:SetScript("OnEditFocusGained", function(self)
self.oldText = self:GetText()
end)
pos_x:SetScript("OnEditFocusLost", function(self)
self:SetText(self.oldText)
self:ClearFocus()
end)
local pos_y_text = ns.createFontstring("objectivetracker", L["PosY"]..":")
pos_y_text:SetPoint("LEFT", pos_x, "RIGHT", 5, 0)
local pos_y = ns.createInputbox("objectivetracker", 30, 20, LolzenUIcfg.objectivetracker["objectivetracker_posy"])
pos_y:SetPoint("LEFT", pos_y_text, "RIGHT", 10, 0)
pos_y:SetScript("OnEscapePressed", function(self)
self:SetText(self.oldText)
self:ClearFocus()
end)
pos_y:SetScript("OnEnterPressed", function(self)
LolzenUIcfg.objectivetracker["objectivetracker_posy"] = tonumber(pos_y:GetText())
self.oldText = self:GetText()
LolzenUI.setOTPos()
end)
pos_y:SetScript("OnEditFocusGained", function(self)
self.oldText = self:GetText()
end)
pos_y:SetScript("OnEditFocusLost", function(self)
self:SetText(self.oldText)
self:ClearFocus()
end)
local anchor_text = ns.createFontstring("objectivetracker", L["anchor"]..":")
anchor_text:SetPoint("LEFT", pos_y, "RIGHT", 5, 0)
local anchor = ns.createPicker("objectivetracker", "anchor", "objectivetracker_anchor", 110, LolzenUIcfg.objectivetracker["objectivetracker_anchor"])
anchor:SetPoint("LEFT", anchor_text, "RIGHT", -10, -3)
anchor.OnClick = function()
LolzenUIcfg.objectivetracker["objectivetracker_anchor"] = ns.picker_anchor[UIDropDownMenu_GetSelectedID(anchor)]
LolzenUI.setOTPos()
end
local scale_text = ns.createFontstring("objectivetracker", L["scale"]..":")
scale_text:SetPoint("TOPLEFT", pos_x_text, "BOTTOMLEFT", 0, -20)
local scale = ns.createPicker("objectivetracker", "alpha", "objectivetrackerframe_scale", 45, LolzenUIcfg.objectivetracker["objectivetracker_scale"])
scale:SetPoint("LEFT", scale_text, "RIGHT", -10, -3)
scale.OnClick = function()
LolzenUIcfg.objectivetracker["objectivetracker_scale"] = tonumber(ns.picker_alpha[UIDropDownMenu_GetSelectedID(scale)])
LolzenUI.setOTScale()
end
ns["objectivetracker"].default = function(self)
LolzenUIcfg.objectivetracker = _G["LolzenUIdefaultcfg"].objectivetracker
ReloadUI()
end
end
end)
|
--[[
[] Author: Martynas Petuska
[] E-mail: martynas.petuska@outlook.com
[] Date: April 2018
--]]
local UpdateInfo = ADDON.UpdateInfo;
local PinType = ADDON.Constants.PinType;
local Sizes = ADDON.Sizes;
local UI = ADDON.UI;
--====================================================== CLASS =======================================================--
---@class MapPin
local MapPin = {};
ADDON.Classes.MapPin = MapPin;
local Objects = {};
local UnusedObjects = {};
local QuestPins = {};
local LocationPins = {};
local FastTravelPins = {};
local PoiPins = {};
--====================================================== LOCAL =======================================================--
---Finds a pin by it's type and index. If no pin is found nothing is returned in its place along with the reference table
---for pinType, otherwise the pin and the reference table are returned.
---@param pinType string
---@param pinIndex number
---@return table, table
local function FindByIndex(pinType, pinIndex)
local obj, referenceTable;
if (pinType == PinType.QUEST) then
referenceTable = QuestPins;
for _, pin in pairs(QuestPins) do
if (pin.typeIndex == pinIndex) then
obj = pin;
end
end
elseif (pinType == PinType.LOCATION) then
referenceTable = LocationPins;
for _, pin in pairs(LocationPins) do
if (pin.typeIndex == pinIndex) then
obj = pin;
end
end
elseif (pinType == PinType.POI) then
referenceTable = PoiPins;
for _, pin in pairs(PoiPins) do
if (pin.typeIndex == pinIndex) then
obj = pin;
end
end
elseif (pinType == PinType.FAST_TRAVEL) then
referenceTable = FastTravelPins;
for _, pin in pairs(FastTravelPins) do
if (pin.typeIndex == pinIndex) then
obj = pin;
end
end
end
return obj, referenceTable;
end
---Sets the pin's normalised coordinates in the map and updates the rotated position of its controls.
---If no arguments are passed, the controls' position is readjusted from the stored values.
---@param nX number
---@param nY number
local function SetPosition(self)
local nX, nY = self.zoObject:GetNormalizedPosition();
local mapRotation = 0;
if (ADDON.Settings.isMapRotationEnabled) then
mapRotation = UpdateInfo.Player.rotation;
end
local playerX, playerY = UpdateInfo.Player.nX, UpdateInfo.Player.nY;
-- Counter-clockwise rotation around player position.
local x = playerX + (nX - playerX) * math.cos(mapRotation) - (nY - playerY) * math.sin(mapRotation);
local y = playerY + (nX - playerX) * math.sin(mapRotation) + (nY - playerY) * math.cos(mapRotation);
for _, control in pairs(self.Controls) do
control:ClearAnchors();
control:SetAnchor(CENTER, control:GetParent(), CENTER, (x - playerX) * UpdateInfo.Map.width, (y - playerY) * UpdateInfo.Map.height);
end
end
--=============================================== EVENTS & CALLBACKS =================================================--
local function OnQuestDataRefresh(iconRefresh)
UpdateInfo.updatePending = true;
if (not iconRefresh) then
MapPin.RefreshAll(PinType.QUEST);
else
for _, pin in pairs(QuestPins) do
pin:RefreshIcon(true);
end
end
end
FOCUSED_QUEST_TRACKER:RegisterCallback("QuestTrackerTrackingStateChanged", function()
OnQuestDataRefresh(true)
end);
CALLBACK_MANAGER:RegisterCallback("OnWorldMapQuestsDataRefresh", function()
OnQuestDataRefresh(false)
end);
--====================================================================================================================--
---Constructor.
---@param zoPinObject table
---@return MapPin
function MapPin:New(zoPinObject)
local pinType, obj, typeIndex, referenceTable;
if (zoPinObject:IsLocation()) then
pinType = PinType.LOCATION;
typeIndex = zoPinObject:GetLocationIndex();
obj, referenceTable = FindByIndex(pinType, typeIndex);
elseif (zoPinObject:IsQuest()) then
pinType = PinType.QUEST;
typeIndex = zoPinObject:GetQuestIndex();
obj, referenceTable = FindByIndex(pinType, typeIndex);
elseif (zoPinObject:IsPOI()) then
pinType = PinType.POI;
typeIndex = zoPinObject:GetPOIIndex();
obj, referenceTable = FindByIndex(pinType, typeIndex);
elseif (zoPinObject:IsFastTravelKeep() or zoPinObject:IsFastTravelWayShrine()) then
pinType = PinType.FAST_TRAVEL;
typeIndex = zoPinObject:GetFastTravelNodeIndex();
obj, referenceTable = FindByIndex(pinType, typeIndex);
else
return ;
end
if (obj) then
obj:Init(zoPinObject);
return obj;
elseif (referenceTable) then
obj = table.remove(UnusedObjects);
if (not obj) then
obj = setmetatable({}, { __index = self });
table.insert(Objects, obj);
obj.objectId = #Objects;
end
table.insert(referenceTable, obj);
obj:Init(zoPinObject, pinType, typeIndex);
return obj;
end
end
---Initialises the new object.
---@param zoPinObject table
---@param pinType string
---@param typeIndex number
function MapPin:Init(zoPinObject, pinType, typeIndex)
if (not zoPinObject) then
return
end
self.inUse = true;
self.enabled = true;
self.zoObject = zoPinObject;
self.pinType = pinType or self.pinType;
self.typeIndex = typeIndex or self.typeIndex;
self.Controls = self.Controls or {};
self.icon = self:GetIcon();
local size = Sizes.mapPinSize * ADDON.Settings.MiniMap.mapScale;
for group, scroll in pairs(UI.Scrolls) do
if (not self.Controls[group]) then
local controlName = scroll:GetName() .. "_MapPin" .. tostring(self.objectId);
self.Controls[group] = WINDOW_MANAGER:CreateControl(controlName, scroll, CT_TEXTURE);
end
self.Controls[group]:SetTexture(self.icon);
self.Controls[group]:SetDimensions(size, size);
self.Controls[group]:SetHidden(not self.enabled);
if (self.pinType == PinType.QUEST) then
if (self.zoObject:IsAssisted()) then
self.Controls[group]:SetDrawLevel(4);
end
self.Controls[group]:SetDrawLevel(3);
elseif (self.pinType == PinType.FAST_TRAVEL) then
self.Controls[group]:SetDrawLevel(2);
else
self.Controls[group]:SetDrawLevel(1);
end
end
SetPosition(self);
self:RefreshIcon();
end
---Gets the icon texture path string for the pin
---@return string
function MapPin:GetIcon()
if (self.zoObject:IsLocation()) then
return self.zoObject:GetLocationIcon();
elseif (self.zoObject:IsPOI()) then
return self.zoObject:GetPOIIcon();
elseif (self.zoObject:IsFastTravelWayShrine() or self.zoObject:IsFastTravelKeep()) then
return self.zoObject:GetFastTravelIcons();
elseif (self.zoObject:IsQuest()) then
return self.zoObject:GetQuestIcon();
end
end
---Gets the pin's normalised coordinates in the map.
---@return number, number
function MapPin:GetPosition()
return self.zoObject:GetNormalizedPosition();
end
---Enables/disables the pin.
---@param isEnabled boolean
function MapPin:SetEnabled(isEnabled)
self.enabled = isEnabled;
for _, control in pairs(self.Controls) do
control:SetHidden(not self.enabled);
end
end
---Returns whether the pin is enabled.
---@return boolean
function MapPin:IsEnabled()
return self.inUse and self.enabled;
end
---Updates the pin.
function MapPin:Update()
if (self:IsEnabled()) then
self:RefreshIcon();
SetPosition(self);
end
end
---Refreshes pin's icon.
---@param force boolean
function MapPin:RefreshIcon(force)
if (not self:IsEnabled()) then
return
end
if (force or self.icon ~= self:GetIcon()) then
self.icon = self:GetIcon();
if (not self.icon or string.find(self.icon, "icon_missing")) then
return self:Remove();
end
for group, scroll in pairs(UI.Scrolls) do
self.Controls[group]:SetTexture(self.icon);
end
end
end
---Removes the pin from usage by disabling its controls and preparing for re-use queue.
function MapPin:Remove()
self:SetEnabled(false);
self.inUse = false;
local _, referenceTable = FindByIndex(self.pinType, self.typeIndex);
table.remove(referenceTable, self.typeIndex);
table.insert(UnusedObjects, self);
end
--====================================================== STATIC ======================================================--
---Removes a pin from usage.
---@param pinType string
---@param pinIndex number
function MapPin.RemovePin(pinType, pinIndex)
local pin = FindByIndex(pinType, pinIndex);
if (pin) then
pin:Remove();
end
end
---Updates all registered pins.
function MapPin.UpdateAll()
for _, pin in pairs(Objects) do
pin:Update();
end
end
---Enables/disables all registered pins.
---@param areEnabled boolean
function MapPin.SetEnabledAll(areEnabled)
for _, pin in pairs(Objects) do
pin:SetEnabled(areEnabled);
end
end
---Refreshes all pins of the given PinType(s). If no PinType is given, refreshes all pins.
---@param ... string
function MapPin.RefreshAll(...)
local pinTypes = { ... };
d("length " .. #pinTypes)
local referenceTables = {};
if (#pinTypes > 0) then
for _, type in pairs(pinTypes) do
local _, referenceTable = FindByIndex(type);
table.insert(referenceTables, referenceTable);
for _, pin in pairs(referenceTable) do
pin.inUse = false;
end
end
else
for _, pin in pairs(Objects) do
if (not pin.inUse) then
pin.inUse = false;
end
end
end
for i, pin in pairs(ZO_WorldMap_GetPinManager():GetActiveObjects()) do
if (#pinTypes > 0) then
if (table.contains(pinTypes, PinType.POI) and pin:IsPOI()) then
MapPin:New(pin);
elseif (table.contains(pinTypes, PinType.LOCATION) and pin:IsLocation()) then
MapPin:New(pin);
elseif (table.contains(pinTypes, PinType.FAST_TRAVEL) and (pin:IsFastTravelKeep() or pin:IsFastTravelWayShrine())) then
MapPin:New(pin);
elseif (table.contains(pinTypes, PinType.QUEST) and pin:IsQuest()) then
MapPin:New(pin);
end
else
MapPin:New(pin);
end
end
if (#pinTypes > 0) then
for _, referenceTable in pairs(referenceTables) do
for _, pin in pairs(referenceTable) do
if (not pin.inUse) then
pin:Remove();
end
end
end
else
for _, pin in pairs(Objects) do
if (not pin.inUse) then
pin:Remove();
end
end
end
end
function MapPin.RemoveAll()
d("objects: " .. #Objects)
for _, pin in pairs(Objects) do
pin:Remove();
end
end
--====================================================================================================================--
|
function SpawnProp(pl, command, args)
if GAMEMODE:GetRound() == 1 then
if util.IsValidProp(args[1]) and !string.find(string.lower(args[1]),"cargo") then
if pl:GetRemainingProps() == 0 then
pl:ChatPrint("You do not have any props left.")
return false
end
local vStart = pl:GetShootPos()
local vForward = pl:GetAimVector()
local trace = {}
trace.start = vStart
trace.endpos = vStart + (vForward * 2048)
trace.filter = pl
local tr = util.TraceLine( trace )
local prop = ents.Create("prop_fortwars")
if ( !prop:IsValid() ) then return end
ang = pl:EyeAngles()
ang.yaw = ang.yaw + 180
ang.roll = 0
ang.pitch = 0
prop:SetPos( tr.HitPos )
prop:SetAngles( ang )
prop:SetModel(args[1])
prop:Spawn()
prop:Activate()
prop:GetPhysicsObject():Wake()
local ed = EffectData()
ed:SetOrigin( prop:GetPos() )
ed:SetEntity( prop )
util.Effect( "propspawn", ed, true, true )
local minx,maxx = prop:WorldSpaceAABB()
local xsize = minx:Distance(maxx)
if xsize>512 then
pl:ChatPrint("That prop is too big.")
prop:Remove()
return
end
local vFlushPoint = tr.HitPos - ( tr.HitNormal * 512 )
vFlushPoint = prop:NearestPoint( vFlushPoint )
vFlushPoint = prop:GetPos() - vFlushPoint
vFlushPoint = tr.HitPos + vFlushPoint
prop:SetPos(vFlushPoint)
local valid=GAMEMODE:IsValidSpawnPos(pl,prop:GetPos())
if valid == false then
pl:ChatPrint("Too far away from a core.")
prop:Remove()
return
end
prop:SetTeam(pl:Team())
prop:SetPropOwner(pl)
pl:SetRemainingProps( pl:GetRemainingProps() - 1 )
else
pl:ChatPrint("That is not a valid prop.")
end
else
pl:ChatPrint("You may only make props in the build round.")
end
end
concommand.Add("gm_spawn",SpawnProp)
concommand.Add("fw_makecores", function()
local core = ents.Create("fw_core")
core:SetPos(Vector(369.766907,-793.759521,-12287.968750))
core:SetBuildRadius(512)
core:SetCoreHealth(1000)
core:SetTeam(1)
core:Spawn()
core = ents.Create("fw_core")
core:SetPos(Vector(36.548717,815.501221,-12287.968750))
core:SetBuildRadius(1024)
core:SetCoreHealth(1000)
core:SetTeam(2)
core:Spawn()
GAMEMODE:SetupFW()
BroadcastLua("GAMEMODE:SetupFW()")
end)
|
ltnh_events = {
map_gui_opened = {},
map_gui_closed = {},
map_checked = {},
map_text_changed = {},
map_elem_changed = {},
map_clicked = {},
map_slider = {},
}
ltnh_events.on_gui_opened = function(event)
if not event.entity or not ltnh_events.map_gui_opened[event.entity.name] then return end
ltnh_events.map_gui_opened[event.entity.name](event)
end
ltnh_events.on_gui_closed = function(event)
if not event.element or not ltnh_events.map_gui_closed[event.element.name] then return end
ltnh_events.map_gui_closed[event.element.name](event)
end
ltnh_events.on_gui_clicked = function(event)
if not event.element or not ltnh_events.map_clicked[event.element.name] then return end
ltnh_events.map_clicked[event.element.name](event)
end
ltnh_events.on_gui_text_changed = function(event)
if not event.element or not ltnh_events.map_text_changed[event.element.name] then return end
ltnh_events.map_text_changed[event.element.name](event)
end
ltnh_events.on_gui_checked_state = function(event)
if not event.element or not ltnh_events.map_checked[event.element.name] then return end
ltnh_events.map_checked[event.element.name](event)
end
ltnh_events.on_gui_elem_changed = function(event)
if not event.element or not ltnh_events.map_elem_changed[event.element.name] then return end
ltnh_events.map_elem_changed[event.element.name](event)
end
ltnh_events.on_gui_slider_changed = function(event)
if not event.element or not ltnh_events.map_slider[event.element.name] then return end
ltnh_events.map_slider[event.element.name](event)
end
script.on_event({defines.events.on_gui_opened}, ltnh_events.on_gui_opened)
script.on_event({defines.events.on_gui_closed}, ltnh_events.on_gui_closed)
script.on_event({defines.events.on_gui_click}, ltnh_events.on_gui_clicked)
script.on_event({defines.events.on_gui_text_changed}, ltnh_events.on_gui_text_changed)
script.on_event({defines.events.on_gui_checked_state_changed}, ltnh_events.on_gui_checked_state)
script.on_event({defines.events.on_gui_elem_changed}, ltnh_events.on_gui_elem_changed)
script.on_event({defines.events.on_gui_value_changed}, ltnh_events.on_gui_slider_changed)
--script.on_event("ltnh-tab-key-event", ltnh.gui.on_tab_key)
return ltnh_events
|
local numKeyArgs = 1
-- Arguments:
-- Keys: <WriteLockKey>
-- Params: <LockToken>
-- Returns:
-- { 0 } - Lock was previously released or expired
-- { 1 } - Lock released
if redis.call("get", KEYS[1]) == ARGV[1] then
redis.call("del", KEYS[1])
return { 1 }
else
return { 0 }
end
|
-- API
local Constants_API = require(script:GetCustomProperty("MetaAbilityProgressionConstants_API"))
local UTIL_API = require(script:GetCustomProperty("MetaAbilityProgressionUTIL_API"))
local viewRange = script:GetCustomProperty("ViewRange")
local gameStateManager = script:GetCustomProperty("GameStateManager"):WaitForObject()
local spottingXP = script:GetCustomProperty("SpottingXP")
local spottingList = {}
local viewPointList = {}
local viewRangeList = {}
local damageOverride ={}
local spottingTask = nil
-- other modified scripts to support spotting: NameplateControllerClient, Minimap
--[[
local spottingServer = script:GetCustomProperty("GAMEHELPER_SpottingServer"):WaitForObject()
function CheckSpotting(player)
for i=1, 16 do
if spottingServer:GetCustomProperty("P" .. tostring(i)) == player.id then
return true
end
end
return false
end
]]
function AddToList(player)
if spottingList[player.id] or damageOverride[player.id] then
return
end
spottingList[player.id] = true
for i=1, 16 do
if script:GetCustomProperty("P" .. tostring(i)) == "" then
-- Add XP
player:AddResource(Constants_API.XP, spottingXP)
-- Add RP to tank
player:AddResource(UTIL_API.GetTankRPString(player:GetResource(Constants_API.GetEquippedTankResource())), spottingXP)
Events.BroadcastToPlayer(player, "GainXP", {reason = Constants_API.XP_GAIN_REASON.SPOTTED_ENEMY, amount = spottingXP})
script:SetNetworkedCustomProperty("P" .. tostring(i), player.id)
return
end
end
end
function AddToListFromDamaged(player)
if spottingList[player.id] then
return
end
spottingList[player.id] = true
for i=1, 16 do
if script:GetCustomProperty("P" .. tostring(i)) == "" then
script:SetNetworkedCustomProperty("P" .. tostring(i), player.id)
return
end
end
end
function RemoveFromList(player)
if not spottingList[player.id] or damageOverride[player.id] then
return
end
spottingList[player.id] = nil
for i=1, 16 do
if script:GetCustomProperty("P" .. tostring(i)) == player.id then
script:SetNetworkedCustomProperty("P" .. tostring(i), "")
end
end
end
function SetViewPoint(player)
if Object.IsValid(viewPointList[player.id]) then
return
end
if not player.serverUserData.currentTankData or not Object.IsValid(player.serverUserData.currentTankData.hitbox) then
return
end
viewPointList[player.id] = player.serverUserData.currentTankData.hitbox:FindDescendantByName("ViewPoint")
viewRangeList[player.id] = tonumber(player.serverUserData.currentTankData.viewRange) or viewRange
--print(player.name .. " viewpoint set")
end
function CheckForSpotting()
local playerList = Game.GetPlayers()
if gameStateManager:GetCustomProperty("GameState") ~= "MATCH_STATE" then
return
end
for x, p in pairs(playerList) do
SetViewPoint(p)
local otherPlayerList = Game.GetPlayers({ignoreDead = true, ignorePlayers = p, ignoreTeams = p.team})
for x2, p2 in pairs(otherPlayerList) do
SetViewPoint(p2)
if Object.IsValid(viewPointList[p.id]) and Object.IsValid(viewPointList[p2.id]) then
if (viewPointList[p.id]:GetWorldPosition() - viewPointList[p2.id]:GetWorldPosition()).size <= viewRangeList[p2.id] then
local raycastResult = World.Raycast(viewPointList[p2.id]:GetWorldPosition(), viewPointList[p.id]:GetWorldPosition(), {ignoreTeams = p.team})
if raycastResult then
if raycastResult.other:FindAncestorByType("Vehicle") then
--print("Tank check pass")
local tank = raycastResult.other:FindAncestorByType("Vehicle")
if tank.driver == p then
AddToList(p)
else
RemoveFromList(p)
end
break
end
else
AddToList(p)
break
end
end
end
RemoveFromList(p)
end
end
end
function OnDamaged(player, damage)
damageOverride[player.id] = true
AddToListFromDamaged(player)
Task.Wait(5)
damageOverride[player.id] = nil
end
function OnJoin(player)
player.damagedEvent:Connect(OnDamaged)
end
function OnGameStateChanged(gsm, property)
if property ~= "GameState" then
return
end
local newState = gameStateManager:GetCustomProperty(property)
if newState == "MATCH_STATE" then
if not spottingTask then
spottingTask = Task.Spawn(CheckForSpotting)
spottingTask.repeatCount = -1
spottingTask.repeatInterval = 1
end
elseif spottingTask then
spottingTask:Cancel()
spottingTask = nil
end
end
Game.playerJoinedEvent:Connect(OnJoin)
gameStateManager.networkedPropertyChangedEvent:Connect(OnGameStateChanged)
OnGameStateChanged(gameStateManager, "GameState")
|
local base = "@PKG@/settarg"
local settarg_cmd = pathJoin(base, "@settarg_cmd@")
prepend_path("PATH",base)
setenv("LMOD_SETTARG_CMD", settarg_cmd)
set_shell_function("settarg", 'eval $($LMOD_SETTARG_CMD -s sh "$@")',
'eval `$LMOD_SETTARG_CMD -s csh $*`' )
set_shell_function("gettargdir", 'builtin echo $TARG', 'echo $TARG')
local respect = "true"
setenv("SETTARG_TAG1", "OBJ", respect )
setenv("SETTARG_TAG2", "_" , respect )
local full_support = (os.getenv("LMOD_FULL_SETTARG_SUPPORT") or
os.getenv("LMOD_SETTARG_FULL_SUPPORT") or "no"):lower()
if (full_support ~= "no") then
set_alias("cdt", "cd $TARG")
set_shell_function("targ", 'builtin echo $TARG', 'echo $TARG')
set_shell_function("dbg", 'settarg "$@" dbg', 'settarg $* dbg')
set_shell_function("empty", 'settarg "$@" empty', 'settarg $* empty')
set_shell_function("opt", 'settarg "$@" opt', 'settarg $* opt')
set_shell_function("mdbg", 'settarg "$@" mdbg', 'settarg $* mdbg')
end
local myShell = myShellName()
local exitCmd = "eval `" .. "@path_to_lua@ " .. settarg_cmd .. " -s " .. myShell .. " --destroy`"
execute{cmd=exitCmd, modeA = {"unload"}}
local titlebar_support = (os.getenv("LMOD_SETTARG_TITLE_BAR") or "no"):lower()
local term = os.getenv("TERM") or " "
if (titlebar_support == "yes") then
if (myShellName() == "bash" or myShellName() == "zsh") then
local precmd = [==[{
local tilde="~";
local H=${HOSTNAME-$(hostname)};
H=${H%%.*};
local SHOST=${SHOST-$H};
eval $(${LMOD_SETTARG_CMD:-:} -s bash);
${SET_TITLE_BAR:-:} "${TARG_TITLE_BAR_PAREN}${USER}@${SHOST}:${PWD/#$HOME/$tilde}";
${USER_PROMPT_CMD:-:};
}
]==]
set_shell_function("precmd",precmd,"")
if (term:find("xterm")) then
setenv("SET_TITLE_BAR","xSetTitleLmod")
execute{cmd='echo -n -e "\\033]2; \\007"',modeA={"unload"}}
end
if (myShellName() == "bash") then
pushenv("PROMPT_COMMAND","precmd")
end
elseif (myShellType() == "csh") then
set_alias("cwdcmd",'eval `$LMOD_SETTARG_CMD -s csh`')
if (term:find("xterm")) then
set_alias("precmd",'echo -n "\\033]2;${TARG_TITLE_BAR_PAREN}${USER}@${HOST} : $cwd\\007"')
execute{cmd='echo -n "\\033]2; \\007"',modeA={"unload"}}
end
end
end
if (myShellType() == "csh") then
execute{cmd='setenv LMOD_SETTARG_CMD :',modeA={"unload"}}
end
local helpMsg = [[
The settarg module dynamically and automatically updates "$TARG" and a
host of other environment variables. These new environment variables
encapsulate the state of the modules loaded.
For example, if you have the settarg module and gcc/4.7.2 module loaded
then the following variables are defined in your environment:
TARG=OBJ/_x86_64_06_1a_gcc-4.7.3
TARG_COMPILER=gcc-4.7.3
TARG_COMPILER_FAMILY=gcc
TARG_MACH=x86_64_06_1a
TARG_SUMMARY=x86_64_06_1a_gcc-4.7.3
If you change your compiler to intel/13.1.0, these variables change to:
TARG=OBJ/_x86_64_06_1a_intel-13.1.0
TARG_COMPILER=intel-13.1.0
TARG_COMPILER_FAMILY=intel
TARG_MACH=x86_64_06_1a
TARG_SUMMARY=x86_64_06_1a_intel-13.1.0
If you then load mpich/3.0.4 module the following variables automatically
change to:
TARG=OBJ/_x86_64_06_1a_intel-13.1.0_mpich-3.0.4
TARG_COMPILER=intel-13.1.0
TARG_COMPILER_FAMILY=intel
TARG_MACH=x86_64_06_1a
TARG_MPI=mpich-3.0.4
TARG_MPI_FAMILY=mpich
TARG_SUMMARY=x86_64_06_1a_dbg_intel-13.1.0_mpich-3.0.4
You also get some TARG_* variables that are always available, independent
of what modules you have loaded:
TARG_MACH=x86_64_06_1a
TARG_MACH_DESCRIPT=...
TARG_HOST=...
TARG_OS=Linux-3.8.0-27-generic
TARG_OS_FAMILY=Linux
One way that these variables can be used is part of a build system where
the executables and object files are placed in $TARG. You can also use
$TARG_COMPILER_FAMILY to know which compiler you are using so that you
can set the appropriate compiler flags.
If the environment variable LMOD_SETTARG_FULL_SUPPORT is set to "yes"
then helpful aliases are defined to set the debug/optimize/max debug
build scenerio
If the environment variable LMOD_SETTARG_TITLE_BAR is set to "yes" then
the xterm title will be set with along with important modules like the
compiler and mpi stack.
Settarg can do more. Please see the Lmod website for more details.
]]
help(helpMsg)
|
local _2afile_2a = "fnl/aniseed/fennel.fnl"
local _0_0
do
local name_0_ = "aniseed.fennel"
local module_0_
do
local x_0_ = package.loaded[name_0_]
if ("table" == type(x_0_)) then
module_0_ = x_0_
else
module_0_ = {}
end
end
module_0_["aniseed/module"] = name_0_
module_0_["aniseed/locals"] = ((module_0_)["aniseed/locals"] or {})
module_0_["aniseed/local-fns"] = ((module_0_)["aniseed/local-fns"] or {})
package.loaded[name_0_] = module_0_
_0_0 = module_0_
end
local autoload = (require("aniseed.autoload")).autoload
local function _1_(...)
local ok_3f_0_, val_0_ = nil, nil
local function _1_()
return {autoload("aniseed.nvim")}
end
ok_3f_0_, val_0_ = pcall(_1_)
if ok_3f_0_ then
_0_0["aniseed/local-fns"] = {autoload = {nvim = "aniseed.nvim"}}
return val_0_
else
return print(val_0_)
end
end
local _local_0_ = _1_(...)
local nvim = _local_0_[1]
local _2amodule_2a = _0_0
local _2amodule_name_2a = "aniseed.fennel"
do local _ = ({nil, _0_0, nil, {{}, nil, nil, nil}})[2] end
local impl
do
local v_0_
do
local v_0_0
local function _2_()
return require("aniseed.deps.fennel")
end
v_0_0 = _2_
_0_0["impl"] = v_0_0
v_0_ = v_0_0
end
local t_0_ = (_0_0)["aniseed/locals"]
t_0_["impl"] = v_0_
impl = v_0_
end
local add_path
do
local v_0_
do
local v_0_0
local function add_path0(path)
local fnl = impl()
fnl["path"] = (fnl.path .. ";" .. path)
return nil
end
v_0_0 = add_path0
_0_0["add-path"] = v_0_0
v_0_ = v_0_0
end
local t_0_ = (_0_0)["aniseed/locals"]
t_0_["add-path"] = v_0_
add_path = v_0_
end
local sync_rtp
do
local v_0_
do
local v_0_0
local function sync_rtp0()
local fnl_suffix = "/fnl/?.fnl"
local rtp = nvim.o.runtimepath
local fnl_path = (rtp:gsub(",", (fnl_suffix .. ";")) .. fnl_suffix)
local lua_path = fnl_path:gsub("/fnl/", "/lua/")
impl()["path"] = (fnl_path .. ";" .. lua_path)
return nil
end
v_0_0 = sync_rtp0
_0_0["sync-rtp"] = v_0_0
v_0_ = v_0_0
end
local t_0_ = (_0_0)["aniseed/locals"]
t_0_["sync-rtp"] = v_0_
sync_rtp = v_0_
end
return sync_rtp()
|
-- Base64-decoding
-- Sourced from http://en.wikipedia.org/wiki/Base64
-- Author Daniel Lindsley
-- License BSD https://github.com/toastdriven/lua-base64
local index_table = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
local function to_binary(integer)
local remaining = tonumber(integer)
local bin_bits = ''
for i = 7, 0, -1 do
local current_power = math.pow(2, i)
if remaining >= current_power then
bin_bits = bin_bits .. '1'
remaining = remaining - current_power
else
bin_bits = bin_bits .. '0'
end
end
return bin_bits
end
local function from_binary(bin_bits)
return tonumber(bin_bits, 2)
end
local function from_base64(to_decode)
local padded = to_decode:gsub('%s', '')
local unpadded = padded:gsub('=', '')
local bit_pattern = ''
local decoded = ''
for i = 1, #unpadded do
local char = to_decode:sub(i, i)
local offset, _ = index_table:find(char)
if offset == nil then
error("Invalid character '" .. char .. "' found.")
end
bit_pattern = bit_pattern .. to_binary(offset-1):sub(3)
end
for i = 1, #bit_pattern, 8 do
local byte = bit_pattern:sub(i, i+7)
decoded = decoded .. string.char(from_binary(byte))
end
local padding_length = #padded-#unpadded
if (padding_length == 1 or padding_length == 2) then
decoded = decoded:sub(1,-2)
end
return decoded
end
return { decode = from_base64 }
|
Script:ReloadScript("scripts/materials/PhysicsSounds.lua")
-- simple entity
BasicEntity = {
Name = "BasicEntity",
Properties = {
object_Model = "",
aianchorAIAction = "",
fAnchorRadius = 0,
Physics = {
bRigidBody=0, -- True if rigid body.
bRigidBodyActive = 1, -- If rigid body is originally created (1) OR will be created only on OnActivate (0).
bActivateOnDamage = 0, -- Activate when a rocket hit the entity.
bResting = 0, -- If rigid body is originally in resting state.
Density = -1,
Mass = 700,
vector_Impulse = {x=1,y=2,z=3}, -- Impulse to apply at event.
max_time_step = 0.01,
sleep_speed = 0.04,
damping = 0,
water_damping = 0,
water_resistance = 1000,
water_density = 1000,
Type="Unknown",
bFixedDamping = 0,
bUseSimpleSolver = 0,
LowSpec = {
bKeepRigidBody = 1,
bRigidBody = 0,
max_time_step = 0.025,
sleep_speed = 0.04,
bKeepMassAndWater = 1,
Mass = 700,
Density = -1,
water_resistance = 1000,
water_density = 1000,
},
},
Animation = {
Animation = "Default",
Speed=1,
bLoop=0,
bPlaying=0,
--bSaveAnimStatus=0,
},
damage_players=0,
sndAnimStart="",
sndAnimStop="",
},
temp_vec={x=0,y=0,z=0},
animsoundstart=nil,
animsoundstop=nil,
animstarted=0,
}
------------------------------------------------------------------------------------------------------
function BasicEntity:IsARigidBody()
local qual=tonumber(getglobal("physics_quality"));
if qual>0 or self.Properties.Physics.LowSpec.bKeepRigidBody==1 then
return self.Properties.Physics.bRigidBody;
end
return self.Properties.Physics.LowSpec.bRigidBody;
end
------------------------------------------------------------------------------------------------------
function BasicEntity:SetFromProperties()
if (self.Properties.object_Model == "") then
do return end;
end
local bPhysicalize = 1;
if (self.ModelName ~= self.Properties.object_Model) then
self.ModelName = self.Properties.object_Model;
--bPhysicalize = 1;
-- try to load an animated model first
if (self:LoadCharacter(self.ModelName,0)) then
-- Needs to be updated when visible
self.bCharacter = 1;
self:DrawCharacter(0,1);
else
-- Dont need to be updated.
-- let's create either a rigid body or a normal static object
self:LoadObject( self.ModelName,0,1 );
self.bCharacter = 0;
self:DrawObject(0,1); --param nPos(slot number), nMode(0 = Don't draw, 1 = Draw normally, 3 = Draw near)
end
end
if (self.Properties.Animation.bPlaying ~= self.bAnimPlaying or self.Properties.Animation.bLoop ~= self.bAnimLoop or
self.Properties.Animation.Animation ~= self.AnimName) then
self.bAnimPlaying = self.Properties.Animation.bPlaying;
self.bAnimLoop = self.Properties.Animation.bLoop;
self.AnimName = self.Properties.Animation.Animation;
if (self.Properties.Animation.bPlaying == 1) then
self:StartAnimation( 0,self.Properties.Animation.Animation,0,0,1,self.Properties.Animation.bLoop );
else
self:ResetAnimation(0);
end
end
self:SetAnimationSpeed( self.Properties.Animation.Speed )
-- Set physics.
self:SetPhysicsProperties( bPhysicalize,self.Properties.Physics.bRigidBodyActive );
--self:EnablePhysics(1);
self:SetSoundProperties();
if (self.bCharacter == 1) then
if (self:IsARigidBody() == 1) then
-- Characters needs also to be updated when they are visible.
self:SetUpdateType( eUT_PhysicsVisible );
else
self:SetUpdateType( eUT_Visible );
end
else
if (self:IsARigidBody() == 1) then
-- Rigid bodies needs only to be updated when physics awake.
self:SetUpdateType( eUT_Physics );
else
-- Static objects should be updated depending on when update is enabled.
self:SetUpdateType( eUT_Always );
end
end
self:GotoState("Default");
end
------------------------------------------------------------------------------------------------------
function BasicEntity:SetSoundProperties()
-- load sounds
self.SplashSound=Sound:Load3DSound("sounds/player/water/watersplash.wav", 0, 255, 2, 50);
if (self.Properties.sndAnimStart~="") then
self.animsoundstart=Sound:Load3DSound(self.Properties.sndAnimStart, 0,255,1,10);
end
if (self.Properties.sndAnimStop~="") then
self.animsoundstop=Sound:Load3DSound(self.Properties.sndAnimStop, 0,255,1,10);
end
end
------------------------------------------------------------------------------------------------------
-- Set Physics parameters.
------------------------------------------------------------------------------------------------------
function BasicEntity:SetPhysicsProperties( bPhysicalize,bActivateRigidBody )
local Mass,Density,qual;
-- [marco] in multiplayer settings must be exactly the same
-- on all machines
if (Game:IsMultiplayer()) then
qual=2;
else
qual = tonumber(getglobal("physics_quality"));
end
if (qual>0 or self.Properties.Physics.LowSpec.bKeepMassAndWater==1) then
Mass = self.Properties.Physics.Mass;
Density = self.Properties.Physics.Density;
else
Mass = self.Properties.Physics.LowSpec.Mass;
Density = self.Properties.Physics.LowSpec.Density;
end
if (self:IsARigidBody() == 1) then
-- Make Rigid body.
if (bPhysicalize==1) then
self:CreateRigidBody( Density,Mass,-1 );
if (self.bCharacter == 1) then
self:PhysicalizeCharacter( Mass,0,0,0);
end
end
local SimParams = {
max_time_step = self.Properties.Physics.max_time_step,
sleep_speed = self.Properties.Physics.sleep_speed,
damping = self.Properties.Physics.damping,
water_damping = self.Properties.Physics.water_damping,
water_resistance = self.Properties.Physics.water_resistance,
water_density = self.Properties.Physics.water_density,
mass = Mass,
density = Density
};
if qual==0 then
SimParams.max_time_step = self.Properties.Physics.LowSpec.max_time_step;
SimParams.sleep_speed = self.Properties.Physics.LowSpec.sleep_speed;
if (self.Properties.Physics.LowSpec.bKeepMassAndWater==0) then
SimParams.water_resistance = self.Properties.Physics.LowSpec.water_resistance;
SimParams.water_density = self.Properties.Physics.LowSpec.water_density;
end
end
self.bRigidBodyActive = bActivateRigidBody;
if (bActivateRigidBody ~= 1) then
-- If rigid body should not be activated, it must have 0 mass.
SimParams.mass = 0;
SimParams.density = 0;
end
local Flags = { flags_mask=pef_fixed_damping+ref_use_simple_solver, flags=0 };
Flags.flags = self.Properties.Physics.bFixedDamping*pef_fixed_damping;
if self.Properties.Physics.bUseSimpleSolver then
Flags.flags = Flags.flags + self.Properties.Physics.bUseSimpleSolver*ref_use_simple_solver;
end
self:SetPhysicParams(PHYSICPARAM_SIMULATION, SimParams );
self:SetPhysicParams(PHYSICPARAM_BUOYANCY, self.Properties.Physics );
self:SetPhysicParams(PHYSICPARAM_FLAGS, Flags );
if (self.Properties.Physics.bResting == 0) then
self:EnableUpdate(1);
self:AwakePhysics(1);
else
self:EnableUpdate(0);
self:AwakePhysics(0);
end
else
-- Not rigid body, not character.
-- Make simple static physics.
if (bPhysicalize == 1) then
self:CreateStaticEntity( self.Mass,-1 );
if (self.bCharacter == 1) then
self:PhysicalizeCharacter( Mass,0,0,0);
end
end
end
-- physics-sounds
if (PhysicsSoundsTable) then
local SoundDesc;
-- load soft contact sounds
self.ContactSounds_Soft={};
if (PhysicsSoundsTable.Soft and PhysicsSoundsTable.Soft[self.Properties.Physics.Type]) then
SoundDesc=PhysicsSoundsTable.Soft[self.Properties.Physics.Type].Impact;
if (SoundDesc) then
self.ContactSounds_Soft.Impact=Sound:Load3DSound(SoundDesc[1], SoundDesc[2], 255, SoundDesc[4], SoundDesc[5]);
self.ContactSounds_Soft.ImpactVolume=SoundDesc[3];
end
SoundDesc=PhysicsSoundsTable.Soft[self.Properties.Physics.Type].Roll;
if (SoundDesc) then
self.ContactSounds_Soft.Roll=Sound:Load3DSound(SoundDesc[1], SoundDesc[2], 255, SoundDesc[4], SoundDesc[5]);
self.ContactSounds_Soft.RollVolume=SoundDesc[3];
Sound:SetSoundLoop(self.ContactSounds_Soft.Roll, 1);
end
SoundDesc=PhysicsSoundsTable.Soft[self.Properties.Physics.Type].Slide;
if (SoundDesc) then
self.ContactSounds_Soft.Slide=Sound:Load3DSound(SoundDesc[1], SoundDesc[2], 255, SoundDesc[4], SoundDesc[5]);
self.ContactSounds_Soft.SlideVolume=SoundDesc[3];
Sound:SetSoundLoop(self.ContactSounds_Soft.Slide, 1);
end
else
--System:Log("[BasicEntity] Warning: Table *PhysicsSoundsTable.Soft* or *PhysicsSoundsTable.Soft["..self.Properties.Physics.Type.."]* no found !");
end
-- load hard contact sounds
self.ContactSounds_Hard={};
if (PhysicsSoundsTable.Hard and PhysicsSoundsTable.Hard[self.Properties.Physics.Type]) then
SoundDesc=PhysicsSoundsTable.Hard[self.Properties.Physics.Type].Impact;
if (SoundDesc) then
self.ContactSounds_Hard.Impact=Sound:Load3DSound(SoundDesc[1], SoundDesc[2], 255, SoundDesc[4], SoundDesc[5]);
self.ContactSounds_Hard.ImpactVolume=SoundDesc[3];
end
SoundDesc=PhysicsSoundsTable.Hard[self.Properties.Physics.Type].Roll;
if (SoundDesc) then
self.ContactSounds_Hard.Roll=Sound:Load3DSound(SoundDesc[1], SoundDesc[2], 255, SoundDesc[4], SoundDesc[5]);
self.ContactSounds_Hard.RollVolume=SoundDesc[3];
Sound:SetSoundLoop(self.ContactSounds_Hard.Roll, 1);
end
SoundDesc=PhysicsSoundsTable.Hard[self.Properties.Physics.Type].Slide;
if (SoundDesc) then
self.ContactSounds_Hard.Slide=Sound:Load3DSound(SoundDesc[1], SoundDesc[2], 255, SoundDesc[4], SoundDesc[5]);
self.ContactSounds_Hard.SlideVolume=SoundDesc[3];
Sound:SetSoundLoop(self.ContactSounds_Hard.Slide, 1);
end
else
--System:Log("[BasicEntity] Warning: Table *PhysicsSoundsTable.Hard* or *PhysicsSoundsTable.Hard["..self.Properties.Physics.Type.."]* no found !");
end
else
--System:Log("[BasicEntity] Warning: Table *PhysicsSoundsTable* no found !");
end
end
------------------------------------------------------------------------------------------------------
function BasicEntity:OnReset()
--if (self:IsARigidBody() == 1) then
-- self:SetPhysicsProperties( 0,self.Properties.Physics.bRigidBodyActive );
--end
--self.Activated=0;
self:GotoState("Default");
if (self:IsARigidBody()==1) then
self:EnableUpdate(1-self.Properties.Physics.bResting);
self:AwakePhysics(1-self.Properties.Physics.bResting);
end
self:StopLastPhysicsSounds();
self:ResetAnimation(0);
if (self.Properties.aianchorAIAction~="") then
AI:RegisterWithAI(self.id, AIAnchor[self.Properties.aianchorAIAction], self.Properties.fAnchorRadius);
end
end
------------------------------------------------------------------------------------------------------
function BasicEntity:OnInit()
self:RegisterState("Default");
self:RegisterState("Activated");
self.bRigidBodyActive = self.Properties.Physics.bRigidBodyActive
self:NetPresent(nil);
self:SetFromProperties();
--self.Activated=0;
--self:EnableUpdate(0);
end
------------------------------------------------------------------------------------------------------
function BasicEntity:OnPropertyChange()
self:SetFromProperties();
end
------------------------------------------------------------------------------------------------------
function BasicEntity:OnEvent( id, params)
if (id == ScriptEvent_PhysicalizeOnDemand) then
self:SetPhysicsProperties( 0,self.bRigidBodyActive );
end
end
------------------------------------------------------------------------------------------------------
function BasicEntity:Event_Remove()
-- self:Hide(1);
self:DrawObject(0,0);
self:DestroyPhysics();
end
------------------------------------------------------------------------------------------------------
function BasicEntity:Event_Hide()
self:Hide(1);
--self:DrawObject(0,0);
--self:DestroyPhysics();
end
------------------------------------------------------------------------------------------------------
function BasicEntity:Event_UnHide()
self:Hide(0);
--self:DrawObject(0,1);
--self:SetPhysicsProperties( 1,self.bRigidBodyActive );
end
------------------------------------------------------------------------------------------------------
function BasicEntity:Event_ResetAnimation()
self:ResetAnimation(0);
self:PlaySound(self.animsoundstop);
end
------------------------------------------------------------------------------------------------------
function BasicEntity:OnCollide(hit)
if (hit.impact) then
if (self.Properties.Physics.HitDamageScale ~= nil and self.Properties.Physics.HitDamageScale ~= 0) then
if (self.OnDamage) then
if (not self._localHitTable) then
self._localHitTable = {pos={x=0,y=0,z=0},};
end
local pos = self:GetPos();
self._localHitTable.damage = hit.fSpeed*self.Properties.Physics.HitDamageScale;
self._localHitTable.pos.x = pos.x;
self._localHitTable.pos.y = pos.y;
self._localHitTable.pos.z = pos.z;
self:OnDamage( self._localHitTable );
end
end
end
if (self.Properties.Physics.Type) then
local mat=Game:GetMaterialBySurfaceID(hit.matId);
if (mat and mat.PhysicsSounds) then
local NewPhysicsSounds;
if (mat.PhysicsSounds==PhysicsSoundsTable.Soft) then
NewPhysicsSounds=self.ContactSounds_Soft;
else
NewPhysicsSounds=self.ContactSounds_Hard;
end
if (NewPhysicsSounds~=self.LastPhysicsSounds) then
self:StopLastPhysicsSounds();
end
self.LastPhysicsSounds=NewPhysicsSounds;
if (self.LastPhysicsSounds and self.LastPhysicsSounds.ImpactVolume) then
if (hit.impact) then
local Volume=hit.impact*0.1;
if (Volume>1) then Volume=1; end
local finalvol=Volume*self.LastPhysicsSounds.ImpactVolume;
if (self.LastPhysicsSounds.Impact and finalvol>1) then
self:PlaySound(self.LastPhysicsSounds.Impact);
Sound:SetSoundVolume(self.LastPhysicsSounds.Impact, finalvol);
--System:Log("Impact: "..hit.impact);
end
end
local Volume;
if (hit.roll) then
Volume=(hit.roll-0.1)*0.1;
else
Volume = 0;
end
if (Volume>1) then Volume=1; end
if (self.LastPhysicsSounds.Roll) then
local rollvol=Volume*self.LastPhysicsSounds.RollVolume;
if (rollvol>1) then
if (not Sound:IsPlaying(self.LastPhysicsSounds.Roll)) then
self:PlaySound(self.LastPhysicsSounds.Roll);
end
Sound:SetSoundVolume(self.LastPhysicsSounds.Roll, rollvol);
Sound:SetSoundFrequency(self.LastPhysicsSounds.Roll, Volume*400+800);
--System:Log("Roll: "..hit.roll);
end
end
if (hit.slide) then
Volume=(hit.slide-0.1)*0.1;
else
Volume = 0;
end
if (Volume>1) then Volume=1; end
if (self.LastPhysicsSounds.Slide) then
local slidevol=Volume*self.LastPhysicsSounds.SlideVolume;
if (slidevol>1) then
if (not Sound:IsPlaying(self.LastPhysicsSounds.Slide)) then
self:PlaySound(self.LastPhysicsSounds.Slide);
end
Sound:SetSoundVolume(self.LastPhysicsSounds.Slide,slidevol );
Sound:SetSoundFrequency(self.LastPhysicsSounds.Slide, Volume*400+800);
--System:Log("Slide: "..hit.slide);
end
end
end
end
end
--if (self.SplashSound and hit.waterresistance and (hit.waterresistance>0)) then
--self:PlaySound(self.SplashSound, hit.waterresistance*0.1);
--System:Log("Splash: "..hit.waterresistance*0.01);
--end
if (hit.splashes) then
if (g_lastSplashTime+g_SplashDuration < _time) then g_curSplashes = 0; end
for i,splash in hit.splashes do
if (g_curSplashes<g_maxSplashes) then
--System:Log("splash : ("..splash.center.x..","..splash.center.y..","..splash.center.z.."), radius "..splash.radius);
ExecuteMaterial(splash.center, g_Vectors.v001, CommonEffects.water_splash, 1);
g_curSplashes = g_curSplashes+1; g_lastSplashTime = _time;
end
end
end
end
------------------------------------------------------------------------------------------------------
function BasicEntity:StopLastPhysicsSounds()
self:OnStopRollSlideContact("roll");
self:OnStopRollSlideContact("slide");
end
------------------------------------------------------------------------------------------------------
function BasicEntity:OnStopRollSlideContact(ContactType)
if (self.LastPhysicsSounds) then
if (ContactType=="roll") then -- and (Sound:IsPlaying(self.LastPhysicsSounds.Roll))) then
--System:Log("Stopping Roll");
Sound:StopSound(self.LastPhysicsSounds.Roll);
end
if (ContactType=="slide") then -- and (Sound:IsPlaying(self.LastPhysicsSounds.Slide))) then
--System:Log("Stopping Slide");
Sound:StopSound(self.LastPhysicsSounds.Slide);
end
end
end
------------------------------------------------------------------------------------------------------
function BasicEntity:OnShutDown()
self:StopLastPhysicsSounds();
end
------------------------------------------------------------------------------------------------------
function BasicEntity:OnDamage( hit )
if (self:IsARigidBody() == 1) then
if (self.Properties.Physics.bActivateOnDamage == 1) then
if (hit.explosion and self:GetState()~="Activated") then
BroadcastEvent(self, "Activate");
self:GotoState("Activated");
end
obsolete = [[
if (self.Activated==0) then
--System:LogToConsole( "Activate!!" );
self.Activated=1;
BroadcastEvent(self, "Activate");
end
if (self.bRigidBodyActive == 0) then
--System:LogToConsole( "Activate!!" );
if (hit.explosion) then
self:SetPhysicsProperties( 0,1 );
--System:LogToConsole( "On Damage (by explosion)" );
self:EnableUpdate(1);
self:AwakePhysics(1);
end
end ]]
end
end
if( hit.ipart and hit.ipart>=0 ) then
self:AddImpulse( hit.ipart, hit.pos, hit.dir, hit.impact_force_mul );
end
end
------------------------------------------------------------------------------------------------------
-- Input events
------------------------------------------------------------------------------------------------------
function BasicEntity:Event_AddImpulse(sender)
local len = sqrt(LengthSqVector(self.Properties.Physics.vector_Impulse));
if (len>0) then
local rlen = 1.0/len;
self.temp_vec.x=self.Properties.Physics.vector_Impulse.x*rlen;
self.temp_vec.y=self.Properties.Physics.vector_Impulse.y*rlen;
self.temp_vec.z=self.Properties.Physics.vector_Impulse.z*rlen;
self:AddImpulse(0,nil,self.temp_vec,len);
end
end
------------------------------------------------------------------------------------------------------
function BasicEntity:Event_Activate(sender)
self:GotoState("Activated");
obsolete = [[
--System:Log("Activating RIGID BODY");
--create rigid body
if (self.Activated==0 and self:IsARigidBody() == 1) then
self:SetPhysicsProperties( 0,1 );
if (self.Properties.Physics.bResting==0) then
self:EnableUpdate(1);
self:AwakePhysics(1);
end
end ]]
end
------------------------------------------------------------------------------------------------------
function BasicEntity:StartEntityAnimation()
self:ResetAnimation(0);
self:StartAnimation( 0,self.Properties.Animation.Animation,0,0,1,self.Properties.Animation.bLoop );
self:SetAnimationSpeed( self.Properties.Animation.Speed );
self:PlaySound(self.animsoundstart);
end
------------------------------------------------------------------------------------------------------
function BasicEntity:Event_StartAnimation(sender)
self:StartEntityAnimation();
self.animstarted=1;
end
------------------------------------------------------------------------------------------------------
function BasicEntity:Event_StopAnimtion(sender)
self:ResetAnimation(0);
self:PlaySound(self.animsoundstop);
end
------------------------------------------------------------------------------------------------------
-- Events to switch material Applied to object.
------------------------------------------------------------------------------------------------------
function BasicEntity:CommonSwitchToMaterial( numStr )
if (not self.sOriginalMaterial) then
self.sOriginalMaterial = self:GetMaterial();
end
if (self.sOriginalMaterial) then
System:Log( "Material: "..self.sOriginalMaterial..numStr );
self:SetMaterial( self.sOriginalMaterial..numStr );
end
end
------------------------------------------------------------------------------------------------------
function BasicEntity:Event_SwitchToMaterialOriginal(sender)
self:CommonSwitchToMaterial( "" );
end
------------------------------------------------------------------------------------------------------
function BasicEntity:Event_SwitchToMaterial1(sender)
self:CommonSwitchToMaterial( "1" );
end
------------------------------------------------------------------------------------------------------
function BasicEntity:Event_SwitchToMaterial2(sender)
self:CommonSwitchToMaterial( "2" );
end
------------------------------------------------------------------------------------------------------
function BasicEntity:OnSave(stm)
stm:WriteInt(self.animstarted);
end
------------------------------------------------------------------------------------------------------
function BasicEntity:OnLoad(stm)
self.animstarted=stm:ReadInt();
if (self.animstarted==1) then
self:StartEntityAnimation();
end
end
function BasicEntity:OnLoadRELEASE(stm)
end
BasicEntity.Default = {
OnBeginState = function(self)
if (self:IsARigidBody()==1) then
if (self.bRigidBodyActive~=self.Properties.Physics.bRigidBodyActive) then
self:SetPhysicsProperties( 0,self.Properties.Physics.bRigidBodyActive );
else
self:EnableUpdate(1-self.Properties.Physics.bResting);
self:AwakePhysics(1-self.Properties.Physics.bResting);
end
else
self:EnableUpdate(0);
end
end,
OnDamage = BasicEntity.OnDamage,
OnCollide = BasicEntity.OnCollide,
}
BasicEntity.Activated = {
OnBeginState = function(self)
if (self:IsARigidBody()==1 and self.bRigidBodyActive==0) then
self:SetPhysicsProperties( 0,1 );
self:EnableUpdate(1);
self:AwakePhysics(1);
end
end,
OnDamage = BasicEntity.OnDamage,
OnCollide = BasicEntity.OnCollide,
}
|
class "Riven"
class "Download"
function Riven:__init()
self:Variables()
self:Menu()
self:Callbacks()
self:AutoUpdater()
self:LoadTableOrbs()
self:LoadOrb()
end
function Riven:Variables()
self.Version = 3.8
self.QTarget = nil
self.QCount = 0
self.LastQ = 0
self.SelectedTarget = nil
self.RTime = 0
self.Ulted = false
self.QAA = false
self.WCasted = false
if myHero:GetSpellData(SUMMONER_1).name:find("SummonerFlash") then
Flash = SUMMONER_1
elseif myHero:GetSpellData(SUMMONER_2).name:find("SummonerFlash") then
Flash = SUMMONER_2
end
if myHero:GetSpellData(SUMMONER_1).name:find("SummonerDot") then
Ignite = SUMMONER_1
elseif myHero:GetSpellData(SUMMONER_2).name:find("SummonerDot") then
Ignite = SUMMONER_2
end
ts = TargetSelector(TARGET_LESS_CAST_PRIORITY, 1000, DAMAGE_PHYSICAL)
enemyMinions = minionManager(MINION_ENEMY, 270, myHero, MINION_SORT_HEALTH_ASC)
jungleMinions = minionManager(MINION_JUNGLE, 270, myHero, MINION_SORT_MAXHEALTH_DEC)
end
function Riven:Menu()
Menu = scriptConfig("Shattered Blade", "ShatteredBlade")
Menu:addSubMenu("Combo", "Combo")
Menu.Combo:addParam("Mode", "Combo Mode", SCRIPT_PARAM_LIST, 1, {"BoxBox Mode"})
Menu.Combo:addParam("Burst", "Burst Mode", SCRIPT_PARAM_ONKEYTOGGLE, false, string.byte("T"))
Menu.Combo:permaShow("Burst")
Menu.Combo:addParam("useFlash", "Use Flash in Burst Mode", SCRIPT_PARAM_ONOFF, true)
Menu.Combo:permaShow("useFlash")
Menu.Combo:addParam("useFlashSlice", "Use Flash Above Range (BUGGY)", SCRIPT_PARAM_SLICE, 300, 0, 425)
Menu.Combo:addParam("blank", "Let E and R Range the Same for R Animation Cancel", SCRIPT_PARAM_INFO, " ")
Menu.Combo:addParam("useERange", "Use E Range Under", SCRIPT_PARAM_SLICE, 500, 175, 1000)
Menu.Combo:addParam("useRRange", "Use R Range Under", SCRIPT_PARAM_SLICE, 500, 175, 1000)
Menu:addSubMenu("LaneClear/JungleClear", "LaneJung")
Menu.LaneJung:addParam("Q", "Use Q", SCRIPT_PARAM_ONOFF, true)
Menu.LaneJung:addParam("W", "Use W", SCRIPT_PARAM_ONOFF, true)
Menu.LaneJung:addParam("E", "Use E", SCRIPT_PARAM_ONOFF, true)
Menu:addSubMenu("Auto W", "AutoW")
Menu.AutoW:addParam("W", "Use Auto W",SCRIPT_PARAM_ONOFF, true)
Menu.AutoW:addParam("S", "x Enemies for Auto W", SCRIPT_PARAM_SLICE, 2, 0, 5, 0)
Menu:addSubMenu("Items Settings", "Items")
Menu.Items:addParam("Use", "Use Items", SCRIPT_PARAM_ONOFF, true)
Menu.Items:addParam("UseBRK", "Use BRK", SCRIPT_PARAM_ONOFF, true)
Menu.Items:addParam("UseHydra", "Use Hydra", SCRIPT_PARAM_ONOFF, true)
Menu.Items:addParam("UseYoumu", "Use Youmus", SCRIPT_PARAM_ONOFF, true)
Menu.Items:addParam("UseQSS", "Use QSS", SCRIPT_PARAM_ONOFF, true)
Menu.Items:addParam("UseZhonya", "Use Zhonyas", SCRIPT_PARAM_ONOFF, true)
Menu.Items:addParam("ZhonyaAmount", "Zhonya %", SCRIPT_PARAM_SLICE, 15, 0, 100, 0)
Menu:addSubMenu("Draws Settings", "Draws")
Menu.Draws:addParam("CDTracker", "Use CD Tracker", SCRIPT_PARAM_ONOFF, true)
Menu:addSubMenu("Emote Cancel", "EmoteCancel")
Menu.EmoteCancel:addParam("useEmoteC", "Use Emote Cancel", SCRIPT_PARAM_ONOFF, true)
Menu.EmoteCancel:addParam("emoteC", "Choose Emote", SCRIPT_PARAM_LIST, 1, {"Dance", "Taunt", "Laugh", "Joke"})
Menu:addSubMenu("Auto Leveler", "Leveler")
if VIP_USER then
Menu.Leveler:addParam("Enable", "Enable Auto Leveler", SCRIPT_PARAM_ONOFF, false)
Menu.Leveler:addParam("Mode", "Mode", SCRIPT_PARAM_LIST, 2, {"Q>W>E", "Q>E>W", "E>Q>W", "E>W>Q"})
Menu.Leveler.Enable = false
DelayToLevel = 0
SequenceLevel = {
[1] = {1,2,3,1,1,4,2,1,2,3,4,1,2,3,2,4,3,3},
[2] = {1,3,2,1,1,4,3,1,3,2,4,1,3,2,3,4,2,2},
[3] = {3,1,2,3,3,4,1,3,1,2,4,3,1,2,1,4,2,2},
[4] = {3,2,1,3,3,4,2,3,2,1,4,3,2,1,2,4,1,1},
}
AddTickCallback(function()
if os.clock()-DelayToLevel >= 3 then
DelayToLevel = os.clock()
if Menu.Leveler.Enable then
autoLevelSetSequence(SequenceLevel[Menu.Leveler.Mode])
else
autoLevelSetSequence(nil)
end
end
end)
else
Menu.Leveler:addParam("info", "This is only for VIP Users", SCRIPT_PARAM_INFO, "")
end
Menu:addSubMenu("Skin Changer", "Skin")
if VIP_USER then
Menu.Skin:addParam("ChangeSkin", "Enable Skin Changer", SCRIPT_PARAM_ONOFF, false)
Menu.Skin:setCallback('ChangeSkin', function(Change)
if Change then
SetSkin(myHero, Menu.Skin.SkinID-1)
else
SetSkin(myHero, -1)
end
end)
Menu.Skin:addParam('SkinID', 'Skins', SCRIPT_PARAM_LIST, 1, {"Classic", "Redeemed", "Crimson Elite", "Battle Bunny", "Championship", "Dragonblade", "Arcade"})
Menu.Skin.SkinID = 1
Menu.Skin:setCallback('SkinID', function(Change)
if Menu.Skin.ChangeSkin then
SetSkin(myHero, Menu.Skin.SkinID-1)
end
end)
if Menu.Skin.ChangeSkin then
SetSkin(myHero, Menu.Skin.SkinID-1)
end
else
Menu.Skin:addParam("info", "This is only for VIP Users", SCRIPT_PARAM_INFO, "")
end
if Ignite then
Menu:addParam("AutoIgnite", "Use Auto Ignite in killable enemies", SCRIPT_PARAM_ONOFF, true)
end
Menu:addParam("Region", "Your Region:", SCRIPT_PARAM_INFO, GetGameRegion())
end
function Riven:Callbacks()
AddTickCallback(function()
if myHero.dead then return end
Target = self:GetCustomTarget()
self:ComboManager(Target)
self:LaneClear()
self:AutoW()
self:Flee()
self:Checks()
self:AutoIgnite()
if myHero:GetSpellData(_Q).currentCd > 0.5 then self.QAA = false end
if myHero:GetSpellData(_W).currentCd > 1 then self.WCasted = true end
if self.Wready then self.WCasted = false end
end)
AddAnimationCallback(function(unit, animation)
if unit and animation and unit.isMe then
if animation == "Spell1a" or animation == "Spell1b" or animation == "Spell1c" then
if animation == "Spell1a" or animation == "Spell1b" then
DelayAction(function()
if ValidTarget(self.QTarget) and GetDistance(self.QTarget) < 270 then
if Menu.EmoteCancel.useEmoteC then DoEmote(Menu.EmoteCancel.emoteC-1) end
self:ResetAAs()
end
end, 0.3-GetLatency()/1000)
elseif animation == "Spell1c" then
DelayAction(function()
if ValidTarget(self.QTarget) and GetDistance(self.QTarget) < 270 then
if Menu.EmoteCancel.useEmoteC then DoEmote(Menu.EmoteCancel.emoteC-1) end
self:ResetAAs()
end
end, 0.4-GetLatency()/1000)
end
end
end
end)
AddMsgCallback(function(msg, key)
if msg == WM_LBUTTONDOWN and not myHero.dead then
for i, enemy in ipairs(GetEnemyHeroes()) do
if GetDistance(enemy, mousePos) <= 115 and ValidTarget(enemy) and enemy.type == "AIHeroClient" then
if self.SelectedTarget ~= enemy then
self.SelectedTarget = enemy
SendMsg("Selected Target: "..enemy.charName)
else
self.SelectedTarget = nil
SendMsg("Unselected Target: "..enemy.charName)
end
end
end
end
end)
AddDrawCallback(function()
if Menu.Draws.CDTracker then
self:DrawCD()
end
if(self:GetCustomTarget()) then
DrawTextA("Target: "..tostring(self:GetCustomTarget().charName),12,60,180)
end
if myHero.dead then return end
end)
AddProcessAttackCallback(function(unit, spell)
self.AADone = false
if unit.isMe and spell.name:lower():find("attack") then
if self.QAA == true and self:Keys() == "Combo" or self:Keys() == "Laneclear" or self:Keys() == "Harass" then
CastSpell(_Q, myHero.spell.target.x, myHero.spell.target.z)
self:ResetAAs()
end
self.AADone = true
end
end)
AddApplyBuffCallback(function(unit, source, buff)
if unit and buff and unit.isMe and buff.name == "RivenFengShuiEngine" then
self.Ulted = true
self.RTime = os.clock()
end
end)
AddRemoveBuffCallback(function(unit, buff)
if unit and buff and unit.isMe and buff.name == "rivenwindslashready" then
self.Ulted = false
self.RTime = 0
end
if unit and buff and unit.isMe and buff.name == "riventricleavesoundthree" then
--self.QAA = false
end
end)
AddUnloadCallback(function()
if VIP_USER then
SetSkin(myHero, -1)
end
end)
end
function Riven:AutoIgnite()
if Ignite and Menu.AutoIgnite then
for i, enemy in ipairs(GetEnemyHeroes()) do
if enemy.health <= 50 + (20 * myHero.level) and myHero:CanUseSpell(Ignite) == READY and GetDistance(enemy) < 650 then
CastSpell(Ignite, enemy)
end
end
end
end
function Riven:IsAfterAA()
return os.clock() * 1000 + (GetLatency() / 2) < self.AfterAttackTime
end
function Riven:GetHPBarPos(enemy)
enemy.barData = {PercentageOffset = {x = -0.05, y = 0}}--GetEnemyBarData()
local barPos = GetUnitHPBarPos(enemy)
local barPosOffset = GetUnitHPBarOffset(enemy)
local barOffset = { x = enemy.barData.PercentageOffset.x, y = enemy.barData.PercentageOffset.y }
local barPosPercentageOffset = { x = enemy.barData.PercentageOffset.x, y = enemy.barData.PercentageOffset.y }
local BarPosOffsetX = 171
local BarPosOffsetY = 46
local CorrectionY = 39
local StartHpPos = 31
barPos.x = math.floor(barPos.x + (barPosOffset.x - 0.5 + barPosPercentageOffset.x) * BarPosOffsetX + StartHpPos)
barPos.y = math.floor(barPos.y + (barPosOffset.y - 0.5 + barPosPercentageOffset.y) * BarPosOffsetY + CorrectionY)
local StartPos = Vector(barPos.x , barPos.y, 0)
local EndPos = Vector(barPos.x + 108 , barPos.y , 0)
return Vector(StartPos.x, StartPos.y, 0), Vector(EndPos.x, EndPos.y, 0)
end
function Riven:DrawCD()
for i = 1, heroManager.iCount, 1 do
local champ = heroManager:getHero(i)
if champ ~= nil and champ ~= myHero and champ.visible and champ.dead == false then
local barPos = self:GetHPBarPos(champ)
if OnScreen(barPos.x, barPos.y) then
local cd = {}
cd[0] = math.ceil(champ:GetSpellData(SPELL_1).currentCd)
cd[1] = math.ceil(champ:GetSpellData(SPELL_2).currentCd)
cd[2] = math.ceil(champ:GetSpellData(SPELL_3).currentCd)
cd[3] = math.ceil(champ:GetSpellData(SPELL_4).currentCd)
local spellColor = {}
spellColor[0] = 0xBBFFD700;
spellColor[1] = 0xBBFFD700;
spellColor[2] = 0xBBFFD700;
spellColor[3] = 0xBBFFD700;
if cd[0] == nil or cd[0] == 0 then cd[0] = "Q" spellColor[0] = 0xBBFFFFFF end
if cd[1] == nil or cd[1] == 0 then cd[1] = "W" spellColor[1] = 0xBBFFFFFF end
if cd[2] == nil or cd[2] == 0 then cd[2] = "E" spellColor[2] = 0xBBFFFFFF end
if cd[3] == nil or cd[3] == 0 then cd[3] = "R" spellColor[3] = 0xBBFFFFFF end
if champ:GetSpellData(SPELL_1).level == 0 then spellColor[0] = 0xBBFF0000 end
if champ:GetSpellData(SPELL_2).level == 0 then spellColor[1] = 0xBBFF0000 end
if champ:GetSpellData(SPELL_3).level == 0 then spellColor[2] = 0xBBFF0000 end
if champ:GetSpellData(SPELL_4).level == 0 then spellColor[3] = 0xBBFF0000 end
DrawRectangle(barPos.x-6, barPos.y-40, 80, 15, 0xBB202020)
DrawText("[" .. cd[0] .. "]" ,12, barPos.x-5+2, barPos.y-40, spellColor[0])
DrawText("[" .. cd[1] .. "]", 12, barPos.x+15+2, barPos.y-40, spellColor[1])
DrawText("[" .. cd[2] .. "]", 12, barPos.x+35+2, barPos.y-40, spellColor[2])
DrawText("[" .. cd[3] .. "]", 12, barPos.x+54+2, barPos.y-40, spellColor[3])
end
end
end
end
function Riven:ResetAAs()
if self.LoadedOrb == "Sac" and TIMETOSACLOAD then
_G.AutoCarry.Orbwalker:ResetAttackTimer()
--_G.AutoCarry.Orbwalker:IsAfterAttack()
elseif LoadedOrb == "Mma" then
_G.MMA_ResetAutoAttack()
elseif self.LoadedOrb == "Pewalk" then
elseif self.LoadedOrb == "Now" then
_G.NebelwolfisOrbWalker:ResetAA()
elseif self.LoadedOrb == "Big" then
elseif self.LoadedOrb == "Sow" then
_G.SOWi:resetAA()
elseif self.LoadedOrb == "SxOrbWalk" then
_G.SxOrb:ResetAA()
elseif self.LoadedOrb == "S1mpleOrbWalker" then
_G.S1mpleOrbWalker:ResetAA()
end
end
function Riven:GetCustomTarget()
ts:update()
if self.SelectedTarget == nil then
return ts.target
elseif self.SelectedTarget ~= nil and ValidTarget(self.SelectedTarget, 750) then
return self.SelectedTarget
else
return ts.target
end
end
function Riven:AutoUpdater()
local host = "www.scarjit.de"
local file = "/HiranN/BoL/Scripts/Riven.lua"
local file2 = "/HiranN/BoL/Versions/"
local name = GetCurrentEnv().FILE_NAME
local path = SCRIPT_PATH
DelayAction(function()
local ServerVersionDATA = GetWebResult(host, file2.."Riven.version")
local ServerVersion = tonumber(ServerVersionDATA)
if ServerVersion then
if ServerVersion > tonumber(self.Version) then
DL = Download()
SendMsg("Updating to version: "..ServerVersion)
DL:newDL(host, file, name, path, function()
SendMsg("Updated to version: "..ServerVersion..", press 2x F9")
end)
else
SendMsg("You have the latest version: "..self.Version)
end
else
SendMsg("Can't connect to Updater Site")
end
end, 0.85)
end
function Riven:ComboManager(target)
if Menu.Combo.Burst then
self:Combo2(target)
elseif Menu.Combo.Mode == 1 then
self:Combo1(target)
end
if ValidTarget(target) then
CastItems()
end
end
function Riven:AutoW()
if Menu.AutoW.S ~= 0 then
if Menu.AutoW.W and CountEnemyHeroInRange(260) >= Menu.AutoW.S then
CastSpell(_W)
end
end
end
DelayFleeM = 0
function Riven:Flee()
if Menu.Keys.Flee then
CastSpell(_Q, mousePos.x, mousePos.z)
CastSpell(_E, mousePos.x, mousePos.z)
if os.clock()-DelayFleeM > 0.15 then
DelayFleeM = os.clock()
myHero:MoveTo(mousePos.x, mousePos.z)
end
end
end
function Riven:Checks()
self.Qready = (myHero:CanUseSpell(_Q) == READY and true or false)
self.Wready = (myHero:CanUseSpell(_W) == READY and true or false)
self.Eready = (myHero:CanUseSpell(_E) == READY and true or false)
self.Rready = (myHero:CanUseSpell(_R) == READY and true or false)
if Flash then
self.Flash = (myHero:CanUseSpell(Flash) == READY and true or false)
end
end
function Riven:Combo1(target)
if ValidTarget(target) and self:Keys() == "Combo" then
if self.Qready and not self.Eready and not self.Wready and not self.Rready then
self:CastQAA2(target)
end
if self.Eready and self.Qready and not self.Wready and not self.Rready and not self.Ulted then
self:CastE(target)
self:CastQAA2(target)
end
if self.Eready and not self.Qready and not self.Wready and not self.Rready and not self.Ulted then
self:CastE(target)
if self.LoadedOrb == "Sac" then self:CastItems2(target) end
end
if self.Eready and self.Wready and not self.Qready and not self.Rready and not self.Ulted then
self:CastE(target)
self:CastW(target)
end
if self.Eready and self.Ulted and self.Rready and target.health <= self:rDmg(target) then
self:CastE(target)
self:CastR(target)
end
if self.Wready and self.Rready and not self.Qready and not self.Eready and not self.Ulted then
self:CastR(target)
self:CastW(target)
end
if self.Wready and not self.Qready and not self.Eready and not self.Rready then
self:CastW(target)
if self.LoadedOrb == "Sac" then self:CastItems2(target) end
end
if self.Wready and self.Ulted and self.Rready and target.health <= self:rDmg(target) and not self.Qready and not self.Eready then
self:CastR(target)
self:CastW(target)
end
if self.Qready and self.Ulted and target.health <= self:rDmg(target) and not self.Eready and not self.Wready then
self:CastR(target)
self:CastQAA2(target)
end
if self.Eready and self.Qready and not self.Wready and not self.Rready and not self.Ulted then
self:CastE(target)
--AA
if self.LoadedOrb == "Sac" then self:CastItems2(target) end
self:CastQAA2(target)
end
if self.Eready and self.Wready and not self.Qready and not self.Rready and not self.Ulted then
self:CastE(target)
-- AA
if self.LoadedOrb == "Sac" then self:CastItems2(target) end
self:CastW(target)
end
if self.Eready and self.Rready and self.Qready and not self.Wready and not self.Ulted then
self:CastE(target)
self:CastR(target)
self:CastQAA2(target)
end
if self.Eready and self.Qready and self.Ulted and self.Rready and not self.Wready then
self:CastE(target)
self:CastR(target)
self:CastQAA2(target)
end
if self.Eready and self.Qready and self.Wready and not self.Rready and not self.Ulted then
self:CastE(target)
--AA!!
if self.LoadedOrb == "Sac" then self:CastItems2(target) end
self:CastQAA2(target) --1 Q
self:CastW(target)
end
if self.Eready and self.Rready and self.Qready and not self.Wready and not self.Ulted then
self:CastE(target)
if self.LoadedOrb == "Sac" then self:CastItems2(target) end
self:CastR(target)
self:CastQAA2(target)
end
if self.Eready and self.Ulted and self.Rready and self.Wready and not self.Qready and target.health <= self:rDmg(target) then
self:CastE(target)
if self.LoadedOrb == "Sac" then self:CastItems2(target) end
self:CastR(target)
end
if self.Eready and self.Wready and self.Qready and not self.Rready and not self.Ulted then
self:CastE(target)
if self.LoadedOrb == "Sac" then self:CastItems2(target) end
self:CastW(target)
self:CastQAA2(target)
end
if self.Eready and self.Rready and not self.Ulted and self.Wready and self.Qready then
self:CastE(target)
if self.LoadedOrb == "Sac" then self:CastItems2(target) end
self:CastR(target)
self:CastW(target)
self:CastQAA2(target)
end
if self.Eready and self.Ulted and self.Wready and self.Qready and target.health <= self:rDmg(target) then
self:CastE(target)
if self.LoadedOrb == "Sac" then self:CastItems2(target) end
self:CastR(target)
self:CastW(target)
self:CastQAA2(target)
end
end
end
function Riven:Combo2(target)
if ValidTarget(target) and self:Keys() == "Combo" then
if self.Eready and self.Rready and self.Wready and self.Qready then -- noch Check hinzuf�?�?�?â??�?â??�?�¼gen f�?�?�?â??�?â??�?�¼r Flash, Menu Flash nutzen
self:CastE(target)
self:CastR(target)
if self.Flash and self.Ulted and GetDistance(target) <= Menu.Combo.useFlashSlice and Menu.Combo.useFlash then
CastSpell(Flash, target.x, target.z)
end
self:CastW(target)
-- AA
if self.WCasted == true then
CastSpell(_R, target.x, target.z)
else
DelayAction(function ()
CastSpell(_R, target.x, target.z)
end, 3)
end
self:CastQAA(target)
elseif Menu.Combo.Burst then
Menu.Combo.Burst = false
end
end
end
function Riven:LaneClear()
if self:Keys() == "Laneclear" then
enemyMinions:update()
jungleMinions:update()
for _, minion in pairs(enemyMinions.objects) do
if Menu.LaneJung.Q then
self:CastQAA2(minion)
end
if Menu.LaneJung.W then
self:CastW(minion)
end
end
for _, minion in pairs(jungleMinions.objects) do
if Menu.LaneJung.Q then
self:CastQAA2(minion)
end
if Menu.LaneJung.W then
self:CastW(minion)
end
if Menu.LaneJung.E then
self:CastE(minion)
end
end
end
end
function Riven:CastItems2 (target)
_G.AutoCarry.Items:UseAll(target)
end
function Riven:CastQAA(target)
if ValidTarget(target) then
self.QTarget = target
if GetDistance(target) > 270 then
self.QAA = true
end
end
end
function Riven:CastQAA2(target)
if ValidTarget(target) then
if GetDistance(target) < 270 then
self.QAA = true
else
self:CastQAA(target)
end
end
end
function Riven:CastW(target)
if ValidTarget(target, 255) and myHero:GetSpellData(_Q).currentCd > 0.5 then
CastSpell(_W)
end
end
function Riven:CastE(target)
if ValidTarget(target, Menu.Combo.useERange) then
CastSpell(_E, target.x, target.z)
end
end
function Riven:CastR(target)
if ValidTarget(target, Menu.Combo.useRRange) then
if not self.Ulted then CastSpell(_R) end
if self.Ulted then
if self:rDmg(target) >= target.health or self.RTime-os.clock() <= -11 then
CastSpell(_R, target.x, target.z)
end
end
end
end
function Riven:rDmg(unit)
local Lvl = myHero:GetSpellData(_R).level
if Lvl < 1 then return 0 end
local DMGCALC = 0
bad = myHero.addDamage*(1.2)
ad = myHero.totalDamage+bad
local hpercent = unit.health/unit.maxHealth
if hpercent <= 0.25 then
DMGCALC = 120*myHero:GetSpellData(_R).level+120+1.8*bad
else
DMGCALC = (40*myHero:GetSpellData(_R).level+40+0.6*bad) * (hpercent)*(-2.67) + 3.67
end
return myHero:CalcDamage(unit, DMGCALC)
end
function Riven:LoadTableOrbs()
self.OrbWalkers = {}
self.LoadedOrb = nil
if _G.Reborn_Loaded or _G.Reborn_Initialised or _G.AutoCarry ~= nil then
table.insert(self.OrbWalkers, "SAC")
end
if _G.MMA_IsLoaded then
table.insert(self.OrbWalkers, "MMA")
end
if _G._Pewalk then
table.insert(self.OrbWalkers, "Pewalk")
end
if FileExist(LIB_PATH .. "/Nebelwolfi's Orb Walker.lua") then
table.insert(self.OrbWalkers, "NOW")
end
if FileExist(LIB_PATH .. "/Big Fat Orbwalker.lua") then
table.insert(self.OrbWalkers, "Big Fat Walk")
end
if FileExist(LIB_PATH .. "/SOW.lua") then
table.insert(self.OrbWalkers, "SOW")
end
if FileExist(LIB_PATH .. "/SxOrbWalk.lua") then
table.insert(self.OrbWalkers, "SxOrbWalk")
end
if FileExist(LIB_PATH .. "/S1mpleOrbWalker.lua") then
table.insert(self.OrbWalkers, "S1mpleOrbWalker")
end
if #self.OrbWalkers > 0 then
Menu:addSubMenu("Orbwalkers", "Orbwalkers")
Menu:addSubMenu("Keys", "Keys")
Menu.Orbwalkers:addParam("Orbwalker", "OrbWalker", SCRIPT_PARAM_LIST, 1, self.OrbWalkers)
Menu.Keys:addParam("info", "Detecting keys from :", SCRIPT_PARAM_INFO, self.OrbWalkers[Menu.Orbwalkers.Orbwalker])
Menu.Keys:addParam("Flee", "Flee Key", SCRIPT_PARAM_ONKEYDOWN, false, string.byte("G"))
local OrbAlr = false
Menu.Orbwalkers:setCallback("Orbwalker", function(value)
if OrbAlr then return end
OrbAlr = true
Menu.Orbwalkers:addParam("info", "Press F9 2x to load your selected Orbwalker.", SCRIPT_PARAM_INFO, "")
SendMsg("Press F9 2x to load your selected Orbwalker")
end)
end
end
function CastItems()
___GetInventorySlotItem = rawget(_G, "GetInventorySlotItem")
_G.GetInventorySlotItem = GetSlotItem
_G.ITEM_1 = 06
_G.ITEM_2 = 07
_G.ITEM_3 = 08
_G.ITEM_4 = 09
_G.ITEM_5 = 10
_G.ITEM_6 = 11
_G.ITEM_7 = 12
ItemNames = {
[3144] = "BilgewaterCutlass",
[3153] = "ItemSwordOfFeastAndFamine",
[3405] = "TrinketSweeperLvl1",
[3166] = "TrinketTotemLvl1",
[3361] = "TrinketTotemLvl3",
[3362] = "TrinketTotemLvl4",
[2003] = "RegenerationPotion",
[3146] = "HextechGunblade",
[3187] = "HextechSweeper",
[3364] = "TrinketSweeperLvl3",
[3074] = "ItemTiamatCleave",
[3077] = "ItemTiamatCleave",
[3340] = "TrinketTotemLvl1",
[3090] = "ZhonyasHourglass",
[3142] = "YoumusBlade",
[3157] = "ZhonyasHourglass",
[3350] = "TrinketTotemLvl2",
[3140] = "QuicksilverSash",
[3139] = "ItemMercurial",
}
if Target ~= nil then
if Menu.Items.UseBRK then
local slot = GetInventorySlotItem(3153)
if Target ~= nil and ValidTarget(Target) and not Target.dead and slot ~= nil and myHero:CanUseSpell(slot) == READY and GetDistance(Target) <= 450 then
CastSpell(slot, Target)
end
end
if Menu.Items.UseHydra then
local slot = GetInventorySlotItem(3074)
if Target ~= nil and ValidTarget(Target) and not Target.dead and slot ~= nil and myHero:CanUseSpell(slot) == READY and GetDistance(Target) <= 300 then
CastSpell(slot)
end
end
if Menu.Items.UseQSS then
if GetInventorySlotItem(3139) ~= nil then
local slot = GetInventorySlotItem(3139)
elseif GetInventorySlotItem(3140) ~= nil then
local slot = GetInventorySlotItem(3140) end
local buffsList = 6,8,9,11,20,21,23,24,29,30,31
if Target ~= nil and ValidTarget(Target) and not Target.dead and slot ~= nil and myHero:CanUseSpell(slot) == READY and GetDistance(Target) <= 600 and HaveBuffs(myHero, buffsList) then
CastSpell(slot)
end
end
if Menu.Items.UseYoumu then
local slot = GetInventorySlotItem(3142)
if Target ~= nil and ValidTarget(Target) and not Target.dead and slot ~= nil and myHero:CanUseSpell(slot) == READY then
CastSpell(slot)
end
end
if Menu.Items.UseZhonya then
local slot = GetInventorySlotItem(3157)
if myHero.health <= (myHero.maxHealth * Menu.Items.ZhonyaAmount / 100) and slot ~= nil and myHero:CanUseSpell(slot) == READY and CountEnemyHeroInRange(900) >= 1 then CastSpell(slot) end
end
end
end
function GetSlotItem(id, unit)
unit = unit or myHero
if (not ItemNames[id]) then
return ___GetInventorySlotItem(id, unit)
end
local name = ItemNames[id]
for slot = ITEM_1, ITEM_7 do
local item = unit:GetSpellData(slot).name
if ((#item > 0) and (item:lower() == name:lower())) then
return slot
end
end
end
function Riven:LoadOrb()
if self.OrbWalkers[Menu.Orbwalkers.Orbwalker] == "SAC" then
self.LoadedOrb = "Sac"
TIMETOSACLOAD = false
DelayAction(function()
TIMETOSACLOAD = true
end,15)
elseif self.OrbWalkers[Menu.Orbwalkers.Orbwalker] == "MMA" then
self.LoadedOrb = "Mma"
elseif self.OrbWalkers[Menu.Orbwalkers.Orbwalker] == "Pewalk" then
self.LoadedOrb = "Pewalk"
elseif self.OrbWalkers[Menu.Orbwalkers.Orbwalker] == "NOW" then
self.LoadedOrb = "Now"
require "Nebelwolfi's Orb Walker"
_G.NOWi = NebelwolfisOrbWalkerClass()
--Menu.Orbwalkers:addSubMenu("NOW", "NOW")
--_G.NebelwolfisOrbWalkerClass(Menu.Orbwalkers.NOW)
elseif self.OrbWalkers[Menu.Orbwalkers.Orbwalker] == "Big Fat Walk" then
self.LoadedOrb = "Big"
require "Big Fat Orbwalker"
elseif self.OrbWalkers[Menu.Orbwalkers.Orbwalker] == "SOW" then
self.LoadedOrb = "Sow"
require "SOW"
Menu.Orbwalkers:addSubMenu("SOW", "SOW")
_G.SOWi = SOW(_G.VP)
SOW:LoadToMenu(Menu.Orbwalkers.SOW)
elseif self.OrbWalkers[Menu.Orbwalkers.Orbwalker] == "SxOrbWalk" then
self.LoadedOrb = "SxOrbWalk"
require "SxOrbWalk"
Menu.Orbwalkers:addSubMenu("SxOrbWalk", "SxOrbWalk")
SxOrb:LoadToMenu(Menu.Orbwalkers.SxOrbWalk)
elseif self.OrbWalkers[Menu.Orbwalkers.Orbwalker] == "S1mpleOrbWalker" then
self.LoadedOrb = "S1mpleOrbWalker"
require "S1mpleOrbWalker"
_G.S1mpleOrbWalker = S1mpleOrbWalker()
DelayAction(function()
_G.S1mpleOrbWalker:AddToMenu(Menu.Orbwalkers)
end, 1)
end
end
function Riven:Keys()
if self.LoadedOrb == "Sac" and TIMETOSACLOAD then
if _G.AutoCarry.Keys.AutoCarry then return "Combo" end
if _G.AutoCarry.Keys.MixedMode then return "Harass" end
if _G.AutoCarry.Keys.LaneClear then return "Laneclear" end
if _G.AutoCarry.Keys.LastHit then return "Lasthit" end
elseif self.LoadedOrb == "Mma" then
if _G.MMA_IsOrbwalking() then return "Combo" end
if _G.MMA_IsDualCarrying() then return "Harass" end
if _G.MMA_IsLaneClearing() then return "Laneclear" end
if _G.MMA_IsLastHitting() then return "Lasthit" end
elseif self.LoadedOrb == "Pewalk" then
if _G._Pewalk.GetActiveMode().Carry then return "Combo" end
if _G._Pewalk.GetActiveMode().Mixed then return "Harass" end
if _G._Pewalk.GetActiveMode().LaneClear then return "Laneclear" end
if _G._Pewalk.GetActiveMode().Farm then return "Lasthit" end
elseif self.LoadedOrb == "Now" then
if _G.NOWi.mode == "LastHit" then
return "Lasthit"
elseif _G.NOWi.mode ~= "JungleClear" then
return _G.NOWi.mode
end
--[[
if _G.NOWi.Config.k.Combo then return "Combo" end
if _G.NOWi.Config.k.Harass then return "Harass" end
if _G.NOWi.Config.k.LaneClear then return "Laneclear" end
if _G.NOWi.Config.k.LastHit then return "Lasthit" end
]]--
elseif self.LoadedOrb == "Big" then
if _G["BigFatOrb_Mode"] == "Combo" then return "Combo" end
if _G["BigFatOrb_Mode"] == "Harass" then return "Harass" end
if _G["BigFatOrb_Mode"] == "LaneClear" then return "Laneclear" end
if _G["BigFatOrb_Mode"] == "LastHit" then return "Lasthit" end
elseif self.LoadedOrb == "Sow" then
if _G.SOWi.Menu.Mode0 then return "Combo" end
if _G.SOWi.Menu.Mode1 then return "Harass" end
if _G.SOWi.Menu.Mode2 then return "Laneclear" end
if _G.SOWi.Menu.Mode3 then return "Lasthit" end
elseif self.LoadedOrb == "SxOrbWalk" then
if _G.SxOrb.isFight then return "Combo" end
if _G.SxOrb.isHarass then return "Harass" end
if _G.SxOrb.isLaneClear then return "Laneclear" end
if _G.SxOrb.isLastHit then return "Lasthit" end
elseif self.LoadedOrb == "S1mpleOrbWalker" then
return _G.S1mpleOrbWalker:GetOrbMode()
end
end
function Download:__init()
socket = require("socket")
self.aktivedownloads = {}
self.callbacks = {}
AddTickCallback(function ()
self:RemoveDone()
end)
class("Async")
function Async:__init(host, filepath, localname, drawoffset, localpath)
self.progress = 0
self.host = host
self.filepath = filepath
self.localname = localname
self.offset = drawoffset
self.localpath = localpath
self.CRLF = '\r\n'
self.headsocket = socket.tcp()
self.headsocket:settimeout(1)
self.headsocket:connect(self.host, 80)
self.headsocket:send('HEAD '..self.filepath..' HTTP/1.1'.. self.CRLF ..'Host: '..self.host.. self.CRLF ..'User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36'.. self.CRLF .. self.CRLF)
self.HEADdata = ""
self.DLdata = ""
self.StartedDownload = false
self.canDL = true
AddTickCallback(function ()
self:tick()
end)
AddDrawCallback(function ()
self:draw()
end)
end
function Async:tick()
if self.progress == 100 then return end
if self.HEADcStatus ~= "timeout" and self.HEADcStatus ~= "closed" then
self.HEADfString, self.HEADcStatus, self.HEADpString = self.headsocket:receive(16);
if self.HEADfString then
self.HEADdata = self.HEADdata..self.HEADfString
elseif self.HEADpString and #self.HEADpString > 0 then
self.HEADdata = self.HEADdata..self.HEADpString
end
elseif self.HEADcStatus == "timeout" then
self.headsocket:close()
--Find Lenght
local begin = string.find(self.HEADdata, "Length: ")
if begin then
self.HEADdata = string.sub(self.HEADdata,begin+8)
local n = 0
local _break = false
for i=1, #self.HEADdata do
local c = tonumber(string.sub(self.HEADdata,i,i))
if c and _break == false then
n = n+1
else
_break = true
end
end
self.HEADdata = string.sub(self.HEADdata,1,n)
self.StartedDownload = true
self.HEADcStatus = "closed"
end
end
if self.HEADcStatus == "closed" and self.StartedDownload == true and self.canDL == true then --Double Check
self.canDL = false
self.DLsocket = socket.tcp()
self.DLsocket:settimeout(1)
self.DLsocket:connect(self.host, 80)
--Start Main Download
self.DLsocket:send('GET '..self.filepath..' HTTP/1.1'.. self.CRLF ..'Host: '..self.host.. self.CRLF ..'User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36'.. self.CRLF .. self.CRLF)
end
if self.DLsocket and self.DLcStatus ~= "timeout" and self.DLcStatus ~= "closed" then
self.DLfString, self.DLcStatus, self.DLpString = self.DLsocket:receive(1024);
if ((self.DLfString) or (self.DLpString and #self.DLpString > 0)) then
self.DLdata = self.DLdata .. (self.DLfString or self.DLpString)
end
elseif self.DLcStatus and self.DLcStatus == "timeout" then
self.DLsocket:close()
self.DLcStatus = "closed"
self.DLdata = string.sub(self.DLdata,#self.DLdata-tonumber(self.HEADdata)+1)
local file = io.open(self.localpath.."\\"..self.localname, "w+b")
file:write(self.DLdata)
file:close()
self.progress = 100
end
if self.progress ~= 100 and self.DLdata and #self.DLdata > 0 then
self.progress = (#self.DLdata/tonumber(self.HEADdata))*100
end
end
function Async:draw()
if self.progress < 100 then
DrawTextA("Downloading: "..self.localname,15,50,35+self.offset)
DrawRectangleOutline(49,50+self.offset,250,20, ARGB(255,255,255,255),1)
if self.progress ~= 100 then
DrawLine(50,60+self.offset,50+(2.5*self.progress),60+self.offset,18,ARGB(150,255-self.progress*2.5,self.progress*2.5,255-self.progress*2.5))
DrawTextA(tostring(math.round(self.progress).." %"), 15,150,52+self.offset)
end
end
end
end
function Download:newDL(host, file, name, path, callback)
local offset = (#self.aktivedownloads+1)*40
self.aktivedownloads[#self.aktivedownloads+1] = Async(host, file, name, offset-40, path)
if not callback then
callback = (function ()
end)
end
self.callbacks[#self.callbacks+1] = callback
end
function Download:RemoveDone()
if #self.aktivedownloads == 0 then return end
local x = {}
for k, v in pairs(self.aktivedownloads) do
if math.round(v.progress) < 100 then
v.offset = k*40-40
x[#x+1] = v
else
self.callbacks[k]()
end
end
self.aktivedownloads = {}
self.aktivedownloads = x
end
if myHero.charName ~= "Riven" then return end
-- BoL Tools Tracker --
assert(load(Base64Decode("G0x1YVIAAQQEBAgAGZMNChoKAAAAAAAAAAAAAQQfAAAAAwAAAEQAAACGAEAA5QAAAJ1AAAGGQEAA5UAAAJ1AAAGlgAAACIAAgaXAAAAIgICBhgBBAOUAAQCdQAABhkBBAMGAAQCdQAABhoBBAOVAAQCKwICDhoBBAOWAAQCKwACEhoBBAOXAAQCKwICEhoBBAOUAAgCKwACFHwCAAAsAAAAEEgAAAEFkZFVubG9hZENhbGxiYWNrAAQUAAAAQWRkQnVnc3BsYXRDYWxsYmFjawAEDAAAAFRyYWNrZXJMb2FkAAQNAAAAQm9sVG9vbHNUaW1lAAQQAAAAQWRkVGlja0NhbGxiYWNrAAQGAAAAY2xhc3MABA4AAABTY3JpcHRUcmFja2VyAAQHAAAAX19pbml0AAQSAAAAU2VuZFZhbHVlVG9TZXJ2ZXIABAoAAABzZW5kRGF0YXMABAsAAABHZXRXZWJQYWdlAAkAAAACAAAAAwAAAAAAAwkAAAAFAAAAGABAABcAAIAfAIAABQAAAAxAQACBgAAAHUCAAR8AgAADAAAAAAQSAAAAU2VuZFZhbHVlVG9TZXJ2ZXIABAcAAAB1bmxvYWQAAAAAAAEAAAABAQAAAAAAAAAAAAAAAAAAAAAEAAAABQAAAAAAAwkAAAAFAAAAGABAABcAAIAfAIAABQAAAAxAQACBgAAAHUCAAR8AgAADAAAAAAQSAAAAU2VuZFZhbHVlVG9TZXJ2ZXIABAkAAABidWdzcGxhdAAAAAAAAQAAAAEBAAAAAAAAAAAAAAAAAAAAAAUAAAAHAAAAAQAEDQAAAEYAwACAAAAAXYAAAUkAAABFAAAATEDAAMGAAABdQIABRsDAAKUAAADBAAEAXUCAAR8AgAAFAAAABA4AAABTY3JpcHRUcmFja2VyAAQSAAAAU2VuZFZhbHVlVG9TZXJ2ZXIABAUAAABsb2FkAAQMAAAARGVsYXlBY3Rpb24AAwAAAAAAQHpAAQAAAAYAAAAHAAAAAAADBQAAAAUAAAAMAEAAgUAAAB1AgAEfAIAAAgAAAAQSAAAAU2VuZFZhbHVlVG9TZXJ2ZXIABAgAAAB3b3JraW5nAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAEBAAAAAAAAAAAAAAAAAAAAAAAACAAAAA0AAAAAAAYyAAAABgBAAB2AgAAaQEAAF4AAgEGAAABfAAABF0AKgEYAQQBHQMEAgYABAMbAQQDHAMIBEEFCAN0AAAFdgAAACECAgUYAQQBHQMEAgYABAMbAQQDHAMIBEMFCAEbBQABPwcICDkEBAt0AAAFdgAAACEAAhUYAQQBHQMEAgYABAMbAQQDHAMIBBsFAAA9BQgIOAQEARoFCAE/BwgIOQQEC3QAAAV2AAAAIQACGRsBAAIFAAwDGgEIAAUEDAEYBQwBWQIEAXwAAAR8AgAAOAAAABA8AAABHZXRJbkdhbWVUaW1lcgADAAAAAAAAAAAECQAAADAwOjAwOjAwAAQGAAAAaG91cnMABAcAAABzdHJpbmcABAcAAABmb3JtYXQABAYAAAAlMDIuZgAEBQAAAG1hdGgABAYAAABmbG9vcgADAAAAAAAgrEAEBQAAAG1pbnMAAwAAAAAAAE5ABAUAAABzZWNzAAQCAAAAOgAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAA4AAAATAAAAAAAIKAAAAAEAAABGQEAAR4DAAIEAAAAhAAiABkFAAAzBQAKAAYABHYGAAVgAQQIXgAaAR0FBAhiAwQIXwAWAR8FBAhkAwAIXAAWARQGAAFtBAAAXQASARwFCAoZBQgCHAUIDGICBAheAAYBFAQABTIHCAsHBAgBdQYABQwGAAEkBgAAXQAGARQEAAUyBwgLBAQMAXUGAAUMBgABJAYAAIED3fx8AgAANAAAAAwAAAAAAAPA/BAsAAABvYmpNYW5hZ2VyAAQLAAAAbWF4T2JqZWN0cwAECgAAAGdldE9iamVjdAAABAUAAAB0eXBlAAQHAAAAb2JqX0hRAAQHAAAAaGVhbHRoAAQFAAAAdGVhbQAEBwAAAG15SGVybwAEEgAAAFNlbmRWYWx1ZVRvU2VydmVyAAQGAAAAbG9vc2UABAQAAAB3aW4AAAAAAAMAAAAAAAEAAQEAAAAAAAAAAAAAAAAAAAAAFAAAABQAAAACAAICAAAACkAAgB8AgAABAAAABAoAAABzY3JpcHRLZXkAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAAABUAAAACAAUKAAAAhgBAAMAAgACdgAABGEBAARfAAICFAIAAjIBAAQABgACdQIABHwCAAAMAAAAEBQAAAHR5cGUABAcAAABzdHJpbmcABAoAAABzZW5kRGF0YXMAAAAAAAIAAAAAAAEBAAAAAAAAAAAAAAAAAAAAABYAAAAlAAAAAgATPwAAAApAAICGgEAAnYCAAAqAgICGAEEAxkBBAAaBQQAHwUECQQECAB2BAAFGgUEAR8HBAoFBAgBdgQABhoFBAIfBQQPBgQIAnYEAAcaBQQDHwcEDAcICAN2BAAEGgkEAB8JBBEECAwAdggABFgECAt0AAAGdgAAACoCAgYaAQwCdgIAACoCAhgoAxIeGQEQAmwAAABdAAIAKgMSHFwAAgArAxIeGQEUAh4BFAQqAAIqFAIAAjMBFAQEBBgBBQQYAh4FGAMHBBgAAAoAAQQIHAIcCRQDBQgcAB0NAAEGDBwCHw0AAwcMHAAdEQwBBBAgAh8RDAFaBhAKdQAACHwCAACEAAAAEBwAAAGFjdGlvbgAECQAAAHVzZXJuYW1lAAQIAAAAR2V0VXNlcgAEBQAAAGh3aWQABA0AAABCYXNlNjRFbmNvZGUABAkAAAB0b3N0cmluZwAEAwAAAG9zAAQHAAAAZ2V0ZW52AAQVAAAAUFJPQ0VTU09SX0lERU5USUZJRVIABAkAAABVU0VSTkFNRQAEDQAAAENPTVBVVEVSTkFNRQAEEAAAAFBST0NFU1NPUl9MRVZFTAAEEwAAAFBST0NFU1NPUl9SRVZJU0lPTgAECwAAAGluZ2FtZVRpbWUABA0AAABCb2xUb29sc1RpbWUABAYAAABpc1ZpcAAEAQAAAAAECQAAAFZJUF9VU0VSAAMAAAAAAADwPwMAAAAAAAAAAAQJAAAAY2hhbXBpb24ABAcAAABteUhlcm8ABAkAAABjaGFyTmFtZQAECwAAAEdldFdlYlBhZ2UABA4AAABib2wtdG9vbHMuY29tAAQXAAAAL2FwaS9ldmVudHM/c2NyaXB0S2V5PQAECgAAAHNjcmlwdEtleQAECQAAACZhY3Rpb249AAQLAAAAJmNoYW1waW9uPQAEDgAAACZib2xVc2VybmFtZT0ABAcAAAAmaHdpZD0ABA0AAAAmaW5nYW1lVGltZT0ABAgAAAAmaXNWaXA9AAAAAAACAAAAAAABAQAAAAAAAAAAAAAAAAAAAAAmAAAAKgAAAAMACiEAAADGQEAAAYEAAN2AAAHHwMAB3YCAAArAAIDHAEAAzADBAUABgACBQQEA3UAAAscAQADMgMEBQcEBAIABAAHBAQIAAAKAAEFCAgBWQYIC3UCAAccAQADMgMIBQcECAIEBAwDdQAACxwBAAMyAwgFBQQMAgYEDAN1AAAIKAMSHCgDEiB8AgAASAAAABAcAAABTb2NrZXQABAgAAAByZXF1aXJlAAQHAAAAc29ja2V0AAQEAAAAdGNwAAQIAAAAY29ubmVjdAADAAAAAAAAVEAEBQAAAHNlbmQABAUAAABHRVQgAAQSAAAAIEhUVFAvMS4wDQpIb3N0OiAABAUAAAANCg0KAAQLAAAAc2V0dGltZW91dAADAAAAAAAAAAAEAgAAAGIAAwAAAPyD15dBBAIAAAB0AAQKAAAATGFzdFByaW50AAQBAAAAAAQFAAAARmlsZQAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAABAAAAAAAAAAAAAAAAAAAAAAA="), nil, "bt", _ENV))()
TrackerLoad("SYmmrH5U23buufxE")
-- BoL Tools Tracker --
function OnLoad()
Riven()
SendMsg("Thanks "..GetUser().." for using Shattered Blade")
Download()
end
function SendMsg(msg)
PrintChat("<font color=\"#06CD51\"><b>[Shattered Blade]</b></font><font color=\"#C2FDF3\"><b> "..msg..".</b></font>")
end
|
--[[
CREATE OR REPLACE SCRIPT LIST_ALL_ROLES() RETURNS TABLE AS
--]]
-- [impl->dsn~listing-all-roles~1]
exit(query("SELECT ROLE_NAME, ROLE_ID FROM ::s.EXA_ROLES_MAPPING",
{ s = exa.meta.script_schema }))
--[[
/
--]]
|
require "lxp"
local count = 0
callbacks = {
StartElement = function (parser, name)
io.write("+ ", string.rep(" ", count), name, "\n")
count = count + 1
end,
EndElement = function (parser, name)
count = count - 1
io.write("- ", string.rep(" ", count), name, "\n")
end
}
p = lxp.new(callbacks)
for l in io.lines() do -- iterate lines
p:parse(l) -- parses the line
p:parse("\n") -- parses the end of line
end
p:parse() -- finishes the document
p:close() -- closes the parser
|
local awful = require('awful')
local gears = require("gears")
local menubar = require("menubar")
require('awful.autofocus')
local beautiful = require('beautiful')
local hotkeys_popup = require('awful.hotkeys_popup').widget
local modkey = require('configuration.keys.mod').modKey
local altkey = require('configuration.keys.mod').altKey
local apps = require('configuration.apps')
-- {{{ Key bindings
globalKeys = gears.table.join(
-- awful.key({ "Control", }, "space", function() naughty.destroy_all_notifications() end,
-- {description = "destroy all notifications", group = "hotkeys"}),
awful.key({ modkey, }, "s", hotkeys_popup.show_help,
{description="show help", group="awesome"}),
awful.key({ modkey, }, "Left", awful.tag.viewprev,
{description = "view previous", group = "tag"}),
awful.key({ modkey, }, "Right", awful.tag.viewnext,
{description = "view next", group = "tag"}),
awful.key({ modkey, "Shift" }, "Left",
function ()
-- get current tag
local t = client.focus and client.focus.first_tag or nil
if t == nil then
return
end
-- get previous tag (modulo 9 excluding 0 to wrap from 1 to 9)
local tag = client.focus.screen.tags[(t.index - 2) % 9 + 1]
awful.client.movetotag(tag)
awful.tag.viewprev()
end,
{description = "move client to previous tag and switch to it", group = "tag"}),
awful.key({ modkey, "Shift" }, "Right",
function ()
-- get current tag
local t = client.focus and client.focus.first_tag or nil
if t == nil then
return
end
-- get next tag (modulo 9 excluding 0 to wrap from 9 to 1)
local tag = client.focus.screen.tags[(t.index % 9) + 1]
awful.client.movetotag(tag)
awful.tag.viewnext()
end,
{description = "move client to next tag and switch to it", group = "tag"}),
awful.key({ modkey, }, "Tab", awful.tag.history.restore,
{description = "go back", group = "tag"}),
awful.key({ modkey, }, "j",
function ()
awful.client.focus.byidx( 1)
end,
{description = "focus next by index", group = "client"}
),
awful.key({ modkey, }, "k",
function ()
awful.client.focus.byidx(-1)
end,
{description = "focus previous by index", group = "client"}
),
awful.key({ modkey, }, "w", function () mymainmenu:show() end,
{description = "show main menu", group = "awesome"}),
-- Layout manipulation
awful.key({ modkey, "Shift" }, "j", function () awful.client.swap.byidx( 1) end,
{description = "swap with next client by index", group = "client"}),
awful.key({ modkey, "Shift" }, "k", function () awful.client.swap.byidx( -1) end,
{description = "swap with previous client by index", group = "client"}),
awful.key({ modkey, "Control" }, "j", function () awful.screen.focus_relative( 1) end,
{description = "focus the next screen", group = "screen"}),
awful.key({ modkey, "Control" }, "k", function () awful.screen.focus_relative(-1) end,
{description = "focus the previous screen", group = "screen"}),
awful.key({ modkey, }, "u", awful.client.urgent.jumpto,
{description = "jump to urgent client", group = "client"}),
awful.key({ modkey, }, "Escape",
function ()
awful.client.focus.history.previous()
if client.focus then
client.focus:raise()
end
end,
{description = "go back", group = "client"}),
-- Standard program
awful.key({ modkey, "Shift" }, "Return", function () awful.spawn(apps.terminal) end,
{description = "open a terminal", group = "launcher"}),
awful.key({ modkey, "Control" }, "r", awesome.restart,
{description = "reload awesome", group = "awesome"}),
awful.key({ modkey, "Shift" }, "e", awesome.quit,
{description = "quit awesome", group = "awesome"}),
awful.key({ modkey, }, "l", function () awful.tag.incmwfact( 0.05) end,
{description = "increase master width factor", group = "layout"}),
awful.key({ modkey, }, "h", function () awful.tag.incmwfact(-0.05) end,
{description = "decrease master width factor", group = "layout"}),
awful.key({ modkey, "Shift" }, "h", function () awful.tag.incnmaster( 1, nil, true) end,
{description = "increase the number of master clients", group = "layout"}),
awful.key({ modkey, "Shift" }, "l", function () awful.tag.incnmaster(-1, nil, true) end,
{description = "decrease the number of master clients", group = "layout"}),
awful.key({ modkey, "Control" }, "h", function () awful.tag.incncol( 1, nil, true) end,
{description = "increase the number of columns", group = "layout"}),
awful.key({ modkey, "Control" }, "l", function () awful.tag.incncol(-1, nil, true) end,
{description = "decrease the number of columns", group = "layout"}),
awful.key({ modkey, }, "space", function () awful.layout.inc( 1) end,
{description = "select next", group = "layout"}),
awful.key({ modkey, "Shift" }, "space", function () awful.layout.inc(-1) end,
{description = "select previous", group = "layout"}),
awful.key({ modkey, "Control" }, "n",
function ()
local c = awful.client.restore()
-- Focus restored client
if c then
c:emit_signal(
"request::activate", "key.unminimize", {raise = true}
)
end
end,
{description = "restore minimized", group = "client"}),
-- volume
awful.key({ }, "XF86AudioMicMute",
function ()
os.execute(string.format("pactl set-source-mute @DEFAULT_SOURCE@ toggle"))--, beautiful.volume.channel))
--beautiful.volume.update()
end,
{description = "mute microphone", group = "hotkeys"}),
awful.key({ }, "XF86AudioRaiseVolume",
function ()
os.execute(string.format("pactl set-sink-volume @DEFAULT_SINK@ +1000"))--, beautiful.volume.channel))
--beautiful.volume.update()
end,
{description = "volume up", group = "hotkeys"}),
awful.key({ }, "XF86AudioLowerVolume",
function ()
os.execute(string.format("pactl set-sink-volume @DEFAULT_SINK@ -1000"))--, beautiful.volume.channel))
--beautiful.volume.update()
end,
{description = "volume down", group = "hotkeys"}),
awful.key({ }, "XF86AudioMute",
function ()
os.execute(string.format("pactl set-sink-mute @DEFAULT_SINK@ toggle"))--, beautiful.volume.togglechannel or beautiful.volume.channel))
--beautiful.volume.update()
end,
{description = "toggle mute", group = "hotkeys"}),
awful.key({ }, "Print",
function ()
os.execute(string.format("flameshot gui"))
end,
{description = "screenshot", group = "hotkeys"}),
awful.key({ }, "XF86ScreenSaver",
function ()
os.execute(string.format("xsecurelock"))
end,
{description = "screen saver", group = "hotkeys"}),
awful.key({ }, "XF86Display",
function ()
os.execute(string.format("arandr"))
end,
{description = "screen configuration with arandr", group = "hotkeys"}),
-- playerctl
awful.key({ }, "XF86AudioPlay",
function ()
os.execute(string.format("playerctl play-pause"))
end,
{description = "play/pause media player", group = "hotkeys"}),
awful.key({ }, "XF86AudioStop",
function ()
os.execute(string.format("playerctl stop"))
end,
{description = "stop media player", group = "hotkeys"}),
awful.key({ }, "XF86AudioNext",
function ()
os.execute(string.format("playerctl next"))
end,
{description = "next track media player", group = "hotkeys"}),
awful.key({ }, "XF86AudioPrev",
function ()
os.execute(string.format("playerctl previous"))
end,
{description = "previous track media player", group = "hotkeys"}),
-- dmenu
awful.key({ modkey }, "p",
function ()
os.execute(string.format("dmenu_run -i -b -fn 'Terminus' -nb '%s' -nf '%s' -sb '%s' -sf '%s'",
beautiful.bg_normal, beautiful.fg_normal, beautiful.bg_focus, beautiful.fg_focus))
end,
{description = "show dmenu", group = "launcher"}),
-- Prompt
awful.key({ modkey }, "r", function () awful.screen.focused().mypromptbox:run() end,
{description = "run prompt", group = "launcher"}),
awful.key({ modkey }, "x",
function ()
awful.prompt.run {
prompt = "Run Lua code: ",
textbox = awful.screen.focused().mypromptbox.widget,
exe_callback = awful.util.eval,
history_path = awful.util.get_cache_dir() .. "/history_eval"
}
end,
{description = "lua execute prompt", group = "awesome"}),
-- Menubar
awful.key({ modkey, "Shift" }, "p", function() menubar.show() end,
{description = "show the menubar", group = "launcher"})
)
-- Bind all key numbers to tags.
-- Be careful: we use keycodes to make it works on any keyboard layout.
-- This should map on the top row of your keyboard, usually 1 to 9.
for i = 1, 9 do
-- Hack to only show tags 1 and 9 in the shortcut window (mod+s)
local descr_view, descr_toggle, descr_move, descr_toggle_focus
if i == 1 or i == 9 then
descr_view = {description = 'view tag #', group = 'tag'}
descr_toggle = {description = 'toggle tag #', group = 'tag'}
descr_move = {description = 'move focused client to tag #', group = 'tag'}
descr_toggle_focus = {description = 'toggle focused client on tag #', group = 'tag'}
end
globalKeys =
awful.util.table.join(
globalKeys,
-- View tag only.
awful.key(
{modkey},
'#' .. i + 9,
function()
local screen = awful.screen.focused()
local tag = screen.tags[i]
if tag then
tag:view_only()
end
end,
descr_view
),
-- Toggle tag display.
awful.key(
{modkey, 'Control'},
'#' .. i + 9,
function()
local screen = awful.screen.focused()
local tag = screen.tags[i]
if tag then
awful.tag.viewtoggle(tag)
end
end,
descr_toggle
),
-- Move client to tag.
awful.key(
{modkey, 'Shift'},
'#' .. i + 9,
function()
if _G.client.focus then
local tag = _G.client.focus.screen.tags[i]
if tag then
_G.client.focus:move_to_tag(tag)
end
end
end,
descr_move
),
-- Toggle tag on focused client.
awful.key(
{modkey, 'Control', 'Shift'},
'#' .. i + 9,
function()
if _G.client.focus then
local tag = _G.client.focus.screen.tags[i]
if tag then
_G.client.focus:toggle_tag(tag)
end
end
end,
descr_toggle_focus
)
)
end
return globalKeys
|
local ROT = require((...):gsub(('.[^./\\]*'):rep(1) .. '$', ''))
local Path = ROT.Class:extend("Path")
function Path:init(toX, toY, passableCallback, options)
self._toX = toX
self._toY = toY
self._fromX = nil
self._fromY = nil
self._passableCallback = passableCallback
self._options = { topology = 8 }
if options then for k, _ in pairs(options) do self._options[k] = options[k] end end
self._dirs = self._options.topology == 8 and ROT.DIRS.EIGHT or ROT.DIRS.FOUR
if self._options.topology == 8 then
self._dirs = {self._dirs[1],
self._dirs[3],
self._dirs[5],
self._dirs[7],
self._dirs[2],
self._dirs[4],
self._dirs[6],
self._dirs[8] }
end
end
function Path:compute() end
function Path:_getNeighbors(cx, cy)
local result = {}
for i = 1, #self._dirs do
local dir = self._dirs[i]
local x = cx + dir[1]
local y = cy + dir[2]
if self._passableCallback(x, y) then
table.insert(result, {x, y})
end
end
return result
end
return Path
|
local ffi = require("ffi")
local errno = require("std_ffi.errno")
local ffi_new = ffi.new
local ffi_str = ffi.string
local C = ffi.C
local _M = {
O_RDONLY = tonumber('00000000', 8),
O_WRONLY = tonumber('00000001', 8),
O_RDWR = tonumber('00000002', 8),
O_CREAT = tonumber('00000100', 8),
O_EXCL = tonumber('00000200', 8),
O_TRUNC = tonumber('00001000', 8),
O_APPEND = tonumber('00002000', 8),
O_NONBLOCK = tonumber('00004000', 8),
O_DSYNC = tonumber('00010000', 8),
O_SYNC = tonumber('04010000', 8),
O_DIRECT = tonumber('00040000', 8),
O_DIRECTORY = tonumber('00200000', 8),
O_CLOEXEC = tonumber('02000000', 8),
S_IRWXU = tonumber('00700', 8),
S_IRUSR = tonumber('00400', 8),
S_IWUSR = tonumber('00200', 8),
S_IXUSR = tonumber('00100', 8),
S_IRWXG = tonumber('00070', 8),
S_IRGRP = tonumber('00040', 8),
S_IWGRP = tonumber('00020', 8),
S_IXGRP = tonumber('00010', 8),
S_IRWXO = tonumber('00007', 8),
S_IROTH = tonumber('00004', 8),
S_IWOTH = tonumber('00002', 8),
S_IXOTH = tonumber('00001', 8),
SEEK_SET = 0,
SEEK_CUR = 1,
SEEK_END = 2,
}
local mt = { __index = _M }
ffi.cdef[[
typedef int64_t off_t;
typedef struct { int fd; } fhandle_t;
]]
ffi.cdef[[
int open(const char *pathname, int flags, int mode);
int close(int fd);
off_t lseek(int fd, off_t offset, int whence);
int64_t write(int fildes, const void *buf, size_t nbyte);
int64_t pwrite(int fd, const void *buf, size_t count, off_t offset);
int fsync(int fd);
int fdatasync(int fd);
int64_t read(int fildes, void *buf, size_t nbyte);
int64_t pread(int fd, void *buf, size_t count, off_t offset);
int umask(int cmask);
char *strerror(int errnum);
int link(const char *oldpath, const char *newpath);
]]
local fhandle_t = ffi.metatype("fhandle_t", {})
local function _error()
local saved_errno = ffi.errno()
local err_str = ffi_str(C.strerror(saved_errno))
return nil, errno.err_msg[saved_errno], err_str
end
local function close_fhandle(fhandle)
if fhandle.fd == -1 then
return nil, nil, nil
end
local res = C.close(fhandle.fd)
if res < 0 then
return _error()
end
fhandle.fd = -1
return nil, nil, nil
end
function _M.open(_, fpath, flags, mode)
-- if O_CREAT is not specified, then mode is ignored.
mode = mode or tonumber('00660', 8)
C.umask(000)
local fd = C.open(fpath, flags, mode)
if fd < 0 then
return _error()
end
local f = {
fpath = fpath,
flags = flags,
mode = mode,
fhandle = ffi.gc(fhandle_t(fd), close_fhandle),
}
return setmetatable(f, mt), nil, nil
end
function _M.close(self)
return close_fhandle(self.fhandle)
end
function _M.write(self, data)
local written = C.write(self.fhandle.fd, data, #data)
local written = tonumber(written)
if written < 0 then
return _error()
end
return written, nil, nil
end
function _M.pwrite(self, data, offset)
local written = C.pwrite(self.fhandle.fd, data, #data, offset)
local written = tonumber(written)
if written < 0 then
return _error()
end
return written, nil, nil
end
function _M.fsync(self)
local res = C.fsync(self.fhandle.fd)
if res < 0 then
return _error()
end
return nil, nil, nil
end
function _M.fdatasync(self)
local res = C.fdatasync(self.fhandle.fd)
if res < 0 then
return _error()
end
return nil, nil, nil
end
function _M.read(self, size)
local buf = ffi_new("char[?]", size)
local read = C.read(self.fhandle.fd, buf, size)
local read = tonumber(read)
if read < 0 then
return _error()
end
return ffi_str(buf, read)
end
function _M.pread(self, size, offset)
local buf = ffi_new("char[?]", size)
local read = C.pread(self.fhandle.fd, buf, size, offset)
local read = tonumber(read)
if read < 0 then
return _error()
end
return ffi_str(buf, read)
end
function _M.seek(self, offset, whence)
local off = C.lseek(self.fhandle.fd, offset, whence)
local off = tonumber(off)
if off < 0 then
return _error()
end
return off, nil, nil
end
_M.MIN_RETRY_TIMES = 1
_M.MAX_RETRY_TIMES = 30
function _M.write_with_retry(self, data, retry_count)
retry_count = retry_count or 3
local to_write
local i = 0
local has_written = 0
local data_size = #data
if retry_count < _M.MIN_RETRY_TIMES then
retry_count = _M.MIN_RETRY_TIMES
elseif retry_count > _M.MAX_RETRY_TIMES then
retry_count = _M.MAX_RETRY_TIMES
end
while has_written < data_size do
if i >= retry_count then
return nil, 'TooManyWriteRetry', 'has retry write data ' .. i .. ' times'
end
if i == 0 then
-- avoid string copy
to_write = data
else
to_write = string.sub(data, has_written+1)
end
local written, err_code, err_msg = _M.write(self, to_write)
if err_code ~= nil then
return nil, err_code, err_msg
end
has_written = has_written + written
i = i + 1
end
return nil, nil, nil
end
function _M.link(_, oldpath, newpath)
local ret = C.link(oldpath, newpath)
if ret < 0 then
return _error()
end
return nil, nil, nil
end
return _M
|
function createToggle(bool, text)
end
function draw()
end
|
-- --------------------
-- TellMeWhen
-- Originally by Nephthys of Hyjal <lieandswell@yahoo.com>
-- Other contributions by:
-- Sweetmms of Blackrock, Oozebull of Twisting Nether, Oodyboo of Mug'thol,
-- Banjankri of Blackrock, Predeter of Proudmoore, Xenyr of Aszune
-- Currently maintained by
-- Cybeloras of Aerie Peak
-- --------------------
if not TMW then return end
local TMW = TMW
local L = TMW.L
local print = TMW.print
local next, pairs, error, rawget, next, wipe, tinsert, sort, strsplit, table, assert, loadstring, ipairs, tostring, assert
= next, pairs, error, rawget, next, wipe, tinsert, sort, strsplit, table, assert, loadstring, ipairs, tostring, assert
--- [[api/icon/api-documentation/|Icon]] is the class of all Icons.
--
-- Icon inherits explicitly from {{{Blizzard.Button}}} and from [[api/base-classes/generic-module-implementor/|GenericModuleImplementor]], and implicitly from the classes that it inherits.
--
-- Icon is the class of all TMW icons, which are the very heart of what TMW is and what it does. Icons provide the methods and functionality that Icon Types need to do their jobs. They also provide other API, like icon event handling, and they provide all the methods needed for setup and updating. Icons themselves do not create or provide any appearance, child frames, or layers - this is functionality that is given to Icon Modules.
--
-- @class file
-- @name Icon.lua
local bitband = bit.band
local function ClearScripts(f)
f:SetScript("OnEvent", nil)
f:SetScript("OnUpdate", nil)
end
local UPD_INTV
TMW:RegisterCallback("TMW_GLOBAL_UPDATE", function()
UPD_INTV = TMW.UPD_INTV
end)
local Icon = TMW:NewClass("Icon", "Button", "UpdateTableManager", "GenericModuleImplementor")
Icon:UpdateTable_Set(TMW.IconsToUpdate)
Icon.IsIcon = true
Icon.attributes = {}
Icon.runEvents = true
Icon.QueuedIcons = {}
Icon.NextUpdateTime = math.huge
local QueuedIcons = Icon.QueuedIcons
do
local tab
TMW.CNDT:RegisterConditionSetImplementingClass("Icon")
TMW.CNDT:RegisterConditionSet("Icon", {
parentSettingType = "icon",
parentDefaults = TMW.Icon_Defaults,
settingKey = "Conditions",
GetSettings = function(self)
if TMW.CI.ics then
return TMW.CI.ics.Conditions
end
end,
iterFunc = TMW.InIconSettings,
iterArgs = {
[1] = TMW,
},
GetTab = function(self)
return tab
end,
tabText = L["CONDITIONS"],
tabTooltip = L["ICONCONDITIONS_DESC"],
})
TMW:RegisterCallback("TMW_OPTIONS_LOADED", function()
tab = TMW.IE:RegisterTab("ICON", "CNDTICON", "Conditions", 5)
tab:SetText(L["CONDITIONS"])
tab:SetHistorySet(TMW.C.HistorySet:GetHistorySet("ICON"))
tab:HookScript("OnClick", function()
TMW.CNDT:LoadConfig("Icon")
end)
TMW.IconDragger:RegisterIconDragHandler(110, -- Copy Conditions
function(IconDragger, info)
local n = IconDragger.srcicon:GetSettings().Conditions.n
if IconDragger.desticon and n > 0 then
info.text = L["ICONMENU_COPYCONDITIONS"]:format(n)
info.tooltipTitle = info.text
info.tooltipText = L["ICONMENU_COPYCONDITIONS_DESC"]:format(
IconDragger.srcicon:GetIconName(true), n, IconDragger.desticon:GetIconName(true))
return true
end
end,
function(IconDragger)
-- copy the settings
local srcics = IconDragger.srcicon:GetSettings()
IconDragger.desticon:GetSettings().Conditions = TMW:CopyWithMetatable(srcics.Conditions)
end
)
end)
end
-- [INTERNAL]
function Icon.OnNewInstance(icon)
local group = icon:GetParent()
local iconID = icon:GetID()
icon.group = group
icon.ID = iconID
group[iconID] = icon
icon.EventHandlersSet = {}
icon.lmbButtonData = {}
icon.position = {}
icon.attributes = icon:InheritTable(Icon, "attributes")
end
-- [INTERNAL]
function Icon.__lt(icon1, icon2)
local g1 = icon1.group.ID
local g2 = icon2.group.ID
if g1 ~= g2 then
return g1 < g2
else
return icon1.ID < icon2.ID
end
end
-- [INTERNAL]
function Icon.__tostring(icon)
return icon:GetName()
end
function Icon.ScriptSort(iconA, iconB)
local gOrder = 1 -- -TMW.db.profile.CheckOrder
local gA = iconA.group.ID
local gB = iconB.group.ID
if gA == gB then
local iOrder = 1 -- -iconA.group.CheckOrder
return iconA.ID*iOrder < iconB.ID*iOrder
end
return gA*gOrder < gB*gOrder
end
Icon:UpdateTable_SetAutoSort(Icon.ScriptSort)
TMW:RegisterCallback("TMW_GLOBAL_UPDATE_POST", Icon, "UpdateTable_PerformAutoSort")
-- [WRAPPER] (no documentation needed)
Icon.SetScript_Blizz = Icon.SetScript
function Icon.SetScript(icon, handler, func)
icon[handler] = func
icon:SetScript_Blizz(handler, func)
end
-- [INTERNAL]
function Icon.CheckUpdateTableRegistration(icon)
if icon.UpdateFunction then
icon:UpdateTable_Register()
else
icon:UpdateTable_Unregister()
end
end
--- Sets the function that will be called when the icon needs to be updated.
--
-- Func will be called with signature (icon, time). Time is equal to TMW.time and GetTime().
-- @name Icon:SetUpdateFunction
-- @paramsig func
-- @param func [function|nil] The function that will be called when the icon needs to be updated. Nil to stop the icon from being updated. An error may be thrown if icon:Update() is called manually when the update function has been set nil.
-- @usage icon:SetUpdateFunction(MultiStateCD_OnUpdate)
function Icon.SetUpdateFunction(icon, func)
icon.UpdateFunction = func
if not icon.IsSettingUp then
icon:CheckUpdateTableRegistration()
end
end
-- [WRAPPER] (no documentation needed)
Icon.RegisterEvent_Blizz = Icon.RegisterEvent
function Icon.RegisterEvent(icon, event)
if not icon.registeredEvents then
icon.registeredEvents = {}
end
icon.registeredEvents[event] = true
icon:RegisterEvent_Blizz(event)
end
-- [WRAPPER] (no documentation needed)
Icon.UnregisterAllEvents_Blizz = Icon.UnregisterAllEvents
function Icon.UnregisterAllEvents(icon, event)
-- UnregisterAllEvents_Blizz uses a metric fuckton of CPU, so don't do it.
-- Instead, keep track of events that we register, and unregister them by hand.
if icon.registeredEvents then
for event in pairs(icon.registeredEvents) do
icon:UnregisterEvent(event)
end
wipe(icon.registeredEvents)
end
end
-- [SCRIPT HANDLER] (no documentation needed)
function Icon.OnShow(icon)
icon:SetInfo("shown", true)
icon.NextUpdateTime = 0
end
-- [SCRIPT HANDLER] (no documentation needed)
function Icon.OnHide(icon)
icon:SetInfo("shown", false)
icon.NextUpdateTime = 0
end
--- Returns the settings table that holds the settings for the icon. If the icon is controlled, will return the settings of its controller.
-- @name Icon:GetSettings
-- @paramsig
-- @return [{{{TMW.Icon_Defaults}}}] The settings table that holds the settings for the icon.
-- @usage local ics = icon:GetSettings()
-- print(icon:GetName() .. "'s enabled setting is set to " .. ics.Enabled)
function Icon.GetSettings(icon)
if icon:IsControlled() then
return icon.group.Controller:GetSettings()
else
return icon:GetRealSettings()
end
end
--- Returns the settings table that holds the settings for the icon, ignoring any overrides that result from the icon's group being a controlled group.
-- @name Icon:GetRealSettings
-- @paramsig
-- @return [{{{TMW.Icon_Defaults}}}] The settings table that holds the settings for the icon.
function Icon.GetRealSettings(icon)
return icon.group:GetSettings().Icons[icon:GetID()]
end
--- Gets the GUID of the icon. This may be a session-temporary GUID or a permanant GUID.
-- @name Icon:GetGUID
-- @paramsig generate
-- @param generate [boolean|nil] True if a permanant GUID should be generated and stored
-- with the icon's settings if there isn't already a permanant GUID for the icon.
-- A permanant GUID should always be generated when creating a reference to an icon that
-- needs to persist between sessions.
-- @return [String] The GUID of the icon.
-- @usage local GUID = icon:GetGUID()
function Icon.GetGUID(icon, generate)
local GUID = icon:GetRealSettings().GUID
if GUID == "" then
GUID = nil
end
if not GUID then
if not icon.TempGUID then
icon.TempGUID = TMW:GenerateGUID("icon", TMW.CONST.GUID_SIZE)
GUID = icon.TempGUID
end
if generate then
GUID = icon.TempGUID
icon.TempGUID = nil
icon:GetRealSettings().GUID = GUID
icon.GUID = GUID
icon:Setup()
else
return icon.TempGUID
end
else
-- Nil this out for icons that are imported that have a GUID.
-- There will be a tempGUID already for the icon, but it won't match
-- the imported GUID.
icon.TempGUID = nil
end
return GUID
end
--- Returns the settings table that holds the view-specific settings for the icon.
-- @name Icon:GetSettingsPerView
-- @paramsig view
-- @param [string|nil] The identifier of the [[api/icon-views/api-documentation/|IconView]] to get settings for, or nil to use the icon's current view.
-- @return [{{{TMW.Icon_Defaults.SettingsPerView[view]}}}] The settings table that holds the view-specific settings for the icon.
-- @usage local icspv = icon:GetSettingsPerView()
--
-- local icspv = icon:GetSettingsPerView("bar")
function Icon.GetSettingsPerView(icon, view)
view = view or icon.group:GetSettings().View
return icon:GetSettings().SettingsPerView[view]
end
--- Determines if the icon is currently being edited in the Icon Editor.
-- @name Icon:IsBeingEdited
-- @paramsig
-- @return [string|nil] If the icon is being edited, returns the identifier string of the currently active Icon Editor tab. Returns nil if the icon is not being edited in the Icon Editor.
function Icon.IsBeingEdited(icon)
if TMW.IE and TMW.CI.icon == icon and TMW.IE.CurrentTab and TMW.IE:IsVisible() then
return TMW.IE.CurrentTab.identifier
end
end
--- Returns a string that contains the texture of the icon plus the name of the group and the ID of the icon.
-- @name Icon:GetIconName
-- @paramsig texture
-- @param texture [boolean] True if the texture should be prepended to the output, otherwise false or nil.
-- @return [string] The string containing the texture of the icon plus the name of the group and the ID of the icon.
function Icon.GetIconName(icon, texture)
local name = L["GROUPICON"]:format(icon.group:GetGroupName(1), icon.ID)
if icon.group.Domain == "global" then
name = L["DOMAIN_GLOBAL"] .. " " .. name
end
if texture and icon.attributes.texture and icon.attributes.texture ~= nil then
return ("|T%s:0|t %s"):format(icon.attributes.texture, name)
else
return name
end
end
--- Alias for icon:GetIconName(1). Exists so that groups and icons both have a obj:GetFullName() method.
-- @name Icon:GetFullName
-- @paramsig
-- @return [string] The string containing the texture of the icon plus the name of the group and the ID of the icon.
function Icon.GetFullName(icon)
return icon:GetIconName(1)
end
--- Returns information about the icon that should be included when listing it in a dropdown menu. Wrapper around TMW:GetIconMenuText() with the groupID and iconID added to the tooltip.
-- @name Icon:GetIconMenuText
-- @paramsig
-- @return [string] The string that should be used as the tooltip title for the menu item.
-- @return [string] The string that should be used as the text for the menu item. This is a tuncation of the first return.
-- @return [string] The string that should be used as the tooltip text for the menu item.
function Icon.GetIconMenuText(icon)
local text, textshort, tooltip = TMW:GetIconMenuText(icon:GetSettings())
tooltip = icon:GetIconName() .. "\r\n" .. tooltip
return text, textshort, tooltip
end
--- Queues an icon event to be fired.
--
-- The event must have been registed through [[api/base-classes/icon-component/|IconComponent]]{{{:RegisterIconEvent()}}}.
-- @name Icon:QueueEvent
-- @paramsig eventInfo
-- @param eventInfo [string|table] Either a string that identifies the event (as registered with [[api/base-classes/icon-component/|IconComponent]]{{{:RegisterIconEvent()}}}) that will be fired (all events of that type will be attempted to be fire), or a table of event settings that is in {{{icon:GetSettings().Events}}} (only that specific event and its settings will be fired). The event will not actually be fired until {{{icon:ProcessQueuedEvents()}}} is called.
-- @usage -- From IconDataProcessor_Alpha_Real: (An example of calling by passing an event identifier)
-- if icon.EventHandlersSet.OnHide then
-- icon:QueueEvent("OnHide")
-- end
--
--
-- -- From IconModule_IconEventConditionHandler: (An example of calling by passing in an eventSettings table)
-- local function TMW_CNDT_OBJ_PASSING_CHANGED(event, ConditionObject, failed)
-- if not failed then
-- local matches = MapConditionObjectToEventSettings[ConditionObject]
-- -- MapConditionObjectToEventSettings maps TMW.CLasses.ConditionObject instances to the eventSettings they were created for.
-- -- matches is a table that contains {[eventSettings] = icon} pairs. These tables were setup in the module's :OnEnable() method.
-- -- See IconModule_IconEventConditionHandler's code for complete implementation.
-- if matches then
-- for eventSettings, icon in pairs(matches) do
-- icon:QueueEvent(eventSettings.__proxyRef)
-- icon:ProcessQueuedEvents()
-- end
-- end
-- end
-- end
function Icon.QueueEvent(icon, eventInfo)
-- Events that get queued will be processed when icon:ProcessQueuedEvents() is called.
-- This can be done manually if an event needs to be processed immediately in an OnEvent handler,
-- but it will be done automatically for all icons during TMW_ONUPDATE_TIMECONSTRAINED_POST (in EventHandler.lua)
icon.EventsToFire[eventInfo] = true
icon.eventIsQueued = true
QueuedIcons[#QueuedIcons + 1] = icon
end
-- [INTERNAL] (no documentation needed)
function Icon.RestoreEvents(icon)
icon.runEvents = true
icon.runEventsTimerHandler = nil
if icon.EventHandlersSet.OnEventsRestored and TMW.Locked then
icon:QueueEvent("OnEventsRestored")
icon:ProcessQueuedEvents()
end
end
local EventSettingsWasPassingConditionMap = {}
--- Triggers processing of all icon events that have been queued through {{{icon:QueueEvent()}}}.
--
-- Icon events will only be fired if their conditions pass (if they have any) and if limitations like the "Continue to lower events" user setting don't prevent more than one event from being fired.
-- Events are fired in the order that they are configured by the user, not in the order that they are queued.
--
-- This method is automatically called at the end of a TMW update cycle for all icons that have queued an event,
-- so it should only be called after an event is queued outside of normal icon updating (like in an OnEvent handler or in a script handler).
--
-- Search TellMeWhen's source for calls of this method and of {{{icon:QueueEvent()}}} for examples of proper usage.
-- @name Icon:ProcessQueuedEvents
-- @paramsig
function Icon.ProcessQueuedEvents(icon)
local EventsToFire = icon.EventsToFire
if EventsToFire and icon.eventIsQueued then
local handledOne
for i = 1, (icon.Events.n or 0) do
-- settings to check for in EventsToFire
local EventSettingsFromIconSettings = icon.Events[i]
local event = EventSettingsFromIconSettings.Event
local EventSettings
if EventsToFire[EventSettingsFromIconSettings] or EventsToFire[event] then
-- we should process EventSettingsFromIconSettings
EventSettings = EventSettingsFromIconSettings
end
local eventData = TMW.EventList[event]
if eventData and EventSettings then
local shouldProcess = true
if EventSettings.OnlyShown and icon.attributes.realAlpha <= 0 then
shouldProcess = false
elseif EventSettings.PassingCndt then
local conditionChecker = eventData.conditionChecker
local conditionResult = true
if conditionChecker then
conditionResult = conditionChecker(icon, EventSettings)
if EventSettings.CndtJustPassed then
local uniqueKey = tostring(icon) .. tostring(EventSettings)
if conditionResult ~= EventSettingsWasPassingConditionMap[uniqueKey] then
EventSettingsWasPassingConditionMap[uniqueKey] = conditionResult
else
conditionResult = false
end
end
end
shouldProcess = conditionResult
end
if shouldProcess and icon.runEvents and icon.attributes.shown then
local EventHandler = TMW.EVENTS:GetEventHandler(EventSettings.Type)
if EventHandler then
local handled = EventHandler:HandleEvent(icon, EventSettings)
if handled then
if not EventSettings.PassThrough then
break
end
handledOne = true
end
end
end
end
end
wipe(EventsToFire)
icon.eventIsQueued = nil
if handledOne then
TMW:Fire("TMW_ICON_UPDATED", icon)
end
end
end
--- Checks if the icon is within the maximum number of icons that will be shown by its parent group.
-- @name Icon:IsInRange
-- @paramsig
-- @return [boolean] True if the icon's ID is within the maximum number of icons allowed by its parent group, otherwise false.
function Icon.IsInRange(icon)
return icon:GetID() <= icon.group.Rows*icon.group.Columns
end
--- Wrapper around [[api/icon-type/api-documentation/|IconType]]{{{:OnGCD(icon, duration)}}}.
-- @name Icon:OnGCD
-- @paramsig duration
-- @param duration [number] The duration to check. This should be the total duration of the cooldown (e.g. the second return from GetSpellCooldown()), not the remaining duration.
-- @return [boolean] True if the duration passed in is a global cooldown, otherwise false.
function Icon.OnGCD(icon, duration)
return icon.typeData:OnGCD(icon, duration)
end
--- Checks if the icon is a valid icon for being in things like the list of icons that can be checked in metas/conditions.
-- @name Icon:IsValid
-- @paramsig
-- @return [boolean] True if the icon is valid, otherwise false.
function Icon.IsValid(icon)
-- checks if the icon should be in the list of icons that can be checked in metas/conditions
return icon.Enabled and icon:IsInRange() and icon.group:IsValid()
end
Icon.Update_Method = "auto"
--- Sets the update method that will be used by the icon.
--
-- Setting to "auto" causes the icon to be updated every single update cycle (within the limits of the Update Interval user setting). "auto" is the default value.
--
-- Setting to "manual" causes the icon to be updated only when {{{icon.NextUpdateTime < TMW.time}}}, or when {{{icon:Update(true)}}} is called (this should not be done outside of special circumstances. Manual updating should be restricted to using only icon.NextUpdateTime).
-- @name Icon:SetUpdateMethod
-- @paramsig method
-- @param method [string] A string the indicates the update method that will be used for the icon. Must be either "auto" or "manual".
-- @usage icon:SetUpdateMethod("manual")
function Icon.SetUpdateMethod(icon, method)
icon.Update_Method = method
if method == "auto" then
-- do nothing for now.
elseif method == "manual" then
icon.NextUpdateTime = 0
else
error("Unknown update method " .. method)
end
end
-- [INTERNAL] (no documentation needed)
function Icon.ScheduleNextUpdate(icon)
local time = TMW.time
local duration
if icon:IsGroupController() then
duration = math.huge
for icon in icon.group:InIcons() do
local attributes = icon.attributes
if not attributes.shown then
break
end
local d = attributes.duration - (time - attributes.start)
if d > 0 and d < duration then
duration = d
end
end
if duration == math.huge then
duration = 0
end
else
local attributes = icon.attributes
duration = attributes.duration - (time - attributes.start)
if duration < 0 then duration = 0 end
end
if duration == 0 then
icon.NextUpdateTime = math.huge
else
icon.NextUpdateTime = time + duration
end
end
local IconEventUpdateEngine = CreateFrame("Frame")
TMW.IconEventUpdateEngine = IconEventUpdateEngine
IconEventUpdateEngine.UpdateEvents = setmetatable({}, {__index = function(self, event)
self[event] = {}
return self[event]
end})
IconEventUpdateEngine:SetScript("OnEvent", function(self, event, arg1)
for icon, arg1ToMatch in next, self.UpdateEvents[event] do
if icon.NextUpdateTime ~= 0 and (arg1ToMatch == true or arg1ToMatch == arg1) then
icon.NextUpdateTime = 0
end
end
end)
--- Registers a Blizzard event that will, upon being fired, trigger the icon to schedule a manual update for the next TMW update cycle.
-- @name Icon:RegisterSimpleUpdateEvent
-- @paramsig event, arg1
-- @param event [string] A Blizzard event.
-- @param arg1 [//any//] An optional arg that must match the first arg of the Blizzard event for the icon update to be triggered. Nil to cause the icon to be updated for any firings of the event, regardless of its first arg. Any event handling that requires checking more than just the first arg should be done manually by the [[api/icon-type/api-documentation/|IconType]] that needs it (use {{{icon:RegisterEvent(event)}}} and {{{icon:SetScript("OnEvent", func)}}} where func is a function that will parse the event args and sets {{{icon.NextUpdateTime}}} to the value of TMW.time at which the icon should be update next, or 0 if an immediate update should happen.
-- @usage icon:RegisterSimpleUpdateEvent("SPELL_UPDATE_COOLDOWN")
-- icon:RegisterSimpleUpdateEvent("UNIT_POWER_FREQUENT", "player")
function Icon.RegisterSimpleUpdateEvent(icon, event, arg1)
if arg1 == nil then
arg1 = true
end
local iconsForEvent = IconEventUpdateEngine.UpdateEvents[event]
local existing = iconsForEvent[icon]
if existing and existing ~= arg1 then
error("Can't change the arg that you are checking for an event without unregistering first", 2)
end
iconsForEvent[icon] = arg1
IconEventUpdateEngine:RegisterEvent(event)
end
--- Unregisters a simple update event that has been registed for the icon with Icon:RegisterSimpleUpdateEvent().
-- @name Icon:UnregisterSimpleUpdateEvent
-- @paramsig event
-- @param event [string] A Blizzard event that should be unregisted from the SimpleUpdateEvent system as was previously registered through {{{icon:RegisterSimpleUpdateEvent()}}}.
function Icon.UnregisterSimpleUpdateEvent(icon, event)
local iconsForEvent = rawget(IconEventUpdateEngine.UpdateEvents, event)
if iconsForEvent then
iconsForEvent[icon] = nil
if not next(iconsForEvent) then
IconEventUpdateEngine:UnregisterEvent(event)
end
end
end
--- Unregisters all simple update events that have been registed for the icon with Icon:RegisterSimpleUpdateEvent().
--
-- This is done automatically every time an icon is setup, and should not be called manually outside of exceptional circumstances.
-- @name Icon:UnregisterAllSimpleUpdateEvents
-- @paramsig
function Icon.UnregisterAllSimpleUpdateEvents(icon)
for event, iconsForEvent in pairs(IconEventUpdateEngine.UpdateEvents) do
iconsForEvent[icon] = nil
if not next(iconsForEvent) then
IconEventUpdateEngine:UnregisterEvent(event)
end
end
end
--- Attempts to update an icon.
--
-- This should normally only be called at the end of a [[api/icon-type/api-documentation/|IconType]]{{{:Setup()}}} method (unless your IconTypes's proper functionality requires that you not do so).
-- You may also call it anywhere else as you deem appropriate, but in most normal situations, there is no need to do so.
--
-- It is automatically called for every valid icon that has an update function defined (through {{{icon:SetUpdateFunction()}}}) each update cycle in the TMW icon update engine.
--
-- It is limited to the updating only as often as the Update Interval user-setting allows (maximum of once per frame/per OnUpdate script call) (unless the force param is used).
-- It updates the icon's conditions as needed and then calls the icon's update function to trigger the chain of updating from icon type -> icon data processor (and hooks) -> icon modules & icon events.
-- @name Icon:Update
-- @paramsig force
-- @param force [boolean|nil] True to force an immediate update of the icon, disregarding both the Update Interval user-setting (and the related once-per-frame constraint) and the value of {{{icon.NextUpdateTime}}}.
-- This should only be used in exceptional circumstances, like when the source of an icon's attributes and its {{{icon:SetInfo}}} calls are from an event (see the Combat Log icon type for an example of this).
function Icon.Update(icon, force)
local time = TMW.time
if icon.attributes.shown and icon.UpdateFunction and (force or icon.LastUpdate <= time - UPD_INTV) then
icon.LastUpdate = time
local Update_Method = icon.Update_Method
local ConditionObject = icon.ConditionObject
if ConditionObject and (ConditionObject.UpdateNeeded or ConditionObject.NextUpdateTime < time) then
-- The condition check needs to come before we determine iconUpdateNeeded because
-- checking a condition may set NextUpdateTime to 0 if the condition passing state changes.
ConditionObject:Check()
end
local iconUpdateNeeded = force or Update_Method == "auto" or icon.NextUpdateTime < time
if iconUpdateNeeded then
icon.__yieldHandledOnce = false
if not icon:IsGroupController() then
icon:UpdateFunction(time)
else
icon.__controlledIconIndex = 0
icon:UpdateFunction(time)
if TMW.Locked then
for i = icon.__controlledIconIndex+1, icon.group.numIcons do
local ic = icon.group[i]
if ic and ic.attributes.realAlpha > 0 then
-- This allows for correct handling of states & opacities in all cases.
ic:SetInfo("alphaOverride", 0)
-- The following won't work for this:
-- ic:SetInfo("state", 0), because it breaks meta icon controller groups (meta icon state overrides local state).
-- ic:Hide(), because it breaks OnShow/OnHide animations on controlled icons.
end
end
end
end
if Update_Method == "manual" then
icon:ScheduleNextUpdate()
end
end
end
end
--- Yields info harvested from an icon's UpdateFunction. This info will be passed to the icon type's Type:HandeInfo(icon, iconToSet, ...) method if appropriate.
-- More specifically, the info passed to icon:YieldInfo() will be passed on to Type:HandeInfo if either the icon is not a group controller (i.e. it is a normal icon), or if there are mor icons in the group that may be filled with the attributes harvested by the icon type. A call to icon:YieldInfo(false, ...) will only pass its parameters to Type:HandeInfo() if no calls to icon:YieldInfo(true, ...) have been made during this run of the icon's UpdateFunction. Behavior is unpredictable if there are no call to icon:YieldInfo() before an UpdateFunction returns. Therefore, an UpdateFunction should always conclude with a call to icon:YieldInfo(false, ...)
-- @name Icon:YieldInfo
-- @paramsig isNotDone, ...
-- @param isNotDone [boolean] true if there might be more calls to Icon:YieldInfo(true, ...) before the UpdateFunction is finished. false if this call is the last one before the UpdateFunction returns.
-- @param ... [vararg] The parameters to be passed to the call to Type:HandeInfo(icon, iconToSet, ...) if it is appropriate to do so. This can be empty if isNotDone is false. It should never be empty if isNotDone is true.
function Icon.YieldInfo(icon, isNotDone, ...)
if not isNotDone and icon.__yieldHandledOnce then
return nil
end
icon.__yieldHandledOnce = true
if not icon:IsGroupController() then
icon.typeData:HandleYieldedInfo(icon, icon, ...)
return nil
else
local nextIconIndex = (icon.__controlledIconIndex or 0) + 1
if nextIconIndex > icon.group.numIcons then
return nil
end
icon.__controlledIconIndex = nextIconIndex
local destIcon = icon.group[nextIconIndex]
if not destIcon then
return
end
destIcon:SetInfo("alphaOverride", nil)
icon.typeData:HandleYieldedInfo(icon, destIcon, ...)
if not isNotDone or not TMW.Locked then
return nil
end
return true
end
end
--- Returns whether or not an icon is controlling an entire group.
-- @name Icon:IsGroupController
-- @paramsig
-- @return isController [boolean] True if this icon is controlling its group, otherwise false.
function Icon.IsGroupController(icon)
return icon.group.Controller ~= nil and icon.group.Controller == icon
end
--- Returns whether or not an icon is controlled by the first icon in its group.
-- @name Icon:IsControlled
-- @paramsig
-- @return isController [boolean] True if this icon is controlled by its group's first icon, otherwise false.
function Icon.IsControlled(icon)
return icon.group.Controller ~= nil and icon.group.Controller ~= icon
end
-- [EVENT HANDLER] (no documentation needed)
function Icon.TMW_CNDT_OBJ_PASSING_CHANGED(icon, event, ConditionObject, failed)
-- failed is boolean, never nil. nil is used for the conditionFailed attribute if there are no conditions on the icon.
if icon.ConditionObject == ConditionObject then
icon.NextUpdateTime = 0
icon:SetInfo("conditionFailed", failed)
end
end
--- Completely disables and resets an icon to a near-default state.
--
-- Unimplements all [[api/base-classes/icon-component/|IconComponent]]s, resets update function and method, unregisters all events, and hides the icon.
-- @name Icon:DisableIcon
-- @paramsig soft
-- @param soft [boolean] True if the icon might not be getting permanantly disabled (in which case this method just serves as a reset)
function Icon.DisableIcon(icon, soft)
icon:UnregisterAllEvents()
icon:UnregisterAllSimpleUpdateEvents()
ClearScripts(icon)
icon:SetUpdateMethod("auto")
icon:SetUpdateFunction(nil)
icon:Hide()
if not soft then
local iconGUID = icon:GetGUID()
if iconGUID then
TMW:DeclareDataOwner(iconGUID, nil)
end
end
TMW:Fire("TMW_ICON_DISABLE", icon, soft)
-- Reset condition stuff
if icon.ConditionObject then
icon.ConditionObject:DeclareExternalUpdater(icon, false)
icon.ConditionObject = nil
end
TMW:UnregisterCallback("TMW_CNDT_OBJ_PASSING_CHANGED", icon)
icon:SetInfo("conditionFailed", nil)
icon:DisableAllModules()
if icon.typeData then
icon.typeData:UnimplementFromIcon(icon)
end
if icon.viewData then
icon.viewData:UnimplementFromIcon(icon)
end
end
--- Completely sets up an icon.
--
-- Implements all requested [[api/base-classes/icon-component/|IconComponent]]s, processes settings, sets up conditions, calls [[api/icon-type/api-documentation/|IconType]]{{{:Setup()}}}, and prepares the icon to be updated or configured.
--
-- This method should not be called manually while TellMeWhen is locked. It may be called liberally from wherever you see fit when in configuration mode.
-- @name Icon:Setup
-- @paramsig
function Icon.Setup(icon)
if not icon or not icon[0] then return end
local group = icon.group
local ics = icon:GetSettings()
local typeData = TMW.Types[ics.Type]
local viewData = group.viewData
local iconGUID = icon:GetGUID()
if not typeData then
error("TellMeWhen: Critical error: Couldn't find type data or fallback type data for " ..
ics.Type .. " (Where is the default icon type? Things broke badly!)")
end
-- Check if the group should update its icons in case
-- an update was called specifically for this icon.
if not group:ShouldUpdateIcons() then
return
end
-- Determine if this icon is a group controller, and setup the entire group if it is.
if icon.ID == 1 then
local newController
if group:GetSettings().Controlled and typeData.canControlGroup then
newController = icon
else
group:GetSettings().Controlled = false
newController = nil
end
-- Only perform a group setup if the group's controller has changed.
-- If we didn't check for this, we would stack overflow by repeatedly doing this.
if newController ~= group.Controller then
group.Controller = newController
group:Setup() -- Don't tail call here, because if something goes wrong then we WANT to stack overflow.
return
end
end
-- Set this so that we can prevent update table registration checks from happening
-- until the end of this method (its a slightly intensive process that adds up if done a ton of times)
-- This is also used externally (in some IconModules, for eg) to prevent other thigns from happening
-- during setup. Listen for TMW_ICON_SETUP_POST to find when this gets set to nil.
icon.IsSettingUp = true
-- Perform a soft reset on the icon.
icon:DisableIcon(true)
-- Store all of the icon's relevant settings on the icon,
-- and nil out any settings that aren't relevant.
-- TODO: (really big TODO) get rid of this behavior.
for k in pairs(TMW.Icon_Defaults) do
if typeData.RelevantSettings[k] then
icon[k] = ics[k]
else
icon[k] = nil
end
end
-- Store these on the icon for convenience
icon.typeData = typeData
icon.viewData = viewData
if icon.Enabled or not TMW.Locked then
icon:Show()
-- Associate the icon's GUID with the icon in a global context
-- so that it can be referred to by GUID.
TMW:DeclareDataOwner(iconGUID, icon)
-- Lame framelevel fix: Sometimes, icons end up with dramatically different frame levels than their group.
icon:SetFrameLevel(group:GetFrameLevel() + 1)
-- Notify that we've begun setting up this icon (we're past all the basic stuff now,
-- and at the point where other parties might be interested in doing anything before we go further)
TMW:Fire("TMW_ICON_SETUP_PRE", icon)
------------ Icon View ------------
viewData:Icon_Setup(icon)
viewData:ImplementIntoIcon(icon)
viewData:Icon_Setup_Post(icon)
------------ Icon Type ------------
typeData:ImplementIntoIcon(icon)
-- Only perform a setup for icons that aren't controlled.
-- Controlled icons shouldn't be setup because they aren't autonomous.
if not icon:IsControlled() then
icon.LastUpdate = 0
icon.NextUpdateTime = 0
TMW.safecall(typeData.Setup, typeData, icon)
end
------------ Conditions ------------
-- Don't setup conditions to untyped icons.
if icon.typeData.type ~= "" then
-- Create our condition object for the icon.
local ConditionObjectConstructor = icon:Conditions_GetConstructor(icon.Conditions)
icon.ConditionObject = ConditionObjectConstructor:Construct()
if icon.ConditionObject then
-- If this icon has valid conditions, listen for updates to them.
icon.ConditionObject:DeclareExternalUpdater(icon, true)
TMW:RegisterCallback("TMW_CNDT_OBJ_PASSING_CHANGED", icon)
icon:SetInfo("conditionFailed", icon.ConditionObject.Failed)
end
end
else
local iconGUID = icon:GetGUID()
if iconGUID then
TMW:DeclareDataOwner(iconGUID, nil)
end
icon:Hide()
-- Disable icons that aren't enabled when we're locked.
--icon:DisableIcon()
end
-- Queue another immediate update.
icon.NextUpdateTime = 0
if TMW.Locked then
-- Clear out configuration mode properties from the icon.
icon:SetInfo("alphaOverride", nil)
if icon.attributes.texture == "Interface\\AddOns\\TellMeWhen\\Textures\\Disabled" then
icon:SetInfo("texture", "")
end
icon:EnableMouse(false)
else
-- Put the icon in a configurable state.
icon:Show()
ClearScripts(icon)
icon:SetUpdateFunction(nil)
icon:SetInfo(
"alphaOverride; start, duration; stack, stackText",
icon.Enabled and 1 or 0.5,
0, 0,
nil, nil
)
if icon.attributes.texture == "" then
icon:SetInfo("texture", "Interface\\AddOns\\TellMeWhen\\Textures\\Disabled")
end
icon:EnableMouse(true)
end
if icon:IsControlled() then
if TMW.Locked then
-- Inherit the controller's attributes icon the controlled icon
-- in order to copy things like timer sweep reverse
-- (which is set statically in the IconType's Setup method, and IconType:Setup() isn't performed for controller icons)
icon:InheritDataFromIcon(icon.group.Controller)
else
-- In config mode, give controller icons the special texture,
-- and make them slightly transparent for the hell of it.
icon:SetInfo("texture; alphaOverride",
"Interface\\AddOns\\TellMeWhen\\Textures\\Controlled",
icon.Enabled and 0.95 or 0.5
)
end
end
-- Now that we're done setting up, we can call this manually
-- (icon.IsSettingUp == true prevents it from being called to save on CPU usage)
icon:CheckUpdateTableRegistration()
icon.IsSettingUp = nil
-- Let everyone know that we're done setting up this icon.
TMW:Fire("TMW_ICON_SETUP_POST", icon)
end
-- [INTERNAL] (no documentation needed)
function Icon.SetupAllModulesForIcon(icon, sourceIcon)
for moduleName, Module in pairs(icon.Modules) do
if Module.SetupForIcon and Module.IsEnabled and not Module.dontInherit then
TMW.safecall(Module.SetupForIcon, Module, sourceIcon)
end
end
end
-- [INTERNAL] (no documentation needed)
function Icon.SetModulesToEnabledStateOfIcon(icon, sourceIcon)
local sourceModules = sourceIcon.Modules
for moduleName, Module in pairs(icon.Modules) do
if Module.IsImplemented and not Module.dontInherit then
local sourceModule = sourceModules[moduleName]
if sourceModule then
if sourceModule.IsEnabled then
Module:Enable(true)
else
Module:Disable()
end
else
Module:Disable()
end
end
end
end
-- If you want me to explain wtf this is, send me (Cybeloras) a PM on CurseForge.
TMW.IconStateArbitrator = {
StateHandlers = {},
UPDATE = function(self, event, icon)
local attributes = icon.attributes
local StateHandlers = self.StateHandlers
local handlerToUse
for i = 1, #StateHandlers do
local handler = StateHandlers[i]
local stateData = attributes[handler.attribute]
if stateData and stateData.Alpha == 0 then
-- If an alpha is set to 0, then the icon should be hidden no matter what,
-- so use it as the final alpha value and stop looking for more.
-- This functionality has existed in TMW since practically day one, by the way. So don't be clever and remove it.
handlerToUse = handler
break
elseif stateData ~= nil then
if not handlerToUse then
-- If we found a state that isn't nil and we haven't figured out
-- a state to use yet, use this one, but keep looking for 0 values.
handlerToUse = handler
end
if handler.haltImmediatelyIfFound then
break
end
end
end
if handlerToUse then
-- calculatedState stores the state that the icon should be showing, before FakeHidden.
-- realAlpha does the same for the alpha. We use it on top of calculatedState in favor of backwards compatibility.
local state = attributes[handlerToUse.attribute]
if not state.Alpha then
-- Attempting to catch an elusive bug. Remove this if it doesn't seem to be happening anymore.
-- One case I've seen is doing an undo/redo while TMW is locked.
-- The underlying data on the setting table that gets passed as a state gets nilled out,
-- so there may be no value.
-- This happens when undoing to a blank icon from a non-blank icon, for example.
print("NO ALPHA ON STATE:", handlerToUse.attribute, icon, icon:GetName(), state.Alpha, state)
end
icon:SetInfo_INTERNAL("realAlpha", state.Alpha or 0)
icon:SetInfo_INTERNAL("calculatedState", state)
end
end,
GetConfigData = function(handler, icon, panelInfo)
if not handler.configGetter then
return nil
end
local configData = handler.configGetter(icon, panelInfo)
if not configData then
return nil
end
local icon = TMW.CI.icon
local dependant = handler.dependant
if dependant and not dependant:ShouldShowConfigPanels(icon) then
return nil
end
return configData
end,
-- PUBLIC METHOD (ish)
AddHandler = function(self, IconDataProcessor, order, dependant, haltImmediatelyIfFound, configGetter)
TMW:ValidateType(1, "IconStateArbitrator:AddHandler()", IconDataProcessor, "IconDataProcessor")
TMW:ValidateType(2, "IconStateArbitrator:AddHandler()", order, "number")
TMW:ValidateType(3, "IconStateArbitrator:AddHandler()", dependant, "IconDataProcessorComponent;nil")
TMW:ValidateType(4, "IconStateArbitrator:AddHandler()", haltImmediatelyIfFound, "boolean;nil")
TMW:ValidateType(5, "IconStateArbitrator:AddHandler()", configGetter, "function;nil")
if IconDataProcessor.NumAttributes ~= 1 then
error("IconStateArbitrator handlers cannot check IconDataProcessors that have more than one attribute!")
end
local handler = {
order = order,
processor = IconDataProcessor,
attribute = IconDataProcessor.attributesStringNoSpaces,
dependant = dependant,
haltImmediatelyIfFound = haltImmediatelyIfFound,
configGetter = configGetter,
GetConfigData = self.GetConfigData,
}
tinsert(self.StateHandlers, handler)
sort(self.StateHandlers, TMW.OrderSort)
TMW:RegisterCallback(IconDataProcessor.changedEvent, self, "UPDATE")
end,
}
-- [INTERNAL] (no documentation needed)
local InheritAllFunc
function Icon.InheritDataFromIcon(iconDestination, iconSource)
if not InheritAllFunc then
local attributes = {}
local attributesSplit = {}
for _, Processor in pairs(TMW.Classes.IconDataProcessor.instances) do
if not Processor.dontInherit then
attributes[#attributes+1] = Processor.attributesStringNoSpaces
for _, attribute in TMW:Vararg(strsplit(",", Processor.attributesStringNoSpaces)) do
attributesSplit[#attributesSplit+1] = attribute
end
end
end
local t = {}
t[#t+1] = "local iconDestination, iconSource = ..."
t[#t+1] = "\n"
t[#t+1] = "local attributes = iconSource.attributes"
t[#t+1] = "\n"
t[#t+1] = "iconDestination:SetInfo('"
t[#t+1] = table.concat(attributes, "; ")
t[#t+1] = "', "
t[#t+1] = "attributes."
t[#t+1] = table.concat(attributesSplit, ", attributes.")
t[#t+1] = ")"
local funcstr = table.concat(t)
InheritAllFunc = assert(loadstring(funcstr))
end
InheritAllFunc(iconDestination, iconSource)
end
local function SetInfo_GenerateFunction(signature, isInternal)
local originalSignature = signature
signature = signature:gsub(" ", "")
local t = {} -- taking a page from DogTag's book on compiling functions
-- Declare all upvalues
for UVSetID, UVSet in ipairs(TMW.Classes.IconDataProcessor.SIUVs) do
t[#t+1] = "local "
t[#t+1] = UVSet.variables
t[#t+1] = " = "
for referenceID, reference in ipairs(UVSet) do
t[#t+1] = "TMW.Classes.IconDataProcessor.SIUVs["
t[#t+1] = UVSetID
t[#t+1] = "]["
t[#t+1] = referenceID
t[#t+1] = "]"
t[#t+1] = ", "
end
t[#t] = nil -- remove the final ", " (if there were any references) or the " = " (if there weren't)
t[#t+1] = "\n"
end
t[#t+1] = "\n"
t[#t+1] = "\n"
t[#t+1] = "return function(icon, "
t[#t+1] = originalSignature:trim(" ,;"):gsub(" ", " "):gsub(";", ",")
t[#t+1] = ")"
t[#t+1] = "\n\n"
t[#t+1] = [[
local attributes, EventHandlersSet = icon.attributes, icon.EventHandlersSet
local doFireIconUpdated
]]
while #signature > 0 do
local match
for _, Processor in ipairs(TMW.Classes.IconDataProcessor.instances) do
match = signature:match("^(" .. Processor.attributesStringNoSpaces .. ")$") -- The attribute string is the only one in the signature
or signature:match("^(" .. Processor.attributesStringNoSpaces .. ";)") -- The attribute string is the first one in the signature
or signature:match("(;" .. Processor.attributesStringNoSpaces .. ")$") -- The attribute string is the last one in the signature
or signature:match(";(" .. Processor.attributesStringNoSpaces .. ";)") -- The attribute string is in the middle of the signature
if match then
t[#t+1] = "local Processor = "
t[#t+1] = Processor.name
t[#t+1] = "\n"
-- Process any hooks that should go before the main function segment
Processor:CompileFunctionHooks(t, "pre")
Processor:CompileFunctionSegment(t)
-- Process any hooks that should go after the main function segment
Processor:CompileFunctionHooks(t, "post")
t[#t+1] = "\n\n"
signature = signature:gsub(match, "", 1)
break
end
end
if not match then
error(("Couldn't find a signature match for the beginning of signature %q from %q"):format(signature, originalSignature), 4)
end
end
if isInternal then
t[#t+1] = [[
return doFireIconUpdated
end -- "return function(icon, ...)"
]]
else
t[#t+1] = [[
if doFireIconUpdated then
TMW:Fire("TMW_ICON_UPDATED", icon)
end
end -- "return function(icon, ...)"
]]
end
local funcstr = table.concat(t)
if TMW.debug then
funcstr = TMW.debug.enumLines(funcstr)
TMW.debug.SetInfoFuncsToFuncStrs[tostring(isInternal) .. originalSignature] = funcstr
end
local func = assert(loadstring(funcstr, "SetInfo " .. originalSignature))()
return func
end
local SetInfoFuncs = setmetatable({}, { __index = function(self, signature)
-- Check and see if we already made a function for this signature, just with different spacing.
local signature_no_spaces = signature:gsub(" ", "")
if rawget(self, signature_no_spaces) then
local func = self[signature_no_spaces]
-- If there was a function, cache it for the original signature also so that we don't go through this lookup process every time.
self[signature] = func
return func
end
local func = SetInfo_GenerateFunction(signature, nil)
self[signature] = func
self[signature:gsub(" ", "")] = func
return func
end})
--- Sets attributes of an icon.
--
-- The attributes passed to this function will be processed by a [[api/icon-data-processor/api-documentation/|IconDataProcessor]] (and possibly one or more [[api/icon-data-processor-hook/api-documentation/|IconDataProcessorHook]]) and interested [[api/icon-module/api-documentation/|IconModule]]s will be notified of any changes to the attributes.
-- @name Icon:SetInfo
-- @paramsig signature, ...
-- @param signature [string] A semicolon-delimited string of attribute strings as passed to the constructor of a [[api/icon-data-processor/api-documentation/|IconDataProcessor]].
-- @param ... [...] Any number of params that will match up one-for-one with the signature passed in.
-- @usage icon:SetInfo("texture", "Interface\\AddOns\\TellMeWhen\\Textures\\Disabled")
--
-- -- From IconTypes/IconType_wpnenchant:
-- icon:SetInfo("state; start, duration; spell",
-- STATE_ABSENT,
-- 0, 0,
-- nil
-- )
--
-- -- From IconTypes/IconType_reactive:
-- icon:SetInfo("state; texture; start, duration; charges, maxCharges, chargeStart, chargeDur; stack, stackText; spell",
-- STATE_USABLE,
-- GetSpellTexture(iName),
-- start, duration,
-- charges, maxCharges, chargeStart, chargeDur
-- stack, stack,
-- iName
-- )
function Icon.SetInfo(icon, signature, ...)
SetInfoFuncs[signature](icon, ...)
end
local SetInfoInternalFuncs = setmetatable({}, { __index = function(self, signature)
-- Check and see if we already made a function for this signature, just with different spacing.
local signature_no_spaces = signature:gsub(" ", "")
if rawget(self, signature_no_spaces) then
local func = self[signature_no_spaces]
-- If there was a function, cache it for the original signature also so that we don't go through this lookup process every time.
self[signature] = func
return func
end
local func = SetInfo_GenerateFunction(signature, true)
self[signature] = func
self[signature:gsub(" ", "")] = func
return func
end})
--- icon:SetInfo_INTERNAL() is a slightly modified version of icon:SetInfo() that doesn't fire TMW_ICON_UPDATED at the end.
-- It must only be called from within SetInfo (inside IconDataProcessorHooks).
-- SetInfo will fire TMW_ICON_UPDATED at the end (and only once, isntead of multiple times), so SetInfo_INTERNAL won't fire it at all to prevent excessive firings.
--
-- When in doubt, don't use this method - use a regular icon:SetInfo() call instead.
-- @name Icon:SetInfo_INTERNAL
-- @paramsig signature, ...
-- @see Icon:SetInfo()
-- @returns [boolean] If true, and if SetInfo_INTERNAL is being called from within the body of an [[api/icon-data-processor-hook/api-documentation/|IconDataProcessorHook]], {{{doFireIconUpdated}}} (local variable within the {{{icon:SetInfo()}}} method) should be set to true.
-- @usage -- An example from Components/Core/IconDataProcessors/IconDataProcessor_Unit_DogTag/Unit_DogTag.lua:
-- Hook:RegisterCompileFunctionSegmentHook("post", function(Processor, t)
-- t[#t+1] = [[
-- local dogTagUnit
--
-- if icon.typeData.unitType == "unitid" then
-- dogTagUnit = unit
-- if not DogTag.IsLegitimateUnit[dogTagUnit] then
-- dogTagUnit = dogTagUnit and TMW_UNITS:TestUnit(dogTagUnit)
-- if not DogTag.IsLegitimateUnit[dogTagUnit] then
-- dogTagUnit = "player"
-- end
-- end
-- else
-- dogTagUnit = "player"
-- end
--
-- if attributes.dogTagUnit ~= dogTagUnit then
-- doFireIconUpdated = icon:SetInfo_INTERNAL("dogTagUnit", dogTagUnit) or doFireIconUpdated
-- end
-- --]]
-- end)
function Icon.SetInfo_INTERNAL(icon, signature, ...)
SetInfoInternalFuncs[signature](icon, ...)
end
-- [INTERNAL] (no documentation needed)
function Icon:ClearSetInfoFunctionCache()
self:AssertSelfIsClass()
wipe(SetInfoFuncs)
wipe(SetInfoInternalFuncs)
InheritAllFunc = nil
end
|
#!/usr/bin/env luajit
-- ./cycsub_r.lua FILE
local afile = ...
local dat = io.open(afile, "rb"):read("*a")
local key = "\x3c\x7c\x33\x5e\x0a\x71\x0d\x5b"
local function cycsub_dec(buffer, key)
local j = #buffer
local out = ""
local checksum = 0
local keyIndex = 0
while j >= 1 do
local roundKey = bit.band(checksum + key:byte(keyIndex + 1), 0xFF)
local bt = buffer:byte(j)
bt = bit.band(bt - roundKey, 0xFF)
out = string.char(bt) .. out
checksum = bit.band(checksum + bt, 0xFF)
keyIndex = (keyIndex + 1) % #key
j = j - 1
end
return out
end
for i = 0, #dat - 1 do
print("----")
print(i)
print("----")
print(cycsub_dec(dat:sub(1, #dat - i), key))
end
io.flush()
|
-- file created: 2010-03-16
local F = far.Flags
local dialog = require "far2.dialog"
local Cfg, M = ...
local Guid1 = win.Uuid("05d16094-0735-426c-a421-62dae2db6b1a")
local function ExecuteDialog (aData, aMsgTitle)
local D = dialog.NewDialog()
local offset = 5 + math.max(M.mBtnHighTextColor:len(), M.mBtnSelHighTextColor:len()) + 10
D._ = {"DI_DOUBLEBOX", 3, 1,62,12, 0, 0, 0, 0, aMsgTitle}
D.lab = {"DI_TEXT", 5, 2, 0, 0, 0, 0, 0, 0, M.mMaxHistorySizes}
D.lab = {"DI_TEXT", 6, 3, 0, 0, 0, 0, 0, 0, M.mSizeCmd}
D.iSizeCmd = {"DI_FIXEDIT", 20, 3,24, 0, 0, 0, 0, 0, ""}
D.lab = {"DI_TEXT", 6, 4, 0, 0, 0, 0, 0, 0, M.mSizeView}
D.iSizeView = {"DI_FIXEDIT", 20, 4,24, 0, 0, 0, 0, 0, ""}
D.lab = {"DI_TEXT", 6, 5, 0, 0, 0, 0, 0, 0, M.mSizeFold}
D.iSizeFold = {"DI_FIXEDIT", 20, 5,24, 0, 0, 0, 0, 0, ""}
D.lab = {"DI_TEXT", 34,2, 0, 0, 0, 0, 0, 0, M.mWinProperties}
D.bDynResize = {"DI_CHECKBOX", 35,3, 0, 0, 0, 0, 0, 0, M.mDynResize}
D.bAutoCenter = {"DI_CHECKBOX", 35,4, 0, 0, 0, 0, 0, 0, M.mAutoCenter}
D.sep = {"DI_TEXT", -1, 7, 0, 0, 0, 0, 0, {DIF_BOXCOLOR=1,DIF_SEPARATOR=1,DIF_CENTERTEXT=1}, M.mSepColors}
D.btnHighTextColor = {"DI_BUTTON", 5, 8, 0, 0, 0, 0, 0, "DIF_BTNNOCLOSE", M.mBtnHighTextColor}
D.labHighTextColor = {"DI_TEXT", offset, 8, 0, 0, 0, 0, 0, 0, M.mTextSample}
D.btnSelHighTextColor = {"DI_BUTTON", 5, 9, 0, 0, 0, 0, 0, "DIF_BTNNOCLOSE", M.mBtnSelHighTextColor}
D.labSelHighTextColor = {"DI_TEXT", offset, 9, 0, 0, 0, 0, 0, 0, M.mTextSample}
D.sep = {"DI_TEXT", 0,10, 0, 0, 0, 0, 0, {DIF_BOXCOLOR=1,DIF_SEPARATOR=1}, ""}
D.btnOk = {"DI_BUTTON", 0,11, 0, 0, 0, 0, 0, {DIF_CENTERGROUP=1, DIF_DEFAULTBUTTON=1}, M.mOk}
D.btnCancel = {"DI_BUTTON", 0,11, 0, 0, 0, 0, 0, "DIF_CENTERGROUP", M.mCancel}
------------------------------------------------------------------------------
dialog.LoadData(D, aData)
local hColor0 = aData.HighTextColor or 0x3A
local hColor1 = aData.SelHighTextColor or 0x0A
local function DlgProc (hDlg, msg, param1, param2)
if msg == F.DN_BTNCLICK then
if param1 == D.btnHighTextColor.id then
local c = far.ColorDialog(hColor0)
if c then hColor0 = c; hDlg:send(F.DM_REDRAW); end
elseif param1 == D.btnSelHighTextColor.id then
local c = far.ColorDialog(hColor1)
if c then hColor1 = c; hDlg:send(F.DM_REDRAW); end
end
elseif msg == F.DN_CTLCOLORDLGITEM then
if param1 == D.labHighTextColor.id then param2[1] = hColor0; return param2; end
if param1 == D.labSelHighTextColor.id then param2[1] = hColor1; return param2; end
end
end
local ret = far.Dialog (Guid1,-1,-1,66,14,"PluginConfig",D,nil,DlgProc)
if ret == D.btnOk.id then
dialog.SaveData(D, aData)
aData.iSizeCmd = tonumber(D.iSizeCmd.Data)
aData.iSizeView = tonumber(D.iSizeView.Data)
aData.iSizeFold = tonumber(D.iSizeFold.Data)
aData.HighTextColor = hColor0
aData.SelHighTextColor = hColor1
return true
end
end
return ExecuteDialog(Cfg, M.mPluginTitle .. ": " .. M.mSettings)
|
_=loadfile and loadfile("TQAE.lua"){
refreshStates=true,
debug = { onAction=true, http=false, UIEevent=true },
--offline = true,
copas = true,
--readOnly=true,
}
--%%name="API Verifier"
--%%type="com.fibaro.binarySwitch"
local fmt = string.format
local EM = hc3_emulator.EM
local function callAPI(host,path,args) -- GET/icons...
local method,call = path:match("(.-)(/.*)")
local base = fmt("http://%s/api",host)
return EM.HC3Request(method,call,args,{base=base})
end
if EM.cfg.offline then EM.create.globalVariable{name="A",value=""} end
local GETcalls = {
"GET/devices",
"GET/devices/1",
"GET/globalVariables",
"GET/globalVariables/A", -- 200
"GET/globalVariables/XYZ", --404
"GET/energy/devices",
"GET/alarms/v1/devices",
"GET/alarms/v1/partitions",
"GET/customEvents",
"GET/panels/location",
"GET/settings/location",
"GET/settings/info",
"GET/debugMessages",
"GET/home",
"GET/icons",
"GET/iosDevices",
"GET/notificationCenter",
"GET/profiles",
"GET/profiles/1",
"GET/refreshStates",
"GET/rooms",
"GET/rooms/219",
"GET/scenes",
"GET/scenes/10",
"GET/sections",
"GET/sections/219",
"GET/users",
"GET/users/2",
"GET/weather",
}
function QuickApp:onInit()
self:debug(self.name, self.id)
local hc3 = "192.168.1.57"
-- local host1 = "192.168.1.183:8976"
local host1 = EM.IPAddress..":8976"
self:debug("Collecting API responses from HC3...")
local ref = {} -- Collect ref responses from HC3
for _,call in ipairs(GETcalls) do
local res,code,h = callAPI(hc3,call)
ref[#ref+1]={res=res,code=code,header=h}
end
self:debug("Running verification with TQAE (intentional errors will log...)")
for i,call in ipairs(GETcalls) do
local res,code,h = callAPI(host1,call)
if code==ref[i].code then
self:trace(fmt("OK - %s (%s)",call,code))
if type(res)~=type(ref[i].res) then
self:warning(fmt("Result mismatch %s (%s/%s)",call,type(res),type(ref[i].res)))
end
else
self:warning(fmt("%s/%s - %s",code,ref[i].code,call))
end
end
end
|
QBCore.Functions.CreateUseableItem("fitbit", function(source, item)
local Player = QBCore.Functions.GetPlayer(source)
TriggerClientEvent('qb-fitbit:use', source)
end)
RegisterServerEvent('qb-fitbit:server:setValue')
AddEventHandler('qb-fitbit:server:setValue', function(type, value)
local src = source
local ply = QBCore.Functions.GetPlayer(src)
local fitbitData = {}
if type == "thirst" then
local currentMeta = ply.PlayerData.metadata["fitbit"]
fitbitData = {
thirst = value,
food = currentMeta.food
}
elseif type == "food" then
local currentMeta = ply.PlayerData.metadata["fitbit"]
fitbitData = {
thirst = currentMeta.thirst,
food = value
}
end
ply.Functions.SetMetaData('fitbit', fitbitData)
end)
QBCore.Functions.CreateCallback('qb-fitbit:server:HasFitbit', function(source, cb)
local Ply = QBCore.Functions.GetPlayer(source)
local Fitbit = Ply.Functions.GetItemByName("fitbit")
if Fitbit ~= nil then
cb(true)
else
cb(false)
end
end)
|
local ffi = require('ffi')
local header = [[
typedef unsigned int mx_uint;
typedef float mx_float;
typedef void *PredictorHandle;
typedef void *NDListHandle;
const char* MXGetLastError();
int MXPredCreate(const char* symbol_json_str,
const void* param_bytes,
int param_size,
int dev_type, int dev_id,
mx_uint num_input_nodes,
const char** input_keys,
const mx_uint* input_shape_indptr,
const mx_uint* input_shape_data,
PredictorHandle* out);
int MXPredCreatePartialOut(const char* symbol_json_str,
const void* param_bytes,
int param_size,
int dev_type, int dev_id,
mx_uint num_input_nodes,
const char** input_keys,
const mx_uint* input_shape_indptr,
const mx_uint* input_shape_data,
mx_uint num_output_nodes,
const char** output_keys,
PredictorHandle* out);
int MXPredCreateMultiThread(const char* symbol_json_str,
const void* param_bytes,
int param_size,
int dev_type, int dev_id,
mx_uint num_input_nodes,
const char** input_keys,
const mx_uint* input_shape_indptr,
const mx_uint* input_shape_data,
int num_threads,
PredictorHandle* out);
int MXPredReshape(mx_uint num_input_nodes,
const char** input_keys,
const mx_uint* input_shape_indptr,
const mx_uint* input_shape_data,
PredictorHandle handle,
PredictorHandle* out);
int MXPredGetOutputShape(PredictorHandle handle,
mx_uint index,
mx_uint** shape_data,
mx_uint* shape_ndim);
int MXPredSetInput(PredictorHandle handle,
const char* key,
const mx_float* data,
mx_uint size);
int MXPredForward(PredictorHandle handle);
int MXPredPartialForward(PredictorHandle handle, int step, int* step_left);
int MXPredGetOutput(PredictorHandle handle,
mx_uint index,
mx_float* data,
mx_uint size);
int MXPredFree(PredictorHandle handle);
int MXNDListCreate(const char* nd_file_bytes,
int nd_file_size,
NDListHandle *out,
mx_uint* out_length);
int MXNDListGet(NDListHandle handle,
mx_uint index,
const char** out_key,
const mx_float** out_data,
const mx_uint** out_shape,
mx_uint* out_ndim);
int MXNDListFree(NDListHandle handle);
]]
ffi.cdef(header)
print('start load libmxnet')
local lib
if ffi.os == 'Windows' then
lib = ffi.load('libmxnet.dll')
else
lib = ffi.load('libmxnet.so')
end
print('finish load libmxnet')
return lib
|
local S = farming.intllib
--[[
-- place cocoa
local function place_cocoa(itemstack, placer, pointed_thing, plantname)
local pt = pointed_thing
-- check if pointing at a node
if not pt or pt.type ~= "node" then
return
end
local under = minetest.get_node(pt.under)
-- return if any of the nodes are not registered
if not minetest.registered_nodes[under.name] then
return
end
-- am I right-clicking on something that has a custom on_place set?
-- thanks to Krock for helping with this issue :)
local def = minetest.registered_nodes[under.name]
if placer and itemstack and def and def.on_rightclick then
return def.on_rightclick(pt.under, under, placer, itemstack, pt)
end
-- check if pointing at jungletree
if under.name ~= "hades_trees:jungletree"
or minetest.get_node(pt.above).name ~= "air" then
return
end
-- is player planting crop?
local name = placer and placer:get_player_name() or ""
-- check for protection
if minetest.is_protected(pt.above, name) then
return
end
-- add the node and remove 1 item from the itemstack
minetest.set_node(pt.above, {name = plantname})
minetest.sound_play("default_place_node", {pos = pt.above, gain = 1.0})
if placer and not farming.is_creative(placer:get_player_name()) then
itemstack:take_item()
-- check for refill
if itemstack:get_count() == 0 then
minetest.after(0.20,
farming.refill_plant,
placer,
"hades_extrafarming:cocoa_beans",
placer:get_wield_index()
)
end
end
return itemstack
end
-- cocoa seed
minetest.register_node("hades_extrafarming:seed_cocoa", {
description = S("Cocoa Seed"),
tiles = {"farming_cocoa_seed.png"},
inventory_image = "farming_cocoa_seed.png",
wield_image = "farming_cocoa_seed.png",
drawtype = "signlike",
groups = {seed = 1, snappy = 3, attached_node = 1, flammable = 2},
paramtype = "light",
paramtype2 = "wallmounted",
walkable = false,
sunlight_propagates = true,
selection_box = farming.select,
on_place = function(itemstack, placer, pointed_thing)
return place_cocoa(itemstack, placer, pointed_thing, "hades_extrafarming:cocoa_1")
end,
})
minetest.register_craft({
type = "shapeless",
output = "hades_extrafarming:seed_cocoa",
recipe = {"group:food_cocoa"}
})
-- cocoa beans
minetest.register_craftitem("hades_extrafarming:cocoa_beans", {
description = S("Cocoa Beans"),
inventory_image = "farming_cocoa_beans.png",
groups = {food_cocoa = 1, flammable = 2},
})
minetest.register_craft( {
output = "dye:brown 2",
recipe = {{"hades_extrafarming:cocoa_beans"}}
})
--]]
-- chocolate cookie
minetest.register_craftitem("hades_extrafarming:cookie", {
description = S("Cookie"),
inventory_image = "farming_cookie.png",
groups = {food = 2, eatable = 2},
on_use = minetest.item_eat(2)
})
minetest.register_craft( {
output = "hades_extrafarming:cookie 8",
recipe = {
{"group:food_wheat", "group:food_cocoa", "group:food_wheat" }
}
})
-- bar of dark chocolate (thanks to Ice Pandora for her deviantart.com chocolate tutorial)
minetest.register_craftitem("hades_extrafarming:chocolate_dark", {
description = S("Bar of Dark Chocolate"),
inventory_image = "farming_chocolate_dark.png",
groups = {food = 2, eatable = 3},
on_use = minetest.item_eat(3)
})
minetest.register_craft( {
output = "hades_extrafarming:chocolate_dark",
recipe = {
{"group:food_cocoa", "group:food_cocoa", "group:food_cocoa"}
}
})
-- chocolate block
minetest.register_node("hades_extrafarming:chocolate_block", {
description = S("Chocolate Block"),
tiles = {"farming_chocolate_block.png"},
is_ground_content = false,
groups = {cracky = 2, oddly_breakable_by_hand = 2},
sounds = hades_sounds.node_sound_stone_defaults()
})
minetest.register_craft({
output = "hades_extrafarming:chocolate_block",
recipe = {
{"hades_extrafarming:chocolate_dark", "hades_extrafarming:chocolate_dark", "hades_extrafarming:chocolate_dark"},
{"hades_extrafarming:chocolate_dark", "hades_extrafarming:chocolate_dark", "hades_extrafarming:chocolate_dark"},
{"hades_extrafarming:chocolate_dark", "hades_extrafarming:chocolate_dark", "hades_extrafarming:chocolate_dark"}
}
})
minetest.register_craft({
output = "hades_extrafarming:chocolate_dark 9",
recipe = {{"hades_extrafarming:chocolate_block"}}
})
--[[
-- cocoa definition
local def = {
drawtype = "plantlike",
tiles = {"farming_cocoa_1.png"},
paramtype = "light",
walkable = false,
selection_box = {
type = "fixed",
fixed = {-0.3, -0.5, -0.3, 0.3, 0.5, 0.3}
},
drop = {},
groups = {
snappy = 3, flammable = 2, plant = 1, growing = 1,
not_in_creative_inventory = 1, leafdecay = 1, leafdecay_drop = 1
},
sounds = hades_sounds.node_sound_leaves_defaults(),
growth_check = function(pos, node_name)
if minetest.find_node_near(pos, 1, {"hades_trees:jungletree"}) then
return false -- can grow
end
return true -- cannot grow
end
}
-- stage 1
minetest.register_node("hades_extrafarming:cocoa_1", table.copy(def))
-- stage 2
def.tiles = {"farming_cocoa_2.png"}
minetest.register_node("hades_extrafarming:cocoa_2", table.copy(def))
-- stage3
def.tiles = {"farming_cocoa_3.png"}
def.drop = {
items = {
{items = {"hades_extrafarming:cocoa_beans 1"}, rarity = 1}
}
}
minetest.register_node("hades_extrafarming:cocoa_3", table.copy(def))
-- stage 4 (final)
def.tiles = {"farming_cocoa_4.png"}
def.groups.growing = nil
def.growth_check = nil
def.drop = {
items = {
{items = {"hades_extrafarming:cocoa_beans 2"}, rarity = 1},
{items = {"hades_extrafarming:cocoa_beans 1"}, rarity = 2},
{items = {"hades_extrafarming:cocoa_beans 1"}, rarity = 4}
}
}
minetest.register_node("hades_extrafarming:cocoa_4", table.copy(def))
-- add to registered_plants
farming.registered_plants["hades_extrafarming:cocoa_beans"] = {
crop = "hades_extrafarming:cocoa",
seed = "hades_extrafarming:seed_cocoa",
minlight = farming.min_light,
maxlight = farming.max_light,
steps = 4
}
-- add random cocoa pods to jungle tree's
minetest.register_on_generated(function(minp, maxp)
if maxp.y < 0 then
return
end
local pos, dir
local cocoa = minetest.find_nodes_in_area(minp, maxp, "default:jungletree")
for n = 1, #cocoa do
pos = cocoa[n]
if minetest.find_node_near(pos, 1,
{"default:jungleleaves", "moretrees:jungletree_leaves_green"}) then
dir = math.random(1, 80)
if dir == 1 then pos.x = pos.x + 1
elseif dir == 2 then pos.x = pos.x - 1
elseif dir == 3 then pos.z = pos.z + 1
elseif dir == 4 then pos.z = pos.z -1
end
if dir < 5
and minetest.get_node(pos).name == "air"
and minetest.get_node_light(pos) > 12 then
--print ("Cocoa Pod added at " .. minetest.pos_to_string(pos))
minetest.swap_node(pos, {
name = "hades_extrafarming:cocoa_" .. tostring(math.random(4))
})
end
end
end
end)
--]]
|
--
-- A manifest of all the game's assets
--
manifest =
{
scripts =
{
['main.lua'] =
{
path = "code/main.lua"
},
['BitmapText.lua'] =
{
path = "code/ui/BitmapText.lua"
},
['PrintTable.lua'] =
{
path = "code/PrintTable.lua"
},
['Panel.lua'] =
{
path = "code/ui/Panel.lua"
},
['Tween.lua'] =
{
path = "code/Tween.lua"
},
['Util.lua'] =
{
path = "code/Util.lua"
},
['DefaultFontDef.lua'] =
{
path = "code/font/DefaultFontDef.lua"
},
['Dependencies.lua'] =
{
path = "code/Dependencies.lua"
},
['Tween.lua'] =
{
path = "code/Tween.lua"
},
['ModalButton.lua'] =
{
path = "code/ui/ModalButton.lua"
},
['LabelValue.lua'] =
{
path = "code/ui/LabelValue.lua"
},
['TrackBar.lua'] =
{
path = "code/ui/TrackBar.lua"
},
['Textbox.lua'] =
{
path = "code/Textbox.lua"
},
-- Let's include the stuff for parsing the conversations
['HigherOrder.lua'] =
{
path = "parse/HigherOrder.lua"
},
['ParseCore.lua'] =
{
path = "parse/ParseCore.lua"
},
['TextboxClip.lua'] =
{
path = "code/TextboxClip.lua"
},
['Rect.lua'] =
{
path = "code/ui/Rect.lua"
},
['TypedText.lua'] =
{
path = "code/ui/TypedText.lua"
},
['TypedSequence.lua'] =
{
path = "code/ui/TypedSequence.lua"
},
-- This movr M of a MVC but here it is in the UI folder
['PlayController.lua'] =
{
path = "code/ui/PlayController.lua"
},
['TextControlStack.lua'] =
{
path = "code/ui/TextControlStack.lua"
},
['TagColor.lua'] =
{
path = "code/discourse/tag/TagColor.lua"
},
['TagPause.lua'] =
{
path = "code/discourse/tag/TagPause.lua"
},
['TagSpeed.lua'] =
{
path = "code/discourse/tag/TagSpeed.lua"
},
['TagScript.lua'] =
{
path = "code/discourse/tag/TagScript.lua"
},
['TagDB.lua'] =
{
path = "code/TagDB.lua"
},
['DiscourseEventManager.lua'] =
{
path = "code/discourse/DiscourseEventManager.lua"
}
},
textures =
{
['gradient_panel.png'] =
{
path = "art/gradient_panel.png",
},
['continue_caret.png'] =
{
path = "art/continue_caret.png",
},
['play.png'] =
{
path = "play.png",
scale = "pixelart"
},
['stop.png'] =
{
path = "stop.png",
scale = "pixelart"
},
['play_on.png'] =
{
path = "play_on.png",
scale = "pixelart"
},
['stop_on.png'] =
{
path = "stop_on.png",
scale = "pixelart"
},
['groove.png'] =
{
path = "better_groove.png",
scale = "pixelart"
},
['track.png'] =
{
path = "track_2.png",
scale = "pixelart"
},
['default_font.png'] =
{
path = "art/font/default_font.png",
scale = "pixelart"
},
['indicator.png'] =
{
path = "indicator.png",
scale = "pixelart"
},
['time_box.png'] =
{
path = "time_box.png",
scale = "pixelart"
},
['event.png'] =
{
path = "event.png",
scale = "pixelart"
},
},
['fonts'] =
{
["default"] =
{
path = "art/junction.ttf",
},
},
['sounds'] =
{
}
}
|
-- Copyright (C) 2017-2020 DBotThePony
-- 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.
jit.on()
local util = setmetatable(DLib.Util or {}, {__index = util})
DLib.util = util
DLib.Util = util
local DLib = DLib
local vgui = vgui
local type = luatype
local ipairs = ipairs
local IsValid = IsValid
local LVector = DLib.LVector
local Vector = Vector
local Angle = Angle
if CLIENT then
concommand.Add('dlib_gui_openurl', function(_, _, args)
return gui.OpenURL(table.concat(args, '%20'))
end)
end
--[[
@doc
@fname DLib.VCreate
@args string panelName, Panel parent
@desc
!g:vgui.Create but does not create panel when parent is not present
@enddesc
@returns
Panel: created panel
]]
function DLib.VCreate(pnlName, pnlParent)
if not IsValid(pnlParent) then
DLib.Message(debug.traceback('Attempt to create ' .. pnlName .. ' without valid parent!', 2))
return
end
return vgui.Create(pnlName, pnlParent)
end
--[[
@doc
@fname DLib.Util.Clone
@args any variable
@desc
creates better copy of variable.
can clone tables better than !g:table.Copy
**NOT RECURSION SAFE**
**will attempt to throw an error when encounters a recursion**
@enddesc
@returns
any: clone
]]
function util.copy(var)
if type(var) == 'table' then
local output = {}
for k, v in pairs(var) do
if k == var or v == var then
error('Confused by recursion')
end
output[util.Copy(k)] = util.Copy(v)
end
return output
end
if type(var) == 'Angle' then return Angle(var.p, var.y, var.r) end
if type(var) == 'Vector' then return Vector(var) end
if type(var) == 'LVector' then return LVector(var) end
return var
end
util.clone = util.copy
util.Clone = util.copy
util.Copy = util.copy
--[[
@doc
@fname DLib.Util.VectorRand
@alias DLib.Util.RandomVector
@args number x, number y, number z
@desc
calls math.Rand(-component, component) for each component
@enddesc
@returns
Vector
]]
function util.randomVector(mx, my, mz)
return Vector(math.Rand(-mx, mx), math.Rand(-my, my), math.Rand(-mz, mz))
end
util.RandomVector = util.randomVector
util.VectorRand = util.randomVector
--[[
@doc
@fname DLib.Util.ComposeEnums
@args table input, vararg ...numbers
@desc
:bor()'s numbers in `input` and :bor()'s numbers in vararg towards newly created value
@enddesc
@returns
number
]]
function util.composeEnums(input, ...)
local num = 0
if type(input) == 'table' then
for k, v in ipairs(input) do
num = num:bor(v)
end
else
num = input
end
return num:bor(...)
end
util.ComposeEnums = util.composeEnums
--[[
@doc
@fname DLib.Util.ValidateSteamID
@args string steamid
@returns
boolean: whenever string provided is regular steamid (STEAM_0)
]]
function util.ValidateSteamID(input)
if not input then return false end
return input:match('STEAM_0:[0-1]:[0-9]+$') ~= nil
end
--[[
@doc
@fname DLib.Util.SteamLink
@args string steamid
@desc
accepts steamid and steamid64
@enddesc
@returns
string
]]
function util.SteamLink(steamid)
if util.ValidateSteamID(steamid) then
return 'https://steamcommunity.com/profiles/' .. util.SteamIDTo64(steamid) .. '/'
else
return 'https://steamcommunity.com/profiles/' .. steamid .. '/'
end
end
--[[
@doc
@fname DLib.Util.CreateSharedConvar
@args string cvarname, string cvardef, string description
@desc
quick way to workaround [this](https://github.com/Facepunch/garrysmod-issues/issues/3323)
adds `FCVAR_REPLICATED, FCVAR_ARCHIVE, FCVAR_NOTIFY` flags serverside and only `FCVAR_REPLICATED` clientside
@enddesc
@returns
ConVar
]]
function util.CreateSharedConvar(cvarname, cvarvalue, description)
if CLIENT then
return CreateConVar(cvarname, cvarvalue, {FCVAR_REPLICATED}, description)
else
return CreateConVar(cvarname, cvarvalue, {FCVAR_REPLICATED, FCVAR_ARCHIVE, FCVAR_NOTIFY}, description)
end
end
-- Replace PrintTable with something better
local rawtype = rawtype
local table = table
local error = error
local pcall = pcall
local debug = debug
local strict = false
local RECURSION_COLOR = Color(195, 222, 69)
local TOO_DEEP_COLOR = Color(196, 158, 91)
local EQUALS_COLOR = Color(169, 117, 222)
local TABLE_TOKEN_COLOR = Color(197, 104, 111)
local COMMENTARY_COLOR = Color(143, 165, 46)
DLib._OldPrintTable = DLib._OldPrintTable or PrintTable
local wellknown, prints
local unmap = {}
for i = 0, 16 do
unmap[string.char(i)] = '\\x' .. string.format('%.2X', i)
end
local function getValueString(typeIn, valueIn)
if typeIn == 'string' then
return DLib.DEFAULT_TEXT_COLOR, '"' .. valueIn:gsub('"', '\\"'):gsub('\t', '\\t'):gsub('\n', '\\n'):gsub('.', function(str) return unmap[str] or str end) .. '"'
end
return DLib.GetPrettyPrint(valueIn, typeIn)
end
function util.PrintableString(valueIn)
return valueIn:gsub('"', '\\"'):gsub('\t', '\\t'):gsub('\n', '\\n'):gsub('.', function(str) return unmap[str] or str end), nil
end
local comparableTypes = {}
local function InternalPrintLoop(tableIn, level, recursionCheck)
if prints > 100000 then
error('I dont want to print more. Probably hit a recursion.')
end
if strict then
if wellknown[tableIn] then
MsgC(RECURSION_COLOR, ' [well known/recursion] ')
return false
end
else
if wellknown[tableIn] and wellknown[tableIn] > 6 then
MsgC(RECURSION_COLOR, ' [well known] ')
return false
end
if recursionCheck and recursionCheck[tableIn] then
MsgC(RECURSION_COLOR, ' [recursion] ')
return false
end
end
if level > 10 then
MsgC(TOO_DEEP_COLOR, ' [too deep] ')
return false
end
local keys = {}
for k in pairs(tableIn) do
table.insert(keys, k)
end
table.sort(keys, function(a, b)
local ta, tb = type(a), type(b)
local cmp = false
local token = ta .. '-' .. tb
if comparableTypes[token] == nil then
comparableTypes[token] = pcall(function()
cmp = a < b
end)
elseif comparableTypes[token] then
cmp = a < b
end
return cmp
end)
wellknown[tableIn] = (wellknown[tableIn] or 0) + 1
local hitAnything = false
for i, key in ipairs(keys) do
prints = prints + 1
if not hitAnything then
MsgC('\n')
hitAnything = true
end
local ktp = type(key)
MsgC(string.rep(' ', level * 4), TABLE_TOKEN_COLOR, '[')
MsgC(getValueString(ktp, key))
MsgC(TABLE_TOKEN_COLOR, ']', EQUALS_COLOR, ' = ')
local value = tableIn[key]
if type(value) == 'table' then
MsgC(TABLE_TOKEN_COLOR, '{')
local useSpaces = InternalPrintLoop(value, level + 1, strict and '' or recursionCheck or {})
if useSpaces then
MsgC(TABLE_TOKEN_COLOR, string.rep(' ', level * 4), '},\n')
else
MsgC(TABLE_TOKEN_COLOR, '},\n')
end
else
local tp = type(value)
MsgC(getValueString(tp, value))
MsgC(TABLE_TOKEN_COLOR, ',\n')
end
end
if not hitAnything then
MsgC(COMMENTARY_COLOR, ' --[[ empty ]] ')
end
return hitAnything
end
--[[
@doc
@fname PrintTable
@replaces
@args table value
@desc
pretty prints a table.
attempts to avoid recursion.
@enddesc
]]
function _G.PrintTable(tableIn)
assert(rawtype(tableIn) == 'table', 'Input must be a table!')
wellknown = {}
prints = 0
strict = false
MsgC(TABLE_TOKEN_COLOR, '{')
InternalPrintLoop(tableIn, 1)
MsgC(TABLE_TOKEN_COLOR, '}\n')
end
util.PrintTable = _G.PrintTable
--[[
@doc
@fname PrintTableStrict
@args table value
@desc
pretty prints a table.
strictly avoids any meaning of recursion.
@enddesc
]]
function _G.PrintTableStrict(tableIn)
assert(rawtype(tableIn) == 'table', 'Input must be a table!')
wellknown = {}
prints = 0
strict = true
MsgC(TABLE_TOKEN_COLOR, '{')
InternalPrintLoop(tableIn, 1)
MsgC(TABLE_TOKEN_COLOR, '}\n')
end
util.PrintTableStrict = _G.PrintTableStrict
local files = file.Find('scripts/weapons/*.txt', 'GAME')
local wepdata = {}
for i, mfile in ipairs(files) do
local parsed = util.KeyValuesToTable(file.Read('scripts/weapons/' .. mfile, 'GAME'))
if parsed then
wepdata[mfile:sub(1, -5)] = parsed
end
end
if CLIENT then
for wepclass, data in pairs(wepdata) do
if data.texturedata then
if data.texturedata.weapon and data.texturedata.weapon.file then
data.texturedata.weapon.material = Material(data.texturedata.weapon.file)
end
if data.texturedata.weapon_s and data.texturedata.weapon_s.file then
data.texturedata.weapon_s.material = Material(data.texturedata.weapon_s.file)
end
if data.texturedata.ammo and data.texturedata.ammo.file then
data.texturedata.ammo.material = Material(data.texturedata.ammo.file)
end
if data.texturedata.ammo2 and data.texturedata.ammo2.file then
data.texturedata.ammo2.material = Material(data.texturedata.ammo2.file)
end
end
end
end
--[[
@doc
@fname DLib.Util.GetWeaponScript
@args Weapon weaponIn
@returns
table: or nil, if no script present
]]
function DLib.Util.GetWeaponScript(weaponIn)
if isstring(weaponIn) then
return wepdata[weaponIn]
elseif type(weaponIn) == 'Weapon' then
return wepdata[weaponIn:GetClass()]
else
error('Invalid weapon provided: ' .. type(weaponIn))
end
end
--[[
@doc
@fname printflags
@args number flags, number minimumDecimals = 0
@returns
string: formatted
]]
function util.printflags(flagsIn, mnum)
assert(type(flagsIn) == 'number', 'flagsIn must be a number')
mnum = mnum or 0
local format = ''
if flagsIn < 0 then
flagsIn = flagsIn + 0xFFFFFFFF
end
flagsIn = flagsIn:floor()
while flagsIn > 0 do
local div = flagsIn % 2
flagsIn = (flagsIn - div) / 2
format = div .. format
end
if #format < mnum then
format = string.rep('0', mnum - #format) .. format
end
print(format)
return format
end
util.printbits = DLib.printflags
do
local sub = string.sub
local byte = string.byte
local char = string.char
local band = bit.band
local lshift = bit.lshift
local rshift = bit.rshift
local assert = assert
local concat = table.concat
local f4, f3, f2, f1 = 63, lshift(63, 6), lshift(63, 12), lshift(63, 18)
local jit_status = jit.status
local jit_off = jit.off
local jit_on = jit.on
local lookup = string.Split('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/', '')
local rlookup = {[61] = 0}
for i, char2 in ipairs(lookup) do
rlookup[byte(char2)] = i - 1
end
-- just for lulz Lua implementation
-- This is very slow
function util.Base64Encode(strIn, splitter)
assert(isstring(strIn), 'Input is not a string! typeof ' .. strIn)
splitter = splitter or 18
local lines = {}
local parts = 0
local i2 = 1
local str = ''
local j = jit_status()
jit_off()
for i = 1, #strIn, 3 do
local a, b, c = byte(strIn, i, i + 3)
if b == nil then
local int = lshift(a, 16)
str = str .. lookup[rshift(band(int, f1), 18) + 1] .. lookup[rshift(band(int, f2), 12) + 1] .. '=='
elseif c == nil then
local int = lshift(b, 8) + lshift(a, 16)
str = str .. lookup[rshift(band(int, f1), 18) + 1] .. lookup[rshift(band(int, f2), 12) + 1] .. lookup[rshift(band(int, f3), 6) + 1] .. '='
else
local int = c + lshift(b, 8) + lshift(a, 16)
str = str .. lookup[rshift(band(int, f1), 18) + 1] .. lookup[rshift(band(int, f2), 12) + 1] .. lookup[rshift(band(int, f3), 6) + 1] .. lookup[band(int, f4) + 1]
end
parts = parts + 1
if parts >= splitter then
lines[i2] = str
i2 = i2 + 1
str = ''
parts = 0
end
end
if str ~= '' then
lines[i2] = str
end
if j then
jit_on()
end
return concat(lines, '\n')
end
local iA, iB, iC = 0xFF0000, 0xFF00, 0xFF
local gsub = string.gsub
function util.Base64Decode(strIn)
local buffer = {}
local str = ''
local size = 0
local point = 1
local bi = 1
strIn = gsub(strIn, '\n', '')
local len = #strIn
assert((len % 4) == 0, 'Unexpected end of base64 input')
local j = jit_status()
jit_off()
while point <= len do
local a, b, c, d = byte(strIn, point, point + 4)
point = point + 4
local int = lshift(rlookup[a], 18) + lshift(rlookup[b], 12) + lshift(rlookup[c], 6) + rlookup[d]
local a1, b1, c1 = rshift(band(int, iA), 16), rshift(band(int, iB), 8), band(int, iC)
if c == 61 then -- xx==
str = str .. char(a1)
elseif d == 61 then -- xxx=
str = str .. char(a1, b1)
else -- xxxx
str = str .. char(a1, b1, c1)
end
size = size + 1
if size > 200 then
size = 0
buffer[bi] = str
str = ''
bi = bi + 1
end
end
if str ~= '' then
buffer[bi] = str
end
if j then
jit_on()
end
return concat(buffer, '')
end
end
|
GAMESTAGE_BASEPLACE = 1
GAMESTAGE_BUILD = 2
GAMESTAGE_PLAY = 3
DAC.DefaultGameStage = GAMESTAGE_BASEPLACE
DAC:RegisterGameStage(GAMESTAGE_BASEPLACE, {
name = "SETUP",
showOnHud = true,
pvp = false,
nextStage = nil,
color = Color(0, 130, 255)
})
DAC:RegisterGameStage(GAMESTAGE_BUILD, {
name = "BUILD",
showOnHud = true,
pvp = false,
allowBuilding = true,
nextStage = GAMESTAGE_PLAY,
duration = GetConVar("dac_build_time"):GetInt(),
color = Color(0, 255, 0)
})
DAC:RegisterGameStage(GAMESTAGE_PLAY, {
name = "MATCH",
showOnHud = true,
pvp = true,
nextStage = nil,
color = Color(251, 255, 0)
})
|
format_version = "1.0"
-- Note that changing this file requires a Reason/Recon restart
-- Max 40 chars
long_name = "Noise Synth"
-- Max 20 chars
medium_name = "Noise Synth"
-- Max 10 chars
short_name = "NoiseSynth"
product_id = "org.porternet.noisesynth"
manufacturer = "meromorph"
version_number = "1.1.0b5"
device_type = "instrument"
supports_patches = true
default_patch = "/Public/Default.repatch"
accepts_notes = true
auto_create_track = true
auto_create_note_lane = true
supports_performance_automation = true
device_height_ru = 2
automation_highlight_color = {r = 60, g = 255, b = 2}
|
local menori = require 'menori'
local application = menori.Application
local ml = menori.ml
local vec3 = ml.vec3
local quat = ml.quat
local love_logo = menori.ImageLoader.load('example_assets/love_logo.png')
-- Creating a node for drawing an object.
local SpriteNode = menori.Node:extend('SpriteNode')
function SpriteNode:init(x, y, sx, sy, speed, ox, oy)
-- Calling the parent's constructor.
SpriteNode.super.init(self)
-- Creating a sprite object from an image.
self.sprite = menori.SpriteLoader.from_image(love_logo)
self.sprite:set_pivot(0.5, 0.5)
self.x = x
self.y = y
self.sx = sx
self.sy = sy
self.angle = 0
self.speed = speed
end
function SpriteNode:render()
love.graphics.push()
-- Node contains two matrices.
-- Local matrix is transformations of the current node.
-- World matrix is the sum of transformations of the parent nodes.
-- to_temp_transform_object converts a matrix to LOVE Transform object.
love.graphics.replaceTransform(self.world_matrix:to_temp_transform_object())
-- Draw a sprite.
self.sprite:draw()
love.graphics.pop()
end
function SpriteNode:update()
self.angle = self.angle + self.speed
self:set_position(self.x, self.y, 0)
self:set_rotation(quat.from_angle_axis(math.rad(self.angle), vec3.unit_z))
self:set_scale(self.sx, self.sy, 1)
end
local PointLight = menori.UniformList:extend('PointLight')
function PointLight:init(x, y, z, r, g, b)
PointLight.super.init(self)
self:set('position', {x, y, z})
self:set('constant', 1.0)
self:set('linear', 0.3)
self:set('quadratic', 0.032)
self:set('ambient', {r, g, b})
self:set('diffuse', {r, g, b})
self:set('specular', {r, g, b})
end
-- Inherit from the scene class and create new scene.
local NewScene = menori.Scene:extend('NewScene')
function NewScene:init()
-- Calling the parent's constructor.
NewScene.super.init(self)
local shader_code = love.filesystem.read('example_assets/lighting.glsl')
local shader_lighting = love.graphics.newShader(menori.utils.shader_preprocess(shader_code))
-- An example of creating a mesh.
local vx = 1
local vz = 1
local vertices = {
{-vx, 0,-vz, 0, 0, 0, 1, 0 },
{-vx, 0, vz, 0, 1, 0, 1, 0 },
{ vx, 0,-vz, 1, 0, 0, 1, 0 },
{ vx, 0, vz, 1, 1, 0, 1, 0 }
}
local indices = menori.Mesh.generate_indices(#vertices)
-- default mesh format POS3|TEX2|NOR3
local model_instance = menori.Mesh.from_primitive(vertices, {
indices = indices, mode = 'triangles', texture = love_logo,
})
-- Now you can use an model instance for every new node.
local quadmesh1 = menori.ModelNode(model_instance, shader_lighting)
local quadmesh2 = menori.ModelNode(model_instance, shader_lighting)
quadmesh1:set_position(5, 0.1,-2)
quadmesh2:set_position(2, 0.1, 2)
-- Initializing the perspective camera and environment.
local aspect = menori.Application.w/menori.Application.h
self.camera_3d = menori.PerspectiveCamera(35, aspect, 0.5, 1024)
self.environment_3d = menori.Environment(self.camera_3d)
self.camera_2d = menori.Camera()
self.environment_2d = menori.Environment(self.camera_2d)
self.environment_3d:add_light('point_lights', PointLight(-2, 1,-1, 0.8, 0.2, 0.1))
self.environment_3d:add_light('point_lights', PointLight( 2, 1,-1, 0.1, 0.6, 0.9))
-- Creating and attaching nodes to each other.
local sprite_node = SpriteNode(200, 200, 0.5, 0.5, 2)
self.child1 = sprite_node:attach(SpriteNode(128, 128, 0.5, 0.5, 1))
-- Load the scene from gltf format, get a table of nodes and scenes contained in the file.
local gltf = menori.glTFLoader.load('example_assets/players_room_model/', 'scene')
local model_node_tree = menori.ModelNodeTree(gltf, shader_lighting)
-- Create a root node and add the loaded scene to it.
self.root_node_3d = menori.Node()
self.root_node_3d:attach(model_node_tree)
self.root_node_3d:attach(quadmesh1)
self.root_node_3d:attach(quadmesh2)
self.root_node_2d = menori.Node()
self.root_node_2d:attach(sprite_node)
-- Camera rotation angle.
self.angle = 0
end
-- Turn on the depth buffer, clear the canvases and set the color.
local renderstates = {
depth = true
}
function NewScene:render()
love.graphics.clear(0.15, 0.1, 0.1)
love.graphics.setDepthMode('less', true)
-- Recursively draw all nodes in root_node.
self:render_nodes(self.root_node_3d, self.environment_3d, renderstates)
love.graphics.setDepthMode()
self:render_nodes(self.root_node_2d, self.environment_2d, renderstates)
love.graphics.setColor(1, 0, 0, 1)
local v = self.child1:get_world_position()
love.graphics.rectangle('fill', v.x - 5, v.y - 5, 10, 10)
local r = self.child1:get_world_rotation()
local p = r * vec3(1, 0, 0) * 100
love.graphics.rectangle('fill', 200 + p.x - 5, 200 + p.y - 5, 10, 10)
love.graphics.setColor(1, 1, 1, 1)
end
function NewScene:update_camera()
-- Rotating the camera around the model.
self.angle = self.angle + 0.2
local q = quat.from_euler_angles(0, math.rad(self.angle), math.rad(-45))
local v = vec3(0, 0, 12)
self.camera_3d.eye = q * v
self.camera_3d:update_view_matrix()
local uniform_list = self.environment_3d.uniform_list
uniform_list:set_vector('view_position', self.camera_3d.eye)
end
function NewScene:update()
self:update_camera()
-- Recursively update all nodes in root_node.
self:update_nodes(self.root_node_3d, self.environment_3d)
self:update_nodes(self.root_node_2d, self.environment_2d)
end
function love.load()
local w, h = 960, 480
application:resize_viewport(w*1.5, h*1.5, {filter = 'linear', msaa = 4})
application:add_scene('new_scene', NewScene())
application:set_scene('new_scene')
end
function love.draw()
application:render()
end
function love.update(dt)
application:update(dt)
end
|
AttackStyleName = FlyRound
Data = {
howToBreakFormation = StraightAndScatter,
axisRotation = 15,
maxAxisRotation = 15,
circleSegmentAngle = 45,
angleVariation = 0.2,
circleHeight = -300,
distanceFromTarget = 1200,
distanceVariation = 0.1,
percentChanceOfCutting = 5,
minSegmentsToCut = 1,
maxSegmentsToCut = 3,
RandomActions = {
{
Type = PickNewTarget,
Weighting = 1,
},
{
Type = NoAction,
Weighting = 9,
},
},
BeingAttackedActions = {},
FiringActions = {},
}
|
object_draft_schematic_genetic_engineering_combiner_use_capsule = object_draft_schematic_genetic_engineering_shared_combiner_use_capsule:new {
}
ObjectTemplates:addTemplate(object_draft_schematic_genetic_engineering_combiner_use_capsule, "object/draft_schematic/genetic_engineering/combiner_use_capsule.iff")
|
-- Tests for pollard_rho.lua
local rho = require 'pollard_rho'
local total, pass = 0, 0
local function dec(str, len)
return #str < len
and str .. (('.'):rep(len-#str))
or str:sub(1,len)
end
local function run(message, f)
total = total + 1
local ok, err = pcall(f)
if ok then pass = pass + 1 end
local status = ok and 'PASSED' or 'FAILED'
print(('%02d. %68s: %s'):format(total, dec(message,68), status))
end
run('Pollard\'s rho factorization', function()
local n = 8051
local function f(x) return (x^2+1)%n end
assert(rho(n, f) == 97)
end)
print(('-'):rep(80))
print(('Total : %02d: Pass: %02d - Failed : %02d - Success: %.2f %%')
:format(total, pass, total-pass, (pass*100/total)))
|
-- FS.lua
-- David Skrundz
--
-- FS.forEachFile("lua", function(name) print(name) end)
-- FS.deleteAll()
-- FS.cleanup()
-- data = FS.read(file)
-- FS.write(file, data)
FS = {}
function FS.forEachFile(extension, callback)
local files = file.list()
for name, _ in pairs(files) do
if stringHasSuffix(name, extension) then
callback(name)
end
end
end
function FS.deleteAll()
local files = file.list()
for name, _ in pairs(files) do
file.remove(name)
end
end
function FS.cleanup()
FS.forEachFile(".lua", function(name)
if name == "init.lua" then return end
file.remove(name)
end)
file.remove("init.lc")
end
function FS.read(fileName)
if file.open(fileName, "r") then
local str = file.read()
file.close()
return str
end
return nil
end
function FS.write(fileName, data)
if file.open(fileName, "w+") then
file.write(data)
file.close()
end
end
function stringHasSuffix(self, suffix)
return suffix == '' or self:sub(-suffix:len()) == suffix
end
|
Notify("START")
p=require("podman")
p({
NAME = "sys_dns",
URL = "coredns",
TAG = "1.8.3",
CPUS = "3",
MEM = "512m",
})
|
-- @Author:pandayu
-- @Version:1.0
-- @DateTime:2018-09-09
-- @Project:pandaCardServer CardGame
-- @Contact: QQ:815099602
local CTasklist = require "game.template.task"
local _M = CTasklist:extends()
_M.class = "role.main_tasklist"
_M.push_name = "main_tasklist"
_M.changed_name_in_role = "main_tasklist"
return _M
|
BasicEnemyGun = Entity:extend()
function BasicEnemyGun:new(obj, offsetX, recoil)
self.offsetX = offsetX
self.obj = obj
self.x = self.obj.x + self.obj.w/2 + self.offsetX
self.y = self.obj.y + self.obj.h/2
self.tweener = Timer.new()
self.recoil = recoil
self.originalPos = { x = self.obj.x + self.obj.w/2 + self.offsetX, y = self.obj.y + self.obj.h/2}
self.recoilPos = {x = self.obj.x + self.obj.w/2 + self.recoil, y = self.obj.y + self.obj.h/2 }
end
function BasicEnemyGun:update(dt)
self.x = self.obj.x + self.obj.w/2 + self.offsetX
self.y = self.obj.y + self.obj.h/2
self.originalPos = { x = self.obj.x + self.obj.w/2 + self.offsetX, y = self.obj.y + self.obj.h/2}
self.recoilPos = {x = self.obj.x + self.obj.w/2 + self.recoil, y = self.obj.y + self.obj.h/2 }
self.tweener:update(dt)
end
function BasicEnemyGun:inning(targetPos)
self.tweener:tween(0.1, self, {x = targetPos.x, y = targetPos.y}, "out-quad", function() self:outing() end)
end
function BasicEnemyGun:outing()
self.tweener:tween(0.1, self, {x = self.originalPos.x, y = self.originalPos.y}, "out-quad")
end
function BasicEnemyGun:shoot()
self:inning(self.recoilPos)
local bulletSpeed = 0
if self.originalPos.x < self.recoilPos.x then
bulletSpeed = -300
else
bulletSpeed = 300
end
table.insert(objects.bullets, Bullet(self.x, self.y, 0, bulletSpeed, 50, "enemy", "basic"))
end
function BasicEnemyGun:draw()
love.graphics.setColor(hex.rgb("ffffff"))
love.graphics.draw(images.spriteSheet, images.enemy.basicGun, self.x, self.y, 0, 1, 1, 16, 16)
end
|
RegisterNetEvent("caue-racing:recieveCreateData")
AddEventHandler("caue-racing:recieveCreateData", function(pRaceName, pRaceType, pRaceThumbnail, pCheckpoints)
local src = source
local aliases = exports["caue-base"]:getChar(src, "aliases")
local distanceMap = 0.0
for i, v in ipairs(pCheckpoints) do
if i == #pCheckpoints and pRaceType == "Lap" then
distanceMap = #(vector3(v["pos"]["x"],v["pos"]["y"],v["pos"]["z"]) - vector3(pCheckpoints[1]["pos"]["x"],pCheckpoints[1]["pos"]["y"],pCheckpoints[1]["pos"]["z"])) + distanceMap
elseif i ~= #pCheckpoints then
distanceMap = #(vector3(v["pos"]["x"],v["pos"]["y"],v["pos"]["z"]) - vector3(pCheckpoints[i+1]["pos"]["x"],pCheckpoints[i+1]["pos"]["y"],pCheckpoints[i+1]["pos"]["z"])) + distanceMap
end
end
distanceMap = math.ceil(distanceMap)
local insertId = MySQL.insert.await([[
INSERT INTO racing_races (name, creator, distance, type, thumbnail, checkpoints)
VALUES (?, ?, ?, ?, ?, ?)
]],
{ pRaceName, aliases, distanceMap, pRaceType, pRaceThumbnail, json.encode(pCheckpoints) })
if not insertId or insertId < 1 then return end
formatRace({
id = insertId,
name = pRaceName,
creator = aliases,
distance = distanceMap,
type = pRaceType,
thumbnail = pRaceThumbnail,
checkpoints = pCheckpoints,
fastest_time = 0,
fastest_name = "N/A",
races = 0,
})
TriggerClientEvent("caue-racing:addedRace", -1, {}, Races)
TriggerClientEvent("DoLongHudText", src, "Race " .. pRaceName .. " created!")
end)
RPC.register("caue-racing:isRaceNameTaken", function(src, pRaceName)
local result = MySQL.scalar.await([[
SELECT id
FROM racing_races
WHERE name = ?
]],
{ pRaceName })
if not result then return false end
return true
end)
|
#!/usr/bin/env gt
--[[
Author: Sascha Steinbiss <ss34@sanger.ac.uk>
Copyright (c) 2014 Genome Research Ltd
Permission to use, copy, modify, and distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
]]
function usage()
io.stderr:write(string.format("Usage: %s <GFF>\n" , arg[0]))
os.exit(1)
end
if #arg < 1 then
usage()
end
remove_codons_visitor = gt.custom_visitor_new()
function remove_codons_visitor:visit_feature(fn)
for node in fn:children() do
if node:get_type() == "exon"
or node:get_type() == "intron"
or node:get_type() == "start_codon"
or node:get_type() == "stop_codon" then
fn:remove_leaf(node)
end
end
return 0
end
function join_first(fn)
-- join intron with first CDS/exon, drop first intron
if fn:get_strand() == '+' then
local rng = nil
for i in fn:children() do
if i:get_type() == 'intron' then
rng = i:get_range()
fn:remove_leaf(i)
break
end
end
if rng then
for c in fn:children() do
if c:get_type() == 'CDS' then
c:set_range(c:get_range():join(rng))
break
end
end
for c in fn:children() do
if c:get_type() == 'exon' then
c:set_range(c:get_range():join(rng))
break
end
end
end
end
if fn:get_strand() == '-' then
local lintron, lcds, lexon = nil, nil, nil
for i in fn:children() do
if i:get_type() == 'intron' then
lintron = i
end
end
if lintron then
for c in fn:children() do
if c:get_type() == 'CDS' then
lcds = c
end
end
for c in fn:children() do
if c:get_type() == 'exon' then
lexon = c
end
end
if lcds and lexon then
lcds:set_range(lexon:get_range():join(lintron:get_range()))
lexon:set_range(lexon:get_range():join(lintron:get_range()))
fn:remove_leaf(lintron)
end
end
end
end
function join_last(fn)
-- join first intron with first CDS/exon, drop it afterwards
if fn:get_strand() == '-' then
rng = nil
for i in fn:children() do
if i:get_type() == 'intron' then
rng = i:get_range()
fn:remove_leaf(i)
break
end
end
if rng then
for c in fn:children() do
if c:get_type() == 'CDS' then
c:set_range(c:get_range():join(rng))
break
end
end
for c in fn:children() do
if c:get_type() == 'exon' then
c:set_range(c:get_range():join(rng))
break
end
end
end
end
if fn:get_strand() == '+' then
local lintron, lcds, lexon = nil, nil, nil
for i in fn:children() do
if i:get_type() == 'intron' then
lintron = i
end
end
if lintron then
for c in fn:children() do
if c:get_type() == 'CDS' then
lcds = c
end
end
for c in fn:children() do
if c:get_type() == 'exon' then
lexon = c
end
end
if lcds and lexon then
lcds:set_range(lexon:get_range():join(lintron:get_range()))
lexon:set_range(lexon:get_range():join(lintron:get_range()))
fn:remove_leaf(lintron)
end
end
end
end
mark_partial_visitor = gt.custom_visitor_new()
function mark_partial_visitor:visit_feature(fn)
has_start, has_stop, has_intron = false, false, false
if fn:get_type() == 'gene' then
-- determine if gene is partial
for fn2 in fn:children() do
if fn2:get_type() == 'mRNA' then
local nof_children = 0
for n in fn2:children() do
nof_children = nof_children + 1
end
local i = 1
for n in fn2:children() do
if n:get_type() == 'start_codon' then
has_start = true
elseif n:get_type() == 'stop_codon' then
has_stop = true
elseif n:get_type() == 'intron' then
has_intron = true
end
end
-- set corresponding attributes
if not has_start then
fn:add_attribute("fiveEndPartial","true")
if fn:get_strand() == "+" then
fn:add_attribute("Start_range",".,.")
elseif fn:get_strand() == "-" then
fn:add_attribute("End_range",".,.")
end
end
if not has_stop then
fn:add_attribute("threeEndPartial","true")
if fn:get_strand() == "-" then
fn:add_attribute("Start_range",".,.")
elseif fn:get_strand() == "+" then
fn:add_attribute("End_range",".,.")
end
end
end
-- disable the leading/trailing intron joining for now
if not has_start and has_intron then
-- join_first(fn2)
end
if not has_stop and has_intron then
-- join_last(fn2)
end
end
end
return 0
end
-- setup generic visitor stream
vis_stream = gt.custom_stream_new_unsorted()
vis_stream.instream = gt.gff3_in_stream_new_sorted(arg[1])
vis_stream.mark_partial_visitor = mark_partial_visitor
vis_stream.remove_codons_visitor = remove_codons_visitor
function vis_stream:next_tree()
local node = self.instream:next_tree()
if node then
node:accept(self.mark_partial_visitor)
node:accept(self.remove_codons_visitor)
end
return node
end
out_stream = gt.gff3_out_stream_new(vis_stream)
local gn = out_stream:next_tree()
while (gn) do
gn = out_stream:next_tree()
end
|
local skynet = require "skynet"
-- openmygateserver
skynet.start(function()
skynet.error("Server start")
local gateserver = skynet.newservice("mygateserver") --启动的网关服务
skynet.call(gateserver, "lua", "open", { --需要给网关服务发送open消息,来启动监听
port = 8083, --监听的端口
maxclient = 2, --客户端最大连接数
nodelay = true, --是否延迟TCP
})
skynet.error("gate server setup on", 8083)
skynet.exit()
end)
|
-------------------------------------------------------------------------------------------
--
-- raylib [core] example - Color selection by mouse (collision detection)
--
-- This example has been created using raylib 1.6 (www.raylib.com)
-- raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
--
-- Copyright (c) 2014-2016 Ramon Santamaria (@raysan5)
--
-------------------------------------------------------------------------------------------
NUM_RECTANGLES = 21
-- Initialization
-------------------------------------------------------------------------------------------
local screenWidth = 800
local screenHeight = 450
InitWindow(screenWidth, screenHeight, "raylib [core] example - color selection (collision detection)")
local colors = { DARKGRAY, MAROON, ORANGE, DARKGREEN, DARKBLUE, DARKPURPLE, DARKBROWN,
GRAY, RED, GOLD, LIME, BLUE, VIOLET, BROWN, LIGHTGRAY, PINK, YELLOW,
GREEN, SKYBLUE, PURPLE, BEIGE }
local colorsRecs = {} -- Rectangles array
local selected = {}
-- Fills colorsRecs data (for every rectangle)
for i = 1, NUM_RECTANGLES do
colorsRecs[i] = Rectangle()
colorsRecs[i].x = 20 + 100*((i-1)%7) + 10*((i-1)%7)
colorsRecs[i].y = 60 + 100*((i-1)//7) + 10*((i-1)//7) -- Using floor division: //
colorsRecs[i].width = 100
colorsRecs[i].height = 100
selected[i] = false
end
local mousePoint = Vector2()
SetTargetFPS(60) -- Set our game to run at 60 frames-per-second
-------------------------------------------------------------------------------------------
-- Main game loop
while not WindowShouldClose() do -- Detect window close button or ESC key
-- Update
---------------------------------------------------------------------------------------
mousePoint = GetMousePosition()
for i = 1, NUM_RECTANGLES do -- Iterate along all the rectangles
if (CheckCollisionPointRec(mousePoint, colorsRecs[i])) then
colors[i].a = 120
if (IsMouseButtonPressed(MOUSE_LEFT_BUTTON)) then selected[i] = not selected[i] end
else colors[i].a = 255 end
end
---------------------------------------------------------------------------------------
-- Draw
---------------------------------------------------------------------------------------
BeginDrawing()
ClearBackground(RAYWHITE)
for i = 1, NUM_RECTANGLES do -- Draw all rectangles
DrawRectangleRec(colorsRecs[i], colors[i])
-- Draw four rectangles around selected rectangle
if (selected[i]) then
DrawRectangle(colorsRecs[i].x, colorsRecs[i].y, 100, 10, RAYWHITE) -- Square top rectangle
DrawRectangle(colorsRecs[i].x, colorsRecs[i].y, 10, 100, RAYWHITE) -- Square left rectangle
DrawRectangle(colorsRecs[i].x + 90, colorsRecs[i].y, 10, 100, RAYWHITE) -- Square right rectangle
DrawRectangle(colorsRecs[i].x, colorsRecs[i].y + 90, 100, 10, RAYWHITE) -- Square bottom rectangle
end
end
EndDrawing()
---------------------------------------------------------------------------------------
end
-- De-Initialization
-------------------------------------------------------------------------------------------
CloseWindow() -- Close window and OpenGL context
-------------------------------------------------------------------------------------------
|
-- draw text
set_callback(function(draw_ctx)
-- get a random color
local color = math.random(0, 0xffffffff)
-- zoom the font size based on frame
local size = (get_frame() % 199)+1
local text = 'Awesome!'
-- calculate size of text
local w, h = draw_text_size(size, text)
-- draw to the center of screen
draw_ctx:draw_text(0-w/2, 0-h/2, size, text, color)
end, ON.GUIFRAME)
|
--[[
module:ProgramNode
author:DylanYang
time:2021-02-12 21:44:28
]]
local CommandListNode = require("patterns.behavioral.interpreter.CommandListNode")
local super = require("patterns.behavioral.interpreter.Node")
local _M = Class("ProgramNode", super)
local public = _M.public
_M.cmdListNode = nil
function public:Parse(context)
context:SkipToken("program")
self.cmdListNode = CommandListNode.new()
self.cmdListNode:Parse(context)
end
function public:ToString()
return string.format("[program %s]", self.cmdListNode:ToString())
end
return _M
|
--- === cp.ui.Column ===
---
--- Represents an `AXColumn` `axuielement`.
local axutils = require "cp.ui.axutils"
local Element = require "cp.ui.Element"
local Column = Element:subclass("cp.ui.Column")
--- cp.ui.Column.matches(element) -> boolean
--- Function
--- Checks if the `axuielement` is a `Column`.
---
--- Parameters:
--- * element - The `axuielement` to check.
---
--- Returns:
--- * `true` if the element is a Column.
function Column.static.matches(element)
return Element.matches(element) and element:attributeValue("AXRole") == "AXColumn"
end
--- cp.ui.Column.index <cp.prop: number; read-only>
--- Field
--- The numeric index of this column in the overall container, with `0` being the first item.
function Column.lazy.prop:index()
return axutils.prop(self.UI, "AXIndex")
end
--- cp.ui.Column.selected <cp.prop: boolean>
--- Field
--- Indicates if the column is currently selected. May be set.
function Column.lazy.prop:selected()
return axutils.prop(self.UI, "AXSelected", true)
end
--- cp.ui.Column:rows() -> table of cp.ui.Row or nil
--- Method
--- Returns a `table` of [Row](cp.ui.Row.md)s contained in the Column.
---
--- Returns:
--- * The `table`, or `nil` if the column's UI is not available.
function Column:rows()
local ui = self:UI()
if ui then
local rowsUI = ui:attributeValue("AXRows")
return self:parent():findRows(rowsUI)
end
end
--- cp.ui.Column:visibleRows() -> table of cp.ui.Rows or nil
--- Method
--- Returns a `table` of [Row](cp.ui.Row.md)s which are currently visible on screen.
---
--- Returns:
--- * The `table`, or `nil` if the column's UI is not available.
function Column:visibleRows()
local ui = self:UI()
if ui then
local rowsUI = ui:attributeValue("AXVisibleRows")
return self:parent():findRows(rowsUI)
end
end
return Column
|
--- Parser for DAT syntax. Inherited from @{l2df.class.parser|l2df.class.BaseParser} class.
-- @classmod l2df.class.parser.dat
-- @author Abelidze
-- @copyright Atom-TM 2019
-- @deprecated
local core = l2df or require(((...):match('(.-)class.+$') or '') .. 'core')
assert(type(core) == 'table' and core.version >= 1.0, 'DatParser works only with l2df v1.0 and higher')
local helper = core.import 'helper'
local BaseParser = core.import 'class.parser'
local strsub = string.sub
local strfind = string.find
local strmatch = string.match
local strformat = string.format
local strjoin = table.concat
local plural = helper.plural
local DatParser = BaseParser:extend()
DatParser.ARRAY_LBRACKET = '{'
DatParser.ARRAY_RBRACKET = '}'
DatParser.BLOCK_LBRACKET = '['
DatParser.BLOCK_RBRACKET = ']'
DatParser.VALUE_END_PATTERN = '[;,%s]'
--- Method for parsing dat formatted string.
-- You can extend existing object by passing it as second parameter.
-- @param string str String for parsing.
-- @param[opt] table obj Object to extend.
-- @return table
function DatParser:parse(str, obj)
assert(type(str) == 'string', 'Parameter "str" must be a string.')
local result = obj or { }
local key = nil
local section = 'global'
local len = #str
local from = 1
local pos = 1
local to = 1
while section do
to, pos, key = strfind(str, '%[%s*(%w+)%s*%]', pos)
result[section] = self:parseBlock(strsub(str, from, (to or len + 1) - 1), result[section])
section = key
from = (pos or 0) + 1
end
return result
end
--- Method for dumping table to dat format.
-- @param table data Table for dumping.
-- @return string
function DatParser:dump(data)
assert(type(data) == 'table', 'Parameter "data" must be a table.')
local result = self:dumpBlock(type(data.global) == 'table' and data.global or { })
for section, block in pairs(data) do
if type(block) == 'table' and section ~= 'global' and section ~= 'private' then
result = strformat('%s\n[%s]\n%s', result, section, self:dumpBlock(block))
end
end
return result
end
--- Method for dumping dat-file's block.
-- @param table block Block for dumping.
-- @param[opt] string tabs
-- @return string
function DatParser:dumpBlock(block, tabs)
tabs = tabs or ''
local result = ''
for key, param in pairs(block) do
local t = type(param)
if t == 'table' then
local size = #param
if size > 0 and param[size] and type(param[size]) ~= 'table' then
result = strformat('%s%s%s: { %s }\n', result, tabs, key, strjoin(param))
else
result = strformat('%s%s%s: [\n%s]\n', result, tabs, key, self:dumpBlock(param, tabs .. "\t"), tabs)
end
elseif t ~= 'function' then
result = strformat('%s%s%s: %s\n', result, tabs, key, self:dumpScalar(param))
end
end
return result
end
--- Method for parsing dat-file's section string.
-- You can extend existing object by passing it as second parameter.
-- @param string str String for parsing.
-- @param[opt] table obj Object to extend.
-- @return table
function DatParser:parseBlock(str, obj)
str = (str or '') .. ' '
local result = obj or { }
local stack = { result }
local is_array = { false }
local head = 1
local param = nil
local plural_param = nil
local parent = nil
local char = nil
local from = 1
local pos = 1
local bpos = 1
local len = #str
while pos < len do
if is_array[head] then
param = #stack[head] + 1
else
bpos = pos
from, pos, param = strfind(str, '([%w_]+)%s*:%s*', pos)
if not param then break end
param = tonumber(param) or param
if head > 1 then
bpos = strfind(str, self.BLOCK_RBRACKET, bpos)
if bpos and bpos < from then
head = head - 1
if is_array[head] then
pos = bpos
param = #stack[head] + 1
end
end
end
end
local value = { }
local is_quoted = false
while pos < len do
pos = pos + 1
char = strsub(str, pos, pos)
if char == self.BLOCK_LBRACKET then
parent = stack[head]
head = head + 1
is_array[head] = false
if is_array[head - 1] then
stack[head] = { }
else
stack[head] = parent[param] or { }
end
plural_param = plural(param)
if parent[plural_param] then
parent[plural_param][#parent[plural_param] + 1] = stack[head]
elseif parent[param] then
parent[plural_param] = { parent[param], stack[head] }
parent[param] = nil
else
parent[param] = stack[head]
end
break
elseif char == self.ARRAY_LBRACKET then
parent = stack[head]
head = head + 1
is_array[head] = true
stack[head] = { }
plural_param = plural(param)
if parent[plural_param] then
parent[plural_param][#parent[plural_param] + 1] = stack[head]
elseif parent[param] then
parent[plural_param] = { parent[param], stack[head] }
parent[param] = nil
else
parent[param] = stack[head]
end
param = 1
elseif char == self.ARRAY_RBRACKET then
if is_array[head] then
if next(value) then
stack[head][param] = self:parseScalar(strjoin(value))
end
is_array[head] = false
head = head - 1
end
break
elseif char == '\"' and not is_quoted then
is_quoted = true
elseif strmatch(char, self.VALUE_END_PATTERN) and not is_quoted or char == '\"' then
if is_array[head] then
if next(value) then
stack[head][param] = self:parseScalar(strjoin(value))
param = param + 1
end
else
parent = stack[head]
parent[param] = self:parseScalar(strjoin(value))
-- plural_param = plural(param)
-- if parent[plural_param] then
-- parent[plural_param][#parent[plural_param] + 1] = self:parseScalar(strjoin(value))
-- elseif parent[param] then
-- parent[plural_param] = { parent[param], self:parseScalar(strjoin(value)) }
-- parent[param] = nil
-- else
-- parent[param] = self:parseScalar(strjoin(value))
-- end
break
end
value = { }
else
value[#value + 1] = char
end
end -- while
end -- while true
return result
end
return DatParser
|
local Constants = require(script.Parent.Parent.Parent.Constants)
local Promise = require(script.Parent.Parent.Parent.Parent.Promise)
local throttle = require(script.Parent.throttle)
local cooldowns = {}
local writeQueues = {}
local function throttleCooldown(methodName, dataStore, key, ...)
if cooldowns[dataStore] == nil then
cooldowns[dataStore] = {}
end
if cooldowns[dataStore][key] ~= nil then
cooldowns[dataStore][key]:await()
end
local ok, value = throttle(methodName, dataStore, key, ...)
-- TODO: Do we need the cooldown if throttle fails?
cooldowns[dataStore][key] = Promise.delay(Constants.WRITE_COOLDOWN):andThen(function()
cooldowns[dataStore][key] = nil
end)
return ok, value
end
local function startWriteQueue(dataStore, key, initialWrite)
local writeQueue = { initialWrite }
writeQueues[dataStore][key] = writeQueue
coroutine.wrap(function()
while #writeQueue > 0 do
local write = table.remove(writeQueue, 1)
write.ok, write.value = throttleCooldown(write.methodName, dataStore, key, unpack(write.arguments))
write.resolved = true
coroutine.resume(write.thread)
end
writeQueues[dataStore][key] = nil
end)()
end
local function queueWrite(dataStore, key, write)
if writeQueues[dataStore][key] == nil then
startWriteQueue(dataStore, key, write)
else
table.insert(writeQueues[dataStore][key], write)
end
end
local function throttleWrite(methodName, dataStore, key, ...)
if writeQueues[dataStore] == nil then
writeQueues[dataStore] = {}
end
local arguments = { ... }
local write = {
methodName = methodName,
arguments = arguments,
thread = coroutine.running(),
resolved = false,
}
queueWrite(dataStore, key, write)
if not write.resolved then
coroutine.yield()
end
return write.ok, write.value
end
return throttleWrite
|
forest_mite = Creature:new {
objectName = "@mob/creature_names:forest_mite",
socialGroup = "mite",
faction = "",
level = 14,
chanceHit = 0.3,
damageMin = 160,
damageMax = 170,
baseXp = 714,
baseHAM = 2000,
baseHAMmax = 2400,
armor = 0,
resists = {0,0,0,0,0,0,0,-1,-1},
meatType = "meat_insect",
meatAmount = 5,
hideType = "hide_scaley",
hideAmount = 4,
boneType = "",
boneAmount = 0,
milk = 0,
tamingChance = 0.25,
ferocity = 0,
pvpBitmask = ATTACKABLE,
creatureBitmask = PACK,
optionsBitmask = AIENABLED,
diet = CARNIVORE,
templates = {"object/mobile/bark_mite_hue.iff"},
hues = { 0, 1, 2, 3, 4, 5, 6, 7 },
controlDeviceTemplate = "object/intangible/pet/bark_mite_hue.iff",
lootGroups = {},
weapons = {"creature_spit_small_yellow"},
conversationTemplate = "",
attacks = {
{"",""},
{"stunattack",""}
}
}
CreatureTemplates:addCreatureTemplate(forest_mite, "forest_mite")
|
local ADDON, Addon = ...
local Util = Addon.Util
local function eventHandlerSystem(self, event, msg)
local ROLL_REGEX = RANDOM_ROLL_RESULT
ROLL_REGEX = gsub(ROLL_REGEX, "%(", "%%(")
ROLL_REGEX = gsub(ROLL_REGEX, "%-", "%%-")
ROLL_REGEX = gsub(ROLL_REGEX, "%)", "%%)")
ROLL_REGEX = gsub(ROLL_REGEX, "%%1%$s", "(.+)")
ROLL_REGEX = gsub(ROLL_REGEX, "%%1%$s", "(.+)")
ROLL_REGEX = gsub(ROLL_REGEX, "%%2%$d", "(%%d+)")
ROLL_REGEX = gsub(ROLL_REGEX, "%%3%$d", "(%%d+)")
ROLL_REGEX = gsub(ROLL_REGEX, "%%4%$d", "(%%d+)")
local name, roll, minRoll, maxRoll = msg:match(ROLL_REGEX)
roll, minRoll, maxRoll = tonumber(roll), tonumber(minRoll), tonumber(maxRoll)
if name and roll and minRoll and maxRoll then
Util.dbgprint (name .. " " .. roll .. " range: " .. minRoll .. " - " .. maxRoll);
table.insert(self.rolls, HereticRoll:New(Util.CompleteUnitName(name), roll, maxRoll))
PlaySound(SOUNDKIT.UI_BONUS_LOOT_ROLL_START);
PlaySound(SOUNDKIT.UI_BONUS_LOOT_ROLL_END);
HereticRollCollectorFrame_Update(self)
end
end
local function eventHandler(self, event, ...)
if (event == "CHAT_MSG_SYSTEM") then
eventHandlerSystem(self, event, ...)
end
end
function HereticRollFrame_SetRoll(rollFrame, roll, showDropTarget)
if not rollFrame then return end
if not roll and not showDropTarget == true then
rollFrame:Hide()
return
end
rollFrame.roll = roll
local nameText = _G[rollFrame:GetName() .. "Name"]
local rollText = _G[rollFrame:GetName() .. "Roll"]
local itemCountText = _G[rollFrame:GetName() .. "ItemCount"]
local slotText = _G[rollFrame:GetName() .. "SlotText"]
if roll then
nameText:SetText(HereticRaidInfo:GetColoredPlayerName(roll.name))
nameText:Show()
rollText:SetText(""..roll.roll)
rollText:SetTextColor(roll:GetColor())
rollText:Show()
local count = Addon:CountLootFor(roll.name)
itemCountText:SetText(Util.formatLootCount(count))
itemCountText:Show()
slotText:Hide()
else
rollText:Hide()
nameText:Hide()
itemCountText:Hide()
slotText:Show()
end
rollFrame:Show()
end
function HereticRollCollectorFrame_Update(self, ...)
local scrollBarName = self:GetName().."ScrollBar"
local scrollBar = _G[scrollBarName]
local numRolls = #self.rolls
FauxScrollFrame_Update(scrollBar, numRolls, 8, 20,
self:GetName() .. "RollFrame", 170, 190);
local offset = FauxScrollFrame_GetOffset(scrollBar)
if (Addon.lootOrder and Addon:lootOrder() == Addon.LOOT_ORDER_LOOT_RECEIVED_HIGHEST_ROLL) then
table.sort(self.rolls, HereticRoll.CompareWithLootCount)
else
table.sort(self.rolls, HereticRoll.Compare)
end
for id=1,8 do
local rollFrameName = self:GetName() .. "RollFrame" .. id
local rollFrame = _G[rollFrameName]
HereticRollFrame_SetRoll(rollFrame, self.rolls[id+offset])
end
end
function HereticRollCollectorFrame_Toggle(self)
if self:IsVisible() then
self:Hide()
else
HereticRollCollectorFrame_Update(self)
self:Show()
end
end
function HereticRollCollectorFrame_BeginRollCollection(self, entry)
if (self.entry == entry) then
return -- Don't start a new collection with the same item.
end
wipe(self.rolls)
self.entry = entry
HereticRollCollectorFrame_Update(self)
end
function HereticRollCollectorFrame_HereticOnDrop(self, button)
if Util.table_contains(self.rolls, button.roll) then
return
end
table.insert(self.rolls, button.roll)
HereticRollCollectorFrame_Update(self)
end
function HereticRollCollectorFrame_OnLoad(self)
self.rolls = {}
self:RegisterForDrag("LeftButton");
self:SetScript("OnEvent", eventHandler);
self:RegisterEvent("CHAT_MSG_SYSTEM");
HereticRollCollectorFrame_Update(self)
self.Toggle = HereticRollCollectorFrame_Toggle
HereticRollCollectorFrame.HereticOnDrop = HereticRollCollectorFrame_HereticOnDrop
end
function RollsScrollBar_Update(self)
HereticRollCollectorFrame_Update(self:GetParent())
end
function HereticRollCollectorFrame_OnUpdate(self, elapsed)
end
function HereticRollCollectorFrame_OnDragStart()
HereticRollCollectorFrame:StartMoving();
end
function HereticRollCollectorFrame_OnDragStop()
HereticRollCollectorFrame:StopMovingOrSizing();
end
function HereticRollFrame_OnDragStart(button)
if (not button.roll or not Addon:CanModify()) then return end
local cursorX, cursorY = GetCursorPosition();
local uiScale = UIParent:GetScale();
button:SetAlpha(.5);
HereticRollDragFrame:SetParent(button:GetParent());
HereticRollDragFrame:SetPoint("CENTER", UIPARENT, "BOTTOMLEFT",
cursorX / uiScale, cursorY / uiScale);
HereticRollDragFrame:StartMoving();
HereticRollDragFrame:ClearAllPoints();
HereticRollFrame_SetRoll(HereticRollDragFrame, button.roll)
if button.HereticOnDragStart then button:HereticOnDragStart(HereticRollDragFrame) end
HereticRollDragFrame:Show()
end
function HereticRollFrame_OnDragStop(button)
if not button.roll or not Addon:CanModify() then return end
local dropFrame = HereticLootmasterFrame:GetItemAtCursor()
local data = nil
if dropFrame and dropFrame.HereticOnDrop then
data = dropFrame:HereticOnDrop(button)
end
if button.HereticOnDragStop then
button:HereticOnDragStop(HereticRollDragFrame, data)
end
button:SetAlpha(1.0);
HereticRollDragFrame:StopMovingOrSizing();
HereticRollDragFrame:ClearAllPoints();
HereticRollDragFrame:Hide();
HereticRollDragFrame:SetUserPlaced(false);
end
function HereticRollFrame_OnClick(button)
if button.HereticOnRightClick then
button:HereticOnRightClick()
end
end
ROLL_BACKDROP = {
bgFile = "Interface\\Tooltips\\UI-Tooltip-Background",
edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border",
tile = true,
tileEdge = true,
tileSize = 8,
edgeSize = 12,
insets = { left = 1, right = 1, top = 1, bottom = 1 },
};
ROLL_BACKDROP_FONT_COLOR = CreateColor(0.0, 0.0, 0.0);
ROLL_BACKDROP_BORDER_COLOR = CreateColor(0, 0, 0);
|
---@class CS.UnityEngine.JointDrive : CS.System.ValueType
---@field public positionSpring number
---@field public positionDamper number
---@field public maximumForce number
---@type CS.UnityEngine.JointDrive
CS.UnityEngine.JointDrive = { }
return CS.UnityEngine.JointDrive
|
local _ENV = mkmodule('plugins.fortplan')
require('dfhack.buildings')
function construct_building_from_params(building_type, x, y, z)
local pos = xyz2pos(x, y, z)
local bld, err =
dfhack.buildings.constructBuilding{type=building_type, pos=pos}
if err then error(err) end
return bld
end
return _ENV
|
data:extend({
{
type = "gun",
name = "heli-flamethrower",
icon = "__base__/graphics/icons/flamethrower.png",
icon_size = 64,
flags = {"hidden"},
subgroup = "gun",
order = "a[basic-clips]-b[tank-machine-gun]-c[flamethrower-ammo]",
attack_parameters =
{
type = "stream",
ammo_category = "flamethrower",
cooldown = 1,
movement_slow_down_factor = 0.4,
damage_modifier = settings.startup["heli-flamethrower-damage-modifier"].value,
gun_barrel_length = 0.8,
gun_center_shift = { 0, -1 },
range = 50,
min_range = 3,
cyclic_sound =
{
begin_sound =
{
{
filename = "__base__/sound/fight/flamethrower-start.ogg",
volume = 0.7
}
},
middle_sound =
{
{
filename = "__base__/sound/fight/flamethrower-mid.ogg",
volume = 0.7
}
},
end_sound =
{
{
filename = "__base__/sound/fight/flamethrower-end.ogg",
volume = 0.7
}
}
}
},
stack_size = 1
}
})
|
--[[
This module is invoked as part of the building of the monolith.
It should be invoked as such:
<lua-program> file1 file2 ... fileN
It will write the processed lua code to standard output. The order
is preserved.
]]
local strings = require('strings')
local tables = require('tables')
local moduleTemplate = strings.template.compile[[
--- BEGIN:(%[module])
export.%[module] = (function ()
%[sourceCode]
end)()
--- END:(%[module])
]]
local args = {...}
for i, modname in ipairs(args) do
local f = assert(io.open(modname..'.lua'))
local luaCode = f:read('*a')
-- special case for debugger, because it should be lazy.
if modname == 'debugger' then
luaCode = strings.template.interpolate([[return function ()
%[sourceCode]
end]], {sourceCode = luaCode})
end
local output = moduleTemplate {
module = modname;
sourceCode = luaCode;
}
f:close()
print(output)
end
|
return require('packer').startup(function(use)
-- Packer can manage itself
use 'wbthomason/packer.nvim'
-- a start screen of vim or nvim
use 'mhinz/vim-startify'
-- animatial statusline
use 'windwp/windline.nvim'
-- treesitter
use { 'nvim-treesitter/nvim-treesitter', run = ':TSUpdate' }
-- which-key
use 'folke/which-key.nvim'
-- telescope
use 'nvim-lua/popup.nvim'
use 'nvim-lua/plenary.nvim'
use { 'nvim-telescope/telescope.nvim', requires = { {'nvim-lua/plenary.nvim'} } }
-- lspconfig
use 'neovim/nvim-lspconfig'
use 'williamboman/nvim-lsp-installer'
-- rust-tools
use 'simrat39/rust-tools.nvim'
-- nvim-cmp
use 'hrsh7th/cmp-nvim-lsp'
use 'hrsh7th/cmp-buffer'
use 'hrsh7th/cmp-path'
use 'hrsh7th/cmp-cmdline'
use 'hrsh7th/nvim-cmp'
use 'hrsh7th/cmp-vsnip'
-- vsnip
use 'hrsh7th/vim-vsnip'
use "rafamadriz/friendly-snippets"
-- use 'nvim-autopairs'
use "windwp/nvim-autopairs"
-- nvim-tree
use {
'kyazdani42/nvim-tree.lua',
requires = 'kyazdani42/nvim-web-devicons',
}
-- bufferline
use {'akinsho/bufferline.nvim', requires = 'kyazdani42/nvim-web-devicons'}
-- surround
use "blackCauldron7/surround.nvim"
-- Comment
use 'numToStr/Comment.nvim'
-- nvim-coloizer
use 'norcalli/nvim-colorizer.lua'
-- gruvbox theme
use {"ellisonleao/gruvbox.nvim", requires = {"rktjmp/lush.nvim"}}
-- lua edit
use 'euclidianAce/BetterLua.vim'
use 'tjdevries/manillua.nvim'
-- easy motion
use 'easymotion/vim-easymotion'
-- highlight word under your cursor
use 'RRethy/vim-illuminate'
-- youdao dictionary
use 'ianva/vim-youdao-translater'
-- markdown preview
use {'iamcco/markdown-preview.nvim', run = 'cd app && yarn install', cmd = 'MarkdownPreview'}
-- fish edit
use 'dag/vim-fish'
-- nix support
use 'LnL7/vim-nix'
end)
|
--[[ Divided Maze ]]
ROT=require 'src.rot'
function love.load()
f =ROT.Display(80,24)
dm=ROT.Map.DividedMaze:new(f:getWidth(), f:getHeight())
dm:create(calbak)
end
function love.draw() f:draw() end
local update=false
function love.update()
if update then
update=false
dm:create(calbak)
end
end
function calbak(x,y,val)
f:write(val==1 and '#' or '.', x, y)
end
function love.keypressed(key) update=true end
|
-- Utility Table functions
-- This Library is not for a bunch of for-loop wrapper functions.
-- Either write your own for-loops or learn python instead
-- @author Validark
local Resources = require(game:GetService("ReplicatedStorage"):WaitForChild("Resources"))
local Table = {}
function Table.Move(a1, f, e, t, a2)
-- Moves elements [f, e] from array a1 into a2 starting at index t
-- Equivalent to Lua 5.3's table.move
-- @param table a1 from which to draw elements from range
-- @param number f starting index for range
-- @param number e ending index for range
-- @param number t starting index to move elements from a1 within [f, e]
-- @param table a2 the second table to move these elements to
-- @default a2 = a1
-- @returns a2
a2 = a2 or a1
t = t + e
for i = e, f, -1 do
t = t - 1
a2[t] = a1[i]
end
return a2
end
function Table.Lock(t)
-- Returns interface proxy which can read from table t but cannot modify it
local ModuleName = getfenv(2).script.Name
local Userdata = newproxy(true)
local Metatable = getmetatable(Userdata)
function Metatable:__index(Index)
return t[Index] or Resources:LoadLibrary("Debug").Error("!%q does not exist in read-only table", ModuleName, Index)
end
function Metatable:__newindex(Index, Value)
Resources:LoadLibrary("Debug").Error("!Cannot write %s to index [%q] of read-only table", ModuleName, Value, Index)
end
Metatable.__metatable = "[" .. ModuleName .. "] Requested metatable of read-only table is locked"
return Userdata
end
return Table.Lock(Table)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.