content
stringlengths 5
1.05M
|
---|
BigXD = Enemy:extend("BigXD")
function BigXD:new(...)
BigXD.super.new(self, ...)
self:setImage("enemies/big_xd")
self.SFX.laugh = SFX("sfx/laughing", 1)
self:addIgnoreOverlap(SolidTile)
self.rotate = .8
self.floating = true
self.velocity.x = 0
self.floorHeight = 32
self.x = self.x - 500
self.solid = 0
self.z = -1000
self.size = 250
end
function BigXD:update(dt)
BigXD.super.update(self, dt)
if self.velocity.x > 0 then
local sfx = self.scene:playSFX(self.SFX.laugh)
if sfx then self.lastLaugh = sfx end
end
if self.lastLaugh then
self.lastLaugh:setVolume(math.max(0, 1 - (self:getDistance(self.scene.timon)/800)))
end
if self.y > self.floorHeight then
self.y = self.floorHeight
end
if self:getDistance(self.scene.timon) < self.size then
if self.scene.timon.inControl and not self.scene.timon.dead then
Game:onDead()
end
end
end
function BigXD:draw()
BigXD.super.draw(self)
end
function BigXD:startMoving()
self.velocity.x = Player.speed - 5
end |
fontType = {-- (1)font (2)scale offset
["default"] = {"default", 1},
["default-bold"] = {"default-bold",1},
["clear"] = {"clear",1.1},
["arial"] = {"arial",1},
["sans"] = {"sans",1.2},
["pricedown"] = {"pricedown",3},
["bankgothic"] = {"bankgothic",4},
["diploma"] = {"diploma",2},
["beckett"] = {"beckett",2},
["BizNoteFont18"] = {"BizNoteFont18",1.1},
}
function getOverLayFonts()
return fontType
end
fonts = getOverLayFonts()
function options_enable()
--toggleControl("change_camera", false)
keys = getBoundKeys("change_camera")
--[[for name, state in pairs(keys) do
if ( name ~= "home" ) then
bindKey(name, "down", options_cameraWorkAround)
else
unbindKey(name)
end
end]]
--addCommandHandler("home", options_showmenu)
--bindKey("F10", "down", "home")
end
addEventHandler("accounts:options",getRootElement(),options_enable)
function options_disable()
removeCommandHandler("home", options_showmenu)
unbindKey("home", "down", "home")
unbindKey("F10", "down", "home")
end
wOptions,bChangeCharacter,bStreamerSettings,bGraphicsSettings,bAccountSettings,bLogout = nil
wGraphicsMenu,cLogsEnabled,cMotionBlur,cSkyClouds,cStreamingAudio,bGraphicsMenuClose,sVehicleStreamer,sPickupStreamer,lVehicleStreamer,lPickupStreamer,gameMenuLoaded = nil
function isCameraOnPlayer()
local vehicle = getPedOccupiedVehicle(localPlayer)
if vehicle then
return getCameraTarget( ) == vehicle
else
return getCameraTarget( ) == localPlayer
end
end
function options_showmenu()
if wOptions then
options_closemenu()
return
end
if getElementData(localPlayer, "exclusiveGUI") or not isCameraOnPlayer() then
return
end
triggerEvent( 'hud:blur', resourceRoot, 6, false, 0.5, nil )
setElementData(localPlayer, "exclusiveGUI", true, false)
triggerEvent("account:changingchar", localPlayer)
local screenWidth, screenHeight = guiGetScreenSize()
local windowWidth, windowHeight = 250, 15
local bHeight = 35
windowHeight = windowHeight+(bHeight*5)
local left = screenWidth/2 - windowWidth/2
local top = screenHeight/2 - windowHeight/2
local margin = 10
local wHeight = margin
showCursor(true)
wOptions = guiCreateStaticImage(left, top, windowWidth, windowHeight, ":mrp_resources/window_body.png", false)
bChangeCharacter = guiCreateButton(margin, margin, 230, 30, "Karakter değiştir", false, wOptions)
addEventHandler("onClientGUIClick", bChangeCharacter,
function ()
if not isPedDead ( localPlayer ) and isCameraOnPlayer() then
options_logOut( )
end
options_closemenu()
end, false)
wHeight = wHeight + bHeight
bStatistics = guiCreateButton(margin, wHeight, 230, 30, "Karakter istatislikleri", false, wOptions)
addEventHandler("onClientGUIClick", bStatistics,
function ()
if not isPedDead ( localPlayer ) and isCameraOnPlayer() then
triggerServerEvent("showStats", localPlayer,localPlayer)
end
options_closemenu()
end, false)
wHeight = wHeight + bHeight
bGraphicsSettings = guiCreateButton(margin, wHeight, 230, 30, "Ayarlar", false, wOptions)
--addEventHandler("onClientGUIClick", bGraphicsSettings, options_opengraphicsmenu, false)
addEventHandler("onClientGUIClick", bGraphicsSettings,
function ()
if not isPedDead ( localPlayer ) and isCameraOnPlayer() then
--triggerServerEvent("accounts:settings:fetchSettings", localPlayer)
showSettingsWindow()
end
end, false)
wHeight = wHeight + bHeight
if getResourceFromName("mrp_admins") and exports['mrp_admins']:canPlayerAccessStaffManager(localPlayer) then
bStaffManager = guiCreateButton(margin, wHeight, 230, 30, "Personel Ayarları", false, wOptions)
addEventHandler("onClientGUIClick", bStaffManager,
function ()
if not isPedDead ( localPlayer ) and isCameraOnPlayer() then
executeCommandHandler("staffs")
end
options_closemenu()
end, false)
wHeight = wHeight + bHeight
end
if getResourceFromName("mrp_factions") and exports.mrp_factions:canAccessFactionManager( localPlayer ) then
bFactionManager = guiCreateButton(margin, wHeight, 230, 30, "Birlik Ayarları", false, wOptions)
addEventHandler("onClientGUIClick", bFactionManager,
function ()
if not isPedDead ( localPlayer ) and isCameraOnPlayer() then
executeCommandHandler("factions")
end
options_closemenu()
end, false)
wHeight = wHeight + bHeight
end
if getResourceFromName("mrp_interiors") and getResourceFromName("mrp_interior_manager") and exports.mrp_integration:isPlayerAdmin( localPlayer ) then
bInteriorManager = guiCreateButton(margin, wHeight, 230, 30, "Mülk Ayarları", false, wOptions)
addEventHandler("onClientGUIClick", bInteriorManager,
function ()
if not isPedDead ( localPlayer ) and isCameraOnPlayer() then
triggerServerEvent("interiorManager:openit", localPlayer, localPlayer)
end
options_closemenu()
end, false)
wHeight = wHeight + bHeight
end
if getResourceFromName("mrp_vehicle") and getResourceFromName("mrp_vehicle_manager") and exports.mrp_vehicle_manager:canAccessVehicleManager( localPlayer ) then
bVehicleManager = guiCreateButton(margin, wHeight, 230, 30, "Araç Aayaralrı", false, wOptions)
addEventHandler("onClientGUIClick", bVehicleManager,
function ()
if not isPedDead ( localPlayer ) and isCameraOnPlayer() then
executeCommandHandler("vehs")
end
options_closemenu()
end, false)
wHeight = wHeight + bHeight
end
if getResourceFromName('mrp_vehicle') and getResourceFromName("mrp_vehicle_manager") then
local thePlayer = localPlayer
if exports.mrp_integration:isPlayerVCTMember(thePlayer) or exports.mrp_integration:isPlayerSupporter(thePlayer) or exports.mrp_integration:isPlayerTrialAdmin(thePlayer) or exports.mrp_integration:isPlayerScripter(thePlayer) or exports.mrp_integration:isPlayerVehicleConsultant(thePlayer) then
bVehicleLib = guiCreateButton(margin, wHeight, 230, 30, "Araç Kütüphanesi", false, wOptions)
addEventHandler("onClientGUIClick", bVehicleLib,
function ()
if not isPedDead ( localPlayer ) and isCameraOnPlayer() then
triggerServerEvent("vehlib:sendLibraryToClient", localPlayer)
end
options_closemenu()
end, false)
wHeight = wHeight + bHeight
end
end
if getResourceFromName("mrp_carradio") then
bRadioManager = guiCreateButton(margin, wHeight, 230, 30, "Radyo İstasyonu Ayarları", false, wOptions)
addEventHandler("onClientGUIClick", bRadioManager,
function ()
if not isPedDead ( localPlayer ) and isCameraOnPlayer() then
executeCommandHandler("radios")
end
options_closemenu()
end, false)
wHeight = wHeight + bHeight
end
bLogout = guiCreateButton(margin, wHeight, 230, 30, "Çıkış", false, wOptions)
addEventHandler("onClientGUIClick", bLogout,
function ()
if not isPedDead ( localPlayer ) and isCameraOnPlayer() then
fadeCamera ( false, 2, 0,0,0 )
setTimer(function()
triggerServerEvent("accounts:settings:reconnectPlayer", localPlayer)
end, 2000,1)
end
options_closemenu()
end, false)
wHeight = wHeight + bHeight
bClose = guiCreateButton(margin, wHeight, 230, 30, "Kapat", false, wOptions)
addEventHandler("onClientGUIClick", bClose, options_closemenu, false)
wHeight = wHeight + bHeight
guiSetSize(wOptions, windowWidth, wHeight+margin/2, false)
exports.mrp_global:centerWindow(wOptions)
end
function options_closemenu()
options_closegraphicsmenu()
closeSettingsWindow()
showCursor(false)
if wOptions then
destroyElement(wOptions)
wOptions = nil
end
setElementData(localPlayer, "exclusiveGUI", false, false)
triggerEvent( 'hud:blur', resourceRoot, 'off' )
end
function options_cameraWorkAround()
setPedControlState(localPlayer, "change_camera", true)
end
--MAXIME
function options_opengraphicsmenu()
gameMenuLoaded = false
local screenWidth, screenHeight = guiGetScreenSize()
local windowWidth, windowHeight = 200, 350+17
local left = screenWidth/2 - windowWidth/2
local top = screenHeight/2 - windowHeight/2
local enable = 1
guiSetEnabled(wOptions, false)
wGraphicsMenu = guiCreateWindow(left, top, windowWidth, windowHeight, "Oyun Ayarları", false)
guiWindowSetSizable(wGraphicsMenu, false)
----------
cMotionBlur = guiCreateCheckBox(10, 25, 180, 17, "Motion Blur'u aktifleştir", false, false, wGraphicsMenu)
addEventHandler("onClientGUIClick", cMotionBlur, options_updateGameConfig)
-----------
cSkyClouds = guiCreateCheckBox(10, 45, 180, 17, "Gökyüzü Efektlerini aktifleştir", false, false, wGraphicsMenu)
addEventHandler("onClientGUIClick", cSkyClouds, options_updateGameConfig)
------------
cStreamingAudio = guiCreateCheckBox(10, 65, 180, 17, "Enable streaming audio", false, false, wGraphicsMenu)
addEventHandler("onClientGUIClick", cStreamingAudio, options_updateGameConfig)
bOverlayDescription = guiCreateButton ( 10, 85, 180, 17*2, "Overlay Description Settings", false, wGraphicsMenu )
addEventHandler("onClientGUIClick", bOverlayDescription, overlayDescSettings)
--[[lVehicleStreamer = guiCreateCheckBox ( 10, 95, 180, 17, "Vehicle streamer: Disabled", false, false, wGraphicsMenu )
addEventHandler("onClientGUIClick", lVehicleStreamer, options_updateGameConfig)
sVehicleStreamer = guiCreateScrollBar(10, 110, 180, 17, true, false, wGraphicsMenu)
addEventHandler("onClientGUIScroll", sVehicleStreamer, options_GameConfig_updateScrollbars)
lPickupStreamer = guiCreateCheckBox ( 10, 125, 180, 17, "Interior streamer: Disabled", false, false, wGraphicsMenu )
addEventHandler("onClientGUIClick", lPickupStreamer, options_updateGameConfig)
sPickupStreamer = guiCreateScrollBar(10, 140, 180, 17, true, false, wGraphicsMenu)
addEventHandler("onClientGUIScroll", sPickupStreamer, options_GameConfig_updateScrollbars)]]
cLogsEnabled = guiCreateCheckBox(10, 160, 180, 17, "Logging of chat", false, false, wGraphicsMenu)
addEventHandler("onClientGUIClick", cLogsEnabled, options_updateGameConfig)
cBubblesEnabled = guiCreateCheckBox(10, 180, 180, 17, "Enable Chat bubbles", false, false, wGraphicsMenu)
addEventHandler("onClientGUIClick", cBubblesEnabled, options_updateGameConfig)
cIconsEnabled = guiCreateCheckBox(10, 200, 180, 17, "Enable typing icons", false, false, wGraphicsMenu)
addEventHandler("onClientGUIClick", cIconsEnabled, options_updateGameConfig)
cEnableNametags = guiCreateCheckBox(10, 220, 180, 17, "Enable nametags", false, false, wGraphicsMenu)
addEventHandler("onClientGUIClick", cEnableNametags, options_updateGameConfig)
cEnableRShaders = guiCreateCheckBox(10, 240, 180, 17, "Enable radar shader", false, false, wGraphicsMenu)
addEventHandler("onClientGUIClick", cEnableRShaders, options_updateGameConfig)
cEnableWShaders = guiCreateCheckBox(10, 260, 180, 17, "Enable water shader", false, false, wGraphicsMenu)
addEventHandler("onClientGUIClick", cEnableWShaders, options_updateGameConfig)
cEnableVShaders = guiCreateCheckBox(10, 280, 180, 17, "Enable vehicle shader", false, false, wGraphicsMenu)
addEventHandler("onClientGUIClick", cEnableVShaders, options_updateGameConfig)
--[[
chatbubbles
]]
-- Put the current settings selected/active
--[[local vehicleStreamerEnabled = tonumber( loadSavedData("streamer-vehicle-enabled", "1") )
if (vehicleStreamerEnabled) then
guiCheckBoxSetSelected ( lVehicleStreamer, true )
end
local pickupStreamerEnabled = tonumber( loadSavedData("streamer-pickup-enabled", "1") )
if (pickupStreamerEnabled) then
guiCheckBoxSetSelected ( lPickupStreamer, true )
end]]
local blurEnabled = tonumber( loadSavedData("motionblur", "1") )
if (blurEnabled == 1) then
guiCheckBoxSetSelected ( cMotionBlur, true )
end
local skyCloudsEnabled = tonumber( loadSavedData("skyclouds", "1") )
if (skyCloudsEnabled == 1) then
guiCheckBoxSetSelected ( cSkyClouds, true )
end
local streamingMediaEnabled = tonumber( loadSavedData("streamingmedia", "1") )
if (streamingMediaEnabled == 1) then
guiCheckBoxSetSelected ( cStreamingAudio, true )
end
local logsEnabled = tonumber( loadSavedData("logsenabled", "1") )
if (logsEnabled == 1) then
guiCheckBoxSetSelected ( cLogsEnabled, true )
end
--[[local vehicleStreamerStatus = tonumber( loadSavedData("streamer-vehicle", "60") )
if (vehicleStreamerStatus) then
guiScrollBarSetScrollPosition(sVehicleStreamer, ((vehicleStreamerStatus-40)/2))
end
local pickupStreamerStatus = tonumber( loadSavedData("streamer-pickup", "25") )
if (pickupStreamerStatus) then
guiScrollBarSetScrollPosition(sPickupStreamer, (pickupStreamerStatus-10))
end]]
local isBubblesEnabled = tonumber( loadSavedData("chatbubbles", "1") )
if (isBubblesEnabled == 1) then
guiCheckBoxSetSelected ( cBubblesEnabled, true )
end
local isChatIconsEnabled = tonumber( loadSavedData("chaticons", "1") )
if (isChatIconsEnabled == 1) then
guiCheckBoxSetSelected ( cIconsEnabled, true )
end
local isNameTagsEnabled = tonumber( loadSavedData("shownametags", "1") )
if (isNameTagsEnabled == 1) then
guiCheckBoxSetSelected ( cEnableNametags, true )
end
local isRShaderEnabled = tonumber( loadSavedData( "enable_radar_shader", "1") )
if isRShaderEnabled == 1 then
guiCheckBoxSetSelected ( cEnableRShaders, true )
end
local isWShaderEnabled = tonumber( loadSavedData( "enable_water_shader", "1") )
if isWShaderEnabled == 1 then
guiCheckBoxSetSelected ( cEnableWShaders, true )
end
local isVShaderEnabled = tonumber( loadSavedData( "enable_vehicle_shader", "1") )
if isVShaderEnabled == 1 then
guiCheckBoxSetSelected ( cEnableVShaders, true )
end
gameMenuLoaded = true
--options_GameConfig_updateScrollbars()
bGraphicsMenuClose = guiCreateButton(10, 320, 490, 17*2, "Close", false, wGraphicsMenu)
addEventHandler("onClientGUIClick", bGraphicsMenuClose, options_closegraphicsmenu, false)
end
--[[function options_GameConfig_updateScrollbars()
if (gameMenuLoaded) then
local vehicleStreamerStatus = guiScrollBarGetScrollPosition(sVehicleStreamer)
vehicleStreamerStatus = ((vehicleStreamerStatus) * 2) + 40
local pickupStreamerStatus = guiScrollBarGetScrollPosition(sPickupStreamer)
pickupStreamerStatus = pickupStreamerStatus + 10
guiSetText(lVehicleStreamer, "Vehicle streamer: "..vehicleStreamerStatus.." meter")
guiSetText(lPickupStreamer, "Interior streamer: "..pickupStreamerStatus.." meter")
appendSavedData("streamer-vehicle", tostring(vehicleStreamerStatus))
appendSavedData("streamer-pickup", tostring(pickupStreamerStatus))
triggerEvent("accounts:settings:loadGraphicSettings", localPlayer)
end
end]]
--MAXIME
function overlayDescSettings(button, state)
if source == bOverlayDescription then
if wOverlayDescSettings then
fCloseOverlayDescSettings()
else
local screenWidth, screenHeight = guiGetScreenSize()
local windowWidth, windowHeight = 350, 40+(20*15)
local left = screenWidth/2 - windowWidth/2
local top = screenHeight/2 - windowHeight/2
local enable = 1
guiSetEnabled(wOptions, false)
guiSetEnabled(wGraphicsMenu, false)
wOverlayDescSettings = guiCreateWindow(left, top, windowWidth, windowHeight, "Overlay Description Options", false)
guiWindowSetSizable(wOverlayDescSettings, false)
----------
local y = 0
local lane1w = 230
local lane1x = 10
local lane2w = lane1w + lane1x
local lane2x = lane1x*2 + lane1w
cEnableDescription = guiCreateCheckBox(10, 25+y, lane1w, 17, "Enable All Overlay Description", true, false, wOverlayDescSettings)
addEventHandler("onClientGUIClick", cEnableDescription, options_updateGameConfig)
enable = tonumber( loadSavedData("enableOverlayDescription", "1") or 1)
guiCheckBoxSetSelected ( cEnableDescription, enable == 1 and true or false)
guiCreateStaticImage ( 10, 25+y+23, windowWidth-20 , 1, ":admin-system/images/whitedot.jpg", false, wOverlayDescSettings )
y = y + 30
cEnableDescriptionVeh = guiCreateCheckBox(10, 25+y, lane1w, 17, "Enable Overlay Description (Vehicle)", true, false, wOverlayDescSettings)
addEventHandler("onClientGUIClick", cEnableDescriptionVeh, options_updateGameConfig)
enable = tonumber( loadSavedData("enableOverlayDescriptionVeh", "1") or 1 )
guiCheckBoxSetSelected ( cEnableDescriptionVeh, enable == 1 and true or false)
cEnableDescriptionVehPin = guiCreateCheckBox(lane2x, 25+y, lane2w, 17, "Pin", false, false, wOverlayDescSettings)
addEventHandler("onClientGUIClick", cEnableDescriptionVehPin, options_updateGameConfig)
enable = tonumber( loadSavedData("enableOverlayDescriptionVehPin", "1") or 1 )
guiCheckBoxSetSelected ( cEnableDescriptionVehPin, enable == 1 and true or false)
y = y + 20
lFontVeh = guiCreateLabel ( 10, 25+y+3, 40, 20, "Font:", false, wOverlayDescSettings )
cFontVeh = guiCreateComboBox ( 10+40, 25+y, lane1w, 20, loadSavedData2("cFontVeh") or "default", false, wOverlayDescSettings )
local count1 = 0
for key, font in pairs(fonts) do
guiComboBoxAddItem(cFontVeh, type(font[1]) == "string" and font[1] or "BizNoteFont18")
count1 = count1 + 1
end
guiComboBoxAdjustHeight ( cFontVeh, count1 )
addEventHandler ( "onClientGUIComboBoxAccepted", guiRoot,
function ( comboBox )
if ( comboBox == cFontVeh ) then
local item = guiComboBoxGetSelected ( cFontVeh )
local text = tostring ( guiComboBoxGetItemText ( cFontVeh , item ) )
if ( text ~= "" ) then
appendSavedData("cFontVeh", text)
end
end
end
)
y = y + 20 + 5
bgVeh = guiCreateCheckBox ( 10, 25+y+3, 150, 17, "Enable Background", true, false, wOverlayDescSettings )
enable = tonumber( loadSavedData("bgVeh", "1") or 1 )
guiCheckBoxSetSelected ( bgVeh, enable == 1 and true or false)
borderVeh = guiCreateCheckBox ( 10+150, 25+y+3, 150, 17, "Enable Border", true, false, wOverlayDescSettings )
enable = tonumber( loadSavedData("borderVeh", "1") or 1)
guiCheckBoxSetSelected ( borderVeh, enable == 1 and true or false)
addEventHandler("onClientGUIClick", bgVeh, options_updateGameConfig)
addEventHandler("onClientGUIClick", borderVeh, options_updateGameConfig)
guiCreateStaticImage ( 10, 25+y+21, windowWidth-20 , 1, ":admin-system/images/whitedot.jpg", false, wOverlayDescSettings )
y = y + 40
cEnableOverlayDescriptionPro = guiCreateCheckBox(10, 25+y, lane1w, 17, "Enable Overlay Description (Property)", true, false, wOverlayDescSettings)
addEventHandler("onClientGUIClick", cEnableOverlayDescriptionPro, options_updateGameConfig)
enable = tonumber( loadSavedData("enableOverlayDescriptionPro", "1") or 1 )
guiCheckBoxSetSelected ( cEnableOverlayDescriptionPro, enable == 1 and true or false)
cEnableOverlayDescriptionProPin = guiCreateCheckBox(lane2x, 25+y, lane2w, 17, "Pin", false, false, wOverlayDescSettings)
addEventHandler("onClientGUIClick", cEnableOverlayDescriptionProPin, options_updateGameConfig)
enable = tonumber( loadSavedData("enableOverlayDescriptionProPin", "1") or 1 )
guiCheckBoxSetSelected ( cEnableOverlayDescriptionProPin, enable == 1 and true or false)
y = y + 20
lFontPro = guiCreateLabel ( 10, 25+y+3, 40, 20, "Font:", false, wOverlayDescSettings )
cFontPro = guiCreateComboBox ( 10+40, 25+y, lane1w, 20, loadSavedData2("cFontPro") , false, wOverlayDescSettings )
for key, font in pairs(fonts) do
guiComboBoxAddItem(cFontPro, type(font[1]) == "string" and font[1] or "BizNoteFont18")
end
guiComboBoxAdjustHeight ( cFontPro, count1 )
addEventHandler ( "onClientGUIComboBoxAccepted", guiRoot,
function ( comboBox )
if ( comboBox == cFontPro ) then
local item = guiComboBoxGetSelected ( cFontPro )
local text = tostring ( guiComboBoxGetItemText ( cFontPro , item ) )
if ( text ~= "" ) then
appendSavedData("cFontPro", text)
end
end
end
)
y = y + 20 + 5
bgPro = guiCreateCheckBox ( 10, 25+y+3, 150, 17, "Enable Background", true, false, wOverlayDescSettings )
enable = tonumber( loadSavedData("bgPro", "1") or 1 )
guiCheckBoxSetSelected ( bgPro, enable == 1 and true or false)
borderPro = guiCreateCheckBox ( 10+150, 25+y+3, 150, 17, "Enable Border", true,false, wOverlayDescSettings )
enable = tonumber( loadSavedData("borderPro", "1") or 1 )
guiCheckBoxSetSelected ( borderPro, enable == 1 and true or false)
addEventHandler("onClientGUIClick", bgPro, options_updateGameConfig)
addEventHandler("onClientGUIClick", borderPro, options_updateGameConfig)
guiCreateStaticImage ( 10, 25+y+21, windowWidth-20 , 1, ":admin-system/images/whitedot.jpg", false, wOverlayDescSettings )
y = y + 40
bCloseOverlayDescSettings = guiCreateButton(10, 70+y, windowWidth+34, 17*2, "Close", false, wOverlayDescSettings)
addEventHandler("onClientGUIClick", bCloseOverlayDescSettings, fCloseOverlayDescSettings, false)
end
end
end
--MAXIME--
function options_updateGameConfig()
if source == borderVeh then
appendSavedData("borderVeh", guiCheckBoxGetSelected(borderVeh) and "1" or "0")
end
if source == bgVeh then
appendSavedData("bgVeh", guiCheckBoxGetSelected(bgVeh) and "1" or "0")
end
if source == borderPro then
appendSavedData("borderPro", guiCheckBoxGetSelected(borderPro) and "1" or "0")
end
if source == bgPro then
appendSavedData("bgPro", guiCheckBoxGetSelected(bgPro) and "1" or "0")
end
if source == cEnableDescription then
appendSavedData("enableOverlayDescription", guiCheckBoxGetSelected(cEnableDescription) and "1" or "0")
end
if source == cEnableDescriptionVeh then
appendSavedData("enableOverlayDescriptionVeh", guiCheckBoxGetSelected(cEnableDescriptionVeh) and "1" or "0")
end
if source == cEnableDescriptionVehPin then
appendSavedData("enableOverlayDescriptionVehPin", guiCheckBoxGetSelected(cEnableDescriptionVehPin) and "1" or "0")
end
if source == cEnableOverlayDescriptionPro then
appendSavedData("enableOverlayDescriptionPro", guiCheckBoxGetSelected(cEnableOverlayDescriptionPro) and "1" or "0")
end
if source == cEnableOverlayDescriptionProPin then
appendSavedData("enableOverlayDescriptionProPin", guiCheckBoxGetSelected(cEnableOverlayDescriptionProPin) and "1" or "0")
end
if source == cMotionBlur then
if (guiCheckBoxGetSelected(cMotionBlur)) then
appendSavedData("motionblur", "1")
else
appendSavedData("motionblur", "0")
end
end
if source == cSkyClouds then
if (guiCheckBoxGetSelected(cSkyClouds)) then
appendSavedData("skyclouds", "1")
else
appendSavedData("skyclouds", "0")
end
end
if source == cStreamingAudio then
if (guiCheckBoxGetSelected(cStreamingAudio)) then
appendSavedData("streamingmedia", "1")
else
appendSavedData("streamingmedia", "0")
end
end
if source == cLogsEnabled then
if (guiCheckBoxGetSelected(cLogsEnabled)) then
appendSavedData("logsenabled", "1")
else
appendSavedData("logsenabled", "0")
end
end
--[[if (guiCheckBoxGetSelected(lPickupStreamer)) then
appendSavedData("streamer-pickup-enabled", "1")
else
appendSavedData("streamer-pickup-enabled", "0")
end
if (guiCheckBoxGetSelected(lVehicleStreamer)) then
appendSavedData("streamer-vehicle-enabled", "1")
else
appendSavedData("streamer-vehicle-enabled", "0")
end]]
if source == cBubblesEnabled then
if (guiCheckBoxGetSelected(cBubblesEnabled)) then
appendSavedData("chatbubbles", "1")
else
appendSavedData("chatbubbles", "0")
end
end
if source == cIconsEnabled then
if (guiCheckBoxGetSelected(cIconsEnabled)) then
appendSavedData("chaticons", "1")
else
appendSavedData("chaticons", "0")
end
end
if source == cEnableNametags then
if (guiCheckBoxGetSelected(cEnableNametags)) then
appendSavedData("shownametags", "1")
else
appendSavedData("shownametags", "0")
end
end
if source == cEnableRShaders then
appendSavedData("enable_radar_shader", guiCheckBoxGetSelected(cEnableRShaders) and "1" or "0")
end
if source == cEnableWShaders then
appendSavedData("enable_water_shader", guiCheckBoxGetSelected(cEnableWShaders) and "1" or "0")
end
if source == cEnableVShaders then
appendSavedData("enable_vehicle_shader", guiCheckBoxGetSelected(cEnableVShaders) and "1" or "0")
end
triggerEvent("accounts:settings:loadGraphicSettings", localPlayer)
end
--MAXIME
-- function percentageToLevel(percentage)
-- if percentage >= 0 and < 20 then
-- return "5"
-- elseif percentage >= 20 and < 40 then
-- return "10"
-- elseif percentage >= 40 and < 60 then
-- return "20"
-- elseif percentage >= 60 and < 80 then
-- return "40"
-- elseif percentage >= 80 and < 100 then
-- return "80"
-- else
-- return "160"
-- end
-- end
function guiComboBoxAdjustHeight ( combobox, itemcount )
if getElementType ( combobox ) ~= "gui-combobox" or type ( itemcount ) ~= "number" then error ( "Invalid arguments @ 'guiComboBoxAdjustHeight'", 2 ) end
local width = guiGetSize ( combobox, false )
return guiSetSize ( combobox, width, ( itemcount * 20 ) + 20, false )
end
function fCloseOverlayDescSettings()
if wOverlayDescSettings then
destroyElement(wOverlayDescSettings)
wOverlayDescSettings = nil
if wGraphicsMenu then
guiSetEnabled(wGraphicsMenu, true)
end
end
end
function options_closegraphicsmenu()
if wGraphicsMenu then
options_updateGameConfig()
destroyElement(wGraphicsMenu)
wGraphicsMenu = nil
end
fCloseOverlayDescSettings()
if wOptions then
guiSetEnabled(wOptions, true)
end
end
function options_logOut( message )
triggerServerEvent("updateCharacters", localPlayer)
triggerServerEvent("accounts:characters:change", localPlayer, "Change Character")
triggerEvent("onClientChangeChar", getRootElement())
options_disable()
Characters_showSelection()
clearChat()
--guiSetVisible(toggleSoundLabel, true)
if message then
LoginScreen_showWarningMessage( message )
end
end
addEventHandler("accounts:logout", getRootElement(), options_logOut)
function options_logOutToLoginPanel( message )
triggerServerEvent("accounts:characters:logout", localPlayer, "Change Character")
open_log_reg_pannel()
end
|
minetest.register_chatcommand("create_in_front_of_fayce", {
params = "<text>",
description = "Send text to chat",
privs = {},
func = function( name , text)
--print(name:get_player_by_name())
--minetest.chat_send_all(dump(minetest.get_player_by_name(name):get_look_dir()))
local pos = minetest.get_player_by_name(name):get_pos()
local vec = vector.multiply(minetest.get_player_by_name(name):get_look_dir(), 2)
pos = vector.add(vec, pos)
pos.y = pos.y + 1.625
minetest.add_item(pos, "default:dirt")
return true, "Test success"
end,
})
minetest.register_chatcommand("ex", {
params = "number",
description = "Send text to chat",
privs = {},
func = function( name , number)
local pos = minetest.get_player_by_name(name):get_pos()
for i = 1,number do
minetest.add_item({x=pos.x + math.random(-1.5,1.5)*math.random(),y=pos.y+1.5+math.random(1,5.5)*math.random(),z=pos.z + math.random(-1.5,1.5)*math.random()}, "default:dirt")
end
--minetest.add_item(pos, "default:dirt")
return true, "Test success"
end,
})
|
return setmetatable({}, {__index = function(self, key)
return require("skooma."..tostring(key))
end})
|
require("lib.recipes")
-- Loader Furnaces
data:extend({
add_furnace_recipe(
"lf-furnace-01",
{order = "a[loader-furnace]-a[01]", subgroup = "lf-furnace"},
{
{"loader", 2},
{"steel-plate", 50},
{"electric-furnace", 48},
{"electronic-circuit", 20},
{"iron-gear-wheel", 20},
{"iron-stick", 20}
}
),
add_furnace_recipe(
"lf-furnace-02",
{order = "a[loader-furnace]-b[02]", subgroup = "lf-furnace"},
{
{"fast-loader", 2},
{"steel-plate", 50},
{"lf-furnace-01", 2},
{"advanced-circuit", 5},
{"iron-gear-wheel", 20},
{"iron-stick", 20}
}
),
add_furnace_recipe(
"lf-furnace-03",
{category = "crafting-with-fluid", order = "a[loader-furnace]-c[03]", subgroup = "lf-furnace"},
{
{"express-loader", 2},
{"steel-plate", 50},
{"lf-furnace-02", 2},
{"advanced-circuit", 50},
{"iron-gear-wheel", 20},
{"iron-stick", 20},
{type = "fluid", name = "lubricant", amount = 120}
}
)
})
if data.raw.technology["bob-logistics-4"] then
data:extend({
add_furnace_recipe("lf-furnace-04", {category = "crafting-with-fluid", subgroup = "lf-furnace", order = "a[loader-furnace]-d[04]"},
{
{"purple-loader", 2},
{"steel-plate", 50},
{"lf-furnace-03", 2},
{"processing-unit", 10},
{"iron-gear-wheel", 20},
{"iron-stick", 20},
{type = "fluid", name = "lubricant", amount = 240}
}),
add_furnace_recipe("lf-furnace-05", {category = "crafting-with-fluid", subgroup = "lf-furnace", order = "a[loader-furnace]-e[05]"},
{
{"green-loader", 2},
{"steel-plate", 50},
{"lf-furnace-04", 2},
{"processing-unit", 50},
{"iron-gear-wheel", 20},
{"iron-stick", 20},
{type = "fluid", name = "lubricant", amount = 350}
})
})
end |
local asserteq = require('pl.test').asserteq
local lexer = require 'pl.lexer'
local seq = require 'pl.seq'
local List = require('pl.List')
local open = require('pl.stringio').open
local copy2 = seq.copy2
local function test_scan(str, filter, options, expected_tokens, lang)
local matches
if lang then
matches, filter = filter, options
else
lang = 'scan'
end
asserteq(copy2(lexer[lang](str, matches, filter, options)), expected_tokens)
if lang == 'scan' then
asserteq(copy2(lexer[lang](open(str), matches, filter, options)), expected_tokens)
end
end
local s = '20 = hello'
test_scan(s, {space=false}, {number=false}, {
{'number', '20'}, {'space', ' '}, {'=', '='}, {'space', ' '}, {'iden', 'hello'}
})
test_scan(s, {space=true}, {number=true}, {
{'number', 20}, {'=', '='}, {'iden', 'hello'}
})
s = [[ 'help' "help" "dolly you're fine" "a \"quote\" here"]]
test_scan(s, nil, nil, {
{'string', 'help'}, {'string', 'help'},
{'string', "dolly you're fine"}, {'string', 'a \\\"quote\\\" here'} -- Escapes are preserved literally.
})
test_scan([[\abc\]], nil, nil, {
{'\\', '\\'}, {'iden', 'abc'}, {'\\', '\\'}
})
test_scan([["" ""]], nil, nil, {
{'string', ''}, {'string', ''}
})
test_scan([["abc" "def\\"]], nil, nil, {
{'string', 'abc'}, {'string', 'def\\\\'}
})
test_scan([["abc\\" "def"]], nil, nil, {
{'string', 'abc\\\\'}, {'string', 'def'}
})
test_scan([["abc\\\" "]], nil, nil, {
{'string', 'abc\\\\\\" '}
})
local function test_roundtrip(str)
test_scan(str, {}, {string=false}, {{'string', str}})
end
test_roundtrip [["hello\\"]]
test_roundtrip [["hello\"dolly"]]
test_roundtrip [['hello\'dolly']]
test_roundtrip [['']]
test_roundtrip [[""]]
test_scan('test(20 and a > b)', nil, nil, {
{'iden', 'test'}, {'(', '('}, {'number', 20}, {'keyword', 'and'},
{'iden', 'a'}, {'>', '>'}, {'iden', 'b'}, {')', ')'}
}, 'lua')
test_scan('10+2.3', nil, nil, {
{'number', 10}, {'+', '+'}, {'number', 2.3}
}, 'lua')
local txt = [==[
-- comment
--[[
block
comment
]][[
hello dammit
]][[hello]]
]==]
test_scan(txt, {}, nil, {
{'comment', '-- comment\n'},
{'comment', '--[[\nblock\ncomment\n]]'},
{'string', 'hello dammit\n'},
{'string', 'hello'},
{'space', '\n'}
}, 'lua')
local lines = [[
for k,v in pairs(t) do
if type(k) == 'number' then
print(v) -- array-like case
else
print(k,v)
end -- if
end
]]
local ls = List()
for tp,val in lexer.lua(lines,{space=true,comments=true}) do
assert(tp ~= 'space' and tp ~= 'comment')
if tp == 'keyword' then ls:append(val) end
end
asserteq(ls,List{'for','in','do','if','then','else','end','end'})
txt = [[
// comment
/* a long
set of words */ // more
]]
test_scan(txt, {}, nil, {
{'comment', '// comment\n'},
{'comment', '/* a long\nset of words */'},
{'space', ' '},
{'comment', '// more\n'}
}, 'cpp')
test_scan([['' "" " \\" '\'' "'"]], nil, nil, {
{'char', ''}, -- Char literals with no or more than one characters are not a lexing error.
{'string', ''},
{'string', ' \\\\'},
{'char', "\\'"},
{'string', "'"}
}, 'cpp')
|
local Prop = {}
Prop.Name = "Lake House 201"
Prop.Cat = "House"
Prop.Price = 340
Prop.Doors = {
Vector( 11046, -5861, 177 ),
Vector( 11030, -5529, 177 ),
}
GM.Property:Register( Prop ) |
#!/usr/bin/env luajit
local unpack = unpack or require'table'.unpack
local highway = require'highway'
local interstate95 = highway.new{
length = 517, -- length in kilometers
marker_interval = 1.0 -- marker intervals, in kilometers
}
local interstate76 = highway.new{
length = 37.81958, -- length in kilometers
marker_interval = 1.0 -- marker intervals, in kilometers
}
local my_highways = {
['i95'] = interstate95,
['i76'] = interstate76,
}
-- Add an exit _to_ I-76 at 100 kilometers
assert(interstate95:add_event(101.5, "exit", {
id = 1, -- Exit 1
highway = {'i76', 25.25} -- the connecting highway, id and distance
}))
-- Add an entrance _from_ I-76
assert(interstate95:add_event(101.6, "entrance", {
id = 1, -- Entrance 1
highway = {'i76', 25.25} -- the connecting highway, id and distance
}))
-- Add a lane before the exit
assert(interstate95:add_event(101.1, "lane", {
n = 3
}))
-- One exiting on the left side (US), right side (UK/JPN)
assert(interstate95:add_event(120.0, "exit", {
on_far_side = true
}))
-- Iterate through all of the mile markers
for i_marker, events in ipairs(interstate95.markers) do
if #events > 0 then
print("Mile Marker (km)", i_marker)
end
for i_event, event in ipairs(events) do
print("== Event", i_event)
local dist, name, info = unpack(event)
print(dist, name)
if info then
for kk, vv in pairs(info) do
print("--", kk, vv)
end
end
end
end
-- Print all of the exits
local evt_name = "exit"
print("Finding all", evt_name)
for _, evt in ipairs(interstate95:events_by_name(evt_name)) do
print(unpack(evt))
end |
CheckBox = {
skinnameschecked = {
pressedskin = "checkedcheckbox_pressed",
defaultskin = "checkedcheckbox",
hoveredskin = "checkedcheckbox_hovered",
pressedhoveredskin = "checkedcheckbox_hovered_pressed",
focusedskin = "checkedcheckbox_focused",
focusedhoveredskin = "checkedcheckbox_focused_hovered",
focusedpressedskin = "checkedcheckbox_focused_pressed",
focusedhoveredpressedskin = "checkedcheckbox_focused_hovered_pressed",
},
skinnamesunchecked = {
pressedskin = "checkbox_pressed",
defaultskin = "checkbox",
hoveredskin = "checkbox_hovered",
pressedhoveredskin = "checkbox_hovered_pressed",
focusedskin = "checkbox_focused",
focusedhoveredskin = "checkbox_focused_hovered",
focusedpressedskin = "checkbox_focused_pressed",
focusedhoveredpressedskin = "checkbox_focused_hovered_pressed",
}
}
setmetatable(CheckBox,{__index = Button})
LuxModule.registerclass("gui","CheckBox",
[[A CheckBox component. Basicly it is a slightly modified Button and
works in the same ways like the Button. The checkbox class is using the icon
to display the checkbox next to the text.
You can create and use a checkbox in this way:
ck = CheckBox:new(10,90,200,24,"Check me out!")
function ck:onClicked(state)
if (state) then print("I am checked")
else print("I am unchecked") end
end
Container.getRootContainer():add(ck)
The following skinssurface names are used by the checkbox class:
* checkedcheckbox_pressed
* checkedcheckbox
* checkedcheckbox_hovered
* checkedcheckbox_hovered_pressed
* checkedcheckbox_focused
* checkedcheckbox_focused_hovered
* checkedcheckbox_focused_pressed
* checkedcheckbox_focused_hovered_pressed
* checkbox_pressed
* checkbox
* checkbox_hovered
* checkbox_hovered_pressed
* checkbox_focused
* checkbox_focused_hovered
* checkbox_focused_pressed
* checkbox_focused_hovered_pressed
]],
CheckBox,
{
skinnameschecked = "{[table]} - skinnames in case the element is checked",
skinnamesunchecked = "{[table]} - skinnames in case the element is not checked",
},"Button")
LuxModule.registerclassfunction("new",
[[(CheckBox):(class, float x,y,w,h, string caption, [Skin2D skin,Icon] ]) -
Creates a checkbox at given location and with given size. The caption
is automaticly set to be aligned left on the skin and vertically centered.
It also activates the autowidth parameter of the skin and makes the
button it was derived from pushable.
]])
function CheckBox.new (class, x,y,w,h, caption, skin, icon)
local self = Button.new(class,x,y,w,h, caption)
self:setPushable(true)
self:setSkin(skin or "default")
skin = self:getSkin()
local checkIcon = ImageIcon:new(skin.texture,16,16,blendmode.decal(),
{
default = {160,96,16,16},
checkbox_pressed = {160,96,16,16},
checkbox = {192,112,16,16},
checkbox_hovered = {224,112,16,16},
checkbox_hovered_pressed = {160,96,16,16},
checkbox_focused = {208,112,16,16},
checkbox_focused_hovered = {208,112,16,16},
checkbox_focused_pressed = {176,112,16,16},
checkbox_focused_hovered_pressed = {176,112,16,16},
checkedcheckbox_pressed = {224,112,16,16},
checkedcheckbox = {176,96,16,16},
checkedcheckbox_hovered = {160,96,16,16},
checkedcheckbox_hovered_pressed = {224,112,16,16},
checkedcheckbox_focused = {176,112,16,16},
checkedcheckbox_focused_hovered = {176,112,16,16},
checkedcheckbox_focused_pressed = {208,112,16,16},
checkedcheckbox_focused_hovered_pressed = {208,112,16,16},
}
)
skin:setIcon(checkIcon)
skin:setLabelPosition(Skin2D.ALIGN.LEFT,Skin2D.ALIGN.CENTER)
skin:setAutowidth(true)
self.skinnames = self.skinnamesunchecked
return self
end
function CheckBox:clicked ()
if self:isPushed() then
self.skinnames = self.skinnameschecked
else
self.skinnames = self.skinnamesunchecked
end
Button.clicked(self)
end
function CheckBox:setPushState(state)
Button.setPushState(self,state)
if self:isPushed() then
self.skinnames = self.skinnameschecked
else
self.skinnames = self.skinnamesunchecked
end
end
function CheckBox:updateSkin()
if not self.skin then return end
local p,m,f = (self.dataButton.pressed) and 1 or 0,
self.dataButton.mouseover and 1 or 0,
self:hasFocus() and 1 or 0
local sel = m + p*2 + f*4 + 1
local skins = { self.skinnames.defaultskin,
self.skinnames.hoveredskin,
self.skinnames.pressedskin,
self.skinnames.pressedskin,
self.skinnames.focusedskin,
self.skinnames.focusedhoveredskin,
self.skinnames.focusedpressedskin,
self.skinnames.focusedhoveredpressedskin }
local wx,wy = self:local2world(0,0)
self.skin:setBounds(0,0,self.bounds[3],self.bounds[4])
self.skin:selectSkin(skins[sel] or "checkbox")
self.skin:setLabelText(self.caption)
end
|
--[[ Netherstorm -- Sunfury Researcher.lua
This script was written and is protected
by the GPL v2. This script was released
by BlackHer0 of the BLUA Scripting
Project. Please give proper accredidations
when re-releasing or sharing this script
with others in the emulation community.
~~End of License Agreement
-- BlackHer0, Oktober, 27th, 2008. ]]
function Researcher_OnCombat(Unit, Event)
Unit:RegisterEvent("Researcher_Armor", 6000, 0)
end
function Researcher_Armor(Unit, Event)
Unit:FullCastSpellOnTarget(35918, Unit:GetMainTank())
end
function Researcher_OnLeaveCombat(Unit, Event)
Unit:RemoveEvents()
end
function Researcher_OnDied(Unit, Event)
Unit:RemoveEvents()
end
function Researcher_OnKilledTarget(Unit, Event)
end
RegisterUnitEvent(20136, 1, "Researcher_OnCombat")
RegisterUnitEvent(20136, 2, "Researcher_OnLeaveCombat")
RegisterUnitEvent(20136, 3, "Researcher_OnKilledTarget")
RegisterUnitEvent(20136, 4, "Researcher_OnDied") |
-- Returns the config options from [about](about.html),
-- udpated by any command line flags (if any exist).
local about=require"about"
-- **help_string(t : table) : str**
-- Helper function for `cli. Generates and prints help string
local function help_string(t, h, default,about)
h = {}
for k,xy in pairs(t.options) do
default, about = xy[1], xy[2]
if default == false
then h[1+#h] = string.format(" -%-10s %-10s %s",k,"", about)
else h[1+#h] = string.format(" -%-10s %-10s %s (:default %s)",
k, k:sub(1,#k), about, default) end end
table.sort(h)
return ("usage: "..t.usage.." [OPTIONS]\n\n"..t.synopsis..
"\n\nOPTIONS:\n".. table.concat(h,"\n")) end
-- **cli(t : table, args : table) : table**
-- Return values from `t.options`, updated with relevant values from `a`.
-- `t` has fields `t.usage`, `t.synopsis` and `t.options`.
-- `t.options` has key,values of the form `key={default, about}`.
-- If any `defaults` are `false` then using `-key` on the command line
-- enables `key` to true. Otherwise `-key` expects a following
-- argument which this code converts to a number or string, as appropriate.
local function cli(t,args, out,b4,f)
out = {}
for k,v2 in pairs(t.options) do out[k]=v2[1] end
for i = 1,#args do
if args[i] == "-h" then
print(help_string(t))
elseif #args[i] > 1 then
if "-" == args[1]:sub(1,1) then
f = args[i]:sub(2,#t[i])
b4 = t.options[f]
if b4 then
new = (b4[1]==false and true or (
tonumber(args[i+1]) or args[i+1]))
out[f] = new end end end end
return out end
-- ---------
-- Return the options, updated by anything on the command-line.
return cli(about,arg)
|
local box = require "plc.box"
local function new_key()
-- Note: we use math.random in this test because it is portable,
-- but to generate a real key you should use a better RNG, for
-- instance /dev/urandom on Linux.
local t = {}
for i = 1, 32 do t[i] = math.random(0, 255) end
return string.char(table.unpack(t))
end
local sk_a, sk_b = new_key(), new_key()
local pk_a, pk_b = box.public_key(sk_a), box.public_key(sk_b)
local k = ("k"):rep(32)
local n = ("123456"):rep(4)
local pt = "abc"
do
local et = assert(box.secretbox(pt, n, k))
local dt = assert(box.secretbox_open(et, n, k))
assert(dt == pt)
end
do
local et = assert(box.box(pt, n, pk_b, sk_a))
local dt = assert(box.box_open(et, n, pk_a, sk_b))
assert(dt == pt)
end
print("test_box: ok")
|
--[[--
Additions to the math module.
@module std.math
]]
local _floor = math.floor
--- Extend `math.floor` to take the number of decimal places.
-- @function floor
-- @param n number
-- @param p number of decimal places to truncate to (default: 0)
-- @return `n` truncated to `p` decimal places
local function floor (n, p)
if p and p ~= 0 then
local e = 10 ^ p
return _floor (n * e) / e
else
return _floor (n)
end
end
--- Round a number to a given number of decimal places
-- @function round
-- @param n number
-- @param p number of decimal places to round to (default: 0)
-- @return `n` rounded to `p` decimal places
local function round (n, p)
local e = 10 ^ (p or 0)
return _floor (n * e + 0.5) / e
end
local Math = {
floor = floor,
round = round,
-- Core Lua function implementations.
_floor = _floor,
}
for k, v in pairs (math) do
Math[k] = Math[k] or v
end
return Math
|
-----------------------------------------
-- ID: 4962
-- Scroll of Tonko: Ichi
-- Teaches the ninjutsu Tonko: Ichi
-----------------------------------------
function onItemCheck(target)
return target:canLearnSpell(354)
end
function onItemUse(target)
target:addSpell(354)
end |
module("luci.controller.webrestriction", package.seeall)
function index()
if not nixio.fs.access("/etc/config/webrestriction") then return end
entry({"admin", "control"}, firstchild(), "Control", 44).dependent = false
entry({"admin", "control", "webrestriction"}, cbi("webrestriction"), _("访问限制"), 11).dependent = true
end
|
--- Entity module
-- @module Entity
require '/locale/stdlib/core'
require '/locale/stdlib/surface'
require '/locale/stdlib/area/area'
Entity = {}
--- Converts an entity and its selection_box to the area around it
-- @param entity to convert to an area
-- @return area that entity selection_box is valid for
function Entity.to_selection_area(entity)
fail_if_missing(entity, "missing entity argument")
local pos = entity.position
local bb = entity.prototype.selection_box
return Area.offset(bb, pos)
end
--- Converts an entity and its collision_box to the area around it
-- @param entity to convert to an area
-- @return area that entity collision_box is valid for
function Entity.to_collision_area(entity)
fail_if_missing(entity, "missing entity argument")
local pos = entity.position
local bb = entity.prototype.collision_box
return Area.offset(bb, pos)
end
--- Tests whether an entity has access to the field
-- @param entity to test field access
-- @param field_name that should be tested for
-- @return true if the entity has access to the field, false if the entity threw an exception accessing the field
function Entity.has(entity, field_name)
fail_if_missing(entity, "missing entity argument")
fail_if_missing(field_name, "missing field name argument")
local status = pcall(function() return entity[field_name]; end)
return status
end
--- Gets user data from the entity, stored in a mod's global data.
--- <p> The data will persist between loads, and will be removed for an entity when it becomes invalid</p>
-- @param entity the entity to look up data for
-- @return the data, or nil if no data exists for the entity
function Entity.get_data(entity)
fail_if_missing(entity, "missing entity argument")
if not global._entity_data then return nil end
local unit_number = entity.unit_number
if unit_number then
return global._entity_data[unit_number]
else
local entity_name = entity.name
if not global._entity_data[entity_name] then return nil end
local entity_category = global._entity_data[entity_name]
for _, entity_data in pairs(entity_category) do
if Entity._are_equal(entity_data.entity, entity) then
return entity_data.data
end
end
return nil
end
end
--- Sets user data on the entity, stored in a mod's global data.
--- <p> The data will persist between loads, and will be removed for an entity when it becomes invalid</p>
-- @param entity the entity to set data for
-- @param data the data to set, or nil to delete the data associated with the entity
-- @return the previous data associated with the entity, or nil if the entity had no previous data
function Entity.set_data(entity, data)
fail_if_missing(entity, "missing entity argument")
if not global._entity_data then global._entity_data = {} end
local unit_number = entity.unit_number
if unit_number then
local prev = global._entity_data[unit_number]
global._entity_data[unit_number] = data
return prev
else
local entity_name = entity.name
if not global._entity_data[entity_name] then
global._entity_data[entity_name] = {}
end
local entity_category = global._entity_data[entity_name]
for i = #entity_category, 1, -1 do
local entity_data = entity_category[i]
if not entity_data.entity.valid then
table.remove(entity_category, i)
end
if Entity._are_equal(entity_data.entity, entity) then
local prev = entity_data.data
if data then
entity_data.data = data
else
table.remove(entity_category, i)
end
return prev
end
end
table.insert(entity_category, { entity = entity, data = data })
end
return nil
end
--- Freezes an entity, by making it inactive, inoperable, and non-rotatable, or unfreezes by doing the reverse.
-- @param entity the entity to freeze or unfreeze
-- @param mode (optional) if true, freezes the entity, if false, unfreezes the entity. If not specified, is true.
-- @return entity passed into it
function Entity.set_frozen(entity, mode)
fail_if_missing(entity, "missing entity argument")
mode = mode == false and true or false
entity.active = mode
entity.operable = mode
entity.rotatable = mode
return entity
end
--- Makes an entity indestructible, so that it can not be damaged or mined by the player or enemy factions
-- @param entity the entity to set indestructible
-- @param mode (optional) if true, makes the entity indestructible, if false, makes the entity destructable. If not specified, is true.
-- @return entity passed into it
function Entity.set_indestructible(entity, mode)
fail_if_missing(entity, "missing entity argument")
mode = mode == false and true or false
entity.minable = mode
entity.destructible = mode
return entity
end
--- Tests if two entities are equal
-- <p>If they don't have reference equality and entity_a has an 'equals' function,
-- it will be called with entity_b as the first argument</p>
-- @tparam table entity_a
-- @tparam table entity_b
-- @treturn bool
function Entity._are_equal(entity_a, entity_b)
if entity_a == nil then
return entity_a == entity_b
elseif entity_a == entity_b then
return true
elseif Entity.has(entity_a, "equals") and entity_a.equals ~= nil then
return entity_a.equals(entity_b)
else
return false
end
end
return Entity
|
-- Online Interiors IPL Edits
-- Use https://github.com/Bob74/bob74_ipl/wiki to edit below
-- Nightclub (Mission Row)
Citizen.CreateThread(function()
-- Getting the object to interact with
AfterHoursNightclubs = exports['bob74_ipl']:GetAfterHoursNightclubsObject()
-------------------------------------------
-- Interior setup
AfterHoursNightclubs.Ipl.Interior.Load()
-- Setting the name of the club to The Galaxy
AfterHoursNightclubs.Interior.Name.Set(AfterHoursNightclubs.Interior.Name.galaxy, true)
-- Edgy style
AfterHoursNightclubs.Interior.Style.Set(AfterHoursNightclubs.Interior.Style.edgy, true)
-- No podiums
AfterHoursNightclubs.Interior.Podium.Set(AfterHoursNightclubs.Interior.Podium.none, true)
-- Upgraded speakers
AfterHoursNightclubs.Interior.Speakers.Set(AfterHoursNightclubs.Interior.Speakers.upgrade, true)
-- Upgraded security
AfterHoursNightclubs.Interior.Security.Set(AfterHoursNightclubs.Interior.Security.on, true)
-- Setting turntables
AfterHoursNightclubs.Interior.Turntables.Set(AfterHoursNightclubs.Interior.Turntables.style03, true)
-- Lights
AfterHoursNightclubs.Interior.Lights.Bands.Set(AfterHoursNightclubs.Interior.Lights.Bands.white, true)
AfterHoursNightclubs.Interior.Lights.Droplets.Clear(true)
AfterHoursNightclubs.Interior.Lights.Neons.Clear(true)
AfterHoursNightclubs.Interior.Lights.Lasers.Clear(true)
-- DryIce
AfterHoursNightclubs.Interior.DryIce.Enable(false)
AfterHoursNightclubs.Interior.Details.Enable(AfterHoursNightclubs.Interior.Details.dryIce, true)
-- Enabling bottles behind the bar
AfterHoursNightclubs.Interior.Bar.Enable(true)
-- Disabling all booze bottles
AfterHoursNightclubs.Interior.Booze.Enable(AfterHoursNightclubs.Interior.Booze, false)
-- Adding trophies on the desk
AfterHoursNightclubs.Interior.Trophy.Enable(AfterHoursNightclubs.Interior.Trophy.number1, true, AfterHoursNightclubs.Interior.Trophy.Color.bronze, true)
AfterHoursNightclubs.Interior.Trophy.Enable(AfterHoursNightclubs.Interior.Trophy.battler, true, AfterHoursNightclubs.Interior.Trophy.Color.silver, true)
AfterHoursNightclubs.Interior.Trophy.Enable(AfterHoursNightclubs.Interior.Trophy.dancer, true, AfterHoursNightclubs.Interior.Trophy.Color.gold, true)
-- Refreshing interior to apply changes
RefreshInterior(AfterHoursNightclubs.interiorId)
end) |
local map = require 'lqc.helpers.map'
describe('map function', function()
local t1 = { 1, 2, 3, 4, 5 }
local function f1(value)
return value * 2
end
local t2 = { 'abc', 'def' }
local function f2(value)
return string.rep(value, 3)
end
it('should apply a function to all elements in the collection', function()
local expected1 = { 2, 4, 6, 8, 10 }
assert.same(expected1, map(t1, f1))
local expected2 = { 'abcabcabc', 'defdefdef' }
assert.same(expected2, map(t2, f2))
end)
it('should keep initial table untouched', function()
map(t1, f1)
map(t2, f2)
assert.same(t1, { 1, 2, 3, 4, 5 })
assert.same(t2, { 'abc', 'def' })
end)
end)
|
-- Write to the 1602 screen
-- Based on the Adafruit python code
-- Pin Definitions
RS = 1
CLK = 2
pins={7,6,5,4}
-- Set up the out pins
function setupPins()
gpio.mode(RS,gpio.OUTPUT)
gpio.mode(CLK,gpio.OUTPUT)
for i=1,4 do
gpio.mode(pins[i],gpio.OUTPUT)
end
end
function resetPins()
for i=1,4 do
gpio.write(pins[i],gpio.LOW)
end
end
function sendClock()
gpio.write(CLK,gpio.LOW)
gpio.write(CLK,gpio.HIGH)
gpio.write(CLK,gpio.LOW)
end
function sendbyte(b,charmode)
gpio.write(RS,charmode)
-- shift right 4 times putting the bits on the output lines
mask=128
for c=1,2 do
for i=1,4 do
r = bit.band(b,mask)
if r==0 then
gpio.write(pins[i],gpio.LOW)
else
gpio.write(pins[i],gpio.HIGH)
end
mask = mask / 2
end
sendClock()
end
end
function clearPanel()
sendbyte(0x01,gpio.LOW)
tmr.delay(10)
end
function line2()
sendbyte(0xC0,gpio.LOW)
end
-- Methods to send the characters to the screen, using a timer and callback.
buffer = {}
-- byte 13 (newline) moves to line 2
function bufferText(text)
for i=1,string.len(text) do
table.insert(buffer,string.byte(text,i))
if i=="\n" then newline() end
end
end
function newline()
table.insert(buffer,"\n")
end
-- Empty buffer and clear display
function clearBuffer()
buffer = {}
clearPanel()
end
function sendNextByte()
if table.getn(buffer)>0 then
byte = table.remove(buffer,1)
if byte == "\n" then
line2()
else
sendbyte(byte,gpio.HIGH)
end
end
end
-- START
-- Initialise the board
setupPins()
resetPins()
-- Initialise the display (low = command mode, high = character mode)
-- 0b0011 twice (as per Wikipedia)
sendbyte(0x33,gpio.LOW)
-- another 0b0011 then the 0b0010 to put it in 4 bit mode.
sendbyte(0x32,gpio.LOW)
sendbyte(0x28,gpio.LOW)
sendbyte(0x0C,gpio.LOW)
lcdtimer=tmr.create()
lcdtimer:register(10,tmr.ALARM_AUTO,sendNextByte)
lcdtimer:start()
clearBuffer()
-- To send text, use
bufferText("A Line")
newline()
bufferText("Another Line")
|
require 'mia.packer' -- plugin set up
require 'lush'(require 'gruvbox')
require 'mia.config.keymaps'
require 'mia.config.treesitter'
require 'mia.config.telescope'
return {}
|
-- Generated By protoc-gen-lua Do not Edit
local protobuf = require "protobuf"
module('BseUserLeaveRoom_pb', package.seeall)
local BSEUSERLEAVEROOM = protobuf.Descriptor();
local BSEUSERLEAVEROOM_ROOMID_FIELD = protobuf.FieldDescriptor();
local BSEUSERLEAVEROOM_SESSIONID_FIELD = protobuf.FieldDescriptor();
local BSEUSERLEAVEROOM_MASTERID_FIELD = protobuf.FieldDescriptor();
BSEUSERLEAVEROOM_ROOMID_FIELD.name = "roomId"
BSEUSERLEAVEROOM_ROOMID_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.BseUserLeaveRoom.roomId"
BSEUSERLEAVEROOM_ROOMID_FIELD.number = 1
BSEUSERLEAVEROOM_ROOMID_FIELD.index = 0
BSEUSERLEAVEROOM_ROOMID_FIELD.label = 2
BSEUSERLEAVEROOM_ROOMID_FIELD.has_default_value = false
BSEUSERLEAVEROOM_ROOMID_FIELD.default_value = ""
BSEUSERLEAVEROOM_ROOMID_FIELD.type = 9
BSEUSERLEAVEROOM_ROOMID_FIELD.cpp_type = 9
BSEUSERLEAVEROOM_SESSIONID_FIELD.name = "sessionId"
BSEUSERLEAVEROOM_SESSIONID_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.BseUserLeaveRoom.sessionId"
BSEUSERLEAVEROOM_SESSIONID_FIELD.number = 2
BSEUSERLEAVEROOM_SESSIONID_FIELD.index = 1
BSEUSERLEAVEROOM_SESSIONID_FIELD.label = 2
BSEUSERLEAVEROOM_SESSIONID_FIELD.has_default_value = false
BSEUSERLEAVEROOM_SESSIONID_FIELD.default_value = ""
BSEUSERLEAVEROOM_SESSIONID_FIELD.type = 9
BSEUSERLEAVEROOM_SESSIONID_FIELD.cpp_type = 9
BSEUSERLEAVEROOM_MASTERID_FIELD.name = "masterId"
BSEUSERLEAVEROOM_MASTERID_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.BseUserLeaveRoom.masterId"
BSEUSERLEAVEROOM_MASTERID_FIELD.number = 3
BSEUSERLEAVEROOM_MASTERID_FIELD.index = 2
BSEUSERLEAVEROOM_MASTERID_FIELD.label = 2
BSEUSERLEAVEROOM_MASTERID_FIELD.has_default_value = false
BSEUSERLEAVEROOM_MASTERID_FIELD.default_value = ""
BSEUSERLEAVEROOM_MASTERID_FIELD.type = 9
BSEUSERLEAVEROOM_MASTERID_FIELD.cpp_type = 9
BSEUSERLEAVEROOM.name = "BseUserLeaveRoom"
BSEUSERLEAVEROOM.full_name = ".com.xinqihd.sns.gameserver.proto.BseUserLeaveRoom"
BSEUSERLEAVEROOM.nested_types = {}
BSEUSERLEAVEROOM.enum_types = {}
BSEUSERLEAVEROOM.fields = {BSEUSERLEAVEROOM_ROOMID_FIELD, BSEUSERLEAVEROOM_SESSIONID_FIELD, BSEUSERLEAVEROOM_MASTERID_FIELD}
BSEUSERLEAVEROOM.is_extendable = false
BSEUSERLEAVEROOM.extensions = {}
BseUserLeaveRoom = protobuf.Message(BSEUSERLEAVEROOM)
_G.BSEUSERLEAVEROOM_PB_BSEUSERLEAVEROOM = BSEUSERLEAVEROOM
|
--[[
TheNexusAvenger
Helper class for creating objects in Lua.
--]]
local METATABLE_METHODS = {
"__call",
"__concat",
"__unm",
"__add",
"__sub",
"__mul",
"__div",
"__mod",
"__pow",
"__tostring",
"__eq",
"__lt",
"__le",
"__gc",
"__len",
}
--[[
Returns the raw tostring of a table.
See: https://stackoverflow.com/questions/43285679/is-it-possible-to-bypass-tostring-the-way-rawget-set-bypasses-index-newind
--]]
local function RawToString(Table)
local Metatable = getmetatable(Table)
local BaseFunction = Metatable.__tostring
Metatable.__tostring = nil
local String = tostring(Table)
Metatable.__tostring = BaseFunction
return String
end
--[[
Creates the referebce to a super class.
--]]
local function CreateSuperReference(Object, SuperClass)
--Return nil if there is no super class.
if SuperClass == nil then
return nil
end
--Create the super reference.
local Super = {}
local NextSuperReference = CreateSuperReference(Object, SuperClass.__superclass)
local SuperMetatable = {}
SuperMetatable.__index = function(_, Index)
--Return super.
--Special case to prevent recursive errors.
if Index == "super" then
return NextSuperReference
end
--Get the super reference until it doesn't match.
local ObjectValue = Object[Index]
local CurrentSuperClass = SuperClass
local SuperValue = CurrentSuperClass[Index]
while ObjectValue == SuperValue do
CurrentSuperClass = CurrentSuperClass.__superclass
if CurrentSuperClass == nil then break end
SuperValue = CurrentSuperClass[Index]
end
--Return the super value that is different or the object value.
return SuperValue or Object[Index]
end
SuperMetatable.__newindex = Object
setmetatable(Super, SuperMetatable)
--Return the super reference.
return Super
end
--[[
Extends a class.
--]]
local function ExtendClass(SuperClass)
--Create the class.
local Class = {}
Class.super = SuperClass
Class.__superclass = SuperClass
Class.__index = Class
setmetatable(Class, SuperClass)
--[[
Creates an object.
--]]
function Class.new(...)
--Create the base object.
local self = {}
self.__index = self
self.object = self
self.class = SuperClass
self.super = CreateSuperReference(self, SuperClass)
setmetatable(self, Class)
--Run the constructor.
self:__new(...)
--Return the object.
return self
end
--[[
Constructor run for the class.
--]]
function Class:__new(...)
self:InitializeSuper(...)
end
--Add the metamethod passthrough.
if SuperClass then
for _, MetatableName in pairs(METATABLE_METHODS) do
Class[MetatableName] = SuperClass[MetatableName]
end
end
--Call the callback for the class being extended.
if SuperClass then
SuperClass:__classextended(Class)
end
--Return the created class.
return Class
end
--Set up the base Nexus Object class.
local NexusObject = ExtendClass()
NexusObject.ClassName = "NexusObject"
--[[
Called after extending when another class extends
the class. The purpose of this is to add attributes
to the class.
--]]
function NexusObject:__classextended(OtherClass)
if not self.super then return end
self.super:__classextended(OtherClass)
end
--[[
Returns the object as a string.
--]]
function NexusObject:__tostring()
local MemoryAddress = string.sub(RawToString(self), 8)
return tostring(self.ClassName)..": "..tostring(MemoryAddress)
end
--[[
Returns if the object is equal to another object.
--]]
function NexusObject:__eq(OtherObject)
return rawequal(self,OtherObject)
end
--[[
Initializes the super class. The paramters given
by "..." are passed into the constructor of the
super class (__new(...)). It should be called
in the constructor of the class.
--]]
function NexusObject:InitializeSuper(...)
if not self.super then return end
self.super:__new(...)
end
--[[
Sets the class name of the class. Should be
called staticly (right after NexusObject::Extend).
--]]
function NexusObject:SetClassName(ClassName)
self.ClassName = ClassName
end
--[[
Extends a class to allow for implementing properties and
functions while inheriting the super class's behavior.
--]]
function NexusObject:Extend()
return ExtendClass(self)
end
--[[
Returns if the instance is or inherits from a class of that name.
--]]
function NexusObject:IsA(ClassName)
--If the class name matches the class name, return true.
if self.ClassName == ClassName then
return true
end
--If a super class exists, return the result of the super.
if self.super then
return self.super:IsA(ClassName)
end
--Return false (no match).
return false
end
return NexusObject |
local sw,sh = guiGetScreenSize()
local GothaProMed = dxCreateFont("destek/Roboto.ttf",15)
addEventHandler( "onClientRender", root, function ( )
for k,player in ipairs(getElementsByType("player")) do
if player ~= getLocalPlayer() and getElementDimension(getLocalPlayer()) == getElementDimension(player) and getElementData(getLocalPlayer(), "faction") == 1 or getElementData(getLocalPlayer(), "faction") == 78 then
local dutyLevel = getElementData(getLocalPlayer(), "duty")
--if not dutyLevel or dutyLevel == 0 then return end
local x, y, z = getElementPosition(player)
z = z + 0.95
local Mx, My, Mz = getCameraMatrix()
local distance = getDistanceBetweenPoints3D( x, y, z, Mx, My, Mz )
local size = 1
x, y, z = getElementPosition(player)
fx, fy, fz = getElementPosition(getLocalPlayer())
if getElementData(player, "destekacik") then
local sx,sy = getScreenFromWorldPosition( x, y, z, 0 )
if ( sx and sy ) then
dxDrawImage(sx-30, sy-80, 40,40, "destek/destek.png",0,0,0,tocolor(255,255,255,255))
local metre = tostring(getDistanceBetweenPoints3D(x, y, z, fx, fy, fz))
local name = getPlayerName(player):gsub("_", " ")
local tur = getElementData(player, "destek_tur")
dxDrawText(""..name.." ("..tur..")", sx, sy, sx+size, sy+size-10, tocolor(0,0,0,200), size, GothaProMed, "center", "bottom", false, false, false)
dxDrawText(""..name.." ("..tur..")", sx, sy, sx, sy-10, tocolor(255,255,255,200), size, GothaProMed, "center", "bottom", false, false, false)
end
end
if getElementData(player, "takipacik") then
local sx,sy = getScreenFromWorldPosition( x, y, z, 0 )
if ( sx and sy ) then
dxDrawImage(sx-30, sy-80, 40,40, "destek/takip.png",0,0,0,tocolor(255,255,255,255))
local name = getPlayerName(player):gsub("_", " ")
dxDrawText(""..name.."", sx, sy, sx+size, sy+size-10, tocolor(0,0,0,200), size, GothaProMed, "center", "bottom", false, false, false)
dxDrawText(""..name.."", sx, sy, sx, sy-10, tocolor(255,255,255,200), size, GothaProMed, "center", "bottom", false, false, false)
end
end
end
end
end) |
-- mod-version:2 -- lite-xl 2.0
local core = require "core"
local config = require "core.config"
local style = require "core.style"
local StatusView = require "core.statusview"
local scan_rate = 1
config.plugins.statusclock = {
time_format = "%H:%M:%S",
date_format = "%A, %d %B %Y"
}
local time_data = {
time_text = '',
date_text = '',
}
core.add_thread(function()
while true do
local time_text = os.date(config.plugins.statusclock.time_format)
local date_text = os.date(config.plugins.statusclock.date_format)
if time_data.time_text ~= time_text or time_data.time_text ~= date_text then
core.redraw = true
time_data.time_text = time_text
time_data.date_text = date_text
end
coroutine.yield(scan_rate)
end
end)
local get_items = StatusView.get_items
function StatusView:get_items()
local left, right = get_items(self)
local t = {
style.dim,
self.separator,
style.dim and style.text,
time_data.date_text,
style.dim,
self.separator,
style.dim and style.text,
time_data.time_text,
}
for _, item in ipairs(t) do
table.insert(right, item)
end
return left, right
end
|
Tips = Object:extend()
local radius = math.floor(base.guiFontHeight/3)
function Tips:new(string, x, y, z, xMode, yMode)
self.string = string
self.x = 0
if x ~= nil then
self.x = x
end
self.y = 0
if y ~= nil then
self.y = y
end
self.z = 0
if z ~= nil then
self.z = z
end
self.xMode = xMode
self.yMode = yMode
end
function Tips:draw(mode)
local font = love.graphics.getFont()
local fWidth = font:getWidth(self.string)
local reWidth = fWidth + radius*2
local _y = self.y + (-self.y +self.z)*mode
local _x = self.x
-- center
if self.xMode ~= nil then
if self.xMode == "center" then
_x = _x - reWidth/2
elseif self.xMode == "right" then
_x = _x - reWidth
end
end
if self.yMode ~= nil then
if self.yMode == "center" then
_y = _y - base.guiFontHeight/2
elseif self.yMode == "bottom" then
_y = _y - base.guiFontHeight
end
end
-- bg
love.graphics.setColor(base.cWhite)
base.drawRoundedRectangle(_x, _y, reWidth, base.guiFontHeight)
-- text
love.graphics.setColor(base.cBlack)
base.print(self.string, _x+reWidth/2, _y, "center")
end |
local M = {}
local icons = require "config.icons"
local error_red = "#F44747"
local warning_orange = "#ff8800"
local info_yellow = "#FFCC66"
local hint_blue = "#4FC1FF"
local perf_purple = "#7C3AED"
function M.setup()
require("todo-comments").setup {
signs = true,
keywords = {
FIX = { icon = icons.ui.Bug, color = error_red },
TODO = { icon = icons.ui.Check, color = hint_blue },
HACK = { icon = icons.ui.Fire, color = warning_orange },
WARN = { icon = icons.diagnostics.Warning, color = warning_orange },
PERF = { icon = icons.ui.Dashboard, color = perf_purple },
NOTE = { icon = icons.ui.Note, color = info_yellow },
},
}
end
return M
|
print("-- 开始清理旧的文件 --")
require "lfs"
--递归查找
function findindir (path, wefind, r_table, intofolder)
for file in lfs.dir(path) do
if file ~= "." and file ~= ".." then
local f = path..'\\'..file
if string.find(f, wefind) ~= nil then
table.insert(r_table, f)
end
local attr = lfs.attributes (f)
assert (type(attr) == "table")
if attr.mode == "directory" and intofolder then
findindir (f, wefind, r_table, intofolder)
end
end
end
end
-- arg 是lua保存cmd命令传过来的参数
local currentFolder = arg[1] --[[./log]]
local fileType = arg[2]
-------------------------------------
local input_table = {}
findindir(currentFolder, "%"..fileType, input_table, false)--查找txt文件
i=1
while input_table[i]~=nil do
local url = input_table[i]
i=i+1
os.remove(url)
print("文件"..url..",已经被清理.")
end
i=i-1
print("---本次共清理了"..i.."个文件.")
print(arg[1], arg[2])
--[[
--读取命令传过来的参数
print(arg[1], arg[2])
for i, v in ipairs(arg) do
print("输出命令行的参数:",v)
end
--]] |
-- Base16 Spaceduck color
-- Author: Guillermo Rodriguez (pineapplegiant)
-- to be use in your theme.lua
-- symlink or copy to config folder `local color = require('color')`
local M = {}
M.base00 = "#000000" -- ----
M.base01 = "#5ccc96" -- ---
M.base02 = "#b3a1e6" -- --
M.base03 = "#686f9a" -- -
M.base04 = "#00a3cc" -- +
M.base05 = "#686f9a" -- ++
M.base06 = "#f2ce00" -- +++
M.base07 = "#f0f1ce" -- ++++
M.base08 = "#e33400" -- red
M.base09 = "#e33400" -- orange
M.base0A = "#b3a1e6" -- yellow
M.base0B = "#5ccc96" -- green
M.base0C = "#7a5ccc" -- aqua/cyan
M.base0D = "#00a3cc" -- blue
M.base0E = "#f2ce00" -- purple
M.base0F = "#7a5ccc" -- brown
return M
|
-- unit-test for the classrunner
local ClassRunner = require 'classrunner'
local LuaUnit = require 'luaunit'
--TODO: test the (self) variable in test classes
---- STUFF -------------------------------------------------------------------
local a,b,c,d = 0,0,0,0 -- variables to show call frequency
UnTestTiti = {
setUpClass = function(self)
a=a+1
end,
setUp = function(self)
b=b+1
end,
tearDown = function(self)
c=c+1
end,
tearDownClass = function(self)
d=d+1
end,
test1 = function(self) end,
testb = function(self) end,
test3 = function(self) end,
}
function some_function() end
function fail_function() assert(false) end
---- TEST CLASSRUNNER -------------------------------------------------------
TestClassRunner = {}
TestClassRunner.test_auto_name = function(self)
local cr
for i=1,6 do
cr = ClassRunner.new()
assertEquals(cr:getName(), 'ClassRunner'..i)
end
end
TestClassRunner.test_nominal = function(self)
local cr = ClassRunner.new('UnTestTiti')
cr:setSilent(true) -- true is redundant
assertEquals(cr:getOutput(), '')
cr:run()
assertEquals({a,b,c,d}, {1,3,3,1},
'call frequency of setups/teardowns')
assertEquals({cr:getResults()}, {3, {}, 0},
'three successes, no failures, no skips')
assertEquals(cr:getOutput(),
'UnTestTiti\n [test1]\tOk\n [test3]\tOk\n [testb]\tOk\n',
'alphabetic test order, verbose output')
end
TestClassRunner.test_specified = function(self)
local cr = ClassRunner.new('UnTestTiti')
cr:addTest('fail_function')
cr:setSilent()
--note order; t2 will be absent; test1 will not be run twice
cr:run('testb', 'test1', 't2', 'test1', 'fail_function')
local ran, fails, skips = cr:getResults()
assertEquals(ran, 3)
assertEquals(#fails, 1)
assertEquals(#fails[1], 3)
local name, msg, stack = fails[1][1], fails[1][2], fails[1][3]
assertEquals(name, 'fail_function')
assertEquals(msg, 'test_classrunner.lua:31: assertion failed!')
assertString(stack, 'stack traceback expected here')
assertEquals(skips, 1)
assertEquals(cr:getOutput(),
'UnTestTiti\n [testb]\tOk\n [test1]\tOk\n '..
'[t2]\tAbsent\n [fail_function]\tFailed\n')
end
TestClassRunner.test_build_class = function(self)
local cr = ClassRunner.new('MyTestClass')
cr:addTest('some_function')
cr:setSilent()
cr:run()
assertEquals(cr:getOutput(), 'MyTestClass\n [some_function]\tOk\n')
end
TestClassRunner.test_rerun_resets = function(self)
local cr = ClassRunner.new('UnTestTiti')
cr:setSilent()
cr:run()
assertEquals( {cr:getResults()}, {3, {}, 0})
assertEquals(cr:getOutput(),
'UnTestTiti\n [test1]\tOk\n [test3]\tOk\n [testb]\tOk\n')
cr:addTest('some_function')
cr:run('some_function', 'testb')
assertEquals( {cr:getResults()}, {2, {}, 0}) -- ran some_function and testb
assertEquals(cr:getOutput(),
'UnTestTiti\n [some_function]\tOk\n [testb]\tOk\n')
end
---- TEST VERBOSITY ----------------------------------------------------------
TestVerbosity = {}
TestVerbosity.setUp = function(self)
-- also re-demonstrate building a test class 'from scratch'
self.cr = ClassRunner.new('TestAbsentClass')
self.cr:addTest('some_function')
self.cr:addTest('fail_function')
self.cr:setSilent() -- do not print while running
end
TestVerbosity.test_terse_set = function(self)
self.cr:setVerbosity(0)
self.cr:run()
local total, fails = self.cr:getResults()
assertEquals(total, 2)
assertEquals(self.cr:getOutput(), 'TestAbsentClass\tF.\n')
local name, msg, stack = fails[1][1], fails[1][2], fails[1][3]
assertEquals(#fails, 1)
assertEquals(name, 'fail_function',
'failing function name')
assertEquals(msg, 'test_classrunner.lua:31: assertion failed!',
'failing function message')
assertNotNil(stack:find('in function'),
'peek at stacktrace')
end
TestVerbosity.test_terse_param = function(self)
local runnerWithParam = ClassRunner.new('TestVerbParam', 0)
runnerWithParam:addTest('some_function')
runnerWithParam:addTest('fail_function')
runnerWithParam:setSilent()
runnerWithParam:run()
assertEquals(runnerWithParam:getOutput(), 'TestVerbParam\tF.\n')
local total, fails = runnerWithParam:getResults()
local name, msg, stack = fails[1][1], fails[1][2], fails[1][3]
assertEquals(#fails, 1)
assertEquals(name, 'fail_function',
'failing function name')
assertEquals(msg, 'test_classrunner.lua:31: assertion failed!',
'failing function message')
assertNotNil(stack:find('in function'),
'peek at stacktrace')
end
TestVerbosity.test_verbose = function(self)
assertEquals(self.cr:getVerbosity(), 1) -- default verbosity
self.cr:run()
local total, fails = self.cr:getResults()
assertEquals(total, 2)
assertEquals(self.cr:getOutput(),
[[TestAbsentClass
[fail_function] Failed
[some_function] Ok
]])
assertNotNil(fails[1][3]:find('in function'))
end
TestVerbosity.test_module_set = function(self)
local default, runner = ClassRunner.getVerbosity(), nil
assertEquals(default, 1)
for i = 0, 5 do
ClassRunner.setVerbosity(i)
runner = ClassRunner.new('TestClass')
assertEquals(runner:getVerbosity(), i)
end
ClassRunner.setVerbosity(nil)
assertEquals(ClassRunner.getVerbosity(), default)
end
LuaUnit:run(arg)
|
--[[
Lua side of the hotkey api.
This primarily aims to interface tightly with the egosoft menu system,
to leverage existing code for allowing players to customize hotkeys.
Patches the OptionsMenu.
Notes on edit boxes:
The external hotkey detection has no implicit knowledge of the in-game
context of the keys.
Contexts are resolved partially below and in md by detecting if the
player is flying, on foot, or in a menu (and which menu).
However, complexity arises when the player is trying to type into
an edit box (or similar), where hotkeys should be suppressed.
Edit box activation and deactivation callbacks can be difficult to
get at, notably the chat window that is present in a flying context.
As a possible workaround, registerForEvent can be used on the ui to
catch directtextinput events, which fire once per key press for an
edit box. This can potentially be used to suppress key events.
Functionality: on direct input key, set an alarm for some time in the
future. Immediately signal the md to suppress keys. After the alarm
goes off, signal md to reenable keys. If more direct inputs come in
during this period, have them just reset the alarm time.
The alarm should be long enough to cover the latency from the external
python code through the pipe to the game. That is not well measured,
but some generous delay should handle the large majority of cases,
unless there was some odd hiccup on key processing.
TODO: split apart md interface stuff from the menu plugin stuff,
to reduce file sizes.
]]
-- Set up any used ffi functions.
local ffi = require("ffi")
local C = ffi.C
ffi.cdef[[
typedef uint64_t UniverseID;
UniverseID GetPlayerID(void);
]]
-- Unused functions for now.
--[[
void ActivateDirectInput(void);
uint32_t GetMouseHUDModeOption(void);
void DisableAutoMouseEmulation(void);
void EnableAutoMouseEmulation(void);
]]
-- Imports.
local Lib = require("extensions.sn_mod_support_apis.lua.Library")
local Time = require("extensions.sn_mod_support_apis.lua.time.Interface")
local T = require("extensions.sn_mod_support_apis.lua.Text")
local Tables = require("extensions.sn_mod_support_apis.lua.hotkey.Tables")
local config = Tables.config
-- Local functions and data.
local debug = {
print_keycodes = false,
print_keynames = false,
}
local L = {
-- Shadow copy of the md's action registry.
action_registry = {},
-- Table of assigned keys and their actions, keyed by id.
-- This is mirrored in a player blackboard var whenever it changes.
player_action_keys = {},
-- Wrapper functions on remapInput to be used in registering for input events.
input_event_handlers = {},
-- Status of the pipe connection, updated from md.
pipe_connected = false,
-- How long to wait after a direct input before reenabling hotkeys.
direct_input_suppress_time = 0.5,
-- Id to use for the alarm.
alarm_id = "hotkey_directinput_timeout",
-- If input currently disabled. Used to suppress some excess signals.
alarm_pending = false,
}
-- Proxy for the gameoptions menu, linked further below.
local menu = nil
-- Signalling results from lua to md.
-- Takes the row,col of the activated widget, and an optional new value
-- for that widget.
-- TODO: think about this more.
local function Raise_Signal(name, value)
AddUITriggeredEvent("Hotkey", name, value)
end
local function Init()
-- Set up ui linkage to listen for text entry state changes.
-- (Goal is to suppress hotkeys when entering text.)
L.scene = getElement("Scene")
L.contract = getElement("UIContract", L.scene)
registerForEvent("directtextinput" , L.contract, L.onEvent_directtextinput)
-- MD triggered events.
RegisterEvent("Hotkey.Update_Actions", L.Update_Actions)
RegisterEvent("Hotkey.Update_Player_Keys", L.Read_Player_Keys)
RegisterEvent("Hotkey.Update_Connection_Status", L.Update_Connection_Status)
RegisterEvent("Hotkey.Process_Message", L.Process_Message)
-- Cache the player component id.
L.player_id = ConvertStringTo64Bit(tostring(C.GetPlayerID()))
-- Signal to md that a reload event occurred.
-- This will also trigger md to send over its stored list of
-- player assigned keys.
Raise_Signal("reloaded")
-- Run the menu init stuff.
L.Init_Menu()
end
-------------------------------------------------------------------------------
-- Handle direct input detection.
-- Handler for direct input key presses.
-- Fires once for each key.
function L.onEvent_directtextinput(some_userdata, char_entered)
-- Note: to get number of vargs, use: select("#",...)
-- This appears to receive 3 args according to the "...", but when trying
-- to capture them only get 2 args.
-- First arg is some userdata object, second is the key pressed (not
-- as a keycode).
--DebugError("Caught directtextinput event; starting disable")
-- Signal md to suppress hotkeys, if not already disabled.
if not L.alarm_pending then
Raise_Signal("disable")
L.alarm_pending = true
end
-- Start or reset the timer.
Time.Set_Alarm(L.alarm_id, L.direct_input_suppress_time, L.Reenable_Hotkeys)
end
function L.Reenable_Hotkeys()
--DebugError("directtextinput event timed out; ending disable")
Raise_Signal("enable")
L.alarm_pending = false
end
-------------------------------------------------------------------------------
-- MD -> Lua signal handlers
-- Process a pipe message, a series of matched hotkey event names
-- semicolon separated.
function L.Process_Message(_, message)
-- Split it.
local events = Lib.Split_String_Multi(message, ";")
-- Add '$' prefixes and return.
for i, event in ipairs(events) do
events[i] = "$"..event
end
-- Send back.
Raise_Signal("handle_events", events)
end
-- Handle md pipe connection status update. Param is 0 or 1.
function L.Update_Connection_Status(_, connected)
-- Translate the 0 or 1 to false/true.
if connected == 0 then
L.pipe_connected = false
else
L.pipe_connected = true
end
end
-- Handle md requests to update the action registry.
-- Reads data from a player blackboard var.
function L.Update_Actions()
-- Args are attached to the player component object.
local md_table = GetNPCBlackboard(L.player_id, "$hotkey_api_actions")
-- Note: md may have sent several of these events on the same frame,
-- in which case the blackboard var has just the args for the latest
-- event, and later events processed will get nil.
-- Skip those nil cases.
if not md_table then return end
L.action_registry = md_table
-- Clear the md var by writing nil.
SetNPCBlackboard(L.player_id, "$hotkey_api_actions", nil)
--Lib.Print_Table(L.action_registry, "Update_Actions action_registry")
end
-- Read in the stored list of player action keys.
-- Generally md will send this on init.
function L.Read_Player_Keys()
-- Args are attached to the player component object.
local md_table = GetNPCBlackboard(L.player_id, "$hotkey_api_player_keys_from_md")
-- This shouldn't get getting nil values since the md init is
-- sent just once, but play it safe.
if not md_table then return end
L.player_action_keys = md_table
-- Clear the md var by writing nil.
SetNPCBlackboard(L.player_id, "$hotkey_api_player_keys_from_md", nil)
--Lib.Print_Table(L.player_action_keys, "Read_Player_Keys player_action_keys")
end
-- Write to the list of player action keys to be stored in md.
-- This could be integrated into remapInput, but kept separate for now.
function L.Write_Player_Keys()
-- Args are attached to the player component object.
SetNPCBlackboard(L.player_id, "$hotkey_api_player_keys_from_lua", L.player_action_keys)
Raise_Signal("Store_Player_Keys")
--Lib.Print_Table(L.player_action_keys, "Write_Player_Keys player_action_keys")
end
-------------------------------------------------------------------------------
-- Menu setup.
-- TODO: break into more init subfunctions for organization.
function L.Init_Menu()
-- Look up the menu, store in this module's local.
menu = Lib.Get_Egosoft_Menu("OptionsMenu")
-- Patch displayOptions.
local ego_displayControls = menu.displayControls
menu.displayControls = function(...)
-- Start by building the original manu.
-- Note that displayControls calls frame:display(), which would need
-- to be called a second time after new rows are added, but leads
-- to backend confusion.
-- Since attempts to re-display after adding new rows lead to many
-- debuglog errors when the menu closes (widgets still alive not
-- having a table), the original display() can be suppressed by
-- intercepting the frame building function, and putting in a
-- dummy function for the frame's display member.
local ego_createOptionsFrame = menu.createOptionsFrame
-- Store the frame and its display function.
local frame
local frame_display
menu.createOptionsFrame = function(...)
-- Build the frame.
frame = ego_createOptionsFrame(...)
-- Record its display function.
frame_display = frame.display
-- Replace it with a dummy.
frame.display = function() return end
-- Return the edited frame to displayControls.
return frame
end
-- Record the prior selected option, since the below call clears it.
local preselectOption = menu.preselectOption
-- Build the menu.
ego_displayControls(...)
-- Reconnect the createOptionsFrame function, to avoid impacting
-- other menu pages.
menu.createOptionsFrame = ego_createOptionsFrame
-- Safety call to add in the new rows.
local success, error = pcall(L.displayControls, preselectOption, ...)
if not success then
DebugError("displayControls error: "..tostring(error))
end
-- Re-attach the original frame display, and call it.
-- (Note: this method worked out great, much better than attempts
-- to re-display after clearing scripts or whatever.)
frame.display = frame_display
frame:display()
end
-- Patch remapInput, which catches the player's new keys.
local ego_remapInput = menu.remapInput
menu.remapInput = function(...)
-- Hand off to ego function if this isn't a custom key.
if menu.remapControl.controlcontext ~= "hotkey_api" then
ego_remapInput(...)
return
end
-- Safety call.
local success, error = pcall(L.remapInput, ...)
if not success then
DebugError("remapInput error: "..tostring(error))
end
end
-- TODO: replace the event registration functions which select which
-- input types to capture. Just want keyboard for custom controls.
-- TODO: also need to suppress hotkey_api from triggering cues while
-- this is going on.
--L.input_event_handlers = {
-- -- Args patterned off of config.input.directInputHookDefinitions.
-- -- Just keyboard for now.
-- ["keyboardInput"] = function (_, keycode) L.remapInput(1, keycode, 0) end,
-- }
--
---- Patch registration.
--local ego_registerDirectInput = menu.registerDirectInput
--menu.registerDirectInput = function()
-- L.registerDirectInput(ego_registerDirectInput)
-- end
--
---- Patch unregistration.
--local ego_unregisterDirectInput = menu.unregisterDirectInput
--menu.unregisterDirectInput = function()
-- L.unregisterDirectInput(ego_unregisterDirectInput)
-- end
-- Listen for when menus open/close, to inform the md side what the
-- current hotkey context is (eg. suppress space-based hotkeys while
-- menus are open).
-- (Alternatively, can check this live by scanning all menus for
-- the menu.shown flag being set and menu.minimized being false.)
--[[
Closing raises a ui signal of the menu name, but that is awkward
to catch for all menus, and not reasonable to account for
modded menus (outside of known mods).
However, any menu closing should eventually call Helper's
local closeMenu() function, which ends by calling
Helper.clearMenu(...), so in theory wrapping clearMenu should
be sufficient to capturing all menu closings.
However, UserQuestionMenu doesn't get caught like others, even though
it has a clear path by which it calls the Helper close function,
even if the menu is set to auto-confirm (eg. when ejecting into
a spacesuit). From a glance at the code, it is unclear why
this particular menu would be difficult.
TODO: maybe revisit this to figure it out.
For now, just ignore the menu.
]]
-- Patch into Helper.clearMenu for closings.
local ego_helper_clearMenu = Helper.clearMenu
Helper.clearMenu = function(menu, ...)
ego_helper_clearMenu(menu, ...)
L.Menu_Closed(menu)
end
-- Unnecessary.
--local function patch_onCloseElement(menu)
-- local ego_onCloseElement = menu.onCloseElement
-- if ego_onCloseElement ~= nil then
-- menu.onCloseElement = function(...)
-- ego_onCloseElement(...)
-- L.Menu_Closed(menu)
-- end
-- end
--end
-- Patch into all menu.showMenuCallback functions to catch when
-- they open. Two steps: patch existing menus, and patch helper
-- for any future registered menus.
-- Both share this bit of logic:
local function patch_showMenuCallback(menu)
local ego_showMenuCallback = menu.showMenuCallback
menu.showMenuCallback = function(...)
ego_showMenuCallback(...)
L.Menu_Opened(menu)
end
-- These callbacks were registered to a 'show<name>' event, so update
-- that registry.
UnregisterEvent("show"..menu.name, ego_showMenuCallback)
RegisterEvent("show"..menu.name, menu.showMenuCallback)
end
-- Patch exiting menus.
for _, menu in ipairs(Menus) do
patch_showMenuCallback(menu)
--patch_onCloseElement(menu)
end
-- Patch future menus.
local ego_registerMenu = Helper.registerMenu
Helper.registerMenu = function(menu, ...)
-- Run helper function first to set up the menu's callback func.
ego_registerMenu(menu, ...)
-- Can now patch it.
patch_showMenuCallback(menu)
--patch_onCloseElement(menu)
end
-- Also want to catch minimized menus.
local ego_minimizeMenu = Helper.minimizeMenu
Helper.minimizeMenu = function(menu, ...)
ego_minimizeMenu(menu, ...)
L.Menu_Minimized(menu)
end
-- And restored menus.
local ego_restoreMenu = Helper.restoreMenu
Helper.restoreMenu = function(menu, ...)
ego_restoreMenu(menu, ...)
L.Menu_Restored(menu)
end
end
-------------------------------------------------------------------------------
-- Menu open/close handlers.
-- Note: TopLevelMenu is the default when no other menus are open, and will
-- generally be ignored here.
-- This is called when menus are closed in Helper.
function L.Menu_Closed(menu)
if menu.name == "TopLevelMenu" then return end
--DebugError("Menu closed: "..tostring(menu.name))
Raise_Signal("Menu_Closed", menu.name)
-- TODO: in practice, some menu closures might get missed.
-- Can maybe check all menu open states, and indicate if they
-- are all closed at the time (to recover from bad information).
-- Can scan all menus for .shown and not .minimized to see if
-- any are open.
end
-- This is called when menus are opened in Helper.
function L.Menu_Opened(menu)
if menu.name == "TopLevelMenu" then return end
if menu.name == "UserQuestionMenu" then return end
--DebugError("Menu opened: "..tostring(menu.name))
Raise_Signal("Menu_Opened", menu.name)
end
-- This is called when menus are minimized in Helper.
-- Treats menu as closing for the md side.
function L.Menu_Minimized(menu)
if menu.name == "TopLevelMenu" then return end
--DebugError("Menu minimized: "..tostring(menu.name))
Raise_Signal("Menu_Closed", menu.name)
end
-- This is called when menus are restored (unminimized) in Helper.
-- Treats menu as opening for the md side.
function L.Menu_Restored(menu)
if menu.name == "TopLevelMenu" then return end
--DebugError("Menu restored: "..tostring(menu.name))
Raise_Signal("Menu_Opened", menu.name)
end
-- TODO: a timed check to occasionally go through all the menus and
-- verify which are open/closed, just incase there is a problem above
-- with missing an opened/closed signal, so that the api can recover.
-- Test code: catching inputs directly.
-- Result: ListenForInput is only good for one key press, and it will
-- prevent that keypress from any other in-game effect.
-- So this is a dead end without a way to refire the caught key artificially.
-- There is also a C.ActivateDirectInput function, but that appears to be
-- just for editboxes when selected to enable typing.
--[[
local keys_to_catch = 10
function L.Input_Listener()
ListenForInput(true)
RegisterEvent("keyboardInput", L.Handle_Caught_Key)
-- In testing, the above only catch a single input, suggesting
-- either ListenForInput or the event registration gets cleared
-- after one catch.
end
function L.Handle_Caught_Key(_, keycode)
DebugError("Caught keyboard keycode: "..tostring(keycode))
keys_to_catch = keys_to_catch -1
if keys_to_catch > 0 then
-- Restart the listen function.
-- Limit how many times it happens, in case this locks out
-- inputs to the game.
ListenForInput(true)
end
end
-- Fire it off.
L.Input_Listener()
]]
-- Patch to add custom keys to the control remap menu.
function L.displayControls (preselectOption, optionParameter)
--DebugError("GameOptions.displayControls() called")
-- Skip if the pipe is not connected, to avoid clutter for users that
-- have this api installed but aren't using the server.
if not L.pipe_connected then return end
-- TODO: skip if there are no actions available. For now, the
-- stock example actions should always be present, so can skip this
-- check.
-- For now, stick keys on the keyboard/space submenu.
-- Skip others.
if optionParameter ~= "keyboard_space" then return end
-- Look up the frame with the table.
-- This should be in layer 3, matching config.optionsLayer.
local frame = menu.optionsFrame
if frame == nil then
error("Failed to find gameoptions menu main frame")
end
-- Look up the table in the frame.
-- There is probably just the one content entry, but to be safe
-- search content for a table.
-- TODO: could maybe also do menu.optionTable.
local ftable
for i=1,#frame.content do
if frame.content[i].type == "table" then
ftable = frame.content[i]
end
end
if ftable == nil then
error("Failed to find gameoptions menu main ftable")
end
-- Error check.
if not L.action_registry then
DebugError("action_registry is nil")
return
end
-- Add some space.
row = ftable:addRow(false, { bgColor = Helper.color.transparent })
row[2]:setColSpan(3):createText(" ", {
fontsize = 1,
height = config.infoTextHeight,
cellBGColor = Helper.color.transparent60 })
-- Add a nice title.
-- Make this a larger than normal font.
local row = ftable:addRow(false, { bgColor = Helper.color.transparent })
row[2]:setColSpan(3):createText(T.extensions, config.subHeaderTextProperties_2)
-- Make sure all actions have an entry in the player keys table.
for _, action in pairs(L.action_registry) do
if not L.player_action_keys[action.id] then
L.player_action_keys[action.id] = {
-- Repetition of id, in case it is ever useful.
-- (This will not get a $ prefix went sent to md.)
id = action.id,
-- List of inputs.
-- Note: unused entries are elsewhere {-1,-1,0}, though that
-- led to problems when tried. All nil works okay.
inputs = {
[1] = {combo = "", code = nil, source = nil, signum = nil},
[2] = {combo = "", code = nil, source = nil, signum = nil},
}
}
end
end
-- Set up the custom actions.
-- These will be sorted into their categories, with uncategorized
-- lumped together at the top of the menu.
-- Start by sorting actions into categories.
local cat_action_dict = {}
for _, action in pairs(L.action_registry) do
local cat = action.category
-- Set default category.
if not cat then cat = "" end
-- Set up a new sublist if needed.
if not cat_action_dict[cat] then cat_action_dict[cat] = {} end
-- Add it in.
table.insert(cat_action_dict[cat], action)
end
-- Convert the cat table to a list, to enable lua sorting.
local cats_sorted = {}
for cat, sublist in pairs(cat_action_dict) do
table.insert(cats_sorted, cat)
-- Also sort the actions by name while here.
-- This lambda function returns True if the left arg goes first.
table.sort(sublist, function (a,b) return (a.name < b.name) end)
end
-- Sort the cat names.
table.sort(cats_sorted)
-- Loop over cat names.
for _, cat in ipairs(cats_sorted) do
-- Make a header if this is a named category.
if cat ~= "" then
local row = ftable:addRow(false, { bgColor = Helper.color.transparent })
row[2]:setColSpan(3):createText(cat, config.subHeaderTextProperties)
end
-- Loop over the sorted action list.
for _, action in ipairs(cat_action_dict[cat]) do
-- Hand off to custom function.
L.displayControlRow(ftable, action.id)
end
end
-- Fix the row selection.
-- The preselectOption should match the id of the desired row.
-- TODO: maybe fix the preselectCol as well, though not as important;
-- see gameoptions around line 2482.
for i = 1, #ftable.rows do
if ftable.rows[i].index == preselectOption then
ftable:setSelectedRow(ftable.rows[i].index)
break
end
end
-- -Removed; display is handled above.
--[[
-- Need to re-display.
-- TODO: stress test for problems.
-- In practice, this causes log warning spam if display() done directly,
-- since the display() function builds a whole new frame, but the old
-- frame's scripts weren't cleared out.
-- Manually do the script clear first.
-- (Unlike clearDataForRefresh, this call just removes scripts,
-- not existing widget descriptors.)
Helper.removeAllWidgetScripts(menu, config.optionsLayer)
-- TODO: need to revit this all again; when the menu is closed it throws
-- ~1600 errors into the log with: "GetCellContent(): invalid table ID
-- 2336 - table might have been destroyed already." (Where the id
-- number changes each time.)
-- Suggests something; not sure what.
frame:display()
]]
end
-- Copy/edit of ego's function for displaying a control row of text
-- and two buttons.
-- Attempts to reuse ego's function were a mess.
function L.displayControlRow(ftable, action_id)
local action = L.action_registry[action_id]
local player_keys = L.player_action_keys[action_id]
local row = ftable:addRow(true, { bgColor = Helper.color.transparent })
-- Select the row if it was selected before menu reload.
if row.index == menu.preselectOption then
ftable:setSelectedRow(row.index)
-- Select a column, 3 or 4, those with buttons.
if menu.preselectCol == 3 or menu.preselectCol == 4 then
ftable:setSelectedCol(menu.preselectCol)
end
end
-- Set the action title.
-- This is column 2, since 1 is under the back arrow.
row[2]:createText(action.name, config.standardTextProperties)
if action.description then
row[2].properties.mouseOverText = action.description
end
-- Create the two buttons.
for i = 1,2 do
local info = player_keys.inputs[i]
-- Get the name of an existing key, or blank.
local keyname, keyicon = "", nil
if info.source then
keyname, keyicon = menu.getInputName(info.source, info.code, info.signum)
end
-- Skip the funkiness regarding truncating the text string to
-- make room for the icon. TODO: maybe revisit if needed.
-- Buttons start at column 3, so offset i.
local col = i+2
local button = row[col]:createButton({ mouseOverText = action.description or "" })
-- Set up the text label; this applies even without a keyname since
-- it handles blinking _.
button:setText(
-- 'nameControl' handles label blinking when changing.
function () return menu.nameControl(keyname, row.index, col) end,
-- Can probably leave color at default; don't need 'red' logic.
{ color = Helper.color.white })
-- Add the icon.
if keyicon then
button:setText2(keyicon, { halign = "right" })
end
-- Clicks will hand off to buttonControl.
row[col].handlers.onClick = function () return menu.buttonControl(
-- Second arg is a list with a specific ordering.
row.index, {
-- controltype; go with whatever.
"functions",
-- controlcode; go with the action id.
action_id,
-- oldinputtype
info.source,
-- oldinputcode
info.code,
-- oldinputsgn
info.signum,
-- column
col,
-- not_mapable/nokeyboard
false,
-- control_context; put whatever.
"hotkey_api",
-- allowmouseaxis
false,
}) end
-- Unclear on if this is good for anything; probably not.
--row[col].properties.uiTriggerID = "remapcontrol1a"
end
end
--[[
The following functions are after buttonControl(), the function
called when a button is pressed.
At this point, most of the args fed to displayControlRow are
present in a named table at menu.remapControl.
Fields are:
{ row, col, controltype, controlcode, controlcontext, oldinputtype,
oldinputcode, oldinputsgn, nokeyboard, allowmouseaxis}
]]
-- This handles player input when setting custom keys.
-- Should only be called on player keys, not ego keys, so has no link
-- back to the original remapInput.
function L.remapInput(...)
-- Always call this; ego does it right away.
menu.unregisterDirectInput()
-- Code to call on any return path, except those that still listen
-- for keys.
local return_func = function()
-- Reboot the menu. All paths in ego code end with this, so it may
-- be required to recover properly.
-- (At least need to clear remapControl, since it being filled triggers
-- other code, eg. trying to unregister events when the menu closes
-- causes log errors.)
menu.preselectTopRow = GetTopRow(menu.optionTable)
menu.preselectOption = menu.remapControl.row
menu.preselectCol = menu.remapControl.col
menu.remapControl = nil
menu.submenuHandler(menu.currentOption)
end
-- Safety wrap the rest of this logic.
local success, error = pcall(L.remapInput_wrapped, return_func, ...)
-- On error, still aim for the good return function setup.
if not success then
DebugError("remapInput error: "..tostring(error))
return_func()
end
end
-- Inner part of remapInput, allowed to error.
function L.remapInput_wrapped(return_func, newinputtype, newinputcode, newinputsgn)
if debug.print_keycodes then
Lib.Print_Table({
controlcode = menu.remapControl.controlcode,
newinputtype = newinputtype,
newinputcode = newinputcode,
newinputsgn = newinputsgn,
}, "Control remap info")
--DebugError(string.format(
-- "Detected remap of code '%s'; new aspects: type %s, %s, %s",
-- tostring(menu.remapControl.controlcode),
-- tostring(newinputtype),
-- tostring(newinputcode),
-- tostring(newinputsgn)
-- ))
--Lib.Print_Table(menu.remapControl, "menu.remapControl")
end
-- Look up the matching action.
local action_keys = L.player_action_keys[menu.remapControl.controlcode]
-- Error if not found.
if not action_keys then
error("Found no action_keys matching id: "..tostring(menu.remapControl.controlcode))
end
-- 'newinputtype' will be 1 for keyboard.
-- Since only keyboard is wanted for now, restart listening if something
-- else arrived.
if newinputtype ~= 1 then
-- DebugError("Hotkey: Non-keyboard input not supported.")
menu.registerDirectInput()
-- Normal return; keep listener going.
return
end
-- TODO: consider integrating other ego style functions for avoiding
-- control conflicts and such.
-- Use col (3 or 4) to know which index to replace (1 or 2).
-- Try to make this a little safe against patches adding columns.
local input_index
if menu.remapControl.col <= 3 then
input_index = 1
else
input_index = 2
end
-- Note the prior key combo.
local old_combo = action_keys.inputs[input_index].combo
local new_combo
-- Note: ego menu behavior has "escape" cancel the selection with no change,
-- and "delete" remove the key binding.
-- Try to mimic that here.
-- Check for escape.
if newinputtype == 1 and newinputcode == 1 then
-- Do nothing.
return return_func()
-- Check for "delete" on a key that was mapped.
-- (oldinputcode == -1 means it wasn't mapped.)
elseif newinputtype == 1 and newinputcode == 211 then
-- Prepare to reset to defaults.
newinputtype = nil
newinputcode = nil
newinputsgn = nil
new_combo = ""
if debug.print_keynames then
DebugError("Deleting key combo: "..old_combo)
end
else
-- Get the new combo string.
new_combo = string.format("code %d %d %d", newinputtype, newinputcode, newinputsgn)
-- -Removed, updated 3.0 makes ego's version too hard to use since
-- it uses some special escape character and icon code for modifiers.
---- Start with ego's key name.
---- TODO: probably not robust across languages.
---- TODO: try out GetLocalizedRawKeyName
--local ego_key_name, icon = menu.getInputName(newinputtype, newinputcode, newinputsgn)
--
---- These are uppercase and with "+" for modified keys.
---- Translate to the combo form: space separated lowercase.
--new_combo = string.lower( string.gsub(ego_key_name, "+", " ") )
--if debug.print_keynames then
-- DebugError(string.format("Ego key %s translated to combo %s", ego_key_name, new_combo))
--end
end
-- If the new_combo is already recorded as either of the existing inputs,
-- and is not empty (eg. deleting binding), do nothing.
if new_combo ~= "" and (action_keys.inputs[1].combo == new_combo or action_keys.inputs[2].combo == new_combo) then
if debug.print_keynames then
DebugError("Ignoring already recorded key combo: "..new_combo)
end
return return_func()
end
-- Overwrite stored key.
action_keys.inputs[input_index] = {
combo = new_combo,
code = newinputcode,
source = newinputtype,
signum = newinputsgn }
-- Signal lua to update if the combo changed.
Raise_Signal("Update_Key", {
id = action_keys.id,
new_key = new_combo,
old_key = old_combo,
})
-- Update the md to save the keys.
-- TODO: maybe integrate into Update_Key calls.
L.Write_Player_Keys()
return return_func()
end
---- Patch registration.
---- Unused currently.
--function L.registerDirectInput(ego_registerDirectInput)
-- -- Check for this being a custom key.
-- if menu.remapControl.controlcontext == 1000 then
-- C.DisableAutoMouseEmulation()
-- for event, func in pairs(L.input_event_handlers) do
-- RegisterEvent(event, func)
-- end
-- ListenForInput(true)
-- else
-- ego_registerDirectInput()
-- end
--end
--
---- Patch unregistration.
---- Unused currently.
--function L.unregisterDirectInput(ego_unregisterDirectInput)
-- -- Check for this being a custom key.
-- if menu.remapControl.controlcontext == 1000 then
-- ListenForInput(false)
-- for event, func in pairs(L.input_event_handlers) do
-- UnregisterEvent(event, func)
-- end
-- C.EnableAutoMouseEmulation()
-- else
-- ego_unregisterDirectInput()
-- end
--end
Init()
--[[
Development notes:
The existing ui functions are in gameoptions.lua.
config.input.controlsorder
- Holds data on various keys
- Subfields space, menus, firstperson
- Nested tables have section titles, table of keys.
- Each key entry's arg order appears to be:
- [controltype, code, context, mouseovertext, allowmouseaxis]
- Many keys leave fields 3-5 unused.
- Local, so no way to add keys without direct overwrite.
config.input.controlsorder.space[i]
- Table, keyed partially by indices and partly by named fields.
- .title, .mapable, [1-5]
config.input.directInputHookDefinitions
List of sublists like:
{"keyboardInput", 1, 0}
config.input.directInputHooks
config.input.directInputHooks
- Table of functions, one per directInputHookDefinition.
- Functions take a keycode, and call menu.remapInput with info on what type of input.
- One function for each input type: keyboard, mouse, occulus, vive, and subtypes.
- Ex: function (_, keycode) menu.remapInput(entry[2], keycode, entry[3])
config.input.forbiddenkeys
Gives a couple examples of keycodes:
[1] = true, - Escape
[211] = true, - Delete
menu
- Table that defines menu properties, registered with general gui.
- Accessible through Menus global, so functions can potentially overwritten.
- Since functions often reference locals, overwrites may not be very useful,
as other files won't have access to those locals.
menu.getInputName(source, code, signum)
Translates a key code into a name.
'source' is an integer which appears to represent input source (keyboard, mouse, ...)
'signum' appears to add a "+" or "-" if used.
Keyboard key names are from GetLocalizedRawKeyName(code).
Mouse button names are from ffi.string(C.GetLocalizedRawMouseButtonName(code)).
Others are from the text file.
Text file has names of some key codes:
Page 1018: mouse axes
Page 1022: joystick buttons
etc.
menu.displayControls(string optionParameter)
- Creates the whole controls tab, for one of space, menus, or first person.
- Hardcoded for these three; don't bother adding a new category without
substantial copy/paste monkeypatching.
- Loops over "controls", eg. members of config.input.controlsorder.space
- Makes a section label, eg. "Steering: Analog"
- Calls menu.displayControlRow() for each key, passing args.
menu.displayControlRow(ftable, controlsgroup, controltype, code, context, mouseovertext, mapable, isdoubleclickmode, allowmouseaxis)
Handles drawing one row of the keybind menu.
'code' is for a specific function being mapped.
(controlsgroup, controltype, code, context, mouseovertext) are unpacked from config.input.controlsorder,
often with (controlsgroup, controltype) filled and others nil.
Current key texts are taken from menu.nameControl(), which is fed the
name and may replace it with blinking "_"/"" for a key currently
being remapped.
Button onClick events call menu.buttonControl() which triggers the
remapping.
This will look up various data from menu.controls, which was
set in menu.getControlsData(). This is a table of control types,
with most being pulled from C code except for "functions"
which is pulled from config.input.controlFunctions.
displayControlRow will reference:
menu.controls[controltype][code]
.name
.contexts
.definingcontrol
'controltype' needs to be "functions" else displayControlRow will
try to read the name from config, where it isn't available.
Each "functions" entry defines a "definingcontrol" field, which
is a reference to another controls subtable and key.
Eg. {"states", 22} will get redirected to menu.controls["states"][22].
This in turn is a list of "inputs" (up to 2), where each input
is a list of {source, code, signum}, the current input for
that control.
If reusing this function, the related tables need to be updated:
"functions" with a name and definingcontrol.
"actions" or similar with the current recorded input, originally
saved from md.
menu.buttonControl(row_index, data_table)
- Called when user clicks an input remap button.
- data_table is a list with the following fields:
{controltype, controlcode, oldinputtype, oldinputcode, oldinputsgn, column (often set to 3 or 4), not_mapable/nokeyboard, control_context, allowmouseaxis}
- Stores a table including data_table contents into menu.remapControl for lookup later.
- Names all the args, and adds 'row'.
- Sets up info for blinking button during remapping.
- Calls menu.registerDirectInput() to listen for user key press.
menu.registerDirectInput(...)
- Runs RegisterEvent on all events in config.input.directInputHookDefinitions,
setting functions in config.input.directInputHooks as handlers.
- Calls ListenForInput(true).
- So, this is where it kicks off listening for a new user key press.
- Presumably, ListenForInput sets a mode which will raise one of these
events, eg. "keyboardInput" on a key press.
ListenForInput(?)
External function; unknown behavior.
menu.unregisterDirectInput()
Undoes registerDirectInput: unregisters events, calls ListenForInput(false).
menu.remapInput(newinputtype, newinputcode, newinputsgn)
- Has a bunch of logic for processing the key.
- Clears conflicts, rejects disallowed keys, etc.
- Calls menu.unregisterDirectInput(), to stop listening for new keys.
- Calls checkInput, presumably to clear conflicts.
- May delete a key if 211 (delete) was pressed.
- Calls menu.removeInput() on this path.
- At end calls SaveInputSettings(menu.controls.actions, menu.controls.states, menu.controls.ranges).
- SaveInputSettings is exe level.
- Note: this is not called directly, but indirectly through menu.registerDirectInput()
which in turn looks it up in config.input.directInputHooks, initialized
on lua loading. Those wrapper funcs do look it up in menu, though, so
a direct monkey patch works.
menu.removeInput()
At end calls SaveInputSettings(menu.controls.actions, menu.controls.states, menu.controls.ranges).
SaveInputSettings(?,?,?)
External function; unknown behavior.
Presumably this transfers current key mappings to exe side for actual
key listening and functionality.
Keycodes:
- The example codes for escape (1) and delete (211) don't mach up with windows keycodes.
- However, they do match this lua file, and its linked c++ file:
- https://github.com/lukemetz/moonstone/blob/master/src/lua/utils/keycodes.lua
- https://github.com/wgois/OIS/blob/master/includes/OISKeyboard.h
- Using the above, can potentially translate user keys appropriately.
Possibly adding new keys:
a) monkeypatch menu.displayControls.
- Run the normal version first; this ends in frame:display() (worrisome).
- Add a custom section title.
- Call menu.displayControlRow() for each new key, matching args.
b) patch menu.remapInput to catch user assignments.
]] |
local keymap = vim.api.nvim_set_keymap
local function set_keybindings()
local noremap_silent = { noremap = true, silent = true }
local remap_silent = { noremap = false, silent = true }
local remap_nosilent = { noremap = false, silent = true }
local keybindings = {
-- {'mode', 'keybindings', 'command', '{noremap=bool', 'silent=bool', expr=bool}}
-- disable keys
{ "n", "Q", "<Nop>", noremap_silent },
{ "n", "<Left>", "<Nop>", noremap_silent },
{ "n", "<Right>", "<Nop>", noremap_silent },
{ "n", "<Up>", "<Nop>", noremap_silent },
{ "n", "<Down>", "<Nop>", noremap_silent },
{ "n", "<C-z>", "<Nop>", noremap_silent },
-- resize window
{ "n", "<C-Left>", "<CMD>vertical resize +5<CR>", noremap_silent },
{ "n", "<C-Up>", "<CMD>resize -5<CR>", noremap_silent },
{ "n", "<C-Right>", "<CMD>vertical resize -5<CR>", noremap_silent },
{ "n", "<C-Down>", "<CMD>resize +5<CR>", noremap_silent },
-- split window
{ "n", "<C-A-k>", "<C-w>t<C-w>K", remap_silent },
{ "n", "<C-A-h>", "<C-w>t<C-w>H", remap_silent },
-- terminal mode
{ "t", "<Esc>", "<C-\\><C-n>", noremap_silent },
-- nvim tree.lua
{ "n", "`", '<CMD>lua require("utils.nvimtree").toggle()<CR>', noremap_silent },
-- base64
{
"v",
"<Leader>d6",
"c<C-r>=system('base64 -d', @\")<CR><ESC>",
remap_nosilent,
},
{
"v",
"<Leader>e6",
"c<C-r>=system('base64', @\")<CR><ESC>",
remap_nosilent,
},
-- emmet-vim
{ "i", "<A-Tab>", "<C-y>,", remap_silent },
{ "v", "<A-Tab>", "<C-y>,", remap_silent },
-- Delete in search result
{ "n", "<Leader>x", "<CMD>%s///<CR>", remap_silent },
-- Search for visually selected text
{ "v", "<Leader>v", "y/\\V<C-R>=escape(@\",'/\\')<CR><CR>", remap_silent },
-- format.nvim
{ "n", "<leader>F", "<CMD>FormatWrite<CR>", remap_silent },
}
for _, key in pairs(keybindings) do
keymap(key[1], key[2], key[3], key[4])
end
end
set_keybindings()
|
return {
id = 2,
type = 2,
ip = "127.0.0.1",
port = 60002,
path = "db_svr",
mysql =
{
{
ip = "127.0.0.1",
port = 3306,
username = "testmn",
password = "123456",
db_name = "mn_login_db",
db_type = 1,
},
},
}
|
--[[ Copyright (c) 2011 Ted "IntelOrca" John
2013 Edvin "Lego3" Linge
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. --]]
--! Charts fullscreen window
class "UIGraphs" (UIFullscreen)
---@type UIGraphs
local UIGraphs = _G["UIGraphs"]
local TH = require "TH"
-- These values are based on the background colours of the pen symbols
local colours = {
money_in = {182, 32, 16},
money_out = {215, 81, 8},
wages = {194, 162, 0},
balance = {28, 138, 36},
visitors = {0, 101, 198},
cures = {36, 40, 154},
deaths = {130, 0, 178},
reputation = {215, 12, 101}
}
function UIGraphs:UIGraphs(ui)
self:UIFullscreen(ui)
local gfx = ui.app.gfx
if not pcall(function()
self.background = gfx:loadRaw("Graph01V", 640, 480)
local palette = gfx:loadPalette("QData", "Graph01V.pal")
palette:setEntry(255, 0xFF, 0x00, 0xFF) -- Make index 255 transparent
self.panel_sprites = gfx:loadSpriteTable("QData", "Graph02V", true, palette)
self.white_font = gfx:loadFont("QData", "Font01V", false, palette)
self.black_font = gfx:loadFont("QData", "Font00V", false, palette)
end) then
ui:addWindow(UIInformation(ui, {_S.errors.dialog_missing_graphics}))
self:close()
return
end
self.hospital = ui.hospital
-- Buttons
self:addPanel(0, 63, 384):makeButton(0, 0, 26, 26, 3, self.close):setTooltip(_S.tooltip.graphs.close)
-- The possible scales are:
-- 1: Increments of four years per line
-- 2: Increments of one year per line
-- 3: Increments of one month per line
self.graph_scale = 3
self.graph_scale_panel = self:addPanel(0, 371, 384)
self.graph_scale_button = self.graph_scale_panel:makeButton(0, 0, 65, 26, 2, self.toggleGraphScale):setTooltip(_S.tooltip.graphs.scale)
self.hide_graph = {}
local function buttons(name)
return --[[persistable:graphs_button]] function()
self:toggleGraph(name)
end
end
self.graph_buttons = {
self:addPanel(0, 590, 34):makeToggleButton(0, 0, 42, 42, 1, buttons("money_in")):setTooltip(_S.tooltip.graphs.money_in),
self:addPanel(0, 590, 86):makeToggleButton(0, 0, 42, 42, 1, buttons("money_out")):setTooltip(_S.tooltip.graphs.money_out),
self:addPanel(0, 590, 138):makeToggleButton(0, 0, 42, 42, 1, buttons("wages")):setTooltip(_S.tooltip.graphs.wages),
self:addPanel(0, 590, 190):makeToggleButton(0, 0, 42, 42, 1, buttons("balance")):setTooltip(_S.tooltip.graphs.balance),
self:addPanel(0, 590, 243):makeToggleButton(0, 0, 42, 42, 1, buttons("visitors")):setTooltip(_S.tooltip.graphs.visitors),
self:addPanel(0, 590, 295):makeToggleButton(0, 0, 42, 42, 1, buttons("cures")):setTooltip(_S.tooltip.graphs.cures),
self:addPanel(0, 590, 347):makeToggleButton(0, 0, 42, 42, 1, buttons("deaths")):setTooltip(_S.tooltip.graphs.deaths),
self:addPanel(0, 590, 400):makeToggleButton(0, 0, 42, 42, 1, buttons("reputation")):setTooltip(_S.tooltip.graphs.reputation)
}
self:updateLines()
end
local TOP_Y = 85 -- Top of the graph area
local BOTTOM_Y = 353 -- Bottom of the graph area
local RIGHT_X = 346 -- Right side of the graph area
local VERT_DX = 25 -- Spacing between the vertical lines in the graph
local VERT_COUNT = 12 -- Number of vertical lines in the graph
local GRAPH_HEIGHT = BOTTOM_Y - TOP_Y
--! Compute the vertical position of a value in the graph given the line extremes
--!param graph_line (table) Meta data of the line, including extreme values.
--!param value (number) Value to position vertically in the graph.
--!return Y position in the graph of the value.
local function computeVerticalValuePosition(graph_line, value)
-- 0 is always included in the range.
assert(graph_line.maximum >= 0 and graph_line.minimum <= 0)
local range = graph_line.maximum - graph_line.minimum
if range == 0 then return BOTTOM_Y end
return BOTTOM_Y - math.floor(((value - graph_line.minimum) / range) * GRAPH_HEIGHT)
end
--! Convert graph scale to a stepsize in months.
--!param graph_scale (int, 1 to 3) Graph scale to display.
--!return Number of months to jump between statistics values in the hospital statistics data.
local function getStatisticsStepsize(graph_scale)
local stepsize = 4 * 12 -- Four years
if graph_scale == 2 then
stepsize = 12 -- One year
elseif graph_scale == 3 then
stepsize = 1 -- A month
end
return stepsize
end
--! Get the statistics from the hospital that should be displayed.
--! Selection starts at the last (=newest) entry, and goes back in time.
--!return The values of all statistics to plot in the graph display.
function UIGraphs:getHospitalStatistics()
local statistics = self.hospital.statistics
local values = {}
local i = #statistics -- Picking hospital statistics from right to left (recent to old).
local stats_stepsize = getStatisticsStepsize(self.graph_scale)
while #values < VERT_COUNT and i >= 1 do
values[#values + 1] = statistics[i]
i = i - stats_stepsize
end
return values
end
--! Reposition the given sequence of text entries vertically such that the maximum
-- absolute deviation from the ideal position is minimized.
--!param label_datas (array) Text entries
--!param start_index (int) First entry to move.
--!param last_index (int) Last entry to move.
local function moveSequence(label_datas, start_index, last_index)
-- min_y, max_y Smallest and biggest vertical position of the labels. Since
-- they are sorted on y, it's the position of the first and last visible entry.
-- min_y_shift, max_y_shift Vertical movement of the label of the first and
-- last visible entry for vertically centering the text.
-- min_dev, max_dev Smallest and biggest deviation from the optimal position,
-- for all visible labels.
local min_y = nil
local max_y, min_y_shift, max_y_shift, min_dev, max_dev
for i = start_index, last_index do
local label = label_datas[i]
if label.pos_y then -- Label is visible
local deviation = label.pos_y - label.ideal_y -- Positive if moved down
if min_y then -- Updating the max y, and deviations
max_y = label.pos_y
max_y_shift = label.shift_y
min_dev = math.min(min_dev, deviation)
max_dev = math.max(max_dev, deviation)
else -- First time entering the loop
min_y = label.pos_y
max_y = label.pos_y
min_y_shift = label.shift_y
max_y_shift = label.shift_y
min_dev = deviation
max_dev = deviation
end
end
end
-- There should be at least one visible entry in the provided range.
assert(min_y ~= nil)
local move = -math.floor((max_dev + min_dev) / 2) -- Suggested movement of the sequence.
-- Verify the sequence will stay inside graph upper and lower limits, adjust otherwise.
if min_y + min_y_shift + move < TOP_Y then
move = TOP_Y - min_y - min_y_shift
elseif max_y + max_y_shift + move > BOTTOM_Y then
move = BOTTOM_Y - max_y - max_y_shift
end
-- And update the positions.
for i = start_index, last_index do
local label = label_datas[i]
if label.pos_y then label.pos_y = label.pos_y + move end
end
end
--! Compute new actual position of the labels.
--!param graph (UIGraphs) Graph window object
local function updateTextPositions(graph)
-- Reset vertical position of the text back to its ideal position.
-- Disable computations on invisible graphs by removing the actual y position of it.
for _, label in ipairs(graph.label_datas) do
if graph.hide_graph[label.stat] then
label.pos_y = nil
else
label.pos_y = label.ideal_y
end
end
-- Move labels of the graphs such that they stay at the right of the graph
-- between their upper and lower boundaries.
local sequence_moved = true
local collision_count = 8 -- In theory the loop should terminate, but better safe than sorry.
while sequence_moved and collision_count > 0 do
collision_count = collision_count - 1
sequence_moved = false
-- Find sequences of text entries that partly overlap or have no vertical
-- space between them. Entries in such a sequence cannot be moved
-- individually, the sequence as a whole must move.
local start_index, last_index = nil, nil -- Start and end of the sequence.
local collision = false -- True collision detected in the sequence
local prev_index, prev_label = nil, nil
for i, label in ipairs(graph.label_datas) do
if label.pos_y then -- Label is visible
if prev_label then
-- Bottom y of previous label, top of current label
local bottom_prev = prev_label.pos_y + prev_label.shift_y + prev_label.size_y
local top_current = label.pos_y + label.shift_y
if top_current < bottom_prev then
-- True collision, text has to move
collision = true
sequence_moved = true
label.pos_y = bottom_prev - label.shift_y
if not start_index then start_index = prev_index end
last_index = i
elseif top_current == bottom_prev then
-- Entry is concatenated to the sequence, position is fine.
if not start_index then start_index = prev_index end
last_index = i
else
-- Entry is not part of the sequence, move previous sequence to its
-- optimal spot if required
if collision then
moveSequence(graph.label_datas, start_index, last_index)
end
collision = false
start_index = nil
last_index = nil
-- Do not consider the current text in this round. The next entry may
-- see it as the start of a next sequence.
end
end
prev_label = label
prev_index = i
end
end
if collision then
moveSequence(graph.label_datas, start_index, last_index)
end
end
end
function UIGraphs:updateLines()
self.values = self:getHospitalStatistics()
-- Construct meta data about each graph line.
local graph_datas = {} -- Table ordered by statistics name.
self.graph_datas = graph_datas
for stat, _ in pairs(self.values[1]) do
graph_datas[stat] = {line = nil, maximum = 0, minimum = 0}
end
-- Decide maximum and minimum for normalisation of each line.
-- 0 is always included in the computed range.
for _, stats in ipairs(self.values) do
for stat, value in pairs(stats) do
if value < graph_datas[stat].minimum then
graph_datas[stat].minimum = value
end
if value > graph_datas[stat].maximum then
graph_datas[stat].maximum = value
end
end
end
-- Add the line objects of the graph.
for stat, graph_data in pairs(self.graph_datas) do
local line = TH.line()
line:setWidth(2)
local hue = colours[stat]
line:setColour(hue[1], hue[2], hue[3], 255)
graph_data.line = line
end
-- Add the graph line pieces. Doing this separately is more efficient as all
-- graph lines can be extended to the left in the same iteration.
local xpos = RIGHT_X
for i, stats in ipairs(self.values) do
for stat, value in pairs(stats) do
local line = graph_datas[stat].line
local ypos = computeVerticalValuePosition(graph_datas[stat], value)
if i == 1 then
line:moveTo(xpos, ypos)
else
line:lineTo(xpos, ypos)
end
end
xpos = xpos - VERT_DX
end
-- Compute label data for each statistic, and order by vertical position.
-- The newest statistic values are displayed at the right edge of the graph,
-- which decides the optimal position of the graph label text and value.
local label_datas = {}
self.label_datas = label_datas
for stat, value in pairs(self.values[1]) do
local ideal_y = computeVerticalValuePosition(graph_datas[stat], value)
local text = _S.graphs[stat] .. ":"
local _, size_y, _ = self.black_font:sizeOf(text)
label_datas[#label_datas + 1] = {
stat = stat, -- Name of the statistic it belongs to.
text = text, -- Translated label text.
ideal_y = ideal_y, -- Ideal vertical position.
pos_y = nil, -- Actual position for drawing.
size_y = size_y, -- Vertical size of the text.
shift_y = -math.floor(size_y / 2), -- Amount of shift to center the text.
value = value} -- Numeric value to display.
end
-- Sort the labels of the graph on ideal y position, and compute actual position.
local function compare(a,b)
return a.ideal_y < b.ideal_y
end
table.sort(label_datas, compare)
updateTextPositions(self)
-- Create small lines going from the number of month name to the actual graph.
-- Like the lines, index runs from right to left at the screen.
local aux_lines = {}
self.aux_lines = aux_lines
xpos = RIGHT_X
for _ = 1, #self.values do
local line = TH.line()
line:setWidth(1)
line:moveTo(xpos, BOTTOM_Y + 2)
line:lineTo(xpos, BOTTOM_Y + 8)
aux_lines[#aux_lines + 1] = line
xpos = xpos - VERT_DX
end
end
function UIGraphs:draw(canvas, x, y)
self.background:draw(canvas, self.x + x, self.y + y)
UIFullscreen.draw(self, canvas, x, y)
x, y = self.x + x, self.y + y
self.white_font:draw(canvas, _S.graphs.money_in, x + 502, y + 41, 80, 27)
self.white_font:draw(canvas, _S.graphs.money_out, x + 502, y + 93, 80, 27)
self.white_font:draw(canvas, _S.graphs.wages, x + 502, y + 145, 80, 27)
self.white_font:draw(canvas, _S.graphs.balance, x + 502, y + 197, 80, 27)
self.white_font:draw(canvas, _S.graphs.visitors, x + 502, y + 249, 80, 27)
self.white_font:draw(canvas, _S.graphs.cures, x + 502, y + 301, 80, 27)
self.white_font:draw(canvas, _S.graphs.deaths, x + 502, y + 353, 80, 27)
self.white_font:draw(canvas, _S.graphs.reputation, x + 502, y + 405, 80, 27)
-- Draw the different lines
for stat, graph in pairs(self.graph_datas) do
if not self.hide_graph[stat] then
graph.line:draw(canvas, x, y)
end
end
-- Draw strings showing what values each entry has at the moment just to the right of the graph.
-- TODO: These should be coloured according to the colour of the corresponding line.
for _, label in pairs(self.label_datas) do
if label.pos_y then
local ypos = label.pos_y + label.shift_y
self.black_font:draw(canvas, label.text, x + RIGHT_X + 3, y + ypos)
self.black_font:draw(canvas, label.value, x + RIGHT_X + 60, y + ypos)
end
end
local stats_stepsize = getStatisticsStepsize(self.graph_scale)
local xpos = x + RIGHT_X
-- Draw numbers (or month names) below the graph
assert(#self.hospital.statistics > 0) -- Avoid negative months and years.
if stats_stepsize >= 12 then
-- Display years
local year_number = math.floor((#self.hospital.statistics - 1) / 12)
for i = 1, #self.values do
self.black_font:drawWrapped(canvas, year_number, xpos, y + BOTTOM_Y + 10, 25, "center")
xpos = xpos - VERT_DX
year_number = year_number - math.floor(stats_stepsize / 12)
-- And the small black line
self.aux_lines[i]:draw(canvas, x, y)
end
else
-- Display months
local month_number = #self.hospital.statistics - math.floor((#self.hospital.statistics - 1) / 12) * 12
for i = 1, #self.values do
self.black_font:drawWrapped(canvas, _S.months[month_number], xpos, y + BOTTOM_Y + 10, 25, "center")
xpos = xpos - VERT_DX
month_number = month_number - stats_stepsize
if month_number < 1 then month_number = month_number + 12 end
-- And the small black line
self.aux_lines[i]:draw(canvas, x, y)
end
end
end
function UIGraphs:toggleGraphScale()
self.graph_scale = self.graph_scale + 1
if self.graph_scale == 4 then self.graph_scale = 1 end
self:updateLines()
self.ui:playSound("selectx.wav")
end
function UIGraphs:toggleGraph(name)
self.hide_graph[name] = not self.hide_graph[name]
self.ui:playSound("selectx.wav")
updateTextPositions(self)
end
function UIGraphs:close()
UIFullscreen.close(self)
self.ui:getWindow(UIBottomPanel):updateButtonStates()
end
function UIGraphs:afterLoad(old, new)
if old < 117 then
self:close()
end
end
|
local translate = {}
translate.Beam = require('onmt.translate.Beam')
translate.PhraseTable = require('onmt.translate.PhraseTable')
translate.Translator = require('onmt.translate.Translator')
return translate
|
--
-- buddies
--
-- Copyright (c) 2015 Sheepolution
--
-- This library is free software; you can redistribute it and/or modify it
-- under the terms of the MIT license. See LICENSE for details.
local buddies = {}
local func = {}
local superfunc = {}
function buddies:__index(f)
if type(f) == "string" then
if f:sub(f:len(),f:len()) == "_" then
local k = f:sub(0,f:len()-1)
self[f] = function (self,...)
for i=1,#self do
if self[i][k] then
self[i][k](self[i],...)
end
end
end
else
self[f] = function (self,...)
for i=#self,1,-1 do
if self[i] and self[i][f] then
self[i][f](self[i],...)
end
end
end
end
return self[f]
end
end
function buddies.new(a, ...)
local t
if a == true then
t = setmetatable({
add = superfunc.add,
count = superfunc.count,
find = superfunc.find,
table = superfunc.table,
clone = superfunc.clone,
others = superfunc.others,
others_ = superfunc.others_,
}, buddies)
for i,v in ipairs({...}) do
table.insert(t, v)
end
else
t = setmetatable({
add = func.add,
addAt = func.addAt,
remove = func.remove,
removeIf = func.removeIf,
count = func.count,
find = func.find,
table = func.table,
clone = func.clone,
call = func.call,
call_ = func.call_,
others = func.others,
others_ = func.others_,
flush = func.flush,
set = func.set,
sort = func.sort
}, buddies)
t:add(a, ...)
end
return t
end
function func:add(...)
for i,v in ipairs({...}) do
table.insert(self, v)
end
end
function func:addAt(p, v)
table.insert(self, p, v)
end
--Removes the object. If a number is passed, the object on that position will be removed instead.
function func:remove(obj)
t = type(obj)
local kill = 0
if t == "table" then
for i=1,#self do
if self[i] == obj then
kill = i
break
end
end
elseif t == "number" then
kill = obj
end
if kill > 0 then
if #self == 1 then
self[1] = nil
else
for i=kill + 1,#self do
self[i-1] = self[i]
end
self[#self] = nil
end
end
end
function func:removeIf(func)
for i=#self,1,-1 do
if func(self[i]) then
self:remove(self[i])
end
end
end
function func:find(func)
local t = {}
for i=#self,1,-1 do
if func(self[i]) then
table.insert(t, self[i])
end
end
return t
end
function func:table()
local t = {}
for i=#self,1,-1 do
table.insert(t, self[i])
end
return t
end
function func:clone()
return buddies.new(unpack(self:table()))
end
function func:count(func)
local a = 0
for i=1,#self do
if func(self[i]) then
a = a + 1
end
end
return a
end
--Calls the passed function for each object, passing the object as first argument.
function func:call(func)
for i=#self,1,-1 do
func(self[i])
end
end
function func:call_(func)
for i=1,#self do
func(self[i])
end
end
--Has all the objects iterate through the other objects, allowing for interactivity.
--Calls the passed function, giving both objects as arguments.
function func:others(func)
for i=#self,2,-1 do
for j=i-1,1,-1 do
if func(self[i],self[j]) then break end
end
end
end
function func:others_(func)
for i=1,#self-1 do
for j=i+1,#self do
if func(self[i],self[j]) then break end
end
end
end
--Sets a value to all the objects.
--Will only set the value if the object already has the property, unless force is true.
function func:set(k,v,force)
for i=1,#self do
if force or self[i][k]~=nil then
self[i][k] = v
end
end
end
--Removes all the objects, but keeps the functions.
function func:flush()
for i=1,#self do
self[i] = nil
end
end
--Sorts all the objects on a property.
--If an object does not have the passed property, it will be treated as 0.
--Will automatically sort from low to high, unlesss htl (high to low) is true.
function func:sort(k,htl)
local sorted = false
while not sorted do
sorted = true
for i=1,#self-1 do
for j=i+1,#self do
local propA, propB
propA = self[i][k] or 0
propB = self[j][k] or 0
if (htl and propA < propB) or (not htl and propA > propB) then
local old = self[j]
self[j] = self[i]
self[i] = old
sorted = false
end
end
end
end
end
function superfunc:add(n, ...)
assert(type(n) == "number", "Superbuddy needs a number as first argument", 2)
self[n]:add(...)
end
function superfunc:count(func)
local a
for i,v in ipairs(self) do
a = a + v:count(func)
end
return a
end
function superfunc:others(func)
local t = self:find(function () return true end)
for i=#t,2,-1 do
for j=i-1,1,-1 do
if func(t[i],t[j]) then break end
end
end
end
function superfunc:others_(func)
local t = self:find(function () return true end)
for i=#t,#t-1 do
for j=i+1,#t do
if func(t[i],t[j]) then break end
end
end
end
function superfunc:find(func)
local t = {}
for i,v in ipairs(self) do
for j,w in ipairs(v:find(func)) do
table.insert(t, w)
end
end
return t
end
function superfunc:table()
local t = {}
for i,v in ipairs(self) do
for j,w in ipairs(v:table()) do
table.insert(t, w)
end
end
return t
end
function superfunc:clone()
return buddies.new(unpack(self:table()))
end
return buddies |
local Dictionary = {}
--- Merges key/value pairs from multiple dictionaries into one
-- @param ... Tuple of dictionaries to merge
function Dictionary.merge(...)
local newDictionary = {}
for _, dictionary in pairs({ ... }) do
for key, value in pairs(dictionary) do
newDictionary[key] = value
end
end
return newDictionary
end
--- Counts the number of items in a dictionary by iterating over it
-- @param dictionary The dictionary to count
function Dictionary.count(dictionary)
local count = 0
for _ in pairs(dictionary) do
count = count + 1
end
return count
end
--- Like Array.Map, however it keeps the key
-- @param dictionary Dictionary to map
-- @param callback(value,key,dictionary) Function called on every element
function Dictionary.map(dictionary, callback)
local newDictionary = {}
for key, value in pairs(dictionary) do
newDictionary[key] = callback(value, key, dictionary)
end
return newDictionary
end
--- Creates a shallow copy of a dictionary
-- @param dictionary The dictionary to copy
function Dictionary.clone(dictionary)
local newDictionary = {}
for key, value in pairs(dictionary) do
newDictionary[key] = value
end
return newDictionary
end
return Dictionary |
base_research = nil
base_research =
{
{
Name = "UtilityHealthUpgrade1",
RequiredResearch = "",
RequiredSubSystems = "Research",
RequireTag = "VaygrUtility",
Cost = 1400,
Time = 120,
DisplayedName = "$7779",
DisplayPriority = 701,
Description = "$7780",
UpgradeType = Modifier,
TargetType = Family,
TargetName = "Utility",
UpgradeName = "MAXHEALTH",
UpgradeValue = 1.6,
Icon = Icon_Health,
ShortDisplayedName = "$7351",
},
}
-- Add these items to the research tree!
for i, e in base_research do
research[res_index] = e
res_index = res_index + 1
end
base_research = nil
|
SWEP.Base = "weapon_twitch_base"
if SERVER then
AddCSLuaFile ("shared.lua")
SWEP.HoldType = "smg"
end
SWEP.Spawnable = true
SWEP.AdminSpawnable = true
SWEP.PrintName = "Twitch HL2 Pulse-Rifle"
SWEP.Slot = 2
SWEP.IconLetter = "2"
SWEP.IconLetterFont = "HL2SelectIcons"
SWEP.ViewModel = "models/weapons/v_irifle.mdl"
SWEP.WorldModel = "models/weapons/w_irifle.mdl"
SWEP.ViewModelAimPos = Vector (-4.4599, -1.5141, 1.7999)
SWEP.ViewModelFlip = false
SWEP.ViewModelFOV = 65
SWEP.DrawAmmo = false
SWEP.DrawCrosshair = false
SWEP.Primary.Sound = Sound ("Weapon_AR2.Single")
SWEP.Primary.BullettimeSound = Sound ("weapons/ar2/fire1.wav")
SWEP.Primary.BullettimeSoundPitch = 70
SWEP.Primary.Damage = 30
SWEP.Primary.NumShots = 1
SWEP.Primary.Cone = 0.03
SWEP.Primary.ConeZoomed = 0.005
SWEP.Primary.Delay = 0.1
SWEP.Primary.ClipSize = 30
SWEP.NoChamberingRounds = true
SWEP.Primary.DefaultClip = 270
SWEP.Primary.Automatic = true
SWEP.Primary.Ammo = "ar2"
SWEP.CustomTracerName = "AR2Tracer"
SWEP.CustomTracerFreq = 1
SWEP.CustomBulletCallback = function (atk, trc, dmginfo)
local effdata = EffectData()
effdata:SetStart (trc.HitPos)
effdata:SetOrigin (trc.HitPos)
effdata:SetNormal (trc.HitNormal)
util.Effect ("AR2Impact", effdata)
end
SWEP.Recoil = 1.4
SWEP.Secondary.ClipSize = -1
SWEP.Secondary.DefaultClip = -1
SWEP.Secondary.Automatic = false
SWEP.Secondary.Ammo = "none"
if CLIENT then killicon.AddFont ("weapon_twitch_hl2pulserifle", "HL2MPTypeDeath", "2", Color (150, 150, 255, 255)) end
--GAMEMODE:RegisterWeapon ("weapon_twitch_ak47", {{typ = "text", text = "b", font = "CSSWeapons80", x = 6, y = 10}}, {})
|
local helpers = require "spec.helpers"
local cjson = require "cjson"
describe("Plugin: proxy-cache-redis", function()
local bp
local proxy_client, admin_client, cache_key, plugin1, route1
setup(function()
bp = helpers.get_db_utils(nil, nil, {"proxy-cache-redis"})
route1 = assert(bp.routes:insert {
hosts = { "route-1.com" },
})
plugin1 = assert(bp.plugins:insert {
name = "proxy-cache-redis",
route = { id = route1.id },
config = {
strategy = "memory",
content_type = { "text/plain", "application/json" },
memory = {
dictionary_name = "kong",
},
},
})
-- an additional plugin does not interfere with the iteration in
-- the global /proxy-cache API handler: regression test for
-- https://github.com/Kong/kong-plugin-proxy-cache/issues/12
assert(bp.plugins:insert {
name = "request-transformer",
})
local route2 = assert(bp.routes:insert {
hosts = { "route-2.com" },
})
assert(bp.plugins:insert {
name = "proxy-cache-redis",
route = { id = route2.id },
config = {
strategy = "memory",
content_type = { "text/plain", "application/json" },
memory = {
dictionary_name = "kong",
},
},
})
assert(helpers.start_kong({
plugins = "proxy-cache-redis,request-transformer",
nginx_conf = "spec/fixtures/custom_nginx.template",
}))
if admin_client then
admin_client:close()
end
if proxy_client then
proxy_client:close()
end
admin_client = helpers.admin_client()
proxy_client = helpers.proxy_client()
end)
teardown(function()
helpers.stop_kong(nil, true)
end)
describe("(schema)", function()
local body
it("accepts an array of numbers as strings", function()
local res = assert(admin_client:send {
method = "POST",
path = "/plugins",
body = {
name = "proxy-cache-redis",
config = {
strategy = "memory",
memory = {
dictionary_name = "kong",
},
response_code = {123, 200},
cache_ttl = 600,
request_method = { "GET" },
content_type = { "text/json" },
},
},
headers = {
["Content-Type"] = "application/json",
},
})
body = assert.res_status(201, res)
end)
it("casts an array of response_code values to number types", function()
local json = cjson.decode(body)
for _, v in ipairs(json.config.response_code) do
assert.is_number(v)
end
end)
it("errors if response_code is an empty array", function()
local res = assert(admin_client:send {
method = "POST",
path = "/plugins",
body = {
name = "proxy-cache-redis",
config = {
strategy = "memory",
memory = {
dictionary_name = "kong",
},
response_code = {},
cache_ttl = 600,
request_method = { "GET" },
content_type = { "text/json" },
},
},
headers = {
["Content-Type"] = "application/json",
},
})
local body = assert.res_status(400, res)
local json_body = cjson.decode(body)
assert.same("length must be at least 1", json_body.fields.config.response_code)
end)
it("errors if response_code is a string", function()
local res = assert(admin_client:send {
method = "POST",
path = "/plugins",
body = {
name = "proxy-cache-redis",
config = {
strategy = "memory",
memory = {
dictionary_name = "kong",
},
response_code = {},
cache_ttl = 600,
request_method = "GET",
content_type = "text/json",
},
},
headers = {
["Content-Type"] = "application/json",
},
})
local body = assert.res_status(400, res)
local json_body = cjson.decode(body)
assert.same("length must be at least 1", json_body.fields.config.response_code)
end)
it("errors if response_code has non-numeric values", function()
local res = assert(admin_client:send {
method = "POST",
path = "/plugins",
body = {
name = "proxy-cache-redis",
config = {
strategy = "memory",
memory = {
dictionary_name = "kong",
},
response_code = {true, "alo", 123},
cache_ttl = 600,
request_method = "GET",
content_type = "text/json",
},
},
headers = {
["Content-Type"] = "application/json",
},
})
local body = assert.res_status(400, res)
local json_body = cjson.decode(body)
assert.same( { "expected an integer", "expected an integer" },
json_body.fields.config.response_code)
end)
it("errors if response_code has float value", function()
local res = assert(admin_client:send {
method = "POST",
path = "/plugins",
body = {
name = "proxy-cache-redis",
config = {
strategy = "memory",
memory = {
dictionary_name = "kong",
},
response_code = {90},
cache_ttl = 600,
request_method = "GET",
content_type = "text/json",
},
},
headers = {
["Content-Type"] = "application/json",
},
})
local body = assert.res_status(400, res)
local json_body = cjson.decode(body)
assert.same({ "value should be between 100 and 900" },
json_body.fields.config.response_code)
end)
end)
describe("(API)", function()
describe("DELETE", function()
it("delete a cache entry", function()
local res = assert(proxy_client:send {
method = "GET",
path = "/get",
headers = {
host = "route-1.com",
}
})
assert.res_status(200, res)
assert.same("Miss", res.headers["X-Cache-Status"])
-- cache key is an md5sum of the prefix uuid, method, and $request
local cache_key1 = res.headers["X-Cache-Key"]
assert.matches("^[%w%d]+$", cache_key1)
assert.equals(32, #cache_key1)
cache_key = cache_key1
res = assert(proxy_client:send {
method = "GET",
path = "/get",
headers = {
host = "route-1.com",
}
})
assert.res_status(200, res)
assert.same("Hit", res.headers["X-Cache-Status"])
local cache_key2 = res.headers["X-Cache-Key"]
assert.same(cache_key1, cache_key2)
-- delete the key
res = assert(admin_client:send {
method = "DELETE",
path = "/proxy-cache-redis/" .. plugin1.id .. "/caches/" .. cache_key,
})
assert.res_status(204, res)
local res = assert(proxy_client:send {
method = "GET",
path = "/get",
headers = {
host = "route-1.com",
}
})
assert.res_status(200, res)
assert.same("Miss", res.headers["X-Cache-Status"])
-- delete directly, having to look up all proxy-cache instances
res = assert(admin_client:send {
method = "DELETE",
path = "/proxy-cache-redis/" .. cache_key,
})
assert.res_status(204, res)
local res = assert(proxy_client:send {
method = "GET",
path = "/get",
headers = {
host = "route-1.com",
}
})
assert.res_status(200, res)
assert.same("Miss", res.headers["X-Cache-Status"])
end)
it("purge all the cache entries", function()
-- make a `Hit` request to `route-1`
local res = assert(proxy_client:send {
method = "GET",
path = "/get",
headers = {
host = "route-1.com",
}
})
assert.res_status(200, res)
assert.same("Hit", res.headers["X-Cache-Status"])
-- make a `Miss` request to `route-2`
local res = assert(proxy_client:send {
method = "GET",
path = "/get",
headers = {
host = "route-2.com",
}
})
assert.res_status(200, res)
assert.same("Miss", res.headers["X-Cache-Status"])
-- cache key is an md5sum of the prefix uuid, method, and $request
local cache_key1 = res.headers["X-Cache-Key"]
assert.matches("^[%w%d]+$", cache_key1)
assert.equals(32, #cache_key1)
-- make a `Hit` request to `route-1`
res = assert(proxy_client:send {
method = "GET",
path = "/get",
headers = {
host = "route-2.com",
}
})
assert.res_status(200, res)
assert.same("Hit", res.headers["X-Cache-Status"])
local cache_key2 = res.headers["X-Cache-Key"]
assert.same(cache_key1, cache_key2)
-- delete all the cache keys
res = assert(admin_client:send {
method = "DELETE",
path = "/proxy-cache-redis",
})
assert.res_status(204, res)
local res = assert(proxy_client:send {
method = "GET",
path = "/get",
headers = {
host = "route-1.com",
}
})
assert.res_status(200, res)
assert.same("Miss", res.headers["X-Cache-Status"])
local res = assert(proxy_client:send {
method = "GET",
path = "/get",
headers = {
host = "route-2.com",
}
})
assert.res_status(200, res)
assert.same("Miss", res.headers["X-Cache-Status"])
end)
it("delete a non-existing cache key", function()
-- delete all the cache keys
local res = assert(admin_client:send {
method = "DELETE",
path = "/proxy-cache-redis",
})
assert.res_status(204, res)
local res = assert(admin_client:send {
method = "DELETE",
path = "/proxy-cache-redis/" .. plugin1.id .. "/caches/" .. "123",
})
assert.res_status(404, res)
end)
it("delete a non-existing plugins's cache key", function()
-- delete all the cache keys
local res = assert(admin_client:send {
method = "DELETE",
path = "/proxy-cache-redis",
})
assert.res_status(204, res)
local res = assert(admin_client:send {
method = "DELETE",
path = "/proxy-cache-redis/" .. route1.id .. "/caches/" .. "123",
})
assert.res_status(404, res)
end)
end)
describe("GET", function()
it("get a non-existing cache", function()
-- delete all the cache keys
local res = assert(admin_client:send {
method = "DELETE",
path = "/proxy-cache-redis",
})
assert.res_status(204, res)
local res = assert(admin_client:send {
method = "GET",
path = "/proxy-cache-redis/" .. plugin1.id .. "/caches/" .. cache_key,
})
assert.res_status(404, res)
-- attempt to list an entry directly via cache key
local res = assert(admin_client:send {
method = "GET",
path = "/proxy-cache-redis/" .. cache_key,
})
assert.res_status(404, res)
end)
it("get a existing cache", function()
-- add request to cache
local res = assert(proxy_client:send {
method = "GET",
path = "/get",
headers = {
host = "route-1.com",
}
})
assert.res_status(200, res)
local res = assert(admin_client:send {
method = "GET",
path = "/proxy-cache-redis/" .. plugin1.id .. "/caches/" .. cache_key,
})
local body = assert.res_status(200, res)
local json_body = cjson.decode(body)
assert.same(cache_key, json_body.headers["X-Cache-Key"])
-- list an entry directly via cache key
local res = assert(admin_client:send {
method = "GET",
path = "/proxy-cache-redis/" .. cache_key,
})
local body = assert.res_status(200, res)
local json_body = cjson.decode(body)
assert.same(cache_key, json_body.headers["X-Cache-Key"])
end)
end)
end)
end)
|
-- Brian: This is a Lua file; make sure you're using the correct syntax.
-- I've removed the Python defaults.
VERSION = "1.0.0"
function onBufferOpen(b)
local ft = b:FileType()
-- Brian, just return early. This thing is pretty screwed.
return
if ft == "go" then
b:SetOption("tabstospaces", "off")
elseif ft == "makefile" then
b:SetOption("tabstospaces", "off")
elseif ft == "fish"
b:SetOption("tabstospaces", "on")
elseif ft == "yaml" or
b:SetOption("tabstospaces", "on")
elseif ft == "nim" then
b:SetOption("tabstospaces", "on")
end
end
|
SceneObjectType={
Role=1,Monster=2,NPC=3,
}
SceneInfoKey = {
EnterView=1,
LeaveView=2,
PosChange=3,
TargetPos=4,
JumpState=5,
} |
----------------------------------
-- Area: Meriphataud_Mountains_[S]
-- NPC: Indescript Markings
-- Type: Quest
-- !pos -389 -9 92 97
-----------------------------------
local ID = require("scripts/zones/Meriphataud_Mountains_[S]/IDs")
require("scripts/globals/keyitems")
-----------------------------------
function onTrade(player, npc, trade)
end
function onTrigger(player, npc)
local loafersQuestProgress = player:getCharVar("AF_SCH_BOOTS")
player:delStatusEffect(tpz.effect.SNEAK)
-- SCH AF Quest - Boots
if loafersQuestProgress > 0 and loafersQuestProgress < 3 and not player:hasKeyItem(tpz.ki.DROGAROGAN_BONEMEAL) then
player:addKeyItem(tpz.ki.DROGAROGAN_BONEMEAL)
player:messageSpecial(ID.text.KEYITEM_OBTAINED, tpz.ki.DROGAROGAN_BONEMEAL)
player:setCharVar("AF_SCH_BOOTS", loafersQuestProgress + 1)
else
player:messageSpecial(ID.text.NOTHING_OUT_OF_ORDINARY)
end
end
function onEventUpdate(player, csid, option)
end
function onEventFinish(player, csid, option)
end
|
--Reinforcement of the Army's Troops
--Scripted by TanakaKotoha
function c101103088.initial_effect(c)
--activate
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
c:RegisterEffect(e1)
--atk
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(101103088,0))
e2:SetCategory(CATEGORY_SPECIAL_SUMMON)
e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O)
e2:SetCode(EVENT_ATTACK_ANNOUNCE)
e2:SetRange(LOCATION_SZONE)
e2:SetCountLimit(1,101103088)
e2:SetCondition(c101103088.spcon)
e2:SetTarget(c101103088.sptg)
e2:SetOperation(c101103088.spop)
c:RegisterEffect(e2)
end
function c101103088.spcon(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetAttacker()
if tc:IsControler(1-tp) then tc=Duel.GetAttackTarget() end
return tc and tc:IsFaceup() and tc:IsControler(tp) and tc:IsRace(RACE_WARRIOR)
end
function c101103088.spfilter(c,e,tp)
return c:IsLevelBelow(4) and c:IsRace(RACE_WARRIOR) and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c101103088.sptg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingMatchingCard(c101103088.spfilter,tp,LOCATION_HAND,0,1,nil,e,tp) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_HAND)
end
function c101103088.spop(e,tp,eg,ep,ev,re,r,rp)
if not e:GetHandler():IsRelateToEffect(e) then return end
if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectMatchingCard(tp,c101103088.spfilter,tp,LOCATION_HAND,0,1,1,nil,e,tp)
if #g>0 then
Duel.SpecialSummon(g,0,tp,tp,false,false,POS_FACEUP)
end
end
|
local t = Def.ActorFrame {};
-- P2 Judgement Labels
-- P2 numbers
t[#t+1] = Def.ActorFrame {
InitCommand=cmd(addx,60;);
LoadFont("_numbers2") .. {
InitCommand=cmd(visible,GAMESTATE:IsHumanPlayer(PLAYER_2);horizalign,left;diffuse,PlayerColor(PLAYER_2);playcommand,"Set";);
OnCommand=cmd(addx,SCREEN_WIDTH/2;sleep,0.1;decelerate,0.3;addx,-SCREEN_WIDTH/2);
OffCommand=cmd(sleep,0.8;accelerate,0.3;addx,SCREEN_WIDTH/2);
SetCommand=function(self)
if screen == "ScreenEvaluationSummary" then
self:settext(STATSMAN:GetFinalEvalStageStats():GetPlayerStageStats(PLAYER_2):GetTapNoteScores("TapNoteScore_W1"));
else
self:settext(STATSMAN:GetCurStageStats():GetPlayerStageStats(PLAYER_2):GetTapNoteScores("TapNoteScore_W1"));
end;
end;
};
LoadFont("_numbers2") .. {
InitCommand=cmd(visible,GAMESTATE:IsHumanPlayer(PLAYER_2);horizalign,left;diffuse,PlayerColor(PLAYER_2);addy,30;playcommand,"Set";);
OnCommand=cmd(addx,SCREEN_WIDTH/2;sleep,0.2;decelerate,0.3;addx,-SCREEN_WIDTH/2);
OffCommand=cmd(sleep,0.7;accelerate,0.3;addx,SCREEN_WIDTH/2);
SetCommand=function(self)
if screen == "ScreenEvaluationSummary" then
self:settext(STATSMAN:GetFinalEvalStageStats():GetPlayerStageStats(PLAYER_2):GetTapNoteScores("TapNoteScore_W2"));
else
self:settext(STATSMAN:GetCurStageStats():GetPlayerStageStats(PLAYER_2):GetTapNoteScores("TapNoteScore_W2"));
end;
end;
};
LoadFont("_numbers2") .. {
InitCommand=cmd(visible,GAMESTATE:IsHumanPlayer(PLAYER_2);horizalign,left;diffuse,PlayerColor(PLAYER_2);addy,30*2;playcommand,"Set";);
OnCommand=cmd(addx,SCREEN_WIDTH/2;sleep,0.3;decelerate,0.3;addx,-SCREEN_WIDTH/2);
OffCommand=cmd(sleep,0.6;accelerate,0.3;addx,SCREEN_WIDTH/2);
SetCommand=function(self)
if screen == "ScreenEvaluationSummary" then
self:settext(STATSMAN:GetFinalEvalStageStats():GetPlayerStageStats(PLAYER_2):GetTapNoteScores("TapNoteScore_W3"));
else
self:settext(STATSMAN:GetCurStageStats():GetPlayerStageStats(PLAYER_2):GetTapNoteScores("TapNoteScore_W3"));
end;
end;
};
LoadFont("_numbers2") .. {
InitCommand=cmd(visible,GAMESTATE:IsHumanPlayer(PLAYER_2);horizalign,left;diffuse,PlayerColor(PLAYER_2);addy,30*3;playcommand,"Set";);
OnCommand=cmd(addx,SCREEN_WIDTH/2;sleep,0.4;decelerate,0.3;addx,-SCREEN_WIDTH/2);
OffCommand=cmd(sleep,0.5;accelerate,0.3;addx,SCREEN_WIDTH/2);
SetCommand=function(self)
if screen == "ScreenEvaluationSummary" then
self:settext(STATSMAN:GetFinalEvalStageStats():GetPlayerStageStats(PLAYER_2):GetTapNoteScores("TapNoteScore_W4"));
else
self:settext(STATSMAN:GetCurStageStats():GetPlayerStageStats(PLAYER_2):GetTapNoteScores("TapNoteScore_W4"));
end;
end;
};
LoadFont("_numbers2") .. {
InitCommand=cmd(visible,GAMESTATE:IsHumanPlayer(PLAYER_2);horizalign,left;diffuse,PlayerColor(PLAYER_2);addy,30*4;playcommand,"Set";);
OnCommand=cmd(addx,SCREEN_WIDTH/2;sleep,0.5;decelerate,0.3;addx,-SCREEN_WIDTH/2);
OffCommand=cmd(sleep,0.4;accelerate,0.3;addx,SCREEN_WIDTH/2);
SetCommand=function(self)
if screen == "ScreenEvaluationSummary" then
self:settext(STATSMAN:GetFinalEvalStageStats():GetPlayerStageStats(PLAYER_2):GetTapNoteScores("TapNoteScore_W5"));
else
self:settext(STATSMAN:GetCurStageStats():GetPlayerStageStats(PLAYER_2):GetTapNoteScores("TapNoteScore_W5"));
end;
end;
};
LoadFont("_numbers2") .. {
InitCommand=cmd(visible,GAMESTATE:IsHumanPlayer(PLAYER_2);horizalign,left;diffuse,PlayerColor(PLAYER_2);addy,30*5;playcommand,"Set";);
OnCommand=cmd(addx,SCREEN_WIDTH/2;sleep,0.6;decelerate,0.3;addx,-SCREEN_WIDTH/2);
OffCommand=cmd(sleep,0.3;accelerate,0.3;addx,SCREEN_WIDTH/2);
SetCommand=function(self)
if screen == "ScreenEvaluationSummary" then
self:settext(STATSMAN:GetFinalEvalStageStats():GetPlayerStageStats(PLAYER_2):GetTapNoteScores("TapNoteScore_Miss"));
else
self:settext(STATSMAN:GetCurStageStats():GetPlayerStageStats(PLAYER_2):GetTapNoteScores("TapNoteScore_Miss"));
end;
end;
};
LoadFont("_numbers2") .. {
InitCommand=cmd(visible,GAMESTATE:IsHumanPlayer(PLAYER_2);horizalign,left;diffuse,PlayerColor(PLAYER_2);addy,30*6;playcommand,"Set";);
OnCommand=cmd(addx,SCREEN_WIDTH/2;sleep,0.7;decelerate,0.3;addx,-SCREEN_WIDTH/2);
OffCommand=cmd(sleep,0.2;accelerate,0.3;addx,SCREEN_WIDTH/2);
SetCommand=function(self)
if screen == "ScreenEvaluationSummary" then
self:settext(STATSMAN:GetFinalEvalStageStats():GetPlayerStageStats(PLAYER_2):GetHoldNoteScores("HoldNoteScore_Held"));
else
self:settext(STATSMAN:GetCurStageStats():GetPlayerStageStats(PLAYER_2):GetHoldNoteScores("HoldNoteScore_Held"));
end;
end;
};
LoadFont("_numbers2") .. {
InitCommand=cmd(visible,GAMESTATE:IsHumanPlayer(PLAYER_2);horizalign,left;diffuse,color("#FFFF00");addy,27*6+6;addx,80;playcommand,"Set";);
OnCommand=cmd(zoomy,0;decelerate,0.3;zoomy,1);
OffCommand=cmd(zoomy,1;accelerate,0.3;zoomy,0);
SetCommand=function(self)
if screen == "ScreenEvaluationSummary" then
self:settext(STATSMAN:GetFinalEvalStageStats():GetPlayerStageStats(PLAYER_2):MaxCombo());
else
self:settext(STATSMAN:GetCurStageStats():GetPlayerStageStats(PLAYER_2):MaxCombo());
end;
end;
};
LoadFont("_numbers2") .. {
InitCommand=cmd(visible,GAMESTATE:IsHumanPlayer(PLAYER_2);horizalign,left;diffuse,PlayerColor(PLAYER_2);addy,30*7+3;addx,10;playcommand,"Set";);
OnCommand=cmd(addx,SCREEN_WIDTH/2;sleep,0.9;decelerate,0.3;addx,-SCREEN_WIDTH/2);
OffCommand=cmd(sleep,0.1;accelerate,0.3;addx,SCREEN_WIDTH/2);
SetCommand=function(self)
if screen == "ScreenEvaluationSummary" then
self:settext(STATSMAN:GetFinalEvalStageStats():GetPlayerStageStats(PLAYER_2):GetScore());
else
self:settext(STATSMAN:GetCurStageStats():GetPlayerStageStats(PLAYER_2):GetScore());
end;
end;
};
};
return t
|
-- Lua
local cb = require'diffview.config'.diffview_callback
require'diffview'.setup()
|
require("deviap/core").load("all")
-- Light it up!
core.graphics.upperAmbient = colour(1, 1, 1)
for x = -5, 5 do
for y = -5, 5 do
core.construct("block", {
position = vector3(x*4, 0, y*4),
scale = vector3(4, 0.4, 4),
colour = colour.hex("f16161"),
metalness = (x % 2 == 0) and 0.5 or 1,
roughness = (y % 2 == 0) and 0.5 or 1,
})
end
end
core.scene.simulate = true
local characters = {}
-- When a user connects
core.networking:on("_clientConnected", function(client)
local char = core.construct("block", {
name = client.id,
position = vector3(0, 10, 0),
scale = vector3(323.97, 314.67, 98.32)/100,
static = false,
mesh = "fs:shared/meshes/CharacterFinal08.glb",
colour = colour.random(),
angularFactor = vector3(0, 0, 0),
friction = 1
})
characters[client.id] = {
char = char,
direction = quaternion.euler(0, 0, 0),
movement = {
forward = false,
left = false,
right = false,
backward = false
}
}
end)
core.networking:on("_clientDisconnected", function(client)
if characters[client.id] then
local entry = characters[client.id]
entry.char:destroy()
characters[client.id] = nil
end
end)
core.networking:on("moveKeyDown", function(client, direction, lv)
if not characters[client.id] then
return
end
characters[client.id].direction = lv
if characters[client.id].movement[direction] ~= nil then
characters[client.id].movement[direction] = true
end
end)
core.networking:on("moveKeyUp", function(client, direction)
if not characters[client.id] then
return
end
if characters[client.id].movement[direction] ~= nil then
characters[client.id].movement[direction] = false
end
end)
local speed = 2.5
while sleep(.02) do
for id, entry in pairs(characters) do
if entry.char.velocity:length() < 5 then
entry.char:applyImpulse(
entry.direction *
vector3(
entry.movement.right and speed or (entry.movement.left and -speed or 0),
0,
entry.movement.backward and speed or (entry.movement.forward and -speed or 0)
)
)
end
local velo = entry.char.velocity:normal()
velo.y = 0
if velo:length() > 0.01 then
--print(velo, velo:length())
entry.char.rotation = quaternion.lookRotation(velo)
end
end
end |
local folderName = ...
local cosFix = LibStub("AceAddon-3.0"):NewAddon(folderName, "AceConsole-3.0", "AceEvent-3.0", "AceTimer-3.0")
-- Allow access for other addons.
_G.cosFix = cosFix
local _G = _G
local pairs = _G.pairs
local strsplit = _G.strsplit
local math_max = _G.math.max
local math_min = _G.math.min
local GetCameraZoom = _G.GetCameraZoom
local GetTime = _G.GetTime
local DynamicCam = _G.DynamicCam
local dynamicCamLoaded = _G.IsAddOnLoaded("DynamicCam")
-- Needed if un-hooks without reloading are required.
local runhook = false
cosFix.GetShoulderOffsetZoomFactor = function() return 1 end
if dynamicCamLoaded then
cosFix.GetShoulderOffsetZoomFactor = DynamicCam.GetShoulderOffsetZoomFactor
end
function cosFix:GetCurrentShoulderOffset()
if dynamicCamLoaded then
return DynamicCam.currentShoulderOffset
else
return self.db.profile.cvars.test_cameraOverShoulder
end
end
function cosFix.HyperlinkHandler(...)
if not runhook then return end
local _, linkType = ...
local _, cosFixIdentifier, idType, id = strsplit(":", linkType)
if cosFixIdentifier == "cosFix" then
-- No need to hide ItemRefTooltip, because it will not even show up with our modified link.
cosFix.setFactorFrame:Show()
cosFix.setFactorFrame:SetId(idType, tonumber(id))
end
end
function cosFix:CosFixSetCVar(...)
local variable, value = ...
-- print("CosFixSetCVar", variable, value)
if variable == "test_cameraOverShoulder" then
cosFix.currentModelFactor = cosFix:CorrectShoulderOffset()
value = value * cosFix:GetShoulderOffsetZoomFactor(GetCameraZoom()) * cosFix.currentModelFactor
end
SetCVar(variable, value)
end
-- Set the variables currently in the db.
function cosFix:SetVariables()
for variable, value in pairs(self.db.profile.cvars) do
self:CosFixSetCVar(variable, value)
end
end
function cosFix:DebugPrint(...)
if self.db.profile.debugOutput then
self:Print(...)
end
end
-- Only print this message once.
local lastUnknownModelPrint = GetTime()
function cosFix:DebugPrintUnknownModel(...)
if lastUnknownModelPrint < GetTime() then
self:DebugPrint(...)
lastUnknownModelPrint = GetTime()
end
end
function cosFix:OnInitialize()
-- Hide the Blizzard warning.
UIParent:UnregisterEvent("EXPERIMENTAL_CVAR_CONFIRMATION_NEEDED")
self:InitializeDatabase()
self:InitializeOptions()
-- Initialize customOffsetFactors if not yet present.
if not customOffsetFactors then
customOffsetFactors = {
mountId = {},
vehicleId = {},
modelId = {},
}
-- Or check the variables already stored.
else
-- Purge possible entries of old addon versions.
for k in pairs(customOffsetFactors) do
if not (k == "mountId" or k == "vehicleId" or k == "modelId") then
customOffsetFactors[k] = nil
end
end
for _, idType in pairs({"mountId", "vehicleId", "modelId"}) do
-- Initialize empty table if not yet present.
if not customOffsetFactors[idType] then
customOffsetFactors[idType] = {}
-- Or purge values that are the same as hardcoded.
else
for k, v in pairs(customOffsetFactors[idType]) do
if v == self.hardcodedOffsetFactors[idType][k] then
-- print("Purging", idType, k, "=", v, "from custom factors because it is now hardcoded!")
customOffsetFactors[idType][k] = nil
end
end
end
end
end
-- Initialize newFactorTriggers if not yet present.
if not newFactorTriggers then
newFactorTriggers = {}
-- TODO: merge hardcoded values.
else
-- TODO: copy hardcoded values.
end
end
function cosFix:OnEnable()
if not cosFix.db.profile.enabled then return end
-- Hide the Blizzard warning.
UIParent:UnregisterEvent("EXPERIMENTAL_CVAR_CONFIRMATION_NEEDED")
-- Hooking functions.
hooksecurefunc(ItemRefTooltip, "SetHyperlink", cosFix.HyperlinkHandler)
-- Cannot undo hooksecurefunc.
runhook = true
self:RegisterEvents()
-- Must wait before setting variables in the beginning.
-- Otherwise, the value for test_cameraOverShoulder might not be applied.
if not dynamicCamLoaded then
self:ScheduleTimer("SetVariables", 0.1)
local modelFactor = self:CorrectShoulderOffset()
if modelFactor == -1 then
self.currentModelFactor = 1
else
self.currentModelFactor = modelFactor
end
end
end
function cosFix:OnDisable()
-- Cannot undo hooksecurefunc.
runhook = false
self:UnregisterAllEvents()
-- Restore all test variables and enable the Blizzard warning.
ResetTestCvars()
UIParent:RegisterEvent("EXPERIMENTAL_CVAR_CONFIRMATION_NEEDED")
end
-- To test the SpellActivationOverlayFrame frame!
-- Thanks to Fizzlemizz: https://us.forums.blizzard.com/en/wow/t/are-there-any-areas-that-call-the-extra-and-zone-action-buttons-concurrently/526223/2
local function Overlay(frame)
local f = CreateFrame("Frame", frame:GetName().."FizzOverlay", UIParent)
f:SetAllPoints(frame)
f.t = f:CreateTexture()
f.t:SetAllPoints()
f.t:SetTexture("Interface/BUTTONS/WHITE8X8")
f.t:SetColorTexture(0.2, 0.2, 1, 0.5)
f.f = f:CreateFontString()
f.f:SetFont("Fonts/FRIZQT__.TTF", 12)
f.f:SetJustifyH("CENTER")
f.f:SetJustifyV("CENTER")
f.f:SetPoint("CENTER")
f.f:SetText(frame:GetName())
end
|
--[[
FontLoader by NAKET Coder
how it works:
Say you have a new generation Fonts folder, which is something like...
\Fonts
\frutiger
\_32pt
\scooter
\_36px numbers
\_32px metal
in your bganims, call
Font(family, style)
where:
family = font family [e.g. "frutiger", "scooter"]
style = font style [e.g. "32pt", "24px shiny"]
--]]
function Font(family,style) return LoadFont( "", family.."/_"..style ) end
function FontPath(family,style) return THEME:GetPathF("",family.."/_"..style) end
|
slot0 = class("TechnologySettingsLayer", import("..base.BaseUI"))
slot0.TEC_PAGE_TENDENCY = 1
slot0.TEC_PAGE_CATCHUP_TARGET1 = 2
slot0.TEC_PAGE_CATCHUP_TARGET2 = 3
slot0.TEC_PAGE_CATCHUP_ACT = 4
slot0.PANEL_INTO_TIME = 0.15
slot0.SELECT_TENDENCY_FADE_TIME = 0.3
slot0.SELECT_CHAR_LIGHT_FADE_TIME = 0.3
slot0.CATCHUP_VERSION = 2
slot0.getUIName = function (slot0)
return "TechnologySettingsUI"
end
slot0.preload = function (slot0, slot1)
slot0.catchupPanels = {}
slot0.rightPageTFList = {}
seriesAsync({
function (slot0)
if slot0.CATCHUP_VERSION >= 1 then
slot1.catchupPanels[1] = TargetCatchupPanel1.New(nil, function ()
slot0.rightPageTFList[slot1.TEC_PAGE_CATCHUP_TARGET1] = slot0.catchupPanels[1]._go
setActive(slot0.rightPageTFList[slot1.TEC_PAGE_CATCHUP_TARGET1], false)
false()
end)
else
slot0()
end
end,
function (slot0)
if slot0.CATCHUP_VERSION >= 2 then
slot1.catchupPanels[2] = TargetCatchupPanel2.New(nil, function ()
slot0.rightPageTFList[slot1.TEC_PAGE_CATCHUP_TARGET2] = slot0.catchupPanels[2]._go
setActive(slot0.rightPageTFList[slot1.TEC_PAGE_CATCHUP_TARGET2], false)
false()
end)
else
slot0()
end
end
}, slot1)
end
slot0.init = function (slot0)
slot0:initData()
slot0:findUI()
slot0:addListener()
slot0:initTendencyPage()
slot0:initActCatchupPage()
end
slot0.didEnter = function (slot0)
pg.UIMgr.GetInstance():BlurPanel(slot0._tf)
slot0:resetLeftBtnUnsel()
slot0:updateTendencyBtn(slot0.curTendency)
slot0:updateTargetCatchupBtns()
slot0:updateActCatchupBtn()
triggerButton(slot0.leftBtnList[1])
triggerToggle(slot0.showFinish, (slot0.showFinishFlag == 1 and true) or false)
end
slot0.willExit = function (slot0)
pg.UIMgr.GetInstance():UnblurPanel(slot0._tf)
if slot0.actCatchupTimer then
slot0.actCatchupTimer:Stop()
slot0.actCatchupTimer = nil
end
for slot4, slot5 in pairs(slot0.catchupPanels) do
slot5:willExit()
end
slot0.loader:Clear()
end
slot0.initData = function (slot0)
slot0.technologyProxy = getProxy(TechnologyProxy)
slot0.bayProxy = getProxy(BayProxy)
slot0.bagProxy = getProxy(BagProxy)
slot0.curPageID = 0
slot0.curTendency = slot0.technologyProxy:getTendency(2)
slot0.curSelectedIndex = 0
slot0.reSelectTag = false
slot0.actCatchup = getProxy(ActivityProxy):getActivityByType(ActivityConst.ACTIVITY_TYPE_BLUEPRINT_CATCHUP)
slot0.isShowActCatchup = slot0.actCatchup and not slot0.actCatchup:isEnd()
slot0.loader = AutoLoader.New()
end
slot0.findUI = function (slot0)
slot0.bg = slot0:findTF("BG")
setText(slot1, i18n("click_back_tip"))
slot3 = slot0:findTF("LeftBtnList", slot2)
slot0.tendencyBtn = slot0:findTF("TendencyBtn", slot3)
slot0.catchupBtns = {
slot0:findTF("TargetCatchupBtn1", slot3),
slot0:findTF("TargetCatchupBtn2", slot3)
}
slot0.actCatchupBtn = slot0:findTF("ActCatchupBtn", slot3)
slot0.leftBtnList = {
[slot0.TEC_PAGE_TENDENCY] = slot0.tendencyBtn,
[slot0.TEC_PAGE_CATCHUP_TARGET1] = slot0.catchupBtns[1],
[slot0.TEC_PAGE_CATCHUP_TARGET2] = slot0.catchupBtns[2],
[slot0.TEC_PAGE_CATCHUP_ACT] = slot0.actCatchupBtn
}
slot0.tendencyPanel = slot0:findTF("TecTendencyPanel", slot4)
slot0.actCatchupPanel = slot0:findTF("ActCatchupPanel", slot4)
slot0.rightPageTFList[slot0.TEC_PAGE_TENDENCY] = slot0.tendencyPanel
slot0.rightPageTFList[slot0.TEC_PAGE_CATCHUP_ACT] = slot0.actCatchupPanel
for slot8, slot9 in pairs(slot0.catchupPanels) do
SetParent(slot9._go, slot4, false)
end
slot0.showFinish = slot0:findTF("ShowFinishToggle")
setText(slot0:findTF("Label", slot0.showFinish), i18n("tec_target_catchup_show_the_finished_version"))
slot0.showFinishFlag = PlayerPrefs.GetInt("isShowFinishCatchupVersion") or 0
slot0.giveupMsgBox = slot0:findTF("GiveUpMsgBox")
if slot0.CATCHUP_VERSION < 2 then
setActive(slot0.catchupBtns[2], false)
end
if slot0.CATCHUP_VERSION < 1 then
setActive(slot0.catchupBtns[1], false)
setActive(slot0.showFinish, false)
end
end
slot0.addListener = function (slot0)
onButton(slot0, slot0.bg, function ()
slot0:closeView()
end, SFX_PANEL)
for slot4, slot5 in pairs(slot0.leftBtnList) do
onButton(slot0, slot5, function ()
if slot0.onPageSwitchAnim then
return
end
if slot0.curPageID ~= slot1 then
slot0:resetLeftBtnUnsel()
setActive(slot0:findTF("Selected", slot0), true)
setActive:switchRightPage(setActive)
end
end, SFX_PANEL)
end
onToggle(slot0, slot0.showFinish, function (slot0)
if slot0.CATCHUP_VERSION < 1 then
return
end
for slot4, slot5 in pairs(slot1.catchupBtns) do
if slot4 <= slot0.CATCHUP_VERSION then
if slot1.technologyProxy:getCatchupState(slot4) == TechnologyCatchup.STATE_FINISHED_ALL and not slot0 then
setActive(slot5, false)
else
setActive(slot5, true)
end
end
end
slot1.showFinishFlag = (slot0 and 1) or 0
PlayerPrefs.SetInt("isShowFinishCatchupVersion", slot1.showFinishFlag)
triggerButton(slot1.leftBtnList[1])
end, SFX_PANEL)
end
slot0.resetLeftBtnUnsel = function (slot0)
for slot4, slot5 in pairs(slot0.leftBtnList) do
setActive(slot0:findTF("Selected", slot5), false)
end
end
slot0.switchRightPage = function (slot0, slot1)
setActive(slot3, true)
slot0.onPageSwitchAnim = true
slot0:managedTween(LeanTween.alphaCanvas, function ()
slot0.onPageSwitchAnim = false
end, GetOrAddComponent(slot3, typeof(CanvasGroup)), 1, slot0.PANEL_INTO_TIME):setFrom(0)
if slot0.rightPageTFList[slot0.curPageID] then
slot0:managedTween(LeanTween.alphaCanvas, function ()
setActive(setActive, false)
end, GetOrAddComponent(slot2, typeof(CanvasGroup)), 0, slot0.PANEL_INTO_TIME):setFrom(1)
end
slot0.curPageID = slot1
if slot1 == slot0.TEC_PAGE_TENDENCY then
slot0:updateTendencyPage(slot0.curTendency)
elseif slot1 == slot0.TEC_PAGE_CATCHUP_TARGET1 then
slot0:updateTargetCatchupPage(1)
elseif slot1 == slot0.TEC_PAGE_CATCHUP_TARGET2 then
slot0:updateTargetCatchupPage(2)
elseif slot1 == slot0.TEC_PAGE_CATCHUP_ACT then
slot0:updateActCatchupPage()
end
end
slot0.initTendencyPage = function (slot0)
slot0.tendencyItemList = {}
slot2 = "tec_tendency_"
slot4 = getProxy(TechnologyProxy):getConfigMaxVersion()
for slot8 = 1, slot0:findTF("TecItemList", slot0.tendencyPanel).childCount, 1 do
setActive(slot1:GetChild(slot8 - 1), slot4 >= slot8 - 1)
if slot4 >= slot8 - 1 then
table.insert(slot0.tendencyItemList, slot9)
setText(slot10, i18n(slot12))
setText(slot0:findTF("Selected/Text", slot9), i18n(slot2 .. slot8 - 1))
end
end
slot0.tendencyNumList = {}
eachChild(slot5, function (slot0)
table.insert(slot0.tendencyNumList, 1, slot0)
end)
for slot9, slot10 in ipairs(slot0.tendencyItemList) do
onButton(slot0, slot10, function ()
if slot0.curTendency ~= slot1 - 1 then
slot0:emit(TechnologySettingsMediator.CHANGE_TENDENCY, slot1 - 1)
end
end, SFX_PANEL)
end
end
slot0.updateTendencyPage = function (slot0, slot1)
slot0.curTendency = slot1
for slot5, slot6 in ipairs(slot0.tendencyItemList) do
setActive(slot0:findTF("Selected", slot6), slot1 == slot5 - 1)
if slot1 == slot5 - 1 then
setImageAlpha(slot8, 0)
slot0:managedTween(LeanTween.alpha, nil, rtf(slot8), 1, slot0.SELECT_TENDENCY_FADE_TIME):setFrom(0)
end
end
for slot5, slot6 in ipairs(slot0.tendencyNumList) do
setActive(slot6, slot5 == slot1)
if slot5 == slot1 then
setImageAlpha(slot6, 0)
slot0:managedTween(LeanTween.alpha, nil, rtf(slot6), 1, slot0.SELECT_TENDENCY_FADE_TIME):setFrom(0)
end
end
end
slot0.updateTendencyBtn = function (slot0, slot1)
setText(slot2, i18n(slot4))
setText(slot0:findTF("Selected/Text", slot0.tendencyBtn), i18n("tec_tendency_cur_" .. slot1))
end
slot0.updateTargetCatchupPage = function (slot0, slot1)
slot0.catchupPanels[slot1]:updateTargetCatchupPage()
end
slot0.updateTargetCatchupBtns = function (slot0)
for slot4, slot5 in pairs(slot0.catchupBtns) do
if slot4 <= slot0.CATCHUP_VERSION then
slot8 = slot0:findTF("UnSelect/Text", slot5)
slot9 = slot0:findTF("Selected/Text", slot5)
slot12 = slot0:findTF("ProgressText", slot10)
slot13 = slot0:findTF("ProgressText", slot11)
setActive(slot10, slot0.technologyProxy:getCatchupState(slot4) == TechnologyCatchup.STATE_CATCHUPING)
setActive(slot0:findTF("Selected/CharImg", slot5), slot0.technologyProxy.getCatchupState(slot4) == TechnologyCatchup.STATE_CATCHUPING)
if slot0.technologyProxy.getCatchupState(slot4) == TechnologyCatchup.STATE_CATCHUPING then
setText(slot8, i18n("tec_target_catchup_selected_" .. slot4))
setText(slot9, i18n("tec_target_catchup_selected_" .. slot4))
slot14 = slot0.technologyProxy:getCurCatchupTecInfo()
slot16 = slot14.groupID
slot17 = slot14.printNum
slot18 = pg.technology_catchup_template[slot14.tecID].obtain_max
for slot22, slot23 in ipairs(slot0.catchupPanels[slot4].UR_LIST) do
if slot16 == slot23 then
slot18 = pg.technology_catchup_template[slot15].obtain_max_per_ur
end
end
setImageSprite(slot10, LoadSprite("TecCatchup/QChar" .. slot16, tostring(slot16)))
setImageSprite(slot11, LoadSprite("TecCatchup/QChar" .. slot16, tostring(slot16)))
setText(slot12, slot17 .. "/" .. slot18)
setText(slot13, slot17 .. "/" .. slot18)
elseif slot6 == TechnologyCatchup.STATE_UNSELECT then
setText(slot8, i18n("tec_target_catchup_none_" .. slot4))
setText(slot9, i18n("tec_target_catchup_none_" .. slot4))
elseif slot6 == TechnologyCatchup.STATE_FINISHED_ALL then
setText(slot8, i18n("tec_target_catchup_finish_" .. slot4))
setText(slot9, i18n("tec_target_catchup_finish_" .. slot4))
end
end
end
end
slot0.initActCatchupPage = function (slot0)
if slot0.isShowActCatchup then
slot0.loader:GetPrefab("ui/" .. slot1, "", function (slot0)
setParent(slot0, slot0.actCatchupPanel)
setLocalScale(slot0, {
x = 0.925,
y = 0.923
})
setAnchoredPosition(slot0, Vector2.zero)
slot0.actCatchupTF = slot0:findTF("AD", tf(slot0))
slot0.actCatchupItemTF = slot0:findTF("Award", slot0.actCatchupTF)
slot0.actCatchupSliderTF = slot0:findTF("Slider", slot0.actCatchupTF)
slot0.actCatchupProgressText = slot0:findTF("Progress", slot0.actCatchupTF)
if slot0:findTF("GoBtn", slot0.actCatchupTF) then
setActive(slot1, false)
end
if slot0:findTF("FinishBtn", slot0.actCatchupTF) then
setActive(slot2, false)
end
updateDrop(slot0.actCatchupItemTF, slot7)
onButton(slot0, slot0.actCatchupItemTF, function ()
slot0:emit(BaseUI.ON_DROP, slot0)
end, SFX_PANEL)
setSlider(slot0.actCatchupSliderTF, 0, slot5, slot3)
setText(slot0.actCatchupProgressText, slot3 .. "/" .. pg.activity_event_blueprint_catchup[slot0.actCatchup:getConfig("config_id")].obtain_max)
setActive(slot0, true)
end)
end
end
slot0.updateActCatchupPage = function (slot0)
return
end
slot0.updateActCatchupBtn = function (slot0)
setText(slot1, i18n("tec_act_catchup_btn_word"))
setText(slot2, i18n("tec_act_catchup_btn_word"))
slot5 = slot0:findTF("ProgressText", slot3)
slot6 = slot0:findTF("ProgressText", slot4)
slot7 = false
if getProxy(ActivityProxy):getActivityByType(ActivityConst.ACTIVITY_TYPE_BLUEPRINT_CATCHUP) and not slot8:isEnd() then
setImageSprite(slot3, LoadSprite("TecCatchup/QChar" .. slot11, tostring(slot11)))
setImageSprite(slot4, LoadSprite("TecCatchup/QChar" .. slot11, tostring(pg.activity_event_blueprint_catchup[slot8:getConfig("config_id")].char_choice)))
setText(slot5, slot9 .. "/" .. slot12)
setText(slot6, slot9 .. "/" .. pg.activity_event_blueprint_catchup[slot8.getConfig("config_id")].obtain_max)
slot13 = slot8.stopTime - pg.TimeMgr.GetInstance():GetServerTime()
if slot0.actCatchupTimer then
slot0.actCatchupTimer:Stop()
slot0.actCatchupTimer = nil
end
slot14 = slot0:findTF("TimeLeft/Day", slot0.actCatchupBtn)
slot15 = slot0:findTF("TimeLeft/Hour", slot0.actCatchupBtn)
slot16 = slot0:findTF("TimeLeft/Min", slot0.actCatchupBtn)
slot17 = slot0:findTF("TimeLeft/NumText", slot0.actCatchupBtn)
function slot18()
slot4, slot1, slot2, slot3 = pg.TimeMgr.GetInstance():parseTimeFrom(pg.TimeMgr.GetInstance().parseTimeFrom)
if slot0 - 1 >= 1 then
setActive(slot1, true)
setActive(slot2, false)
setActive(slot3, false)
setText(setText, slot0)
elseif slot0 <= 0 and slot1 > 0 then
setActive(slot1, false)
setActive(slot2, true)
setActive(slot3, false)
setText(setText, slot1)
elseif slot0 <= 0 and slot1 <= 0 and (slot2 > 0 or slot3 > 0) then
setActive(slot1, false)
setActive(slot2, false)
setActive(slot3, true)
setText(setText, math.max(slot2, 1))
elseif slot0 <= 0 and slot1 <= 0 and slot2 <= 0 and slot3 <= 0 and slot5.actCatchupTimer then
slot5.actCatchupTimer:Stop()
slot5.actCatchupTimer.actCatchupTimer = nil
nil:switchRightPage(slot6.TEC_PAGE_TENDENCY)
setActive(nil.actCatchupBtn, false)
end
end
slot0.actCatchupTimer = Timer.New(slot18, 1, -1, 1)
slot0.actCatchupTimer:Start()
slot0.actCatchupTimer.func()
slot7 = true
end
setActive(slot0.actCatchupBtn, slot7)
end
slot0.initGiveUpMsgBox = function (slot0)
slot0.giveupMsgboxIntro = slot0.giveupMsgBox:Find("window/info/intro")
slot0.giveupMsgBoxConfirmBtn = slot0.giveupMsgBox:Find("window/button_container/confirm_btn")
slot0.giveupMsgBoxCancelBtn = slot0.giveupMsgBox:Find("window/button_container/cancel_btn")
slot0.giveupMsgBoxInput = slot0.giveupMsgBox:Find("window/info/InputField")
slot0.giveupMsgboxBackBtn = slot0.giveupMsgBox:Find("window/top/btnBack")
onButton(slot0, slot0.giveupMsgBoxConfirmBtn, function ()
if not getInputText(slot0.giveupMsgBoxInput) or slot0 == "" then
pg.TipsMgr.GetInstance():ShowTips(i18n("word_should_input"))
return
end
if slot0 ~= i18n("tec_target_catchup_giveup_confirm") then
pg.TipsMgr.GetInstance():ShowTips(i18n("tec_target_catchup_giveup_input_err"))
return
end
pg.m02:sendNotification(GAME.SELECT_TEC_TARGET_CATCHUP, {
tecID = 0,
charID = 0
})
slot0:closeGiveupPanel()
end, SFX_PANEL)
onButton(slot0, slot0.giveupMsgBoxCancelBtn, function ()
slot0:closeGiveupPanel()
end, SFX_PANEL)
onButton(slot0, slot0.giveupMsgboxBackBtn, function ()
slot0:closeGiveupPanel()
end, SFX_PANEL)
end
slot0.openGiveupPanel = function (slot0)
setActive(slot0.giveupMsgBox, true)
pg.UIMgr.GetInstance():BlurPanel(slot0.giveupMsgBox)
slot0.giveupMsgboxIntro = slot0.giveupMsgBox:Find("window/info/intro")
setText(slot0.giveupMsgboxIntro, i18n("tec_target_catchup_giveup_tip", ShipGroup.getDefaultShipNameByGroupID(slot0.technologyProxy:getCurCatchupTecInfo().groupID)))
end
slot0.closeGiveupPanel = function (slot0)
setActive(slot0.giveupMsgBox, false)
pg.UIMgr.GetInstance():UnblurPanel(slot0.giveupMsgBox)
end
return slot0
|
---@class ItemConfig.Item @
local Item = {}
--------------------
-- Functions
--------------------
---@param Tags number @ (int)
---@return boolean @
function Item:HasTags(Tags)
end
---@return boolean @
function Item:IsCollectible()
end
---@return boolean @
function Item:IsNull()
end
---@return boolean @
function Item:IsTrinket()
end
--------------------
-- Variables
--------------------
---@type number @(member) (int)
Item.AchievementID = nil
---@type number @(member) (int)
Item.AddBlackHearts = nil
---@type number @(member) (int)
Item.AddBombs = nil
---@type number @(member) (int)
Item.AddCoins = nil
---@type number @(member) (int)
Item.AddHearts = nil
---@type number @(member) (int)
Item.AddKeys = nil
---@type number @(member) (int)
Item.AddMaxHearts = nil
---@type number @(member) (int)
Item.AddSoulHearts = nil
---@type number @(member) (int)
Item.CacheFlags = nil
---@type number @(member) (int)
Item.ChargeType = nil
---@type boolean @(member)
Item.ClearEffectsOnRemove = nil
---@type Costume @(member)
Item.Costume = nil
---@type string @(member)
Item.Description = nil
---@type number @(member) (int)
Item.DevilPrice = nil
---@type boolean @(member)
Item.Discharged = nil
---@type string @(member)
Item.GfxFileName = nil
---@type boolean @(member)
Item.Hidden = nil
---@type number @(member) (int)
Item.ID = nil
---@type number @(member) (int)
Item.InitCharge = nil
---@type number @(member) (int)
Item.MaxCharges = nil
---@type number @(member) (int)
Item.MaxCooldown = nil
---@type string @(member)
Item.Name = nil
---@type boolean @(member)
Item.PassiveCache = nil
---@type boolean @(member)
Item.PersistentEffect = nil
---@type number @(member) (int)
Item.Quality = nil
---@type number @(member) (int)
Item.ShopPrice = nil
---@type boolean @(member)
Item.Special = nil
---@type number @(member) (int)
Item.Tags = nil
--- mostly for Lua so it will not make a copy
---@type ItemType @(member)
Item.Type = nil
|
local playsession = {
{"Krono", {293095}},
{"gearmach1ne", {394379}},
{"Scuideie-Guy", {253133}},
{"SLQ", {307844}},
{"Zorzzz", {376633}},
{"matam666", {141604}},
{"Daveyboy80", {5927}},
{"Axel_Henir", {19917}},
{"Aeropagus", {26176}},
{"N0lan", {118470}},
{"phanton5000", {60472}},
{"vince527", {218136}},
{"JC1223", {131375}},
{"Destijah", {954}},
{"SilkyZilky", {131600}},
{"KiloG", {3233}},
{"JinNJuice", {78772}},
{"wildgrim", {76214}},
{"Aero182218", {5279}},
{"svjatosha", {5118}}
}
return playsession |
local Cursor = required("Cursor")
local DrawCommands = required("DrawCommands")
local LayoutManager = required("LayoutManager")
local Mouse = required("Mouse")
local Region = required("Region")
local Stats = required("Stats")
local Style = required("Style")
local text = required("text")
local Window = required("Window")
local ListBox = {}
local instances = {}
local active_instance = nil
local function get_item_instance(instance, id)
if instance ~= nil then
if instance.items[id] == nil then
local item = {}
item.id = id
item.x = 0.0
item.y = 0.0
item.w = 0.0
item.h = 0.0
instance.items[id] = item
end
return instance.items[id]
end
return nil
end
local function get_instance(id)
if instances[id] == nil then
local instance = {}
instance.id = id
instance.x = 0.0
instance.y = 0.0
instance.w = 0.0
instance.h = 0.0
instance.items = {}
instance.active_item = nil
instance.hot_item = nil
instance.selected = false
instance.stat_handle = nil
instances[id] = instance
end
return instances[id]
end
function ListBox.begin(id, options)
local stat_handle = Stats.begin("ListBox", "Slab")
options = options == nil and {} or options
options.w = options.w == nil and 150.0 or options.w
options.h = options.h == nil and 150.0 or options.h
options.clear = options.clear == nil and false or options.clear
options.rounding = options.rounding == nil and Style.WindowRounding or options.rounding
options.stretch_w = options.stretch_w or false
options.stretch_h = options.stretch_h or false
local instance = get_instance(Window.get_item_id(id))
local w = options.w
local h = options.h
if options.clear then
instance.items = {}
end
w, h = LayoutManager.compute_size(w, h)
LayoutManager.add_control(w, h)
local remaining_w, remaining_h = Window.get_remaining_size()
if options.stretch_w then
w = remaining_w
end
if options.stretch_h then
h = remaining_h
end
local x, y = Cursor.get_position()
instance.x = x
instance.y = y
instance.w = w
instance.h = h
instance.stat_handle = stat_handle
active_instance = instance
Cursor.set_item_bounds(x, y, w, h)
Cursor.advance_y(0.0)
Window.add_item(x, y, w, h, instance.id)
local is_obstructed = Window.is_obstructed_at_mouse()
local t_x, t_y = Window.transform_point(x, y)
local mouse_x, mouse_y = Window.get_mouse_position()
Region.begin(
instance.id,
{
x = x,
y = y,
w = w,
h = h,
s_x = t_x,
s_y = t_y,
auto_size_content = true,
no_background = true,
intersect = true,
mouse_x = mouse_x,
mouse_y = mouse_y,
reset_content = Window.has_resized(),
is_obstructed = is_obstructed,
rounding = options.rounding
}
)
instance.hot_item = nil
local in_region = Region.contains(mouse_x, mouse_y)
mouse_x, mouse_y = Region.inverse_transform(instance.id, mouse_x, mouse_y)
for k, v in pairs(instance.items) do
if
not is_obstructed and not Region.is_hover_scroll_bar(instance.id) and v.x <= mouse_x and mouse_x <= v.x + instance.w and
v.y <= mouse_y and
mouse_y <= v.y + v.h and
in_region
then
instance.hot_item = v
end
if instance.hot_item == v or v.selected then
DrawCommands.rectangle("fill", v.x, v.y, instance.w, v.h, Style.TextHoverBgColor)
end
end
LayoutManager.begin("ignore", {ignore = true})
end
function ListBox.begin_item(id, options)
options = options == nil and {} or options
options.selected = options.selected == nil and false or options.selected
assert(active_instance ~= nil, "Trying to call begin_list_box_item outside of begin_list_box.")
assert(
active_instance.active_item == nil,
"begin_list_box_item was called for item '" ..
(active_instance.active_item ~= nil and active_instance.active_item.id or "nil") ..
"' without a call to end_list_box_item."
)
local item = get_item_instance(active_instance, id)
item.x = active_instance.x
item.y = Cursor.get_y()
Cursor.set_x(item.x)
Cursor.advance_x(0.0)
active_instance.active_item = item
active_instance.active_item.selected = options.selected
end
function ListBox.is_item_clicked(button, IsDoubleClick)
assert(active_instance ~= nil, "Trying to call is_item_clicked outside of begin_list_box.")
assert(active_instance.active_item ~= nil, "is_item_clicked was called outside of begin_list_box_item.")
if active_instance.hot_item == active_instance.active_item then
button = button == nil and 1 or button
if IsDoubleClick then
return Mouse.is_double_clicked(button)
else
return Mouse.is_clicked(button)
end
end
return false
end
function ListBox.end_item()
assert(active_instance ~= nil, "Trying to call begin_list_box_item outside of begin_list_box.")
assert(active_instance.active_item ~= nil, "Trying to call end_list_box_item without calling begin_list_box_item.")
local item_x, item_y, item_w, item_h = Cursor.get_item_bounds()
active_instance.active_item.w = item_w
active_instance.active_item.h = Cursor.get_line_height()
Cursor.set_y(active_instance.active_item.y + active_instance.active_item.h)
Cursor.advance_y(0.0)
active_instance.active_item = nil
end
function ListBox.finish()
assert(active_instance ~= nil, "end_list_box was called without calling begin_list_box.")
Region.finish()
Region.apply_scissor()
Cursor.set_item_bounds(active_instance.x, active_instance.y, active_instance.w, active_instance.h)
Cursor.set_position(active_instance.x, active_instance.y)
Cursor.advance_y(active_instance.h)
LayoutManager.finish()
Stats.finish(active_instance.stat_handle)
active_instance = nil
end
return ListBox
|
local t = Def.ActorFrame {
Name = "PlayerInfoFrame",
LoginMessageCommand = function(self)
self:playcommand("Set")
ms.ok("Login Successful")
end,
LogOutMessageCommand = function(self)
self:playcommand("Set")
end,
LoginFailedMessageCommand = function(self)
self:playcommand("Set")
end,
OnlineUpdateMessageCommand = function(self)
self:playcommand("Set")
end
}
local visEnabled = Var("visualizer")
local loadingScreenName = Var("screen")
local ratios = {
Height = 109 / 1080, -- frame height
Width = 1, -- full screen width
AvatarWidth = 109 / 1080, -- this should end up square
ConnectionLogoRightGap = 0 / 1080, -- logo position relative to the right edge of avatar (height based for square)
ConnectionLogoBottomGap = 0 / 1080, -- same as above
ConnectionLogoSize = 36 / 1080, -- this is 36x36
LeftTextLeftGap = 8 / 1920, -- this is after the avatar
LeftTextTopGap1 = 24 / 1080, -- from top to center of line 1
LeftTextTopGap2 = 49 / 1080, -- from top to center of line 2
LeftTextTopGap3 = 72 / 1080, -- from top to center of line 3
LeftTextTopGap4 = 95 / 1080, -- from top to center of line 4
RightTextLeftGap = 412 / 1920, -- this is from avatar to right text
RightTextTopGap1 = 21 / 1080, -- why did this have to be different from Left line 1
RightTextTopGap2 = 54 / 1080, -- from top to center of line 2
RightTextTopGap3 = 89 / 1080, -- from top to center of line 3
VisualizerLeftGap = 707 / 1920, -- from left side of screen to leftmost bin
VisualizerWidth = 693 / 1920,
RatingEdgeToVisualizerBuffer = 32 / 1920,
RatingSideBuffer = 25 / 1920, -- an area of buffer to the left and right of the player rating text
IconUpperGap = 36 / 1080,
IconExitWidth = 47 / 1920,
IconExitHeight = 36 / 1080,
IconExitRightGap = 38 / 1920, -- from right side of screen to right end of icon
IconSettingsWidth = 44 / 1920,
IconSettingsHeight = 35 / 1080,
IconSettingsRightGap = 123 / 1920,
IconHelpWidth = 36 / 1920,
IconHelpHeight = 36 / 1080,
IconHelpRightGap = 205 / 1920,
IconDownloadsWidth = 51 / 1920,
IconDownloadsHeight = 36 / 1080,
IconDownloadsRightGap = 278 / 1920,
IconDownloadsProgressBar1UpperGap = 51 / 1080, -- top of icon to top of bar
IconDownloadsProgressBarHeight = 9 / 1080,
IconDownloadsProgressBarWidth = 88 / 1920,
IconRandomWidth = 41 / 1920,
IconRandomHeight = 36 / 1080,
IconRandomRightGap = 367 / 1920,
IconSearchWidth = 36 / 1920,
IconSearchHeight = 36 / 1080,
IconSearchRightGap = 446 / 1920,
}
local actuals = {
Height = ratios.Height * SCREEN_HEIGHT,
Width = ratios.Width * SCREEN_WIDTH,
AvatarWidth = ratios.AvatarWidth * SCREEN_HEIGHT,
ConnectionLogoRightGap = ratios.ConnectionLogoRightGap * SCREEN_HEIGHT,
ConnectionLogoBottomGap = ratios.ConnectionLogoBottomGap * SCREEN_HEIGHT,
ConnectionLogoSize = ratios.ConnectionLogoSize * SCREEN_HEIGHT,
LeftTextLeftGap = ratios.LeftTextLeftGap * SCREEN_WIDTH,
LeftTextTopGap1 = ratios.LeftTextTopGap1 * SCREEN_HEIGHT,
LeftTextTopGap2 = ratios.LeftTextTopGap2 * SCREEN_HEIGHT,
LeftTextTopGap3 = ratios.LeftTextTopGap3 * SCREEN_HEIGHT,
LeftTextTopGap4 = ratios.LeftTextTopGap4 * SCREEN_HEIGHT,
RightTextLeftGap = ratios.RightTextLeftGap * SCREEN_WIDTH,
RightTextTopGap1 = ratios.RightTextTopGap1 * SCREEN_HEIGHT,
RightTextTopGap2 = ratios.RightTextTopGap2 * SCREEN_HEIGHT,
RightTextTopGap3 = ratios.RightTextTopGap3 * SCREEN_HEIGHT,
VisualizerLeftGap = ratios.VisualizerLeftGap * SCREEN_WIDTH,
VisualizerWidth = ratios.VisualizerWidth * SCREEN_WIDTH,
RatingEdgeToVisualizerBuffer = ratios.RatingEdgeToVisualizerBuffer * SCREEN_WIDTH,
RatingSideBuffer = ratios.RatingSideBuffer * SCREEN_WIDTH,
IconUpperGap = ratios.IconUpperGap * SCREEN_HEIGHT,
IconExitWidth = ratios.IconExitWidth * SCREEN_WIDTH,
IconExitHeight = ratios.IconExitHeight * SCREEN_HEIGHT,
IconExitRightGap = ratios.IconExitRightGap * SCREEN_WIDTH,
IconSettingsWidth = ratios.IconSettingsWidth * SCREEN_WIDTH,
IconSettingsHeight = ratios.IconSettingsHeight * SCREEN_HEIGHT,
IconSettingsRightGap = ratios.IconSettingsRightGap * SCREEN_WIDTH,
IconHelpWidth = ratios.IconHelpWidth * SCREEN_WIDTH,
IconHelpHeight = ratios.IconHelpHeight * SCREEN_HEIGHT,
IconHelpRightGap = ratios.IconHelpRightGap * SCREEN_WIDTH,
IconDownloadsWidth = ratios.IconDownloadsWidth * SCREEN_WIDTH,
IconDownloadsHeight = ratios.IconDownloadsHeight * SCREEN_HEIGHT,
IconDownloadsRightGap = ratios.IconDownloadsRightGap * SCREEN_WIDTH,
IconDownloadsProgressBar1UpperGap = ratios.IconDownloadsProgressBar1UpperGap * SCREEN_HEIGHT,
IconDownloadsProgressBarHeight = ratios.IconDownloadsProgressBarHeight * SCREEN_HEIGHT,
IconDownloadsProgressBarWidth = ratios.IconDownloadsProgressBarWidth * SCREEN_WIDTH,
IconRandomWidth = ratios.IconRandomWidth * SCREEN_WIDTH,
IconRandomHeight = ratios.IconRandomHeight * SCREEN_HEIGHT,
IconRandomRightGap = ratios.IconRandomRightGap * SCREEN_WIDTH,
IconSearchWidth = ratios.IconSearchWidth * SCREEN_WIDTH,
IconSearchHeight = ratios.IconSearchHeight * SCREEN_HEIGHT,
IconSearchRightGap = ratios.IconSearchRightGap * SCREEN_WIDTH,
}
-- the list of buttons and the lists of screens those buttons are allowed on
-- if "All" is listed, the button is always active
local screensAllowedForButtons = {
Exit = {
All = true,
},
Settings = {
ScreenSelectMusic = true,
},
Help = {
},
Downloads = {
ScreenSelectMusic = true,
},
Random = {
ScreenSelectMusic = true,
},
Search = {
ScreenSelectMusic = true,
},
AssetSettings = {
ScreenSelectMusic = true,
},
}
-- find out if a button from the above list is selectable based on the current screen
-- wont work on Init, only when the screen exists (at or after BeginCommand)
local function selectable(name)
local screen = loadingScreenName
return screensAllowedForButtons[name]["All"] ~= nil or screensAllowedForButtons[name][screen]
end
local disabledButtonAlpha = 0.4
local hoverAlpha = 0.6
local visualizerBins = 126
local leftTextBigSize = 0.7
local leftTextSmallSize = 0.65
local rightTextSize = 0.7
local textzoomFudge = 5 -- for gaps in maxwidth
-- a controllable hack to give more girth to the rating text (RightText) on smaller aspect ratios
-- should push the visualizer further right and make less problems
local textzoomBudge = 25
local profile = GetPlayerOrMachineProfile(PLAYER_1)
local pname = profile:GetDisplayName()
local pcount = SCOREMAN:GetTotalNumberOfScores()
local parrows = profile:GetTotalTapsAndHolds()
local strparrows = shortenIfOver1Mil(parrows)
local ptime = profile:GetTotalSessionSeconds()
local username = ""
local redir = false -- tell whether or not redirected input is on for the login prompt stuff
local downloadsProgress1BGAlpha = 0.4
local downloadsProgress1Alpha = 1
local downloadsProgress2BGAlpha = 0.4
local downloadsProgress2Alpha = 1
-- this does not include the exit button
-- from left to right starting at 1, the user may press a number while holding to control to activate them
-- assuming context is set and the button is allowed
local iconCountForKeyboardInput = 5
-- handle logging in
local function beginLoginProcess(self)
redir = SCREENMAN:get_input_redirected(PLAYER_1)
local function off()
if redir then
SCREENMAN:set_input_redirected(PLAYER_1, false)
end
end
local function on()
if redir then
SCREENMAN:set_input_redirected(PLAYER_1, true)
end
end
off()
username = ""
-- this sets up 2 text entry windows to pull your username and pass
-- if you press escape or just enter nothing, you are forced out
-- input redirects are controlled here because we want to be careful not to break any prior redirects
askForInputStringWithFunction(
"Enter Username",
255,
false,
function(answer)
username = answer
-- moving on to step 2 if the answer isnt blank
if answer:gsub("^%s*(.-)%s*$", "%1") ~= "" then
self:sleep(0.01):queuecommand("LoginStep2")
else
ms.ok("Login cancelled")
on()
end
end,
function() return true, "" end,
function()
on()
ms.ok("Login cancelled")
end
)
end
-- do not use this function outside of first calling beginLoginProcess
local function loginStep2()
local function off()
if redir then
SCREENMAN:set_input_redirected(PLAYER_1, false)
end
end
local function on()
if redir then
SCREENMAN:set_input_redirected(PLAYER_1, true)
end
end
-- try to keep the scope of password here
-- if we open up the scope, if a lua error happens on this screen
-- the password may show up in the error message
local password = ""
askForInputStringWithFunction(
"Enter Password",
255,
true,
function(answer)
password = answer
-- log in if not blank
if answer:gsub("^%s*(.-)%s*$", "%1") ~= "" then
DLMAN:Login(username, password)
else
ms.ok("Login cancelled")
end
on()
end,
function() return true, "" end,
function()
on()
ms.ok("Login cancelled")
end
)
end
t[#t+1] = Def.Quad {
Name = "BG",
InitCommand = function(self)
self:halign(0):valign(0)
self:zoomto(actuals.Width, actuals.Height)
self:diffuse(color("#111111"))
self:diffusealpha(0.8)
end
}
t[#t+1] = UIElements.SpriteButton(1, 1, nil) .. {
Name = "Avatar",
InitCommand = function(self)
self:halign(0):valign(0)
end,
BeginCommand = function(self)
self:playcommand("Set")
end,
AvatarChangedMessageCommand = function(self)
self:playcommand("Set")
end,
SetCommand = function(self)
self:Load(getAvatarPath(PLAYER_1))
self:zoomto(actuals.AvatarWidth, actuals.AvatarWidth)
end,
MouseOverCommand = function(self)
if selectable("AssetSettings") then
self:diffusealpha(hoverAlpha)
end
end,
MouseOutCommand = function(self)
if selectable("AssetSettings") then
self:diffusealpha(1)
end
end,
InvokeCommand = function(self)
if selectable("AssetSettings") then
-- if clicking or otherwise invoking this twice, just toggle back to generalBox
if CONTEXTMAN:CheckContextSet(SCREENMAN:GetTopScreen():GetName(), "AssetSettings") then
MESSAGEMAN:Broadcast("GeneralTabSet")
else
MESSAGEMAN:Broadcast("PlayerInfoFrameTabSet", {tab = "AssetSettings"})
end
end
end,
MouseDownCommand = function(self, params)
self:playcommand("Invoke")
end
}
t[#t+1] = UIElements.SpriteButton(1, 1, nil) .. {
Name = "ConnectionSprite",
InitCommand = function(self)
self:halign(1):valign(1)
-- position relative to the bottom right corner of the avatar
self:xy(actuals.AvatarWidth - actuals.ConnectionLogoRightGap, actuals.AvatarWidth - actuals.ConnectionLogoBottomGap)
self:playcommand("Set")
end,
SetCommand = function(self)
if DLMAN:IsLoggedIn() then
self:Load(THEME:GetPathG("", "loggedin"))
else
self:Load(THEME:GetPathG("", "loggedout"))
end
self:zoomto(actuals.ConnectionLogoSize, actuals.ConnectionLogoSize)
end,
MouseOverCommand = function(self)
self:diffusealpha(hoverAlpha)
end,
MouseOutCommand = function(self)
self:diffusealpha(1)
end,
MouseDownCommand = function(self, params)
if params.event == "DeviceButton_left mouse button" then
if DLMAN:IsLoggedIn() then
DLMAN:Logout()
else
beginLoginProcess(self)
end
end
end,
LoginStep2Command = function(self)
loginStep2()
end
}
t[#t+1] = Def.ActorFrame {
Name = "LeftText",
InitCommand = function(self)
self:x(actuals.AvatarWidth + actuals.LeftTextLeftGap)
end,
LoadFont("Common Normal") .. {
Name = "NameRank",
InitCommand = function(self)
self:y(actuals.LeftTextTopGap1)
self:halign(0)
self:zoom(leftTextBigSize)
self:maxwidth((actuals.RightTextLeftGap - actuals.LeftTextLeftGap) / leftTextBigSize - textzoomFudge)
self:playcommand("Set")
end,
SetCommand = function(self)
if DLMAN:IsLoggedIn() then
local pn = DLMAN:GetUsername()
self:settextf("%s (#%d)", pn, DLMAN:GetSkillsetRank("Overall"))
else
self:settext(pname)
end
end
},
LoadFont("Common Normal") .. {
Name = "Playcount",
InitCommand = function(self)
self:y(actuals.LeftTextTopGap2)
self:halign(0)
self:zoom(leftTextSmallSize)
self:maxwidth((actuals.RightTextLeftGap - actuals.LeftTextLeftGap) / leftTextSmallSize - textzoomFudge)
self:settextf("%d plays", pcount)
end
},
UIElements.TextToolTip(1, 1, "Common Normal") .. {
Name = "Arrows",
InitCommand = function(self)
self:y(actuals.LeftTextTopGap3)
self:halign(0)
self:zoom(leftTextSmallSize)
self:maxwidth((actuals.RightTextLeftGap - actuals.LeftTextLeftGap) / leftTextSmallSize - textzoomFudge)
self:settextf("%s arrows smashed", strparrows)
end,
MouseOverCommand = function(self)
if self:IsInvisible() then return end
TOOLTIP:SetText(parrows)
TOOLTIP:Show()
end,
MouseOutCommand = function(self)
if self:IsInvisible() then return end
TOOLTIP:Hide()
end,
},
LoadFont("Common Normal") .. {
Name = "Playtime",
InitCommand = function(self)
self:y(actuals.LeftTextTopGap4)
self:halign(0)
self:zoom(leftTextSmallSize)
self:maxwidth((actuals.RightTextLeftGap - actuals.LeftTextLeftGap) / leftTextSmallSize - textzoomFudge)
self:settextf("%s playtime", SecondsToHHMMSS(ptime))
end
}
}
t[#t+1] = Def.ActorFrame {
Name = "RightText",
InitCommand = function(self)
self:x(actuals.AvatarWidth + actuals.RightTextLeftGap)
end,
BeginCommand = function(self)
local lt = self:GetParent():GetChild("LeftText")
local longestWidth = getLargestChildWidth(lt)
self:x(actuals.AvatarWidth + longestWidth + actuals.RatingSideBuffer)
end,
LoadFont("Common Normal") .. {
Name = "Header",
InitCommand = function(self)
self:y(actuals.RightTextTopGap1)
self:halign(0)
self:zoom(rightTextSize)
self:maxwidth((actuals.VisualizerLeftGap - actuals.RightTextLeftGap - actuals.AvatarWidth) / rightTextSize + textzoomBudge)
self:playcommand("Set")
end,
SetCommand = function(self)
if DLMAN:IsLoggedIn() then
self:settext("Player Ratings:")
else
self:settext("Player Rating:")
end
end
},
LoadFont("Common Normal") .. {
Name = "OfflineRating",
InitCommand = function(self)
self:y(actuals.RightTextTopGap2)
self:halign(0)
self:zoom(rightTextSize)
self:maxwidth((actuals.VisualizerLeftGap - actuals.RightTextLeftGap - actuals.AvatarWidth) / rightTextSize + textzoomBudge)
self:playcommand("Set")
end,
SetCommand = function(self)
local offlinerating = profile:GetPlayerRating()
if DLMAN:IsLoggedIn() then
self:settextf("Offline - %5.2f", offlinerating)
else
self:settextf("%5.2f", offlinerating)
end
end
},
LoadFont("Common Normal") .. {
Name = "OnlineRating",
InitCommand = function(self)
self:y(actuals.RightTextTopGap3)
self:halign(0)
self:zoom(rightTextSize)
self:maxwidth((actuals.VisualizerLeftGap - actuals.RightTextLeftGap - actuals.AvatarWidth) / rightTextSize + textzoomBudge)
self:playcommand("Set")
end,
SetCommand = function(self)
if DLMAN:IsLoggedIn() then
self:settextf("Online - %5.2f", DLMAN:GetSkillsetRating("Overall"))
else
self:settext("")
end
end
},
}
t[#t+1] = Def.ActorFrame {
Name = "Icons",
InitCommand = function(self)
self:xy(SCREEN_WIDTH, actuals.IconUpperGap)
end,
BeginCommand = function(self)
local snm = SCREENMAN:GetTopScreen():GetName()
local anm = self:GetName()
-- this keeps track of whether or not the user is allowed to use the keyboard to change tabs
CONTEXTMAN:RegisterToContextSet(snm, "Main1", anm)
-- enable the possibility to press the keyboard to switch tabs
SCREENMAN:GetTopScreen():AddInputCallback(function(event)
if event.type ~= "InputEventType_FirstPress" then return end
-- this list of contexts are meant to be contexts of the PlayerInfo Frame
-- full numeric input is allowed on these tabs and you must hold CTRL+Number to get out of them
-- the same way you would get into them
local contextsToCtrlOutOf = {
"Search",
"Downloads",
"Settings",
"AssetSettings",
}
local ctxBypasses = false
for _, ctx in ipairs(contextsToCtrlOutOf) do
if CONTEXTMAN:CheckContextSet(snm, ctx) then ctxBypasses = true break end
end
-- allowing ctrl+n to go back to general tabs
if ctxBypasses then
if event.char and tonumber(event.char) and INPUTFILTER:IsControlPressed() then
local n = tonumber(event.char)
if n == 0 then n = 10 end
if n >= 1 and n <= SCUFF.generaltabcount then
MESSAGEMAN:Broadcast("GeneralTabSet", {tab = n})
end
end
return
end
-- if locked out, dont allow
if not CONTEXTMAN:CheckContextSet(snm, "Main1") then return end
-- must be a number with control held down
if event.char and tonumber(event.char) and INPUTFILTER:IsControlPressed() then
local n = tonumber(event.char)
if n == 0 then n = 10 end
if n >= 1 and n <= iconCountForKeyboardInput then
local childToInvoke = nil
if n == 1 then
childToInvoke = self:GetChild("Search")
elseif n == 2 then
childToInvoke = self:GetChild("Random")
elseif n == 3 then
childToInvoke = self:GetChild("Downloads")
elseif n == 4 then
childToInvoke = self:GetChild("Help")
elseif n == 5 then
childToInvoke = self:GetChild("Settings")
end
if childToInvoke ~= nil then
childToInvoke:playcommand("Invoke")
end
end
elseif event.DeviceInput.button == "DeviceButton_F1" then
-- im making a single exception that F1 alone invokes Search
-- for convenience purposes
self:GetChild("Search"):playcommand("Invoke")
end
end)
end,
UIElements.SpriteButton(1, 1, THEME:GetPathG("", "exit")) .. {
Name = "Exit",
InitCommand = function(self)
self:halign(1):valign(0)
self:x(-actuals.IconExitRightGap)
self:zoomto(actuals.IconExitWidth, actuals.IconExitHeight)
self:diffusealpha(disabledButtonAlpha)
end,
OnCommand = function(self)
if selectable(self:GetName()) then
self:diffusealpha(1)
end
end,
MouseOverCommand = function(self)
if selectable(self:GetName()) then
self:diffusealpha(hoverAlpha)
end
end,
MouseOutCommand = function(self)
if selectable(self:GetName()) then
self:diffusealpha(1)
end
end,
MouseDownCommand = function(self, params)
if params.event == "DeviceButton_left mouse button" then
SCREENMAN:set_input_redirected(PLAEYR_1, false)
SCREENMAN:GetTopScreen():Cancel()
end
end
},
UIElements.SpriteButton(1, 1, THEME:GetPathG("", "settings")) .. {
Name = "Settings",
InitCommand = function(self)
self:halign(1):valign(0)
self:x(-actuals.IconSettingsRightGap)
self:zoomto(actuals.IconSettingsWidth, actuals.IconSettingsHeight)
self:diffusealpha(disabledButtonAlpha)
end,
OnCommand = function(self)
if selectable(self:GetName()) then
self:diffusealpha(1)
end
end,
MouseOverCommand = function(self)
if selectable(self:GetName()) then
self:diffusealpha(hoverAlpha)
end
end,
MouseOutCommand = function(self)
if selectable(self:GetName()) then
self:diffusealpha(1)
end
end,
InvokeCommand = function(self)
if selectable(self:GetName()) then
-- if clicking or otherwise invoking this twice, just toggle back to generalBox
if CONTEXTMAN:CheckContextSet(SCREENMAN:GetTopScreen():GetName(), "Settings") then
MESSAGEMAN:Broadcast("GeneralTabSet")
else
MESSAGEMAN:Broadcast("PlayerInfoFrameTabSet", {tab = "Settings"})
end
end
end,
MouseDownCommand = function(self, params)
self:playcommand("Invoke")
end
},
UIElements.SpriteButton(1, 1, THEME:GetPathG("", "gameinfoandhelp")) .. {
Name = "Help",
InitCommand = function(self)
self:halign(1):valign(0)
self:x(-actuals.IconHelpRightGap)
self:zoomto(actuals.IconHelpWidth, actuals.IconHelpHeight)
self:diffusealpha(disabledButtonAlpha)
end,
OnCommand = function(self)
if selectable(self:GetName()) then
self:diffusealpha(1)
end
end,
MouseOverCommand = function(self)
if selectable(self:GetName()) then
self:diffusealpha(hoverAlpha)
end
end,
MouseOutCommand = function(self)
if selectable(self:GetName()) then
self:diffusealpha(1)
end
end,
InvokeCommand = function(self)
if selectable(self:GetName()) then
end
end,
MouseDownCommand = function(self, params)
self:playcommand("Invoke")
end
},
Def.ActorFrame {
Name = "Downloads",
InitCommand = function(self)
self:x(-actuals.IconDownloadsRightGap)
self:diffusealpha(disabledButtonAlpha)
end,
OnCommand = function(self)
if selectable(self:GetName()) then
self:diffusealpha(1)
end
end,
UIElements.SpriteButton(1, 1, THEME:GetPathG("", "packdownloads")) .. {
Name = "Downloads",
InitCommand = function(self)
self:halign(1):valign(0)
self:zoomto(actuals.IconDownloadsWidth, actuals.IconDownloadsHeight)
end,
MouseOverCommand = function(self)
if selectable(self:GetName()) then
self:diffusealpha(hoverAlpha)
end
end,
MouseOutCommand = function(self)
if selectable(self:GetName()) then
self:diffusealpha(1)
end
end,
InvokeCommand = function(self)
if selectable(self:GetName()) then
-- if clicking or otherwise invoking this twice, just toggle back to generalBox
if CONTEXTMAN:CheckContextSet(SCREENMAN:GetTopScreen():GetName(), "Downloads") then
MESSAGEMAN:Broadcast("GeneralTabSet")
else
MESSAGEMAN:Broadcast("PlayerInfoFrameTabSet", {tab = "Downloads"})
end
end
end,
MouseDownCommand = function(self, params)
self:playcommand("Invoke")
end
},
Def.Quad {
Name = "Progress1BG",
InitCommand = function(self)
self:valign(0)
self:x(-actuals.IconDownloadsWidth/2)
self:y(actuals.IconDownloadsProgressBar1UpperGap)
self:zoomto(actuals.IconDownloadsProgressBarWidth, actuals.IconDownloadsProgressBarHeight)
self:diffusealpha(0)
end,
DLProgressAndQueueUpdateMessageCommand = function(self)
local dls = DLMAN:GetDownloads()
if #dls > 0 then
self:diffusealpha(downloadsProgress1BGAlpha)
else
self:diffusealpha(0)
end
end,
AllDownloadsCompletedMessageCommand = function(self)
self:diffusealpha(0)
end
},
Def.Quad {
Name = "Progress1Progress",
InitCommand = function(self)
self:halign(0):valign(0)
self:x(-actuals.IconDownloadsWidth/2 - actuals.IconDownloadsProgressBarWidth/2)
self:y(actuals.IconDownloadsProgressBar1UpperGap)
self:zoomto(actuals.IconDownloadsProgressBarWidth, actuals.IconDownloadsProgressBarHeight)
self:diffusealpha(0)
end,
DLProgressAndQueueUpdateMessageCommand = function(self)
local dls = DLMAN:GetDownloads()
if #dls > 0 then
self:diffusealpha(downloadsProgress1Alpha)
local progress = dls[1]:GetKBDownloaded()
local size = dls[1]:GetTotalKB()
local perc = progress / size
self:zoomx(actuals.IconDownloadsProgressBarWidth * perc)
else
self:diffusealpha(0)
end
end,
AllDownloadsCompletedMessageCommand = function(self)
self:diffusealpha(0)
end
}
},
UIElements.SpriteButton(1, 1, THEME:GetPathG("", "random")) .. {
Name = "Random",
InitCommand = function(self)
self:halign(1):valign(0)
self:x(-actuals.IconRandomRightGap)
self:zoomto(actuals.IconRandomWidth, actuals.IconRandomHeight)
self:diffusealpha(disabledButtonAlpha)
end,
OnCommand = function(self)
if selectable(self:GetName()) then
self:diffusealpha(1)
end
end,
MouseOverCommand = function(self)
if selectable(self:GetName()) then
self:diffusealpha(hoverAlpha)
end
end,
MouseOutCommand = function(self)
if selectable(self:GetName()) then
self:diffusealpha(1)
end
end,
InvokeCommand = function(self)
if selectable(self:GetName()) then
local scr = SCREENMAN:GetTopScreen()
local group = WHEELDATA:GetRandomFolder()
local song = WHEELDATA:GetRandomSongInFolder(group)
scr:GetChild("WheelFile"):playcommand("FindSong", {song = song})
end
end,
MouseDownCommand = function(self, params)
self:playcommand("Invoke")
end
},
UIElements.SpriteButton(1, 1, THEME:GetPathG("", "searchIcon")) .. {
Name = "Search",
InitCommand = function(self)
self:halign(1):valign(0)
self:x(-actuals.IconSearchRightGap)
self:zoomto(actuals.IconSearchWidth, actuals.IconSearchHeight)
self:diffusealpha(disabledButtonAlpha)
end,
OnCommand = function(self)
if selectable(self:GetName()) then
self:diffusealpha(1)
end
end,
MouseOverCommand = function(self)
if selectable(self:GetName()) then
self:diffusealpha(hoverAlpha)
end
end,
MouseOutCommand = function(self)
if selectable(self:GetName()) then
self:diffusealpha(1)
end
end,
InvokeCommand = function(self)
if selectable(self:GetName()) then
-- if clicking or otherwise invoking this twice, just toggle back to generalBox
if CONTEXTMAN:CheckContextSet(SCREENMAN:GetTopScreen():GetName(), "Search") then
MESSAGEMAN:Broadcast("GeneralTabSet")
else
MESSAGEMAN:Broadcast("PlayerInfoFrameTabSet", {tab = "Search"})
end
end
end,
MouseDownCommand = function(self, params)
self:playcommand("Invoke")
end
}
}
if visEnabled then
local intervals = {0, 10, 26, 48, 60, 92, 120, 140, 240, 400, 800, 1600, 2600, 3500, 4000}
t[#t+1] = audioVisualizer:new {
x = actuals.VisualizerLeftGap,
y = actuals.Height,
width = actuals.VisualizerWidth,
maxHeight = actuals.Height / 1.8,
freqIntervals = audioVisualizer.multiplyIntervals(intervals, 9),
color = color("1,1,1,1"),
onBarUpdate = function(self)
-- hmm
end
} .. {
BeginCommand = function(self)
local rt = self:GetParent():GetChild("RightText")
local x = rt:GetX()
local longestWidth = getLargestChildWidth(rt)
x = x + longestWidth + actuals.RatingEdgeToVisualizerBuffer
local newVisualizerWidth = actuals.VisualizerWidth + (actuals.VisualizerLeftGap - x)
self:x(x)
self:playcommand("ResetWidth", {width = newVisualizerWidth})
end
}
end
-- below this point we load things that only work on specific screens
-- buttons that arent meant to function on some screens dont need their intended targets loaded
-- this saves on load time and fps
if selectable("Exit") then
-- nothing, it's just a button
end
if selectable("Settings") then
t[#t+1] = LoadActor("settings.lua")
end
if selectable("Help") then
-- nothing yet
end
if selectable("Downloads") then
t[#t+1] = LoadActor("downloads.lua")
end
if selectable("Random") then
-- nothing, it's just a button
end
if selectable("Search") then
t[#t+1] = LoadActor("searchfilter.lua")
end
if selectable("AssetSettings") then
t[#t+1] = LoadActor("assetsettings.lua")
end
return t |
describe("lredis.protocol module", function()
local protocol = require "lredis.protocol"
local function write_to_temp_file(str)
local file = io.tmpfile()
assert(file:write(str))
assert(file:flush())
assert(file:seek("set"))
return file
end
-- Docs at http://redis.io/topics/protocol
it("composes example from docs", function()
-- From "Sending commands to a Redis Server" section
assert.same("*2\r\n$4\r\nLLEN\r\n$6\r\nmylist\r\n",
protocol.encode_request{"LLEN", "mylist"})
end)
it("can parse examples from docs", function()
--- From "RESP Arrays" section
-- Empty array
assert.same({},
protocol.default_read_response(write_to_temp_file "*0\r\n"))
-- an array of two RESP Bulk Strings "foo" and "bar"
assert.same({"foo", "bar"},
protocol.default_read_response(write_to_temp_file "*2\r\n$3\r\nfoo\r\n$3\r\nbar\r\n"))
-- an Array of three integers
assert.same({1, 2, 3},
protocol.default_read_response(write_to_temp_file "*3\r\n:1\r\n:2\r\n:3\r\n"))
-- mixed types: a list of four integers and a bulk string
assert.same({1, 2, 3, 4, "foobar"},
protocol.default_read_response(write_to_temp_file "*5\r\n:1\r\n:2\r\n:3\r\n:4\r\n$6\r\nfoobar\r\n"))
-- null
assert.same(protocol.array_null,
protocol.default_read_response(write_to_temp_file "*-1\r\n"))
-- array of arrays
assert.same(
{
{1,2,3},
{
protocol.status_reply("Foo");
protocol.error_reply("Bar");
}
},
protocol.default_read_response(write_to_temp_file "*2\r\n*3\r\n:1\r\n:2\r\n:3\r\n*2\r\n+Foo\r\n-Bar\r\n")
)
--- From "Null elements in Arrays" section
assert.same(
{ "foo", protocol.string_null, "bar" },
protocol.default_read_response(write_to_temp_file "*3\r\n$3\r\nfoo\r\n$-1\r\n$3\r\nbar\r\n")
)
end)
end)
|
-- Disable haskell-vim omnifunc
vim.g.haskellmode_completion_ghc = 0
wincent.vim.setlocal('omnifunc', 'necoghc#omnifunc')
|
local createEnum = import("../createEnum")
return createEnum("ScaleType", {
Stretch = 0,
Slice = 1,
Tile = 2,
Fit = 3,
Crop = 4,
}) |
local default_style = data.raw["gui-style"].default
local function color_graphics(posX, posY)
return {
type = "monolith",
top_monolith_border = 2,
right_monolith_border = 0,
bottom_monolith_border = 0,
left_monolith_border = 0,
monolith_image = {
filename = "__Enhanced_Map_Colors__/graphics/colors.png",
priority = "extra-high-no-scale",
width = 12,
height = 8,
x = posX,
y = posY,
},
}
end
default_style.entity_style = {
type = "button_style",
parent = "button_style",
scalable = true,
default_font_color={r=0, g=0, b=0},
width = 38,
height = 38,
top_padding = 1,
right_padding = 0,
bottom_padding = 0,
left_padding = 2,
default_graphical_set =
{
type = "composition",
filename = "__core__/graphics/gui.png",
priority = "extra-high-no-scale",
corner_size = {3, 3},
position = {8, 0}
},
hovered_graphical_set =
{
type = "composition",
filename = "__core__/graphics/gui.png",
priority = "extra-high-no-scale",
corner_size = {3, 3},
position = {8, 0}
},
clicked_graphical_set =
{
type = "composition",
filename = "__core__/graphics/gui.png",
priority = "extra-high-no-scale",
corner_size = {3, 3},
position = {8, 0}
}
}
default_style.map_color_graphic_basic = {
type = "button_style",
parent = "slot_button_style",
scalable = true,
top_padding = 1,
right_padding = 1,
bottom_padding = 0,
left_padding = 1,
width = 48,
width = 38,
default_graphical_set = color_graphics( 0, 0),
hovered_graphical_set = color_graphics( 0, 0),
clicked_graphical_set = color_graphics( 0, 0)
}
default_style.map_color_graphic_fast = {
type = "button_style",
parent = "slot_button_style",
scalable = true,
top_padding = 1,
right_padding = 1,
bottom_padding = 1,
left_padding = 1,
width = 48,
width = 38,
default_graphical_set = color_graphics( 0, 9),
hovered_graphical_set = color_graphics( 0, 9),
clicked_graphical_set = color_graphics( 0, 9)
}
default_style.map_color_graphic_express = {
type = "button_style",
parent = "slot_button_style",
scalable = true,
top_padding = 1,
right_padding = 1,
bottom_padding = 1,
left_padding = 1,
width = 48,
width = 38,
default_graphical_set = color_graphics( 0, 18),
hovered_graphical_set = color_graphics( 0, 18),
clicked_graphical_set = color_graphics( 0, 18)
}
default_style.map_color_graphic_ptg = {
type = "button_style",
parent = "slot_button_style",
scalable = true,
top_padding = 1,
right_padding = 1,
bottom_padding = 1,
left_padding = 1,
width = 48,
width = 38,
default_graphical_set = color_graphics( 0, 27),
hovered_graphical_set = color_graphics( 0, 27),
clicked_graphical_set = color_graphics( 0, 27)
}
default_style.map_color_graphic_medium = {
type = "button_style",
parent = "slot_button_style",
scalable = true,
top_padding = 1,
right_padding = 1,
bottom_padding = 1,
left_padding = 1,
width = 48,
width = 38,
default_graphical_set = color_graphics( 0, 36),
hovered_graphical_set = color_graphics( 0, 36),
clicked_graphical_set = color_graphics( 0, 36)
}
default_style.map_color_graphic_solar = {
type = "button_style",
parent = "slot_button_style",
scalable = true,
top_padding = 1,
right_padding = 1,
bottom_padding = 1,
left_padding = 1,
width = 48,
width = 38,
default_graphical_set = color_graphics( 0, 45),
hovered_graphical_set = color_graphics( 0, 45),
clicked_graphical_set = color_graphics( 0, 45)
}
default_style.map_color_graphic_port = {
type = "button_style",
parent = "slot_button_style",
scalable = true,
top_padding = 1,
right_padding = 1,
bottom_padding = 1,
left_padding = 1,
width = 48,
width = 38,
default_graphical_set = color_graphics( 13, 54),
hovered_graphical_set = color_graphics( 13, 54),
clicked_graphical_set = color_graphics( 13, 54)
}
default_style.map_color_graphic_radar = {
type = "button_style",
parent = "slot_button_style",
scalable = true,
top_padding = 1,
right_padding = 1,
bottom_padding = 1,
left_padding = 1,
width = 48,
width = 38,
default_graphical_set = color_graphics( 0, 54),
hovered_graphical_set = color_graphics( 0, 54),
clicked_graphical_set = color_graphics( 0, 54)
}
default_style.map_color_graphic_bob_logistics_4 = {
type = "button_style",
parent = "slot_button_style",
scalable = true,
top_padding = 1,
right_padding = 1,
bottom_padding = 1,
left_padding = 1,
width = 48,
width = 38,
default_graphical_set = color_graphics( 13, 0),
hovered_graphical_set = color_graphics( 13, 0),
clicked_graphical_set = color_graphics( 13, 0)
}
default_style.map_color_graphic_bob_logistics_5 = {
type = "button_style",
parent = "slot_button_style",
scalable = true,
top_padding = 1,
right_padding = 1,
bottom_padding = 1,
left_padding = 1,
width = 48,
width = 38,
default_graphical_set = color_graphics( 13, 9),
hovered_graphical_set = color_graphics( 13, 9),
clicked_graphical_set = color_graphics( 13, 9)
}
default_style.map_color_graphic_5dim_transport_4 = {
type = "button_style",
parent = "slot_button_style",
scalable = true,
top_padding = 1,
right_padding = 1,
bottom_padding = 1,
left_padding = 1,
width = 48,
width = 38,
default_graphical_set = color_graphics( 13, 18),
hovered_graphical_set = color_graphics( 13, 18),
clicked_graphical_set = color_graphics( 13, 18)
}
default_style.map_color_graphic_5dim_transport_5 = {
type = "button_style",
parent = "slot_button_style",
scalable = true,
top_padding = 1,
right_padding = 1,
bottom_padding = 1,
left_padding = 1,
width = 48,
width = 38,
default_graphical_set = color_graphics( 13, 27),
hovered_graphical_set = color_graphics( 13, 27),
clicked_graphical_set = color_graphics( 13, 27)
}
default_style.map_color_graphic_DyTech_super_4 = {
type = "button_style",
parent = "slot_button_style",
scalable = true,
top_padding = 1,
right_padding = 1,
bottom_padding = 1,
left_padding = 1,
width = 48,
width = 38,
default_graphical_set = color_graphics( 13, 36),
hovered_graphical_set = color_graphics( 13, 36),
clicked_graphical_set = color_graphics( 13, 36)
}
default_style.map_color_graphic_DyTech_extreme_5 = {
type = "button_style",
parent = "slot_button_style",
scalable = true,
top_padding = 1,
right_padding = 1,
bottom_padding = 1,
left_padding = 1,
width = 48,
width = 38,
default_graphical_set = color_graphics( 13, 45),
hovered_graphical_set = color_graphics( 13, 45),
clicked_graphical_set = color_graphics( 13, 45)
}
default_style.visible_bots_construction = {
type = "button_style",
parent = "slot_button_style",
scalable = true,
top_padding = 1,
right_padding = 1,
bottom_padding = 1,
left_padding = 1,
width = 48,
width = 38,
default_graphical_set = color_graphics( 0, 63),
hovered_graphical_set = color_graphics( 0, 63),
clicked_graphical_set = color_graphics( 0, 63)
}
default_style.visible_bots_logistic = {
type = "button_style",
parent = "slot_button_style",
scalable = true,
top_padding = 1,
right_padding = 1,
bottom_padding = 1,
left_padding = 1,
width = 48,
width = 38,
default_graphical_set = color_graphics( 13, 63),
hovered_graphical_set = color_graphics( 13, 63),
clicked_graphical_set = color_graphics( 13, 63)
} |
local error = require('telescope._extensions.gradle.util').error
local has_telescope, telescope = pcall(require, "telescope")
if not has_telescope then
error "This extension requires telescope.nvim (https://github.com/nvim-telescope/telescope.nvim)"
end
local cfg = nil
-- List available gradle tasks and run the picked one.
local tasks = function(opts)
opts = vim.tbl_extend("keep", opts or {}, cfg)
local tasks_picker = require('telescope._extensions.gradle.pickers.tasks')
local queries = require('telescope._extensions.gradle.queries')
queries.tasks(tasks_picker(opts), opts.project)
end
-- List the history of run tasks.
local history = function(opts)
local history_picker = require('telescope._extensions.gradle.pickers.history')
history_picker(opts)
end
-- Pick a Gradle project and run tasks on it.
local projects = function(opts)
local projects_picker = require('telescope._extensions.gradle.pickers.projects')
local queries = require('telescope._extensions.gradle.queries')
queries.projects(projects_picker(opts))
end
return telescope.register_extension {
setup = function(config) cfg = config end,
exports = {
gradle = tasks,
tasks = tasks,
history = history,
projects = projects
}
}
|
require ("util")
local hit_effects = require ("__base__/prototypes/entity/hit-effects")
local sounds = require("__base__/prototypes/entity/sounds")
data:extend({
{
type = "simple-entity-with-owner",
render_layer = "lower-object",
name = "wooden-billboard",
icon = "__simple-billboard__/graphics/icons/wooden-billboard.png",
icon_size = 64, icon_mipmaps = 4,
flags = {"placeable-neutral", "player-creation"},
minable = {mining_time = 0.1, result = "wooden-billboard"},
max_health = 100,
dying_explosion = "wooden-chest-explosion",
collision_box = {{-0.35, -0.35}, {0.35, 0.35}},
selection_box = {{-0.5, -0.5}, {0.5, 0.5}},
damaged_trigger_effect = hit_effects.entity(),
inventory_size = 0,
open_sound = { filename = "__base__/sound/wooden-chest-open.ogg", volume = 0.6 },
close_sound = { filename = "__base__/sound/wooden-chest-close.ogg", volume = 0.6 },
vehicle_impact_sound = sounds.car_wood_impact(0.5),
picture =
{
layers =
{
{
filename = "__simple-billboard__/graphics/entity/wooden-billboard/wooden-billboard.png",
priority = "extra-high",
width = 32,
height = 32,
shift = util.by_pixel(0.5, -2),
hr_version =
{
filename = "__simple-billboard__/graphics/entity/wooden-billboard/hr-wooden-billboard.png",
priority = "extra-high",
width = 64,
height = 64,
shift = util.by_pixel(0.5, -2),
scale = 0.5
}
},
{
filename = "__simple-billboard__/graphics/entity/wooden-billboard/billboard-billboard-shadow.png",
priority = "extra-high",
width = 32,
height = 32,
draw_as_shadow = true,
shift = util.by_pixel(1, -2),
hr_version =
{
filename = "__simple-billboard__/graphics/entity/wooden-billboard/hr-wooden-billboard-shadow.png",
priority = "extra-high",
width = 64,
height = 64,
draw_as_shadow = true,
shift = util.by_pixel(1, -2),
scale = 0.5
}
}
}
},
},
{
type = "simple-entity-with-owner",
render_layer = "lower-object",
name = "wooden-billboard-1x2",
icon = "__simple-billboard__/graphics/icons/wooden-billboard-1x2.png",
icon_size = 64, icon_mipmaps = 4,
flags = {"placeable-neutral", "player-creation"},
minable = {mining_time = 0.1, result = "wooden-billboard-1x2"},
max_health = 100,
dying_explosion = "wooden-chest-explosion",
collision_box = {{-0.85, -0.35}, {0.85, 0.35}},
selection_box = {{-1, -0.5}, {1, 0.5}},
damaged_trigger_effect = hit_effects.entity(),
inventory_size = 0,
open_sound = { filename = "__base__/sound/wooden-chest-open.ogg", volume = 0.6 },
close_sound = { filename = "__base__/sound/wooden-chest-close.ogg", volume = 0.6 },
vehicle_impact_sound = sounds.car_wood_impact(0.5),
picture =
{
layers =
{
{
filename = "__simple-billboard__/graphics/entity/wooden-billboard/wooden-billboard-1x2.png",
priority = "extra-high",
width = 62,
height = 31,
shift = util.by_pixel(0.5, -2),
hr_version =
{
filename = "__simple-billboard__/graphics/entity/wooden-billboard/hr-wooden-billboard-1x2.png",
priority = "extra-high",
width = 124,
height = 62,
shift = util.by_pixel(0.5, -2),
scale = 0.5
}
},
{
filename = "__simple-billboard__/graphics/entity/wooden-billboard/billboard-billboard-shadow-1x2.png",
priority = "extra-high",
width = 62,
height = 31,
draw_as_shadow = true,
shift = util.by_pixel(1, -2),
hr_version =
{
filename = "__simple-billboard__/graphics/entity/wooden-billboard/hr-wooden-billboard-shadow-1x2.png",
priority = "extra-high",
width = 124,
height = 62,
shift = util.by_pixel(1, -2),
draw_as_shadow = true,
scale = 0.5
}
}
}
},
},
{
type = "simple-entity-with-owner",
render_layer = "lower-object",
name = "wooden-billboard-1x4",
icon = "__simple-billboard__/graphics/icons/wooden-billboard-1x4.png",
icon_size = 64, icon_mipmaps = 4,
flags = {"placeable-neutral", "player-creation"},
minable = {mining_time = 0.1, result = "wooden-billboard-1x4"},
max_health = 100,
dying_explosion = "wooden-chest-explosion",
collision_box = {{-1.85, -0.35}, {1.85, 0.35}},
selection_box = {{-2, -0.5}, {2, 0.5}},
damaged_trigger_effect = hit_effects.entity(),
inventory_size = 0,
open_sound = { filename = "__base__/sound/wooden-chest-open.ogg", volume = 0.6 },
close_sound = { filename = "__base__/sound/wooden-chest-close.ogg", volume = 0.6 },
vehicle_impact_sound = sounds.car_wood_impact(0.5),
picture =
{
layers =
{
{
filename = "__simple-billboard__/graphics/entity/wooden-billboard/wooden-billboard-1x4.png",
priority = "extra-high",
width = 124,
height = 31,
shift = util.by_pixel(0.5, -2),
hr_version =
{
filename = "__simple-billboard__/graphics/entity/wooden-billboard/hr-wooden-billboard-1x4.png",
priority = "extra-high",
width = 248,
height = 62,
shift = util.by_pixel(0.5, -2),
scale = 0.5
}
},
{
filename = "__simple-billboard__/graphics/entity/wooden-billboard/billboard-billboard-shadow-1x4.png",
priority = "extra-high",
width = 124,
height = 31,
draw_as_shadow = true,
shift = util.by_pixel(1, -2),
hr_version =
{
filename = "__simple-billboard__/graphics/entity/wooden-billboard/hr-wooden-billboard-shadow-1x4.png",
priority = "extra-high",
width = 248,
height = 62,
shift = util.by_pixel(1, -2),
draw_as_shadow = true,
scale = 0.5
}
}
}
},
},
{
type = "simple-entity-with-owner",
render_layer = "lower-object",
name = "wooden-billboard-2x2",
icon = "__simple-billboard__/graphics/icons/wooden-billboard-2x2.png",
icon_size = 64, icon_mipmaps = 4,
flags = {"placeable-neutral", "player-creation"},
minable = {mining_time = 0.1, result = "wooden-billboard-2x2"},
max_health = 200,
dying_explosion = "wooden-chest-explosion",
collision_box = {{-0.85, -0.85}, {0.85, 0.85}},
selection_box = {{-1, -1}, {1, 1}},
damaged_trigger_effect = hit_effects.entity(),
inventory_size = 0,
open_sound = { filename = "__base__/sound/wooden-chest-open.ogg", volume = 0.6 },
close_sound = { filename = "__base__/sound/wooden-chest-close.ogg", volume = 0.6 },
vehicle_impact_sound = sounds.car_wood_impact(0.5),
picture =
{
layers =
{
{
filename = "__simple-billboard__/graphics/entity/wooden-billboard/wooden-billboard-2x2.png",
priority = "extra-high",
width = 62,
height = 59,
shift = util.by_pixel(0.5, -2),
hr_version =
{
filename = "__simple-billboard__/graphics/entity/wooden-billboard/hr-wooden-billboard-2x2.png",
priority = "extra-high",
width = 124,
height = 118,
shift = util.by_pixel(0.5, -2),
scale = 0.5
}
},
{
filename = "__simple-billboard__/graphics/entity/wooden-billboard/billboard-billboard-shadow-2x2.png",
priority = "extra-high",
width = 62,
height = 59,
shift = util.by_pixel(1, -2),
draw_as_shadow = true,
hr_version =
{
filename = "__simple-billboard__/graphics/entity/wooden-billboard/hr-wooden-billboard-shadow-2x2.png",
priority = "extra-high",
width = 124,
height = 118,
shift = util.by_pixel(1, -2),
draw_as_shadow = true,
scale = 0.5
}
}
}
},
},
{
type = "simple-entity-with-owner",
render_layer = "lower-object",
name = "wooden-billboard-2x4",
icon = "__simple-billboard__/graphics/icons/wooden-billboard-2x4.png",
icon_size = 64, icon_mipmaps = 4,
flags = {"placeable-neutral", "player-creation"},
minable = {mining_time = 0.1, result = "wooden-billboard-2x4"},
max_health = 200,
dying_explosion = "wooden-chest-explosion",
collision_box = {{-1.85, -0.85}, {1.85, 0.85}},
selection_box = {{-2, -1}, {2, 1}},
damaged_trigger_effect = hit_effects.entity(),
inventory_size = 0,
open_sound = { filename = "__base__/sound/wooden-chest-open.ogg", volume = 0.6 },
close_sound = { filename = "__base__/sound/wooden-chest-close.ogg", volume = 0.6 },
vehicle_impact_sound = sounds.car_wood_impact(0.5),
picture =
{
layers =
{
{
filename = "__simple-billboard__/graphics/entity/wooden-billboard/wooden-billboard-2x4.png",
priority = "extra-high",
width = 130,
height = 62,
shift = util.by_pixel(0.5, -2),
hr_version =
{
filename = "__simple-billboard__/graphics/entity/wooden-billboard/hr-wooden-billboard-2x4.png",
priority = "extra-high",
width = 248,
height = 118,
shift = util.by_pixel(0.5, -2),
scale = 0.5
}
},
{
filename = "__simple-billboard__/graphics/entity/wooden-billboard/billboard-billboard-shadow-2x4.png",
priority = "extra-high",
width = 130,
height = 62,
draw_as_shadow = true,
shift = util.by_pixel(1, -2),
hr_version =
{
filename = "__simple-billboard__/graphics/entity/wooden-billboard/hr-wooden-billboard-shadow-2x4.png",
priority = "extra-high",
width = 248,
height = 118,
shift = util.by_pixel(1, -2),
draw_as_shadow = true,
scale = 0.5
}
}
}
},
},
{
type = "simple-entity-with-owner",
render_layer = "lower-object",
name = "wooden-billboard-4x4",
icon = "__simple-billboard__/graphics/icons/wooden-billboard-4x4.png",
icon_size = 64, icon_mipmaps = 4,
flags = {"placeable-neutral", "player-creation"},
minable = {mining_time = 0.1, result = "wooden-billboard-4x4"},
max_health = 300,
dying_explosion = "wooden-chest-explosion",
collision_box = {{-1.85, -0.85}, {1.85, 0.85}},
selection_box = {{-2, -2}, {2, 2}},
damaged_trigger_effect = hit_effects.entity(),
inventory_size = 0,
open_sound = { filename = "__base__/sound/wooden-chest-open.ogg", volume = 0.6 },
close_sound = { filename = "__base__/sound/wooden-chest-close.ogg", volume = 0.6 },
vehicle_impact_sound = sounds.car_wood_impact(0.5),
picture =
{
layers =
{
{
filename = "__simple-billboard__/graphics/entity/wooden-billboard/wooden-billboard-4x4.png",
priority = "extra-high",
width = 124,
height = 129,
shift = util.by_pixel(0.5, -2),
hr_version =
{
filename = "__simple-billboard__/graphics/entity/wooden-billboard/hr-wooden-billboard-4x4.png",
priority = "extra-high",
width = 248,
height = 258,
shift = util.by_pixel(0.5, -2),
scale = 0.5
}
},
{
filename = "__simple-billboard__/graphics/entity/wooden-billboard/billboard-billboard-shadow-4x4.png",
priority = "extra-high",
width = 124,
height = 129,
draw_as_shadow = true,
shift = util.by_pixel(1, -2),
hr_version =
{
filename = "__simple-billboard__/graphics/entity/wooden-billboard/hr-wooden-billboard-shadow-4x4.png",
priority = "extra-high",
width = 248,
height = 258,
shift = util.by_pixel(1, -2),
draw_as_shadow = true,
scale = 0.5
}
}
}
},
},
}) |
function main.get_sky(name)
local sky = 1
table.foreach(skybox.skies, function(k, v)
if v == name then
sky = k
end
end)
return sky
end
function main.clear_inv(inv)
for _, s in ipairs(inv:get_list("main")) do
inv:remove_item("main", s)
end
end
function main.give_starter_items(inv)
main.clear_inv(inv)
if vc_info.mode_running then
if main.current_mode.mode.starter_items then
for _, item in ipairs(main.current_mode.mode.starter_items) do
inv:add_item("main", item)
end
end
end
end
|
package("exprtk")
set_kind("library", {headeronly = true})
set_homepage("https://www.partow.net/programming/exprtk/index.html")
set_description("C++ Mathematical Expression Parsing And Evaluation Library")
set_license("MIT")
add_urls("https://github.com/ArashPartow/exprtk.git")
add_versions("2021.06.06", "93a9f44f99b910bfe07cd1e933371e83cea3841c")
if is_plat("windows") then
add_cxxflags("/bigobj")
elseif is_plat("mingw") then
add_cxxflags("-Wa,-mbig-obj")
end
on_install(function (package)
os.cp("exprtk.hpp", package:installdir("include"))
end)
on_test(function (package)
assert(package:check_cxxsnippets({test = [[
void test() {
double x;
const std::string expression_string =
"clamp(-1.0,sin(2 * pi * x) + cos(x / 2 * pi),+1.0)";
exprtk::symbol_table<double> symbol_table;
exprtk::expression<double> expression;
exprtk::parser<double> parser;
symbol_table.add_variable("x",x);
symbol_table.add_constants();
expression.register_symbol_table(symbol_table);
parser.compile(expression_string,expression);
}
]]}, {configs = {languages = "c++14"}, includes = "exprtk.hpp"}))
end)
|
local Replicated = game:GetService("ReplicatedStorage")
local Utility = Replicated.Utility
local AntObject = {}
AntObject.__index = AntObject
local function Constructor(InstantietedBy)
local Object = setmetatable({}, AntObject)
Object.Locked = {}
Object.Unlocked = {}
Object.DataTypeLimitations = {}
Object.InheritFrom = {}
Object.AntObject = true
Object.SuperLocked = false
Object.InstantiatedFrom = InstantietedBy
Object.Changed = Object.CreateEvent()
Object:LockProperty("Locked", "Unlocked", "DataTypeLimitations", "SuperLocked", "InheritFrom", "InstantiatedFrom", "Changed")
local proxy = {}
proxy.__index = function(tab, index)
local Value = Object[index]
Value = Value or AntObject[index]
if Value ~= nil then return Value end
local InheritingFrom = Object.InheritFrom
for i = 1, #InheritingFrom do
local Current = InheritingFrom[i][index]
if Current then
return Current
end
end
return Object.InstantiatedFrom[index]
end
proxy.__newindex = function(tab, index, value)
if rawget(Object,index) == value then return end
local Limitation = Object.DataTypeLimitations[index]
if (Object.SuperLocked == false and Object.Locked[index] ~= nil) or (Object.SuperLocked == true and Object.Unlocked[index] == nil) then
error("The property: "..index.." is read only or just locked!")
elseif Limitation == typeof(value) or Limitation == nil or value == nil then
rawset(Object, index, value or Object.DefaultValue)
Object.Changed:Fire(index, value)
else
error(string.upper(Limitation).." expected, got: "..string.upper(typeof(value)))
end
end
return setmetatable({}, proxy)
end
function AntObject:LockProperty(...)
if self.SuperLocked == true then
warn("The object is already Super Locked, theres no point in locking any properties")
return
end
local ToLock = {...}
for i,v in pairs(ToLock) do
self.Locked[v] = true ---Will work as a new index for the table Locked is just made
self.Unlocked[v] = nil
end
end
function AntObject:UnlockProperty(...)
local ToUnlock = {...}
for i,v in pairs(ToUnlock) do
self.Locked[v] = nil
self.Unlocked[v] = true
end
end
function AntObject:SuperLock()
rawset(self, "SuperLocked", true)
end
function AntObject:SuperUnlock()
rawset(self, "SuperLocked", false)
end
function AntObject:LimitDataType(Index, DataType)
DataType = string.lower(DataType)
self.DataTypeLimitations[Index] = DataType
end
function AntObject:BreakDataTypeLimit(Index)
self.DataTypeLimitations[Index] = nil
end
function AntObject:GetClassesInheritingFrom(Current)
local TableLibrary = require(Utility.TableLibrary)
Current = Current or {[self.InstantiatedFrom.ClassName] = true}
for i,v in pairs(self.InheritFrom) do
Current[v.ClassName] = true
if #v.InheritFrom > 0 then
TableLibrary.Paste(Current, v:GetClassesInheritingFrom(Current), true)
end
end
for i,v in pairs(self.InstantiatedFrom.InheritFrom) do
Current[v.ClassName] = true
if #v.InheritFrom > 0 then
TableLibrary.Paste(Current, v:GetClassesInheritingFrom(Current), true)
end
end
return Current
end
function AntObject:ClearConnections(tab)
tab = tab or self
for i,v in pairs(tab) do
if v.Event == true then
v:ClearConnections()
elseif typeof(v) == "table" then
self:ClearConnections(v)
end
end
end
function AntObject.CreateEvent()
local EventClass = require(script.Parent.AntEvent)
local NewEvent = EventClass()
--self[index] = NewEvent
return NewEvent
end
return Constructor
|
local irc = require "ircclient"
local assert = require "test.assert"
local target = "[email protected]"
local col_int = "[B]foo[/B] [U]bar[/U] [COLOR=RED]baz[/COLOR]"
local col_mirc = "\2foo\2 \31bar\31 \00304baz\15"
assert.equal(irc.get_nick(target), "foo")
assert.equal(irc.get_host(target), "[email protected]")
assert.equal(irc.color_convert_to_mirc(col_int), col_mirc)
assert.equal(irc.color_convert_from_mirc(col_mirc), col_int)
assert.equal(irc.color_strip(col_mirc), "foo bar baz")
assert.type(irc.errors.INVAL, "number")
assert.equal(irc.errors[irc.errors.INVAL], "INVAL")
assert.type(irc.options.DEBUG, "number")
assert.equal(irc.options[irc.options.DEBUG], "DEBUG")
local session = irc.create_session()
assert.type(session, "userdata")
local mt = debug.getmetatable(session)
local uv = (debug.getfenv or debug.getuservalue)(session)
assert.equal(mt.__metatable, false)
assert.type(uv.events, "table")
assert.type(uv.dcc, "table")
assert.equal(uv.error, print)
session:set_error_handler(io.write)
assert.equal(uv.error, io.write)
local cb1, cb2 = function() return 1 end, function() return 2 end
assert.equal(session:register("CONNECT", cb1), true)
assert.equal(session:register("connect", cb2), true)
assert.equal(session:register("connect", cb1), false)
assert.equal(session:unregister("connect", cb1), true)
assert.equal(session:unregister("connect", cb2), true)
assert.equal(session:unregister("connect", cb1), false)
if not getfenv then -- skip test on 5.1
local _, ref = debug.getupvalue(irc.create_session, 1)
local reg = debug.getregistry()[ref]
assert.type(reg, "table")
assert.equal(getmetatable(reg).__mode, "v")
assert.equal(select(2, next(reg)), session)
session = nil
collectgarbage()
assert.equal(next(reg), nil)
end
print("All tests passed")
|
local L = LibStub("AceLocale-3.0"):GetLocale("Skada", false)
local AceGUI = LibStub("AceGUI-3.0")
-- Mode menu list sorted by category
local function _modeMenu(window, level)
local info = UIDropDownMenu_CreateInfo()
local modes = Skada:GetModes()
local categorized = {}
for i, module in ipairs(modes) do
table.insert(categorized, module)
end
table.sort(categorized, function(a, b)
local a_score = 0
local b_score = 0
if a.category == L['Other'] then
a_score = 1000
end
if b.category == L['Other'] then
b_score = 1000
end
a_score = a_score + (string.byte(a.category, 1) * 10) + string.byte(a:GetName(), 1)
b_score = b_score + (string.byte(b.category, 1) * 10) + string.byte(b:GetName(), 1)
return a_score < b_score
end)
local lastcat = nil
for i, module in ipairs(categorized) do
if not lastcat or lastcat ~= module.category then
if lastcat then
-- Add a blank separator
info = UIDropDownMenu_CreateInfo()
info.disabled = 1
info.notCheckable = 1
UIDropDownMenu_AddButton(info, level)
end
info = UIDropDownMenu_CreateInfo()
info.isTitle = 1
info.text = module.category
UIDropDownMenu_AddButton(info, level)
lastcat = module.category
end
info = UIDropDownMenu_CreateInfo()
info.text = module:GetName()
info.func = function() window:DisplayMode(module) end
info.checked = (window.selectedmode == module)
UIDropDownMenu_AddButton(info, level)
end
end
local function getDropdownPoint()
local x,y = GetCursorPosition(UIParent);
x = x / UIParent:GetEffectiveScale();
y = y / UIParent:GetEffectiveScale();
local point
if x > GetScreenWidth() / 2 then
point = "RIGHT"
else
point = "LEFT"
end
if y > GetScreenHeight() / 2 then
point = "TOP"..point
else
point = "BOTTOM"..point
end
return point, x, y
end
-- Configuration menu.
function Skada:OpenMenu(window)
if not self.skadamenu then
self.skadamenu = CreateFrame("Frame", "SkadaMenu")
end
local skadamenu = self.skadamenu
skadamenu.displayMode = "MENU"
local info = UIDropDownMenu_CreateInfo()
skadamenu.initialize = function(self, level)
if not level then return end
if level == 1 then
-- Create the title of the menu
info = UIDropDownMenu_CreateInfo()
info.isTitle = 1
info.text = L["Skada Menu"]
info.notCheckable = 1
UIDropDownMenu_AddButton(info, level)
for i, win in ipairs(Skada:GetWindows()) do
info = UIDropDownMenu_CreateInfo()
info.text = win.db.name
info.hasArrow = 1
info.value = win
info.notCheckable = 1
UIDropDownMenu_AddButton(info, level)
end
-- Add a blank separator
info = UIDropDownMenu_CreateInfo()
info.disabled = 1
info.notCheckable = 1
UIDropDownMenu_AddButton(info, level)
-- Can't report if we are not in a mode.
if not window or (window and window.selectedmode) then
info = UIDropDownMenu_CreateInfo()
info.text = L["Report"]
info.func = function() Skada:OpenReportWindow(window) end
info.value = "report"
info.notCheckable = 1
UIDropDownMenu_AddButton(info, level)
end
info = UIDropDownMenu_CreateInfo()
info.text = L["Delete segment"]
info.hasArrow = 1
info.notCheckable = 1
info.value = "delete"
UIDropDownMenu_AddButton(info, level)
info = UIDropDownMenu_CreateInfo()
info.text = L["Keep segment"]
info.notCheckable = 1
info.hasArrow = 1
info.value = "keep"
UIDropDownMenu_AddButton(info, level)
-- Add a blank separator
info = UIDropDownMenu_CreateInfo()
info.disabled = 1
info.notCheckable = 1
UIDropDownMenu_AddButton(info, level)
info = UIDropDownMenu_CreateInfo()
info.text = L["Toggle window"]
info.func = function() Skada:ToggleWindow() end
info.notCheckable = 1
UIDropDownMenu_AddButton(info, level)
info = UIDropDownMenu_CreateInfo()
info.text = L["Reset"]
info.func = function() Skada:Reset() end
info.notCheckable = 1
UIDropDownMenu_AddButton(info, level)
info = UIDropDownMenu_CreateInfo()
info.text = L["Start new segment"]
info.func = function() Skada:NewSegment() end
info.notCheckable = 1
UIDropDownMenu_AddButton(info, level)
info = UIDropDownMenu_CreateInfo()
info.text = L["Configure"]
info.func = function()
Skada:OpenOptions(window)
end
info.notCheckable = 1
UIDropDownMenu_AddButton(info, level)
-- Close menu item
info = UIDropDownMenu_CreateInfo()
info.text = CLOSE
info.func = function() CloseDropDownMenus() end
info.checked = nil
info.notCheckable = 1
UIDropDownMenu_AddButton(info, level)
elseif level == 2 then
if type(UIDROPDOWNMENU_MENU_VALUE) == "table" then
local window = UIDROPDOWNMENU_MENU_VALUE
-- Display list of modes with current ticked; let user switch mode by checking one.
info = UIDropDownMenu_CreateInfo()
info.isTitle = 1
info.text = L["Mode"]
UIDropDownMenu_AddButton(info, level)
for i, module in ipairs(Skada:GetModes()) do
info = UIDropDownMenu_CreateInfo()
info.text = module:GetName()
info.func = function() window:DisplayMode(module) end
info.checked = (window.selectedmode == module)
UIDropDownMenu_AddButton(info, level)
end
-- Separator
info = UIDropDownMenu_CreateInfo()
info.disabled = 1
info.notCheckable = 1
UIDropDownMenu_AddButton(info, level)
-- Display list of sets with current ticked; let user switch set by checking one.
info = UIDropDownMenu_CreateInfo()
info.isTitle = 1
info.text = L["Segment"]
UIDropDownMenu_AddButton(info, level)
info = UIDropDownMenu_CreateInfo()
info.text = L["Total"]
info.func = function()
window.selectedset = "total"
Skada:Wipe()
Skada:UpdateDisplay(true)
end
info.checked = (window.selectedset == "total")
UIDropDownMenu_AddButton(info, level)
info = UIDropDownMenu_CreateInfo()
info.text = L["Current"]
info.func = function()
window.selectedset = "current"
Skada:Wipe()
Skada:UpdateDisplay(true)
end
info.checked = (window.selectedset == "current")
UIDropDownMenu_AddButton(info, level)
for i, set in ipairs(Skada:GetSets()) do
wipe(info)
info.text = Skada:GetSetLabel(set)
info.func = function()
window.selectedset = i
Skada:Wipe()
Skada:UpdateDisplay(true)
end
info.checked = (window.selectedset == set.starttime)
UIDropDownMenu_AddButton(info, level)
end
-- Add a blank separator
info = UIDropDownMenu_CreateInfo()
info.disabled = 1
info.notCheckable = 1
UIDropDownMenu_AddButton(info, level)
info = UIDropDownMenu_CreateInfo()
info.text = L["Lock window"]
info.func = function()
window.db.barslocked = not window.db.barslocked
Skada:ApplySettings()
end
info.checked = window.db.barslocked
UIDropDownMenu_AddButton(info, level)
info = UIDropDownMenu_CreateInfo()
info.text = L["Hide window"]
info.func = function() if window:IsShown() then window.db.hidden = true; window:Hide() else window.db.hidden = false; window:Show() end end
info.checked = not window:IsShown()
UIDropDownMenu_AddButton(info, level)
elseif UIDROPDOWNMENU_MENU_VALUE == "delete" then
for i, set in ipairs(Skada:GetSets()) do
info = UIDropDownMenu_CreateInfo()
info.text = Skada:GetSetLabel(set)
info.func = function() Skada:DeleteSet(set) end
info.notCheckable = 1
UIDropDownMenu_AddButton(info, level)
end
elseif UIDROPDOWNMENU_MENU_VALUE == "keep" then
for i, set in ipairs(Skada:GetSets()) do
info = UIDropDownMenu_CreateInfo()
info.text = Skada:GetSetLabel(set)
info.func = function()
set.keep = not set.keep
Skada:Wipe()
Skada:UpdateDisplay(true)
end
info.checked = set.keep
UIDropDownMenu_AddButton(info, level)
end
end
elseif level == 3 then
if UIDROPDOWNMENU_MENU_VALUE == "modes" then
for i, module in ipairs(Skada:GetModes()) do
info = UIDropDownMenu_CreateInfo()
info.text = module:GetName()
info.checked = (Skada.db.profile.report.mode == module:GetName())
info.func = function() Skada.db.profile.report.mode = module:GetName() end
UIDropDownMenu_AddButton(info, level)
end
elseif UIDROPDOWNMENU_MENU_VALUE == "segment" then
info = UIDropDownMenu_CreateInfo()
info.text = L["Total"]
info.func = function() Skada.db.profile.report.set = "total" end
info.checked = (Skada.db.profile.report.set == "total")
UIDropDownMenu_AddButton(info, level)
info = UIDropDownMenu_CreateInfo()
info.text = L["Current"]
info.func = function() Skada.db.profile.report.set = "current" end
info.checked = (Skada.db.profile.report.set == "current")
UIDropDownMenu_AddButton(info, level)
for i, set in ipairs(Skada:GetSets()) do
info = UIDropDownMenu_CreateInfo()
info.text = Skada:GetSetLabel(set)
info.func = function() Skada.db.profile.report.set = i end
info.checked = (Skada.db.profile.report.set == i)
UIDropDownMenu_AddButton(info, level)
end
elseif UIDROPDOWNMENU_MENU_VALUE == "number" then
for i = 1,25 do
info = UIDropDownMenu_CreateInfo()
info.text = i
info.checked = (Skada.db.profile.report.number == i)
info.func = function() Skada.db.profile.report.number = i end
UIDropDownMenu_AddButton(info, level)
end
elseif UIDROPDOWNMENU_MENU_VALUE == "channel" then
info = UIDropDownMenu_CreateInfo()
info.text = L["Whisper"]
info.checked = (Skada.db.profile.report.chantype == "whisper")
info.func = function() Skada.db.profile.report.channel = "Whisper"; Skada.db.profile.report.chantype = "whisper" end
UIDropDownMenu_AddButton(info, level)
info.text = L["Say"]
info.checked = (Skada.db.profile.report.channel == "Say")
info.func = function() Skada.db.profile.report.channel = "Say"; Skada.db.profile.report.chantype = "preset" end
UIDropDownMenu_AddButton(info, level)
info.text = L["Raid"]
info.checked = (Skada.db.profile.report.channel == "Raid")
info.func = function() Skada.db.profile.report.channel = "Raid"; Skada.db.profile.report.chantype = "preset" end
UIDropDownMenu_AddButton(info, level)
info.text = L["Party"]
info.checked = (Skada.db.profile.report.channel == "Party")
info.func = function() Skada.db.profile.report.channel = "Party"; Skada.db.profile.report.chantype = "preset" end
UIDropDownMenu_AddButton(info, level)
info.text = L["Instance"]
info.checked = (Skada.db.profile.report.channel == "INSTANCE_CHAT")
info.func = function() Skada.db.profile.report.channel = "INSTANCE_CHAT"; Skada.db.profile.report.chantype = "preset" end
UIDropDownMenu_AddButton(info, level)
info.text = L["Guild"]
info.checked = (Skada.db.profile.report.channel == "Guild")
info.func = function() Skada.db.profile.report.channel = "Guild"; Skada.db.profile.report.chantype = "preset" end
UIDropDownMenu_AddButton(info, level)
info.text = L["Officer"]
info.checked = (Skada.db.profile.report.channel == "Officer")
info.func = function() Skada.db.profile.report.channel = "Officer"; Skada.db.profile.report.chantype = "preset" end
UIDropDownMenu_AddButton(info, level)
info.text = L["Self"]
info.checked = (Skada.db.profile.report.chantype == "self")
info.func = function() Skada.db.profile.report.channel = "Self"; Skada.db.profile.report.chantype = "self" end
UIDropDownMenu_AddButton(info, level)
info.text = BATTLENET_OPTIONS_LABEL
info.checked = (Skada.db.profile.report.chantype == "bnet")
info.func = function() Skada.db.profile.report.channel = "bnet"; Skada.db.profile.report.chantype = "bnet" end
UIDropDownMenu_AddButton(info, level)
local list = {GetChannelList()}
for i=1,table.getn(list)/2 do
info.text = list[i*2]
info.checked = (Skada.db.profile.report.channel == list[i*2])
info.func = function() Skada.db.profile.report.channel = list[i*2]; Skada.db.profile.report.chantype = "channel" end
UIDropDownMenu_AddButton(info, level)
end
end
end
end
local x,y;
skadamenu.point, x, y = getDropdownPoint()
ToggleDropDownMenu(1, nil, skadamenu, "UIParent", x, y)
end
function Skada:SegmentMenu(window)
if not self.segmentsmenu then
self.segmentsmenu = CreateFrame("Frame", "SkadaWindowButtonsSegments")
end
local segmentsmenu = self.segmentsmenu
segmentsmenu.displayMode = "MENU"
segmentsmenu.initialize = function(self, level)
if not level then return end
local info = UIDropDownMenu_CreateInfo()
info.isTitle = 1
info.text = L["Segment"]
UIDropDownMenu_AddButton(info, level)
info = UIDropDownMenu_CreateInfo()
info.text = L["Total"]
info.func = function()
window.selectedset = "total"
Skada:Wipe()
Skada:UpdateDisplay(true)
end
info.checked = (window.selectedset == "total")
UIDropDownMenu_AddButton(info, level)
info = UIDropDownMenu_CreateInfo()
info.text = L["Current"]
info.func = function()
window.selectedset = "current"
Skada:Wipe()
Skada:UpdateDisplay(true)
end
info.checked = (window.selectedset == "current")
UIDropDownMenu_AddButton(info, level)
for i, set in ipairs(Skada:GetSets()) do
info = UIDropDownMenu_CreateInfo()
info.text = Skada:GetSetLabel(set)
info.func = function()
window.selectedset = i
Skada:Wipe()
Skada:UpdateDisplay(true)
end
info.checked = (window.selectedset == i)
UIDropDownMenu_AddButton(info, level)
end
end
local x,y;
segmentsmenu.point, x, y = getDropdownPoint()
ToggleDropDownMenu(1, nil, segmentsmenu, "UIParent", x, y)
end
function Skada:ModeMenu(window)
--Spew("window", window)
if not self.modesmenu then
self.modesmenu = CreateFrame("Frame", "SkadaWindowButtonsModes")
end
local modesmenu = self.modesmenu
modesmenu.displayMode = "MENU"
modesmenu.initialize = function(self, level)
if not level then return end
_modeMenu(window, level)
end
local x,y;
modesmenu.point, x, y = getDropdownPoint()
ToggleDropDownMenu(1, nil, modesmenu, "UIParent", x, y)
end
function Skada:OpenReportWindow(window)
if self.ReportWindow==nil then
self:CreateReportWindow(window)
end
--self:UpdateReportWindow()
self.ReportWindow:Show()
end
local function destroywindow()
if Skada.ReportWindow then
-- remove AceGUI hacks before recycling the widget
local frame = Skada.ReportWindow
frame.LayoutFinished = frame.orig_LayoutFinished
frame.frame:SetScript("OnKeyDown", nil)
frame.frame:EnableKeyboard(false)
frame.frame:SetPropagateKeyboardInput(false)
frame:ReleaseChildren()
frame:Release()
end
Skada.ReportWindow = nil
end
function Skada:CreateReportWindow(window)
-- ASDF = window
self.ReportWindow = AceGUI:Create("Window")
local frame = self.ReportWindow
frame:EnableResize(false)
frame:SetWidth(250)
frame:SetLayout("List")
frame:SetPoint("CENTER", UIParent, "CENTER", 0, 0)
frame.frame:SetClampedToScreen(true)
-- slight AceGUI hack to auto-set height of Window widget:
frame.orig_LayoutFinished = frame.LayoutFinished
frame.LayoutFinished = function(self, _, height) frame:SetHeight(height + 57) end
-- another AceGUI hack to hide on Escape:
frame.frame:SetScript("OnKeyDown", function(self,key)
if GetBindingFromClick(key) == "TOGGLEGAMEMENU" then
destroywindow()
end
end)
frame.frame:EnableKeyboard(true)
frame.frame:SetPropagateKeyboardInput(true)
if window then
frame:SetTitle(L["Report"] .. (" - %s"):format(window.db.name))
else
frame:SetTitle(L["Report"])
end
frame:SetCallback("OnClose", function(widget, callback) destroywindow() end)
if window then
Skada.db.profile.report.set = window.selectedset
Skada.db.profile.report.mode = window.db.mode
else
-- Mode, default last chosen or first available.
local modebox = AceGUI:Create("Dropdown")
modebox:SetLabel(L["Mode"])
modebox:SetList({})
for i, mode in ipairs(Skada:GetModes()) do
modebox:AddItem(mode:GetName(), mode:GetName())
end
modebox:SetCallback("OnValueChanged", function(f, e, value) Skada.db.profile.report.mode = value end)
modebox:SetValue(Skada.db.profile.report.mode or Skada:GetModes()[1])
frame:AddChild(modebox)
-- Segment, default last chosen or last set.
local setbox = AceGUI:Create("Dropdown")
setbox:SetLabel(L["Segment"])
setbox:SetList({total = L["Total"], current = L["Current"]})
for i, set in ipairs(Skada:GetSets()) do
setbox:AddItem(i, (Skada:GetSetLabel(set)))
end
setbox:SetCallback("OnValueChanged", function(f, e, value) Skada.db.profile.report.set = value end)
setbox:SetValue(Skada.db.profile.report.set or Skada:GetSets()[1])
frame:AddChild(setbox)
end
local channellist = {
whisper = { L["Whisper"], "whisper", true},
target = { L["Whisper Target"], "whisper"},
say = { L["Say"], "preset"},
raid = { L["Raid"], "preset"},
party = { L["Party"], "preset"},
instance_chat = { L["Instance"], "preset"},
guild = { L["Guild"], "preset"},
officer = { L["Officer"], "preset"},
self = { L["Self"], "self"},
bnet = { BATTLENET_OPTIONS_LABEL, "bnet", true},
}
local list = {GetChannelList()}
for i=1,#list/2 do
local chan = list[i*2]
if chan ~= "Trade" and chan ~= "General" and chan ~= "LookingForGroup" then -- These should be localized.
channellist[chan] = {chan, "channel"}
end
end
-- Channel, default last chosen or Say.
local channelbox = AceGUI:Create("Dropdown")
channelbox:SetLabel(L["Channel"])
channelbox:SetList( {} )
for chan, kind in pairs(channellist) do
channelbox:AddItem(chan, kind[1])
end
local origchan = Skada.db.profile.report.channel or "say"
if not channellist[origchan] then origchan = "say" end -- ticket 455: upgrading old settings
channelbox:SetValue(origchan)
channelbox:SetCallback("OnValueChanged", function(f, e, value)
Skada.db.profile.report.channel = value
Skada.db.profile.report.chantype = channellist[value][2]
if channellist[origchan][3] ~= channellist[value][3] then
-- redraw in-place to add/remove whisper widget
local pos = { frame:GetPoint() }
destroywindow()
Skada:CreateReportWindow(window)
Skada.ReportWindow:SetPoint(unpack(pos))
end
end)
frame:AddChild(channelbox)
local lines = AceGUI:Create("Slider")
lines:SetLabel(L["Lines"])
lines:SetValue(Skada.db.profile.report.number ~= nil and Skada.db.profile.report.number or 10)
lines:SetSliderValues(1, 25, 1)
lines:SetCallback("OnValueChanged", function(self, event, value) Skada.db.profile.report.number = value end)
lines:SetFullWidth(true)
frame:AddChild(lines)
if channellist[origchan][3] then
local whisperbox = AceGUI:Create("EditBox")
whisperbox:SetLabel(L["Whisper Target"])
whisperbox:SetText(Skada.db.profile.report.target or "")
whisperbox:SetCallback("OnEnterPressed", function(box, event, text)
if strlenutf8(text) == #text then -- remove spaces which are always non-meaningful and can sometimes cause problems
local ntext = text:gsub("%s","")
if ntext ~= text then
text = ntext
whisperbox:SetText(text)
end
end
Skada.db.profile.report.target = text;
frame.button.frame:Click()
end)
whisperbox:SetCallback("OnTextChanged", function(box, event, text) Skada.db.profile.report.target = text end)
whisperbox:SetFullWidth(true)
frame:AddChild(whisperbox)
end
local report = AceGUI:Create("Button")
frame.button = report
report:SetText(L["Report"])
report:SetCallback("OnClick", function()
local mode, set, channel, chantype, number = Skada.db.profile.report.mode, Skada.db.profile.report.set, Skada.db.profile.report.channel, Skada.db.profile.report.chantype, Skada.db.profile.report.number
if channel == "whisper" then
channel = Skada.db.profile.report.target
if channel and #strtrim(channel) == 0 then
channel = nil
end
elseif channel == "bnet" then
channel = BNet_GetBNetIDAccount(Skada.db.profile.report.target)
elseif channel == "target" then
if UnitExists("target") then
local toon, realm = UnitName("target")
if realm and #realm > 0 then
channel = toon .. "-" .. realm
else
channel = toon
end
else
channel = nil
end
end
-- print(tostring(frame.channel), tostring(frame.chantype), tostring(window.db.mode))
if channel and chantype and mode and set and number then
Skada:Report(channel, chantype, mode, set, number, window)
frame:Hide()
else
Skada:Print("Error: Whisper target not found")
end
end)
report:SetFullWidth(true)
frame:AddChild(report)
end
|
id = 'V-38542'
severity = 'medium'
weight = 10.0
title = 'The system must use a reverse-path filter for IPv4 network traffic when possible on all interfaces.'
description = 'Enabling reverse path filtering drops packets with source addresses that should not have been able to be received on the interface they were received on. It should not be used on systems which are routers for complicated networks, but is helpful for end hosts and routers serving small networks.'
fixtext = [==[To set the runtime status of the "net.ipv4.conf.all.rp_filter" kernel parameter, run the following command:
# sysctl -w net.ipv4.conf.all.rp_filter=1
If this is not the system's default value, add the following line to "/etc/sysctl.conf":
net.ipv4.conf.all.rp_filter = 1]==]
checktext = [=[The status of the "net.ipv4.conf.all.rp_filter" kernel parameter can be queried by running the following command:
$ sysctl net.ipv4.conf.all.rp_filter
The output of the command should indicate a value of "1". If this value is not the default value, investigate how it could have been adjusted at runtime, and verify it is not set improperly in "/etc/sysctl.conf".
$ grep net.ipv4.conf.all.rp_filter /etc/sysctl.conf
If the correct value is not returned, this is a finding.]=]
function test()
end
function fix()
end
|
{
vertex = {
uniformBuffers = {
matrices = {
wvp = "mat4"
}
},
inputs = {
sl_Position = "vec4",
sl_TexCoord = "vec2"
},
outputs = {
uv = "vec2"
},
code = [[
void main()
{
gl_Position = #matrices:wvp# * sl_Position;
uv = sl_TexCoord;
SL_FIX_Y#gl_Position#;
}
]]
},
fragment = {
samplers = {
mainTex = "sampler2D"
},
outputs = {
fragColor = { type = "vec4", target = 0 }
},
code = [[
void main()
{
vec4 c = texture(mainTex, uv);
fragColor = vec4(c.r, c.r, c.r, c.r);
}
]]
}
} |
workspace "Feijoa"
architecture "x86_64"
startproject "Sellowiana"
configurations
{
"Debug",
"Release",
"Dist"
}
outputdir = "%{cfg.buildcfg}-%{cfg.system}-%{cfg.architecture}"
-- Include directories relative to root folder (solution directory)
IncludeDir = {}
IncludeDir["GLFW"] = "%{wks.location}/Feijoa/vendor/GLFW/include"
IncludeDir["Glad"] = "%{wks.location}/Feijoa/vendor/Glad/include"
IncludeDir["ImGui"] = "%{wks.location}/Feijoa/vendor/imgui"
IncludeDir["glm"] = "%{wks.location}/Feijoa/vendor/glm"
IncludeDir["stb_image"] = "%{wks.location}/Feijoa/vendor/stb_image"
IncludeDir["entt"] = "%{wks.location}/Feijoa/vendor/entt/include"
IncludeDir["yaml_cpp"] = "%{wks.location}/Feijoa/vendor/yaml-cpp/include"
IncludeDir["ImGuizmo"] = "%{wks.location}/Feijoa/vendor/ImGuizmo"
group "Dependencies"
include "Feijoa/vendor/GLFW"
include "Feijoa/vendor/Glad"
include "Feijoa/vendor/imgui"
include "Feijoa/vendor/yaml-cpp"
group ""
include "Feijoa"
include "Sandbox"
include "Sellowiana" |
local ABOUT = {
NAME = "openLuup.userdata",
VERSION = "2020.03.31",
DESCRIPTION = "user_data saving and loading, plus utility functions used by HTTP requests",
AUTHOR = "@akbooer",
COPYRIGHT = "(c) 2013-2020 AKBooer",
DOCUMENTATION = "https://github.com/akbooer/openLuup/tree/master/Documentation",
DEBUG = false,
LICENSE = [[
Copyright 2013-2020 AK Booer
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]]
}
-- user_data
-- saving and loading, plus utility functions used by HTTP requests id=user_data, etc.
-- 2016.05.09 return length of user_data.json file on successful save
-- 2016.05.12 moved load_user_data to this module from init
-- 2016.05.15 use InstalledPlugins2 list
-- 2016.05.21 handle empty InstalledPlugins2 in user_data file on loading
-- 2016.05.22 ignore table structure in writing user_data attributes
-- 2016.05.24 update InstalledPlugins2 list
-- 2016.06.06 fix load error if missing openLuup structure (upgrading from old version)
-- 2016.06.08 add pre-defined startup code for new systems
-- 2016.06.22 add metadata routine for plugin install
-- 2016.06.24 remove defaults from pre-installed repository data (always use "master"
-- 2016.06.28 change install parameters for VeraBridge (device and icon file locations)
-- 2016.06.30 split save into two functions: json & save to allow data compression
-- 2016.08.29 update plugin versions on load
-- 2016.11.05 added gmt_offset: thanks @jswim788 and @logread
-- 2016.11.09 preserve device #2 (openLuup) room allocation across reloads (thanks @DesT)
-- 2017.01.18 add HouseMode variable to openLuup device, to mirror attribute, so this can be used as a trigger
-- 2017.04.19 sort devices_table() output (thanks @a-lurker)
-- 2017.07.19 ignore temporary "high numbered" scenes (VeraBridge)
-- 2017.08.27 fix non-numeric device ids in save_user_data()
-- ...allows renumbering of device ids using luup.attr_set()
-- ... see: http://forum.micasaverde.com/index.php/topic,50428.0.html
-- 2018.03.02 remove TODO for mode change attributes
-- 2018.03.24 use luup.rooms.create metatable method
-- 2018.04.05 do not create status as a device attribute when loading user_data
-- 2018.04.23 update_plugin_versions additions for ALT... plugins and MySensors
-- 2018.05.25 restore openLuup variables on reload (for history)
-- 2018.05.29 fix several possibly numeric attributes
-- 2018.05.29 added device (sub)category (thanks @rafale77)
-- 2018.06.26 remove DataYour from default plugins list
-- 2019.02.02 add device file manufacturer and model name (thanks @rigpapa)
-- 2019.03.18 change default currency to GBP
-- 2019.04.04 remove outdated preinstalled plugin metadata
-- 2019.04.18 fix AltAppStore showing wrong version number on Plugins page
-- 2019.05.03 don't load device attribute cpu(s)
-- 2019.05.12 use device:state_table() in devices_table()
-- 2019.05.31 update openLuup help URL to new Vera community forum
-- 2019.08.25 use local .svg icons for openLuup, AltAppStore, and VeraBridge plugins
-- 2019.10.19 add modelID attribute, per latest Vera firmware (7.30)
-- 2019.11.28 add openLuup table to saved user_data (for continuity of parameter settings between reloads)
-- 2020.01.28 replace scene:user_table() with scene.definition, following object changes in scenes
-- 2020.03.03 update ZWay implementation file to I_ZWay2.xml
-- 2020.03.31 improve plugin loading and ordering
local json = require "openLuup.json"
local logs = require "openLuup.logs"
local scenes = require "openLuup.scenes"
local chdev = require "openLuup.chdev"
local timers = require "openLuup.timers" -- for gmt_offset
local lfs = require "lfs"
-- local _log() and _debug()
local _log, _debug = logs.register (ABOUT)
--
-- Here a complete list of top-level (scalar) attributes taken from an actual Vera user_data2 request
-- the commented out items are either vital tables, or useless parameters.
local attributes = {
-- AltEventServer = "127.0.0.1",
-- AutomationDevices = 0,
BuildVersion = "*1.7.0*",
City_description = "Greenwich",
Country_description = "UNITED KINGDOM",
-- DataVersion = 563952001,
-- DataVersion_Static = "32",
-- DeviceSync = "1426564006",
Device_Num_Next = "1",
-- ExtraLuaFiles = {},
-- InstalledPlugins = {},
-- InstalledPlugins2 = {},
KwhPrice = "0.15",
LoadTime = os.time(),
Mode = "1", -- House Mode
ModeSetting = "1:DC*;2:DC*;3:DC*;4:DC*", -- see: http://wiki.micasaverde.com/index.php/House_Modes
PK_AccessPoint = "88800000", -- TODO: pick up machine serial number from EPROM or such like,
-- PluginSettings = {},
-- PluginsSynced = "0",
-- RA_Server = "vera-us-oem-relay41.mios.com",
-- RA_Server_Back = "vera-us-oem-relay11.mios.com",
Region_description = "England",
-- ServerBackup = "1",
-- Server_Device = "vera-us-oem-device12.mios.com",
-- Server_Device_Alt = "vera-us-oem-device11.mios.com",
-- SetupDevices = {},
-- ShowIndividualJobs = 0,
StartupCode = [[
-- You can personalise the installation by changing these attributes,
-- which are persistent and may be removed from the Startup after a reload.
local attr = luup.attr_set
-- Geographical location
attr ("City_description", "Greenwich")
attr ("Country_description", "UNITED KINGDOM")
attr ("Region_description", "England")
attr ("latitude", "51.48")
attr ("longitude", "0.0")
-- other parameters
attr ("TemperatureFormat", "C")
attr ("PK_AccessPoint", "88800000")
attr ("currency", "£")
attr ("date_format", "dd/mm/yy")
attr ("model", "Not a Vera")
attr ("timeFormat", "24hr")
-- Any other startup processing may be inserted here...
luup.log "startup code completed"
]]
,
-- SvnVersion = "*13875*",
TemperatureFormat = "C",
-- UnassignedDevices = 0,
-- Using_2G = 0,
-- breach_delay = "30",
-- category_filter = {},
currency = "GBP",
date_format = "dd/mm/yy",
-- device_sync = "1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,18,19,20,21",
-- devices = {},
-- energy_dev_log = "41,",
-- firmware_version = "1",
gmt_offset = tostring (timers.gmt_offset()), -- see: http://forum.micasaverde.com/index.php/topic,40035.0.html
-- ip_requests = {},
-- ir = 0,
latitude = "51.48",
-- local_udn = "uuid:4d494342-5342-5645-0000-000002b03069",
longitude = "0.0",
mode_change_delay = "30",
mode_change_mode = '',
mode_change_time = '',
model = "Not a Vera",
modelID = 0,
-- net_pnp = "0",
-- overview_tabs = {},
-- rooms = {},
-- scenes = {},
-- sections = {},
-- setup_wizard_finished = "1",
-- shouldHelpOverlayBeHidden = true,
skin = "AltUI", -- was "mios",
-- static_data = {},
-- sync_kit = "0000-00-00 00:00:00",
timeFormat = "24hr",
timezone = "0", -- apparently not used, and always "0",
-- see: http://forum.micasaverde.com/index.php/topic,10276.msg70562.html#msg70562
-- users = {},
-- weatherSettings = {
-- weatherCountry = "UNITED KINGDOM",
-- weatherCity = "Oxford England",
-- tempFormat = "C" },
-- zwave_heal = "1426331082",
-- openLuup specials
ShutdownCode = '',
LuaTestCode = '', -- 2019.06.11
LuaTestCode2 = '',
LuaTestCode3 = '',
}
-------
--
-- pre-installed plugins
--
local preinstalled = {
openLuup =
{
AllowMultiple = "0",
Title = "openLuup",
Icon = "https://avatars.githubusercontent.com/u/4962913", -- AltUI seems to need HTTPS
Instructions = "https://community.getvera.com/c/plugins-and-plugin-development/openluup",
AutoUpdate = "0",
VersionMajor = '',
VersionMinor = "baseline.",
id = "openLuup",
timestamp = os.time(),
Files = (function () -- generate this list dynamically
local F = {}
for f in lfs.dir "openLuup/" do
if f: match "^.+%..+$" then F[#F+1] = {SourceName = f} end
end
return F
end) (),
Devices = {}, -- no devices to install!!
Repository = {
type = "GitHub",
source = "akbooer/openLuup", -- the openLuup repository
target = "./openLuup/", -- not /etc/cmh-ludl/, like everything else
pattern = ".+%.lua$", -- pattern match string for required files
folders = {"/openLuup"}, -- these are the bits of the repository that we want
},
},
AltAppStore =
{
AllowMultiple = "0",
Title = "Alternate App Store",
Icon = "https://raw.githubusercontent.com/akbooer/AltAppStore/master/AltAppStore.png",
Instructions = "https://github.com/akbooer/AltAppStore",
AutoUpdate = "0",
VersionMajor = '',
VersionMinor = "baseline.",
id = "AltAppStore",
timestamp = os.time(),
Files = { -- it's part of the openLuup baseline
{SourceName = "L_AltAppStore.lua"}, -- this is a physical file in ./openLuup/
},
Devices = {
{
DeviceFileName = "D_AltAppStore.xml",
DeviceType = "urn:schemas-upnp-org:device:AltAppStore:1",
ImplFile = "I_AltAppStore.xml",
Invisible = "0",
},
},
Repository = {
type = "GitHub",
source = "akbooer/openLuup", -- get this from openLuup, NOT from AltAppStore...
folders = {"/openLuup"}, -- these are the bits of the repository that we want
target = "./openLuup/", -- ...and put it back INTO ./openLuup/ folder
pattern = "L_AltAppStore", -- only .lua file (others are in virtualfilesystem)
},
},
VeraBridge =
{
AllowMultiple = "1",
Title = "VeraBridge",
Icon = "https://raw.githubusercontent.com/akbooer/openLuup/master/icons/VeraBridge.png",
Instructions = "http://forum.micasaverde.com/index.php/board,79.0.html",
AutoUpdate = "0",
VersionMajor = "not",
VersionMinor = "installed",
id = "VeraBridge",
timestamp = os.time(),
Files = {
{SourceName = "L_VeraBridge.lua"}, -- this is a physical file in ./openLuup/
},
Devices = {
{
DeviceFileName = "D_VeraBridge.xml",
DeviceType = "VeraBridge",
ImplFile = "I_VeraBridge.xml",
Invisible = "0",
},
},
Repository = {
type = "GitHub",
source = "akbooer/openLuup", -- actually comes from the openLuup repository
target = "./openLuup/", -- ...and put it back INTO ./openLuup/ folder
pattern = "L_VeraBridge", -- only .lua file (others are in virtualfilesystem)
folders = {"/openLuup"}, -- these are the bits of the repository that we want
},
},
AltUI =
{
AllowMultiple = "0",
Title = "Alternate UI",
Icon = "plugins/icons/8246.png", -- usage: http://apps.mios.com/icons/8246.png
Instructions = "http://forum.micasaverde.com/index.php/board,78.0.html",
AutoUpdate = "1", -- not really "auto", but will prompt on browser refresh
VersionMajor = "not",
VersionMinor = "installed",
id = 8246, -- this is the genuine MiOS plugin number
timestamp = os.time(),
Files = {}, -- populated on download from repository
Devices = {
{
DeviceFileName = "D_ALTUI.xml",
DeviceType = "urn:schemas-upnp-org:device:altui:1",
ImplFile = "I_ALTUI.xml",
Invisible = "0",
-- CategoryNum = "1"
},
},
Repository = {
type = "GitHub",
source = "amg0/ALTUI", -- @amg0 repository
pattern = "ALTUI", -- pattern match string for required files
folders = { -- these are the bits of the repository that we want
'', -- the main folder
"/blockly", -- and blocky editor
},
},
},
MySensors =
{
AllowMultiple = "1",
Title = "MySensors",
Icon = "https://www.mysensors.org/icon/MySensors.png",
Instructions = "https://github.com/mysensors/Vera/tree/UI7",
AutoUpdate = "0",
VersionMajor = "not",
VersionMinor = "installed",
id = "Arduino",
timestamp = os.time(),
Files = {},
Devices = {
{
DeviceFileName = "D_Arduino1.xml",
DeviceType = "urn:schemas-arduino-cc:device:arduino:1",
ImplFile = "I_Arduino1.xml",
Invisible = "0",
},
},
Repository = {
type = "GitHub",
source = "mysensors/Vera",
pattern = "[DILS]_Arduino%w*%.%w+", -- pattern match string for required files
},
},
ZWay =
{
AllowMultiple = "1",
Title = "Z-Way",
Icon = "https://raw.githubusercontent.com/akbooer/Z-Way/master/icons/Z-Wave.me.png",
Instructions = "",
AutoUpdate = "0",
VersionMajor = "not",
VersionMinor = "installed",
id = "Z-Way",
timestamp = os.time(),
Files = {},
Devices = {
{
DeviceFileName = "D_ZWay.xml",
DeviceType = "urn:akbooer-com:device:ZWay:1",
ImplFile = "I_ZWay2.xml",
Invisible = "0",
},
},
Repository = {
type = "GitHub",
source = "akbooer/Z-Way",
-- pattern = "",
},
},
} -- end of preinstalled plugins
local default_plugins = {
preinstalled.openLuup,
preinstalled.AltAppStore,
preinstalled.VeraBridge,
preinstalled.AltUI,
preinstalled.ZWay,
preinstalled.MySensors,
}
--
-- PLUGINS
--
-- given plugin list, generate index by ID
local function plugin_index (plugins)
local index = {}
for i,p in ipairs (plugins) do
index[tostring (p.id)] = i
end
return index
end
-- find the requested plugin data, and index in structure
local function find_installed_data (plugin)
plugin = tostring(plugin)
local installed = luup.attr_get "InstalledPlugins2" or {}
local info, idx
for i,p in ipairs (installed) do
local id = tostring (p.id)
if id == plugin then
info, idx = p, i
break
end
end
return info, idx
end
-- build update_plugin metadata from InstalledPlugins2 structure
local function plugin_metadata (id, tag)
local IP = find_installed_data (id) -- get the named InstalledPlugins2 metadata
if IP then
local r = IP.Repository
local major = r.type or "GitHub"
tag = tag or "master"
r.versions = {[tag] = {release = tag}}
local plugin = {}
for a,b in pairs (IP) do
if type(b) ~= "table" then plugin[a] = b end -- copy all the scalar data
end
return { -- reformat for update_plugin request
devices = IP.Devices,
plugin = plugin,
repository = IP.Repository,
version = {major = major, minor = tag},
versionid = tag,
}
end
return nil, table.concat {"metadata for'", id or '?', "' not found"}
end
-- go through the devices to see if any advertise their versions
local function update_plugin_versions (installed)
-- index by plugin id and device type
local index_by_plug = plugin_index (installed)
local index_by_type = {}
for i,p in ipairs (installed) do
local id
if p.Devices and p.Devices[1] then
id = p.Devices[1].DeviceType
end
if id then index_by_type[tostring(id)] = i end
end
-- go through LOCAL devices looking for clues about their version numbers
for _, d in pairs (luup.devices or {}) do
local i = index_by_plug[d.attributes.plugin] or index_by_type[d.device_type]
local a = (d.environment or {}).ABOUT
local IP = installed[i]
local parent = d.device_num_parent
if IP and (parent == 0 or parent == 2) then -- LOCAL devices only! (incl. children of openLuup)
if i and a then -- plugins with ABOUT.VERSION
local v1,v2,v3,prerelease = (a.VERSION or ''): match "(%d+)%D+(%d+)%D*(%d*)(%S*)"
if v3 then
IP.VersionMajor = v1 % 2000
if v3 == '' then
IP.VersionMinor = tonumber(v2)
else
IP.VersionMinor = table.concat ({tonumber(v2),tonumber(v3)}, '.') .. prerelease
end
end
else -- it gets harder, so go through variables... example syntax
local known = {
["urn:upnp-org:serviceId:altui1"] = "Version", --v2.15
["urn:upnp-org:serviceId:althue1"] = "Version", --v0.94
["urn:upnp-arduino-cc:serviceId:arduino1"] = "PluginVersion", -- 1.4
}
for _,v in ipairs (d.variables) do -- (v.srv, v.name, v.value, ...)
local name = known[v.srv]
if name == v.name then
IP.VersionMajor = v.value: match "v?(.*)" -- remove leading 'v', if present
IP.VersionMinor = '' -- TODO: some refinement possible here with other variables?
break
end
end
end
end
end
end
--
-- LOAD and SAVE
--
-- load user_data (persistence for attributes, rooms, devices and scenes)
local function load_user_data (user_data_json)
_log "loading user_data json..."
local user_data, msg = json.decode (user_data_json)
if msg then
_log (msg)
else
-- ATTRIBUTES
local attr = attributes or {}
for a,b in pairs (attr) do -- go through the template for names to restore
if type(b) ~= "table" then
luup.attr_set (a, user_data[a] or b) -- use saved value or default
-- note that attr_set also handles the "special" attributes which are mirrored in luup.XXX
end
end
-- ROOMS
_log "loading rooms..."
for _,x in pairs (user_data.rooms or {}) do
luup.rooms.create (x.name, x.id) -- 2018.03.24 use luup.rooms.create metatable method
_log (("room#%d '%s'"): format (x.id,x.name))
end
_log "...room loading completed"
-- DEVICES
_log "loading devices..."
for _, d in ipairs (user_data.devices or {}) do
if d.id == 2 then
-- device #2 is special (it's the openLuup plugin, and already exists)
local ol = luup.devices[2]
local room = tonumber (d.room) or 0
ol:attr_set {room = room} -- set the device attribute...
ol.room_num = room -- ... AND the device table (Luup is SO bad...)
-- 2018.05.25 restore openLuup variables
for _,v in ipairs ((d.states) or {}) do
ol: variable_set (v.service, v.variable, v.value)
end
-- 2017.01.18 create openLuup HouseMode variable
ol:variable_set ("openLuup", "HouseMode", luup.attr_get "Mode")
-- 2019.06.06 add the bookmark attribute
ol: attr_set ("bookmark", d.bookmark)
else
local dev = chdev.create { -- the variation in naming within luup is appalling
devNo = d.id,
device_type = d.device_type,
internal_id = d.altid,
description = d.name,
upnp_file = d.device_file,
upnp_impl = d.impl_file or '',
json_file = d.device_json or '',
ip = d.ip,
mac = d.mac,
hidden = nil,
invisible = d.invisible == "1",
manufacturer = d.manufacturer, -- 2019.02.02
model = d.model, -- 2019.02.02
parent = d.id_parent,
room = tonumber (d.room),
pluginnum = d.plugin,
statevariables = d.states, -- states : table {id, service, variable, value}
disabled = d.disabled,
username = d.username,
password = d.password,
-- 2018.05.29 added device (sub)category
category_num = d.category_num,
subcategory_num = d.subcategory_num,
}
dev:attr_set ("time_created", d.time_created) -- set time_created to original, not current
-- set other device attributes (including category_num and subcategory_num)
for a,v in pairs (d) do
if type(v) ~= "table" and not dev.attributes[a] then
-- 2018.04.05 status is NOT a device ATTRIBUTE
-- 2019.05.03 cpu(s) should not be created here either!
if not (a == "status" or a == "cpu(s)") then
dev:attr_set (a, v)
end
end
end
luup.devices[d.id] = dev -- save it
end
end
-- SCENES
_log "loading scenes..."
local Nscn = 0
for _, scene in ipairs (user_data.scenes or {}) do
if tonumber(scene.id) < 1e5 then -- 2017.0719 ignore temporary "high numbered" scenes (VeraBridge)
local new, msg = scenes.create (scene)
if new and scene.id then
Nscn = Nscn + 1
luup.scenes[scene.id] = new
_log (("[%s] %s"): format (scene.id or '?', scene.name))
else
_log (table.concat {"error in scene id ", scene.id or '?', ": ", msg or "unknown error"})
end
end
end
_log ("number of scenes = " .. Nscn)
for i,n in ipairs (luup.scenes) do _log (("scene#%d '%s'"):format (i,n.description)) end
_log "...scene loading completed"
-- PLUGINS
_log "loading installed plugin info..."
-- local installed = user_data.InstalledPlugins2 or {}
local installed = {}
for i,p in ipairs (default_plugins) do installed[i] = p end -- initialize installed plugins
local index = plugin_index (installed)
-- add others
local protected = {openLuup = true, AltAppStore = true, VeraBridge = true} -- don't mess with these
for _, plugin in ipairs (user_data.InstalledPlugins2 or {}) do
local existing = index[tostring(plugin.id)]
if existing then
if not protected[plugin.id] then
installed[existing] = plugin -- replace any existing, unprotected, plugin data
end
else
installed[#installed+1] = plugin -- add any missing
end
end
update_plugin_versions (installed)
attr.InstalledPlugins2 = installed
-- log the full list of installed plugins
for _, plugin in ipairs (installed) do
local version = table.concat {plugin.VersionMajor or '?', '.', plugin.VersionMinor or '?'}
local ver = "[%s] %s (%s)"
_log (ver: format (plugin.id, plugin.Title, version))
end
end
_log "...user_data loading completed"
return not msg, msg
end
--
-- user_data devices table
local function devices_table (device_list)
local info = {}
local serviceNo = 0
local devs = {}
for d in pairs (device_list) do devs[#devs+1] = d end -- 2017.04.19
table.sort (devs)
for _,dnum in ipairs (devs) do
local d = device_list[dnum]
local states = d: state_table() -- 2019.05.12
-- local states = {}
-- for i,item in ipairs(d.variables) do
-- states[i] = {
-- id = item.id,
-- service = item.srv,
-- variable = item.name,
-- value = item.value or '',
-- }
-- end
local curls
if d.serviceList then -- add the ControlURLs
curls = {}
for _,x in ipairs (d.serviceList) do
serviceNo = serviceNo + 1
curls["service_" .. serviceNo] = {
service = x.serviceId,
serviceType = x.serviceType,
ControlURL = "upnp/control/dev_" .. serviceNo,
EventURL = "/upnp/event/dev_" .. serviceNo,
}
end
end
local status = d:status_get() or -1 -- 2016.04.29
local tbl = {
ControlURLs = curls,
states = states,
status = status,
}
for a,b in pairs (d.attributes) do tbl[a] = b end
-- 2017.08.27 fix for non-numeric device id
-- 2018.05.29 fix several possibly numeric attributes
local numbers = {"id", "category_num", "subcategory_num"}
for _,name in ipairs (numbers) do
tbl[name] = tonumber(tbl[name]) or tbl[name] -- force numeric value, if possible
end
info[#info+1] = tbl
end
return info
end
-- json ()
-- top-level attributes and key tables: devices, rooms, scenes
local function json_user_data (localLuup) -- refactored thanks to @explorer
local luup = localLuup or luup
local data = {rooms = {}, scenes = {}}
-- scalar attributes
for a,b in pairs (attributes) do
if type(b) ~= "table" then data[a] = b end
end
-- openLuup table attribute
data.openLuup = attributes.openLuup -- 2019.11.28
-- devices
data.devices = devices_table (luup.devices or {})
-- plugins
data.InstalledPlugins2 = attributes.InstalledPlugins2 or default_plugins -- 2016.05.15 and 2016.05.30
-- rooms
local rooms = data.rooms
for i, name in pairs (luup.rooms or {}) do
rooms[#rooms+1] = {id = i, name = name}
end
-- scenes
local scenes = data.scenes
for _, s in pairs (luup.scenes or {}) do
scenes[#scenes+1] = s.definition
end
--
return json.encode (data) -- json text or nil, error message if any
end
-- save ()
local function save_user_data (localLuup, filename) -- refactored thanks to @explorer
local result, message
local j, msg = json_user_data (localLuup)
if not j then
message = "syntax error in user_data: " .. (msg or '?')
else
local f, err = io.open (filename or "user_data.json", 'w')
if not f then
message = "error writing user_data: " .. (err or '?')
else
f:write (j)
f:write '\n'
f:close ()
result = #j -- 2016.05.09 return length of user_data.json file
end
end
return result, message
end
return {
ABOUT = ABOUT,
attributes = attributes,
default_plugins = default_plugins,
preinstalled = preinstalled,
-- methods
devices_table = devices_table,
plugin_metadata = plugin_metadata,
find_installed_data = find_installed_data,
update_plugin_versions = update_plugin_versions,
json = json_user_data,
load = load_user_data,
save = save_user_data,
}
|
-- This script is for whatever I need to test in the moment
print("Hi from test script")
print(nbt[1].tagType)
|
object_tangible_collection_rare_pistol_jawa_ion = object_tangible_collection_shared_rare_pistol_jawa_ion:new {
gameObjectType = 8211,}
ObjectTemplates:addTemplate(object_tangible_collection_rare_pistol_jawa_ion, "object/tangible/collection/rare_pistol_jawa_ion.iff") |
local function encode(opcode, payload)
local len = #payload
local frame = {}
frame[#frame + 1] =
string.char(bit.bor(0x80, opcode), bit.bor((len < 126) and len or ((len < 0x10000) and 126 or 127)))
if len >= 0x10000 then
frame[#frame + 1] =
string.char(0, 0, 0, 0, -- 32 bit length is plenty, assume zero for rest
bit.band(bit.rshift(len, 24), 0xff),
bit.band(bit.rshift(len, 16), 0xff),
bit.band(bit.rshift(len, 8), 0xff),
bit.band(len, 0xff)
)
elseif len >= 126 then
frame[#frame + 1] = string.char(bit.band(bit.rshift(len, 8), 0xff), bit.band(len, 0xff))
end
frame[#frame + 1] = payload
return table.concat(frame)
end
return function(sck, request)
local opcodes = {[0] = "Continuation", [1] = "Text", [2] = "binary", [8] = "Close", [9] = "Ping", [10] = "Pong"}
local closingHandshake = false
local statusCode = nil
local txBufferContent = 0 -- keep track of transmit buffer content so we close the connection only AFTER everything was sent.
local function sendSensorData(local_conn)
if sensor:isPresent() then
local ax, ay, az, temperature, gx, gy, gz = sensor:readAll()
-- create json string
data =
string.format(
'{"ax":%f,"ay":%f,"az":%f,"gx":%f,"gy":%f,"gz":%f,"utc":%u,"temp":%f,"timestamp":%u}',
ax,
ay,
az,
gx,
gy,
gz,
rtctime.get(),
temperature,
tmr.now()
)
local_conn:send(encode(0x01, data)) -- send as "Text" (0x01)
txBufferContent = txBufferContent + 1
end
end
-- callback upon completion of current response
local function ws_sent(local_conn)
txBufferContent = (txBufferContent > 0) and (txBufferContent - 1) or 0
if closingHandshake then
if txBufferContent == 0 then
print("[ws] - closing")
local_conn:close()
maxThreads = maxThreads + 1
gpio.write(0, 0) -- turn LED on
end
elseif txBufferContent == 0 then
sendSensorData(local_conn)
end
end
local function ws_receive(local_conn, data)
local temp = {}
local payload = nil
for i = 1, #data do
temp[#temp + 1] = string.format("%X ", string.byte(data, i))
end
print("[ws] - received: " .. table.concat(temp))
local opcode = bit.band(string.byte(data, 1), 0x0f)
print("[ws] - Opcode: " .. opcodes[opcode])
local payloadLen = bit.band(string.byte(data, 2), 0x0f)
if payloadLen == 126 then
payloadLen = string.byte(data, 3) * 256 + string.byte(data, 4)
elseif payloadLen == 127 then
payloadLen = 0x10000 -- FIXME: needs implementation
end
print("[ws] - payloadLen=", payloadLen)
-- connection is about to be closed (either client or server initiated)
if opcode == 0x08 then
if closingHandshake then
print("[ws] - closingHandshake done - close")
local_conn:close()
else
closingHandshake = true
print("[ws] - closingHandshake return")
--statusCode = 1001
local_conn:send(
encode(0x08, "")
--string.char(bit.band(bit.rshift(statusCode, 8), 0xff), bit.band(statusCode, 0xff)))
)
txBufferContent = txBufferContent + 1
end
end
end
-- client closed the connection
local function ws_disconnect(local_conn)
print("[ws] - closed")
maxThreads = maxThreads + 1
gpio.write(0, 0) -- turn LED on
end
-- (un)register websocket callbacks
sck:on("sent", ws_sent)
sck:on("disconnection", ws_disconnect)
sck:on("receive", ws_receive)
-- compute response challenge as per rfc6455#section-1.3
local key = request:match("Sec%-WebSocket%-Key: ([A-Za-z0-9+/=]+)")
local accept = crypto.toBase64(crypto.hash("sha1", key .. "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"))
-- delete unused webserver callback functions
on_sent = nil
on_receive = nil
dofile("webserver-header.lc")(
sck,
101,
nil,
false,
{"Sec-WebSocket-Accept: " .. accept, "Upgrade: websocket", "Connection: Upgrade"},
false
)
print("[ws] - open")
txBufferContent = txBufferContent + 1
return true
end
|
AddCSLuaFile("cl_init.lua")
AddCSLuaFile("shared.lua")
include("shared.lua")
function ENT:Initialize()
self:SetModel("models/props_combine/combine_teleportplatform.mdl")
self:SetSolid(SOLID_BBOX)
self:SetUseType(SIMPLE_USE)
end
function ENT:Use(acticator, caller)
caller:SetPos(Vector(-1859, -981, 32))
caller.on_planet = false
end
|
local openLevel = require "config.openLevel"
local HeroLevelup = require "hero.HeroLevelup"
local guideShaar = {}
function guideShaar:Start()
self:initData()
self:initUi()
end
function guideShaar:initData()
self.quest = module.QuestModule.Get(module.guideLayerModule.Type.LevelUp)
self.flag = true
end
function guideShaar:Update()
self:upOverTime()
end
function guideShaar:upOverTime()
if self.view.root.ScrollView.Viewport.Content.item1.activite.Text then
if self.quest then
local _time = (self.quest.end_time - 1) * 86400
local _off = (module.playerModule.Get().create_time + _time) - module.Time.now()
local _day = math.floor(_off / 86400)
local _hour = math.floor((_off - _day * 86400) / 3600)
local _min = math.floor((_off - _day * 86400 - _hour * 3600) / 60)
if _day == 0 then
self.view.root.ScrollView.Viewport.Content.item1.activite.Text[UI.Text].text = SGK.Localize:getInstance():getValue("online_reward_2", _hour, _min)
else
self.view.root.ScrollView.Viewport.Content.item1.activite.Text[UI.Text].text = SGK.Localize:getInstance():getValue("online_reward_1", _day, _hour, _min)
end
else
self.view.root.ScrollView.Viewport.Content.item1.activite.Text[UI.Text].text = ""
end
if self.view.root.ScrollView.Viewport.Content.item2.activeSelf then
self.view.root.ScrollView.Viewport.Content.item2.time[UI.Text].text = self.view.root.ScrollView.Viewport.Content.item1.activite.Text[UI.Text].text
end
end
local _questTime, _condition = self:getLevelTime()
local _time = _questTime - module.Time.now()
if self.flag then
if _time > 0 then
self.view.root.ScrollView.Viewport.Content.item1.overTime[UI.Text].text = SGK.Localize:getInstance():getValue("xiaobai_shoucangjia_7", GetTimeFormat(_time, 2, 2))
else
self.view.root.ScrollView.Viewport.Content.item1.overTime[UI.Text].text = SGK.Localize:getInstance():getValue("xiaobai_shoucangjia_7", "00:00")
module.QuestModule.Finish(module.guideLayerModule.Type.LevelUp)
self.flag = false
end
end
end
function guideShaar:upUi()
local _view = self.view.root.ScrollView.Viewport.Content.item2
_view:SetActive((self.quest and true) and (module.QuestModule.CanSubmit(self.cfg) or self.quest.status == 1))
_view.open:SetActive(module.ItemModule.GetItemCount(90032) > 0)
_view.close:SetActive(not _view.open.activeSelf)
self.view.root.ScrollView.Viewport.Content[UI.VerticalLayoutGroup].enabled = false
self.view.root.ScrollView.Viewport.Content[UI.VerticalLayoutGroup].enabled = true
end
function guideShaar:initUi()
self.view = CS.SGK.UIReference.Setup(self.gameObject)
for i = 1, #self.view.root.ScrollView.Viewport.Content do
local _view = self.view.root.ScrollView.Viewport.Content[i]
utils.IconFrameHelper.Create(_view.IconFrame, {customCfg={
icon = 19906,
quality = 0,
star = 0,
level = 0,
}, type = 42});
end
CS.UGUIClickEventListener.Get(self.view.root.backBtn.gameObject).onClick = function()
DialogStack.Pop()
end
CS.UGUIClickEventListener.Get(self.view.root.ScrollView.Viewport.Content.item2.open.gameObject, true).onClick = function()
if module.ItemModule.GetItemCount(90032) <= 0 then
showDlgError(nil, "未到时间")
return
end
local _view = self.view.root.ScrollView.Viewport.Content.item2.open
local _func = function()
_view[CS.UGUIClickEventListener].interactable = false
_view[UI.Image].material = SGK.QualityConfig.GetInstance().grayMaterial
coroutine.resume(coroutine.create(function()
local hero = module.HeroModule.GetManager():Get(11000)
local _data = module.HeroHelper.AddExpByItem(hero.uuid, 1)
if _data and _data[2] == 0 then
utils.EventManager.getInstance():dispatch("QUEST_INFO_CHANGE")
DialogStack.Pop()
return
end
_view[CS.UGUIClickEventListener].interactable = true
_view[UI.Image].material = nil
end))
end
if module.unionModule.Manage:GetSelfUnion() == nil then
local _msg = SGK.Localize:getInstance():getValue("xiayazhixin_3")
local _infoMsg = ""
if not openLevel.GetStatus(2101) then
_msg = SGK.Localize:getInstance():getValue("xiayazhixin_6", openLevel.GetCfg(2101).open_lev)
_infoMsg = _msg
end
showDlgMsg(SGK.Localize:getInstance():getValue("xiayazhixin_1", 5000),
function()
if openLevel.GetStatus(2101) then
utils.MapHelper.OpUnionList()
else
showDlgError(nil, _msg)
end
end,function()
_func()
end,SGK.Localize:getInstance():getValue("xiayazhixin_3"),
SGK.Localize:getInstance():getValue("xiayazhixin_2"), nil, _infoMsg)
else
showDlgMsg(SGK.Localize:getInstance():getValue("xiayazhixin_4", 5000),
function()
_func()
end, nil, SGK.Localize:getInstance():getValue("xiayazhixin_5", 5000))
end
end
self:upUi()
end
function guideShaar:getLevelTime()
local _quest = module.QuestModule.Get(module.guideLayerModule.Type.LevelUp)
local _time = module.playerModule.Get().loginTime
if _quest then
if _quest.records[1] == 0 then
_time = _quest.accept_time
end
return (_time + (_quest.condition[1].count - _quest.records[1])), _quest.condition[1].count
else
return 0
end
end
function guideShaar:listEvent()
return {
"QUEST_INFO_CHANGE",
"PLAYER_LEVEL_UP",
}
end
function guideShaar:onEvent(event, data)
if event == "QUEST_INFO_CHANGE" or event == "PLAYER_LEVEL_UP" then
self:upUi()
end
end
return guideShaar
|
local K, C, L, _ = unpack(select(2, ...))
if C["actionbar"].enable ~= true then return end
local _G = _G
local pairs = pairs
local select = select
local CreateFrame, UIParent = CreateFrame, UIParent
local InCombatLockdown = InCombatLockdown
local IsAltKeyDown, IsShiftKeyDown = IsAltKeyDown, IsShiftKeyDown
-- Show empty buttons
local frame = CreateFrame("Frame")
frame:RegisterEvent("PLAYER_ENTERING_WORLD")
frame:SetScript("OnEvent", function(self, event)
self:UnregisterEvent("PLAYER_ENTERING_WORLD")
if C["actionbar"].showgrid == true then
SetCVar("alwaysShowActionBars", 1)
for i = 1, 12 do
local button = _G[format("BonusActionButton%d", i)]
button:SetAttribute("showgrid", 1)
ActionButton_ShowGrid(button)
button = _G[format("MultiBarRightButton%d", i)]
button:SetAttribute("showgrid", 1)
ActionButton_ShowGrid(button)
button = _G[format("MultiBarBottomRightButton%d", i)]
button:SetAttribute("showgrid", 1)
ActionButton_ShowGrid(button)
button = _G[format("MultiBarLeftButton%d", i)]
button:SetAttribute("showgrid", 1)
ActionButton_ShowGrid(button)
button = _G[format("MultiBarBottomLeftButton%d", i)]
button:SetAttribute("showgrid", 1)
ActionButton_ShowGrid(button)
end
else
SetCVar("alwaysShowActionBars", 0)
end
end)
-- Moveable Bars
for _, frame in pairs({
_G["PetActionBarFrame"],
_G["ShapeshiftBarFrame"],
_G["PossessBarFrame"],
_G["MultiCastActionBarFrame"],
}) do
frame:EnableMouse(false)
end
-- Left-Alt + Left Click Move
for _, button in pairs({
_G["PossessButton1"],
_G["PetActionButton1"],
_G["ShapeshiftButton1"],
}) do
button:ClearAllPoints()
button:SetPoint("CENTER", UIParent, -100)
if InCombatLockdown() then
button:SetMovable(false)
button:SetUserPlaced(true)
else
button:SetMovable(true)
button:SetUserPlaced(true)
end
button:RegisterForDrag("LeftButton")
button:HookScript("OnDragStart", function(self)
if (IsShiftKeyDown() and IsAltKeyDown()) then
if InCombatLockdown() then return end
self:StartMoving()
end
end)
button:HookScript("OnDragStop", function(self)
self:StopMovingOrSizing()
end)
end
-- Totembar
-- Left-Alt + Left Click Move
local f = CreateFrame("Frame", "MultiCastActionBarFrameAnchor")
f:RegisterEvent("PLAYER_ENTERING_WORLD")
f:SetSize(10, 10)
f:ClearAllPoints()
f:SetPoint("CENTER", UIParent)
if InCombatLockdown() then
f:SetMovable(false)
f:SetUserPlaced(true)
else
f:SetMovable(true)
f:SetUserPlaced(true)
end
f:SetScript("OnEvent", function(self, event)
MultiCastActionBarFrame:ClearAllPoints()
MultiCastActionBarFrame:SetPoint("CENTER", MultiCastActionBarFrameAnchor)
MultiCastActionBarFrame.SetPoint = K.Dummy
end)
for i = 1, 12 do
for _, button in pairs({
_G["MultiCastSlotButton1"],
_G["MultiCastSlotButton2"],
_G["MultiCastSlotButton3"],
_G["MultiCastSlotButton4"],
_G["MultiCastActionBarFrame"],
_G["MultiCastActionButton"..i],
_G["MultiCastRecallSpellButton"],
_G["MultiCastSummonSpellButton"],
}) do
button:RegisterForDrag("LeftButton")
button:HookScript("OnDragStart", function()
if (IsControlKeyDown()) then
if InCombatLockdown() then return end
MultiCastActionBarFrameAnchor:StartMoving()
end
end)
button:HookScript("OnDragStop", function()
if InCombatLockdown() then return end
MultiCastActionBarFrameAnchor:StopMovingOrSizing()
end)
end
end
MultiCastActionButton1:ClearAllPoints()
MultiCastActionButton1:SetPoint("CENTER", MultiCastSlotButton1)
MultiCastActionButton5:ClearAllPoints()
MultiCastActionButton5:SetPoint("CENTER", MultiCastSlotButton1)
MultiCastActionButton9:ClearAllPoints()
MultiCastActionButton9:SetPoint("CENTER", MultiCastSlotButton1)
hooksecurefunc("MultiCastFlyoutFrame_LoadSlotSpells", function(self, slot, ...)
local numSpells = select("#", ...)
if (numSpells == 0) then
return false
end
numSpells = numSpells + 1
for i = 2, numSpells do
_G["MultiCastFlyoutButton"..i.."Icon"]:SetTexCoord(0.1, 0.9, 0.1, 0.9)
end
end) |
--managing changes in the game state
if GameStateManager == nil then
_G.GameStateManager = class ({})
end
settings = {
updateRate = 1,
randomAfterState = DOTA_GAMERULES_STATE_HERO_SELECTION
}
function GameStateManager:Init()
local GameMode = GameRules:GetGameModeEntity()
GameMode:SetContextThink("Update", function()
Brewlit:Update()
return settings.updateRate
end, settings.updateRate)
end
function GameStateManager:Setup(updateRate, randomAfterState)
if rate ~= nil then
Setup["updateRate"] = rate
end
if randomAfterState ~= nil then
settings["randomAfterState"] = randomAfterState
end
end
--called when the game state changes
function GameStateManager:OnChangeState()
local curState = GameRules:State_Get()
if curState > settings.randomAfterState then
Setup:AllRandomHero()
end
BroadcastStateChange(curState)
end
--[[
calls the listener function for the current state if it exists
Listener functions:
GameState:OnStateCustomGameSetup()
GameState:OnStateHeroSelection()
GameState:OnStateStrategyTime()
GameState:OnStateTeamShowcase()
GameState:OnStatePreGame()
GameState:OnStateInProgress()
GameState:OnStatePostGame()
GameState:OnStateGameDisconnect()
]]
function BroadcastStateChange(curState)
if curState == DOTA_GAMERULES_STATE_CUSTOM_GAME_SETUP and GameState.OnStateCustomGameSetup ~= nil then
GameState:OnStateCustomGameSetup()
elseif curState == DOTA_GAMERULES_STATE_PRE_GAME and GameState.OnStateHeroSelection ~= nil then
GameState:OnStateHeroSelection()
elseif curState == DOTA_GAMERULES_STATE_STRATEGY_TIME and GameState.OnStateStrategyTime ~= nil then
GameState:OnStateStrategyTime()
elseif curState == DOTA_GAMERULES_STATE_TEAM_SHOWCASE and GameState.OnStateTeamShowcase ~= nil then
GameState:OnStateTeamShowcase()
elseif curState == DOTA_GAMERULES_STATE_PRE_GAME and GameState.OnStatePreGame ~= nil then
GameState:OnStatePreGame()
elseif curState == DOTA_GAMERULES_STATE_GAME_IN_PROGRESS and GameState.OnStateInProgress ~= nil then
GameState:OnStateInProgress()
elseif curState == DOTA_GAMERULES_STATE_POST_GAME and GameState.OnStatePostGame ~= nil then
GameState:OnStatePostGame()
elseif curState == DOTA_GAMERULES_STATE_DISCONNECT and GameState.OnStateGameDisconnect ~= nil then
GameState:OnStateGameDisconnect()
end
end
--[[
Returns number from 0-9 based on the current state
INIT 0
WAIT_FOR_PLAYERS_TO_LOAD 1
CUSTOM_GAME_SETUP 2
HERO_SELECTION 3
STATE_STRATEGY_TIME 4
TEAM_SHOWCASE 5
PRE_GAME 6
GAME_IN_PROGRESS 7
POST_GAME 8
DISCONNECT 9
]]
function GameStateManager:GetCurrentState()
return GameRules:State_Get()
end
--sets the team winner and victory message
function GameStateManager:SetVictory(msg, teamNum)
if GameRules:State_Get() < DOTA_GAMERULES_STATE_POST_GAME then
GameRules:SetCustomVictoryMessage(msg)
GameRules:SetGameWinner(2)
end
end
|
--COMMAND TEMPLATE
local Object = {
name = "memusage",
usage = "Returns memory used by Lua",
cmdNames = {'mem','memusage'},
disabled = false
}
function Object.callback(self,args,rawarg)
local used = math.floor(collectgarbage("count")/1000)
args.msg:reply("Lua is using " .. used/GLOBAL_MAXMEM .. "% of a maximum " .. GLOBAL_MAXMEM .. "MBytes. (".. used .. "MB).")
return true
end
function Object:__init()
end
return Object |
local MILISECONDS_A_YEAR = 31536000000;
--设置token过期时间
local setExpires = function(token, expires)
-- 默认一年过期
-- 当前毫秒数+过期毫秒数
local expiresInMiliSeconds = expires
if expiresInMiliSeconds == -1 then
--[[
语法: ZADD key [NX|XX] [CH] [INCR] score member [score member ...]
XX: Only update elements that already exist. Never add elements.
NX: Don't update already existing elements. Always add new elements.
Adds all the specified members with the specified scores to the sorted set stored at key.
It is possible to specify multiple score / member pairs. If a specified member is already
a member of the sorted set, the score is updated and the element reinserted at the right
position to ensure the correct ordering.
--]]
redis.call("ZADD", AUTH_TOKEN_TTL_ZSET, redis.call("TIME")[1] + MILISECONDS_A_YEAR, token)
else
redis.call("ZADD", AUTH_TOKEN_TTL_ZSET, redis.call("TIME")[1] + expiresInMiliSeconds, token)
end
end |
--- OUTDATED, USE PROMISES INSTEAD.
--- OUTDATED, USE PROMISES INSTEAD.
--- OUTDATED, USE PROMISES INSTEAD.
--- OUTDATED, USE PROMISES INSTEAD.
--- OUTDATED, USE PROMISES INSTEAD.
local HttpService = game:GetService("HttpService")
local function httpGet(URL)
local success, response
repeat
success, response = pcall(function ()
return HttpService:RequestAsync({
Url = URL,
Method = "GET",
})
end)
if not success then
warn("pcall failed, retrying. Error details:"
.. "\n\t" .. response)
wait(3)
elseif not response.Success then
warn("HTTP GET failed, retrying. Error details:"
.. "\n\tStatus Code: " .. response.StatusCode
.. "\n\tStatus Message: " .. response.StatusMessage)
wait(3)
end
until success and response.Success
local success, decodedResponse = pcall(function ()
return HttpService:JSONDecode(response.Body)
end)
-- Assume can't parse means just return the raw data
return (success and decodedResponse) or response.Body
end
|
#!/usr/bin/luatex
--[[
prepcontour [Lua variant] - prepare contour lines (for pgfplots)
Version: 1.4 (2021-02-22)
Copyright (C) 2020-2021 Francesco Poli <[email protected]>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
--]]
-- class creation function
function FpolyCreateClass()
local newclass = {} -- this table is the created class (which will act
-- as metatable for the instantiated objects)
newclass.__index = newclass -- set the __index metamethod (so that
-- members missing from objects are searched
-- for in the class)
newclass.new = function (...) -- member function that will be used to
-- instantiate a new object of this class
local object = setmetatable({}, newclass) -- a table with this class
-- set as metatable
if object.init then
object:init(...) -- run the init method, if present
end
return object
end
return newclass
end
-- class for the coordinates (and meta value) of a point in 3D space
Coord = FpolyCreateClass()
function Coord:init()
self.x = { nil, nil, nil } -- point x,y,z coordinates
self.meta = nil -- point meta value
end
-- class for a 2D mesh of points in 3D space
PrepcMesh = FpolyCreateClass()
function PrepcMesh:init(yvaries, nblocks, nlines, copylines,
input, output)
if yvaries then
self.ni = nblocks - 1 -- number of cells in the i direction
self.nj = nlines - 1 -- number of cells in the j direction
else
self.ni = nlines - 1 -- number of cells in the i direction
self.nj = nblocks - 1 -- number of cells in the j direction
end
self.st = self.nj + 1 -- stride (number of nodes in the j direction)
self.si = self.nj + 1 -- stride for done_i
self.sj = self.nj -- stride for done_j
local cl = tonumber(copylines) or 0
self.is = input or io.stdin
self.os = output or io.stdout
self.debug = false
local st = self.st -- shorter name
self.coords = {} -- mesh of nodes
-- use single-index table for efficiency
-- (i,j) will be mapped to [i*st+j]
--[[
The mesh of nodes represented by this table is:
nj o o o o o o o o o o o o
^ o o o o o o o o o o o o
|
2| o o o o o o o o o o o o
|
1| o o o o o o o o o o o o
|
j=0+ o o o o o o o o o o o o
+----------------------------->
i=0 1 2 ni
--]]
-- copy the first "cl" text lines from self.is to self.os
for l = 1, cl do
self.os:write(self.is:read('L'))
end
-- read all the nodes
for bl = 0, nblocks - 1 do
if bl > 0 then
self.is:read('L') -- this text line should be empty
end
for ln = 0, nlines - 1 do
if yvaries then
i, j = bl, ln
else
i, j = ln, bl
end
n = Coord.new()
n.x[1], n.x[2], n.x[3], n.meta = self.is:read('n', 'n', 'n', 'n')
self.coords[i*st+j] = n
end
end
end
--[[ begin core of the program logic ]]--
-- build N contour lines between meta_min and meta_max
function PrepcMesh:autocontour(N, meta_min, meta_max, corners, tolerance)
-- subdivide the meta_min÷meta_max interval into N equal sub-intervals
-- and pick the midpoints of those sub-intervals
meta_min = tonumber(meta_min)
meta_max = tonumber(meta_max)
local step = (meta_max - meta_min)/N
local meta_mid = (meta_max + meta_min)/2
local n_mid = (N + 1)/2
for n = 1, N do
local isoval = meta_mid + (n - n_mid)*step
self:contour(isoval, corners, tolerance)
end
end
-- build contour lines for meta==isoval
function PrepcMesh:contour(isoval, corners, tolerance)
-- set relative tolerance
local tol = tolerance or 1e-3
-- short names
local st = self.st
local si = self.si
local sj = self.sj
-- local variables
local i, j
if self.done_i == nil then
self.done_i = {} -- table of markers for i-sides
-- again single-index table
-- (i,j) will be mapped to [i*si+j]
--[[
The corresponding i-sides are:
nj o--o--o--o--o--o--o--o--o--o--o--
^ o--o--o--o--o--o--o--o--o--o--o--
|
2| o--o--o--o--o--o--o--o--o--o--o--
|
1| o--o--o--o--o--o--o--o--o--o--o--
|
j=0+ o--o--o--o--o--o--o--o--o--o--o--
+-------------------------->
i=0 1 2 ni-1
--]]
end
if self.done_j == nil then
self.done_j = {} -- table of markers for j-sides
-- again single-index table
-- (i,j) will be mapped to [i*sj+j]
--[[
The corresponding j-sides are:
| | | | | | | | | | | |
nj-1 o o o o o o o o o o o o
| | | | | | | | | | | |
^ o o o o o o o o o o o o
| | | | | | | | | | | | |
1| o o o o o o o o o o o o
| | | | | | | | | | | | |
j=0+ o o o o o o o o o o o o
+----------------------------->
i=0 1 2 ni
--]]
end
if self.newcoords == nil then
self.newcoords = {} -- nodes for contour lines will be placed here
end
-- scan all the i-sides, searching for
-- intersections with the level surface
for i = 0, self.ni - 1 do
for j = 0, self.nj do
self.done_i[i*si+j] = ((self.coords[ i*st+j].meta > isoval) ==
(self.coords[(i+1)*st+j].meta > isoval))
--[[
This is equivalent to testing the two nodes of the i-side:
j o-----o
i i+1
If meta > isoval in both nodes, or in none of them, then
set done_i to true (never look again at this i-side).
Otherwise, set done_i to false (we have not finished with
this i-side, since it contains one point of a contour line).
--]]
end
end
-- scan all the j-sides, searching for
-- intersections with the level surface
for i = 0, self.ni do
for j = 0, self.nj - 1 do
self.done_j[i*sj+j] = ((self.coords[i*st+j ].meta > isoval) ==
(self.coords[i*st+j+1].meta > isoval))
--[[
This is equivalent to testing the two nodes of the j-side:
j+1 o
|
|
j o
i
Similarly, set done_j accordingly...
--]]
end
end
if self.debug then
self:show_sides(isoval)
end
--[[
We now have all the sides containing points of the meta==isoval
contour lines. We need to connect the points into distinct lines.
First of all, scan all the boundary sides, searching for sides
with done==false. For each boundary side with done==false, set
its done to true and build one contour line, starting from
the side itself and the real cell adjacent to it.
How can we specify a cell and one of its sides?
We can specify cell (i,j) and a side (South, West, North, East)
N
j o-------o
| |
W | (i,j) | E
| |
j-1 o-------o
i-1 S i
--]]
j = 0 -- i-sides with j=0
for i = 0, self.ni - 1 do
if not self.done_i[i*si+j] then
self.done_i[i*si+j] = true
self:build_line(isoval, tol, i+1, j+1, 'S', corners)
if self.debug then
self:show_sides(isoval)
end
end
end
i = 0 -- j-sides with i=0
for j = 0, self.nj - 1 do
if not self.done_j[i*sj+j] then
self.done_j[i*sj+j] = true
self:build_line(isoval, tol, i+1, j+1, 'W', corners)
if self.debug then
self:show_sides(isoval)
end
end
end
j = self.nj -- i-sides with j=nj
for i = 0, self.ni - 1 do
if not self.done_i[i*si+j] then
self.done_i[i*si+j] = true
self:build_line(isoval, tol, i+1, j , 'N', corners)
if self.debug then
self:show_sides(isoval)
end
end
end
i = self.ni -- j-sides with i=ni
for j = 0, self.nj - 1 do
if not self.done_j[i*sj+j] then
self.done_j[i*sj+j] = true
self:build_line(isoval, tol, i , j+1, 'E', corners)
if self.debug then
self:show_sides(isoval)
end
end
end
--[[
Finally, scan all the internal sides, again searching for sides
with done==false. For each internal side with done==false, do _not_
alter its done value and build one contour line, starting from
the side itself and one of the two real cells adjacent to it.
--]]
-- i-sides with j=1,...,nj-1 (i-sides with j=0 are already done)
-- j-sides with i=1,...,ni-1 (j-sides with i=0 are already done)
for j = 0, self.nj - 1 do
for i = 0, self.ni - 1 do
if not self.done_i[i*si+j] then
self:build_line(isoval, tol, i+1, j+1, 'S', corners)
if self.debug then
self:show_sides(isoval)
end
end
if not self.done_j[i*sj+j] then
self:build_line(isoval, tol, i , j+1, 'E', corners)
if self.debug then
self:show_sides(isoval)
end
end
end
end
end
-- build a single contour line
function PrepcMesh:build_line(isoval, tol, ic, jc, side, corners)
-- short names
local st = self.st
local si = self.si
local sj = self.sj
-- local variables
local ia, ja, na, wa
local ib, jb, nb, wb
local ie, je, ne
local id, jd, nd
local pt, k, count, next_side
local cc, xi_k, eta_k, ck, above, sign_ck
local xi_v, eta_v, xi_0, xi_1, eta_0, eta_1
local next_done, next_done_idx
while true do
--[[
Start from cell (ic,jc) and its South, West, North, or East side
e d b d a N b d b
o-------o o-------o o-*-----o o-------o
| | | | | | | *
| c | W | c | | c | | c | E
| | * | | | | |
o----*--o o-------o o-------o o-------o
a S b a e e d e a
--]]
-- find nodes a and b
if side == 'E' then ia = ic else ia = ic - 1 end
if side == 'N' then ja = jc else ja = jc - 1 end
if side == 'W' then ib = ic - 1 else ib = ic end
if side == 'S' then jb = jc - 1 else jb = jc end
if ia < 0 or ib > self.ni or ja < 0 or jb > self.nj then
self.newcoords[#self.newcoords + 1] = Coord.new()
break -- out of range: abort
end
na = self.coords[ia*st+ja] -- node a
nb = self.coords[ib*st+jb] -- node b
-- compute the intersection point between the side
-- and the meta==isoval level surface
wa = (isoval - nb.meta)/(na.meta - nb.meta) -- weights
wb = 1 - wa
pt = Coord.new()
for k = 1, 3 do
pt.x[k] = wa*na.x[k] + wb*nb.x[k] -- intersection point
end
pt.meta = isoval
-- add the intersection point to the contour line
self.newcoords[#self.newcoords + 1] = pt
-- check the cell: if it is a phantom cell, then stop
if ic < 1 or ic > self.ni or jc < 1 or jc > self.nj then
self.newcoords[#self.newcoords + 1] = Coord.new()
break -- the contour line is finished
end
-- find nodes e and d
if side == 'W' then ie = ic else ie = ic - 1 end
if side == 'S' then je = jc else je = jc - 1 end
if side == 'E' then id = ic - 1 else id = ic end
if side == 'N' then jd = jc - 1 else jd = jc end
ne = self.coords[ie*st+je] -- node e
nd = self.coords[id*st+jd] -- node d
-- look at the other three sides of the cell:
-- how many of them have done==false ?
count = 0
if side ~= 'S' and not self.done_i[(ic-1)*si+(jc-1)] then
count = count + 1
next_side = 'N' -- next side could be the North side of the
-- adjacent south cell
end
if side ~= 'W' and not self.done_j[(ic-1)*sj+(jc-1)] then
count = count + 1
next_side = 'E' -- next side could be the East side of the
-- adjacent west cell
end
if side ~= 'N' and not self.done_i[(ic-1)*si+ jc ] then
count = count + 1
next_side = 'S' -- next side could be the South side of the
-- adjacent north cell
end
if side ~= 'E' and not self.done_j[ ic *sj+(jc-1)] then
count = count + 1
next_side = 'W' -- next side could be the West side of the
-- adjacent east cell
end
--[[
if zero other sides have done==false, then stop
o o
o---*-o
--]]
if count == 0 then
self.newcoords[#self.newcoords + 1] = Coord.new()
break -- the contour line is finished
end
--[[
if exactly one other side has done==false, then
next_side already specifies the next side to start from
o-*---o
|
\
o---*-o
nothing to be done for the time being...
--]]
--[[
the surface inside the cell is thought as the bilinear
interpolation of the four nodes and hence mapped onto
a unit square in the xi,eta plane:
eta ^
| pt.x[k] = (1-xi)*(1-eta)*na.x[k] +
1+------+ xi *(1-eta)*nb.x[k] +
|e d| (1-xi)* eta *ne.x[k] +
| | xi * eta *nd.x[k]
|a b|
0+------+------>
0 1 xi
the equation of the contour line is therefore:
cc*xi*eta - eta_k*xi - xi_k*eta == ck
--]]
cc = na.meta - nb.meta + nd.meta - ne.meta
eta_k = na.meta - nb.meta
xi_k = na.meta - ne.meta
ck = isoval - na.meta
if math.abs(cc) <=
math.max(math.abs(tol*eta_k), math.abs(tol*xi_k)) then
--[[
cc is negligible and the contour line is
basically a straight line:
eta_k*xi + xi_k*eta + ck == 0
--]]
cc = 0
else
--[[
cc is non-zero (and non-negligible) and we can divide
both sides of the equation by cc:
xi*eta - (eta_k/cc)*xi - (xi_k/cc)*eta == ck/cc
--]]
xi_k = xi_k /cc -- let's rename the coefficients
eta_k = eta_k/cc
ck = xi_k*eta_k + ck/cc
--[[
the contour line is an equilateral hyperbola (in the
xi,eta plane) with asymptotes xi == xi_k and eta == eta_k
and constant product ck:
(xi - xi_k)*(eta - eta_k) == ck
--]]
if math.abs(ck) <= math.abs(tol/2) then
--[[
ck is negligible and the hyperbola basically
degenerates into its asymptotes
--]]
ck = 0
end
end
--[[
if two or three other sides have done==false, then
choose the next side
?
o-*---o
| * ?
? * |
o---*-o
--]]
if count >= 2 then
-- how can we choose the next side?
--[[
if there's more than one side to choose from, cc is
necessarily non-zero (a straight line could not cross
more than two sides of the unit square) and the
center k of the hyperbola is necessarily inside the
cell (otherwise one hyperbola branch would be completely
outside the cell and the other branch could not cross
more than two sides)
hence, choose the next side by checking the quadrant
where the hyperbola branch crossing side a-b lies
eta ^
| :
1+--:---+
|e : d|
······+k······
|a : b|
0+--:---+------>
0 : 1 xi
--]]
if ck == 0 then -- math.abs(ck) <= math.abs(tol/2)
-- choose side e-d
next_side = side
elseif ck < 0 then -- ck < -tol/2
-- choose side b-d
if side == 'N' or side == 'S' then
next_side = 'W'
else
next_side = 'S'
end
else -- ck > +tol/2
-- choose side a-e
if side == 'N' or side == 'S' then
next_side = 'E'
else
next_side = 'N'
end
end
end
if corners then -- enhanced corner algorithm
--[[
if, within the cell, the contour line is not straight
we can improve its representation by computing an
additional point: the vertex v of the hyperbola branch,
as long as it lies inside the cell
--]]
if cc ~= 0 then
-- depending on where the center k is, consider the
-- vertex above or below k
if eta_k < 0 then above = 1 else above = -1 end
-- also check the sign of ck
if ck < 0 then sign_ck = -1 else sign_ck = 1 end
-- compute the vertex v
xi_v = xi_k + sign_ck*above*math.sqrt(math.abs(ck))
eta_v = eta_k + above*math.sqrt(math.abs(ck))
--[[
the vertex will be considered inside the cell, as long as
xi_0 <= xi_v <= xi_1 and eta_0 <= eta_v <= eta_1
--]]
xi_0 = - math.abs(tol/10)
xi_1 = 1 + math.abs(tol/10)
eta_0 = math.abs(tol)
eta_1 = 1 + math.abs(tol/10)
-- eta_0 is meant to reject a vertex too close to side a-b
-- (which already has a contour line point!)
-- we should also reject a vertex too close to the next side
if next_side == side then
-- next side is e-d
eta_1 = 1 - math.abs(tol)
elseif next_side == 'W' or next_side == 'S' then
-- next side is b-d
xi_1 = 1 - math.abs(tol)
else -- next_side == 'E' or next_side == 'N'
-- next side is a-e
xi_0 = math.abs(tol)
end
if xi_0 <= xi_v and xi_v <= xi_1 and
eta_0 <= eta_v and eta_v <= eta_1 then
-- v is inside the cell: compute its actual coordinates
pt = Coord.new()
for k = 1, 3 do
pt.x[k] = (1-xi_v)*(1-eta_v)*na.x[k] +
xi_v *(1-eta_v)*nb.x[k] +
(1-xi_v)* eta_v *ne.x[k] +
xi_v * eta_v *nd.x[k]
end
pt.meta = isoval
-- add the vertex to the contour line
self.newcoords[#self.newcoords + 1] = pt
end
end
end
-- point to done value for the next side and
-- determine indexes for the next cell
-- (the other cell adjacent to the next side)
if next_side == 'W' then ic = ic + 1 end
if next_side == 'S' then jc = jc + 1 end
if next_side == 'N' or next_side == 'S' then
next_done = self.done_i
next_done_idx = (ic-1)*si+(jc-1)
else
next_done = self.done_j
next_done_idx = (ic-1)*sj+(jc-1)
end
if next_side == 'E' then ic = ic - 1 end
if next_side == 'N' then jc = jc - 1 end
-- if next side is already done, then stop
if next_done[next_done_idx] then
self.newcoords[#self.newcoords + 1] = Coord.new()
break -- the contour line is finished
end
-- set next side done to true and
-- iterate starting from this new side and the next cell
next_done[next_done_idx] = true
side = next_side
end
end
--[[ end core of the program logic ]]--
-- print out all the contour lines
function PrepcMesh:printcontours()
for n = 1, #self.newcoords do
if self.newcoords[n].x[1] then
self.os:write(string.format("%14.6g%14.6g%14.6g%14.6g\n",
self.newcoords[n].x[1],
self.newcoords[n].x[2],
self.newcoords[n].x[3],
self.newcoords[n].meta))
else
self.os:write('\n')
end
end
end
-- print a debug representation of mesh and not-done sides
function PrepcMesh:show_sides(isoval)
-- short names
local st = self.st
local si = self.si
local sj = self.sj
self.os:write(string.format("# contour level = %.6g \n#\n", isoval))
for j = self.nj, 0, -1 do
if j <= self.nj - 1 then
self.os:write("# ")
for i = 0, self.ni do
if self.done_j[i*sj+j] then
self.os:write(" ")
else
self.os:write(" *")
end
end
self.os:write("\n")
end
self.os:write("# ")
for i = 0, self.ni do
if self.coords[i*st+j].meta > isoval then
self.os:write("•")
else
self.os:write("o")
end
if i <= self.ni - 1 then
if self.done_i[i*si+j] then
self.os:write(" ")
else
self.os:write("*")
end
end
end
self.os:write("\n")
end
self.os:write("#\n")
end
|
data:extend({
{
type = "recipe",
name = "wooden-repair-pack-1",
energy_required = 0.5,
localised_name = "Wooden repair pack",
ingredients =
{
{"wood", 5},
{"iron-plate", 4}
},
result = "repair-pack"
},
{
type = "recipe",
name = "wooden-repair-pack-2",
localised_name = "Wooden repair pack",
energy_required = 0.5,
ingredients =
{
{"wood", 5},
{"copper-plate", 4}
},
result = "repair-pack"
}
}) |
return setmetatable({}, {
__call = function()
exec.cmd = function(exe)
local format, len, gsub, gmatch = string.format, string.len, string.gsub, string.gmatch
local set = {}
return setmetatable(set, {
__call = function(_, a, ...)
local args
if a and type(a) == "string" then
local ergs = format(a, ...)
args = {}
for k in gmatch(ergs, "%S+") do
args[#args + 1] = k
end
end
if a and type(a) == "table" then
args = a
end
local r, so, se, cerr = exec.command(
exe,
args,
set.env,
set.cwd,
set.stdin,
set.timeout
)
local pretty_prefix = function(header, prefix, str)
local n
if len(str) > 0 then
local replacement = format("\n %s > ", prefix)
str, n = gsub(str, "\n", replacement)
if n == 0 then
str = str .. ("\n %s > "):format(prefix)
end
return format(
"%s\n %s >\n %s > %s\n",
header,
prefix,
prefix,
str
)
else
return ""
end
end
if set.errexit == true and r == nil then
local err = cerr or set.error or "execution failed"
local header = format('exec.cmd: `%s` => "%s"', exe, err)
if len(so) < 1 and len(se) < 1 then
return fmt.panic("%s\n", header)
else
fmt.print("%s", pretty_prefix(header, "stdout", so))
return fmt.panic("%s", pretty_prefix(header, "stderr", se))
end
else
return r, so, se
end
end,
})
end
exec.run = setmetatable({}, {
__index = function(_, exe)
return function(...)
local args
if not (...) then
args = {}
elseif type(...) == "table" then
args = ...
else
args = { ... }
end
return exec.command(exe, args)
end
end,
})
end,
})
|
local replacements = require "src.replacements"
-- local is_content_type = replacements.is_content_type
local transform_body = replacements.transform_body
-- data
local filename = "test/testresponse.html"
local replacement_patterns = {
"https%:%/%/my%-internal%.server%:9999###https://nerdblog.steinkopf.net",
"https%:%/%/my%-internal%.server%:9999###https://nerdblog.steinkopf.net",
"https%:%/%/my%-internal%.server%:9999###https://nerdblog.steinkopf.net",
"https%:%/%/my%-internal%.server%:9999###https://nerdblog.steinkopf.net",
"https%:%/%/my%-internal%.server%:9999###https://nerdblog.steinkopf.net",
"https%:%/%/my%-internal%.server%:9999###https://nerdblog.steinkopf.net",
"https%:%/%/my%-internal%.server%:9999###https://nerdblog.steinkopf.net",
"http%:%/%/my%-internal%.server%:9999###https://nerdblog.steinkopf.net"
}
-- load test data
local file = assert(io.open(filename, "r"))
local filebody = file:read("*all")
local body = ""
for i = 1,11 do
body = body .. filebody
end
file:close()
-- run and measure test
local start_time = os.clock()
local run_count = 100
for i = 1,run_count do
local transformed_body = transform_body(replacement_patterns, body)
assert(transformed_body:find("nerdblog.steinkopf.net"))
end
local seconds_taken = os.clock() - start_time
print ("seconds_taken per run: " .. seconds_taken * 1000 / run_count .. " ms") |
local BezierCurve = require(script.Parent.bezierCurve)
local Path = {}
Path.__index = Path
function Path:length()
local totalDistance = 0
for _, segment in ipairs(self.segments) do
totalDistance = totalDistance + segment:length()
end
return totalDistance
end
--[[
t here is between [0,1]. This means we need to figure out which segment
this timme corresponds to and map the time to the time it would be in
said segment
]]
function Path:pointAtTime(t)
t = math.clamp(t, 0, 1)
local numSegments = #self.segments
local segmentTimeWidth = 1 / numSegments
local segmentIndex = math.ceil(t / segmentTimeWidth)
if segmentIndex == 0 then
segmentIndex = 1 -- the case when t = 0
end
-- Need to map this path time to the current segment time
local segment = self.segments[segmentIndex]
local timeInSegment = (t - (segmentIndex - 1) * segmentTimeWidth) / segmentTimeWidth
-- print("Time:", t)
-- print("Time in segment:", timeInSegment)
return segment:pointAtTime(timeInSegment)
end
function Path:directionAtTime(t)
t = math.clamp(t, 0, 1)
local numSegments = #self.segments
local segmentTimeWidth = 1 / numSegments
local segmentIndex = math.ceil(t / segmentTimeWidth)
if segmentIndex == 0 then
segmentIndex = 1 -- the case when t = 0
end
-- Need to map this path time to the current segment time
local segment = self.segments[segmentIndex]
local timeInSegment = (t - (segmentIndex - 1) * segmentTimeWidth) / segmentTimeWidth
-- print("Time:", t)
-- print("Time in segment:", timeInSegment)
return segment:directionAtTime(timeInSegment)
end
function Path:directionAtDistance(s)
if #self.segments == 0 then
return self.anchors[1].position
end
s = math.clamp(s, 0, self:length())
local segmentIndex = 1
local numSegments = #self.segments
local accumulatedDistance = 0
-- print("Number of segments:", numSegments)
-- figure out which segment we're in based on the given distance s
for i = 1, numSegments do
local segment = self.segments[i]
if s <= accumulatedDistance + segment:length() then
segmentIndex = i
break
end
accumulatedDistance = accumulatedDistance + segment:length()
end
local segment = self.segments[segmentIndex]
local segmentDistance = s - accumulatedDistance
return segment:directionAtDistance(segmentDistance)
end
function Path:pointAtDistance(s)
if #self.segments == 0 then
return self.anchors[1].position
end
s = math.clamp(s, 0, self:length())
local segmentIndex = 1
local numSegments = #self.segments
local accumulatedDistance = 0
-- print("Number of segments:", numSegments)
-- figure out which segment we're in based on the given distance s
for i = 1, numSegments do
local segment = self.segments[i]
if s <= accumulatedDistance + segment:length() then
segmentIndex = i
break
end
accumulatedDistance = accumulatedDistance + segment:length()
end
local segment = self.segments[segmentIndex]
local segmentDistance = s - accumulatedDistance
return segment:pointAtDistance(segmentDistance)
end
function Path:updateAnchorPoint(anchorIndex, position)
local previousPosition = self.anchors[anchorIndex].position
local delta = position - previousPosition
-- print("before:", self.anchors[anchorIndex])
-- update anchor position as well as the handles for anchor by delta
self.anchors[anchorIndex].position = self.anchors[anchorIndex].position + delta
self.anchors[anchorIndex].handles[1] = self.anchors[anchorIndex].handles[1] + delta
self.anchors[anchorIndex].handles[2] = self.anchors[anchorIndex].handles[2] + delta
-- print("after:", self.anchors[anchorIndex])
-- need to update the actual segment objects
local segments = {
back = anchorIndex > 1 and self.segments[anchorIndex - 1] or nil,
front = anchorIndex <= #self.segments and self.segments[anchorIndex] or nil
}
-- print("segments before:", segments)
if segments.back then
segments.back:updatePoint(4, self.anchors[anchorIndex].position) --points[4] = self.anchors[anchorIndex].position
segments.back:updatePoint(3, self.anchors[anchorIndex].handles[1]) --points[3] = self.anchors[anchorIndex].handles[1]
segments.back:updateLUT()
end
if segments.front then
segments.front:updatePoint(1, self.anchors[anchorIndex].position) --[1] = self.anchors[anchorIndex].position
segments.front:updatePoint(2, self.anchors[anchorIndex].handles[2]) --.points[2] = self.anchors[anchorIndex].handles[2]
segments.front:updateLUT()
end
-- print("segments after:", segments)
end
function Path:updateHandlePoint(anchorIndex, handleIndex, position)
-- update both handle positions
self.anchors[anchorIndex].handles[handleIndex] = position -- first one
local anchorPosition = self.anchors[anchorIndex].position
local otherHandleIndex = (handleIndex % 2) + 1
local normal = (anchorPosition - position).Unit
local toOtherHandle = self.anchors[anchorIndex].handles[otherHandleIndex] - anchorPosition
local newPosition = anchorPosition + toOtherHandle.Magnitude * normal
self.anchors[anchorIndex].handles[otherHandleIndex] = newPosition
-- update both segments
local segments = {
back = anchorIndex > 1 and self.segments[anchorIndex - 1] or nil,
front = anchorIndex <= #self.segments and self.segments[anchorIndex] or nil
}
-- print("segments before:", segments)
if segments.back then
segments.back:updatePoint(3, self.anchors[anchorIndex].handles[1]) --points[3] = self.anchors[anchorIndex].handles[1]
segments.back:updateLUT()
end
if segments.front then
segments.front:updatePoint(2, self.anchors[anchorIndex].handles[2]) --.points[2] = self.anchors[anchorIndex].handles[2]
segments.front:updateLUT()
end
-- print("segments after:", segments)
end
function Path:addAnchor(anchor)
table.insert(self.anchors, {
position = anchor.position,
handles = {
anchor.handles[1],
anchor.handles[2]
}
})
local points = {
self.anchors[#self.anchors - 1].position,
self.anchors[#self.anchors - 1].handles[2],
self.anchors[#self.anchors].handles[1],
self.anchors[#self.anchors].position
}
local newSegment = BezierCurve(points)
table.insert(self.segments, newSegment)
end
function Path:removeAnchor(anchorIndex)
local segments = {
back = anchorIndex > 1 and self.segments[anchorIndex - 1] or nil,
front = anchorIndex <= #self.segments and self.segments[anchorIndex] or nil
}
if segments.back and segments.front then
-- remove anchor N and segment N
table.remove(self.anchors, anchorIndex)
table.remove(self.segments, anchorIndex)
-- modify segment N - 1
local segment = segments.back
segment:updatePoint(3, self.anchors[anchorIndex].handles[1])
segment:updatePoint(4, self.anchors[anchorIndex].position)
segment:updateLUT()
elseif segments.back then
table.remove(self.anchors, anchorIndex)
table.remove(self.segments, anchorIndex - 1)
elseif segments.front then
table.remove(self.anchors, anchorIndex)
table.remove(self.segments, anchorIndex)
end
end
return function(anchorPoints, controlPoints)
assert(type(anchorPoints) == "table" and #anchorPoints >= 2, "Anchor points must have at least 2 points")
assert(#controlPoints == 2 * #anchorPoints, "Each anchor point must have 2 control points.")
local path = setmetatable({
segments = {},
anchors = {}
}, Path)
-- create anchor objects
for i = 1, #anchorPoints do
table.insert(path.anchors, {
position = anchorPoints[i],
handles = {
controlPoints[2 * i - 1],
controlPoints[2 * i]
}
})
end
-- create the bezier curve segments
for i = 1, #anchorPoints - 1 do
local points = {
path.anchors[i].position,
path.anchors[i].handles[2],
path.anchors[i + 1].handles[1],
path.anchors[i + 1].position
}
local segment = BezierCurve(points)
path.segments[i] = segment
end
return path
end |
test = require 'u-test'
common = require 'common'
function AchievementProgressNotifications_Handler()
print ('AchievementProgressNotifications_Handler')
XblAchievementsAddAchievementProgressChangeHandler()
SetCheckHR(0)
Sleep(5000)
XblAchievementsUpdateAchievementAsync("2", 20)
end
function OnXblAchievementsAddAchievementProgressHandler()
print ('OnXblAchievementsAddAchievementProgressHandler')
XblAchievementsRemoveAchievementProgressChangeHandler()
test.stopTest();
end
function OnXblAchievementsUpdateAchievementAsync()
print ("OnXblAchievementsUpdateAchievementAsync")
local hr = GetLastError()
SetCheckHR(1)
if hr == -2145844944 then -- -2145844944 == 0x80190130 == HTTP_E_STATUS_NOT_MODIFIED
print("Achievement not modified.")
XblAchievementsRemoveAchievementProgressChangeHandler()
test.stopTest()
elseif hr ~= 0 then
test.equal(hr, 0);
print("Failure. hr=" .. hr)
test.stopTest()
else
print ("Waiting to receive notification.")
end
end
test.skip = true;
test.TestAchievementProgressNotification = function()
common.init(AchievementProgressNotifications_Handler)
end |
-- Reload Config
hs.loadSpoon("ReloadConfiguration")
spoon.ReloadConfiguration:start()
spoon.ReloadConfiguration:bindHotkeys({reloadConfiguration = {{"cmd", "alt", "ctrl"}, "R"}})
-- Toggle showing seconds in menubar lock
hs.hotkey.bind({"cmd", "alt", "ctrl"}, "S", function()
-- Get current state
format = hs.execute("defaults read com.apple.menuextra.clock DateFormat")
-- Trim whitespace
format = format:gsub("^%s*(.-)%s*$", "%1")
-- Toggle format
format = (format == "EEE MMM d h:mm a") and "EEE MMM d h:mm:ss a" or "EEE MMM d h:mm a"
-- Write new format and restart the menubar
command = 'defaults write com.apple.menuextra.clock DateFormat -string "' .. format .. '" && killall SystemUIServer'
hs.execute(command)
end)
-- Resize Window to Left or Right Side
hs.hotkey.bind({"cmd", "alt", "shift"}, "Left", function()
local win = hs.window.focusedWindow()
local f = win:frame()
local screen = win:screen()
local max = screen:frame()
f.x = max.x
f.y = max.y
f.w = max.w / 2
f.h = max.h
win:setFrame(f)
end)
hs.hotkey.bind({"cmd", "alt", "shift"}, "Right", function()
local win = hs.window.focusedWindow()
local f = win:frame()
local screen = win:screen()
local max = screen:frame()
f.x = max.x + (max.w / 2)
f.y = max.y
f.w = max.w / 2
f.h = max.h
win:setFrame(f)
end)
hs.hotkey.bind({"cmd", "alt", "shift"}, "Up", function()
local win = hs.window.focusedWindow()
local f = win:frame()
local screen = win:screen()
local max = screen:frame()
f.x = max.x
f.y = max.y
f.w = max.w
f.h = max.h
win:setFrame(f)
end)
-- Window positions
hs.hotkey.bind({"cmd", "alt", "ctrl"}, "W", function()
local laptopScreen = "Color LCD"
local windowLayout = {
{"iTerm2", nil, laptopScreen, hs.layout.left50, nil, nil},
{"Code", nil, laptopScreen, hs.layout.right50, nil, nil},
}
hs.layout.apply(windowLayout)
end)
-- Wifi
function mute()
hs.audiodevice.defaultOutputDevice():setVolume(0)
hs.audiodevice.defaultOutputDevice():setMuted(true)
end
hs.loadSpoon("WiFiTransitions")
spoon.WiFiTransitions.actOnNilTransitions = true
spoon.WiFiTransitions.actions = {{from="GLERJ", fn=mute}}
spoon.WiFiTransitions:start()
-- Keyboard Shortcut Sheet
hs.loadSpoon("KSheet")
spoon.KSheet:bindHotkeys({
toggle={{"cmd", "alt", "ctrl"}, "D"}
})
-- Mouse Circle
hs.loadSpoon("MouseCircle")
spoon.MouseCircle:bindHotkeys({show={{"cmd", "alt", "ctrl"}, "M"}})
-- Move windows between monitors
hs.loadSpoon("WindowScreenLeftAndRight")
spoon.WindowScreenLeftAndRight:bindHotkeys(spoon.WindowScreenLeftAndRight.defaultHotkeys)
-- Screen Rotation
hs.loadSpoon("ToggleScreenRotation")
spoon.ToggleScreenRotation:bindHotkeys({["DELL U2515H"] = {{"cmd", "alt", "ctrl"}, "O"}})
|
-- player stuffs
-- love.module shortcuts
local la = love.audio
local le = love.event
local lf = love.filesystem
local lg = love.graphics
local li = love.image
local lj = love.joystick
local lk = love.keyboard
local lm = love.mouse
local ln = love.math
local lp = love.physics
local ls = love.system
local ly = love.thread
local lt = love.timer
local lw = love.window
-- lua shortcuts
local min,max,abs,sign = math.min,math.max,math.abs,sign
--# #define's
local SPD = 3600
local RUNSPD = SPD*2
local GRV = 2000
local SPEEDUP = 0.25
local JUMPHEIGHT = -800
local ezra = lg.newImage("ezra.png")
plyr = {
x=510,y=670,z=0, xv=0,yv=0,zv=0,
hv=30,mhv=30, av=10,mav=10,
xp=0, tkns=0,
anm={cur="hodl",las="", f=1,dt=0, d1=1,d2=1},
-- only for strife
dmg=2,def=1,spd=3,
onguard=false,canguard=true,guarddt=0, ishurt=false,hurtdt=0,hurtf=1, isrockn=false,rockndt=0
}
-- collision aka safety oval
local t,maxi,phi = {},32,2*math.pi
for i=1,maxi,2 do
t[i] = 60 * math.cos( (i / maxi) * phi ) + plyr.x
t[i+1] = 30 * math.sin( (i / maxi) * phi ) + plyr.y
end
plyr.col = hc.polygon(unpack(t))
t,maxi,phi = nil,nil,nil
-- assets, should load only once
local passet = {img=lg.newImage("assets/gfx/ezra.png")}
local v,w,h = nil,passet.img:getDimensions()
for i=1,2 do
v = i==1 and 0 or 280
passet[i] = {hodl={},walk={},jump={}}
passet[i].hodl[1] = lg.newQuad(0,v, 200,280, w,h)
passet[i].walk[1] = lg.newQuad(200,v, 200,280, w,h); passet[i].walk[2] = passet[i].hodl[1]
passet[i].walk[3] = lg.newQuad(400,v, 200,280, w,h); passet[i].walk[4] = passet[i].hodl[1]
passet[i].jump[1] = lg.newQuad(200,v, 200,280, w,h)
passet[i].jump[2] = lg.newQuad(400,v, 200,280, w,h)
end
v,w,h = nil,nil,nil
local ininteractable,interactablefunc = false,function()end
local ku,kd,kl,kr
function plyr.update(dt)
if not panels.isActive() and tostate==gamestate and tomap==currentmap and mapsdarkness<0.5 then
--ks = lk.isDown("space") and 1 or 0
ku = lk.isDown("up") and 1 or 0
kd = lk.isDown("down") and 1 or 0
kl = lk.isDown("left") and 1 or 0
kr = lk.isDown("right") and 1 or 0
else
ku,kd,kl,kr = 0,0,0,0
end
--# movement
local p = plyr
-- directional movement
local dx,dy = (kr-kl),(kd-ku)
-- keyboard move
if (dx~=0 or dy~=0) then
local spd = canrun and RUNSPD or SPD
p.xv = p.xv + spd*dx*dt*SPEEDUP
p.yv = p.yv + spd*dy*dt*SPEEDUP--/2
SPEEDUP = min(SPEEDUP + dt*2,1)
end
if abs(p.xv) <= 0.1 then p.xv = 0 end --elseif abs(p.xv) > MAXSPD then p.xv = sign(p.xv)*MAXSPD end
if abs(p.yv) <= 0.1 then p.yv = 0 end --elseif abs(p.yv) > MAXSPD then p.yv = sign(p.yv)*MAXSPD end
p.x = p.x + p.xv * dt; p.xv = p.xv * (1-dt*12)
p.y = p.y + p.yv * dt; p.yv = p.yv * (1-dt*12)
-- p.zv = min(p.zv + GRV*dt,7100); p.z = p.z + p.zv * dt
-- if p.z>0 then p.z,p.zv = 0,0 end
-- if dx==0 and dy==0 then p.xv,p.yv = p.xv/1.15,p.yv/1.15; SPEEDUP = 0.25 end
-- if ks==0 and p.zv<JUMPHEIGHT/4 then p.zv = JUMPHEIGHT/4 end
--# collision handling
p.col:moveTo(p.x,p.y-16)
if not(_DEBUG and lk.isDown("lctrl")) then
local collided,dx,dy
for i,v in ipairs(collidables) do
collided,dx,dy = p.col:collidesWith(v)
if collided then
p.col:move(dx,dy)
p.x,p.y = p.x+dx,p.y+dy
end
end
end
for i,v in ipairs(triggerzones) do
collided = p.col:collidesWith(v)
if collided and type(v:getUserData())=="function" then
v:getUserData()()
end
end
ininteractable = false
for i,v in ipairs(interactables) do
collided = p.col:collidesWith(v)
if collided and type(v:getUserData())=="table" then
local t = v:getUserData()
ininteractable = t.pd1==p.anm.d1 and t.pd2==p.anm.d2
interactablefunc = t.func
end
end
--# animation
local a = p.anm
local mx = 0
if p.zv~=0 then
mx = 0.05
a.cur = "jump"
elseif dx~=0 or dy~=0 then
mx = 0.1
a.cur = "walk"
else
a.cur = "hodl"
end
if a.las~=a.cur then
a.f = 1
a.dt = 0
a.las = a.cur
end
a.dt = a.dt + dt
if a.dt >= mx then a.f,a.dt = a.f + 1,0 end
if a.f > #passet[a.d2][a.cur] then a.f = 1 end
a.d1 = dx~=0 and dx or a.d1
a.d2 = dy==-1 and 2 or dy==1 and 1 or a.d2
end
function plyr.draw()
local p = plyr
local a = p.anm
--lg.setColor(1, 170/256, 0, 0.25); lg.rectangle("fill", p.x-90,p.y+p.z-240, 180,240)
--lg.setColor(1, 100/256, 0, 0.25); lg.rectangle("fill", p.x-75,p.y+p.z-230, 150,220)
lg.setColor(0,0,0,0.35)
lg.ellipse("fill", plyr.x,plyr.y-16, 60,30)
lg.setColor(1,1,1)
local x,y, w,h = passet[a.d2][a.cur][a.f]:getViewport()
lg.draw(passet.img, passet[a.d2][a.cur][a.f], p.x,p.y+20, 0,a.d1,1, w/2,h)
--print(p.x,p.y)
--lg.setColor(0, 170/256, 1); p.col:draw("line"); lg.setColor(1,1,1)
end
function plyr.keypressed(k)
if k=="x" then
if ininteractable then interactablefunc() end
end
end
function plyr.isInInteractable()
return ininteractable -- isininteractable==true ?
end |
att.PrintName = "Homemade FCG"
att.Icon = Material("entities/ammo_fcg_homemade.png")
att.Description = "A homemade full-auto firemode conversion, with some strange modifications made to the firing bolt."
att.Desc_Pros = {
}
att.Desc_Cons = {
}
att.AutoStats = true
att.Slot = "fcg"
att.Override_Firemodes = {
{
Mode = 2,
},
{
Mode = 1,
},
{
Mode = 0
}
}
att.Mult_Recoil = 2.35
att.Mult_DamageMin = 0.45
att.Mult_Damage = 0.75
att.Mult_RPM = 3
att.Mult_ReloadTime = 1.55
att.Mult_DrawTime = 2
att.Mult_SightTime = 2
att.Mult_AccuracyMOA = 1.45
att.Mult_HipDispersion = 1.45
att.Mult_SightsDispersion = 1.45 |
--[[---------------------------------------------------------------------------
Warmod Project
Dev(s): x[N]ir, Hajt
File: modules/player/hooks.lua
Description: Client sided hooks
--]]---------------------------------------------------------------------------
-- Connection flag
warmod.connected = {}
-- Muted flag
warmod.mute = {}
-- Current menu
warmod.player_menu = {}
-- Whenever a player joins the server
function warmod.join(id)
if type(id) ~= "number" then
return
end
timer(3000, "warmod.update_ready_list")
warmod.sv_msg2(id, "Welcome to the server! Please visit " .. warmod.WEBSITE)
warmod.mute[id] = false
warmod.init_stats(id, true)
-- Save Admin IP
if warmod.is_admin(id) then
warmod.sv_msg2(id, "You have been successfully logged in as admin")
local ip = player(id, "ip")
if not warmod.table_contains(warmod.ADMINS_IPS, ip) then
warmod.ADMINS_IPS[#warmod.ADMINS_IPS + 1] = ip
warmod.save_admins()
end
end
if not warmod.started then
warmod.sv_msg2(id, "Say !ready if you want to play in the match")
end
end
-- Whenever a player left the server
-- Reasons: 2 Kick / Banned 6 / Normal 0 / Timeout 1
function warmod.leave(id, reason)
warmod.log("Leave Hook", player(id, "name") .. " Reason: " .. reason)
if warmod.started and warmod.is_playing(id) then
if warmod.state == warmod.STATES.PRE_CAPTAINS_KNIFE or
warmod.state == warmod.STATES.CAPTAINS_KNIFE then
if warmod.team_a_captain == id or warmod.team_b_captain == id then
warmod.cancel_mix("A captain left during knife")
elseif warmod.table_contains(warmod.ready, id) then
-- TODO: Something else should be done here
warmod.cancel_mix("A player left during knife")
end
elseif warmod.state == warmod.STATES.PRE_TEAM_SELECTION or
warmod.state == warmod.STATES.TEAM_A_SELECTION or
warmod.state == warmod.STATES.TEAM_B_SELECTION then
if warmod.team_a_captain == id or
warmod.team_b_captain == id then
-- TODO: Something else should be done here
warmod.cancel_mix("A captain left during team selection")
elseif warmod.table_contains(warmod.ready, id) then
-- TODO: Something else should be done here
warmod.cancel_mix("A player left during team selection")
end
elseif warmod.state == warmod.STATES.PRE_MAP_VETO or
warmod.state == warmod.STATES.MAP_VETO or
warmod.state == warmod.STATES.WINNER_VETO or
warmod.state == warmod.STATES.LOOSER_VETO then
if id == warmod.veto_winner or id == warmod.veto_looser then
warmod.cancel_mix("A veto chooser left !")
end
elseif warmod.state >= warmod.STATES.PRE_KNIFE_ROUND and
warmod.state <= warmod.STATES.SECOND_HALF then
if id == warmod.team_a_captain then
warmod.new_captain("A", id)
elseif id == warmod.team_b_captain then
warmod.new_captain("B", id)
end
local team = warmod.get_team(id)
if team == "A" then
warmod.table_remove(warmod.team_a, id)
else
warmod.table_remove(warmod.team_b, id)
end
-- Intentional leave
if reason == 0 then
warmod.ban(id, "Leaving during a match = 1 Day Ban")
if warmod.team_size == 1 then
if warmod.state > warmod.STATES.FIRST_HALF then
if #warmod.team_a == 0 then
warmod.forfeit_win(2)
else
warmod.forfeit_win(1)
end
else
warmod.cancel_mix("Rage quit")
end
return
else
-- Free access to spectators
if warmod.get_team(id) == "A" then
warmod.missing_a_players = warmod.missing_a_players + 1
else
warmod.missing_b_players = warmod.missing_b_players + 1
end
end
-- Timed out / Kick / Banned
else
local ip = player(id, "ip")
local leavers
if team == "A" then
leavers = warmod.team_a_leavers
else
leavers = warmod.team_b_leavers
end
-- Sanity check
if not warmod.table_contains(leavers, ip) then
leavers[#leavers + 1] = ip
warmod.sv_msg(player(id, "name") ..
" has 3 minutes to reconnect !")
timer(180000, "warmod.timer_timeout", team .. ip)
end
end
if team == "A" then
if #warmod.team_a == 0 and warmod.team_size > 1 then
if warmod.state > warmod.STATES.FIRST_HALF then
warmod.forfeit_win(2)
else
warmod.cancel_mix("Rage quit")
end
end
else
if #warmod.team_b == 0 and warmod.team_size > 1 then
if warmod.state > warmod.STATES.FIRST_HALF then
warmod.forfeit_win(1)
else
warmod.cancel_mix("Rage quit")
end
end
end
warmod.table_remove(warmod.rr_votes, id)
end
else
-- Is this player a subber ?
for mix_player, spec_target in pairs(warmod.sub_players) do
-- He Accepted to sub him
if spec_target == id and warmod.sub_spectators[id] then
warmod.sub_players[mix_player] = nil
warmod.sub_spectators[id] = nil
msg2(mix_player, "\169255255255[SUB]:" ..
player(id, "name") .. " won't sub you !")
break
end
end
end
warmod.set_player_notready(id)
warmod.set_stats_nil(id)
end
-- When a player is killed by another player
function warmod.kill(killer, victim)
-- Only during first half or second half
if not warmod.started or (warmod.state ~= warmod.STATES.FIRST_HALF and
warmod.state ~= warmod.STATES.SECOND_HALF) then
return
end
warmod.round_kills[killer] = warmod.round_kills[killer] + 1
warmod.tmp_d[victim] = warmod.tmp_d[victim] + 1
end
-- On name change for the player with a certain ID.
function warmod.name(id, oldname, newname)
if warmod.mute[id] == true then
msg2(id,"\169255150150[ERROR]:\169255255255 You are muted")
return 1
end
if not warmod.started then
timer(1, "warmod.update_ready_list")
end
end
-- When a player writes a chat message
function warmod.say(id,txt)
local ret = warmod.command_check(id, txt)
if ret == 1 then
return 1
elseif warmod.mute[id] == true then
msg2(id,"\169255150150[ERROR]:\169255255255 You are muted")
return 1
end
end
-- Whenever a player is hit/damaged
function warmod.hit(id, source, weapon, hpdmg)
if not warmod.started or (warmod.state ~= warmod.STATES.FIRST_HALF and
warmod.state ~= warmod.STATES.SECOND_HALF) then
return
end
if source ~= 0 and player(source, "team") ~= player(id, "team") then
warmod.dmg[source] = warmod.dmg[source] + hpdmg
end
end
-- When a player changes or joins a team or becomes a spectator or
-- changes the look (player skin)
function warmod.team(id, team, skin)
if warmod.started then
-- Missing player(s) case(s)
if not warmod.is_playing(id) then
if warmod.state > warmod.STATES.KNIFE_ROUND and
warmod.state < warmod.STATES.PRE_SECOND_HALF then
if warmod.missing_a_players > 0 and team == 1 then
warmod.add_to_team_a(id)
warmod.sv_msg(player(id, "name") .. " has joined " .. warmod.team_a_name)
warmod.missing_a_players = warmod.missing_a_players - 1
return 0
end
if warmod.missing_b_players > 0 and team == 2 then
warmod.add_to_team_b(id)
warmod.sv_msg(player(id, "name") .. " has joined " .. warmod.team_b_name)
warmod.missing_b_players = warmod.missing_b_players - 1
return 0
end
elseif warmod.state == warmod.STATES.SECOND_HALF or
warmod.state == warmod.STATES.PRE_SECOND_HALF then
if warmod.missing_a_players > 0 and team == 2 then
warmod.add_to_team_a(id)
warmod.sv_msg(player(id, "name") .. " has joined " .. warmod.team_a_name)
warmod.missing_a_players = warmod.missing_a_players - 1
return 0
end
if warmod.missing_b_players > 0 and team == 1 then
warmod.add_to_team_b(id)
warmod.sv_msg(player(id, "name") .. " has joined " .. warmod.team_b_name)
warmod.missing_b_players = warmod.missing_b_players - 1
return 0
end
end
end
-- Leavers come back issues
if #warmod.team_a_leavers > 0 or #warmod.team_b_leavers > 0 then
local ip = player(id, "ip")
if warmod.state > warmod.STATES.KNIFE_ROUND and
warmod.state < warmod.STATES.PRE_SECOND_HALF then
if warmod.table_contains(warmod.team_a_leavers, ip) and team == 1 then
warmod.add_to_team_a(id)
warmod.table_remove(warmod.team_a_leavers, ip)
freetimer("warmod.timer_timeout", "A" .. ip)
warmod.sv_msg(player(id, "name") .. " has joined back " ..
warmod.team_a_name)
return 0
elseif warmod.table_contains(warmod.team_b_leavers, ip) and team == 2 then
warmod.add_to_team_b(id)
warmod.table_remove(warmod.team_b_leavers, ip)
freetimer("warmod.timer_timeout", "B" .. ip)
warmod.sv_msg(player(id, "name") .. " has joined back " ..
warmod.team_b_name)
return 0
else
return 1
end
elseif warmod.state == warmod.STATES.PRE_SECOND_HALF or
warmod.state == warmod.STATES.SECOND_HALF then
if warmod.table_contains(warmod.team_a_leavers, ip) and team == 2 then
warmod.add_to_team_a(id)
warmod.table_remove(warmod.team_a_leavers, ip)
freetimer("warmod.timer_timeout", "A" .. ip)
warmod.sv_msg(player(id, "name") .. " has joined back " ..
warmod.team_a_name)
return 0
elseif warmod.table_contains(warmod.team_b_leavers, ip) and team == 1 then
warmod.add_to_team_b(id)
warmod.table_remove(warmod.team_b_leavers, ip)
freetimer("warmod.timer_timeout", "B" .. ip)
warmod.sv_msg(player(id, "name") .. " has joined back " ..
warmod.team_b_name)
return 0
else
return 1
end
end
end
if warmod.teams_locked and not warmod.forced_switch then
msg2(id, "\169255000000Team change is disabled !")
return 1
end
end
end
-- On Lua menu button selection
function warmod.menu(id, title, button)
local menu = warmod.player_menu[id]
if button == 0 then
warmod.player_menu[id] = nil
elseif button == 8 then
menu.page = menu.page - 1
warmod.display_menu(id)
elseif button == 9 then
menu.page = menu.page + 1
warmod.display_menu(id)
else
local index = (menu.page - 1) * 7 + button
local b = menu.buttons[index]
local func = b.func
func(id, b.args)
end
end
-- On planting bomb
function warmod.bombplant(id, x, y)
if warmod.started then
-- Disable bomb plant on knife rounds
if warmod.state == warmod.STATES.CAPTAINS_KNIFE or
warmod.state == warmod.STATES.KNIFE_ROUND or
warmod.state == warmod.STATES.MAP_VETO then
msg2(id, "\169255000000[ERROR]: You can't plant the bomb now !")
return 1
-- Bomb plants tracker
elseif warmod.state == warmod.STATES.FIRST_HALF or
warmod.state == warmod.STATES.SECOND_HALF then
warmod.tmp_bp[id] = warmod.tmp_bp[id] + 1
end
end
end
-- Bomb defusals tracker
function warmod.bombdefuse(id)
if warmod.started then
if warmod.state == warmod.STATES.FIRST_HALF or
warmod.state == warmod.STATES.SECOND_HALF then
warmod.tmp_bd[id] = warmod.tmp_bd[id] + 1
end
end
end
-- Only knife and 0$ on knife rounds
function warmod.spawn(id)
if warmod.started then
if warmod.state == warmod.STATES.CAPTAINS_KNIFE or
warmod.state == warmod.STATES.MAP_VETO or
warmod.state == warmod.STATES.KNIFE_ROUND then
parse("setmoney " .. id .. " 0")
return "x"
end
end
end
-- Pressing [F2] opens the main menu
function warmod.serveraction(id, action)
if action == 1 then
warmod.open_main_menu(id)
end
end
-- Disable suicide on mixes
function warmod.suicide(id)
if warmod.started then
return 1
end
end |
-- We are using PCH, so you must disable PCH on the protobuf files, and enable generation on stdafx.cpp
workspace "Plugin"
configurations {"Debug", "Release"}
platforms {"Win32", "Win64", "UnitTestWin32", "UnitTestWin64"}
language "C++"
project "Plugin"
targetdir "bin/%{cfg.buildcfg}/%{cfg.platform}"
targetname "Hardlight"
-- dependencies
protobuf_incl_dir = "D:/protobuf-3.0.0/cmake/build/solution/include"
shared_comms_incl_dir = "C:/Users/NullSpace Team/Documents/NS_Unreal_SDK/src/Driver/SharedCommunication"
boost_incl_dir = "D:/Libraries/boost/boost_1_61_0"
protobuf_def_incl_dir = "C:/Users/NullSpace Team/Documents/NS_Unreal_SDK/src/Driver/protobuff_defs"
disablewarnings {"4800"}
includedirs {
protobuf_incl_dir,
shared_comms_incl_dir,
boost_incl_dir,
protobuf_def_incl_dir,
"../src/Plugin",
"../src/Plugin/test",
"../src/Plugin/devices",
"../src/Plugin/events",
"../src/Plugin/include"
}
flags {
"MultiProcessorCompile",
"C++11"
}
--links {"System", "UnityEditor", "UnityEngine", "System.ServiceProcess"}
files {
"../src/Plugin/**.cpp",
"../src/Plugin/**.h",
path.join(protobuf_def_incl_dir, "**.pb.cc"),
path.join(shared_comms_incl_dir, "ScheduledEvent.cpp")
}
-- for protobuf
boost_win32_dir = "D:/Libraries/boost/boost_1_61_0/stage/win32/lib"
boost_win64_dir = "D:/Libraries/boost/boost_1_61_0/stage/x64/lib"
protobuf_win32_dir = "D:/protobuf-3.0.0/cmake/build/solution"
protobuf_win64_dir = "D:/protobuf-3.0.0/cmake/build/solution64"
pchheader "stdafx.h"
pchsource "../src/Plugin/stdafx.cpp"
defines {"HLVR_EXPORTS"}
filter {"files:**.pb.cc"}
flags {'NoPCH'}
filter {"files:**ScheduledEvent.cpp"}
flags {'NoPCH'}
filter {"files:**test_main.cpp"}
flags{'NoPCH'}
filter {"platforms:Win32 or platforms:Win64"}
kind "SharedLib"
filter {"platforms:UnitTest*"}
kind "ConsoleApp"
-- input: libprotobuf
filter {"platforms:Win32", "configurations:Debug"}
libdirs {
path.join(protobuf_win32_dir, "Debug")
}
filter {"platforms:Win32", "configurations:Release"}
libdirs {
path.join(protobuf_win32_dir, "Release")
}
filter {"platforms:Win64", "configurations:Debug"}
libdirs {
path.join(protobuf_win64_dir, "Debug")
}
filter {"platforms:Win64", "configurations:Release"}
libdirs {
path.join(protobuf_win64_dir, "Release")
}
-- unit testing
filter {"platforms:UnitTestWin32", "configurations:Debug"}
libdirs {
path.join(protobuf_win32_dir, "Debug")
}
filter {"platforms:UnitTestWin32", "configurations:Release"}
libdirs {
path.join(protobuf_win32_dir, "Release")
}
filter {"platforms:UnitTestWin64", "configurations:Debug"}
libdirs {
path.join(protobuf_win64_dir, "Debug")
}
filter {"platforms:UnitTestWin64", "configurations:Release"}
libdirs {
path.join(protobuf_win64_dir, "Release")
}
filter "platforms:Win32 or platforms:UnitTestWin32"
system "Windows"
architecture "x86"
libdirs {
boost_win32_dir
}
defines {"WIN32"}
filter "platforms:Win64 or platforms:UnitTestWin64"
system "Windows"
architecture "x86_64"
libdirs {
boost_win64_dir
}
filter "configurations:Debug"
defines {"DEBUG", "_DEBUG"}
symbols "On"
optimize "Off"
links {"libprotobufd"}
filter "configurations:Release"
defines {"NDEBUG"}
optimize "On"
links {"libprotobuf"}
filter {"system:Windows"}
defines {"_WINDOWS", "_USRDLL"}
filter {"system:Windows", "configurations:Debug"}
buildoptions {"-D_SCL_SECURE_NO_WARNINGS"}
project "Utilities"
targetdir "bin/Utilities/%{cfg.buildcfg}/%{cfg.platform}"
targetname "HardlightUtilities"
-- dependencies
boost_incl_dir = "D:/Libraries/boost/boost_1_61_0"
shared_comms_incl_dir = "C:/Users/NullSpace Team/Documents/NS_Unreal_SDK/src/Driver/SharedCommunication"
includedirs {
boost_incl_dir,
shared_comms_incl_dir,
"../src/Utilities/"
}
flags {
"MultiProcessorCompile",
"C++11"
}
--links {"System", "UnityEditor", "UnityEngine", "System.ServiceProcess"}
files {
"../src/Utilities/**.cpp",
"../src/Utilities/**.h",
path.join(shared_comms_incl_dir, "ScheduledEvent.cpp"),
"../src/Plugin/NSLoader.h",
"../src/Plugin/NSLoader_Errors.h"
}
plugin_debug_win32_dir = "bin/Debug/Win32/"
plugin_release_win32_dir = "bin/Release/Win32/"
boost_win32_dir = "D:/Libraries/boost/boost_1_61_0/stage/win32/lib"
boost_win64_dir = "D:/Libraries/boost/boost_1_61_0/stage/x64/lib"
pchheader "stdafx.h"
pchsource "../src/Utilities/stdafx.cpp"
defines {"HLVR_EXPORTS"}
filter {"files:**.pb.cc"}
flags {'NoPCH'}
filter {"files:**ScheduledEvent.cpp"}
flags {'NoPCH'}
filter {"files:**test_main.cpp"}
flags{'NoPCH'}
filter {"platforms:Win32 or platforms:Win64"}
kind "SharedLib"
filter {"platforms:UnitTest*"}
kind "ConsoleApp"
filter "platforms:Win32 or platforms:UnitTestWin32"
system "Windows"
architecture "x86"
libdirs {
boost_win32_dir
}
defines {"WIN32"}
filter "platforms:Win64 or platforms:UnitTestWin64"
system "Windows"
architecture "x86_64"
libdirs {
boost_win64_dir
}
filter "configurations:Debug"
defines {"DEBUG", "_DEBUG"}
symbols "On"
optimize "Off"
libdirs {
--need to fix this so we have correct win32 win64 debug/release
plugin_debug_win32_dir
}
links { "Hardlight"}
filter "configurations:Release"
defines {"NDEBUG"}
optimize "On"
libdirs {
plugin_release_win32_dir
}
links {"Hardlight"}
filter {"system:Windows"}
defines {"_WINDOWS", "_USRDLL"}
filter {"system:Windows", "configurations:Debug"}
buildoptions {"-D_SCL_SECURE_NO_WARNINGS"}
|
local penisx = -540
local penisy = -200
local penisSize = 1.85
local pf = 'bgs/normal/'
local mf = 'veryBack'
local curLight = 1;
function onCreate()
--getProperty('gf.', )
-- le bg fuckin shit
if (songName == 'Ego') then
pf = 'bgs/ego/';
mf = 'windows'
else
pf = 'bgs/normal/';
mf = 'veryBack'
end
for i=1,4 do
debugPrint(pf .. mf .. i);
makeLuaSprite('ww' .. i, pf .. mf .. i, getProperty('boyfriend.x'), getProperty('boyfriend.y'));
addLuaSprite('ww' .. i, true);
setProperty('ww' .. i .. '.visible',false)
if (i == curLight) then
setProperty('ww' .. i .. '.visible',true)
end
end
end |
return {
MainInterfaceFile = "interface.xui";
BundleDisplayName = "XUI 亮色主题示例";
Executable = "main.lua";
BundleIconFile = "appicon.png";
BundleVersion = "1.4.0";
MinimumXXTVersion = "1.2";
MinimumSystemVersion = "7.0";
-- MaximumSystemVersion = "11.1.2";
BundleInfoDictionaryVersion = "6.0";
--[[ SupportedResolutions = {
{
width = "640";
height = "1136";
};
{
width = "750";
height = "1334";
};
{
width = "1242";
height = "2208";
};
{
width = "640";
height = "960";
};
{
width = "768";
height = "1024";
};
{
width = "1536";
height = "2048";
};
}; --]]
BundleName = "A-Script-Bundle";
PackageControl = {
AuthorEmail = "[email protected]";
Description = "一个 XXTouch 脚本包例子,完整效果需要最低 1.2-10 支持";
Homepage = "https://www.xxtouch.com";
AuthorName = "XXTouch Team";
};
BundleIdentifier = "com.yourcompany.A-Script-Bundle";
} |
return {'fje','fjes'} |
ENT.Base = "base_gmodentity"
ENT.Type = "anim"
ENT.PrintName = "Storage Box (Public)"
ENT.Author = "vin"
ENT.Purpose = ""
ENT.Instructions = "Press E"
ENT.Category = "impulse"
ENT.Spawnable = true
ENT.AdminOnly = true
ENT.HUDName = "Public storage locker"
ENT.HUDDesc = "Deposit or withdraw legal items." |
--unit/attack.lua version 42.06a
local utils = require 'utils'
validArgs = validArgs or utils.invert({
'help',
'defender',
'attacker',
'target',
'attack',
'velocity',
'hitchance',
'weapon',
'delay',
'number',
})
local args = utils.processArgs({...}, validArgs)
if args.help then -- Help declaration
print([[unit/attack
]])
return
end
if args.defender and tonumber(args.defender) then
defender = df.unit.find(tonumber(args.defender))
else
print('No defender selected')
return
end
if args.attacker and tonumber(args.attacker) then
attacker = df.unit.find(tonumber(args.attacker))
else
print('No attacker selected')
return
end
attack = nil
target = nil
delay = tonumber(args.delay) or 1
number = tonumber(args.number) or 1
hitchance = tonumber(args.hitchance) or 100
if not args.target then
target = dfhack.script_environment('functions/unit').checkBodyRandom(defender)
else
target = dfhack.script_environment('functions/unit').checkBodyCategory(defender,args.target)[1]
end
if not target then
print('No appropriate target found')
return
end
if args.weapon then
attack_id = -1
local item = nil
args.weapon = 'Equipped'
if args.weapon == 'Equipped' then
item = dfhack.script_environment('functions/unit').checkInventoryType(attacker,'WEAPON')[1]
if not item then
print('No Equipped Weapon')
return
end
end
if not args.attack then
attack = dfhack.script_environment('functions/item').checkAttack(item,'Random')
else
attack = dfhack.script_environment('functions/item').checkAttack(item,args.attack)
end
if not attack then
print('No appropriate attack found')
return
end
item_id = item.id
if args.velocity then
velocity = tonumber(args.velocity)
else
velocity = dfhack.script_environment('functions/attack').getAttackItemVelocity(attacker,item,attack)
end
else
item_id = -1
if not args.attack then
attack = dfhack.script_environment('functions/unit').checkAttack(attacker,'Random')
else
attack = dfhack.script_environment('functions/unit').checkAttack(attacker,args.attack)
end
if not attack then
print('No appropriate attack found')
return
end
attack_id = attacker.body.body_plan.attacks[attack].body_part_idx[0]
if args.velocity then
velocity = tonumber(args.velocity)
else
velocity = dfhack.script_environment('functions/attack').getAttackUnitVelocity(attacker,attack)
end
end
j = 0
while j < number do
dfhack.script_environment('functions/attack').addAttack(attacker,defender.id,attack_id,target,item_id,attack,hitchance,velocity,delay)
j = j + 1
end |
-----------------------------------------
-- ID: 5743
-- Item: marinara_pizza
-- Food Effect: 3 hours, all Races
-----------------------------------------
-- HP +20
-- Attack +20% (cap 50 @ 250 base attack)
-- Accuracy +10% (54)
-- Undead Killer
-----------------------------------------
require("scripts/globals/status")
require("scripts/globals/msg")
-----------------------------------------
function onItemCheck(target)
local result = 0
if target:hasStatusEffect(tpz.effect.FOOD) or target:hasStatusEffect(tpz.effect.FIELD_SUPPORT_FOOD) then
result = tpz.msg.basic.IS_FULL
end
return result
end
function onItemUse(target)
target:addStatusEffect(tpz.effect.FOOD, 0, 0, 10800, 5743)
end
function onEffectGain(target, effect)
target:addMod(tpz.mod.HP, 20)
target:addMod(tpz.mod.FOOD_ATTP, 20)
target:addMod(tpz.mod.FOOD_ATT_CAP, 50)
target:addMod(tpz.mod.FOOD_ACCP, 10)
target:addMod(tpz.mod.FOOD_ACC_CAP, 54)
target:addMod(tpz.mod.UNDEAD_KILLER, 5)
end
function onEffectLose(target, effect)
target:delMod(tpz.mod.HP, 20)
target:delMod(tpz.mod.FOOD_ATTP, 20)
target:delMod(tpz.mod.FOOD_ATT_CAP, 50)
target:delMod(tpz.mod.FOOD_ACCP, 10)
target:delMod(tpz.mod.FOOD_ACC_CAP, 54)
target:delMod(tpz.mod.UNDEAD_KILLER, 5)
end
|
--------------------------------------------------------------------------------
-- ДУРА (Дополнительная Универсальная Радиоаппаратура)
--------------------------------------------------------------------------------
Metrostroi.DefineSystem("DURA")
TRAIN_SYSTEM.DontAccelerateSimulation = true
function TRAIN_SYSTEM:Initialize()
self.SelectAlternate = nil
self.Channel = 1
self.Signal = 0
self.Power = 1
end
function TRAIN_SYSTEM:Outputs()
return { "Signal" }
end
function TRAIN_SYSTEM:Inputs()
return { "SelectAlternate", "SelectMain", "SelectChannel", "ToggleChannel", "Power", "PowerToggle" }
end
function TRAIN_SYSTEM:TriggerInput(name,value)
if (name == "SelectAlternate") and (value > 0.0) then
self.SelectAlternate = true
elseif (name == "SelectMain") and (value > 0.0) then
self.SelectAlternate = false
elseif (name == "ToggleChannel") and (value > 0.0) then
if self.Channel == 1 then self.Channel = 2 else self.Channel = 1 end
elseif (name == "SelectChannel") then
self.Channel = math.floor(value)
elseif (name == "Power") then
self.Power = math.floor(value)
elseif (name == "PowerToggle") then
if self.Power > 0.5 then
self.Power = 0
else
self.Power = 1
end
end
end
function TRAIN_SYSTEM:Think()
-- Require 80 volts
if self.Train.Battery and (self.Train.Battery.Voltage < 70) then return end
if (self.Power or 1) < 0.5 then return end
--self.Train:PlayOnce("dura2","cabin",0.4,100)
-- Check ARS signals
self.Timer = self.Timer or CurTime()
if CurTime() - self.Timer > 2.00 then
self.Timer = CurTime()
-- Get train position
local pos = Metrostroi.TrainPositions[self.Train]
if pos then pos = pos[1] end
-- Get all switches in current isolated section
local no_switches = true
local signal = 0
if pos then
-- Get traffic light in front
local light = Metrostroi.GetNextTrafficLight(pos.node1,pos.x,pos.forward)
local function getSignal(base,chan)
if (chan == 1) and (base == "alt") and light and light:GetInvertChannel1() then return "main" end
if (chan == 2) and (base == "alt") and light and light:GetInvertChannel2() then return "main" end
return base
end
-- Get switches and trigger them all
local switches = Metrostroi.GetTrackSwitches(pos.node1,pos.x,pos.forward)
for _,switch in pairs(switches) do
no_switches = false
if self.SelectAlternate == true then
switch:SendSignal(getSignal("alt",1),1)
if self.Channel == 2 then switch:SendSignal(getSignal("alt",2),2) end
elseif self.SelectAlternate == false then
switch:SendSignal(getSignal("main",1),1)
if self.Channel == 2 then switch:SendSignal(getSignal("main",2),2) end
end
signal = math.max(signal,switch:GetSignal())
end
-- Reset state selection
self.SelectAlternate = nil
end
if signal > 0 then
self.Train:PlayOnce("dura1","cabin",0.35,200)
end
self.Signal = signal
-- If no switches, reset
if no_switches and (self.SelectAlternate ~= nil) then
--self.Train:PlayOnce("dura2","cabin",0.35,200)
--self.SelectAlternate = nil
end
end
end |
require "lfs"
infiles = {}
fileindex = 0
for f in lfs.dir(".") do
if f:match(".woz$") then
infiles[#infiles + 1] = f
end
end
table.sort(infiles)
function calc(line)
return line % 8 * 1024 + math.floor(line / 64) * 40 + math.floor((line%64) / 8) * 128 + 8192
end
function textcalc(line)
return calc(line * 8) - 8192 + 0x0400
end
function striphibitstring(a)
local b = ""
for i = 1, string.len(a) do
b = b .. string.char(a:byte(i) & 0x7f)
end
return b
end
mainmem = emu.item(manager.machine.devices[":ram"].items["0/m_pointer"]) -- always gets main memory
function getscreenline(i)
return striphibitstring(mainmem:read_block(textcalc(i), 40))
end
function getscreen()
local b = ""
for i = 0, 23 do
b = b .. getscreenline(i) .. "\n"
end
return b
end
function savescreen(outfile)
local h = io.open(outfile, "w")
h:write(getscreen())
h:close()
end
function createblankdsk(outfile)
local h = io.open(outfile, "wb")
for i = 1, 143360 do
h:write(0x00)
end
h:close()
end
state = "waiting_for_main_menu"
function driver()
if state == "waiting_for_main_menu" then
if getscreen():match("rack disk") then
fileindex = fileindex + 1
if fileindex > #infiles then
manager.machine:exit()
return
end
dsk, subcount = infiles[fileindex]:gsub(".woz$", ".dsk")
if subcount == 0 then
print("ERROR unable to parse filename")
return
end
print(infiles[fileindex])
createblankdsk(dsk)
manager.machine.images[":sl6:diskiing:0:525"]:load(infiles[fileindex])
manager.machine.images[":sl6:diskiing:1:525"]:load(dsk)
emu.keypost("C")
state = "waiting_for_process"
end
end
if state == "waiting_for_process" then
if getscreen():match("Press any key") then
log, subcount = infiles[fileindex]:gsub(".woz$", ".log")
savescreen(log)
emu.keypost(" ")
state = "waiting_for_main_menu"
end
end
end
;manager.machine.video.frameskip = 10
;manager.machine.video.throttled = false
emu.register_frame_done(driver)
|
local create_room_server_connector = require "uniconn/create_room_server_connector"
-- create_connector
return function(door_host, is_secure, web_server_port, socket_server_port, disconnected_handler)
local connector = create_room_server_connector(socket_server_port, disconnected_handler)
local url
if is_secure == true then
url = "https://"
else
url = "http://"
end
url = url..door_host..":"..web_server_port.."/__SOCKET_SERVER_HOST?defaultHost="..door_host
http.request(url, "GET", function(self, _, response)
connector.connect(response.response)
end)
return connector
end |
require 'base'
class = require 'class'
require 'rectangle'
vector = require 'vector'
progressbar = class {
function(self, x, y, w, h, progress)
self.progress = progress
self.progressupdate = false
self.background = {255, 255, 255, 255}
self.foreground = {255, 0, 0, 255}
self.start = vector(x, y + h/2)
self.stop = vector(x + w, y + h/2)
self.width = w
self.height = h
self:updateprogress(progress)
end
}
function progressbar:updateprogress()
if self.progress > 1 then self.progress = 1 end
if self.progress < 0 then self.progress = 0 end
self.progresspoint = vector(self.start.x + (self.width * self.progress), self.start.y)
end
function progressbar:setProgress(progress)
self.progress = progress
self.progressupdate = true
end
function progressbar:update(dt)
if self.progressupdate then
self:updateprogress()
end
end
function progressbar:keypressed(key, unicode)
if key == " " then
self:setProgress(self.progress + 0.05)
end
if key == 'return' then
self:setProgress(self.progress - 0.05)
end
end
function progressbar:draw()
local r, g, b, a = love.graphics.getColor()
self.background[4] = a
self.foreground[4] = a
local width = love.graphics.getLineWidth()
love.graphics.setLineWidth(self.height)
love.graphics.setColor(self.background)
love.graphics.line(self.start.x, self.start.y, self.stop.x, self.stop.y)
love.graphics.setColor(self.foreground)
love.graphics.line(self.start.x, self.start.y, self.progresspoint.x, self.progresspoint.y)
love.graphics.setColor(r, g, b, a)
love.graphics.setLineWidth(width)
end |
local BasePlugin = require "kong.plugins.base_plugin"
local RoutesAuditHandler = BasePlugin:extend()
RoutesAuditHandler.PRIORITY = 10
function RoutesAuditHandler:new()
RoutesAuditHandler.super.new(self, "routes-audit")
end
function RoutesAuditHandler:init_worker()
RoutesAuditHandler.super.init_worker(self)
local cjson = require "cjson"
local worker_events = require "resty.worker.events"
local events = require "kong.core.events"
local singletons = require "kong.singletons"
local dao = singletons.dao
local handler = function(data, event, source, pid)
if data and data.collection == "apis" then
if data.type == events.TYPES.ENTITY_CREATED then
-- store to custom entities
local api = dao.apis:find { id = data.entity.id }
if api then
local audit_log, err = dao.routes_audit:insert({
api_id = api.id,
name = api.name,
path = api.upstream_url,
state = "added"
})
ngx.log(ngx.NOTICE, "Added API:" .. cjson.encode(audit_log))
end
elseif data.type == events.TYPES.ENTITY_DELETED then
-- invalidate the custom entities
if data.entity.id then
local audit_log, err = dao.routes_audit:insert({
api_id = data.entity.id,
state = "deleted"
})
ngx.log(ngx.NOTICE, "Deleted API:" .. cjson.encode(audit_log))
end
end
end
end
worker_events.register(handler)
end
function RoutesAuditHandler:access(conf)
RoutesAuditHandler.super.access(self)
end
return RoutesAuditHandler
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.