repo_name stringlengths 6 69 | path stringlengths 6 178 | copies stringclasses 278 values | size stringlengths 4 7 | content stringlengths 671 917k | license stringclasses 15 values |
|---|---|---|---|---|---|
scscgit/scsc_wildstar_addons | MailHelper/libs/GeminiAddon/GeminiAddon.lua | 6 | 25267 | --- GeminiAddon-1.1
-- Formerly DaiAddon
-- Inspired by AceAddon
-- Modules and packages embeds are based heavily on AceAddon's functionally, so credit goes their authors.
--
-- Allows the addon to have modules
-- Allows for packages to be embedded (if supported) into the addon and it's modules
--
-- The core callbacks have been "renamed" for consumption that are used when creating an addon:
-- OnLoad -> OnInitialize
--
-- New callback:
-- OnEnable - Called when the character has been loaded and is in the world. Called after OnInitialize and after Restore would have occured
--
-- General flow should be:
-- OnInitialize -> OnEnable
local MAJOR, MINOR = "Gemini:Addon-1.1", 6
local APkg = Apollo.GetPackage(MAJOR)
if APkg and (APkg.nVersion or 0) >= MINOR then
return -- no upgrade is needed
end
local GeminiAddon = APkg and APkg.tPackage or {}
-- Upvalues
local error, type, tostring, select, pairs = error, type, tostring, select, pairs
local setmetatable, getmetatable, xpcall = setmetatable, getmetatable, xpcall
local assert, loadstring, rawset, next, unpack = assert, loadstring, rawset, next, unpack
local tconcat, tinsert, tremove, ostime = table.concat, table.insert, table.remove, os.time
local strformat = string.format
-- Wildstar APIs
local Apollo, ApolloTimer, GameLib = Apollo, ApolloTimer, GameLib
-- Package tables
GeminiAddon.Addons = GeminiAddon.Addons or {} -- addon collection
GeminiAddon.AddonStatus = GeminiAddon.AddonStatus or {} -- status of addons
GeminiAddon.Timers = GeminiAddon.Timers or {} -- Timers for OnEnable
local mtGenTable = { __index = function(tbl, key) tbl[key] = {} return tbl[key] end }
-- per addon lists
GeminiAddon.Embeds = GeminiAddon.Embeds or setmetatable({}, mtGenTable)
GeminiAddon.InitializeQueue = GeminiAddon.InitializeQueue or setmetatable({}, mtGenTable) -- addons that are new and not initialized
GeminiAddon.EnableQueue = GeminiAddon.EnableQueue or setmetatable({}, mtGenTable) -- addons awaiting to be enabled
-- Check if the player unit is available
local function IsPlayerInWorld()
return GameLib.GetPlayerUnit() ~= nil
end
local tLibError = Apollo.GetPackage("Gemini:LibError-1.0")
local fnErrorHandler = tLibError and tLibError.tPackage and tLibError.tPackage.Error or Print
-- xpcall safecall implementation
local function CreateDispatcher(argCount)
local code = [[
local xpcall, eh = ...
local method, ARGS
local function call() return method(ARGS) end
local function dispatch(func, ...)
method = func
if not method then return end
ARGS = ...
return xpcall(call, eh)
end
return dispatch
]]
local ARGS = {}
for i = 1, argCount do ARGS[i] = "arg"..i end
code = code:gsub("ARGS", tconcat(ARGS, ", "))
return assert(loadstring(code, "safecall Dispatcher[" .. argCount .. "]"))(xpcall, fnErrorHandler)
end
local Dispatchers = setmetatable({}, {__index=function(self, argCount)
local dispatcher = CreateDispatcher(argCount)
rawset(self, argCount, dispatcher)
return dispatcher
end})
Dispatchers[0] = function(func)
return xpcall(func, fnErrorHandler)
end
local function safecall(func, ...)
if type(func) == "function" then
return Dispatchers[select('#', ...)](func, ...)
end
end
local function AddonToString(self)
return self.Name
end
local Enable, Disable, Embed, GetName, SetEnabledState, AddonLog
local EmbedModule, EnableModule, DisableModule, NewModule, GetModule, SetDefaultModulePrototype, SetDefaultModuleState, SetDefaultModulePackages
-- delay the firing the OnEnable callback until after Character is in world
-- and OnRestore would have occured
local function DelayedEnable(oAddon)
local strName = oAddon:GetName()
if GameLib.GetPlayerUnit() == nil then
-- If the Player Unit doesn't exist we wait for the CharacterCreated event instead
GeminiAddon.Timers[strName] = nil
Apollo.RegisterEventHandler("CharacterCreated", "___OnDelayEnable", oAddon)
return
end
local tEnableQueue = GeminiAddon.EnableQueue[strName]
while #tEnableQueue > 0 do
local oAddonToEnable = tremove(tEnableQueue, 1)
GeminiAddon:EnableAddon(oAddonToEnable)
end
-- Cleanup
GeminiAddon.EnableQueue[strName] = nil
GeminiAddon.Timers[strName] = nil
Apollo.RemoveEventHandler("CharacterCreated", oAddon)
oAddon.___OnDelayEnable = nil
end
local function NewAddonProto(strInitAddon, oAddonOrName, oNilOrName)
local oAddon, strAddonName
-- get addon name
if type(oAddonOrName) == "table" then
oAddon = oAddonOrName
strAddonName = oNilOrName
else
strAddonName = oAddonOrName
end
oAddon = oAddon or {}
oAddon.Name = strAddonName
-- use existing metatable if exists
local addonmeta = {}
local oldmeta = getmetatable(oAddon)
if oldmeta then
for k,v in pairs(oldmeta) do addonmeta[k] = v end
end
addonmeta.__tostring = AddonToString
setmetatable(oAddon, addonmeta)
-- setup addon skeleton
GeminiAddon.Addons[strAddonName] = oAddon
oAddon.Modules = {}
oAddon.OrderedModules = {}
oAddon.DefaultModulePackages = {}
-- Embed any packages that are needed
Embed( oAddon )
-- Add to Queue of Addons to be Initialized during OnLoad
tinsert(GeminiAddon.InitializeQueue[strInitAddon], oAddon)
return oAddon
end
-- Create a new addon using GeminiAddon
-- The final addon object will be returned.
-- @paramsig [object, ] strAddonName, bOnConfigure[, tDependencies][, strPkgName, ...]
-- @param object Table to use as the base for the addon (optional)
-- @param strAddonName Name of the addon object to create
-- @param bOnConfigure Add a button to the options list and fire OnConfigure when clicked. Instead of issuing true, you can pass custom text for the button.
-- @param tDependencies List of dependencies for the addon
-- @param strPkgName List of packages to embed into the addon - requires the packages to be registered with Apollo.RegisterPackage and for the packages to support embedding
-- @usage
-- -- Create a simple addon
-- local MyAddon = Apollo.GetPackage("Gemini:Addon-1.1").tPackage:NewAddon("MyAddon", false)
--
-- -- Create a simple addon with a configure button with custom text
-- local MyAddon = Apollo.GetPackage("Gemini:Addon-1.1").tPackage:NewAddon("MyAddon", "Addon Options Button")
--
-- -- Create a simple addon with a configure button and a dependency on ChatLog / ChatLogEx
-- local MyAddon = Apollo.GetPackage("Gemini:Addon-1.1").tPackage:NewAddon("MyAddon", true, { "ChatLog", "ChatLogEx" })
--
-- -- Create an addon with a base object
-- local tAddonBase = { config = { ... some default settings ... }, ... }
-- local MyAddon = Apollo.GetPackage("Gemini:Addon-1.1").tPackage:NewAddon(tAddonBase, "MyAddon", false)
--
-- -- Create an addon with a base object with a dependency on ChatLog / ChatLogEx
-- local tAddonBase = { config = { ... some default settings ... }, ... }
-- local MyAddon = Apollo.GetPackage("Gemini:Addon-1.1").tPackage:NewAddon(tAddonBase, "MyAddon", false, { "ChatLog", "ChatLogEx" })
function GeminiAddon:NewAddon(oAddonOrName, ...)
local oAddon, strAddonName
local oNilOrName = nil
local i = 1
-- get addon name
if type(oAddonOrName) == "table" then
strAddonName = ...
oNilOrName = strAddonName
i = 2
else
strAddonName = oAddonOrName
end
if type(strAddonName) ~= "string" then
error(("Usage: NewAddon([object, ] strAddonName, bOnConfigure[, tDependencies][, strPkgName, ...]): 'strAddonName' - string expected got '%s'."):format(type(strAddonName)), 2)
end
if self.Addons[strAddonName] then
error(("Usage: NewAddon([object, ] strAddonName, bOnConfigure[, tDependencies][, strPkgName, ...]): 'strAddonName' - Addon '%s' already registered in GeminiAddon."):format(strAddonName), 2)
end
-- get configure state
local strConfigBtnName = select(i, ...)
i = i + 1
local bConfigure = (strConfigBtnName == true or type(strConfigBtnName) == "string")
if bConfigure then
strConfigBtnName = type(strConfigBtnName) == "boolean" and strAddonName or strConfigBtnName
else
strConfigBtnName = ""
end
-- get dependencies
local tDependencies
if select(i,...) and type(select(i, ...)) == "table" then
tDependencies = select(i, ...)
i = i + 1
else
tDependencies = {}
end
local oAddon = NewAddonProto(strAddonName, oAddonOrName, oNilOrName)
self:EmbedPackages(oAddon, select(i, ...))
-- Setup callbacks for the addon
-- Setup the OnLoad callback handler to initialize the addon
-- and delay enable the addon
oAddon.OnLoad = function(self)
local strName = self:GetName()
local tInitQueue = GeminiAddon.InitializeQueue[strName]
while #tInitQueue > 0 do
local oAddonToInit = tremove(tInitQueue, 1)
local retVal = GeminiAddon:InitializeAddon(oAddonToInit)
if retVal ~= nil then
Apollo.AddAddonErrorText(self, retVal)
return retVal
end
tinsert(GeminiAddon.EnableQueue[strName], oAddonToInit)
end
GeminiAddon.InitializeQueue[strName] = nil
self.___OnDelayEnable = function() DelayedEnable(self) end
-- Wait 0 seconds (hah?) this allows OnRestore to have occured
GeminiAddon.Timers[strName] = ApolloTimer.Create(0, false, "___OnDelayEnable",self)
end
-- Register with Apollo
Apollo.RegisterAddon(oAddon, bConfigure, strConfigBtnName, tDependencies)
return oAddon
end
-- Get the addon object by its name from the internal GeminiAddon addon registry
-- Throws an error if the addon object cannot be found (except if silent is set)
-- @param strAddonName the addon name registered with GeminiAddon
-- @param bSilent return nil if addon is not found instead of throwing an error
-- @usage
-- local MyAddon = Apollo.GetPackage("Gemini:Addon-1.1").tPackage:GetAddon("MyAddon")
function GeminiAddon:GetAddon(strAddonName, bSilent)
if not bSilent and not self.Addons[strAddonName] then
error(("Usage: GetAddon(strAddonName): 'strAddonName' - Cannot find an GeminiAddon called '%s'."):format(tostring(strAddonName)), 2)
end
return self.Addons[strAddonName]
end
--- Enable the addon
-- Used internally when the player has entered the world
--
-- **Note:** do not call this manually
-- @param oAddon addon object to enable
function GeminiAddon:EnableAddon(oAddon)
if type(oAddon) == "string" then
oAddon = self:GetAddon(oAddon)
end
local strAddonName = AddonToString(oAddon)
if self.AddonStatus[strAddonName] or not oAddon.EnabledState then
return false
end
-- set status first before calling OnEnable. this allows for Disabling of the addon in OnEnable.
self.AddonStatus[strAddonName] = true
safecall(oAddon.OnEnable, oAddon)
if self.AddonStatus[strAddonName] then
-- embed packages
local tEmbeds = self.Embeds[oAddon]
for i = 1, #tEmbeds do
local APkg = Apollo.GetPackage(tEmbeds[i])
local oPkg = APkg and APkg.tPackage or nil
if oPkg then
safecall(oPkg.OnEmbedEnable, oPkg, oAddon)
end
end
-- enable modules
local tModules = oAddon.OrderedModules
for i = 1, #tModules do
self:EnableAddon(tModules[i])
end
end
return self.AddonStatus[strAddonName]
end
function GeminiAddon:DisableAddon(oAddon)
if type(oAddon) == "string" then
oAddon = self:GetAddon(oAddon)
end
local strAddonName = AddonToString(oAddon)
if not self.AddonStatus[strAddonName] then
return false
end
-- set statuses first before calling OnDisable, this allows for aborting the disable in OnDisable.
self.AddonStatus[strAddonName] = false
safecall( oAddon.OnDisable, oAddon )
if not self.AddonStatus[strAddonName] then
local tEmbeds = self.Embeds[oAddon]
for i = 1, #tEmbeds do
local APkg = Apollo.GetPackage(tEmbeds[i])
local oPkg = APkg and APkg.tPackage or nil
if oPkg then
safecall(oPkg.OnEmbedDisable, oPkg, oAddon)
end
end
local tModules = oAddon.OrderedModules
for i = 1, #tModules do
self:DisableAddon(tModules[i])
end
end
return not self.AddonStatus[strAddonName]
end
--- Initialize the addon after creation
-- Used internally when OnLoad is called for the addon
--
-- **Note:** do not call this manually
-- @param oAddon addon object to initialize
function GeminiAddon:InitializeAddon(oAddon)
local _, retVal = safecall(oAddon.OnInitialize, oAddon)
if retVal ~= nil then return retVal end
local tEmbeds = self.Embeds[oAddon]
for i = 1, #tEmbeds do
local APkg = Apollo.GetPackage(tEmbeds[i])
local oPkg = APkg and APkg.tPackage or nil
if oPkg then
local _, retVal = safecall(oPkg.OnEmbedInitialize, oPkg, oAddon)
if retVal ~= nil then return retVal end
end
end
end
--- Embed packages into the specified addon
-- @paramsig oAddon[, strPkgName, ...]
-- @param oAddon The addon object to embed packages in
-- @param strPkgName List of packages to embed into the addon
function GeminiAddon:EmbedPackages(oAddon, ...)
for i = 1, select('#', ...) do
local strPkgName = select(i, ...)
self:EmbedPackage(oAddon, strPkgName, false, 4)
end
end
--- Embed a package into the specified addon
--
-- **Note:** This function is for internal use by :EmbedPackages
-- @paramsig strAddonName, strPkgName[, silent[, offset]]
-- @param oAddon addon object to embed the package in
-- @param strPkgName name of the package to embed
-- @param bSilent marks an embed to fail silently if the package doesn't exist (optional)
-- @param nOffset will push the error messages back to said offset, defaults to 2 (optional)
function GeminiAddon:EmbedPackage(oAddon, strPkgName, bSilent, nOffset)
local APkg = Apollo.GetPackage(strPkgName)
local oPkg = APkg and APkg.tPackage or nil
if not oPkg and not bSilent then
error(("Usage: EmbedPackage(oAddon, strPkgName, bSilent, nOffset): 'strPkgName' - Cannot find a package instance of '%s'."):format(tostring(strPkgName)), nOffset or 2)
elseif oPkg and type(oPkg.Embed) == "function" then
oPkg:Embed(oAddon)
tinsert(self.Embeds[oAddon], strPkgName)
return true
elseif oPkg then
error(("Usage: EmbedPackage(oAddon, strPkgName, bSilent, nOffset): Package '%s' is not Embed capable."):format(tostring(strPkgName)), nOffset or 2)
end
end
--- Return the specified module from an addon object.
-- Throws an error if the addon object cannot be found (except if silent is set)
-- @name //addon//:GetModule
-- @paramsig strModuleName[, bSilent]
-- @param strModuleName unique name of the module
-- @param bSilent if true, the module is optional, silently return nil if its not found (optional)
-- @usage
-- local MyModule = MyAddon:GetModule("MyModule")
function GetModule(self, strModuleName, bSilent)
if not self.Modules[strModuleName] and not bSilent then
error(("Usage: GetModule(strModuleName, bSilent): 'strModuleName' - Cannot find module '%s'."):format(tostring(strModuleName)), 2)
end
return self.Modules[strModuleName]
end
local function IsModuleTrue(self) return true end
--- Create a new module for the addon.
-- The new module can have its own embedded packages and/or use a module prototype to be mixed into the module.
-- @name //addon//:NewModule
-- @paramsig strName[, oPrototype|strPkgName[, strPkgName, ...]]
-- @param strName unique name of the module
-- @param oPrototype object to derive this module from, methods and values from this table will be mixed into the module (optional)
-- @param strPkgName List of packages to embed into the module
-- @usage
-- -- Create a module with some embeded packages
-- local MyModule = MyAddon:NewModule("MyModule", "PkgWithEmbed-1.0", "PkgWithEmbed2-1.0")
--
-- -- Create a module with a prototype
-- local oPrototype = { OnEnable = function(self) Print("OnEnable called!") end }
-- local MyModule = MyAddon:NewModule("MyModule", oPrototype, "PkgWithEmbed-1.0", "PkgWithEmbed2-1.0")
function NewModule(self, strName, oPrototype, ...)
if type(strName) ~= "string" then error(("Usage: NewModule(strName, [oPrototype, [strPkgName, strPkgName, strPkgName, ...]): 'strName' - string expected got '%s'."):format(type(strName)), 2) end
if type(oPrototype) ~= "string" and type(oPrototype) ~= "table" and type(oPrototype) ~= "nil" then error(("Usage: NewModule(strName, [oPrototype, [strPkgName, strPkgName, strPkgName, ...]): 'oPrototype' - table (oPrototype), string (strPkgName) or nil expected got '%s'."):format(type(oPrototype)), 2) end
if self.Modules[strName] then error(("Usage: NewModule(strName, [oPrototype, [strPkgName, strPkgName, strPkgName, ...]): 'strName' - Module '%s' already exists."):format(strName), 2) end
-- Go up the family tree to find the addon that started it all
local oCurrParent, oNextParent = self, self.Parent
while oNextParent do
oCurrParent = oNextParent
oNextParent = oCurrParent.Parent
end
local oModule = NewAddonProto(oCurrParent:GetName(), strformat("%s_%s", self.Name or tostring(self), strName))
oModule.IsModule = IsModuleTrue
oModule:SetEnabledState(self.DefaultModuleState)
oModule.ModuleName = strName
oModule.Parent = self
if type(oPrototype) == "string" then
GeminiAddon:EmbedPackages(oModule, oPrototype, ...)
else
GeminiAddon:EmbedPackages(oModule, ...)
end
GeminiAddon:EmbedPackages(oModule, unpack(self.DefaultModulePackages))
if not oPrototype or type(oPrototype) == "string" then
oPrototype = self.DefaultModulePrototype or nil
--self:_Log("Using Prototype type: " .. tostring(oPrototype))
end
if type(oPrototype) == "table" then
local mt = getmetatable(oModule)
mt.__index = oPrototype
setmetatable(oModule, mt)
end
safecall(self.OnModuleCreated, self, oModule)
self.Modules[strName] = oModule
tinsert(self.OrderedModules, oModule)
return oModule
end
--- returns the name of the addon or module without any prefix
-- @name //addon|module//:GetName
-- @paramsig
-- @usage
-- Print(MyAddon:GetName())
-- Print(MyAddon:GetModule("MyModule"):GetName())
function GetName(self)
return self.ModuleName or self.Name
end
-- Check if the addon is queued to be enabled
local function QueuedForInitialization(oAddon)
for strAddonName, tAddonList in pairs(GeminiAddon.EnableQueue) do
for nIndex = 1, #tAddonList do
if tAddonList[nIndex] == oAddon then
return true
end
end
end
return false
end
--- Enables the addon, if possible, returns true on success.
-- This internally calls GeminiAddon:EnableAddon(), thus dispatching the OnEnable callback
-- and enabling all modules on the addon (unless explicitly disabled)
-- :Enable() also sets the internal `enableState` variable to true.
-- @name //addon//:Enable
-- @paramsig
-- @usage
function Enable(self)
self:SetEnabledState(true)
if not QueuedForInitialization(self) then
return GeminiAddon:EnableAddon(self)
end
end
function Disable(self)
self:SetEnabledState(false)
return GeminiAddon:DisableAddon(self)
end
--- Enables the Module, if possible, return true or false depending on success.
-- Short-hand function that retrieves the module via `:GetModule` and calls `:Enable` on the module object.
-- @name //addon//:EnableModule
-- @paramsig name
-- @usage
-- -- Enable MyModule using :GetModule
-- local MyModule = MyAddon:GetModule("MyModule")
-- MyModule:Enable()
--
-- -- Enable MyModule using the short-hand
-- MyAddon:EnableModule("MyModule")
function EnableModule(self, strModuleName)
local oModule = self:GetModule(strModuleName)
return oModule:Enable()
end
--- Disables the Module, if possible, return true or false depending on success.
-- Short-hand function that retrieves the module via `:GetModule` and calls `:Disable` on the module object.
-- @name //addon//:DisableModule
-- @paramsig name
-- @usage
-- -- Disable MyModule using :GetModule
-- local MyModule = MyAddon:GetModule("MyModule")
-- MyModule:Disable()
--
-- -- Disable MyModule using the short-hand
-- local MyAddon:DisableModule("MyModule")
function DisableModule(self, strModuleName)
local oModule = self:GetModule(strModuleName)
return oModule:Disable()
end
--- Set the default packages to be mixed into all modules created by this object.
-- Note that you can only change the default module packages before any module is created.
-- @name //addon//:SetDefaultModulePackages
-- @paramsig strPkgName[, strPkgName, ...]
-- @param strPkgName List of Packages to embed into the addon
-- @usage
-- -- Create the addon object
-- local MyAddon = Apollo.GetPackage("Gemini:Addon-1.1").tPackage:NewAddon("MyAddon")
-- -- Configure default packages for modules
-- MyAddon:SetDefaultModulePackages("MyEmbeddablePkg-1.0")
-- -- Create a module
-- local MyModule = MyAddon:NewModule("MyModule")
function SetDefaultModulePackages(self, ...)
if next(self.Modules) then
error("Usage: SetDefaultModulePackages(...): cannot change the module defaults after a module has been registered.", 2)
end
self.DefaultModulePackages = {...}
end
--- Set the default state in which new modules are being created.
-- Note that you can only change the default state before any module is created.
-- @name //addon//:SetDefaultModuleState
-- @paramsig state
-- @param state Default state for new modules, true for enabled, false for disabled
-- @usage
-- -- Create the addon object
-- local MyAddon = Apollo.GetPackage("Gemini:Addon-1.1").tPackage:NewAddon("MyAddon")
-- -- Set the default state to "disabled"
-- MyAddon:SetDefaultModuleState(false)
-- -- Create a module and explicilty enable it
-- local MyModule = MyAddon:NewModule("MyModule")
-- MyModule:Enable()
function SetDefaultModuleState(self, bState)
if next(self.Modules) then
error("Usage: SetDefaultModuleState(bState): cannot change the module defaults after a module has been registered.", 2)
end
self.DefaultModuleState = bState
end
--- Set the default prototype to use for new modules on creation.
-- Note that you can only change the default prototype before any module is created.
-- @name //addon//:SetDefaultModulePrototype
-- @paramsig prototype
-- @param prototype Default prototype for the new modules (table)
-- @usage
-- -- Define a prototype
-- local prototype = { OnEnable = function(self) Print("OnEnable called!") end }
-- -- Set the default prototype
-- MyAddon:SetDefaultModulePrototype(prototype)
-- -- Create a module and explicitly Enable it
-- local MyModule = MyAddon:NewModule("MyModule")
-- MyModule:Enable()
-- -- should Print "OnEnable called!" now
-- @see NewModule
function SetDefaultModulePrototype(self, tPrototype)
if next(self.Modules) then
error("Usage: SetDefaultModulePrototype(tPrototype): cannot change the module defaults after a module has been registered.", 2)
end
if type(tPrototype) ~= "table" then
error(("Usage: SetDefaultModulePrototype(tPrototype): 'tPrototype' - table expected got '%s'."):format(type(tPrototype)), 2)
end
self.DefaultModulePrototype = tPrototype
end
--- Set the state of an addon or module
-- This should only be called before any enabling actually happened, e.g. in/before OnInitialize.
-- @name //addon|module//:SetEnabledState
-- @paramsig state
-- @param state the state of an addon or module (enabled = true, disabled = false)
function SetEnabledState(self, bState)
self.EnabledState = bState
end
--- Return an iterator of all modules associated to the addon.
-- @name //addon//:IterateModules
-- @paramsig
-- @usage
-- -- Enable all modules
-- for strModuleName, oModule in MyAddon:IterateModules() do
-- oModule:Enable()
-- end
local function IterateModules(self) return pairs(self.Modules) end
-- Returns an iterator of all embeds in the addon
-- @name //addon//:IterateEmbeds
-- @paramsig
local function IterateEmbeds(self) return pairs(GeminiAddon.Embeds[self]) end
--- Query the enabledState of an addon.
-- @name //addon//:IsEnabled
-- @paramsig
-- @usage
-- if MyAddon:IsEnabled() then
-- MyAddon:Disable()
-- end
local function IsEnabled(self) return self.EnabledState end
local function IsModule(self) return false end
function AddonLog(self, t)
self._DebugLog = self._DebugLog or {}
tinsert(self._DebugLog, { what = t, when = ostime() })
end
local tMixins = {
NewModule = NewModule,
GetModule = GetModule,
Enable = Enable,
Disable = Disable,
EnableModule = EnableModule,
DisableModule = DisableModule,
IsEnabled = IsEnabled,
SetDefaultModulePackages = SetDefaultModulePackages,
SetDefaultModuleState = SetDefaultModuleState,
SetDefaultModulePrototype = SetDefaultModulePrototype,
SetEnabledState = SetEnabledState,
IterateModules = IterateModules,
IterateEmbeds = IterateEmbeds,
GetName = GetName,
-- _Log = AddonLog,
DefaultModuleState = true,
EnabledState = true,
IsModule = IsModule,
}
-- Embed( target )
-- target (object) - target GeminiAddon object to embed in
--
-- **Note:** This is for internal use only. Do not call manually
function Embed(target)
for k, v in pairs(tMixins) do
target[k] = v
end
end
--- Get an iterator over all registered addons.
-- @usage
-- -- Print a list of all registered GeminiAddons
-- for name, addon in GeminiAddon:IterateAddons() do
-- Print("Addon: " .. name)
-- end
function GeminiAddon:IterateAddons() return pairs(self.Addons) end
--- Get an iterator over the internal status registry.
-- @usage
-- -- Print a list of all enabled addons
-- for name, status in GeminiAddon:IterateAddonStatus() do
-- if status then
-- Print("EnabledAddon: " .. name)
-- end
-- end
function GeminiAddon:IterateAddonStatus() return pairs(self.AddonStatus) end
function GeminiAddon:OnLoad() end
function GeminiAddon:OnDependencyError(strDep, strError) return false end
Apollo.RegisterPackage(GeminiAddon, MAJOR, MINOR, {})
| mit |
RunAwayDSP/darkstar | scripts/globals/weaponskills/true_strike.lua | 10 | 1507 | -----------------------------------
-- True Strike
-- Club weapon skill
-- Skill level: 175
-- Deals params.critical damage. params.accuracy varies with TP.
-- 100% Critical Hit Rate. Has a substantial accuracy penalty at 100TP. http://www.bg-wiki.com/bg/True_Strike
-- Will stack with Sneak Attack.
-- Aligned with the Breeze Gorget & Thunder Gorget.
-- Aligned with the Breeze Belt & Thunder Belt.
-- Element: None
-- Modifiers: STR:100%
-- 100%TP 200%TP 300%TP
-- 1.00 1.00 1.00
-----------------------------------
require("scripts/globals/status")
require("scripts/globals/settings")
require("scripts/globals/weaponskills")
-----------------------------------
function onUseWeaponSkill(player, target, wsID, tp, primary, action, taChar)
local params = {}
params.numHits = 1
params.ftp100 = 1 params.ftp200 = 1 params.ftp300 = 1
params.str_wsc = 0.5 params.dex_wsc = 0.0 params.vit_wsc = 0.0 params.agi_wsc = 0.0 params.int_wsc = 0.0 params.mnd_wsc = 0.0 params.chr_wsc = 0.0
params.crit100 = 1.0 params.crit200 = 1.0 params.crit300 = 1.0
params.canCrit = true
params.acc100 = 0.5 params.acc200= 0.7 params.acc300= 1
params.atk100 = 2; params.atk200 = 2; params.atk300 = 2;
if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then
params.str_wsc = 1.0
end
local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, wsID, params, tp, action, primary, taChar)
return tpHits, extraHits, criticalHit, damage
end
| gpl-3.0 |
lichtl/darkstar | scripts/zones/Aht_Urhgan_Whitegate/npcs/Hadahda.lua | 14 | 1047 | -----------------------------------
-- Area: Aht Urhgan Whitegate
-- NPC: Hadahda
-- Type: Standard NPC
-- @pos -112.029 -6.999 -66.114 50
-----------------------------------
package.loaded["scripts/zones/Aht_Urhgan_Whitegate/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Aht_Urhgan_Whitegate/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x0206);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
scscgit/scsc_wildstar_addons | twinkieplates/TwinkiePlates.lua | 1 | 83326 | -----------------------------------------------------------------------------------------------
-- Client Lua Script for TwinkiePlates
-- Copyright (c) NCsoft. All rights reserved
-----------------------------------------------------------------------------------------------
require "Window"
require "ChallengesLib"
require "Unit"
require "GameLib"
require "Apollo"
require "PathMission"
require "Quest"
require "Episode"
require "math"
require "string"
require "DialogSys"
require "PublicEvent"
require "PublicEventObjective"
require "CommunicatorLib"
require "GroupLib"
require "PlayerPathLib"
require "bit32"
local TwinkiePlates = {}
local E_VULNERABILITY = Unit.CodeEnumCCState.Vulnerability
local F_PATH = 0
local F_QUEST = 1
local F_CHALLENGE = 2
local F_FRIEND = 3
local F_RIVAL = 4
local F_PVP = 4
local F_AGGRO = 5
local F_CLEANSE = 6
local F_LOW_HP = 7
local F_GROUP = 8
local F_NAMEPLATE = 0
local F_HEALTH = 1
local F_HEALTH_TEXT = 2
local F_CLASS = 3
local F_LEVEL = 4
local F_TITLE = 5
local F_GUILD = 6
local F_CASTING_BAR = 7
local F_CC_BAR = 8
local F_ARMOR = 9
local F_BUBBLE = 10
local N_NEVER_ENABLED = 0
local N_ENABLED_IN_COMBAT = 1
local N_ALWAYS_OUT_OF_COMBAT = 2
local N_ALWAYS_ENABLED = 3
local _ccWhiteList =
{
[Unit.CodeEnumCCState.Blind] = "Blind",
[Unit.CodeEnumCCState.Disarm] = "Disarm",
[Unit.CodeEnumCCState.Disorient] = "Disorient",
[Unit.CodeEnumCCState.Fear] = "Fear",
[Unit.CodeEnumCCState.Knockdown] = "Knockdown",
[Unit.CodeEnumCCState.Subdue] = "Subdue",
[Unit.CodeEnumCCState.Stun] = "Stun",
[Unit.CodeEnumCCState.Root] = "Root",
[Unit.CodeEnumCCState.Tether] = "Tether",
[Unit.CodeEnumCCState.Vulnerability] = "MoO",
}
local _tDisplayHideExceptionUnitNames =
{
["NyanPrime"] = false, -- Hidden
["Cactoid"] = true, -- Visible
["Spirit of the Darned"] = true,
["Wilderrun Trap"] = true,
["Essence of Logic"] = true,
["Teleporter Generator"] = false,
["Firewall"] = false,
["Engineer2 - Hostile Invisible Unit for Fields (1.2m Radius)"] = false,
["Spiritmother Selene's Echo"] = true,
["Data Devourer Spawner"] = false,
["Spore Cloud"] = false,
}
local _color = ApolloColor.new
local _tFromPlayerClassToIcon =
{
[GameLib.CodeEnumClass.Esper] = "NPrimeNameplates_Sprites:IconEsper",
[GameLib.CodeEnumClass.Medic] = "NPrimeNameplates_Sprites:IconMedic",
[GameLib.CodeEnumClass.Stalker] = "NPrimeNameplates_Sprites:IconStalker",
[GameLib.CodeEnumClass.Warrior] = "NPrimeNameplates_Sprites:IconWarrior",
[GameLib.CodeEnumClass.Engineer] = "NPrimeNameplates_Sprites:IconEngineer",
[GameLib.CodeEnumClass.Spellslinger] = "NPrimeNameplates_Sprites:IconSpellslinger",
}
local _tFromNpcRankToIcon =
{
[Unit.CodeEnumRank.Elite] = "NPrimeNameplates_Sprites:icon_6_elite",
[Unit.CodeEnumRank.Superior] = "NPrimeNameplates_Sprites:icon_5_superior",
[Unit.CodeEnumRank.Champion] = "NPrimeNameplates_Sprites:icon_4_champion",
[Unit.CodeEnumRank.Standard] = "NPrimeNameplates_Sprites:icon_3_standard",
[Unit.CodeEnumRank.Minion] = "NPrimeNameplates_Sprites:icon_2_minion",
[Unit.CodeEnumRank.Fodder] = "NPrimeNameplates_Sprites:icon_1_fodder",
}
local _dispColor =
{
[Unit.CodeEnumDisposition.Neutral] = _color("FFFFBC55"),
[Unit.CodeEnumDisposition.Hostile] = _color("FFFA394C"),
[Unit.CodeEnumDisposition.Friendly] = _color("FF7DAF29"),
[Unit.CodeEnumDisposition.Unknown] = _color("FFFFFFFF"),
}
local _tFromSettingToColor =
{
Self = _color("FF7DAF29"),
Target = _color("xkcdLightMagenta"),
FriendlyPc = _color("FF7DAF29"),
FriendlyNpc = _color("xkcdKeyLime"),
NeutralPc = _color("FFFFBC55"),
NeutralNpc = _color("xkcdDandelion"),
HostilePc = _color("xkcdLipstickRed"),
HostileNpc = _color("FFFA394C"),
Group = _color("FF7DAF29"), -- FF597CFF
Harvest = _color("FFFFFFFF"),
Other = _color("FFFFFFFF"),
Hidden = _color("FFFFFFFF"),
NoAggro = _color("FF55FAFF"),
Cleanse = _color("FFAF40E1"),
LowHpFriendly = _color("FF0000FF"),
LowHpNotFriendly = _color("FF55FAFF"),
}
local _paths =
{
[0] = "Soldier",
[1] = "Settler",
[2] = "Scientist",
[3] = "Explorer",
}
local _tUiElements =
{
["Nameplates"] = {
["Self"] = "NameplatesSelf",
["Target"] = "NameplatesTarget",
["Group"] = "NameplatesGroup",
["FriendlyPc"] = "NameplatesFriendlyPc",
["FriendlyNpc"] = "NameplatesFriendlyNpc",
["NeutralPc"] = "NameplatesNeutralPc",
["NeutralNpc"] = "NameplatesNeutralNpc",
["HostilePc"] = "NameplatesHostilePc",
["HostileNpc"] = "NameplatesHostileNpc",
["Other"] = "NameplatesOther"
},
["Health"] = {
["Self"] = "HealthSelf",
["Target"] = "HealthTarget",
["Group"] = "HealthGroup",
["FriendlyPc"] = "HealthFriendlyPc",
["FriendlyNpc"] = "HealthFriendlyNpc",
["NeutralPc"] = "HealthNeutralPc",
["NeutralNpc"] = "HealthNeutralNpc",
["HostilePc"] = "HealthHostilePc",
["HostileNpc"] = "HealthHostileNpc",
["Other"] = "HealthOther"
},
["HealthText"] = {
["Self"] = "HealthTextSelf",
["Target"] = "HealthTextTarget",
["Group"] = "HealthTextGroup",
["FriendlyPc"] = "HealthTextFriendlyPc",
["FriendlyNpc"] = "HealthTextFriendlyNpc",
["NeutralPc"] = "HealthTextNeutralPc",
["NeutralNpc"] = "HealthTextNeutralNpc",
["HostilePc"] = "HealthTextHostilePc",
["HostileNpc"] = "HealthTextHostileNpc",
["Other"] = "HealthTexOther"
},
["Class"] = {
["Self"] = "ClassSelf",
["Target"] = "ClassTarget",
["Group"] = "ClassGroup",
["FriendlyPc"] = "ClassFriendlyPc",
["FriendlyNpc"] = "ClassFriendlyNpc",
["NeutralPc"] = "ClassNeutralPc",
["NeutralNpc"] = "ClassNeutralNpc",
["HostilePc"] = "ClassHostilePc",
["HostileNpc"] = "ClassHostileNpc",
["Other"] = "ClassOther"
},
["Level"] = {
["Self"] = "LevelSelf",
["Target"] = "LevelTarget",
["Group"] = "LevelGroup",
["FriendlyPc"] = "LevelFriendlyPc",
["FriendlyNpc"] = "LevelFriendlyNpc",
["NeutralPc"] = "LevelNeutralPc",
["NeutralNpc"] = "LevelNeutralNpc",
["HostilePc"] = "LevelHostilePc",
["HostileNpc"] = "LevelHostileNpc",
["Other"] = "LevelOther"
},
["Title"] = {
["Self"] = "TitleSelf",
["Target"] = "TitleTarget",
["Group"] = "TitleGroup",
["FriendlyPc"] = "TitleFriendlyPc",
["FriendlyNpc"] = "TitleFriendlyNpc",
["NeutralPc"] = "TitleNeutralPc",
["NeutralNpc"] = "TitleNeutralNpc",
["HostilePc"] = "TitleHostilePc",
["HostileNpc"] = "TitleHostileNpc",
["Other"] = "TitleOther"
},
["Guild"] = {
["Self"] = "GuildSelf",
["Target"] = "GuildTarget",
["Group"] = "GuildGroup",
["FriendlyPc"] = "GuildFriendlyPc",
["FriendlyNpc"] = "GuildFriendlyNpc",
["NeutralPc"] = "GuildNeutralPc",
["NeutralNpc"] = "GuildNeutralNpc",
["HostilePc"] = "GuildHostilePc",
["HostileNpc"] = "GuildHostileNpc",
["Other"] = "GuildOther"
},
["CastingBar"] = {
["Self"] = "CastingBarSelf",
["Target"] = "CastingBarTarget",
["Group"] = "CastingBarGroup",
["FriendlyPc"] = "CastingBarFriendlyPc",
["FriendlyNpc"] = "CastingBarFriendlyNpc",
["NeutralPc"] = "CastingBarNeutralPc",
["NeutralNpc"] = "CastingBarNeutralNpc",
["HostilePc"] = "CastingBarHostilePc",
["HostileNpc"] = "CastingBarHostileNpc",
["Other"] = "CastingBarOther"
},
["CCBar"] = {
["Self"] = "CCBarSelf",
["Target"] = "CCBarTarget",
["Group"] = "CCBarGroup",
["FriendlyPc"] = "CCBarFriendlyPc",
["FriendlyNpc"] = "CCBarFriendlyNpc",
["NeutralPc"] = "CCBarNeutralPc",
["NeutralNpc"] = "CCBarNeutralNpc",
["HostilePc"] = "CCBarHostilePc",
["HostileNpc"] = "CCBarHostileNpc",
["Other"] = "CCBarOther"
},
["Armor"] = {
["Self"] = "ArmorSelf",
["Target"] = "ArmorTarget",
["Group"] = "ArmorGroup",
["FriendlyPc"] = "ArmorFriendlyPc",
["FriendlyNpc"] = "ArmorFriendlyNpc",
["NeutralPc"] = "ArmorNeutralPc",
["NeutralNpc"] = "ArmorNeutralNpc",
["HostilePc"] = "ArmorHostilePc",
["HostileNpc"] = "ArmorHostileNpc",
["Other"] = "ArmorOther"
},
["TextBubbleFade"] = {
["Self"] = "TextBubbleFadeSelf",
["Target"] = "TextBubbleFadeTarget",
["Group"] = "TextBubbleFadeGroup",
["FriendlyPc"] = "TextBubbleFadeFriendlyPc",
["FriendlyNpc"] = "TextBubbleFadeFriendlyNpc",
["NeutralPc"] = "TextBubbleFadeNeutralPc",
["NeutralNpc"] = "TextBubbleFadeNeutralNpc",
["HostilePc"] = "TextBubbleFadeHostilePc",
["HostileNpc"] = "TextBubbleFadeHostileNpc",
["Other"] = "TextBubbleOther"
},
}
local _tUnitCategories =
{
"Self",
"Target",
"Group",
"FriendlyPc",
"FriendlyNpc",
"NeutralPc",
"NeutralNpc",
"HostilePc",
"HostileNpc",
"Other",
}
local _matrixButtonSprites =
{
[N_NEVER_ENABLED] = "MatrixOff",
[N_ENABLED_IN_COMBAT] = "MatrixInCombat",
[N_ALWAYS_OUT_OF_COMBAT] = "MatrixOutOfCombat",
[N_ALWAYS_ENABLED] = "MatrixOn",
}
local _asbl =
{
["Chair"] = true,
["CityDirections"] = true,
["TradeskillNode"] = true,
}
local _flags =
{
opacity = 1,
contacts = 1,
}
local _fontPrimary =
{
[1] = { font = "CRB_Header9_O", height = 20 },
[2] = { font = "CRB_Header10_O", height = 21 },
[3] = { font = "CRB_Header11_O", height = 22 },
[4] = { font = "CRB_Header12_O", height = 24 },
[5] = { font = "CRB_Header14_O", height = 28 },
[6] = { font = "CRB_Header16_O", height = 34 },
}
local _fontSecondary =
{
[1] = { font = "CRB_Interface9_O", height = 20 },
[2] = { font = "CRB_Interface10_O", height = 21 },
[3] = { font = "CRB_Interface11_O", height = 22 },
[4] = { font = "CRB_Interface12_O", height = 24 },
[5] = { font = "CRB_Interface14_O", height = 28 },
[6] = { font = "CRB_Interface16_O", height = 34 },
}
local _tDispositionToString = {
[Unit.CodeEnumDisposition.Hostile] = { ["Pc"] = "HostilePc", ["Npc"] = "HostileNpc" },
[Unit.CodeEnumDisposition.Neutral] = { ["Pc"] = "NeutralPc", ["Npc"] = "NeutralNpc" },
[Unit.CodeEnumDisposition.Friendly] = { ["Pc"] = "FriendlyPc", ["Npc"] = "FriendlyNpc" },
[Unit.CodeEnumDisposition.Unknown] = { ["Pc"] = "Hidden", ["Npc"] = "Hidden" },
}
local _tUiElementToFlag = {
["Nameplates"] = F_NAMEPLATE,
["Health"] = F_HEALTH,
["HealthText"] = F_HEALTH_TEXT,
["Class"] = F_CLASS,
["Level"] = F_LEVEL,
["Title"] = F_TITLE,
["Guild"] = F_GUILD,
["CastingBar"] = F_CASTING_BAR,
["CCBar"] = F_CC_BAR,
["Armor"] = F_ARMOR,
["TextBubbleFade"] = F_BUBBLE,
}
local _tPvpZones = {
[4456] = true, -- The Slaughterdome
[4457] = true, -- The Slaughterdome
[4460] = true, -- The Slaughterdome
[478] = true, -- The Cryoplex
[4471] = true, -- Walatiki Temple
[2176] = true, -- Walatiki Temple
[2193] = false, -- Test
[2177] = true, -- Halls of the Bloodsworn
[4472] = true, -- Halls of the Bloodsworn
[103] = true, -- Daggerstone Pass
}
local _unitPlayer
local _playerPath
local _playerPos
local _bIsPlayerBlinded
local _tTargetNameplate
local _floor = math.floor
local _min = math.min
local _max = math.max
local _ipairs = ipairs
local _pairs = pairs
local _tableInsert = table.insert
local _tableRemove = table.remove
local _next = next
local _type = type
local _weaselStr = String_GetWeaselString
local _strLen = string.len
local _textWidth = Apollo.GetTextWidth
local _or = bit32.bor
local _lshift = bit32.lshift
local _and = bit32.band
local _not = bit32.bnot
local _xor = bit32.bxor
local _wndConfigUi
local _tSettings = {}
local _count = 0
local _cycleSize = 25
local _iconPixie =
{
strSprite = "",
cr = white,
loc =
{
fPoints = { 0, 0, 1, 1 },
nOffsets = { 0, 0, 0, 0 }
},
}
local _tTargetPixie =
{
strSprite = "BK3:sprHolo_Accent_Rounded",
cr = white,
loc =
{
fPoints = { 0.5, 0.5, 0.5, 0.5 },
nOffsets = { 0, 0, 0, 0 }
},
}
-------------------------------------------------------------------------------
function TwinkiePlates:new(o)
o = o or {}
setmetatable(o, self)
self.__index = self
return o
end
function TwinkiePlates:Init()
Apollo.RegisterAddon(self, true)
end
function TwinkiePlates:OnLoad()
self.tNameplates = {}
self.pool = {}
self.buffer = {}
self.challenges = ChallengesLib.GetActiveChallengeList()
Apollo.RegisterEventHandler("NextFrame", "OnDebuggerUnit", self)
Apollo.RegisterSlashCommand("tp", "OnConfigure", self)
Apollo.RegisterEventHandler("ShowTwinkiePlatesConfigurationWnd", "OnConfigure", self)
Apollo.RegisterEventHandler("InterfaceMenuListHasLoaded", "OnInterfaceMenuListHasLoaded", self)
Apollo.RegisterEventHandler("NextFrame", "OnFrame", self)
Apollo.RegisterEventHandler("ChangeWorld", "OnChangeWorld", self)
Apollo.RegisterEventHandler("SubZoneChanged", "OnSubZoneChanged", self)
Apollo.RegisterEventHandler("UnitCreated", "OnUnitCreated", self)
Apollo.RegisterEventHandler("UnitDestroyed", "OnUnitDestroyed", self)
Apollo.RegisterEventHandler("UnitTextBubbleCreate", "OnTextBubble", self)
Apollo.RegisterEventHandler("UnitTextBubblesDestroyed", "OnTextBubble", self)
Apollo.RegisterEventHandler("TargetUnitChanged", "OnTargetUnitChanged", self)
Apollo.RegisterEventHandler("UnitActivationTypeChanged", "OnUnitActivationTypeChanged", self)
Apollo.RegisterEventHandler("UnitLevelChanged", "OnUnitLevelChanged", self)
Apollo.RegisterEventHandler("PlayerTitleChange", "OnPlayerMainTextChanged", self)
Apollo.RegisterEventHandler("UnitNameChanged", "OnUnitMainTextChanged", self)
Apollo.RegisterEventHandler("UnitTitleChanged", "OnUnitMainTextChanged", self)
Apollo.RegisterEventHandler("GuildChange", "OnPlayerMainTextChanged", self)
Apollo.RegisterEventHandler("UnitGuildNameplateChanged", "OnUnitMainTextChanged", self)
Apollo.RegisterEventHandler("UnitMemberOfGuildChange", "OnUnitMainTextChanged", self)
-- Apollo.RegisterEventHandler("UnitGibbed", "OnUnitGibbed", self)
Apollo.RegisterEventHandler("CombatLogDeath", "OnCombatLogDeath", self)
Apollo.RegisterEventHandler("CombatLogResurrect", "OnCombatLogResurrect", self)
-- Apollo.RegisterEventHandler("CharacterFlagsUpdated", "OnCharacterFlagsUpdated", self)
Apollo.RegisterEventHandler("ApplyCCState", "OnCCStateApplied", self)
-- Apollo.RegisterEventHandler("UnitGroupChanged", "OnGroupUpdated", self)
Apollo.RegisterEventHandler("ChallengeUnlocked", "OnChallengeUnlocked", self)
-- Too unreliable
-- Apollo.RegisterEventHandler("UnitEnteredCombat", "OnUnitCombatStateChanged", self)
Apollo.RegisterEventHandler("UnitPvpFlagsChanged", "OnUnitPvpFlagsChanged", self)
Apollo.RegisterEventHandler("FriendshipAdd", "OnFriendshipChanged", self)
Apollo.RegisterEventHandler("FriendshipRemove", "OnFriendshipChanged", self)
self.nameplacer = Apollo.GetAddon("Nameplacer")
if (self.nameplacer) then
Apollo.RegisterEventHandler("Nameplacer_UnitNameplatePositionChanged", "OnNameplatePositionSettingChanged", self)
end
self.perspectivePlates = Apollo.GetAddon("PerspectivePlates")
self.xmlDoc = XmlDoc.CreateFromFile("TwinkiePlates.xml")
Apollo.LoadSprites("TwinkiePlates_Sprites.xml")
end
function TwinkiePlates:OnSave(p_type)
if p_type ~= GameLib.CodeEnumAddonSaveLevel.Account then return end
return _tSettings
end
function TwinkiePlates:OnRestore(p_type, p_savedData)
if p_type ~= GameLib.CodeEnumAddonSaveLevel.Account then return end
_tSettings = p_savedData
self:CheckMatrixIntegrity()
end
function TwinkiePlates:OnFriendshipChanged()
_flags.contacts = 1
end
function TwinkiePlates:OnNameClick(wndHandler, wndCtrl, nClick)
local l_unit = wndCtrl:GetData()
if (l_unit ~= nil and nClick == 0) then
GameLib.SetTargetUnit(l_unit)
return true
end
end
function TwinkiePlates:OnChangeWorld()
_unitPlayer = nil
if (_tTargetNameplate ~= nil) then
if (_tTargetNameplate.targetMark ~= nil) then
_tTargetNameplate.targetMark:Destroy()
end
_tTargetNameplate.wndNameplate:Destroy()
_tTargetNameplate = nil
end
end
function TwinkiePlates:UpdateCurrentZoneInfo(nZoneId)
-- local tCurrentZone = GameLib.GetCurrentZoneMap()
self.nCurrentZoneId = nZoneId
end
function TwinkiePlates:OnUnitCombatStateChanged(unit, bIsInCombat)
if (unit == nil) then return end
local tNameplate = self.tNameplates[unit:GetId()]
self:SetCombatState(tNameplate, bIsInCombat)
if (_unitPlayer ~= nil and _unitPlayer:GetTarget() == unit) then
self:SetCombatState(_tTargetNameplate, bIsInCombat)
end
end
function TwinkiePlates:OnGroupUpdated(unitNameplateOwner)
if (unitNameplateOwner == nil) then return end
local tNameplate = self.tNameplates[unitNameplateOwner:GetId()]
if (tNameplate ~= nil) then
local strPcOrNpc = tNameplate.bIsPlayer and "Pc" or "Npc"
tNameplate.bIsInGroup = unitNameplateOwner:IsInYourGroup()
tNameplate.strUnitCategory = tNameplate.bIsInGroup and "Group" or _tDispositionToString[tNameplate.eDisposition][strPcOrNpc]
end
end
function TwinkiePlates:OnUnitPvpFlagsChanged(unit)
if (not unit) then return end
local bPvpFlagged = self:IsPvpFlagged(unit)
local tNameplate = self.tNameplates[unit:GetId()]
-- Update unit nameplate
if (tNameplate) then
tNameplate.bIsPvpFlagged = bPvpFlagged
end
-- Update target nameplate as well
if (_tTargetNameplate and _unitPlayer:GetTarget() == unit) then
_tTargetNameplate.bIsPvpFlagged = bPvpFlagged
end
end
function TwinkiePlates:OnSubZoneChanged(nZoneId, strSubZoneName)
-- Print("TwinkiePlates:OnSubZoneChanged; Current zone: " .. tostring(nZoneId))
self:UpdateCurrentZoneInfo(nZoneId)
end
function TwinkiePlates:InitNameplate(unitNameplateOwner, tNameplate, bIsTargetNameplate)
tNameplate = tNameplate or {}
bIsTargetNameplate = bIsTargetNameplate or false
local bIsCharacter = unitNameplateOwner:IsACharacter()
tNameplate.unitNameplateOwner = unitNameplateOwner
tNameplate.unitClassID = bIsCharacter and unitNameplateOwner:GetClassId() or unitNameplateOwner:GetRank()
tNameplate.bPet = self:IsPet(unitNameplateOwner)
tNameplate.eDisposition = self:GetDispositionTo(unitNameplateOwner, _unitPlayer)
tNameplate.bIsPlayer = bIsCharacter
tNameplate.bForcedHideDisplayToggle = _tDisplayHideExceptionUnitNames[unitNameplateOwner:GetName()]
tNameplate.strUnitCategory = self:GetUnitCategoryType(unitNameplateOwner)
tNameplate.color = "FFFFFFFF"
tNameplate.bIsTargetNameplate = bIsTargetNameplate
tNameplate.bHasHealth = self:HasHealth(unitNameplateOwner)
if (bIsTargetNameplate) then
local l_source = self.tNameplates[unitNameplateOwner:GetId()]
tNameplate.nCcActiveId = l_source and l_source.nCcActiveId or -1
tNameplate.nCcNewId = l_source and l_source.nCcNewId or -1
tNameplate.nCcDuration = l_source and l_source.nCcDuration or 0
tNameplate.nCcDurationMax = l_source and l_source.nCcDurationMax or 0
else
tNameplate.nCcActiveId = -1
tNameplate.nCcNewId = -1
tNameplate.nCcDuration = 0
tNameplate.nCcDurationMax = 0
end
tNameplate.bRefreshHealthShieldBar = false
tNameplate.bIsLowHealth = false
tNameplate.nCurrHealth = tNameplate.bHasHealth and tNameplate.unitNameplateOwner:GetHealth() or nil
tNameplate.healthy = false
tNameplate.prevArmor = nil
tNameplate.levelWidth = 1
tNameplate.iconFlags = -1
tNameplate.nNonCombatStateFlags = -1
tNameplate.nMatrixFlags = -1
tNameplate.bRearrange = false
tNameplate.bIsUnitOutOfRange = true
tNameplate.bIsOccluded = unitNameplateOwner:IsOccluded()
tNameplate.bIsInCombat = self:IsInCombat(tNameplate)
tNameplate.bIsInGroup = unitNameplateOwner:IsInYourGroup()
tNameplate.isMounted = unitNameplateOwner:IsMounted()
tNameplate.bIsObjective = false
tNameplate.bIsPvpFlagged = unitNameplateOwner:IsPvpFlagged()
tNameplate.bHasActivationState = self:HasActivationState(unitNameplateOwner)
tNameplate.bHasShield = unitNameplateOwner:GetShieldCapacityMax() ~= nil and unitNameplateOwner:GetShieldCapacityMax() ~= 0
local l_zoomSliderW = _tSettings["SliderBarScale"] / 2
local l_zoomSliderH = _tSettings["SliderBarScale"] / 10
local l_fontSize = _tSettings["SliderFontSize"]
local l_font = _tSettings["ConfigAlternativeFont"] and _fontSecondary or _fontPrimary
if (tNameplate.wndNameplate == nil) then
-- Print("TwinkiePlates: InitNameplate; New form!")
tNameplate.wndNameplate = Apollo.LoadForm(self.xmlDoc, "Nameplate", "InWorldHudStratum", self)
tNameplate.containerTop = tNameplate.wndNameplate:FindChild("ContainerTop")
tNameplate.wndContainerMain = tNameplate.wndNameplate:FindChild("ContainerMain")
tNameplate.containerIcons = tNameplate.wndNameplate:FindChild("ContainerIcons")
tNameplate.wndUnitNameText = tNameplate.wndNameplate:FindChild("TextUnitName")
tNameplate.textUnitGuild = tNameplate.wndNameplate:FindChild("TextUnitGuild")
tNameplate.textUnitLevel = tNameplate.wndNameplate:FindChild("TextUnitLevel")
tNameplate.wndContainerCc = tNameplate.wndNameplate:FindChild("ContainerCC")
tNameplate.containerCastBar = tNameplate.wndNameplate:FindChild("ContainerCastBar")
tNameplate.wndCastBar = tNameplate.containerCastBar:FindChild("BarCasting")
tNameplate.wndClassRankIcon = tNameplate.wndNameplate:FindChild("IconUnit")
tNameplate.iconArmor = tNameplate.wndNameplate:FindChild("IconArmor")
tNameplate.wndHealthProgressBar = tNameplate.wndNameplate:FindChild("BarHealth")
tNameplate.wndHealthText = tNameplate.wndNameplate:FindChild("TextHealth")
tNameplate.wndShieldBar = tNameplate.wndNameplate:FindChild("BarShield")
tNameplate.wndAbsorbBar = tNameplate.wndNameplate:FindChild("BarAbsorb")
tNameplate.wndCcBar = tNameplate.wndNameplate:FindChild("BarCC")
tNameplate.wndCleanseFrame = tNameplate.wndNameplate:FindChild("CleanseFrame")
tNameplate.wndCleanseFrame:SetBGColor(_tFromSettingToColor["Cleanse"])
if (not _tSettings["ConfigBarIncrements"]) then
tNameplate.wndHealthProgressBar:SetFullSprite("Bar_02")
tNameplate.wndHealthProgressBar:SetFillSprite("Bar_02")
tNameplate.wndAbsorbBar:SetFullSprite("Bar_02")
tNameplate.wndAbsorbBar:SetFillSprite("Bar_02")
end
tNameplate.wndCastBar:SetMax(100)
self:InitNameplateVerticalOffset(tNameplate)
self:InitAnchoring(tNameplate)
local l_fontH = l_font[l_fontSize].height
local l_fontGuild = l_fontSize > 1 and l_fontSize - 1 or l_fontSize
tNameplate.iconArmor:SetFont(l_font[l_fontSize].font)
tNameplate.containerTop:SetAnchorOffsets(0, 0, 0, l_font[l_fontSize].height * 0.8)
tNameplate.wndClassRankIcon:SetAnchorOffsets(-l_fontH * 0.9, 0, l_fontH * 0.1, 0)
tNameplate.wndUnitNameText:SetFont(l_font[l_fontSize].font)
tNameplate.textUnitLevel:SetFont(l_font[l_fontSize].font)
tNameplate.textUnitGuild:SetFont(l_font[l_fontGuild].font)
tNameplate.wndHealthText:SetFont(l_font[l_fontGuild].font)
-- tNameplate.textUnitGuild:SetAnchorOffsets(0, 0, 0, l_font[l_fontGuild].height * 0.9)
tNameplate.containerCastBar:SetFont(l_font[l_fontSize].font)
tNameplate.wndContainerCc:SetFont(l_font[l_fontSize].font)
tNameplate.containerCastBar:SetAnchorOffsets(0, 0, 0, (l_font[l_fontSize].height * 0.75) + l_zoomSliderH)
tNameplate.wndContainerCc:SetAnchorOffsets(0, 0, 0, (l_font[l_fontSize].height * 0.75) + l_zoomSliderH)
tNameplate.wndContainerMain:SetFont(l_font[l_fontSize].font)
tNameplate.wndCastBar:SetAnchorOffsets(-l_zoomSliderW, (l_zoomSliderH * 0.25), l_zoomSliderW, l_zoomSliderH)
tNameplate.wndCcBar:SetAnchorOffsets(-l_zoomSliderW, (l_zoomSliderH * 0.25), l_zoomSliderW, l_zoomSliderH)
local l_armorWidth = tNameplate.iconArmor:GetHeight() / 2
tNameplate.iconArmor:SetAnchorOffsets(-l_armorWidth, 0, l_armorWidth, 0)
end
tNameplate.nMatrixFlags = self:GetCombatStateDependentFlags(tNameplate)
self:UpdateAnchoring(tNameplate)
if (not tNameplate.bIsVerticalOffsetUpdated) then
self:InitNameplateVerticalOffset(tNameplate)
end
tNameplate.wndUnitNameText:SetData(unitNameplateOwner)
tNameplate.wndHealthProgressBar:SetData(unitNameplateOwner)
tNameplate.bIsOnScreen = tNameplate.wndNameplate:IsOnScreen()
self:UpdateOpacity(tNameplate)
tNameplate.wndContainerCc:Show(false)
tNameplate.wndContainerMain:Show(false)
tNameplate.containerCastBar:Show(false)
tNameplate.textUnitGuild:Show(false)
tNameplate.iconArmor:Show(false)
tNameplate.wndCleanseFrame:Show(false)
-- self:UpdateHealthShieldText(tNameplate)
tNameplate.wndShieldBar:Show(tNameplate.bHasShield)
local mc_left, mc_top, mc_right, mc_bottom = tNameplate.wndContainerMain:GetAnchorOffsets()
tNameplate.wndContainerMain:SetAnchorOffsets(mc_left, mc_top, mc_right, tNameplate.bHasShield and mc_top + 14 or mc_top + 11)
if (_tSettings["ConfigLargeShield"]) then
tNameplate.wndShieldBar:SetAnchorOffsets(0, 8, 0, 14)
end
-- Some NPCs do seem to spawn in combat while they don't have a valid HP value.
-- We still want to show their health bars
if (tNameplate.bHasHealth or tNameplate.bIsInCombat) then
self:UpdateMainBars(tNameplate)
self:UpdateHealthShieldText(tNameplate)
else
tNameplate.wndHealthText:Show(false)
-- When a PC dyes we also hide the CC status container window
tNameplate.wndContainerCc:Show(false)
end
tNameplate.nNonCombatStateFlags = self:GetNonCombatStateDependentFlags(tNameplate)
self:UpdateNonCombatStateElements(tNameplate)
tNameplate.containerIcons:DestroyAllPixies()
if (tNameplate.bIsPlayer) then
self:UpdateIconsPc(tNameplate)
else
self:UpdateIconsNpc(tNameplate)
end
self:UpdateTextNameGuild(tNameplate)
self:UpdateTextLevel(tNameplate)
self:UpdateInterruptArmor(tNameplate)
self:InitClassRankIcon(tNameplate)
tNameplate.wndNameplate:Show(self:GetNameplateVisibility(tNameplate), true)
self:UpdateTopContainer(tNameplate)
tNameplate.wndNameplate:ArrangeChildrenVert(1)
return tNameplate
end
function TwinkiePlates:UpdateAnchoring(tNameplate, nCodeEnumFloaterLocation)
local tAnchorUnit = tNameplate.unitNameplateOwner:IsMounted() and tNameplate.unitNameplateOwner:GetUnitMount() or tNameplate.unitNameplateOwner
local bReposition = false
local nCodeEnumFloaterLocation = nCodeEnumFloaterLocation
if (self.nameplacer) then
if (not nCodeEnumFloaterLocation) then
local tNameplatePositionSetting = self.nameplacer:GetUnitNameplatePositionSetting(tNameplate.unitNameplateOwner:GetName())
if (tNameplatePositionSetting and tNameplatePositionSetting["nAnchorId"]) then
nCodeEnumFloaterLocation = tNameplatePositionSetting["nAnchorId"]
end
end
if (nCodeEnumFloaterLocation) then
-- Already updated
if (nCodeEnumFloaterLocation == tNameplate.nAnchorId and tAnchorUnit == tNameplate.wndNameplate:GetUnit()) then
return
end
tNameplate.nAnchorId = nCodeEnumFloaterLocation
tNameplate.wndNameplate:SetUnit(tAnchorUnit, tNameplate.nAnchorId)
return
end
end
if (_tSettings["ConfigDynamicVPos"] and not tNameplate.bIsPlayer) then
local tOverhead = tNameplate.unitNameplateOwner:GetOverheadAnchor()
if (tOverhead ~= nil) then
bReposition = not tNameplate.bIsOccluded and tOverhead.y < 25
end
end
nCodeEnumFloaterLocation = bReposition and 0 or 1
if (nCodeEnumFloaterLocation ~= tNameplate.nAnchorId or tAnchorUnit ~= tNameplate.wndNameplate:GetUnit()) then
tNameplate.nAnchorId = nCodeEnumFloaterLocation
tNameplate.wndNameplate:SetUnit(tAnchorUnit, tNameplate.nAnchorId)
end
end
function TwinkiePlates:InitNameplateVerticalOffset(tNameplate, nInputNameplacerVerticalOffset)
local nVerticalOffset = _tSettings["SliderVerticalOffset"]
local nNameplacerVerticalOffset = nInputNameplacerVerticalOffset
if (self.nameplacer or nNameplacerVerticalOffset) then
if (not nNameplacerVerticalOffset) then
local tNameplatePositionSetting = self.nameplacer:GetUnitNameplatePositionSetting(tNameplate.unitNameplateOwner:GetName())
if (tNameplatePositionSetting) then
nNameplacerVerticalOffset = tNameplatePositionSetting["nVerticalOffset"]
end
end
end
if (not nNameplacerVerticalOffset) then
nNameplacerVerticalOffset = 0
end
self:SetNameplateVerticalOffset(tNameplate, nVerticalOffset, nNameplacerVerticalOffset)
tNameplate.bIsVerticalOffsetUpdated = true
end
function TwinkiePlates:IsInCombat(tNameplate)
-- Print("TwinkiePlates: _tPvpZones[self.nCurrentZoneId]: " .. tostring(_tPvpZones[self.nCurrentZoneId]))
if (not self.nCurrentZoneId) then
-- Print("TwinkiePlates:IsInCombat; Updating current zone!")
self:UpdateCurrentZoneInfo(GameLib.GetCurrentZoneId())
end
-- PvP zones always on
if (_tSettings["ConfigAlwaysPvPCombatDetection"] and _tPvpZones[self.nCurrentZoneId]) then
-- Print("TwinkiePlates:IsInCombat; PvP Zone detected!")
return true
end
-- Player based combat status
if _tSettings["ConfigPlayerCombatDetection"] then
-- Print("TwinkiePlates:IsInCombat; Player setting! " .. tostring(_unitPlayer:IsInCombat()))
return _unitPlayer:IsInCombat()
end
return tNameplate.unitNameplateOwner:IsInCombat()
end
function TwinkiePlates:IsPet(unit)
local strUnitType = unit:GetType()
return strUnitType == "Pet" or strUnitType == "Scanner"
end
function TwinkiePlates:IsPvpFlagged(unit)
if (self:IsPet(unit) and unit:GetUnitOwner()) then
unit = unit:GetUnitOwner()
end
return unit:IsPvpFlagged()
end
function TwinkiePlates:OnUnitCreated(unitNameplateOwner)
_tableInsert(self.buffer, unitNameplateOwner)
end
function TwinkiePlates:UpdateBuffer()
for i = 1, #self.buffer do
local l_unit = self.buffer[i]
if (l_unit ~= nil and l_unit:IsValid()) then
self:AllocateNameplate(l_unit)
end
self.buffer[i] = nil
end
end
function TwinkiePlates:OnFrame()
-- Player initialization.
if (_unitPlayer == nil) then
_unitPlayer = GameLib.GetPlayerUnit()
if (_unitPlayer ~= nil) then
_playerPath = _paths[PlayerPathLib.GetPlayerPathType()]
if (_unitPlayer:GetTarget() ~= nil) then
self:OnTargetUnitChanged(_unitPlayer:GetTarget())
end
self:CheckMatrixIntegrity()
end
end
-- Addon configuration loading. Maybe can be used to reaload the configuration without reloading the whole UI.
if (_wndConfigUi == nil and _next(_tSettings) ~= nil) then
self:InitConfiguration()
end
if (_unitPlayer == nil) then return
end
---------------------------------------------------------------------------
_playerPos = _unitPlayer:GetPosition()
_bIsPlayerBlinded = _unitPlayer:IsInCCState(Unit.CodeEnumCCState.Blind)
for flag, flagValue in _pairs(_flags) do
_flags[flag] = flagValue == 1 and 2 or flagValue
end
local nCount = 0
for id, tNameplate in _pairs(self.tNameplates) do
nCount = nCount + 1
local bIsCyclicUpdate = (nCount > _count and nCount < _count + _cycleSize)
self:UpdateNameplate(tNameplate, bIsCyclicUpdate)
end
_count = (_count + _cycleSize > nCount) and 0 or _count + _cycleSize
if (_tTargetNameplate ~= nil) then
self:UpdateNameplate(_tTargetNameplate, true)
end
if (_wndConfigUi ~= nil and _wndConfigUi:IsVisible()) then
self:UpdateConfiguration()
end
self:UpdateBuffer()
for flag, flagValue in _pairs(_flags) do
_flags[flag] = flagValue == 2 and 0 or flagValue
end
end
function TwinkiePlates:UpdateNameplate(tNameplate, bCyclicUpdate)
if (bCyclicUpdate) then
local nDistanceToUnit = self:DistanceToUnit(tNameplate.unitNameplateOwner)
tNameplate.bIsUnitOutOfRange = nDistanceToUnit > _tSettings["SliderDrawDistance"]
end
tNameplate.bIsOnScreen = tNameplate.wndNameplate:IsOnScreen()
if (tNameplate.bIsOnScreen) then
tNameplate.eDisposition = self:GetDispositionTo(tNameplate.unitNameplateOwner, _unitPlayer)
if (tNameplate.bHasHealth
or (tNameplate.bIsPlayer and self:HasHealth(tNameplate.unitNameplateOwner))
-- Some units only start having HPs after some events (eg. Essence of Logic)
or (tNameplate.bForcedHideDisplayToggle and self:HasHealth(tNameplate.unitNameplateOwner))) then
tNameplate.bHasHealth = true
tNameplate.nCurrHealth = tNameplate.unitNameplateOwner:GetHealth();
end
tNameplate.strUnitCategory = self:GetNameplateCategoryType(tNameplate)
end
tNameplate.bIsOccluded = tNameplate.wndNameplate:IsOccluded()
local bIsNameplateVisible = self:GetNameplateVisibility(tNameplate)
if (tNameplate.wndNameplate:IsVisible() ~= bIsNameplateVisible) then
tNameplate.wndNameplate:Show(bIsNameplateVisible, true)
end
if (not bIsNameplateVisible) then return
end
---------------------------------------------------------------------------
-- local bIsInCombat = tNameplate.unitNameplateOwner:IsInCombat()
local bIsInCombat = self:IsInCombat(tNameplate)
if (tNameplate.bIsInCombat ~= bIsInCombat) then
if (tNameplate.unitNameplateOwner == _unitPlayer) then
-- Print("Updating combat state")
end
tNameplate.bIsInCombat = bIsInCombat
if (tNameplate.unitNameplateOwner == _unitPlayer) then
-- Print("tNameplate.bIsInCombat: " .. tostring(tNameplate.bIsInCombat))
end
if (tNameplate.unitNameplateOwner == _unitPlayer) then
-- Print("Combat state flags: " .. tostring(tNameplate.nMatrixFlags))
end
tNameplate.nMatrixFlags = self:GetCombatStateDependentFlags(tNameplate)
if (tNameplate.unitNameplateOwner == _unitPlayer) then
-- Print("New combat state flags: " .. tostring(tNameplate.nMatrixFlags))
end
self:UpdateTextNameGuild(tNameplate)
self:UpdateTopContainer(tNameplate)
end
local bShowCcBar = GetFlag(tNameplate.nMatrixFlags, F_CC_BAR)
if ((bShowCcBar and (tNameplate.nCcActiveId ~= -1 or tNameplate.nCcNewId ~= -1))
-- We need to hide the CC bar cause the combat state may have changed
or (not bShowCcBar and tNameplate.wndContainerCc:IsVisible())) then
self:UpdateCc(tNameplate)
end
if (_flags.opacity == 2) then
self:UpdateOpacity(tNameplate)
end
if (_flags.contacts == 2 and tNameplate.bIsPlayer) then
self:UpdateIconsPc(tNameplate)
end
self:UpdateAnchoring(tNameplate)
self:UpdateCasting(tNameplate)
self:UpdateInterruptArmor(tNameplate)
if (tNameplate.bHasHealth) then
self:UpdateMainBars(tNameplate)
self:UpdateHealthShieldText(tNameplate)
end
if (bCyclicUpdate) then
local nNonCombatStateFlags = self:GetNonCombatStateDependentFlags(tNameplate)
if (tNameplate.nNonCombatStateFlags ~= nNonCombatStateFlags) then
tNameplate.nNonCombatStateFlags = nNonCombatStateFlags
self:UpdateNonCombatStateElements(tNameplate)
end
if (not tNameplate.bIsPlayer) then
self:UpdateIconsNpc(tNameplate)
end
end
if (tNameplate.bRearrange) then
tNameplate.wndNameplate:ArrangeChildrenVert(1)
tNameplate.bRearrange = false
end
if self.perspectivePlates then
tNameplate.wndNameplate = tNameplate.wndNameplate
tNameplate.unitOwner = tNameplate.unitNameplateOwner
self.perspectivePlates:OnRequestedResize(tNameplate)
end
end
function TwinkiePlates:UpdateMainBars(tNameplate)
local nHealth = tNameplate.nCurrHealth;
local nHealthMax = tNameplate.unitNameplateOwner:GetMaxHealth();
local nShield = tNameplate.unitNameplateOwner:GetShieldCapacity();
local nShieldMax = tNameplate.unitNameplateOwner:GetShieldCapacityMax();
local bIsFullHealth = nHealth == nHealthMax;
local bIsShieldFull = false;
local bIsHiddenBecauseFull = false;
local bIsFriendly = tNameplate.eDisposition == Unit.CodeEnumDisposition.Friendly
if (tNameplate.bHasShield) then
bIsShieldFull = nShield == nShieldMax;
end
if (not tNameplate.bIsTargetNameplate) then
local bConfigHideWhenFullHealth = _tSettings["ConfigSimpleWhenHealthy"]
local bConfigHideWhenFullShield = _tSettings["ConfigSimpleWhenFullShield"]
bIsHiddenBecauseFull =
-- Check only health
(bConfigHideWhenFullHealth and bIsFullHealth) and (not bConfigHideWhenFullShield)
-- Check only shield
or (bConfigHideWhenFullShield and bIsShieldFull) and (not bConfigHideWhenFullHealth)
-- Check health and shield
or (bConfigHideWhenFullHealth and bIsFullHealth) and (bConfigHideWhenFullShield and bIsShieldFull);
end
local bConfigShowHealthBar = GetFlag(tNameplate.nMatrixFlags, F_HEALTH)
local bIsHealthBarVisible = bConfigShowHealthBar and not bIsHiddenBecauseFull and nHealth
if (tNameplate.wndContainerMain:IsVisible() ~= bIsHealthBarVisible) then
tNameplate.wndContainerMain:Show(bIsHealthBarVisible)
tNameplate.bRearrange = true
end
if (bIsHealthBarVisible) then
if (tNameplate.bHasShield) then
self:SetProgressBar(tNameplate.wndShieldBar, nShield, nShieldMax)
end
local strLowHealthCheck = bIsFriendly and "SliderLowHealthFriendly" or "SliderLowHealth"
if (_tSettings[strLowHealthCheck] ~= 0) then
local nLowHealthThresholdCutoff = (_tSettings[strLowHealthCheck] / 100)
local nHealthPercentage = nHealth / nHealthMax
tNameplate.bIsLowHealth = nHealthPercentage <= nLowHealthThresholdCutoff
end
self:SetProgressBar(tNameplate.wndHealthProgressBar, nHealth, nHealthMax)
tNameplate.bRefreshHealthShieldBar = false
local nAbsorb = tNameplate.unitNameplateOwner:GetAbsorptionValue();
if (nAbsorb > 0) then
if (not tNameplate.wndAbsorbBar:IsVisible()) then
tNameplate.wndAbsorbBar:Show(true)
end
self:SetProgressBar(tNameplate.wndAbsorbBar, nAbsorb, nHealthMax)
else
tNameplate.wndAbsorbBar:Show(false)
end
end
end
function TwinkiePlates:UpdateTopContainer(tNameplate)
local bIsLevelVisible = GetFlag(tNameplate.nMatrixFlags, F_LEVEL)
local bIsClassIconVisible = GetFlag(tNameplate.nMatrixFlags, F_CLASS)
tNameplate.wndClassRankIcon:SetBGColor(bIsClassIconVisible and "FFFFFFFF" or "00FFFFFF")
local l_width = tNameplate.levelWidth + tNameplate.wndUnitNameText:GetWidth()
local l_ratio = tNameplate.levelWidth / l_width
local l_middle = (l_width * l_ratio) - (l_width / 2)
if (not bIsLevelVisible) then
local l_extents = tNameplate.wndUnitNameText:GetWidth() / 2
tNameplate.textUnitLevel:SetTextColor("00FFFFFF")
tNameplate.textUnitLevel:SetAnchorOffsets(-l_extents - 5, 0, -l_extents, 1)
tNameplate.wndUnitNameText:SetAnchorOffsets(-l_extents, 0, l_extents, 1)
else
tNameplate.textUnitLevel:SetTextColor("FFFFFFFF")
tNameplate.textUnitLevel:SetAnchorOffsets(-(l_width / 2), 0, l_middle, 1)
tNameplate.wndUnitNameText:SetAnchorOffsets(l_middle, 0, (l_width / 2), 1)
end
end
function TwinkiePlates:UpdateHealthShieldText(tNameplate)
local bHealthTextEnabled = GetFlag(tNameplate.nMatrixFlags, F_HEALTH_TEXT) and tNameplate.bHasHealth
if (tNameplate.wndHealthText:IsVisible() ~= bHealthTextEnabled) then
tNameplate.wndHealthText:Show(bHealthTextEnabled)
tNameplate.bRearrange = true
end
if (bHealthTextEnabled) then
local nHealth = tNameplate.nCurrHealth;
local nHealthMax = tNameplate.unitNameplateOwner:GetMaxHealth();
local nShield = tNameplate.unitNameplateOwner:GetShieldCapacity();
local nShieldMax = tNameplate.unitNameplateOwner:GetShieldCapacityMax();
local strShieldText = ""
local strHealthText = self:GetNumber(nHealth, nHealthMax)
if (tNameplate.bHasShield and nShield ~= 0) then
strShieldText = " (" .. self:GetNumber(nShield, nShieldMax) .. ")"
end
tNameplate.wndHealthText:SetText(strHealthText .. strShieldText)
-- self:UpdateMainContainerHeightWithHealthText(tNameplate)
-- else
-- self:UpdateMainContainerHeightWithoutHealthText(tNameplate)
end
-- tNameplate.bRearrange = true
end
function TwinkiePlates:UpdateNonCombatStateElements(tNameplate)
local bPvpFlaggedSettingEnabled = _unitPlayer:IsPvpFlagged() and GetFlag(tNameplate.nNonCombatStateFlags, F_PVP)
local bNoAggroSettingEnabled = GetFlag(tNameplate.nNonCombatStateFlags, F_AGGRO)
local bIsShowCleansableSettingEnabled = GetFlag(tNameplate.nNonCombatStateFlags, F_CLEANSE)
local bIsLowHpSettingEnabled = GetFlag(tNameplate.nNonCombatStateFlags, F_LOW_HP)
local colorNameplateText = _tFromSettingToColor[tNameplate.strUnitCategory]
local colorNameplateBar = _dispColor[tNameplate.eDisposition]
local bHostile = tNameplate.eDisposition == Unit.CodeEnumDisposition.Hostile
local bIsFriendly = tNameplate.eDisposition == Unit.CodeEnumDisposition.Friendly
tNameplate.color = colorNameplateText
if (tNameplate.bIsPlayer or tNameplate.bPet) then
if (not bPvpFlaggedSettingEnabled and bHostile) then
colorNameplateText = _dispColor[Unit.CodeEnumDisposition.Neutral]
colorNameplateBar = _dispColor[Unit.CodeEnumDisposition.Neutral]
tNameplate.color = colorNameplateText
end
if (bIsShowCleansableSettingEnabled and bIsFriendly --[[ and not tNameplate.wndCleanseFrame:IsVisible()]]) then
tNameplate.wndCleanseFrame:Show(true)
tNameplate.wndCleanseFrame:SetBGColor(_tFromSettingToColor["Cleanse"])
-- elseif (tNameplate.wndCleanseFrame:IsVisible()) then
else
tNameplate.wndCleanseFrame:Show(false)
end
else
if (bNoAggroSettingEnabled and bHostile) then
colorNameplateText = _tFromSettingToColor["NoAggro"]
end
if (tNameplate.wndCleanseFrame:IsVisible()) then
tNameplate.wndCleanseFrame:Show(false)
end
end
if (bIsLowHpSettingEnabled) then
colorNameplateBar = bIsFriendly and _tFromSettingToColor["LowHpFriendly"] or _tFromSettingToColor["LowHpNotFriendly"]
end
tNameplate.wndUnitNameText:SetTextColor(colorNameplateText)
tNameplate.textUnitGuild:SetTextColor(colorNameplateText)
tNameplate.wndHealthProgressBar:SetBarColor(colorNameplateBar)
if (tNameplate.bIsTargetNameplate and tNameplate.targetMark ~= nil) then
tNameplate.targetMark:SetBGColor(tNameplate.color)
end
end
function TwinkiePlates:GetCombatStateDependentFlags(tNameplate)
local nFlags = 0
local bIsInCombat = tNameplate.bIsInCombat
local strUnitCategoryType = tNameplate.strUnitCategory
if (tNameplate.unitNameplateOwner == _unitPlayer) then
-- Print("GetCombatStateDependentFlags; tNameplate.bIsIncombat:" .. tostring(tNameplate.bIsInCombat))
end
for strUiElement in _pairs(_tUiElements) do
local nMatrixConfigurationCellValue = _tSettings[_tUiElements[strUiElement][strUnitCategoryType]]
if ((_type(nMatrixConfigurationCellValue) ~= "number")
or (nMatrixConfigurationCellValue == N_ALWAYS_ENABLED)
or (nMatrixConfigurationCellValue == N_ENABLED_IN_COMBAT and bIsInCombat)
or (nMatrixConfigurationCellValue == N_ALWAYS_OUT_OF_COMBAT and not bIsInCombat)) then
nFlags = SetFlag(nFlags, _tUiElementToFlag[strUiElement])
end
end
if (not tNameplate.bHasHealth) then
nFlags = ClearFlag(nFlags, F_HEALTH)
end
return nFlags
end
function TwinkiePlates:GetNonCombatStateDependentFlags(tNameplate)
if (_unitPlayer == nil) then return
end
local nFlags = SetFlag(0, tNameplate.eDisposition)
local bIsFriendly = tNameplate.eDisposition == Unit.CodeEnumDisposition.Friendly
if (tNameplate.bIsInGroup) then nFlags = SetFlag(nFlags, F_GROUP)
end
if (tNameplate.bIsPvpFlagged) then nFlags = SetFlag(nFlags, F_PVP)
end
if (tNameplate.bIsLowHealth) then nFlags = SetFlag(nFlags, F_LOW_HP)
end
if (_tSettings["ConfigAggroIndication"]) then
if (tNameplate.bIsInCombat and not tNameplate.bIsPlayer and tNameplate.unitNameplateOwner:GetTarget() ~= _unitPlayer) then
nFlags = SetFlag(nFlags, F_AGGRO)
end
end
if (_tSettings["ConfigCleanseIndicator"] and bIsFriendly) then
local tUnitDebuffs = tNameplate.unitNameplateOwner:GetBuffs()["arHarmful"]
for i = 1, #tUnitDebuffs do
if (tUnitDebuffs[i]["splEffect"]:GetClass() == Spell.CodeEnumSpellClass.DebuffDispellable) then
nFlags = SetFlag(nFlags, F_CLEANSE)
end
end
end
return nFlags
end
function TwinkiePlates:GetDispositionTo(unitSubject, unitObject)
if (not unitSubject or not unitObject) then return Unit.CodeEnumDisposition.Unknown
end
if (self:IsPet(unitSubject) and unitSubject:GetUnitOwner()) then
unitSubject = unitSubject:GetUnitOwner()
end
return unitSubject:GetDispositionTo(unitObject)
end
function SetFlag(p_flags, p_flag)
return _or(p_flags, _lshift(1, p_flag))
end
function ClearFlag(p_flags, p_flag)
return _and(p_flags, _xor(_lshift(1, p_flag), 65535))
end
function GetFlag(p_flags, p_flag)
return _and(p_flags, _lshift(1, p_flag)) ~= 0
end
function TwinkiePlates:GetNumber(p_current, p_max)
if (p_current == nil or p_max == nil) then return ""
end
if (_tSettings["ConfigHealthPct"]) then
return _floor((p_current / p_max) * 100) .. "%"
else
return self:FormatNumber(p_current)
end
end
function TwinkiePlates:UpdateConfiguration()
self:UpdateConfigSlider("SliderDrawDistance", 50, 155.0, "m")
self:UpdateConfigSlider("SliderLowHealth", 0, 101.0, "%")
self:UpdateConfigSlider("SliderLowHealthFriendly", 0, 101.0, "%")
self:UpdateConfigSlider("SliderVerticalOffset", 0, 101.0, "px")
self:UpdateConfigSlider("SliderBarScale", 50, 205.0, "%")
self:UpdateConfigSlider("SliderFontSize", 1, 6.2)
end
function TwinkiePlates:UpdateConfigSlider(p_name, p_min, p_max, p_labelSuffix)
local l_slider = _wndConfigUi:FindChild(p_name)
if (l_slider ~= nil) then
local l_sliderVal = l_slider:FindChild("SliderBar"):GetValue()
l_slider:SetProgress((l_sliderVal - p_min) / (p_max - p_min))
l_slider:FindChild("TextValue"):SetText(l_sliderVal .. (p_labelSuffix or ""))
end
end
function TwinkiePlates:OnTargetUnitChanged(unitTarget)
if (not _unitPlayer) then return
end
if (unitTarget and self.tNameplates[unitTarget:GetId()]) then
self.tNameplates[unitTarget:GetId()].wndNameplate:Show(false, true)
end
if (unitTarget ~= nil) then
if (_tTargetNameplate == nil) then
_tTargetNameplate = self:InitNameplate(unitTarget, nil, true)
if (_tSettings["ConfigLegacyTargeting"]) then
self:UpdateLegacyTargetPixie()
_tTargetNameplate.wndNameplate:AddPixie(_tTargetPixie)
else
_tTargetNameplate.targetMark = Apollo.LoadForm(self.xmlDoc, "Target Indicator", _tTargetNameplate.containerTop, self)
local nTargetMarkVerticalOffset = _tTargetNameplate.targetMark:GetHeight() / 2
_tTargetNameplate.targetMark:SetAnchorOffsets(-nTargetMarkVerticalOffset, 0, nTargetMarkVerticalOffset, 0)
_tTargetNameplate.targetMark:SetBGColor(_tTargetNameplate.color)
end
else
-- Target nameplate is never reset because it's not attached to any specific unit thus is never affected by OnUnitDestroyed event
_tTargetNameplate.bIsVerticalOffsetUpdated = false
_tTargetNameplate = self:InitNameplate(unitTarget, _tTargetNameplate, true)
if (_tSettings["ConfigLegacyTargeting"]) then
self:UpdateLegacyTargetPixie()
_tTargetNameplate.wndNameplate:UpdatePixie(1, _tTargetPixie)
end
end
-- We need to call this otherwise hidden health text configuration may not update correctly
-- self:UpdateHealthShieldText(_tTargetNameplate)
end
_flags.opacity = 1
_tTargetNameplate.wndNameplate:Show(unitTarget ~= nil, true)
end
function TwinkiePlates:UpdateLegacyTargetPixie()
local nWidth = _tTargetNameplate.wndUnitNameText:GetWidth()
local nHeight = _tTargetNameplate.wndUnitNameText:GetHeight()
if (_tTargetNameplate.textUnitLevel:IsVisible()) then nWidth = nWidth + _tTargetNameplate.textUnitLevel:GetWidth()
end
if (_tTargetNameplate.textUnitGuild:IsVisible()) then nHeight = nHeight + _tTargetNameplate.textUnitGuild:GetHeight()
end
if (_tTargetNameplate.wndContainerMain:IsVisible()) then nHeight = nHeight + _tTargetNameplate.wndContainerMain:GetHeight()
end
nHeight = (nHeight / 2) + 30
nWidth = (nWidth / 2) + 50
nWidth = nWidth < 45 and 45 or (nWidth > 200 and 200 or nWidth)
nHeight = nHeight < 45 and 45 or (nHeight > 75 and 75 or nHeight)
_tTargetPixie.loc.nOffsets[1] = -nWidth
_tTargetPixie.loc.nOffsets[2] = -nHeight
_tTargetPixie.loc.nOffsets[3] = nWidth
_tTargetPixie.loc.nOffsets[4] = nHeight
end
function TwinkiePlates:OnTextBubble(unitNameplateOwner, p_text)
if (_unitPlayer == nil) then return
end
local tNameplate = self.tNameplates[unitNameplateOwner:GetId()]
if (tNameplate ~= nil) then
self:ProcessTextBubble(tNameplate, p_text)
end
end
function TwinkiePlates:ProcessTextBubble(p_nameplate, p_text)
if (GetFlag(p_nameplate.nMatrixFlags, F_BUBBLE)) then
self:UpdateOpacity(p_nameplate, (p_text ~= nil))
end
end
function TwinkiePlates:OnPlayerMainTextChanged()
if (_unitPlayer == nil) then return
end
self:OnUnitMainTextChanged(_unitPlayer)
end
function TwinkiePlates:OnNameplatePositionSettingChanged(strUnitName, tNameplatePositionSetting)
-- Print("[TwinkiePlates] OnNameplatePositionSettingChanged; strUnitName: " .. strUnitName .. "; tNameplatePositionSetting: " .. table.tostring(tNameplatePositionSetting))
if (not tNameplatePositionSetting or (not tNameplatePositionSetting["nAnchorId"] and not tNameplatePositionSetting["nVerticalOffset"])) then return
end
if (_tTargetNameplate and _tTargetNameplate.unitNameplateOwner and _tTargetNameplate.unitNameplateOwner:GetName() == strUnitName) then
if (tNameplatePositionSetting["nAnchorId"]) then
self:UpdateAnchoring(_tTargetNameplate, tNameplatePositionSetting["nAnchorId"])
end
if (tNameplatePositionSetting["nVerticalOffset"]) then
self:InitNameplateVerticalOffset(_tTargetNameplate, tNameplatePositionSetting["nVerticalOffset"])
end
end
for _, tNameplate in _pairs(self.tNameplates) do
if (tNameplate.unitNameplateOwner:GetName() == strUnitName) then
if (tNameplatePositionSetting["nAnchorId"]) then
self:UpdateAnchoring(tNameplate, tNameplatePositionSetting["nAnchorId"])
end
if (tNameplatePositionSetting["nVerticalOffset"]) then
self:InitNameplateVerticalOffset(tNameplate, tNameplatePositionSetting["nVerticalOffset"])
end
end
end
end
function TwinkiePlates:OnUnitMainTextChanged(unitNameplateOwner)
if (unitNameplateOwner == nil) then return
end
local tNameplate = self.tNameplates[unitNameplateOwner:GetId()]
if (tNameplate ~= nil) then
self:UpdateTextNameGuild(tNameplate)
self:UpdateTopContainer(tNameplate)
end
if (_tTargetNameplate ~= nil and _unitPlayer:GetTarget() == unitNameplateOwner) then
self:UpdateTextNameGuild(_tTargetNameplate)
self:UpdateTopContainer(_tTargetNameplate)
end
end
function TwinkiePlates:OnUnitLevelChanged(unitNameplateOwner)
if (unitNameplateOwner == nil) then return
end
local l_nameplate = self.tNameplates[unitNameplateOwner:GetId()]
if (l_nameplate ~= nil) then
self:UpdateTextLevel(l_nameplate)
self:UpdateTopContainer(l_nameplate)
end
if (_tTargetNameplate ~= nil and _unitPlayer:GetTarget() == unitNameplateOwner) then
self:UpdateTextLevel(_tTargetNameplate)
self:UpdateTopContainer(_tTargetNameplate)
end
end
function TwinkiePlates:OnUnitActivationTypeChanged(unitNameplateOwner)
if (_unitPlayer == nil) then return
end
local tNameplate = self.tNameplates[unitNameplateOwner:GetId()]
local bHasActivationState = self:HasActivationState(unitNameplateOwner)
if (tNameplate ~= nil) then
tNameplate.bHasActivationState = bHasActivationState
elseif (bHasActivationState) then
self:AllocateNameplate(unitNameplateOwner)
end
if (_tTargetNameplate ~= nil and _unitPlayer:GetTarget() == unitNameplateOwner) then
_tTargetNameplate.bHasActivationState = bHasActivationState
end
end
function TwinkiePlates:OnChallengeUnlocked()
self.challenges = ChallengesLib.GetActiveChallengeList()
end
-------------------------------------------------------------------------------
function string.starts(String, Start)
return string.sub(String, 1, string.len(Start)) == Start
end
function TwinkiePlates:OnConfigure(strCmd, strArg)
if (strArg == "occlusion") then
_tSettings["ConfigOcclusionCulling"] = not _tSettings["ConfigOcclusionCulling"]
local l_occlusionString = _tSettings["ConfigOcclusionCulling"] and "<Enabled>" or "<Disabled>"
-- Print("[nPrimeNameplates] Occlusion culling " .. l_occlusionString)
elseif ((strArg == nil or strArg == "") and _wndConfigUi ~= nil) then
_wndConfigUi:Show(not _wndConfigUi:IsVisible(), true)
end
end
function TwinkiePlates:OnCombatLogDeath(tLogInfo)
-- Print("tLogInfo: " .. tLogInfo.unitCaster:GetName())
end
function TwinkiePlates:OnCombatLogResurrect(tLogInfo)
-- Print("tLogInfo: " .. tLogInfo.unitCaster:GetName())
end
-- Called from form
function TwinkiePlates:OnConfigButton(wndHandler, wndControl, eMouseButton)
local strHandlerName = wndHandler:GetName()
if (strHandlerName == "ButtonClose") then
_wndConfigUi:Show(false)
elseif (strHandlerName == "ButtonApply") then
RequestReloadUI()
elseif (string.starts(strHandlerName, "Config")) then
_tSettings[strHandlerName] = wndHandler:IsChecked()
end
end
-- Called from form
function TwinkiePlates:OnSliderBarChanged(p1, wndHandler, nValue, nOldValue)
local strParentHandlerName = wndHandler:GetParent():GetName()
if (_tSettings[strParentHandlerName] ~= nil) then
_tSettings[strParentHandlerName] = nValue
end
end
-- Called from form
function TwinkiePlates:OnMatrixClick(p_wndHandler, wndCtrl, nClick)
if (nClick ~= 0 and nClick ~= 1) then return
end
local l_parent = p_wndHandler:GetParent():GetParent():GetName()
local l_key = l_parent .. p_wndHandler:GetName()
local l_valueOld = _tSettings[l_key]
local l_xor = bit32.bxor(bit32.extract(l_valueOld, nClick), 1)
local l_valueNew = bit32.replace(l_valueOld, l_xor, nClick)
p_wndHandler:SetTooltip(self:GetMatrixTooltip(l_valueNew))
_tSettings[l_key] = l_valueNew
p_wndHandler:SetSprite(_matrixButtonSprites[l_valueNew])
end
function TwinkiePlates:OnInterfaceMenuListHasLoaded()
Event_FireGenericEvent("InterfaceMenuList_NewAddOn", "TwinkiePlates", { "ShowTwinkiePlatesConfigurationWnd", "", "" })
end
function TwinkiePlates:CheckMatrixIntegrity()
if (_type(_tSettings["ConfigBarIncrements"]) ~= "boolean") then _tSettings["ConfigBarIncrements"] = true
end
if (_type(_tSettings["ConfigHealthText"]) ~= "boolean") then _tSettings["ConfigHealthText"] = true
end
if (_type(_tSettings["ConfigShowHarvest"]) ~= "boolean") then _tSettings["ConfigShowHarvest"] = true
end
if (_type(_tSettings["ConfigOcclusionCulling"]) ~= "boolean") then _tSettings["ConfigOcclusionCulling"] = true
end
if (_type(_tSettings["ConfigFadeNonTargeted"]) ~= "boolean") then _tSettings["ConfigFadeNonTargeted"] = true
end
if (_type(_tSettings["ConfigDynamicVPos"]) ~= "boolean") then _tSettings["ConfigDynamicVPos"] = true
end
if (_type(_tSettings["ConfigLargeShield"]) ~= "boolean") then _tSettings["ConfigLargeShield"] = false
end
if (_type(_tSettings["ConfigHealthPct"]) ~= "boolean") then _tSettings["ConfigHealthPct"] = false
end
if (_type(_tSettings["ConfigSimpleWhenHealthy"]) ~= "boolean") then _tSettings["ConfigSimpleWhenHealthy"] = false
end
if (_type(_tSettings["ConfigSimpleWhenFullShield"]) ~= "boolean") then _tSettings["ConfigSimpleWhenFullShield"] = false
end
if (_type(_tSettings["ConfigAggroIndication"]) ~= "boolean") then _tSettings["ConfigAggroIndication"] = false
end
if (_type(_tSettings["ConfigHideAffiliations"]) ~= "boolean") then _tSettings["ConfigHideAffiliations"] = false
end
if (_type(_tSettings["ConfigAlternativeFont"]) ~= "boolean") then _tSettings["ConfigAlternativeFont"] = false
end
if (_type(_tSettings["ConfigLegacyTargeting"]) ~= "boolean") then _tSettings["ConfigLegacyTargeting"] = false
end
if (_type(_tSettings["ConfigCleanseIndicator"]) ~= "boolean") then _tSettings["ConfigCleanseIndicator"] = false
end
if (_type(_tSettings["SliderDrawDistance"]) ~= "number") then _tSettings["SliderDrawDistance"] = 100
end
if (_type(_tSettings["SliderLowHealth"]) ~= "number") then _tSettings["SliderLowHealth"] = 30
end
if (_type(_tSettings["SliderLowHealthFriendly"]) ~= "number") then _tSettings["SliderLowHealthFriendly"] = 0
end
if (_type(_tSettings["SliderVerticalOffset"]) ~= "number") then _tSettings["SliderVerticalOffset"] = 20
end
if (_type(_tSettings["SliderBarScale"]) ~= "number") then _tSettings["SliderBarScale"] = 100
end
if (_type(_tSettings["SliderFontSize"]) ~= "number") then _tSettings["SliderFontSize"] = 1
end
--[[ for i, category in _ipairs(_tUiElements) do
for j, filter in _ipairs(_tUnitCategories) do
local l_key = category .. filter
if (type(_tSettings[l_key]) ~= "number") then
_tSettings[l_key] = 3
end
end
end]]
for _, tUiElement in _pairs(_tUiElements) do
for _, strUiElementCategory in _pairs(tUiElement) do
if (_type(_tSettings[strUiElementCategory]) ~= "number") then
_tSettings[strUiElementCategory] = 3
end
end
end
end
function TwinkiePlates:InitConfiguration()
_wndConfigUi = Apollo.LoadForm(self.xmlDoc, "Configuration", nil, self)
_wndConfigUi:Show(false)
local wndConfigurationMatrix = _wndConfigUi:FindChild("MatrixConfiguration")
-- Matrix layout
self:DistributeMatrixColumns(wndConfigurationMatrix:FindChild("RowNames"))
for strUiElementName, tUiElement in _pairs(_tUiElements) do
local wndCategoryContainer = wndConfigurationMatrix:FindChild(strUiElementName)
self:DistributeMatrixColumns(wndCategoryContainer, strUiElementName)
end
for k, v in _pairs(_tSettings) do
if (string.starts(k, "Config")) then
local l_button = _wndConfigUi:FindChild(k)
if (l_button ~= nil) then
l_button:SetCheck(v)
end
elseif (string.starts(k, "Slider")) then
local l_slider = _wndConfigUi:FindChild(k)
if (l_slider ~= nil) then
l_slider:FindChild("SliderBar"):SetValue(v)
end
end
end
end
function TwinkiePlates:DistributeMatrixColumns(wndElementRow, p_categoryName)
-- local l_columns = (1 / #_tUnitCategories)
for i, filter in _ipairs(_tUnitCategories) do
-- local l_left = l_columns * (i - 1)
-- local l_right = l_columns * i
local l_button = wndElementRow:FindChild(filter)
-- l_button:SetAnchorPoints(l_left, 0, l_right, 1)
-- l_button:SetAnchorOffsets(1, 1, -1, -1)
if (p_categoryName ~= nil) then
local l_value = _tSettings[p_categoryName .. filter] or 0
l_button:SetSprite(_matrixButtonSprites[l_value])
l_button:SetStyle("IgnoreTooltipDelay", true)
l_button:SetTooltip(self:GetMatrixTooltip(l_value))
end
end
end
function TwinkiePlates:GetMatrixTooltip(nValue)
if (nValue == 0) then return "Never enabled"
end
if (nValue == 1) then return "Enabled in combat"
end
if (nValue == 2) then return "Enabled out of combat"
end
if (nValue == 3) then return "Always enabled"
end
return "?"
end
function TwinkiePlates:DistanceToUnit(unitNameplateOwner)
if (unitNameplateOwner == nil) then return 0
end
local l_pos = unitNameplateOwner:GetPosition()
if (l_pos == nil) then return 0
end
if (l_pos.x == 0) then return 0
end
local deltaPos = Vector3.New(l_pos.x - _playerPos.x, l_pos.y - _playerPos.y, l_pos.z - _playerPos.z)
return deltaPos:Length()
end
-------------------------------------------------------------------------------
function TwinkiePlates:FormatNumber(p_number)
if (p_number == nil) then return ""
end
local l_result = p_number
if p_number < 1000 then l_result = p_number
elseif p_number < 1000000 then l_result = _weaselStr("$1f1k", p_number / 1000)
elseif p_number < 1000000000 then l_result = _weaselStr("$1f1m", p_number / 1000000)
elseif p_number < 1000000000000 then l_result = _weaselStr("$1f1b", p_number / 1000000)
end
return l_result
end
function TwinkiePlates:UpdateTextNameGuild(tNameplate)
local bShowTitle = GetFlag(tNameplate.nMatrixFlags, F_TITLE)
local bShowGuild = GetFlag(tNameplate.nMatrixFlags, F_GUILD)
local bHideAffiliation = _tSettings["ConfigHideAffiliations"]
local unitNameplateOwner = tNameplate.unitNameplateOwner
local strUnitName = bShowTitle and unitNameplateOwner:GetTitleOrName() or unitNameplateOwner:GetName()
local strGuildName
local nFontSize = _tSettings["SliderFontSize"]
local tFontSettings = _tSettings["ConfigAlternativeFont"] and _fontSecondary or _fontPrimary
local nWidth = _textWidth(tFontSettings[nFontSize].font, strUnitName .. " ")
--[[
if (tNameplate.unitNameplateOwner == _unitPlayer) then
Print("Updating title/guild text: " .. tostring(bShowTitle) .. " " .. tostring(bShowGuild))
end
]]
if (bShowGuild and tNameplate.bIsPlayer) then
strGuildName = unitNameplateOwner:GetGuildName() and ("<" .. unitNameplateOwner:GetGuildName() .. ">") or nil
elseif (bShowGuild and not bHideAffiliation and not tNameplate.bIsPlayer) then
strGuildName = unitNameplateOwner:GetAffiliationName() or nil
end
tNameplate.wndUnitNameText:SetText(strUnitName)
tNameplate.wndUnitNameText:SetAnchorOffsets(0, 0, nWidth, 0)
local l_hasGuild = strGuildName ~= nil and (_strLen(strGuildName) > 0)
if (tNameplate.textUnitGuild:IsVisible() ~= l_hasGuild) then
tNameplate.textUnitGuild:Show(l_hasGuild)
tNameplate.bRearrange = true
end
if (l_hasGuild) then
tNameplate.textUnitGuild:SetTextRaw(strGuildName)
end
end
function TwinkiePlates:UpdateTextLevel(p_nameplate)
local l_level = p_nameplate.unitNameplateOwner:GetLevel()
if (l_level ~= nil) then
l_level = --[[ "Lv" .. --]] l_level .. " "
local l_fontSize = _tSettings["SliderFontSize"]
local l_font = _tSettings["ConfigAlternativeFont"] and _fontSecondary or _fontPrimary
local l_width = _textWidth(l_font[l_fontSize].font, l_level)
p_nameplate.levelWidth = l_width
p_nameplate.textUnitLevel:SetText(l_level)
else
p_nameplate.levelWidth = 1
p_nameplate.textUnitLevel:SetText("")
end
end
function TwinkiePlates:InitClassRankIcon(tNameplate)
local tIconMappingTable = tNameplate.bIsPlayer and _tFromPlayerClassToIcon or _tFromNpcRankToIcon
local strIconRef = tIconMappingTable[tNameplate.unitClassID]
tNameplate.wndClassRankIcon:Show(strIconRef ~= nil)
tNameplate.wndClassRankIcon:SetSprite(strIconRef ~= nil and strIconRef or "")
end
--[[
function TwinkiePlates:OnCharacterFlagsUpdated(strRandomVar)
Print("OnCharacterFlagsUpdated; strRandomVar: " .. tostring(strRandomVar))
end
]]
function TwinkiePlates:OnCCStateApplied(nCcId, unitNameplateOwner)
if (_ccWhiteList[nCcId] == nil) then
return
end
local l_nameplate = self.tNameplates[unitNameplateOwner:GetId()]
if (l_nameplate ~= nil) then
if (GetFlag(l_nameplate.nMatrixFlags, F_CC_BAR)) then
self:RegisterCc(l_nameplate, nCcId)
end
end
if (_tTargetNameplate ~= nil and _tTargetNameplate.unitNameplateOwner == unitNameplateOwner) then
if (GetFlag(_tTargetNameplate.nMatrixFlags, F_CC_BAR)) then
self:RegisterCc(_tTargetNameplate, nCcId)
end
end
end
function TwinkiePlates:RegisterCc(tNameplate, nCcId)
local strCcNewName = _ccWhiteList[nCcId]
if (strCcNewName) then
-- Register the new CC only if there no MoO already ongoning. The CC duration check is performed in the UpdateCc method
if (tNameplate.nCcNewId == -1 or (tNameplate.nCcNewId ~= -1 and tNameplate.nCcActiveId ~= Unit.CodeEnumCCState.Vulnerability and tNameplate.nCcNewId ~= Unit.CodeEnumCCState.Vulnerability)) then
tNameplate.nCcNewId = nCcId
end
end
end
function TwinkiePlates:UpdateCc(tNameplate)
local nCcNewDuration = tNameplate.nCcNewId >= 0 and tNameplate.unitNameplateOwner:GetCCStateTimeRemaining(tNameplate.nCcNewId) or 0
tNameplate.nCcDuration = tNameplate.nCcActiveId >= 0 and tNameplate.unitNameplateOwner:GetCCStateTimeRemaining(tNameplate.nCcActiveId) or 0
if (nCcNewDuration <= 0 and tNameplate.nCcNewId ~= -1) then
tNameplate.nCcNewId = -1
end
if (tNameplate.nCcDuration <= 0 and tNameplate.nCcActiveId ~= -1) then
tNameplate.nCcActiveId = -1
end
local strCcActiveName = _ccWhiteList[tNameplate.nCcActiveId]
local strCcNewName = _ccWhiteList[tNameplate.nCcNewId]
local bShowCcBar = (strCcActiveName and tNameplate.nCcDuration > 0) or (strCcNewName and nCcNewDuration > 0)
if (tNameplate.wndContainerCc:IsVisible() ~= bShowCcBar) then
tNameplate.wndContainerCc:Show(bShowCcBar)
tNameplate.bRearrange = true
end
if (bShowCcBar) then
local bUpdateCc = not tNameplate.nCcDurationMax
or tNameplate.nCcActiveId == -1
or (tNameplate.nCcNewId == Unit.CodeEnumCCState.Vulnerability)
or ((nCcNewDuration and nCcNewDuration > tNameplate.nCcDuration)
and tNameplate.nCcActiveId ~= Unit.CodeEnumCCState.Vulnerability)
-- New CC has a longer duration than the previous one (if any) and the current CC state is not a MoO
if (bUpdateCc) then
tNameplate.nCcDurationMax = nCcNewDuration
tNameplate.nCcDuration = nCcNewDuration
tNameplate.nCcActiveId = tNameplate.nCcNewId
tNameplate.nCcNewId = -1
tNameplate.wndContainerCc:SetText(strCcNewName)
tNameplate.wndCcBar:SetMax(nCcNewDuration)
end
-- Update the CC progress bar
tNameplate.wndCcBar:SetProgress(tNameplate.nCcDuration)
end
end
function TwinkiePlates:UpdateCasting(tNameplate)
local bCastingBarConfiguration = GetFlag(tNameplate.nMatrixFlags, F_CASTING_BAR)
local bShowCastBar = tNameplate.unitNameplateOwner:ShouldShowCastBar() and bCastingBarConfiguration
if (tNameplate.containerCastBar:IsVisible() ~= bShowCastBar) then
tNameplate.containerCastBar:Show(bShowCastBar)
tNameplate.bRearrange = true
end
if (bShowCastBar) then
local bIsCcVulnerable = tNameplate.unitNameplateOwner:GetInterruptArmorMax() >= 0
-- tNameplate.wndNameplate:ToFront()
tNameplate.wndCastBar:SetBarColor(bIsCcVulnerable and "xkcdDustyOrange" or _color("ff990000"))
tNameplate.wndCastBar:SetProgress(tNameplate.unitNameplateOwner:GetCastTotalPercent())
tNameplate.containerCastBar:SetText(tNameplate.unitNameplateOwner:GetCastName())
end
end
function TwinkiePlates:UpdateInterruptArmor(tNameplate)
local nArmorMax = tNameplate.unitNameplateOwner:GetInterruptArmorMax()
local nCurrentInterruptArmor = tNameplate.unitNameplateOwner:GetInterruptArmorValue()
local bShowArmor = GetFlag(tNameplate.nMatrixFlags, F_ARMOR) and --[[nArmorMax]] (nCurrentInterruptArmor ~= 0 or nArmorMax == -1)
if (tNameplate.iconArmor:IsVisible() ~= bShowArmor) then
tNameplate.iconArmor:Show(bShowArmor)
end
if (not bShowArmor) then
tNameplate.prevArmor = 0
return
end
if (nCurrentInterruptArmor --[[nArmorMax]] > 0) then
-- p_nameplate.iconArmor:SetText(p_nameplate.unitNameplateOwner:GetInterruptArmorValue())
tNameplate.iconArmor:SetText(nCurrentInterruptArmor)
end
if (tNameplate.prevArmor ~= nArmorMax) then
tNameplate.prevArmor = nArmorMax
if (nArmorMax == -1) then
tNameplate.iconArmor:SetText("")
tNameplate.iconArmor:SetSprite("NPrimeNameplates_Sprites:IconArmor_02")
elseif (nArmorMax > 0) then
tNameplate.iconArmor:SetSprite("NPrimeNameplates_Sprites:IconArmor")
end
end
end
function TwinkiePlates:UpdateOpacity(tNameplate, bHasTextBubble)
if (tNameplate.bIsTargetNameplate) then return
end
bHasTextBubble = bHasTextBubble or false
if (bHasTextBubble) then
tNameplate.wndNameplate:SetOpacity(0.25, 10)
else
local l_opacity = 1
if (_tSettings["ConfigFadeNonTargeted"] and _unitPlayer:GetTarget() ~= nil) then
l_opacity = 0.6
end
tNameplate.wndNameplate:SetOpacity(l_opacity, 10)
end
end
function TwinkiePlates:UpdateIconsNpc(tNameplate)
local nFlags = 0
local nIcons = 0
local tRewardInfo = tNameplate.unitNameplateOwner:GetRewardInfo()
if (tRewardInfo ~= nil and _next(tRewardInfo) ~= nil) then
for i = 1, #tRewardInfo do
local strType = tRewardInfo[i].strType
if (strType == _playerPath) then
nIcons = nIcons + 1
nFlags = SetFlag(nFlags, F_PATH)
elseif (strType == "Quest") then
nIcons = nIcons + 1
nFlags = SetFlag(nFlags, F_QUEST)
elseif (strType == "Challenge") then
local l_ID = tRewardInfo[i].idChallenge
local l_challenge = self.challenges[l_ID]
if (l_challenge ~= nil and l_challenge:IsActivated()) then
nIcons = nIcons + 1
nFlags = SetFlag(nFlags, F_CHALLENGE)
end
end
end
end
tNameplate.bIsObjective = nFlags > 0
if (nFlags ~= tNameplate.iconFlags) then
tNameplate.iconFlags = nFlags
tNameplate.containerIcons:DestroyAllPixies()
local l_height = tNameplate.containerIcons:GetHeight()
local l_width = 1 / nIcons
local l_iconN = 0
tNameplate.containerIcons:SetAnchorOffsets(0, 0, nIcons * l_height, 0)
if (GetFlag(nFlags, F_CHALLENGE)) then
self:AddIcon(tNameplate, "IconChallenge", l_iconN, l_width)
l_iconN = l_iconN + 1
end
if (GetFlag(nFlags, F_PATH)) then
self:AddIcon(tNameplate, "IconPath", l_iconN, l_width)
l_iconN = l_iconN + 1
end
if (GetFlag(nFlags, F_QUEST)) then
self:AddIcon(tNameplate, "IconQuest", l_iconN, l_width)
l_iconN = l_iconN + 1
end
end
end
function TwinkiePlates:UpdateIconsPc(tNameplate)
local nConfigurationFlags = 0
local nIconsCounter = 0
if (tNameplate.unitNameplateOwner:IsFriend() or
tNameplate.unitNameplateOwner:IsAccountFriend()) then
nIconsCounter = nIconsCounter + 1
nConfigurationFlags = SetFlag(nConfigurationFlags, F_FRIEND)
end
if (tNameplate.unitNameplateOwner:IsRival()) then
nIconsCounter = nIconsCounter + 1
nConfigurationFlags = SetFlag(nConfigurationFlags, F_RIVAL)
end
if (nConfigurationFlags ~= tNameplate.iconFlags) then
tNameplate.iconFlags = nConfigurationFlags
tNameplate.containerIcons:DestroyAllPixies()
local nIconsContainerHeight = tNameplate.containerIcons:GetHeight()
local nIconsContainerWidth = 1 / nIconsCounter
local nIconPos = 0
tNameplate.containerIcons:SetAnchorOffsets(0, 0, nIconsCounter * nIconsContainerHeight, 0)
if (GetFlag(nConfigurationFlags, F_FRIEND)) then
self:AddIcon(tNameplate, "IconFriend", nIconPos, nIconsContainerWidth)
nIconPos = nIconPos + 1
end
if (GetFlag(nConfigurationFlags, F_RIVAL)) then
self:AddIcon(tNameplate, "IconRival", nIconPos, nIconsContainerWidth)
nIconPos = nIconPos + 1
end
end
end
function TwinkiePlates:AddIcon(p_nameplate, p_sprite, p_iconN, p_width)
_iconPixie.strSprite = p_sprite
_iconPixie.loc.fPoints[1] = p_iconN * p_width
_iconPixie.loc.fPoints[3] = (p_iconN + 1) * p_width
p_nameplate.containerIcons:AddPixie(_iconPixie)
end
function TwinkiePlates:HasHealth(unitNameplateOwner)
if (unitNameplateOwner == nil or not unitNameplateOwner:IsValid()) then
return false
end
if (unitNameplateOwner:GetMouseOverType() == "Simple" or unitNameplateOwner:GetMouseOverType() == "SimpleCollidable") then
return false
end
if (unitNameplateOwner:IsDead()) then
return false
end
local nUnitMaxHealth = unitNameplateOwner:GetMaxHealth()
if (nUnitMaxHealth == nil or nUnitMaxHealth == 0) then
return false
end
return true
end
function TwinkiePlates:GetNameplateVisibility(tNameplate)
if (_bIsPlayerBlinded) then return false
end
local unitTarget = _unitPlayer:GetTarget()
-- return false if the nameplate is targeted by the player. Targeted nameplate is handled by _TargetNP
if (unitTarget == tNameplate.unitNameplateOwner and not tNameplate.bIsTargetNameplate) then return false
end
if (not tNameplate.bIsOnScreen) then return false
end
if (_tSettings["ConfigOcclusionCulling"] and tNameplate.bIsOccluded) then return false
end
if (tNameplate.bIsUnitOutOfRange) then return false
end
-- if this is the target nameplate
if (tNameplate.bIsTargetNameplate) then
-- return true if this still is the player's target nameplate
return unitTarget == tNameplate.unitNameplateOwner
end
if (not GetFlag(tNameplate.nMatrixFlags, F_NAMEPLATE)) then
return tNameplate.bHasActivationState or tNameplate.bIsObjective
end
if (tNameplate.unitNameplateOwner:IsDead() or (tNameplate.nCurrHealth and tNameplate.nCurrHealth <= 0)) then return false
end
if (tNameplate.bForcedHideDisplayToggle ~= nil) then
return tNameplate.bForcedHideDisplayToggle
end
-- Uninportant NPCs handling
local bIsFriendly = tNameplate.eDisposition == Unit.CodeEnumDisposition.Friendly
if (not tNameplate.bIsPlayer and bIsFriendly) then
return tNameplate.bHasActivationState or tNameplate.bIsObjective
end
return true
end
function TwinkiePlates:InitAnchoring(tNameplate, nCodeEnumFloaterLocation)
local tAnchorUnit = tNameplate.unitNameplateOwner:IsMounted() and tNameplate.unitNameplateOwner:GetUnitMount() or tNameplate.unitNameplateOwner
if (self.nameplacer or nCodeEnumFloaterLocation) then
if (not nCodeEnumFloaterLocation) then
local tNameplatePositionSetting = self.nameplacer:GetUnitNameplatePositionSetting(tNameplate.unitNameplateOwner:GetName())
if (tNameplatePositionSetting and tNameplatePositionSetting["nAnchorId"]) then
nCodeEnumFloaterLocation = tNameplatePositionSetting["nAnchorId"]
end
end
if (nCodeEnumFloaterLocation and (nCodeEnumFloaterLocation ~= tNameplate.nAnchorId or tAnchorUnit ~= tNameplate.unitNameplateOwner)) then
tNameplate.nAnchorId = nCodeEnumFloaterLocation
tNameplate.wndNameplate:SetUnit(tAnchorUnit, tNameplate.nAnchorId)
return
end
end
tNameplate.nAnchorId = 1
tNameplate.wndNameplate:SetUnit(tAnchorUnit, tNameplate.nAnchorId)
end
function TwinkiePlates:GetUnitCategoryType(unitNameplateOwner)
if (unitNameplateOwner == nil or not unitNameplateOwner:IsValid()) then return "Hidden"
end
if (unitNameplateOwner:CanBeHarvestedBy(_unitPlayer)) then
return _tSettings["ConfigShowHarvest"] and "Other" or "Hidden"
end
if (unitNameplateOwner:IsThePlayer()) then return "Self"
end
-- Not using GameLib.GetTarget() cause it seems to return a copy of the original unit and that can be more resource intensive - untested
if (_unitPlayer and _unitPlayer:GetTarget() == unitNameplateOwner) then return "Target"
end
if (unitNameplateOwner:IsInYourGroup()) then return "Group" end
local strUnitType = unitNameplateOwner:GetType()
if (strUnitType == "BindPoint") then return "Other"
end
if (strUnitType == "PinataLoot") then return "Other"
end
if (strUnitType == "Ghost") then return "Hidden"
end
if (strUnitType == "Mount") then return "Hidden"
end
-- Some interactable objects are identified as NonPlayer
-- This hack is done to prevent display the nameplate for this kind of units
if (strUnitType == "NonPlayer" and not unitNameplateOwner:GetUnitRaceId() and not unitNameplateOwner:GetLevel()) then
return "Hidden"
end
local eDisposition = unitNameplateOwner:GetDispositionTo(_unitPlayer)
local bIsCharacter = unitNameplateOwner:IsACharacter()
local strPcOrNpc = (bIsCharacter) and "Pc" or "Npc"
if (_tDisplayHideExceptionUnitNames[unitNameplateOwner:GetName()] ~= nil) then
return _tDisplayHideExceptionUnitNames[unitNameplateOwner:GetName()] and _tDispositionToString[eDisposition][strPcOrNpc] or "Hidden"
end
local tRewardInfo = unitNameplateOwner:GetRewardInfo()
if (tRewardInfo ~= nil and _next(tRewardInfo) ~= nil) then
for i = 1, #tRewardInfo do
if (tRewardInfo[i].strType ~= "Challenge") then
return _tDispositionToString[eDisposition][strPcOrNpc]
end
end
end
if (bIsCharacter or self:HasActivationState(unitNameplateOwner)) then
return _tDispositionToString[eDisposition][strPcOrNpc]
end
if (unitNameplateOwner:GetHealth() == nil) then return "Hidden"
end
local l_archetype = unitNameplateOwner:GetArchetype()
-- Returning Friendly/Neutral/Hostile .. Pc/Npc
if (l_archetype ~= nil) then
return _tDispositionToString[eDisposition][strPcOrNpc]
end
return "Hidden"
end
function TwinkiePlates:GetNameplateCategoryType(tNameplate)
local unitNameplateOwner = tNameplate.unitNameplateOwner
if (unitNameplateOwner == nil or not unitNameplateOwner:IsValid()) then return "Hidden"
end
-- Top priority checks:
-- 1) Self (Player)
-- 2) Player's target
-- 3) Group
if (tNameplate.strUnitCategory == "Self") then return tNameplate.strUnitCategory end
-- TODO Replace this check with a more consistent one
if (_unitPlayer and _unitPlayer:GetTarget() == tNameplate) then return "Target" end
if (tNameplate.bIsInGroup) then return "Group" end
-- Harvesting nodes
if (unitNameplateOwner:CanBeHarvestedBy(_unitPlayer)) then
return _tSettings["ConfigShowHarvest"] and "Other" or "Hidden"
end
local eDisposition = tNameplate.eDisposition
local bIsCharacter = tNameplate.bIsPlayer
local strPcOrNpc = (bIsCharacter) and "Pc" or "Npc"
local strUnitCategory = _tDispositionToString[eDisposition][strPcOrNpc]
-- Forced exceptions (hide/show)
if (tNameplate.bForcedHideDisplayToggle ~= nil) then
return tNameplate.bForcedHideDisplayToggle and strUnitCategory or "Hidden"
end
-- Objectives
--[[ local tRewardInfo = unitNameplateOwner:GetRewardInfo()
if (tRewardInfo ~= nil and _next(tRewardInfo) ~= nil) then
for i = 1, #tRewardInfo do
if (tRewardInfo[i].strType ~= "Challenge") then
return strUnitCategory
end
end
end]]
-- Interactables
if (bIsCharacter or tNameplate.bHasActivationState) then
return strUnitCategory
end
-- Dead creatures
if (tNameplate.nCurrHealth == nil) then return "Hidden" end
return strUnitCategory
end
function TwinkiePlates:SetCombatState(tNameplate, bIsInCombat)
-- Do nothing because combat state change event is too unreliable for PCs
-- Combat state change detection is performed on frame
--[[
if (tNameplate == nil) then return
end
-- If combat state changed
if (tNameplate.bIsInCombat ~= bIsInCombat) then
tNameplate.bIsInCombat = bIsInCombat
tNameplate.nMatrixFlags = self:GetCombatStateDependentFlags(tNameplate)
self:UpdateTextNameGuild(tNameplate)
self:UpdateTopContainer(tNameplate)
end
self:UpdateHealthShieldText(tNameplate)
]]
end
function TwinkiePlates:HasActivationState(unitNameplateOwner)
local tActivationStates = unitNameplateOwner:GetActivationState()
if (_next(tActivationStates) == nil) then return false
end
local bShow = false
for strState, a in _pairs(tActivationStates) do
if (strState == "Busy") then return false
end
if (not _asbl[strState]) then bShow = true
end
end
return bShow
end
function TwinkiePlates:SetProgressBar(p_bar, p_current, p_max)
p_bar:SetMax(p_max)
p_bar:SetProgress(p_current)
end
function TwinkiePlates:SetNameplateVerticalOffset(tNameplate, nVerticalOffset, nNameplacerVerticalOffset)
tNameplate.wndNameplate:SetAnchorOffsets(-200, -75 - nVerticalOffset - nNameplacerVerticalOffset, 200, 75 - nVerticalOffset - nNameplacerVerticalOffset)
if self.perspectivePlates then
local bounds = {}
bounds.left = -200
bounds.top = -75 - nVerticalOffset - nNameplacerVerticalOffset
bounds.right = 200
bounds.bottom = 75 - nVerticalOffset - nNameplacerVerticalOffset
tNameplate.unitOwner = tNameplate.unitNameplateOwner
self.perspectivePlates:OnRequestedResize(tNameplate, 1, bounds)
end
end
function TwinkiePlates:AllocateNameplate(unitNameplateOwner)
if (self.tNameplates[unitNameplateOwner:GetId()] == nil) then
local strUnitCategoryType = self:GetUnitCategoryType(unitNameplateOwner)
if (strUnitCategoryType ~= "Hidden") then
local l_nameplate = self:InitNameplate(unitNameplateOwner, _tableRemove(self.pool) or nil)
self.tNameplates[unitNameplateOwner:GetId()] = l_nameplate
end
end
end
function TwinkiePlates:OnUnitDestroyed(unitNameplateOwner)
local tNameplate = self.tNameplates[unitNameplateOwner:GetId()]
if (tNameplate == nil) then return
end
if (#self.pool < 50) then
tNameplate.wndNameplate:Show(false, true)
tNameplate.wndNameplate:SetUnit(nil)
tNameplate.wndUnitNameText:SetData(nil)
tNameplate.wndHealthProgressBar:SetData(nil)
tNameplate.bIsVerticalOffsetUpdated = nil
_tableInsert(self.pool, tNameplate)
else
tNameplate.wndNameplate:Destroy()
end
self.tNameplates[unitNameplateOwner:GetId()] = nil
end
function TwinkiePlates:UpdateMainContainerHeightWithHealthText(p_nameplate)
-- local l_fontSize = _tSettings["SliderFontSize"]
-- local l_zoomSliderH = _tSettings["SliderBarScale"] / 10
-- local l_shieldHeight = p_nameplate.bHasShield and l_zoomSliderH * 1.3 or l_zoomSliderH
-- local l_healthTextFont = _tSettings["ConfigAlternativeFont"] and _fontSecondary or _fontPrimary
-- local l_healthTextHeight = _tSettings["ConfigHealthText"] and (l_healthTextFont[l_fontSize].height * 0.75) or 0
-- p_nameplate.wndHealthProgressBar:SetAnchorOffsets(0, 0, 0, --[[l_shieldHeight + l_healthTextHeight]] p_nameplate.bHasShield and 0 or -4)
p_nameplate.wndHealthText:Show(true)
end
function TwinkiePlates:UpdateMainContainerHeightWithoutHealthText(p_nameplate)
-- Reset text
-- Set container height without text
-- local l_zoomSliderH = _tSettings["SliderBarScale"] / 10
-- local l_shieldHeight = p_nameplate.bHasShield and l_zoomSliderH * 1.3 or l_zoomSliderH
-- p_nameplate.wndContainerMain:SetAnchorOffsets(144, -5, -144, --[[l_shieldHeight]] 16)
p_nameplate.wndHealthText:Show(false)
end
-------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------
-- Configuration Functions
---------------------------------------------------------------------------------------------------
function TwinkiePlates:OnButtonSignalShowInfoPanel(wndHandler, wndControl, eMouseButton)
end
local TwinkiePlatesInst = TwinkiePlates:new()
TwinkiePlatesInst:Init()
function table.val_to_str(v)
if "string" == type(v) then
v = string.gsub(v, "\n", "\\n")
if string.match(string.gsub(v, "[^'\"]", ""), '^"+$') then
return "'" .. v .. "'"
end
return '"' .. string.gsub(v, '"', '\\"') .. '"'
else
return "table" == type(v) and table.tostring(v) or
tostring(v)
end
end
function table.key_to_str(k)
if "string" == type(k) and string.match(k, "^[_%a][_%a%d]*$") then
return k
else
return "[" .. table.val_to_str(k) .. "]"
end
end
function table.tostring(tbl)
if (not tbl) then return "nil"
end
local result, done = {}, {}
for k, v in ipairs(tbl) do
table.insert(result, table.val_to_str(v))
done[k] = true
end
for k, v in pairs(tbl) do
if not done[k] then
table.insert(result,
table.key_to_str(k) .. "=" .. table.val_to_str(v))
end
end
return "{" .. table.concat(result, ",") .. "}"
end
| mit |
lichtl/darkstar | scripts/zones/Northern_San_dOria/npcs/Vamorcote.lua | 13 | 2690 | -----------------------------------
-- Area: Northern San d'Oria
-- NPC: Vamorcote
-- Starts and Finishes Quest: The Setting Sun
-- @zone 231
-- @pos -137.070 10.999 161.855
--
-- Auto-Script: Requires Verification (Verified by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/globals/settings");
require("scripts/zones/Northern_San_dOria/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
-- "The Setting Sun" conditional script
if (player:getQuestStatus(SANDORIA,THE_SETTING_SUN) == QUEST_ACCEPTED) then
if (trade:hasItemQty(535,1) and trade:getItemCount() == 1) then
player:startEvent (0x0292)
end;
end;
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
-- Look at the "The Setting Sun" quest status and San d'Oria player's fame
theSettingSun = player:getQuestStatus(SANDORIA,THE_SETTING_SUN);
if (theSettingSun == QUEST_AVAILABLE and
player:getFameLevel(SANDORIA) >= 5 and
player:getQuestStatus(SANDORIA, BLACKMAIL) ~= QUEST_COMPLETED)
then
player:startEvent(0x028e,0,535,535); --The quest is offered to the player.
elseif (theSettingSun == QUEST_ACCEPTED) then
player:startEvent(0x028f,0,0,535); --The NPC asks if the player got the key.'
elseif (theSettingSun == QUEST_COMPLETED and player:needToZone()) then
player:startEvent(0x0293); --The quest is already done by the player and the NPC does small talks.
else
player:startEvent(0x028b);
end;
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x028e and option == 1) then --Player accepts the quest
player:addQuest(SANDORIA,THE_SETTING_SUN);
elseif (csid == 0x0292) then --The player trades the Engraved Key to the NPC. Here come the rewards!
player:tradeComplete();
player:addGil(GIL_RATE*10000);
player:messageSpecial(GIL_OBTAINED,GIL_RATE*10000);
player:addFame(SANDORIA,30);
player:completeQuest(SANDORIA,THE_SETTING_SUN);
end;
end;
| gpl-3.0 |
raingloom/yaoui | examples/anime/main.lua | 2 | 15447 | yui = require 'yaoui'
function love.load()
yui.UI.registerEvents()
love.graphics.setBackgroundColor(23, 24, 27)
love.window.setMode(1200, 755)
-- Create anime grid
anime_view = generateAnimeGrid('All')
-- Create top left tabs bar
tabs_bar = yui.View(0, 0, 600, 80, {
yui.Stack({
bottom = {
yui.Flow({
yui.Tabs({
tabs = {
{text = 'All', hover = 'All', onClick = function(self) anime_view = regenerateAnimeGrid('All') end},
{text = 'Action', hover = 'Action', onClick = function(self) anime_view = regenerateAnimeGrid({'Action'}) end},
{text = 'Fantasy', hover = 'Fantasy', onClick = function(self) anime_view = regenerateAnimeGrid({'Fantasy'}) end},
{text = 'Magic', hover = 'Magic', onClick = function(self) anime_view = regenerateAnimeGrid({'Magic'}) end},
{text = 'Sci-Fi', hover = 'Sci-Fi', onClick = function(self) anime_view = regenerateAnimeGrid({'Sci-Fi'}) end},
{text = 'Shounen', hover = 'Shounen', onClick = function(self) anime_view = regenerateAnimeGrid({'Shounen'}) end},
{text = 'Super Power', hover = 'Super Power', onClick = function(self) anime_view = regenerateAnimeGrid({'Super Power'}) end},
{text = 'Supernatural', hover = 'Supernatural', onClick = function(self) anime_view = regenerateAnimeGrid({'Supernatural'}) end},
}
}),
}),
}
})
})
-- Create top right dropdown + settings bar
right_bar = yui.View(600, 0, 600, 80, {
yui.Stack({
bottom = {
yui.Flow({margin_right = 10, spacing = 5,
yui.Dropdown({
options = {
'All',
'Action', 'Adventure', 'Comedy', 'Drama', 'Fantasy', 'Historical', 'Horror', 'Magic', 'Mecha', 'Military', 'Music',
'Mystery', 'Parody', 'Police', 'Psychological', 'Romance', 'Samurai', 'School', 'Sci-Fi', 'Seinen', 'Shounen',
'Slice of Life', 'Space', 'Sports', 'Super Power', 'Supernatural', 'Thriller',
},
onSelect = function(self, option)
if option == 'All' then anime_view = regenerateAnimeGrid(option)
else anime_view = regenerateAnimeGrid({option}) end
end,
}),
right = {
yui.IconButton({icon = 'fa-cutlery', hover = 'PORN', size = 28}),
yui.IconButton({icon = 'fa-eye', hover = 'PORN', size = 28}),
yui.HorizontalSpacing({w = 1}),
yui.IconButton({icon = 'fa-wheelchair', hover = 'PORN', size = 28}),
yui.IconButton({icon = 'fa-bell', hover = 'the Bells of Awakening', size = 28}),
yui.IconButton({icon = 'fa-tree', hover = 'PORN', size = 28}),
yui.IconButton({icon = 'fa-cog', hover = 'Settings', size = 28}),
},
})
}
})
})
-- Store ImageButton objects so that they don't have to be recreated on regeneration
-- Recreating too many objects (which would happen if we recreated them on every regeneration)
-- currently bugs Thranduil out and I haven't figured out a fix
animes = {}
for i = 1, 8 do table.insert(animes, anime_view[1][1][i]) end
for i = 1, 8 do table.insert(animes, anime_view[1][2][i]) end
for i = 1, 8 do table.insert(animes, anime_view[1][3][i]) end
end
function love.update(dt)
yui.update({anime_view, tabs_bar, right_bar})
anime_view:update(dt)
tabs_bar:update(dt)
right_bar:update(dt)
end
function love.draw()
anime_view:draw()
love.graphics.setColor(unpack(yui.Theme.colors.hover_bg))
love.graphics.rectangle('fill', 0, 0, 1200, 80)
love.graphics.setColor(255, 255, 255)
tabs_bar:draw()
right_bar:draw()
end
function regenerateAnimeGrid(genres_filter)
local animeGenreInGenresFilter = function(anime_genres, genres_filter)
for _, genre in ipairs(anime_genres) do
for _, filter_genre in ipairs(genres_filter) do
if genre == filter_genre then return true end
end
end
end
local anime_info = getAnimeInfo()
local grid = {}
for i = 1, 24 do
local insert_current_anime = false
if genres_filter == 'All' then insert_current_anime = true
elseif animeGenreInGenresFilter(anime_info[i].genres, genres_filter) then insert_current_anime = true end
if insert_current_anime then table.insert(grid, animes[i]) end
end
local rows = {}
rows[1], rows[2], rows[3] = {}, {}, {}
for i = 1, 8 do table.insert(rows[1], grid[i]) end
for i = 9, 16 do table.insert(rows[2], grid[i]) end
for i = 17, 24 do table.insert(rows[3], grid[i]) end
local anime_view = yui.View(0, 80, 1200, 755, {
yui.Stack({
yui.Flow(rows[1]),
yui.Flow(rows[2]),
yui.Flow(rows[3]),
})
})
return anime_view
end
function generateAnimeGrid()
local anime_info = getAnimeInfo()
local grid = {}
for i = 1, 24 do
table.insert(grid, yui.ImageButton({
image = anime_info[i].image,
w = 150, h = 225,
ix = anime_info[i].image_offsets[1] or 0,
iy = anime_info[i].image_offsets[2] or 0,
onClick = function(self)
love.system.openURL(anime_info[i].link)
end,
overlayNew = function(self)
self.font_awesome_font = love.graphics.newFont(self.yui.Theme.font_awesome_path, 14)
self.overlay_font = love.graphics.newFont(self.yui.Theme.open_sans_bold, 14)
self.title = anime_info[i].title
self.score = anime_info[i].score
end,
overlay = function(self)
-- Draw overlay rectangle
love.graphics.setColor(50, 50, 50, self.alpha/3)
love.graphics.rectangle('fill', self.x, self.y, self.w, self.h)
-- Draw title
if self.title then
local r, g, b = unpack(self.yui.Theme.colors.text_light)
love.graphics.setColor(r, g, b, self.alpha)
love.graphics.setFont(self.overlay_font)
if type(self.title) == 'string' then
love.graphics.print(self.title, self.x + self.w - self.overlay_font:getWidth(self.title) - 10, self.y + 5)
elseif type(self.title) == 'table' then
love.graphics.print(self.title[1], self.x + self.w - self.overlay_font:getWidth(self.title[1]) - 10, self.y + 5)
love.graphics.print(self.title[2], self.x + self.w - self.overlay_font:getWidth(self.title[2]) - 10, self.y + self.overlay_font:getHeight() + 5)
end
love.graphics.setColor(255, 255, 255, 255)
end
-- Draw score
love.graphics.setColor(255, 255, 255, self.alpha)
local score_text = self.score .. '/10'
local score_text_w = self.overlay_font:getWidth(score_text)
love.graphics.print(score_text,
self.x + self.w - score_text_w - 5,
self.y + self.h - 5 - self.overlay_font:getHeight())
-- Draw stars
love.graphics.setFont(self.font_awesome_font)
love.graphics.setColor(222, 222, 64, self.alpha)
love.graphics.setScissor(self.x + 5,
self.y + self.h - 6 - self.font_awesome_font:getHeight(),
(self.score/10)*75,
self.font_awesome_font:getHeight())
love.graphics.print(self.yui.Theme.font_awesome['fa-star'], self.x + 5, self.y + self.h - 6 - self.font_awesome_font:getHeight())
love.graphics.print(self.yui.Theme.font_awesome['fa-star'], self.x + 5 + 15, self.y + self.h - 6 - self.font_awesome_font:getHeight())
love.graphics.print(self.yui.Theme.font_awesome['fa-star'], self.x + 5 + 30, self.y + self.h - 6 - self.font_awesome_font:getHeight())
love.graphics.print(self.yui.Theme.font_awesome['fa-star'], self.x + 5 + 45, self.y + self.h - 6 - self.font_awesome_font:getHeight())
love.graphics.print(self.yui.Theme.font_awesome['fa-star'], self.x + 5 + 60, self.y + self.h - 6 - self.font_awesome_font:getHeight())
love.graphics.setScissor()
love.graphics.setFont(self.overlay_font)
love.graphics.setColor(255, 255, 255, 255)
end,
}))
end
local rows = {}
rows[1], rows[2], rows[3] = {}, {}, {}
for i = 1, 8 do table.insert(rows[1], grid[i]) end
for i = 9, 16 do table.insert(rows[2], grid[i]) end
for i = 17, 24 do table.insert(rows[3], grid[i]) end
local anime_view = yui.View(0, 80, 1200, 755, {
yui.Stack({
yui.Flow(rows[1]),
yui.Flow(rows[2]),
yui.Flow(rows[3]),
})
})
return anime_view
end
function getAnimeInfo()
local info = {}
local titles = {
'Shin Sekai Yori', 'Hunter x Hunter', {'Fullmetal Alchemist', 'Brotherhood'}, 'Steins;Gate', 'Gintama', {'Clannad', 'After Story'},
{'Great Teacher', 'Onizuka'}, 'Death Note', 'Monster', {"Howl's Moving", "Castle"}, 'Haikyuu!!', 'Attack on Titan',
{'The Disappearance', 'of Haruhi Suzumiya'}, 'Hajime no Ippo', 'Samurai X', 'Gurren Lagann', 'Mononoke Hime', 'Fate/Zero',
{'Legend of Galactic', 'Heroes'}, 'Code Geass', 'Spirited Away', 'Your Lie in April', 'Mushishi', 'Wolf Children'
}
local scores = {
8.54, 9.15, 9.25, 9.18, 9.16, 9.12,
8.79, 8.76, 8.75, 8.73, 8.67, 8.68,
8.88, 8.86, 8.45, 8.82, 8.81, 8.58,
9.08, 8.86, 8.93, 8.93, 8.80, 8.88,
}
local genres = {
{'Mystery', 'Drama', 'Horror', 'Sci-Fi', 'Supernatural'},
{'Action', 'Adventure', 'Shounen', 'Super Power'},
{'Action', 'Adventure', 'Drama', 'Fantasy', 'Magic', 'Shounen', 'Military'},
{'Sci-Fi', 'Thriller'},
{'Action', 'Comedy', 'Historical', 'Parody', 'Samurai', 'Sci-Fi', 'Shounen'},
{'Drama', 'Fantasy', 'Romance', 'Slice of Life', 'Supernatural'},
{'Comedy', 'Drama', 'School', 'Shounen', 'Slice of Life'},
{'Mystery', 'Supernatural', 'Police', 'Psychological', 'Thriller'},
{'Mystery', 'Drama', 'Horror', 'Police', 'Psychological', 'Thriller', 'Seinen'},
{'Adventure', 'Drama', 'Fantasy', 'Romance'},
{'Comedy', 'Drama', 'School', 'Shounen', 'Sports'},
{'Action', 'Drama', 'Fantasy', 'Shounen', 'Super Power'},
{'Comedy', 'Mystery', 'Romance', 'School', 'Sci-Fi', 'Supernatural'},
{'Comedy', 'Drama', 'Shounen', 'Sports'},
{'Action', 'Adventure', 'Comedy', 'Historical', 'Samurai', 'Romance'},
{'Action', 'Comedy', 'Mecha', 'Sci-Fi'},
{'Action', 'Adventure', 'Fantasy'},
{'Action', 'Fantasy', 'Supernatural'},
{'Drama', 'Sci-Fi', 'Space', 'Military'},
{'Action', 'Mecha', 'School', 'Sci-Fi', 'Super Power', 'Military'},
{'Adventure', 'Drama', 'Supernatural'},
{'Drama', 'Music', 'Romance', 'School', 'Shounen'},
{'Adventure', 'Mystery', 'Fantasy', 'Historical', 'Slice of Life', 'Supernatural', 'Seinen'},
{'Fantasy', 'Slice of Life'},
}
local images = {
love.graphics.newImage('images/ssy.jpg'),
love.graphics.newImage('images/hxh.jpg'),
love.graphics.newImage('images/fma.jpg'),
love.graphics.newImage('images/sg.jpg'),
love.graphics.newImage('images/gin.jpg'),
love.graphics.newImage('images/clan.jpg'),
love.graphics.newImage('images/oni.jpg'),
love.graphics.newImage('images/dn.jpg'),
love.graphics.newImage('images/mons.jpg'),
love.graphics.newImage('images/howl.jpg'),
love.graphics.newImage('images/hai.jpg'),
love.graphics.newImage('images/tit.jpg'),
love.graphics.newImage('images/haru.jpg'),
love.graphics.newImage('images/ippo.jpg'),
love.graphics.newImage('images/x.jpg'),
love.graphics.newImage('images/lag.jpg'),
love.graphics.newImage('images/hime.jpg'),
love.graphics.newImage('images/fate.jpg'),
love.graphics.newImage('images/den.jpg'),
love.graphics.newImage('images/geass.jpg'),
love.graphics.newImage('images/sen.jpg'),
love.graphics.newImage('images/lie.jpg'),
love.graphics.newImage('images/shi.jpg'),
love.graphics.newImage('images/wolf.jpg'),
}
local image_offsets = {
{450, 160}, {55, 50}, {40, 60}, {50, 80}, {20, 0}, {260, 130}, {10, 10}, {30, 30},
{175, 80}, {70, 0}, {150, 240}, {240, 40}, {45, 60}, {20, 0}, {50, 80}, {25, 0},
{60, 20}, {180, 180}, {80, 0}, {30, 10}, {50, 25}, {20, 30}, {25, 80}, {50, 120},
}
local links = {
'http://myanimelist.net/anime/13125/Shinsekai_yori',
'http://myanimelist.net/anime/11061/Hunter_x_Hunter_%282011%29',
'http://myanimelist.net/anime/5114/Fullmetal_Alchemist:_Brotherhood',
'http://myanimelist.net/anime/9253/Steins;Gate',
'http://myanimelist.net/anime/28977/Gintama%C2%B0',
'http://myanimelist.net/anime/4181/Clannad:_After_Story',
'http://myanimelist.net/anime/245/Great_Teacher_Onizuka',
'http://myanimelist.net/anime/1535/Death_Note',
'http://myanimelist.net/anime/19/Monster',
'http://myanimelist.net/anime/431/Howl_no_Ugoku_Shiro',
'http://myanimelist.net/anime/20583/Haikyuu!!',
'http://myanimelist.net/anime/16498/Shingeki_no_Kyojin',
'http://myanimelist.net/anime/7311/Suzumiya_Haruhi_no_Shoushitsu',
'http://myanimelist.net/anime/263/Hajime_no_Ippo',
'http://myanimelist.net/anime/45/Rurouni_Kenshin:_Meiji_Kenkaku_Romantan',
'http://myanimelist.net/anime/2001/Tengen_Toppa_Gurren_Lagann',
'http://myanimelist.net/anime/164/Mononoke_Hime',
'http://myanimelist.net/anime/10087/Fate_Zero',
'http://myanimelist.net/anime/820/Ginga_Eiyuu_Densetsu',
'http://myanimelist.net/anime/1575/Code_Geass:_Hangyaku_no_Lelouch',
'http://myanimelist.net/anime/199/Sen_to_Chihiro_no_Kamikakushi',
'http://myanimelist.net/anime/23273/Shigatsu_wa_Kimi_no_Uso',
'http://myanimelist.net/anime/457/Mushishi',
'http://myanimelist.net/anime/12355/Ookami_Kodomo_no_Ame_to_Yuki',
}
for i = 1, 24 do
table.insert(info, {
title = titles[i],
link = links[i],
score = scores[i],
image = images[i],
image_offsets = image_offsets[i] or {},
genres = genres[i],
})
end
return info
end
| mit |
RunAwayDSP/darkstar | scripts/zones/Rabao/npcs/Shupah_Mujuuk.lua | 12 | 3349 | -----------------------------------
-- Area: Rabao
-- NPC: Shupah Mujuuk
-- Title Change NPC
-- !pos 12 8 20 247
-----------------------------------
require("scripts/globals/titles")
-----------------------------------
local eventId = 1011
local titleInfo =
{
{
cost = 200,
title =
{
dsp.title.THE_IMMORTAL_FISHER_LU_SHANG,
dsp.title.INDOMITABLE_FISHER,
dsp.title.KUFTAL_TOURIST,
dsp.title.ACQUIRER_OF_ANCIENT_ARCANUM,
dsp.title.DESERT_HUNTER,
dsp.title.ROOKIE_HERO_INSTRUCTOR,
},
},
{
cost = 300,
title =
{
dsp.title.HEIR_OF_THE_GREAT_WIND,
},
},
{
cost = 400,
title =
{
dsp.title.FODDERCHIEF_FLAYER,
dsp.title.WARCHIEF_WRECKER,
dsp.title.DREAD_DRAGON_SLAYER,
dsp.title.OVERLORD_EXECUTIONER,
dsp.title.DARK_DRAGON_SLAYER,
dsp.title.ADAMANTKING_KILLER,
dsp.title.BLACK_DRAGON_SLAYER,
dsp.title.MANIFEST_MAULER,
dsp.title.BEHEMOTHS_BANE,
dsp.title.ARCHMAGE_ASSASSIN,
dsp.title.HELLSBANE,
dsp.title.GIANT_KILLER,
dsp.title.LICH_BANISHER,
dsp.title.JELLYBANE,
dsp.title.BOGEYDOWNER,
dsp.title.BEAKBENDER,
dsp.title.SKULLCRUSHER,
dsp.title.MORBOLBANE,
dsp.title.GOLIATH_KILLER,
dsp.title.MARYS_GUIDE,
},
},
{
cost = 500,
title =
{
dsp.title.SIMURGH_POACHER,
dsp.title.ROC_STAR,
dsp.title.SERKET_BREAKER,
dsp.title.CASSIENOVA,
dsp.title.THE_HORNSPLITTER,
dsp.title.TORTOISE_TORTURER,
dsp.title.MON_CHERRY,
dsp.title.BEHEMOTH_DETHRONER,
dsp.title.THE_VIVISECTOR,
dsp.title.DRAGON_ASHER,
dsp.title.EXPEDITIONARY_TROOPER,
},
},
{
cost = 600,
title =
{
dsp.title.ADAMANTKING_USURPER,
dsp.title.OVERLORD_OVERTHROWER,
dsp.title.DEITY_DEBUNKER,
dsp.title.FAFNIR_SLAYER,
dsp.title.ASPIDOCHELONE_SINKER,
dsp.title.NIDHOGG_SLAYER,
dsp.title.MAAT_MASHER,
dsp.title.KIRIN_CAPTIVATOR,
dsp.title.CACTROT_DESACELERADOR,
dsp.title.LIFTER_OF_SHADOWS,
dsp.title.TIAMAT_TROUNCER,
dsp.title.VRTRA_VANQUISHER,
dsp.title.WORLD_SERPENT_SLAYER,
dsp.title.XOLOTL_XTRAPOLATOR,
dsp.title.BOROKA_BELEAGUERER,
dsp.title.OURYU_OVERWHELMER,
dsp.title.VINEGAR_EVAPORATOR,
dsp.title.VIRTUOUS_SAINT,
dsp.title.BYEBYE_TAISAI,
dsp.title.TEMENOS_LIBERATOR,
dsp.title.APOLLYON_RAVAGER,
dsp.title.WYRM_ASTONISHER,
dsp.title.NIGHTMARE_AWAKENER,
},
},
}
function onTrade(player,npc,trade)
end
function onTrigger(player,npc)
dsp.title.changerOnTrigger(player, eventId, titleInfo)
end
function onEventUpdate(player,csid,option)
end
function onEventFinish(player,csid,option)
dsp.title.changerOnEventFinish(player, csid, option, eventId, titleInfo)
end | gpl-3.0 |
lichtl/darkstar | scripts/zones/Windurst_Walls/npcs/Jack_of_Diamonds.lua | 17 | 1238 | -----------------------------------
-- Area: Windurst Walls
-- NPC: Jack of Diamonds
-- Adventurer's Assistant
-- Working 100%
-------------------------------------
require("scripts/globals/settings");
package.loaded["scripts/zones/Windurst_Walls/TextIDs"] = nil;
require("scripts/zones/Windurst_Walls/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (trade:getItemCount() == 1 and trade:hasItemQty(0x218,1) == true) then
player:startEvent(0x2712,GIL_RATE*50);
player:addGil(GIL_RATE*50);
player:tradeComplete();
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x2711,0,2);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
sjznxd/lc-20130222 | applications/luci-statistics/luasrc/model/cbi/luci_statistics/rrdtool.lua | 80 | 3431 | --[[
Luci configuration model for statistics - collectd rrdtool plugin configuration
(c) 2008 Freifunk Leipzig / Jo-Philipp Wich <xm@leipzig.freifunk.net>
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
$Id$
]]--
m = Map("luci_statistics",
translate("RRDTool Plugin Configuration"),
translate(
"The rrdtool plugin stores the collected data in rrd database " ..
"files, the foundation of the diagrams.<br /><br />" ..
"<strong>Warning: Setting the wrong values will result in a very " ..
"high memory consumption in the temporary directory. " ..
"This can render the device unusable!</strong>"
))
-- collectd_rrdtool config section
s = m:section( NamedSection, "collectd_rrdtool", "luci_statistics" )
-- collectd_rrdtool.enable
enable = s:option( Flag, "enable", translate("Enable this plugin") )
enable.default = 1
-- collectd_rrdtool.datadir (DataDir)
datadir = s:option( Value, "DataDir", translate("Storage directory") )
datadir.default = "/tmp"
datadir.rmempty = true
datadir.optional = true
datadir:depends( "enable", 1 )
-- collectd_rrdtool.stepsize (StepSize)
stepsize = s:option( Value, "StepSize",
translate("RRD step interval"), translate("Seconds") )
stepsize.default = 30
stepsize.isinteger = true
stepsize.rmempty = true
stepsize.optional = true
stepsize:depends( "enable", 1 )
-- collectd_rrdtool.heartbeat (HeartBeat)
heartbeat = s:option( Value, "HeartBeat",
translate("RRD heart beat interval"), translate("Seconds") )
heartbeat.default = 60
heartbeat.isinteger = true
heartbeat.rmempty = true
heartbeat.optional = true
heartbeat:depends( "enable", 1 )
-- collectd_rrdtool.rrasingle (RRASingle)
rrasingle = s:option( Flag, "RRASingle",
translate("Only create average RRAs"), translate("reduces rrd size") )
rrasingle.default = true
rrasingle.rmempty = true
rrasingle.optional = true
rrasingle:depends( "enable", 1 )
-- collectd_rrdtool.rratimespans (RRATimespan)
rratimespans = s:option( Value, "RRATimespans",
translate("Stored timespans"), translate("seconds; multiple separated by space") )
rratimespans.default = "600 86400 604800 2678400 31622400"
rratimespans.rmempty = true
rratimespans.optional = true
rratimespans:depends( "enable", 1 )
-- collectd_rrdtool.rrarows (RRARows)
rrarows = s:option( Value, "RRARows", translate("Rows per RRA") )
rrarows.isinteger = true
rrarows.default = 100
rrarows.rmempty = true
rrarows.optional = true
rrarows:depends( "enable", 1 )
-- collectd_rrdtool.xff (XFF)
xff = s:option( Value, "XFF", translate("RRD XFiles Factor") )
xff.default = 0.1
xff.isnumber = true
xff.rmempty = true
xff.optional = true
xff:depends( "enable", 1 )
-- collectd_rrdtool.cachetimeout (CacheTimeout)
cachetimeout = s:option( Value, "CacheTimeout",
translate("Cache collected data for"), translate("Seconds") )
cachetimeout.isinteger = true
cachetimeout.default = 100
cachetimeout.rmempty = true
cachetimeout.optional = true
cachetimeout:depends( "enable", 1 )
-- collectd_rrdtool.cacheflush (CacheFlush)
cacheflush = s:option( Value, "CacheFlush",
translate("Flush cache after"), translate("Seconds") )
cacheflush.isinteger = true
cacheflush.default = 100
cacheflush.rmempty = true
cacheflush.optional = true
cacheflush:depends( "enable", 1 )
return m
| apache-2.0 |
lichtl/darkstar | scripts/zones/Port_Windurst/npcs/Taniko-Maniko.lua | 17 | 1797 | -----------------------------------
-- Area: Port Windurst
-- NPC: Taniko-Maniko
-- Standard Merchant NPC
-- Confirmed shop stock, August 2013
-----------------------------------
require("scripts/globals/shop");
package.loaded["scripts/zones/Port_Windurst/TextIDs"] = nil;
require("scripts/zones/Port_Windurst/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,TANIKOMANIKO_SHOP_DIALOG);
stock = {
0x4181, 2542,1, --Brass Zaghnal
0x4302, 7128,1, --Wrapped Bow
0x43AB, 162,1, --Ice Arrow
0x43AC, 162,1, --Lightning Arrow
0x4015, 104,2, --Cat Baghnakhs
0x4001, 129,2, --Cesti
0x4109, 5864,2, --Bone Pick
0x4301, 482,2, --Self Bow
0x43A6, 3,2, --Wooden Arrow
0x439C, 54,2, --Hawkeye
0x4380, 1575,2, --Boomerang
0x4102, 4198,3, --Bone Axe
0x4180, 309,3, --Bronze Zaghnal
0x41C0, 97,3, --Harpoon
0x4300, 39,3, --Shortbow
0x43A7, 4,3 --Bone Arrow
}
showNationShop(player, NATION_WINDURST, stock);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
lichtl/darkstar | scripts/zones/Southern_San_dOria/npcs/Lotte.lua | 17 | 1455 | -----------------------------------
-- Area: Southern San d'Oria
-- NPC: Lotte
-- General Info NPC
-------------------------------------
package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Southern_San_dOria/TextIDs");
require("scripts/globals/settings");
require("scripts/globals/quests");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
-- "Flyers for Regine" conditional script
local FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE);
if (FlyerForRegine == 1) then
local count = trade:getItemCount();
local MagicFlyer = trade:hasItemQty(532,1);
if (MagicFlyer == true and count == 1) then
player:messageSpecial(FLYER_REFUSED);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x234);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
RunAwayDSP/darkstar | scripts/globals/mobskills/gregale_wing_air.lua | 11 | 1147 | ---------------------------------------------
-- Gregale Wing
--
-- Description: An icy wind deals Ice damage to enemies within a very wide area of effect. Additional effect: Paralyze
-- Type: Magical
-- Utsusemi/Blink absorb: Wipes shadows
-- Range: 30' radial.
-- Notes: Used only Jormungand and Isgebind
---------------------------------------------
require("scripts/globals/settings")
require("scripts/globals/status")
require("scripts/globals/monstertpmoves")
---------------------------------------------
function onMobSkillCheck(target,mob,skill)
if (mob:AnimationSub() ~= 1) then
return 1
end
return 0
end
function onMobWeaponSkill(target, mob, skill)
local typeEffect = dsp.effect.PARALYSIS
MobStatusEffectMove(mob, target, typeEffect, 40, 0, 120)
local dmgmod = 1
local info = MobMagicalMove(mob,target,skill,mob:getWeaponDmg()*5,dsp.magic.ele.ICE,dmgmod,TP_NO_EFFECT)
local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,dsp.attackType.MAGICAL,dsp.damageType.ICE,MOBPARAM_WIPE_SHADOWS)
target:takeDamage(dmg, mob, dsp.attackType.MAGICAL, dsp.damageType.ICE)
return dmg
end
| gpl-3.0 |
lichtl/darkstar | scripts/zones/Bastok_Markets/npcs/Zacc.lua | 14 | 1605 | -----------------------------------
-- Area: Bastok Markets
-- NPC: Zacc
-- Type: Quest NPC
-- @zone 235
-- @pos -255.709 -13 -91.379
-----------------------------------
package.loaded["scripts/zones/Bastok_Markets/TextIDs"] = nil;
require("scripts/zones/Bastok_Markets/TextIDs");
require("scripts/globals/quests");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getQuestStatus(BASTOK, WISH_UPON_A_STAR) == QUEST_COMPLETED) then -- Quest: Wish Upon a Star - Quest has been completed.
player:startEvent(0x0150);
elseif (player:getFameLevel(BASTOK) > 4 and player:getQuestStatus(BASTOK, WISH_UPON_A_STAR) == QUEST_AVAILABLE) then -- Quest: Wish Upon a Star - Start quest.
player:startEvent(0x0149);
else -- Standard dialog
player:startEvent(0x0148);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x0149) then -- Quest: Wish Upon a Star
player:addQuest(BASTOK, WISH_UPON_A_STAR);
player:setVar("WishUponAStar_Status", 1);
end
end;
| gpl-3.0 |
lichtl/darkstar | scripts/zones/Southern_San_dOria/npcs/Emoussine.lua | 27 | 2406 | -----------------------------------
-- Area: Southern San d'Oria
-- NPC: Emoussine
-- Type: Chocobo Renter
-- @pos -11 1 -100
-----------------------------------
package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/chocobo");
require("scripts/globals/keyitems");
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/zones/Southern_San_dOria/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (FlyerForRegine == 1) then
count = trade:getItemCount();
MagicFlyer = trade:hasItemQty(532,1);
if (MagicFlyer == true and count == 1) then
player:messageSpecial(FLYER_REFUSED);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local level = player:getMainLvl();
local gil = player:getGil();
if (player:hasKeyItem(CHOCOBO_LICENSE) and level >= 15) then
local price = getChocoboPrice(player);
player:setLocalVar("chocoboPriceOffer",price);
if (level >= 20) then
level = 0;
end
player:startEvent(0x0258,price,gil,level);
else
player:startEvent(0x025B);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish Action
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
local price = player:getLocalVar("chocoboPriceOffer");
if (csid == 0x0258 and option == 0) then
if (player:delGil(price)) then
updateChocoboPrice(player, price);
if (player:getMainLvl() >= 20) then
local duration = 1800 + (player:getMod(MOD_CHOCOBO_RIDING_TIME) * 60)
player:addStatusEffectEx(EFFECT_CHOCOBO,EFFECT_CHOCOBO,1,0,duration,true);
else
player:addStatusEffectEx(EFFECT_CHOCOBO,EFFECT_CHOCOBO,1,0,900,true);
end
player:setPos(-126,-62,274,0x65,0x64);
end
end
end; | gpl-3.0 |
lichtl/darkstar | scripts/zones/Ifrits_Cauldron/npcs/Flame_Spout.lua | 14 | 1607 | ----------------------------------
-- Area: Ifrit's Cauldron
-- NPC: Flame Spout
-- @pos 193.967 -0.400 19.492 205
-----------------------------------
require("scripts/zones/Ifrits_Cauldron/TextIDs");
require("scripts/globals/settings");
require("scripts/globals/quests");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
local npcid = npc:getID();
if (trade:getItemCount() == 1 and trade:hasItemQty(4105,1) == true) then -- Ice Cluster Trade
GetNPCByID(npcid+5):openDoor(90);
player:tradeComplete();
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
-- printf("%u",npc:getID())
local npcid = npc:getID();
-- Commented out to preserve CSIDs for the quest, since the workaround was removed.
--[[if (npcid == 17617204) then
player:startEvent(0x000b);
elseif (npcid == 17617205) then
player:startEvent(0x000c);
elseif (npcid == 17617206) then
player:startEvent(0x000d);
elseif (npcid == 17617207) then
player:startEvent(0x000e);
end]]
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end; | gpl-3.0 |
lichtl/darkstar | scripts/zones/Southern_San_dOria/npcs/Amaura.lua | 14 | 3069 | -----------------------------------
-- Area: Southern San d'Oria
-- NPC: Amaura
-- Involved in Quest: The Medicine Woman, To Cure a Cough
-- @zone 230
-- @pos -85 -6 89
-----------------------------------
package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/titles");
require("scripts/globals/keyitems");
require("scripts/globals/quests");
require("scripts/zones/Southern_San_dOria/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (player:hasKeyItem(AMAURAS_FORMULA) == true) then
if (trade:hasItemQty(920,1) == true and trade:hasItemQty(642,1) == true and trade:hasItemQty(846,1) == true and trade:getItemCount() == 3) then
player:startEvent(0x027D);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
medicineWoman = player:getQuestStatus(SANDORIA,THE_MEDICINE_WOMAN);
toCureaCough = player:getQuestStatus(SANDORIA,TO_CURE_A_COUGH);
if (medicineWoman == QUEST_ACCEPTED) then
amaurasFormulaKI = player:hasKeyItem(AMAURAS_FORMULA);
coldMedicine = player:hasKeyItem(COLD_MEDICINE);
if (amaurasFormulaKI == false and coldMedicine == false) then
player:startEvent(0x027C);
else
player:startEvent(0x0282);
end
elseif (player:getVar("DiaryPage") == 3 or toCureaCough == QUEST_ACCEPTED) then
if (player:hasKeyItem(THYME_MOSS) == false and player:hasKeyItem(COUGH_MEDICINE) == false) then
player:startEvent(0x0285); -- need thyme moss for cough med
elseif (player:hasKeyItem(THYME_MOSS) == true) then
player:startEvent(0x0286); -- receive cough med for Nenne
end
else
player:startEvent(0x0282);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x027C and option == 0) then
player:addKeyItem(AMAURAS_FORMULA);
player:messageSpecial(KEYITEM_OBTAINED,AMAURAS_FORMULA);
elseif (csid == 0x027D) then
player:tradeComplete();
player:delKeyItem(AMAURAS_FORMULA);
player:addKeyItem(COLD_MEDICINE);
player:messageSpecial(KEYITEM_OBTAINED,COLD_MEDICINE);
elseif (csid == 0x0285) then
player:addQuest(SANDORIA,TO_CURE_A_COUGH);
elseif (csid == 0x0286) then
player:delKeyItem(THYME_MOSS);
player:addKeyItem(COUGH_MEDICINE);
player:messageSpecial(KEYITEM_OBTAINED,COUGH_MEDICINE);
end
end; | gpl-3.0 |
lichtl/darkstar | scripts/zones/Valley_of_Sorrows/npcs/Field_Manual.lua | 29 | 1049 | -----------------------------------
-- Area: Valley of Sorrows
-- Field Manual
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/fieldsofvalor");
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
startFov(FOV_EVENT_SORROWS,player);
end;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onEventSelection
-----------------------------------
function onEventUpdate(player,csid,menuchoice)
updateFov(player,csid,menuchoice,139,140,141,0,0);
end;
-----------------------------------
-- onEventFinish Action
-----------------------------------
function onEventFinish(player,csid,option)
finishFov(player,csid,option,139,140,141,0,0,FOV_EVENT_SORROWS);
end;
| gpl-3.0 |
lichtl/darkstar | scripts/globals/effects/magic_shield.lua | 33 | 1698 | -----------------------------------
--
-- Magic Shield BLOCKS all magic attacks
--
-----------------------------------
require("scripts/globals/status");
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
if (effect:getPower() == 3) then -- arcane stomp
target:addMod(MOD_FIRE_ABSORB, 100);
target:addMod(MOD_EARTH_ABSORB, 100);
target:addMod(MOD_WATER_ABSORB, 100);
target:addMod(MOD_WIND_ABSORB, 100);
target:addMod(MOD_ICE_ABSORB, 100);
target:addMod(MOD_LTNG_ABSORB, 100);
target:addMod(MOD_LIGHT_ABSORB, 100);
target:addMod(MOD_DARK_ABSORB, 100);
elseif (effect:getPower() < 2) then
target:addMod(MOD_UDMGMAGIC, -101);
else
target:addMod(MOD_MAGIC_ABSORB, 100);
end;
end;
-----------------------------------
-- onEffectTick Action
-----------------------------------
function onEffectTick(target,effect)
end;
-----------------------------------
-- onEffectLose Action
-----------------------------------
function onEffectLose(target,effect)
if (effect:getPower() == 3) then -- arcane stomp
target:delMod(MOD_FIRE_ABSORB, 100);
target:delMod(MOD_EARTH_ABSORB, 100);
target:delMod(MOD_WATER_ABSORB, 100);
target:delMod(MOD_WIND_ABSORB, 100);
target:delMod(MOD_ICE_ABSORB, 100);
target:delMod(MOD_LTNG_ABSORB, 100);
target:delMod(MOD_LIGHT_ABSORB, 100);
target:delMod(MOD_DARK_ABSORB, 100);
elseif (effect:getPower() < 2) then
target:delMod(MOD_UDMGMAGIC, -101);
else
target:delMod(MOD_MAGIC_ABSORB, 100);
end;
end;
| gpl-3.0 |
lichtl/darkstar | scripts/zones/Xarcabard/npcs/Luck_Rune.lua | 14 | 1042 | -----------------------------------
-- Area: Xarcabard
-- NPC: Luck Rune
-- Involved in Quest: Mhaura Fortune
-- @pos 576.117 -0.164 -16.935 112
-----------------------------------
package.loaded["scripts/zones/Xarcabard/TextIDs"] = nil;
-------------------------------------
require("scripts/zones/Xarcabard/TextIDs");
-----------------------------------
-- onTrade
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger
-----------------------------------
function onTrigger(player,npc)
player:messageSpecial(NOTHING_OUT_OF_THE_ORDINARY);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end; | gpl-3.0 |
raingloom/yaoui | examples/anime/yaoui/UI/Draggable.lua | 9 | 4084 | local ui_path = (...):match('(.-)[^%.]+$') .. '.'
local Object = require(ui_path .. 'classic.classic')
local Draggable = Object:extend('Draggable')
function Draggable:draggableNew(settings)
local settings = settings or {}
self.dragging = false
self.drag_hot = false
self.drag_enter = false
self.drag_exit = false
self.drag_start = false
self.drag_end = false
self.drag_margin = settings.drag_margin or self.h/4
self.drag_x, self.drag_y = 0, 0
self.drag_min_limit_x, self.drag_min_limit_y = settings.drag_min_limit_x, settings.drag_min_limit_y
self.drag_max_limit_x, self.drag_max_limit_y = settings.drag_max_limit_x, settings.drag_max_limit_y
self.only_drag_horizontally = settings.only_drag_horizontally
self.only_drag_vertically = settings.only_drag_vertically
self.previous_drag_hot = false
self.drag_previous_mouse_position = nil
end
function Draggable:draggableUpdate(dt, parent)
local x, y = self.getMousePosition()
if self.draggable then
-- Check for drag_hot
if self.hot and x >= self.x and x <= (self.x + self.w) and y >= self.y and y <= (self.y + self.drag_margin) then
self.drag_hot = true
else self.drag_hot = false end
-- Check for drag_enter
if self.drag_hot and not self.previous_drag_hot then
self.drag_enter = true
else self.drag_enter = false end
-- Check for drag_exit
if not self.drag_hot and self.previous_drag_hot then
self.drag_exit = true
else self.drag_exit = false end
self.drag_start = false
self.drag_end = false
end
-- Drag
if self.drag_hot and self.input:pressed('left-click') then
self.dragging = true
self.drag_start = true
end
-- Resizing has precedence over dragging
if self.dragging and not self.resizing and self.input:down('left-click') then
local dx, dy = x - self.drag_previous_mouse_position.x, y - self.drag_previous_mouse_position.y
local parent_x, parent_y = 0, 0
if parent then parent_x, parent_y = parent.x, parent.y end
if self.only_drag_horizontally or (not self.only_drag_horizontally and not self.only_drag_vertically) then
self.drag_x = self.drag_x + dx
if self.drag_min_limit_x then
if (parent_x + self.ix + self.drag_x) < self.drag_min_limit_x then
self.drag_x = self.drag_x - dx
end
end
if self.drag_max_limit_x then
if (parent_x + self.ix + self.drag_x) > self.drag_max_limit_x then
self.drag_x = self.drag_x - dx
end
end
end
if self.only_drag_vertically or (not self.only_drag_vertically and not self.only_drag_horizontally) then
self.drag_y = self.drag_y + dy
if self.drag_min_limit_y then
if (parent_y + self.iy + self.drag_y) < self.drag_min_limit_y then
self.drag_y = self.drag_y - dy
end
end
if self.drag_max_limit_y then
if (parent_y + self.iy + self.drag_y) > self.drag_max_limit_y then
self.drag_y = self.drag_y - dy
end
end
end
end
if self.dragging and self.input:released('left-click') then
self.dragging = false
self.drag_end = true
end
if parent then self.x, self.y = parent.x + self.ix + self.drag_x + (self.resize_x or 0), parent.y + self.iy + self.drag_y + (self.resize_y or 0)
else self.x, self.y = self.ix + self.drag_x + (self.resize_x or 0), self.iy + self.drag_y + (self.resize_y or 0) end
-- Set previous frame state
self.previous_drag_hot = self.drag_hot
self.drag_previous_mouse_position = {x = x, y = y}
end
function Draggable:setDragLimits(x_min, y_min, x_max, y_max)
self.drag_min_limit_x = x_min
self.drag_min_limit_y = y_min
self.drag_max_limit_x = x_max
self.drag_max_limit_y = y_max
end
return Draggable
| mit |
sjznxd/lc-20130222 | applications/luci-firewall/luasrc/model/cbi/firewall/forwards.lua | 85 | 3942 | --[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Copyright 2010-2012 Jo-Philipp Wich <xm@subsignal.org>
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
]]--
local ds = require "luci.dispatcher"
local ft = require "luci.tools.firewall"
m = Map("firewall", translate("Firewall - Port Forwards"),
translate("Port forwarding allows remote computers on the Internet to \
connect to a specific computer or service within the \
private LAN."))
--
-- Port Forwards
--
s = m:section(TypedSection, "redirect", translate("Port Forwards"))
s.template = "cbi/tblsection"
s.addremove = true
s.anonymous = true
s.sortable = true
s.extedit = ds.build_url("admin/network/firewall/forwards/%s")
s.template_addremove = "firewall/cbi_addforward"
function s.create(self, section)
local n = m:formvalue("_newfwd.name")
local p = m:formvalue("_newfwd.proto")
local E = m:formvalue("_newfwd.extzone")
local e = m:formvalue("_newfwd.extport")
local I = m:formvalue("_newfwd.intzone")
local a = m:formvalue("_newfwd.intaddr")
local i = m:formvalue("_newfwd.intport")
if p == "other" or (p and a) then
created = TypedSection.create(self, section)
self.map:set(created, "target", "DNAT")
self.map:set(created, "src", E or "wan")
self.map:set(created, "dest", I or "lan")
self.map:set(created, "proto", (p ~= "other") and p or "all")
self.map:set(created, "src_dport", e)
self.map:set(created, "dest_ip", a)
self.map:set(created, "dest_port", i)
self.map:set(created, "name", n)
end
if p ~= "other" then
created = nil
end
end
function s.parse(self, ...)
TypedSection.parse(self, ...)
if created then
m.uci:save("firewall")
luci.http.redirect(ds.build_url(
"admin/network/firewall/redirect", created
))
end
end
function s.filter(self, sid)
return (self.map:get(sid, "target") ~= "SNAT")
end
ft.opt_name(s, DummyValue, translate("Name"))
local function forward_proto_txt(self, s)
return "%s-%s" %{
translate("IPv4"),
ft.fmt_proto(self.map:get(s, "proto"),
self.map:get(s, "icmp_type")) or "TCP+UDP"
}
end
local function forward_src_txt(self, s)
local z = ft.fmt_zone(self.map:get(s, "src"), translate("any zone"))
local a = ft.fmt_ip(self.map:get(s, "src_ip"), translate("any host"))
local p = ft.fmt_port(self.map:get(s, "src_port"))
local m = ft.fmt_mac(self.map:get(s, "src_mac"))
if p and m then
return translatef("From %s in %s with source %s and %s", a, z, p, m)
elseif p or m then
return translatef("From %s in %s with source %s", a, z, p or m)
else
return translatef("From %s in %s", a, z)
end
end
local function forward_via_txt(self, s)
local a = ft.fmt_ip(self.map:get(s, "src_dip"), translate("any router IP"))
local p = ft.fmt_port(self.map:get(s, "src_dport"))
if p then
return translatef("Via %s at %s", a, p)
else
return translatef("Via %s", a)
end
end
match = s:option(DummyValue, "match", translate("Match"))
match.rawhtml = true
match.width = "50%"
function match.cfgvalue(self, s)
return "<small>%s<br />%s<br />%s</small>" % {
forward_proto_txt(self, s),
forward_src_txt(self, s),
forward_via_txt(self, s)
}
end
dest = s:option(DummyValue, "dest", translate("Forward to"))
dest.rawhtml = true
dest.width = "40%"
function dest.cfgvalue(self, s)
local z = ft.fmt_zone(self.map:get(s, "dest"), translate("any zone"))
local a = ft.fmt_ip(self.map:get(s, "dest_ip"), translate("any host"))
local p = ft.fmt_port(self.map:get(s, "dest_port")) or
ft.fmt_port(self.map:get(s, "src_dport"))
if p then
return translatef("%s, %s in %s", a, p, z)
else
return translatef("%s in %s", a, z)
end
end
ft.opt_enabled(s, Flag, translate("Enable")).width = "1%"
return m
| apache-2.0 |
PrimaStudios/ProjectPrima | src/libs/LoveAStar-master/astar.lua | 1 | 5545 |
-- This version has a few LOVE specific calls for getting some benchmarking information
-- Please use astar_good.lua if you plan on using this in your projects
binary_heap = require "binary_heap"
--- Toggle off the pathMap toggles to set up for the next call
-- @param pathMap: the flattened path map
-- @param openSet: the open set
-- @param closedSet: the closed set
local function cleanPathMap(pathMap, openSet, closedSet)
cleanUpStart = love.timer.getTime() -- <== FOR STRESS TEST
for _,v in pairs(openSet) do
if type(v) == "table" then
pathMap[v.value.pathLoc].open = false
end
end
for _,v in pairs(closedSet) do
pathMap[v.pathLoc].closed = false
end
cleanUpEnd = love.timer.getTime() -- <== FOR STRESS TEST
end
--- Constructs the found path. This works in reverse from the
--- pathfinding algorithm, by using parent values and the associated
--- location of that parent on the closed set to jump around until it
--- returns to the start node's position.
-- @param closedSet: the closed set
-- @param startPos: the position of the start node
-- #returns path: the found path
local function buildPath(closedSet, startPos)
buildPathStart = love.timer.getTime() -- <== FOR STRESS TEST
local path = {closedSet[#closedSet]}
while path[#path].pathLoc ~= startPos do
table.insert(path, closedSet[path[#path].pCloseLoc])
end
buildPathEnd = love.timer.getTime() -- <== FOR STRESS TEST
aStarEnd = love.timer.getTime() -- <== FOR STRESS TEST
return path
end
--- The A* search algorithm. Using imported heuristics and distance values
--- between individual nodes, this finds the shortest path from the start
--- node's position to the exit node's position.
-- @param pathMap: the flattened path map
-- @param startPos: the start node's position, relative to the pathMap
-- @param exitPos: the exit node's position, relative to the pathMap
-- #returns path: the found path (or empty if it failed to find a path)
function startPathing(pathMap, startPos, exitPos)
aStarStart = love.timer.getTime() -- <== FOR STRESS TEST
pathMap[startPos].parent = pathMap[startPos]
-- Initialize the gScore and fScore of the start node
pathMap[startPos].gScore = 0
pathMap[startPos].fScore =
pathMap[startPos].gScore + pathMap[startPos].hScore
-- Toggle the open trigger on pathMap for the start node
pathMap[startPos].open = true
-- Initialize the openSet and add the start node to it
local openSet = binary_heap:new()
openSet:insert(pathMap[startPos].fScore, pathMap[startPos])
-- Initialize the closedSet and the testNode
local closedSet = {}
local testNode = {}
mainLoopStart = love.timer.getTime() -- <== FOR STRESS TEST
-- The main loop for the algorithm. Will continue to check as long as
-- there are open nodes that haven't been checked.
while #openSet > 0 do
-- Find the next node with the best fScore
findNextStart = love.timer.getTime() -- <== FOR STRESS TEST
_, testNode = openSet:pop()
findNextEnd = love.timer.getTime() -- <== FOR STRESS TEST
pathMap[testNode.pathLoc].open = false
-- Add that node to the closed set
pathMap[testNode.pathLoc].closed = true
table.insert(closedSet, testNode)
-- Check to see if that is the exit node's position
if closedSet[#closedSet].pathLoc == exitPos then
mainLoopEnd = love.timer.getTime() -- <== FOR STRESS TEST
-- Clean the path map
cleanPathMap(pathMap, openSet, closedSet)
-- Return the build path
return buildPath(closedSet, startPos)
end
neighborStart = love.timer.getTime() -- <== FOR STRESS TEST
-- Check all the (pre-assigned) neighbors. If they are not closed
-- already, then check to see if they are either not on the open
-- or if they are on the open list, but their currently assigned
-- distance score (either given to them when they were first added
-- or reassigned earlier) is greater than the distance score that
-- goes through the current test node. If either is true, then
-- calculate their fScore and assign the current test node as their
-- parent
for k,v in pairs(testNode.neighbors) do
if not pathMap[v].closed then
local tempGScore = testNode.gScore + testNode.distance[k]
if not pathMap[v].open then
pathMap[v].open = true
pathMap[v].parent = testNode
pathMap[v].pCloseLoc = #closedSet
pathMap[v].gScore = tempGScore
pathMap[v].fScore =
pathMap[v].hScore + tempGScore
openSet:insert(pathMap[v].fScore, pathMap[v])
elseif tempGScore < pathMap[v].gScore then
pathMap[v].parent = testNode
pathMap[v].gScore = tempGScore
pathMap[v].fScore =
pathMap[v].hScore + tempGScore
end
end
end
neighborEnd = love.timer.getTime() -- <== For STRESS TEST
end
-- Returns an empty table if it failed to find any path to the exit node
return {}
end
--======================================================================
-- Helper functions for easier plug-in to other games
--======================================================================
function newNode(pathLoc, hScore, neighbors, distance)
assert(type(pathLoc) == "number", "bad arg #1: needs number")
assert(type(hScore) == "number", "bad arg #1: needs number")
assert(type(neighbors) == "table" and
type(next(neighbors)) == "number", "bad arg #1: needs table")
assert(type(distance) == "table" and
type(next(distance)) == "number", "bad arg #1: needs number")
local n = {
pathLoc = pathLoc,
hScore = hScore,
neighbors = neighbors,
distance = distance,
}
return n
end
| apache-2.0 |
lichtl/darkstar | scripts/zones/Bastok_Markets/npcs/Porter_Moogle.lua | 14 | 1535 | -----------------------------------
-- Area: Bastok Markets
-- NPC: Porter Moogle
-- Type: Storage Moogle
-- @zone 235
-- @pos TODO
-----------------------------------
package.loaded["scripts/zones/Bastok_Markets/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Bastok_Markets/TextIDs");
require("scripts/globals/porter_moogle_util");
local e =
{
TALK_EVENT_ID = 545,
STORE_EVENT_ID = 546,
RETRIEVE_EVENT_ID = 547,
ALREADY_STORED_ID = 548,
MAGIAN_TRIAL_ID = 549
};
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
porterMoogleTrade(player, trade, e);
end
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
-- No idea what the params are, other than event ID and gil.
player:startEvent(e.TALK_EVENT_ID, 0x6FFFFF, 0x01, 0x06DD, 0x27, 0x7C7E, 0x15, player:getGil(), 0x03E8);
end
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
porterEventUpdate(player, csid, option, e.RETRIEVE_EVENT_ID, RETRIEVE_DIALOG_ID, ITEM_CANNOT_BE_OBTAINED);
end
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
porterEventFinish(player, csid, option, e.TALK_EVENT_ID, ITEM_CANNOT_BE_OBTAINED, ITEM_OBTAINED, NOT_HAVE_ENOUGH_GIL);
end | gpl-3.0 |
lichtl/darkstar | scripts/zones/Phomiuna_Aqueducts/npcs/_0rq.lua | 14 | 1474 | -----------------------------------
-- Area: Phomiuna_Aqueducts
-- NPC: Oil lamp
-- @pos -60 -23 60 27
-----------------------------------
package.loaded["scripts/zones/Phomiuna_Aqueducts/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/missions");
require("scripts/zones/Phomiuna_Aqueducts/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local DoorOffset = npc:getID();
player:messageSpecial(LAMP_OFFSET+6); -- light lamp
npc:openDoor(7); -- lamp animation
local element = VanadielDayElement();
--printf("element: %u",element);
if (element == 6 or element == 7) then -- lightday or darkday
if (GetNPCByID(DoorOffset+1):getAnimation() == 8) then -- lamp dark open?
GetNPCByID(DoorOffset-5):openDoor(15); -- Open Door _0rk
end
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end; | gpl-3.0 |
cracker1375/mr-Error | libs/serpent.lua | 656 | 7877 | local n, v = "serpent", 0.28 -- (C) 2012-15 Paul Kulchenko; MIT License
local c, d = "Paul Kulchenko", "Lua serializer and pretty printer"
local snum = {[tostring(1/0)]='1/0 --[[math.huge]]',[tostring(-1/0)]='-1/0 --[[-math.huge]]',[tostring(0/0)]='0/0'}
local badtype = {thread = true, userdata = true, cdata = true}
local keyword, globals, G = {}, {}, (_G or _ENV)
for _,k in ipairs({'and', 'break', 'do', 'else', 'elseif', 'end', 'false',
'for', 'function', 'goto', 'if', 'in', 'local', 'nil', 'not', 'or', 'repeat',
'return', 'then', 'true', 'until', 'while'}) do keyword[k] = true end
for k,v in pairs(G) do globals[v] = k end -- build func to name mapping
for _,g in ipairs({'coroutine', 'debug', 'io', 'math', 'string', 'table', 'os'}) do
for k,v in pairs(G[g] or {}) do globals[v] = g..'.'..k end end
local function s(t, opts)
local name, indent, fatal, maxnum = opts.name, opts.indent, opts.fatal, opts.maxnum
local sparse, custom, huge = opts.sparse, opts.custom, not opts.nohuge
local space, maxl = (opts.compact and '' or ' '), (opts.maxlevel or math.huge)
local iname, comm = '_'..(name or ''), opts.comment and (tonumber(opts.comment) or math.huge)
local seen, sref, syms, symn = {}, {'local '..iname..'={}'}, {}, 0
local function gensym(val) return '_'..(tostring(tostring(val)):gsub("[^%w]",""):gsub("(%d%w+)",
-- tostring(val) is needed because __tostring may return a non-string value
function(s) if not syms[s] then symn = symn+1; syms[s] = symn end return tostring(syms[s]) end)) end
local function safestr(s) return type(s) == "number" and tostring(huge and snum[tostring(s)] or s)
or type(s) ~= "string" and tostring(s) -- escape NEWLINE/010 and EOF/026
or ("%q"):format(s):gsub("\010","n"):gsub("\026","\\026") end
local function comment(s,l) return comm and (l or 0) < comm and ' --[['..tostring(s)..']]' or '' end
local function globerr(s,l) return globals[s] and globals[s]..comment(s,l) or not fatal
and safestr(select(2, pcall(tostring, s))) or error("Can't serialize "..tostring(s)) end
local function safename(path, name) -- generates foo.bar, foo[3], or foo['b a r']
local n = name == nil and '' or name
local plain = type(n) == "string" and n:match("^[%l%u_][%w_]*$") and not keyword[n]
local safe = plain and n or '['..safestr(n)..']'
return (path or '')..(plain and path and '.' or '')..safe, safe end
local alphanumsort = type(opts.sortkeys) == 'function' and opts.sortkeys or function(k, o, n) -- k=keys, o=originaltable, n=padding
local maxn, to = tonumber(n) or 12, {number = 'a', string = 'b'}
local function padnum(d) return ("%0"..tostring(maxn).."d"):format(tonumber(d)) end
table.sort(k, function(a,b)
-- sort numeric keys first: k[key] is not nil for numerical keys
return (k[a] ~= nil and 0 or to[type(a)] or 'z')..(tostring(a):gsub("%d+",padnum))
< (k[b] ~= nil and 0 or to[type(b)] or 'z')..(tostring(b):gsub("%d+",padnum)) end) end
local function val2str(t, name, indent, insref, path, plainindex, level)
local ttype, level, mt = type(t), (level or 0), getmetatable(t)
local spath, sname = safename(path, name)
local tag = plainindex and
((type(name) == "number") and '' or name..space..'='..space) or
(name ~= nil and sname..space..'='..space or '')
if seen[t] then -- already seen this element
sref[#sref+1] = spath..space..'='..space..seen[t]
return tag..'nil'..comment('ref', level) end
if type(mt) == 'table' and (mt.__serialize or mt.__tostring) then -- knows how to serialize itself
seen[t] = insref or spath
if mt.__serialize then t = mt.__serialize(t) else t = tostring(t) end
ttype = type(t) end -- new value falls through to be serialized
if ttype == "table" then
if level >= maxl then return tag..'{}'..comment('max', level) end
seen[t] = insref or spath
if next(t) == nil then return tag..'{}'..comment(t, level) end -- table empty
local maxn, o, out = math.min(#t, maxnum or #t), {}, {}
for key = 1, maxn do o[key] = key end
if not maxnum or #o < maxnum then
local n = #o -- n = n + 1; o[n] is much faster than o[#o+1] on large tables
for key in pairs(t) do if o[key] ~= key then n = n + 1; o[n] = key end end end
if maxnum and #o > maxnum then o[maxnum+1] = nil end
if opts.sortkeys and #o > maxn then alphanumsort(o, t, opts.sortkeys) end
local sparse = sparse and #o > maxn -- disable sparsness if only numeric keys (shorter output)
for n, key in ipairs(o) do
local value, ktype, plainindex = t[key], type(key), n <= maxn and not sparse
if opts.valignore and opts.valignore[value] -- skip ignored values; do nothing
or opts.keyallow and not opts.keyallow[key]
or opts.valtypeignore and opts.valtypeignore[type(value)] -- skipping ignored value types
or sparse and value == nil then -- skipping nils; do nothing
elseif ktype == 'table' or ktype == 'function' or badtype[ktype] then
if not seen[key] and not globals[key] then
sref[#sref+1] = 'placeholder'
local sname = safename(iname, gensym(key)) -- iname is table for local variables
sref[#sref] = val2str(key,sname,indent,sname,iname,true) end
sref[#sref+1] = 'placeholder'
local path = seen[t]..'['..tostring(seen[key] or globals[key] or gensym(key))..']'
sref[#sref] = path..space..'='..space..tostring(seen[value] or val2str(value,nil,indent,path))
else
out[#out+1] = val2str(value,key,indent,insref,seen[t],plainindex,level+1)
end
end
local prefix = string.rep(indent or '', level)
local head = indent and '{\n'..prefix..indent or '{'
local body = table.concat(out, ','..(indent and '\n'..prefix..indent or space))
local tail = indent and "\n"..prefix..'}' or '}'
return (custom and custom(tag,head,body,tail) or tag..head..body..tail)..comment(t, level)
elseif badtype[ttype] then
seen[t] = insref or spath
return tag..globerr(t, level)
elseif ttype == 'function' then
seen[t] = insref or spath
local ok, res = pcall(string.dump, t)
local func = ok and ((opts.nocode and "function() --[[..skipped..]] end" or
"((loadstring or load)("..safestr(res)..",'@serialized'))")..comment(t, level))
return tag..(func or globerr(t, level))
else return tag..safestr(t) end -- handle all other types
end
local sepr = indent and "\n" or ";"..space
local body = val2str(t, name, indent) -- this call also populates sref
local tail = #sref>1 and table.concat(sref, sepr)..sepr or ''
local warn = opts.comment and #sref>1 and space.."--[[incomplete output with shared/self-references skipped]]" or ''
return not name and body..warn or "do local "..body..sepr..tail.."return "..name..sepr.."end"
end
local function deserialize(data, opts)
local env = (opts and opts.safe == false) and G
or setmetatable({}, {
__index = function(t,k) return t end,
__call = function(t,...) error("cannot call functions") end
})
local f, res = (loadstring or load)('return '..data, nil, nil, env)
if not f then f, res = (loadstring or load)(data, nil, nil, env) end
if not f then return f, res end
if setfenv then setfenv(f, env) end
return pcall(f)
end
local function merge(a, b) if b then for k,v in pairs(b) do a[k] = v end end; return a; end
return { _NAME = n, _COPYRIGHT = c, _DESCRIPTION = d, _VERSION = v, serialize = s,
load = deserialize,
dump = function(a, opts) return s(a, merge({name = '_', compact = true, sparse = true}, opts)) end,
line = function(a, opts) return s(a, merge({sortkeys = true, comment = true}, opts)) end,
block = function(a, opts) return s(a, merge({indent = ' ', sortkeys = true, comment = true}, opts)) end }
| gpl-2.0 |
RunAwayDSP/darkstar | scripts/zones/Metalworks/npcs/Karst.lua | 9 | 1444 | -----------------------------------
-- Area: Metalworks
-- NPC: Karst
-- Type: President
-- Involved in Bastok Missions 5-2
-- !pos 106 -21 0 237
-----------------------------------
require("scripts/globals/keyitems");
require("scripts/globals/missions");
-----------------------------------
function onTrade(player,npc,trade)
end;
function onTrigger(player,npc)
local currentMission = player:getCurrentMission(BASTOK);
if (currentMission == dsp.mission.id.bastok.XARCABARD_LAND_OF_TRUTHS and player:getCharVar("MissionStatus") == 0) then
player:startEvent(602);
elseif (currentMission == dsp.mission.id.bastok.XARCABARD_LAND_OF_TRUTHS and player:hasKeyItem(dsp.ki.SHADOW_FRAGMENT)) then
player:startEvent(603);
elseif (currentMission == dsp.mission.id.bastok.ON_MY_WAY) and (player:getCharVar("MissionStatus") == 0) then
player:startEvent(765);
elseif (currentMission == dsp.mission.id.bastok.ON_MY_WAY) and (player:getCharVar("MissionStatus") == 3) then
player:startEvent(766);
else
player:startEvent(601);
end
end;
function onEventUpdate(player,csid,option)
end;
function onEventFinish(player,csid,option)
if (csid == 602) then
player:setCharVar("MissionStatus",2);
elseif (csid == 765) then
player:setCharVar("MissionStatus",1);
elseif (csid == 766 or csid == 603) then
finishMissionTimeline(player, 1, csid, option);
end
end; | gpl-3.0 |
RunAwayDSP/darkstar | scripts/zones/Bostaunieux_Oubliette/npcs/Novalmauge.lua | 9 | 3889 | -----------------------------------
-- Area: Bostaunieux Obliette
-- NPC: Novalmauge
-- Starts and Finishes Quest: The Rumor, Souls in Shadow
-- Involved in Quest: The Holy Crest, Trouble at the Sluice
-- !pos 70 -24 21 167
-----------------------------------
local ID = require("scripts/zones/Bostaunieux_Oubliette/IDs")
require("scripts/globals/keyitems")
require("scripts/globals/npc_util")
require("scripts/globals/pathfind")
require("scripts/globals/wsquest")
require("scripts/globals/quests")
-----------------------------------
local path =
{
41.169430, -24.000000, 19.860674,
42.256676, -24.000000, 19.885197,
41.168694, -24.000000, 19.904638,
21.859211, -24.010996, 19.792259,
51.917370, -23.924366, 19.970068,
74.570229, -24.024828, 20.103880,
44.533886, -23.947662, 19.926519
}
local wsQuest = dsp.wsquest.spiral_hell
function onSpawn(npc)
npc:initNpcAi()
npc:setPos(dsp.path.first(path))
onPath(npc)
end
function onPath(npc)
dsp.path.patrol(npc, path)
end
function onTrade(player, npc, trade)
local wsQuestEvent = dsp.wsquest.getTradeEvent(wsQuest, player, trade)
if player:getCharVar("troubleAtTheSluiceVar") == 2 and npcUtil.tradeHas(trade, 959) then -- Dahlia
player:startEvent(17)
npc:wait()
elseif player:getQuestStatus(SANDORIA, dsp.quest.id.sandoria.THE_RUMOR) == QUEST_ACCEPTED and npcUtil.tradeHas(trade, 930) then -- Beastman Blood
player:startEvent(12)
npc:wait()
elseif wsQuestEvent ~= nil then
player:startEvent(wsQuestEvent)
npc:wait()
end
end
function onTrigger(player, npc)
local wsQuestEvent = dsp.wsquest.getTriggerEvent(wsQuest, player)
local troubleAtTheSluice = player:getQuestStatus(SANDORIA, dsp.quest.id.sandoria.TROUBLE_AT_THE_SLUICE)
local troubleAtTheSluiceStat = player:getCharVar("troubleAtTheSluiceVar")
local theHolyCrestStat = player:getCharVar("TheHolyCrest_Event")
local theRumor = player:getQuestStatus(SANDORIA, dsp.quest.id.sandoria.THE_RUMOR)
npc:wait()
if wsQuestEvent ~= nil then
player:startEvent(wsQuestEvent)
-- THE HOLY CREST
elseif theHolyCrestStat == 1 then
player:startEvent(6)
elseif theHolyCrestStat == 2 and player:getCharVar("theHolyCrestCheck") == 0 then
player:startEvent(7)
-- TROUBLE AT THE SLUICE
elseif troubleAtTheSluiceStat == 1 then
player:startEvent(15)
elseif troubleAtTheSluiceStat == 2 then
player:startEvent(16)
-- THE RUMOR
elseif theRumor == QUEST_AVAILABLE and player:getFameLevel(SANDORIA) >= 3 and player:getMainLvl() >= 10 then
player:startEvent(13)
elseif theRumor == QUEST_ACCEPTED then
player:startEvent(11)
elseif theRumor == QUEST_COMPLETED then
player:startEvent(14) -- Standard dialog after "The Rumor"
else
player:startEvent(10) -- Standard dialog
end
end
function onEventFinish(player, csid, option, npc)
if csid == 6 then
player:setCharVar("TheHolyCrest_Event", 2)
elseif csid == 7 then
player:setCharVar("theHolyCrestCheck", 1)
elseif csid == 12 and npcUtil.completeQuest(player, SANDORIA, dsp.quest.id.sandoria.THE_RUMOR, {item = 4853}) then
player:confirmTrade()
elseif csid == 13 and option == 1 then
player:addQuest(SANDORIA, dsp.quest.id.sandoria.THE_RUMOR)
elseif csid == 14 then
player:setCharVar("theHolyCrestCheck", 0)
elseif csid == 15 then
player:setCharVar("troubleAtTheSluiceVar", 2)
elseif csid == 17 then
npcUtil.giveKeyItem(player, dsp.ki.NEUTRALIZER)
player:setCharVar("troubleAtTheSluiceVar", 0)
player:setCharVar("theHolyCrestCheck", 0)
player:confirmTrade()
else
dsp.wsquest.handleEventFinish(wsQuest, player, csid, option, ID.text.SPIRAL_HELL_LEARNED)
end
npc:wait(0)
end | gpl-3.0 |
RunAwayDSP/darkstar | scripts/zones/Bastok_Markets_[S]/npcs/GentleTiger.lua | 9 | 1233 | ----------------------------------
-- Area: Bastok Markets [S]
-- NPC: GentleTiger
-- Type: Quest
-- !pos -203 -10 1
-----------------------------------
require("scripts/globals/quests");
-----------------------------------
function onTrade(player,npc,trade)
end;
function onTrigger(player,npc)
local onSabbatical = player:getQuestStatus(CRYSTAL_WAR,dsp.quest.id.crystalWar.ON_SABBATICAL);
local onSabbaticalProgress = player:getCharVar("OnSabbatical");
if (onSabbatical == QUEST_ACCEPTED) then
if (onSabbaticalProgress == 1) then
player:startEvent(46);
else
player:startEvent(47);
end
elseif (player:getQuestStatus(CRYSTAL_WAR,dsp.quest.id.crystalWar.FIRES_OF_DISCONTENT) == QUEST_ACCEPTED) then
if (player:getCharVar("FiresOfDiscProg") == 5) then
player:startEvent(160);
else
player:startEvent(161);
end
else
player:startEvent(109);
end
end;
function onEventUpdate(player,csid,option)
end;
function onEventFinish(player,csid,option)
if (csid == 46) then
player:setCharVar("OnSabbatical", 2);
elseif (csid == 160) then
player:setCharVar("FiresOfDiscProg",6);
end
end;
| gpl-3.0 |
lichtl/darkstar | scripts/zones/The_Garden_of_RuHmet/npcs/_iz2.lua | 14 | 2003 | -----------------------------------
-- Area: The Garden of RuHmet
-- NPC: _iz2 (Ebon_Panel)
-- @pos 422.351 -5.180 -100.000 35 | Hume Tower
-----------------------------------
package.loaded["scripts/zones/The_Garden_of_RuHmet/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/The_Garden_of_RuHmet/TextIDs");
require("scripts/globals/missions");
require("scripts/globals/titles");
require("scripts/globals/keyitems");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local Race = player:getRace();
if (player:getCurrentMission(COP) == WHEN_ANGELS_FALL and player:getVar("PromathiaStatus") == 1) then
player:startEvent(0x00CA);
elseif (player:getCurrentMission(COP) == WHEN_ANGELS_FALL and player:getVar("PromathiaStatus") == 2) then
if ( Race==2 or Race==1) then
player:startEvent(0x0078);
else
player:messageSpecial(NO_NEED_INVESTIGATE);
end
else
player:messageSpecial(NO_NEED_INVESTIGATE);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x00CA) then
player:setVar("PromathiaStatus",2);
elseif (0x0078 and option ~=0) then -- Hume
player:addTitle(WARRIOR_OF_THE_CRYSTAL);
player:setVar("PromathiaStatus",3);
player:addKeyItem(LIGHT_OF_VAHZL);
player:messageSpecial(KEYITEM_OBTAINED,LIGHT_OF_VAHZL);
end
end; | gpl-3.0 |
lichtl/darkstar | scripts/zones/Outer_Horutoto_Ruins/npcs/_5ej.lua | 17 | 3739 | -----------------------------------
-- Area: Inner Horutoto Ruins
-- NPC: Ancient Magical Gizmo #6 (J out of E, F, G, H, I, J)
-- Involved In Mission: The Heart of the Matter
-----------------------------------
package.loaded["scripts/zones/Outer_Horutoto_Ruins/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/keyitems");
require("scripts/globals/missions");
require("scripts/zones/Outer_Horutoto_Ruins/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
-- Check if we are on Windurst Mission 1-2
if (player:getCurrentMission(WINDURST) == THE_HEART_OF_THE_MATTER) then
MissionStatus = player:getVar("MissionStatus");
if (MissionStatus == 2) then
-- Entered a Dark Orb
if (player:getVar("MissionStatus_orb6") == 1) then
player:startEvent(0x0033);
else
player:messageSpecial(ORB_ALREADY_PLACED);
end
elseif (MissionStatus == 4) then
-- Took out a Glowing Orb
if (player:getVar("MissionStatus_orb6") == 2) then
player:startEvent(0x0033);
else
player:messageSpecial(G_ORB_ALREADY_GOTTEN);
end
else
player:messageSpecial(DARK_MANA_ORB_RECHARGER);
end
else
player:messageSpecial(DARK_MANA_ORB_RECHARGER);
end
return 1;
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x0033) then
orb_value = player:getVar("MissionStatus_orb6");
if (orb_value == 1) then
player:setVar("MissionStatus_orb6",2);
-- Push the text that the player has placed the orb
player:messageSpecial(SIXTH_DARK_ORB_IN_PLACE);
--Delete the key item
player:delKeyItem(SIXTH_DARK_MANA_ORB);
-- Check if all orbs have been placed or not
if (player:getVar("MissionStatus_orb1") == 2 and
player:getVar("MissionStatus_orb2") == 2 and
player:getVar("MissionStatus_orb3") == 2 and
player:getVar("MissionStatus_orb4") == 2 and
player:getVar("MissionStatus_orb5") == 2) then
player:messageSpecial(ALL_DARK_MANA_ORBS_SET);
player:setVar("MissionStatus",3);
end
elseif (orb_value == 2) then
player:setVar("MissionStatus_orb6",3);
-- Time to get the glowing orb out
player:addKeyItem(SIXTH_GLOWING_MANA_ORB);
player:messageSpecial(KEYITEM_OBTAINED,SIXTH_GLOWING_MANA_ORB);
-- Check if all orbs have been placed or not
if (player:getVar("MissionStatus_orb1") == 3 and
player:getVar("MissionStatus_orb2") == 3 and
player:getVar("MissionStatus_orb3") == 3 and
player:getVar("MissionStatus_orb4") == 3 and
player:getVar("MissionStatus_orb5") == 3) then
player:messageSpecial(RETRIEVED_ALL_G_ORBS);
player:setVar("MissionStatus",5);
end
end
end
end; | gpl-3.0 |
lichtl/darkstar | scripts/zones/Windurst_Woods/npcs/Tesch_Garanjy.lua | 16 | 4318 | -----------------------------------
-- Area: Windurst Woods
-- NPC: Tesch_Garanjy
-- Armor Storage NPC
-----------------------------------
package.loaded["scripts/zones/Windurst_Woods/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/globals/armorstorage");
require("scripts/zones/Windurst_Woods/TextIDs");
Deposit = 0x272b;
Withdrawl = 0x272c;
ArraySize = #StorageArray;
G1 = 0;
G2 = 0;
G3 = 0;
G4 = 0;
G5 = 0;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
for SetId = 1,ArraySize,11 do
TradeCount = trade:getItemCount();
T1 = trade:hasItemQty(StorageArray[SetId + 5],1);
if (T1 == true) then
if (player:hasKeyItem(StorageArray[SetId + 10]) == false) then
if (TradeCount == StorageArray[SetId + 3]) then
T2 = trade:hasItemQty(StorageArray[SetId + 4],1);
T3 = trade:hasItemQty(StorageArray[SetId + 6],1);
T4 = trade:hasItemQty(StorageArray[SetId + 7],1);
T5 = trade:hasItemQty(StorageArray[SetId + 8],1);
if (StorageArray[SetId + 4] == 0) then
T2 = true;
end;
if (StorageArray[SetId + 6] == 0) then
T3 = true;
end;
if (StorageArray[SetId + 7] == 0) then
T4 = true;
end;
if (StorageArray[SetId + 8] == 0) then
T5 = true;
end;
if (T2 == true and T3 == true and T4 == true and T5 == true) then
player:startEvent(Deposit,0,0,0,0,0,StorageArray[SetId + 9]);
player:addKeyItem(StorageArray[SetId + 10]);
player:messageSpecial(KEYITEM_OBTAINED,StorageArray[SetId + 10]);
break;
end;
end;
end;
end;
end;
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
CurrGil = player:getGil();
for KeyItem = 11,ArraySize,11 do
if player:hasKeyItem(StorageArray[KeyItem]) then
if StorageArray[KeyItem - 9] == 1 then
G1 = G1 + StorageArray[KeyItem - 8];
elseif StorageArray[KeyItem - 9] == 2 then
G2 = G2 + StorageArray[KeyItem - 8];
elseif StorageArray[KeyItem - 9] == 3 then
G3 = G3 + StorageArray[KeyItem - 8];
elseif StorageArray[KeyItem - 9] == 4 then
G4 = G4 + StorageArray[KeyItem - 8];
elseif StorageArray[KeyItem - 9] == 6 then
G5 = G5 + StorageArray[KeyItem - 8];
end;
end;
end;
player:startEvent(Withdrawl,G1,G2,G3,G4,CurrGil,G5);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
if (csid == Withdrawl) then
player:updateEvent(StorageArray[option * 11 - 6],
StorageArray[option * 11 - 5],
StorageArray[option * 11 - 4],
StorageArray[option * 11 - 3],
StorageArray[option * 11 - 2],
StorageArray[option * 11 - 1]);
end;
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
if (csid == Withdrawl) then
if (option > 0 and option <= StorageArray[ArraySize] - 10) then
if (player:getFreeSlotsCount() >= StorageArray[option * 11 - 7]) then
for Item = 2,6,1 do
if (StorageArray[option * 11 - Item] > 0) then
player:addItem(StorageArray[option * 11 - Item],1);
player:messageSpecial(ITEM_OBTAINED,StorageArray[option * 11 - Item]);
end;
end;
player:delKeyItem(StorageArray[option * 11]);
player:setGil(player:getGil() - StorageArray[option * 11 - 1]);
else
for Item = 2,6,1 do
if (StorageArray[option * 11 - Item] > 0) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,StorageArray[option * 11 - Item]);
end;
end;
end;
end;
end;
if (csid == Deposit) then
player:tradeComplete();
end;
end; | gpl-3.0 |
lichtl/darkstar | scripts/zones/Northern_San_dOria/npcs/Abeaule.lua | 25 | 4316 | -----------------------------------
-- Area: Northern San d'Oria
-- NPC: Abeaule
-- Starts and Finishes Quest: The Trader in the Forest, The Medicine Woman
-- @pos -136 -2 56 231
-----------------------------------
package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/titles");
require("scripts/globals/keyitems");
require("scripts/globals/quests");
require("scripts/zones/Northern_San_dOria/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
theTraderInTheForest = player:getQuestStatus(SANDORIA,THE_TRADER_IN_THE_FOREST);
if (theTraderInTheForest == QUEST_ACCEPTED) then
if (trade:hasItemQty(4367,1) and trade:getItemCount() == 1) then -- Trade Batagreens
player:startEvent(0x020d);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
theTraderInTheForest = player:getQuestStatus(SANDORIA,THE_TRADER_IN_THE_FOREST);
medicineWoman = player:getQuestStatus(SANDORIA,THE_MEDICINE_WOMAN);
if (theTraderInTheForest == QUEST_AVAILABLE) then
if (player:getVar("theTraderInTheForestCS") == 1) then
player:startEvent(0x0250);
else
player:startEvent(0x020c);
player:setVar("theTraderInTheForestCS",1);
end
elseif (theTraderInTheForest == QUEST_ACCEPTED) then
player:startEvent(0x0251);
elseif (theTraderInTheForest == QUEST_COMPLETED and medicineWoman == QUEST_AVAILABLE and player:getFameLevel(SANDORIA) >= 3) then
if (player:getVar("medicineWomanCS") == 1) then
player:startEvent(0x0267);
else
player:startEvent(0x0265);
player:setVar("medicineWomanCS",1);
end
elseif (player:hasKeyItem(COLD_MEDICINE)) then
player:startEvent(0x0266);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
-- "The Trader in the Forest" Quest
if (csid == 0x020c and option == 0 or csid == 0x0250 and option == 0) then
if (player:getFreeSlotsCount() == 0) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,592);
else
player:addQuest(SANDORIA,THE_TRADER_IN_THE_FOREST);
player:setVar("theTraderInTheForestCS",0);
player:addItem(592);
player:messageSpecial(ITEM_OBTAINED,592); -- Supplies Order
end
elseif (csid == 0x0251 and option == 1) then
local SUPPLIES_ORDER = 592;
if (player:getFreeSlotsCount() > 0 and player:hasItem(592) == false) then -- Supplies Order
player:addItem(SUPPLIES_ORDER);
player:messageSpecial(ITEM_OBTAINED, SUPPLIES_ORDER);
else
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED, SUPPLIES_ORDER);
end
elseif (csid == 0x020d) then
if (player:getFreeSlotsCount() == 0) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,12600); -- Robe
else
player:tradeComplete();
player:addTitle(GREEN_GROCER);
player:addItem(12600);
player:messageSpecial(ITEM_OBTAINED,12600); -- Robe
player:addFame(SANDORIA,30);
player:completeQuest(SANDORIA,THE_TRADER_IN_THE_FOREST);
end
-- "The Medicine Woman" Quest
elseif (csid == 0x0265 and option == 0 or csid == 0x0267 and option == 0) then
player:addQuest(SANDORIA,THE_MEDICINE_WOMAN);
elseif (csid == 0x0266) then
player:addTitle(TRAVELING_MEDICINE_MAN);
player:delKeyItem(COLD_MEDICINE);
player:addGil(GIL_RATE*2100);
player:messageSpecial(GIL_OBTAINED,GIL_RATE*2100);
player:addFame(SANDORIA,30);
player:completeQuest(SANDORIA,THE_MEDICINE_WOMAN);
end
end; | gpl-3.0 |
NiLuJe/koreader | frontend/ui/data/keyboardlayouts/fa_keyboard.lua | 6 | 4330 | local en_popup = require("ui/data/keyboardlayouts/keypopup/en_popup")
local fa_popup = require("ui/data/keyboardlayouts/keypopup/fa_popup")
local prd = en_popup.prd -- period (.)
local _at = en_popup._at
local alef = fa_popup.alef
local h_aa = fa_popup.h_aa -- This is Persian letter هـ / as in English "hello".
local waw = fa_popup.waw
local yaa = fa_popup.yaa
local kaf = fa_popup.kaf
local diacritics = fa_popup.diacritics
local arabic_comma = fa_popup.arabic_comma
return {
min_layer = 1,
max_layer = 4,
shiftmode_keys = {["1/2"] = true, ["2/2"] = true},
symbolmode_keys = {["نشانهها"] = true,["الفبا"]=true}, -- نشانهها means "Symbol", الفبا means "letter" (traditionally "ABC" on QWERTY layouts)
utf8mode_keys = {["🌐"] = true}, -- The famous globe key for layout switching
umlautmode_keys = {["Äéß"] = false}, -- No need for this keyboard panel
keys = {
-- first row
{ -- 1 2 3 4
{ "ض", "ض", "~", "1", },
{ "ص", "ص", "`", "2", },
{ "ث", "ث", "|", "3", },
{ "ق", "ق", "•", "4", },
{ "ف", "ف", "√", "5", },
{ "غ", "غ", "π", "6", },
{ "ع", "ع", "÷", "7", },
{ h_aa, h_aa, "×", "8", },
{ "خ", "خ", "¶", "9", },
{ "ح", "ح", "Δ", "0", },
{ "ج", "ج", "‘", ">" },
},
-- second row
{ -- 1 2 3 4
{ "ش", "ش", "£", _at, },
{ "س", "س", "¥", "#", },
{ yaa, yaa, "$", "﷼", },
{ "ب", "ب", "¢", "ـ", },
{ "ل", "ل", "^", "&", },
{ alef, alef, "°", "-", },
{ "ت", "ت", "=", "+", },
{ "ن", "ن", "{", "(", },
{ "م", "م", "}", ")" },
{ kaf, kaf, "\\", "٫", },
{ "گ", "گ", "/", "<", },
},
-- third row
{ -- 1 2 3 4
{ "ظ", "ظ", "٪", "/", },
{ "ط", "ط", "©", "«", },
{ "ژ", "ژ", "®", "»", },
{ "ز", "ز", "™", ":", },
{ "ر", "ر", "✓", "؛", },
{ "ذ", "ذ", "[", "!", },
{ "د", "د", "]", "؟", },
{ "پ", "پ", "↑", "↑", },
{ waw, waw, "←", "←", },
{ "چ", "چ", "→", "→", },
{ label = "",
width = 1,
bold = false
},
},
-- fourth row
{
{"نشانهها","نشانهها","الفبا","الفبا",
width = 1.75},
{ arabic_comma, arabic_comma, "2/2", "1/2",
width = 1},
{ label = "🌐", },
{ label = "فاصله",
" ", " ", " ", " ",
width = 3.6},
{ label = ".|.",
diacritics, diacritics, diacritics, diacritics,
width = 1},
{ prd, prd, "↓", "↓", },
{ label = "⮠",
"\n", "\n", "\n", "\n",
width = 1.7,
},
},
},
}
| agpl-3.0 |
yariplus/love-demos | love-slider/entities/SliderTile.lua | 1 | 2602 | local Entity = require "entities/Entity"
local SliderTile = {}
setmetatable(SliderTile, {__index = Entity})
SliderTile.blankQuad = love.graphics.newQuad(0, 0, 64, 64, 640, 640)
function SliderTile:update(dt)
end
function SliderTile:draw(dt)
love.graphics.setColor(50, 0, 0)
love.graphics.print(self.number, self.sprite.x + 30, self.sprite.y + 30)
end
function SliderTile:flip()
end
function SliderTile:click(x, y, button)
if button == "l" then
self.clickables:click(x, y, button)
end
end
function SliderTile:new(sprite, x, y, number)
local o = {
position = {
x = x,
y = y
}
}
o.sprite = sprite
setmetatable(o, {__index = self})
o.sprite:setPos(x * 96 - 24, y * 96 - 24)
o.side = "back"
o.sprite.batch:set( o.sprite.id, SliderTile.blankQuad, o.sprite.x, o.sprite.y )
o.number = number
o.clickables = Clickables:new(o)
o.clickables:addClickableArea(0, 0, 64, 64, function ()
local bx = game.blank.x
local by = game.blank.y
if bx == o.position.x then
if by > o.position.y then
local _by = by
local _oy = o.position.y
while _by > _oy do
game.positions[bx][_by] = game.positions[bx][_by - 1]
game.positions[bx][_by].sprite:setPos(bx * 96 - 24, _by * 96 - 24)
game.positions[bx][_by].position.y = _by
game.positions[bx][_by - 1] = {number=0}
game.blank.x = bx
game.blank.y = _by - 1
_by = _by - 1
end
else
local _by = by
local _oy = o.position.y
while _by < _oy do
game.positions[bx][_by] = game.positions[bx][_by + 1]
game.positions[bx][_by].sprite:setPos(bx * 96 - 24, _by * 96 - 24)
game.positions[bx][_by].position.y = _by
game.positions[bx][_by + 1] = {number=0}
game.blank.x = bx
game.blank.y = _by + 1
_by = _by + 1
end
end
end
if by == o.position.y then
if bx > o.position.x then
local _bx = bx
local _ox = o.position.x
while _bx > _ox do
game.positions[_bx][by] = game.positions[_bx - 1][by]
game.positions[_bx][by].sprite:setPos(_bx * 96 - 24, by * 96 - 24)
game.positions[_bx][by].position.x = _bx
game.positions[_bx - 1][by] = {number=0}
game.blank.x = _bx - 1
_bx = _bx - 1
end
else
local _bx = bx
local _ox = o.position.x
while _bx < _ox do
game.positions[_bx][by] = game.positions[_bx + 1][by]
game.positions[_bx][by].sprite:setPos(_bx * 96 - 24, by * 96 - 24)
game.positions[_bx][by].position.x = _bx
game.positions[_bx + 1][by] = {number=0}
game.blank.x = _bx + 1
_bx = _bx + 1
end
end
end
end)
return o
end
return SliderTile
| cc0-1.0 |
lichtl/darkstar | scripts/zones/Southern_San_dOria/npcs/Foletta.lua | 17 | 1458 | -----------------------------------
-- Area: Southern San d'Oria
-- NPC: Foletta
-- General Info NPC
-------------------------------------
package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Southern_San_dOria/TextIDs");
require("scripts/globals/settings");
require("scripts/globals/quests");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
-- "Flyers for Regine" conditional script
local FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE);
if (FlyerForRegine == 1) then
local count = trade:getItemCount();
local MagicFlyer = trade:hasItemQty(532,1);
if (MagicFlyer == true and count == 1) then
player:messageSpecial(FLYER_REFUSED);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x29a);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
lichtl/darkstar | scripts/zones/Windurst_Woods/npcs/Boizo-Naizo.lua | 14 | 1621 | -----------------------------------
-- Area: Windurst Woods
-- NPC: Boizo-Naizo
-- Involved in Quest: Riding on the Clouds
-- @zone 241
-- @pos -9.581 -3.75 -26.062
-----------------------------------
package.loaded["scripts/zones/Windurst_Woods/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/quests");
require("scripts/zones/Windurst_Woods/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (player:getQuestStatus(JEUNO,RIDING_ON_THE_CLOUDS) == QUEST_ACCEPTED and player:getVar("ridingOnTheClouds_4") == 6) then
if (trade:hasItemQty(1127,1) and trade:getItemCount() == 1) then -- Trade Kindred seal
player:setVar("ridingOnTheClouds_4",0);
player:tradeComplete();
player:addKeyItem(SPIRITED_STONE);
player:messageSpecial(KEYITEM_OBTAINED,SPIRITED_STONE);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x0113);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end; | gpl-3.0 |
OctoEnigma/shiny-octo-system | gamemodes/terrortown/entities/entities/ttt_cse_proj.lua | 3 | 4910 |
AddCSLuaFile()
if CLIENT then
local GetPTranslation = LANG.GetParamTranslation
local hint_params = {usekey = Key("+use", "USE")}
ENT.TargetIDHint = {
name = "vis_name",
hint = "vis_hint",
fmt = function(ent, txt) return GetPTranslation(txt, hint_params) end
};
end
ENT.Type = "anim"
ENT.Base = "ttt_basegrenade_proj"
ENT.Model = Model("models/Items/battery.mdl")
ENT.RenderGroup = RENDERGROUP_BOTH
ENT.Range = 128
ENT.MaxScenesPerPulse = 3
ENT.SceneDuration = 10
ENT.PulseDelay = 10
ENT.CanUseKey = true
function ENT:Initialize()
self.BaseClass.Initialize(self)
self:SetSolid(SOLID_VPHYSICS)
if SERVER then
self:SetMaxHealth(50)
self:SetExplodeTime(CurTime() + 1)
end
self:SetHealth(50)
end
function ENT:GetNearbyCorpses()
local pos = self:GetPos()
local near = ents.FindInSphere(pos, self.Range)
if not near then return end
local near_corpses = {}
local n = #near
local ent = nil
for i=1, n do
ent = near[i]
if IsValid(ent) and ent.player_ragdoll and ent.scene then
table.insert(near_corpses, {ent=ent, dist=pos:LengthSqr()})
end
end
return near_corpses
end
local zapsound = Sound("npc/assassin/ball_zap1.wav")
function ENT:OnTakeDamage(dmginfo)
self:TakePhysicsDamage(dmginfo)
self:SetHealth(self:Health() - dmginfo:GetDamage())
if self:Health() < 0 then
self:Remove()
local effect = EffectData()
effect:SetOrigin(self:GetPos())
util.Effect("cball_explode", effect)
sound.Play(zapsound, self:GetPos())
end
end
function ENT:ShowSceneForCorpse(corpse)
local scene = corpse.scene
local hit = scene.hit_trace
local dur = self.SceneDuration
if hit then
-- line showing bullet trajectory
local e = EffectData()
e:SetEntity(corpse)
e:SetStart(hit.StartPos)
e:SetOrigin(hit.HitPos)
e:SetMagnitude(hit.HitBox)
e:SetScale(dur)
util.Effect("crimescene_shot", e)
end
if not scene then return end
for _, dummy_key in pairs({"victim", "killer"}) do
local dummy = scene[dummy_key]
if dummy then
-- Horrible sins committed here to get all the data we need over the
-- wire, the pose parameters are going to be truncated etc. but
-- everything sort of works out. If you know a better way to get this
-- much data to an effect, let me know.
local e = EffectData()
e:SetEntity(corpse)
e:SetOrigin(dummy.pos)
e:SetAngles(dummy.ang)
e:SetColor(dummy.sequence)
e:SetScale(dummy.cycle)
e:SetStart(Vector(dummy.aim_yaw, dummy.aim_pitch, dummy.move_yaw))
e:SetRadius(dur)
util.Effect("crimescene_dummy", e)
end
end
end
local scanloop = Sound("weapons/gauss/chargeloop.wav")
function ENT:StartScanSound()
if not self.ScanSound then
self.ScanSound = CreateSound(self, scanloop)
end
if not self.ScanSound:IsPlaying() then
self.ScanSound:PlayEx(0.5, 100)
end
end
function ENT:StopScanSound(force)
if self.ScanSound and self.ScanSound:IsPlaying() then
self.ScanSound:FadeOut(0.5)
end
if self.ScanSound and force then
self.ScanSound:Stop()
end
end
if CLIENT then
local glow = Material("sprites/blueglow2")
function ENT:DrawTranslucent()
render.SetMaterial(glow)
render.DrawSprite(self:LocalToWorld(self:OBBCenter()), 32, 32, COLOR_WHITE)
end
end
function ENT:UseOverride(activator)
if IsValid(activator) and activator:IsPlayer() then
if activator:IsActiveDetective() and activator:CanCarryType(WEAPON_EQUIP) then
self:StopScanSound(true)
self:Remove()
activator:Give("weapon_ttt_cse")
else
self:EmitSound("HL2Player.UseDeny")
end
end
end
function ENT:OnRemove()
self:StopScanSound(true)
end
function ENT:Explode(tr)
if SERVER then
-- prevent starting effects when round is about to restart
if GetRoundState() == ROUND_POST then return end
self:SetCollisionGroup(COLLISION_GROUP_WEAPON)
local corpses = self:GetNearbyCorpses()
if #corpses > self.MaxScenesPerPulse then
table.SortByMember(corpses, "dist", function(a, b) return a > b end)
end
local e = EffectData()
e:SetOrigin(self:GetPos())
e:SetRadius(128)
e:SetMagnitude(0.5)
e:SetScale(4)
util.Effect("pulse_sphere", e)
-- show scenes for nearest corpses
for i=1, self.MaxScenesPerPulse do
local corpse = corpses[i]
if corpse and IsValid(corpse.ent) then
self:ShowSceneForCorpse(corpse.ent)
end
end
if #corpses > 0 then
self:StartScanSound()
else
self:StopScanSound()
end
-- "schedule" next show pulse
self:SetDetonateTimer(self.PulseDelay)
end
end
| mit |
lichtl/darkstar | scripts/globals/items/slice_of_dragon_meat.lua | 18 | 1345 | -----------------------------------------
-- ID: 4272
-- Item: slice_of_dragon_meat
-- Food Effect: 5Min, Galka only
-----------------------------------------
-- Strength 6
-- Intelligence -8
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:getRace() ~= 8) then
result = 247;
end
if (target:getMod(MOD_EAT_RAW_MEAT) == 1) then
result = 0;
end
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,300,4272);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_STR, 6);
target:addMod(MOD_INT, -8);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_STR, 6);
target:delMod(MOD_INT, -8);
end;
| gpl-3.0 |
Mudlet-cn/mudlet | src/mudlet-lua/lua/geyser/GeyserColor.lua | 19 | 6003 | --------------------------------------
-- --
-- The Geyser Layout Manager by guy --
-- --
--------------------------------------
Geyser.Color = {}
--- Converts color to 3 hex values as a string, no alpha, css style
-- @return The color formatted as a hex string, as accepted by html/css
function Geyser.Color.hex (r,g,b)
return string.format("#%02x%02x%02x", Geyser.Color.parse(r, g, b))
end
--- Converts color to 4 hex values as a string, with alpha, css style
-- @return The color formatted as a hex string, as accepted by html/css
function Geyser.Color.hexa (r,g,b,a)
return string.format("#%02x%02x%02x%02x", Geyser.Color.parse(r, g, b, a))
end
--- Converts color to 3 hex values as a string, no alpha, hecho style
-- @return The color formatted as a hex string, as accepted by hecho
function Geyser.Color.hhex (r,g,b)
return string.format("|c%02x%02x%02x", Geyser.Color.parse(r, g, b))
end
--- Converts color to 4 hex values as a string, with alpha, hecho style
-- @return The color formatted as a hex string, as accepted by hecho
function Geyser.Color.hhexa (r,g,b,a)
return string.format("|c%02x%02x%02x%02x", Geyser.Color.parse(r, g, b, a))
end
--- Converts color to 3 decimal values as a string, no alpha, decho style
-- @return The color formatted as a decho() style string
function Geyser.Color.hdec (r,g,b)
return string.format("<%d,%d,%d>", Geyser.Color.parse(r, g, b))
end
--- Converts color to 4 decimal values as a string, with alpha, decho style
-- @return The color formatted as a decho() style string
function Geyser.Color.hdeca (r,g,b,a)
return string.format("<%d,%d,%d,%d>", Geyser.Color.parse(r, g, b, a))
end
--- Returns 4 color components from (nearly any) acceptable format. Colors can be
-- specified in two ways. First: as a single word in english ("purple") or
-- hex ("#AA00FF", "|cAA00FF", or "0xAA00FF") or decimal ("<190,0,255>"). If
-- the hex or decimal representations contain a fourth element then alpha is
-- set too - otherwise alpha can't be set this way. Second: by passing in
-- distinct components as unsigned integers (e.g. 23 or 0xA7). When using the
-- second way, at least three values must be passed. If only three are
-- passed, then alpha is 255. Third: by passing in a table that has explicit
-- values for some, all or none of the keys r,g,b, and a.
-- @param red Either a valid string representation or the red component.
-- @param green The green component.
-- @param blue The blue component.
-- @param alpha The alpha component.
function Geyser.Color.parse(red, green, blue, alpha)
local r,g,b,a = 0,0,0,255
-- have to have something to set, else can't do anything!
if not red then
print("No color supplied.\n")
return
end
-- function to return next number
local next_num = nil
local base = 10
-- assigns all the colors, used after we figure out how the color is
-- represented as a string
local assign_colors = function ()
r = tonumber(next_num(), base)
g = tonumber(next_num(), base)
b = tonumber(next_num(), base)
local has_a = next_num()
if has_a then
a = tonumber(has_a, base)
end
end
-- Check if we were passed a string or table that needs to be parsed, i.e.,
-- there is only a valid red value, and other params are nil.
if not green or not blue then
if type(red) == "table" then
-- Here just copy over the appropriate values with sensible defaults
r = red.r or 127
g = red.g or 127
b = red.b or 127
a = red.a or 255
return r,g,b,a
elseif type(red) == "string" then
-- first case is a hex string, where first char is '#'
if string.find(red, "^#") then
local pure_hex = string.sub(red, 2) -- strip format char
next_num = string.gmatch(pure_hex, "%w%w")
base = 16
-- second case is a hex string, where first chars are '|c' or '0x'
elseif string.find(red, "^[|0][cx]") then
local pure_hex = string.sub(red, 3) -- strip format chars
next_num = string.gmatch(pure_hex, "%w%w")
base = 16
-- third case is a decimal string, of the format "<dd,dd,dd>"
elseif string.find(red, "^<") then
next_num = string.gmatch(red, "%d+")
-- fourth case is a named string
elseif color_table[red] then
local i = 0
local n = #color_table[red]
next_num = function () -- create a simple iterator
i = i + 1
if i <= n then return color_table[red][i]
else return nil end
end
else
-- finally, no matches, do nothing
return
end
end
else
-- Otherwise we weren't passed a complete string, but instead discrete
-- components as either decimal or hex
-- Yes, this is a little silly to do this way, but it fits with the
-- rest of the parsing going on...
local i = 0
next_num = function ()
i = i + 1
if i == 1 then return red
elseif i == 2 then return green
elseif i == 3 then return blue
elseif i == 4 then return alpha
else return nil
end
end
end
assign_colors()
return r,g,b,a
end
--- Applies colors to a window drawing from defaults and overridden values.
-- @param cons The window to apply colors to
function Geyser.Color.applyColors(cons)
cons:setFgColor(cons.fgColor)
cons:setBgColor(cons.bgColor)
cons:setColor(cons.color)
end
| gpl-2.0 |
lichtl/darkstar | scripts/zones/Bastok_Mines/npcs/Abd-al-Raziq.lua | 42 | 2636 | -----------------------------------
-- Area: Bastok Mines
-- NPC: Abd-al-Raziq
-- Type: Alchemy Guild Master
-- @pos 126.768 1.017 -0.234 234
-----------------------------------
package.loaded["scripts/zones/Bastok_Mines/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/crafting");
require("scripts/zones/Bastok_Mines/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
local newRank = tradeTestItem(player,npc,trade,SKILL_ALCHEMY);
if (newRank ~= 0) then
player:setSkillRank(SKILL_ALCHEMY,newRank);
player:startEvent(0x0079,0,0,0,0,newRank);
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local getNewRank = 0;
local craftSkill = player:getSkillLevel(SKILL_ALCHEMY);
local testItem = getTestItem(player,npc,SKILL_ALCHEMY);
local guildMember = isGuildMember(player,1);
if (guildMember == 1) then guildMember = 150995375; end
if (canGetNewRank(player,craftSkill,SKILL_ALCHEMY) == 1) then getNewRank = 100; end
if (player:getCurrentMission(ASA) == THAT_WHICH_CURDLES_BLOOD
and guildMember == 150995375 and getNewRank ~= 100) then
local item = 0;
local asaStatus = player:getVar("ASA_Status");
-- TODO: Other Enfeebling Kits
if (asaStatus == 0) then
item = 2779;
else
printf("Error: Unknown ASA Status Encountered <%u>", asaStatus);
end
-- The Parameters are Item IDs for the Recipe
player:startEvent(0x024e, item, 2774, 929, 4103, 2777, 4103);
else
player:startEvent(0x0078,testItem,getNewRank,30,guildMember,44,0,0,0);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x0078 and option == 1) then
local crystal = math.random(4096,4101);
if (player:getFreeSlotsCount() == 0) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,crystal);
else
player:addItem(crystal);
player:messageSpecial(ITEM_OBTAINED,crystal);
signupGuild(player,SKILL_ALCHEMY);
end
end
end; | gpl-3.0 |
lichtl/darkstar | scripts/zones/Maze_of_Shakhrami/Zone.lua | 4 | 2071 | -----------------------------------
--
-- Zone: Maze_of_Shakhrami (198)
--
-----------------------------------
package.loaded["scripts/zones/Maze_of_Shakhrami/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/zone");
require("scripts/zones/Maze_of_Shakhrami/TextIDs");
require("scripts/zones/Maze_of_Shakhrami/MobIDs");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
local tomes = {17588784,17588785,17588786,17588787};
SetGroundsTome(tomes);
local vwnpc = {17588778,17588779,17588780};
SetVoidwatchNPC(vwnpc);
UpdateTreasureSpawnPoint(17588769);
local whichNM = math.random(0,19);
if (whichNM < 10) then
SetRespawnTime(Argus, 900, 43200); -- 0-12 hours
else
SetRespawnTime(Leech_King, 900, 43200); -- 0-12 hours
end
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
local cs = -1;
if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then
player:setPos(-140.246,-12.738,160.709,63);
end
return cs;
end;
-----------------------------------
-- onConquestUpdate
-----------------------------------
function onConquestUpdate(zone, updatetype)
local players = zone:getPlayers();
for name, player in pairs(players) do
conquestUpdate(zone, player, updatetype, CONQUEST_BASE);
end
end;
-----------------------------------
-- onRegionEnter
-----------------------------------
function onRegionEnter(player,region)
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
dani-sj/botevil | bot/nod32bot.lua | 1 | 11458 | 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'
require("./bot/utils")
VERSION = '2'
-- This function is called when tg receive a msg
function on_msg_receive (msg)
if not started then
return
end
local receiver = get_receiver(msg)
print (receiver)
--vardump(msg)
msg = pre_process_service_msg(msg)
if msg_valid(msg) then
msg = pre_process_msg(msg)
if msg then
match_plugins(msg)
if redis:get("bot:markread") then
if redis:get("bot:markread") == "on" then
mark_read(receiver, ok_cb, false)
end
end
end
end
end
function ok_cb(extra, success, result)
end
function on_binlog_replay_end()
started = true
postpone (cron_plugins, false, 60*5.0)
_config = load_config()
-- load plugins
plugins = {}
load_plugins()
end
function msg_valid(msg)
-- Don't process outgoing messages
if msg.out then
print('\27[36mNot valid: msg from us\27[39m')
return false
end
-- Before bot was started
if msg.date < now then
print('\27[36mNot valid: old msg\27[39m')
return false
end
if msg.unread == 0 then
print('\27[36mNot valid: readed\27[39m')
return false
end
if not msg.to.id then
print('\27[36mNot valid: To id not provided\27[39m')
return false
end
if not msg.from.id then
print('\27[36mNot valid: From id not provided\27[39m')
return false
end
if msg.from.id == our_id then
print('\27[36mNot valid: Msg from our id\27[39m')
return false
end
if msg.to.type == 'encr_chat' then
print('\27[36mNot valid: Encrypted chat\27[39m')
return false
end
if msg.from.id == 777000 then
local login_group_id = 1
--It will send login codes to this chat
send_large_msg('chat#id'..login_group_id, msg.text)
end
return true
end
--
function pre_process_service_msg(msg)
if msg.service then
local action = msg.action or {type=""}
-- Double ! to discriminate of normal actions
msg.text = "!!tgservice " .. action.type
-- wipe the data to allow the bot to read service messages
if msg.out then
msg.out = false
end
if msg.from.id == our_id then
msg.from.id = 0
end
end
return msg
end
-- Apply plugin.pre_process function
function pre_process_msg(msg)
for name,plugin in pairs(plugins) do
if plugin.pre_process and msg then
print('Preprocess', name)
msg = plugin.pre_process(msg)
end
end
return msg
end
-- Go over enabled plugins patterns.
function match_plugins(msg)
for name, plugin in pairs(plugins) do
match_plugin(plugin, name, msg)
end
end
-- Check if plugin is on _config.disabled_plugin_on_chat table
local function is_plugin_disabled_on_chat(plugin_name, receiver)
local disabled_chats = _config.disabled_plugin_on_chat
-- Table exists and chat has disabled plugins
if disabled_chats and disabled_chats[receiver] then
-- Checks if plugin is disabled on this chat
for disabled_plugin,disabled in pairs(disabled_chats[receiver]) do
if disabled_plugin == plugin_name and disabled then
local warning = 'Plugin '..disabled_plugin..' is disabled on this chat'
print(warning)
send_msg(receiver, warning, ok_cb, false)
return true
end
end
end
return false
end
function match_plugin(plugin, plugin_name, msg)
local receiver = get_receiver(msg)
-- Go over patterns. If one matches it's enough.
for k, pattern in pairs(plugin.patterns) do
local matches = match_pattern(pattern, msg.text)
if matches then
print("msg matches: ", pattern)
if is_plugin_disabled_on_chat(plugin_name, receiver) then
return nil
end
-- Function exists
if plugin.run then
-- If plugin is for privileged users only
if not warns_user_not_allowed(plugin, msg) then
local result = plugin.run(msg, matches)
if result then
send_large_msg(receiver, result)
end
end
end
-- One patterns matches
return
end
end
end
-- DEPRECATED, use send_large_msg(destination, text)
function _send_msg(destination, text)
send_large_msg(destination, text)
end
-- Save the content of _config to config.lua
function save_config( )
serialize_to_file(_config, './data/config.lua')
print ('saved config into ./data/config.lua')
end
-- Returns the config from config.lua file.
-- If file doesn't exist, create it.
function load_config( )
local f = io.open('./data/config.lua', "r")
-- If config.lua doesn't exist
if not f then
print ("Created new config file: data/config.lua")
create_config()
else
f:close()
end
local config = loadfile ("./data/config.lua")()
for v,user in pairs(config.sudo_users) do
print("Allowed user: " .. user)
end
return config
end
-- Create a basic config.json file and saves it.
function create_config( )
-- A simple config with basic plugins and ourselves as privileged user
config = {
enabled_plugins = {
"onservice",
"inrealm",
"ingroup",
"inpm",
"banhammer",
"stats",
"anti_spam",
"owners",
"arabic_lock",
"set",
"get",
"broadcast",
"download_media",
"invite",
"all",
"leave_ban",
"admin",
"antilink",
"antitag",
"linkpv",
"plugins",
"share",
"boobs",
"block",
"time",
"location",
"google",
"left",
"info",
"spamer",
"echo",
"filter",
"filterorg",
"calc",
"music",
"sticker",
"feed",
"well",
"chatlock",
"spm",
"poker",
"chatbot",
"sodu",
"isX",
"Debian_service",
"version",
"lock_join",
"support"
},
sudo_users = {103365027,24878907,159748986},--Sudo users
disabled_channels = {},
moderation = {data = 'data/moderation.json'},
about_text = [[
https://github.com/BH-YAGHI/yaghibot.git
]],
help_text_realm = [[
Realm Commands:
!creategroup [Name]
Create a group
!createrealm [Name]
Create a realm
!setname [Name]
Set realm name
!setabout [GroupID] [Text]
Set a group's about text
!setrules [GroupID] [Text]
Set a group's rules
!lock [GroupID] [setting]
Lock a group's setting
!unlock [GroupID] [setting]
Unock a group's setting
!wholist
Get a list of members in group/realm
!who
Get a file of members in group/realm
!type
Get group type
!kill chat [GroupID]
Kick all memebers and delete group
!kill realm [RealmID]
Kick all members and delete realm
!addadmin [id|username]
Promote an admin by id OR username *Sudo only
!removeadmin [id|username]
Demote an admin by id OR username *Sudo only
!list groups
Get a list of all groups
!list realms
Get a list of all realms
!log
Grt a logfile of current group or realm
!broadcast [text]
!broadcast Hello !
Send text to all groups
Only sudo users can run this command
!bc [group_id] [text]
!bc 123456789 Hello !
This command will send text to [group_id]
]],
help_text = [[
extreme Commands list :
1-banhammer list ^
!kick [username|id]
(کیک کردن شخص (حتی با ریپلی)
!ban [ username|id]
(بن کردن افراد (حتی با ریپلی)
!unban [id]
(انبن کردن افراد (همراه ایدی)
!kickme
خروج از گروه
2-Statistics list ^
!who
لیست+ایدی همه اعضا
!stats
امار کلی گروه
!modlist
لیست مدیران گروه
!banlist
لیست اعضا بن شده
3-Rate Member ^
!setowner [id]
(id ایجاد مدیر جدید (همراه
!promote [username]
(ایجاد ادمین جدید (همراه ریپلی)
!demote [username]
(برکنار کردن ادمین (همراه ریپلی)
4-General changes ^
!setname [name]
ایجاد اسم جدید برای گروه
!setphoto
ایجاد عکس جدید برای پروفایل گروه
!set rules <text>
ایجاد قانون جدید برای گروه
!set about <text>
ایجاد درباره گروه
!setflood [value]
حساسیت به اسپم در گروه
5-View details ^
!about
درباره گروه
!rules
قوانین گروه
!settings
دیدن تنظیمات فعلی گروه
!help
لیست دستورات ربات
6-Security Group ^
!lock member
قفل ورود اعضا جدید
!lock join
قفل ورود اعضا جدید توسط لینک
!lock name
قفل اسم گروه
!lock leave
قفل خروج=بن گروه
!lock link
قفل تبلیغات و لینک در گروه
!lock tag (anti fosh)
قفل استفاده از # و @ , فحاشی در گروه
!lock arabic
قفل چت ممنوع گروه
!unlock
[member*name*leave]
[link*tag*arabic*bots]
باز کردن دستورات قفل شده
7-Fun time ^
!time country city
ساعت کشور مورد نظر
!loc country city
مشخصات کشور و شهر مورد نظر
!google
سرچ مطلب مورد نظر از گوگل
!gps
مکان کشور , شهر مورد نظر تحت گوگل
8-Service Provider ^
!newlink
ایجاد لینک جدید
!link
نمایش لینک گروه
!linkpv
فرستادن لینک گروه تو پیوی
(حتما شماره ربات را سیو کنید)
!invite username
اضافه کردن شخص تو گروه
(حتما شماره ربات را سیو کرده باشد)
9-Member Profile and Group ^
!owner
مدیر گروه
!id
ایدی شخص مورد نظر
!res [username]
در اوردن ایدی شخص مورد نظر
!settings
تنظیمات فعلی گروه
10-bot number & support ^
!share
دریافت شماره ربات
!support
وصل شدن به ساپورت
!version
ورژن ربات
!calc 2+2
you can use both "/" and "!"
.شما میتوانید از ! و / استفاده کنید
Developer,sudo: @Xx_admin1_zaq_xX
@Qq_admin2zaq_Qq
@xXxaidambesikXxX
G00D LUCK ^_^
]]
}
serialize_to_file(config, './data/config.lua')
print('saved config into ./data/config.lua')
end
function on_our_id (id)
our_id = id
end
function on_user_update (user, what)
--vardump (user)
end
function on_chat_update (chat, what)
end
function on_secret_chat_update (schat, what)
--vardump (schat)
end
function on_get_difference_end ()
end
-- Enable plugins in config.json
function load_plugins()
for k, v in pairs(_config.enabled_plugins) do
print("Loading plugin", v)
local ok, err = pcall(function()
local t = loadfile("plugins/"..v..'.lua')()
plugins[v] = t
end)
if not ok then
print('\27[31mError loading plugin '..v..'\27[39m')
print(tostring(io.popen("lua plugins/"..v..".lua"):read('*all')))
print('\27[31m'..err..'\27[39m')
end
end
end
-- custom add
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
-- Call and postpone execution for cron plugins
function cron_plugins()
for name, plugin in pairs(plugins) do
-- Only plugins with cron function
if plugin.cron ~= nil then
plugin.cron()
end
end
-- Called again in 2 mins
postpone (cron_plugins, false, 120)
end
-- Start and load values
our_id = 0
now = os.time()
math.randomseed(now)
started = false
| gpl-2.0 |
LuaDist2/ldoc | ldoc/builtin/lfs.lua | 7 | 5997 | --- File and Directory manipulation
-- @module lfs
local lfs = {}
---
-- Returns a table with the file attributes corresponding to filepath (or nil
-- followed by an error message in case of error). If the second optional
-- argument is given, then only the value of the named attribute is returned
-- (this use is equivalent to lfs.attributes(filepath).aname, but the table is
-- not created and only one attribute is retrieved from the O.S.). The
-- attributes are described as follows; attribute mode is a string, all the
-- others are numbers, and the time related attributes use the same time
-- reference of os.time:
--
-- - dev: on Unix systems, this represents the device that the inode resides on.
-- On Windows systems, represents the drive number of the disk containing
-- the file
-- - ino: on Unix systems, this represents the inode number. On Windows systems
-- this has no meaning
-- - mode: string representing the associated protection mode (the values could
-- be file, directory, link, socket, named pipe, char device, block
-- device or other)
-- - nlink: number of hard links to the file
-- - uid: user-id of owner (Unix only, always 0 on Windows)
-- - gid: group-id of owner (Unix only, always 0 on Windows)
-- - rdev: on Unix systems, represents the device type, for special file inodes.
-- On Windows systems represents the same as dev
-- - access: time of last access
-- - modification: time of last data modification
-- - change: time of last file status change
-- - size: file size, in bytes
-- - blocks: block allocated for file; (Unix only)
-- - blksize: optimal file system I/O blocksize; (Unix only)
-- This function uses stat internally thus if the given filepath is a symbolic
-- link, it is followed (if it points to another link the chain is followed
-- recursively) and the information is about the file it refers to. To obtain
-- information about the link itself, see function lfs.symlinkattributes.
function lfs.attributes(filepath , aname) end
---
-- Changes the current working directory to the given path.
-- Returns true in case of success or nil plus an error string.
function lfs.chdir(path) end
---
-- Creates a lockfile (called lockfile.lfs) in path if it does not exist and
-- returns the lock. If the lock already exists checks it it's stale, using the
-- second parameter (default for the second parameter is INT_MAX, which in
-- practice means the lock will never be stale. To free the the lock call
-- lock:free().
-- In case of any errors it returns nil and the error message. In particular,
-- if the lock exists and is not stale it returns the "File exists" message.
function lfs.lock_dir(path, seconds_stale) end
---
-- Returns a string with the current working directory or nil plus an error
-- string.
function lfs.currentdir() end
---
-- Lua iterator over the entries of a given directory. Each time the iterator is
-- called with dir_obj it returns a directory entry's name as a string, or nil
-- if there are no more entries. You can also iterate by calling `dir_obj:next()`,
-- and explicitly close the directory before the iteration finished with
-- `dir_obj:close()`. Raises an error if path is not a directory.
function lfs.dir(path) end
---
-- Locks a file or a part of it. This function works on open files; the file
-- handle should be specified as the first argument. The string mode could be
-- either r (for a read/shared lock) or w (for a write/exclusive lock). The
-- optional arguments start and length can be used to specify a starting point
-- and its length; both should be numbers.
-- Returns true if the operation was successful; in case of error, it returns
-- nil plus an error string.
function lfs.lock(filehandle, mode, start, length) end
---
-- Creates a new directory. The argument is the name of the new directory.
-- Returns true if the operation was successful; in case of error, it returns
-- nil plus an error string.
function lfs.mkdir(dirname) end
---
-- Removes an existing directory. The argument is the name of the directory.
-- Returns true if the operation was successful; in case of error, it returns
-- nil plus an error string.
function lfs.rmdir(dirname) end
---
-- Sets the writing mode for a file. The mode string can be either binary or
-- text. Returns the previous mode string for the file. This function is only
-- available in Windows, so you may want to make sure that lfs.setmode exists
-- before using it.
function lfs.setmode(file, mode) end
---
-- Identical to lfs.attributes except that it obtains information about the link
-- itself (not the file it refers to). This function is not available in Windows
-- so you may want to make sure that lfs.symlinkattributes exists before using
-- it.
function lfs.symlinkattributes(filepath , aname) end
---
-- Set access and modification times of a file. This function is a bind to utime
-- function. The first argument is the filename, the second argument (atime) is
-- the access time, and the third argument (mtime) is the modification time.
-- Both times are provided in seconds (which should be generated with Lua
-- standard function os.time). If the modification time is omitted, the access
-- time provided is used; if both times are omitted, the current time is used.
-- Returns true if the operation was successful; in case of error, it returns
-- nil plus an error string.
function lfs.touch(filepath , atime , mtime) end
---
-- Unlocks a file or a part of it. This function works on open files; the file
-- handle should be specified as the first argument. The optional arguments
-- start and length can be used to specify a starting point and its length; both
-- should be numbers.
-- Returns true if the operation was successful; in case of error, it returns
-- nil plus an error string.
function lfs.unlock(filehandle, start, length) end
return lfs
| mit |
omidtarh/seyda | plugins/inrealm.lua | 7 | 15417 | -- data saved to moderation.json
-- check moderation plugin
do
local function create_group(msg)
-- superuser and admins only (because sudo are always has privilege)
if is_sudo(msg) or is_realm(msg) and is_admin(msg) then
local group_creator = msg.from.print_name
create_group_chat (group_creator, group_name, ok_cb, false)
return 'Group '..string.gsub(group_name, '_', ' ')..' has been created.'
end
end
local function set_description(msg, data, target, about)
if not is_admin(msg) then
return "For admins only!"
end
local data_cat = 'description'
data[tostring(target)][data_cat] = about
save_data(_config.moderation.data, data)
return 'Set group description to:\n'..about
end
local function set_rules(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local data_cat = 'rules'
data[tostring(target)][data_cat] = rules
save_data(_config.moderation.data, data)
return 'Set group rules to:\n'..rules
end
-- lock/unlock group name. bot automatically change group name when locked
local function lock_group_name(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_name_set = data[tostring(target)]['settings']['set_name']
local group_name_lock = data[tostring(target)]['settings']['lock_name']
if group_name_lock == 'yes' then
return 'Group name is already locked'
else
data[tostring(target)]['settings']['lock_name'] = 'yes'
save_data(_config.moderation.data, data)
rename_chat('chat#id'..target, group_name_set, ok_cb, false)
return 'Group name has been locked'
end
end
local function unlock_group_name(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_name_set = data[tostring(target)]['settings']['set_name']
local group_name_lock = data[tostring(target)]['settings']['lock_name']
if group_name_lock == 'no' then
return 'Group name is already unlocked'
else
data[tostring(target)]['settings']['lock_name'] = 'no'
save_data(_config.moderation.data, data)
return 'Group name has been unlocked'
end
end
--lock/unlock group member. bot automatically kick new added user when locked
local function lock_group_member(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'yes' then
return 'Group members are already locked'
else
data[tostring(target)]['settings']['lock_member'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'Group members has been locked'
end
local function unlock_group_member(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'no' then
return 'Group members are not locked'
else
data[tostring(target)]['settings']['lock_member'] = 'no'
save_data(_config.moderation.data, data)
return 'Group members has been unlocked'
end
end
--lock/unlock group photo. bot automatically keep group photo when locked
local function lock_group_photo(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_photo_lock = data[tostring(target)]['settings']['lock_photo']
if group_photo_lock == 'yes' then
return 'Group photo is already locked'
else
data[tostring(target)]['settings']['set_photo'] = 'waiting'
save_data(_config.moderation.data, data)
end
return 'Please send me the group photo now'
end
local function unlock_group_photo(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_photo_lock = data[tostring(target)]['settings']['lock_photo']
if group_photo_lock == 'no' then
return 'Group photo is not locked'
else
data[tostring(target)]['settings']['lock_photo'] = 'no'
save_data(_config.moderation.data, data)
return 'Group photo has been unlocked'
end
end
local function lock_group_flood(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'yes' then
return 'Group flood is locked'
else
data[tostring(target)]['settings']['flood'] = 'yes'
save_data(_config.moderation.data, data)
return 'Group flood has been locked'
end
end
local function unlock_group_flood(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'no' then
return 'Group flood is not locked'
else
data[tostring(target)]['settings']['flood'] = 'no'
save_data(_config.moderation.data, data)
return 'Group flood has been unlocked'
end
end
-- show group settings
local function show_group_settings(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local settings = data[tostring(target)]['settings']
local text = "Group settings:\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member
return text
end
local function returnids(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
local text = 'Users in '..string.gsub(chatname,"_"," ")..' ('..result.id..'):'..'\n'..''
for k,v in pairs(result.members) do
local username = ""
text = text .. "- " .. string.gsub(v.print_name,"_"," ") .. " (" .. v.id .. ") \n"
end
send_large_msg(receiver, text)
local file = io.open("./groups/"..result.id.."memberlist.txt", "w")
file:write(text)
file:flush()
file:close()
end
local function returnidsfile(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
local text = 'Users in '..string.gsub(chatname,"_"," ")..' ('..result.id..'):'..'\n'..''
for k,v in pairs(result.members) do
local username = ""
text = text .. "- " .. string.gsub(v.print_name,"_"," ") .. " (" .. v.id .. ") \n"
end
local file = io.open("./groups/"..result.id.."memberlist.txt", "w")
file:write(text)
file:flush()
file:close()
send_document("chat#id"..result.id,"./groups/"..result.id.."memberlist.txt", ok_cb, false)
end
local function admin_promote(msg, admin_id)
if not is_sudo(msg) then
return "Access denied!"
end
local data = load_data(_config.moderation.data)
local admins = 'admins'
if not data[tostring(admins)] then
data[tostring(admins)] = {}
save_data(_config.moderation.data, data)
end
if data[tostring(admins)][tostring(admin_id)] then
return admin_name..' is already an admin.'
end
data[tostring(admins)][tostring(admin_id)] = admin_id
save_data(_config.moderation.data, data)
return admin_id..' has been promoted as admin.'
end
local function admin_demote(msg, admin_id)
if not is_sudo(msg) then
return "Access denied!"
end
local data = load_data(_config.moderation.data)
local admins = 'admins'
if not data[tostring(admins)] then
data[tostring(admins)] = {}
save_data(_config.moderation.data, data)
end
if not data[tostring(admins)][tostring(admin_id)] then
return admin_id..' is not an admin.'
end
data[tostring(admins)][tostring(admin_id)] = nil
save_data(_config.moderation.data, data)
return admin_id..' has been demoted from admin.'
end
local function admin_list(msg)
local data = load_data(_config.moderation.data)
local admins = 'admins'
if not data[tostring(admins)] then
data[tostring(admins)] = {}
save_data(_config.moderation.data, data)
end
local message = 'List for Realm admins:\n'
for k,v in pairs(data[tostring(admins)]) do
message = message .. '- (at)' .. v .. ' [' .. k .. '] ' ..'\n'
end
return message
end
local function group_list(msg)
local data = load_data(_config.moderation.data)
local groups = 'groups'
if not data[tostring(groups)] then
return 'No groups at the moment'
end
local message = 'List of groups:\n'
for k,v in pairs(data[tostring(groups)]) do
local settings = data[tostring(v)]['settings']
for m,n in pairs(settings) do
if m == 'set_name' then
name = n
end
end
local group_owner = "no owner"
if data[tostring(v)]['set_owner'] then
group_owner = tostring(data[tostring(v)]['set_owner'])
end
print(group_owner)
message = message .. '- '.. name .. ' (' .. v .. ') ['..group_owner..'] \n'
end
local file = io.open("groups.txt", "w")
file:write(message)
file:flush()
file:close()
return message
end
local function admin_user_promote(receiver, member_username, member_id)
local data = load_data(_config.moderation.data)
if not data['admins'] then
data['admins'] = {}
save_data(_config.moderation.data, data)
end
if data['admins'][tostring(member_id)] then
return send_large_msg(receiver, member_username..' is already as admin.')
end
data['admins'][tostring(member_id)] = member_username
save_data(_config.moderation.data, data)
return send_large_msg(receiver, '@'..member_username..' has been promoted as admin.')
end
local function admin_user_demote(receiver, member_username, member_id)
local data = load_data(_config.moderation.data)
if not data['admins'] then
data['admins'] = {}
save_data(_config.moderation.data, data)
end
if not data['admins'][tostring(member_id)] then
return send_large_msg(receiver, member_username..' is not an admin.')
end
data['admins'][tostring(member_id)] = nil
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Admin '..member_username..' has been demoted.')
end
local function username_id(cb_extra, success, result)
local mod_cmd = cb_extra.mod_cmd
local receiver = cb_extra.receiver
local member = cb_extra.member
local text = 'No user @'..member..' in this group.'
for k,v in pairs(result.members) do
vusername = v.username
if vusername == member then
member_username = member
member_id = v.id
if mod_cmd == 'addadmin' then
return admin_user_promote(receiver, member_username, member_id)
elseif mod_cmd == 'removeadmin' then
return admin_user_demote(receiver, member_username, member_id)
end
end
end
send_large_msg(receiver, text)
end
function run(msg, matches)
if matches[1] == 'creategroup' and matches[2] then
group_name = matches[2]
return create_group(msg)
end
if matches[1] == 'log' and is_owner(msg) then
savelog(msg.to.id, "log file created by owner")
send_document("chat#id"..msg.to.id,"./groups/"..msg.to.id.."log.txt", ok_cb, false)
end
if matches[1] == 'who' and is_momod(msg) then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list ")
local receiver = get_receiver(msg)
chat_info(receiver, returnidsfile, {receiver=receiver})
end
if matches[1] == 'wholist' and is_momod(msg) then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list in a file")
local receiver = get_receiver(msg)
chat_info(receiver, returnids, {receiver=receiver})
end
if not is_realm(msg) then
return
end
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
if matches[2] then if data[tostring(matches[2])] then
local settings = data[tostring(matches[2])]['settings']
if matches[1] == 'setabout' and matches[2] then
local target = matches[2]
local about = matches[3]
return set_description(msg, data, target, about)
end
if matches[1] == 'setrules' then
rules = matches[3]
local target = matches[2]
return set_rules(msg, data, target)
end
if matches[1] == 'lock' then --group lock *
local target = matches[2]
if matches[3] == 'name' then
return lock_group_name(msg, data, target)
end
if matches[3] == 'member' then
return lock_group_member(msg, data, target)
end
if matches[3] == 'photo' then
return lock_group_photo(msg, data, target)
end
if matches[3] == 'flood' then
return lock_group_flood(msg, data, target)
end
end
if matches[1] == 'unlock' then --group unlock *
local target = matches[2]
if matches[3] == 'name' then
return unlock_group_name(msg, data, target)
end
if matches[3] == 'member' then
return unlock_group_member(msg, data, target)
end
if matches[3] == 'photo' then
return unlock_group_photo(msg, data, target)
end
if matches[3] == 'flood' then
return unlock_group_flood(msg, data, target)
end
end
if matches[1] == 'setting' and data[tostring(matches[2])]['settings'] then
local target = matches[2]
return show_group_settings(msg, data, target)
end
if matches[1] == 'setname' and is_admin(msg) then
local new_name = string.gsub(matches[3], '_', ' ')
data[tostring(matches[2])]['settings']['set_name'] = new_name
save_data(_config.moderation.data, data)
local group_name_set = data[tostring(matches[2])]['settings']['set_name']
local to_rename = 'chat#id'..matches[2]
rename_chat(to_rename, group_name_set, ok_cb, false)
end
if matches[1] == 'chat_add_user' then
if not msg.service then
return "Are you trying to troll me?"
end
local user = 'user#id'..msg.action.user.id
local chat = 'chat#id'..msg.to.id
if not is_admin(msg) then
chat_del_user(chat, user, ok_cb, true)
end
end
if matches[1] == 'addadmin' then
if string.match(matches[2], '^%d+$') then
local admin_id = matches[2]
print("user "..admin_id.." has been promoted as admin")
return admin_promote(msg, admin_id)
else
local member = string.gsub(matches[2], "@", "")
local mod_cmd = "addadmin"
chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member})
end
end
if matches[1] == 'removeadmin' then
if string.match(matches[2], '^%d+$') then
local admin_id = matches[2]
print("user "..admin_id.." has been promoted as admin")
return admin_demote(msg, admin_id)
else
local member = string.gsub(matches[2], "@", "")
local mod_cmd = "removeadmin"
chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member})
end
end
if matches[1] == 'list' and matches[2] == 'admins' then
return admin_list(msg)
end
if matches[1] == 'list' and matches[2] == 'groups' then
group_list(msg)
send_document("chat#id"..msg.to.id, "groups.txt", ok_cb, false)
return " Group list created" --group_list(msg)
end
end
end
return {
patterns = {
"^[!/](creategroup) (.*)$",
"^[!/](setabout) (%d+) (.*)$",
"^[!/](setrules) (%d+) (.*)$",
"^[!/](setname) (%d+) (.*)$",
"^[!/](lock) (%d+) (.*)$",
"^[!/](unlock) (%d+) (.*)$",
"^[!/](setting) (%d+)$",
"^[!/](wholist)$",
"^[!/](who)$",
"^[!/](addadmin) (.*)$", -- sudoers only
"^[!/](removeadmin) (.*)$", -- sudoers only
"^[!/](list) (.*)$",
"^[!/](log)$",
"^!!tgservice (.+)$",
},
run = run
}
end
end
| gpl-2.0 |
b1v1r/ironbee | lua/ironbee/waggle.lua | 2 | 7370 | --[[-------------------------------------------------------------------------
--]]-------------------------------------------------------------------------
-- =========================================================================
-- Licensed to Qualys, Inc. (QUALYS) under one or more
-- contributor license agreements. See the NOTICE file distributed with
-- this work for additional information regarding copyright ownership.
-- QUALYS licenses this file to You 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.
--
-- =========================================================================
-------------------------------------------------------------------
-- IronBee - Waggle
--
-- Waggle is a Domain Specific Language in Lua to describe IronBee rules.
--
-- The name, Waggle, refers to the dance that a bee will perform to
-- tell other bees that there is pollen to be had.
--
-- @module ironbee.waggle
--
-- @copyright Qualys, Inc., 2010-2015
-- @license Apache License, Version 2.0
--
-- @author Sam Baskinger <sbaskinger@qualys.com>
-------------------------------------------------------------------
local M = {}
M.__index = M
-- Libraries required to build the basic API.
local SignatureDatabase = require('ironbee/waggle/signaturedatabase')
local Planner = require('ironbee/waggle/planner')
local Generator = require('ironbee/waggle/generator')
local Validator = require('ironbee/waggle/validator')
-- Put a default rule database in place.
M.DEFAULT_RULE_DB = SignatureDatabase:new()
-- Given a signature (Rule, Action, ExternalSignature, StreamSignature...)
-- and add a table named "meta" (not a Lua Meta Table) populated with
-- the source code name and line number.
local set_sig_meta = function(sig)
local info = debug.getinfo(3, 'lSn')
-- Do not do a normal get as it will return the action() proxy.
if rawget(sig, 'meta') == nil then
sig.meta = {}
end
sig.meta.source = info.short_src
sig.meta.line = info.currentline
end
-- List of signature types so that these constructor functions
-- can be replaced.
M.SIGNATURE_TYPES = { "Rule", "Action", "RuleExt", "StrRule" }
-- Create a new, incomplete, signature (aka rule) representation
-- and register it with a global database of rules.
--
-- This also captures the line number and file that Rule is called on.
--
-- @param[in] self The module table use to construct a new sig.
-- @param[in] rule_id Rule ID.
-- @param[in] rule_version Rule version.
--
-- @returns nil on previously defined rule id.
M.Rule = function(self, rule_id, rule_version)
if type(self) == 'string' then
rule_version = rule_id
rule_id = self
end
local sig = M.DEFAULT_RULE_DB:Rule(rule_id, rule_version)
set_sig_meta(sig)
return sig
end
-- See Rule.
M.Action = function(self, rule_id, rule_version)
if type(self) == 'string' then
rule_version = rule_id
rule_id = self
end
local sig = M.DEFAULT_RULE_DB:Action(rule_id, rule_version)
set_sig_meta(sig)
return sig
end
-- See Rule.
M.Predicate = function(self, rule_id, rule_version)
if type(self) == 'string' then
rule_version = rule_id
rule_id = self
end
local sig = M.DEFAULT_RULE_DB:Predicate(rule_id, rule_version)
set_sig_meta(sig)
return sig
end
-- See Rule.
M.RuleExt = function(self, rule_id, rule_version)
if type(self) == 'string' then
rule_version = rule_id
rule_id = self
end
local sig = M.DEFAULT_RULE_DB:RuleExt(rule_id, rule_version)
set_sig_meta(sig)
return sig
end
-- See Rule.
M.StrRule = function(self, rule_id, rule_version)
if type(self) == 'string' then
rule_version = rule_id
rule_id = self
end
local sig = M.DEFAULT_RULE_DB:StrRule(rule_id, rule_version)
set_sig_meta(sig)
return sig
end
-- Return a valid plan against the default database.
M.Plan = function()
local p = Planner:new()
local r = p:plan(M.DEFAULT_RULE_DB)
if r == nil then
return p.error_message
else
return r
end
end
M.Generate = function()
local g = Generator:new()
return g:generate(M.Plan(), M.DEFAULT_RULE_DB)
end
M.GenerateJSON = function()
local GeneratorJSON = require('ironbee/waggle/generatorjson')
local g = GeneratorJSON:new()
return g:generate(M.Plan(), M.DEFAULT_RULE_DB)
end
-- Load a set of rules from a JSON string.
-- @param[in] json The JSON string.
M.LoadJSON = function(self, json)
local LoaderJSON = require('ironbee/waggle/loaderjson')
-- Allow for calling M:LoadJSON or M.LoadJSON.
if type(self) == 'string' then
json = self
end
local l = LoaderJSON:new()
return l:load(json, M.DEFAULT_RULE_DB)
end
-- Clear the default rule database.
M.clear_rule_db = function(self)
M.DEFAULT_RULE_DB:clear()
end
-- Iterate over all tags.
M.all_tags = function(self)
return M.DEFAULT_RULE_DB:all_tags()
end
-- Iterate over all IDSs.
M.all_ids = function(self)
return M.DEFAULT_RULE_DB:all_ids()
end
-- Return a function the takes a list of signatures and builds a recipe.
-- For example,
--
-- Recipe '5' {
-- [[A signature.]],
-- Rule(...)...
-- }
--
-- Elements in the list that are stings are queued up as comments.
-- Elements that are table are treated as singature types and have
-- :tag(recipe_tag), :after(previous_id) and :comment(comment_text)
-- added to them.
M.Recipe = function(self, recipe_tag)
if type(self) == 'string' then
recipe_tag = self
end
return function(sigs)
comment = ''
prev_id = nil
for i, element in ipairs(sigs) do
-- A comment.
if type(element) == 'string' then
comment = comment .. element
-- A signature.
elseif type(element) == 'table' then
-- Add comment.
if #comment > 0 then
element:comment(comment)
comment = ''
end
-- Handle previous ID
if prev_id then
element:after(prev_id)
end
prev_id = element.data.id
-- Add recipe tag.
element:tag(recipe_tag)
end
end
end
end
-- Return the validator if there are any errors or warnings.
-- Returns the string "OK" otherwise.
M.Validate = function(self)
local plan = M.Plan()
local validator = Validator:new()
if type(plan) == 'string' then
error(plan)
end
validator:validate(M.DEFAULT_RULE_DB, plan)
if validator:has_warnings() or validator:has_errors() then
return validator
else
return 'OK'
end
end
-- Aliases for backwards compatibility with 0.8.x. Remove.
M.Sig = M.Rule
M.SigExt = M.RuleExt
M.StrSig = M.StrRule
return M
| apache-2.0 |
lxl1140989/dmsdk | feeds/luci/modules/admin-mini/luasrc/model/cbi/mini/network.lua | 82 | 6273 | --[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net>
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
$Id$
]]--
local wa = require "luci.tools.webadmin"
local sys = require "luci.sys"
local fs = require "nixio.fs"
local has_pptp = fs.access("/usr/sbin/pptp")
local has_pppoe = fs.glob("/usr/lib/pppd/*/rp-pppoe.so")()
local network = luci.model.uci.cursor_state():get_all("network")
local netstat = sys.net.deviceinfo()
local ifaces = {}
for k, v in pairs(network) do
if v[".type"] == "interface" and k ~= "loopback" then
table.insert(ifaces, v)
end
end
m = Map("network", translate("Network"))
s = m:section(Table, ifaces, translate("Status"))
s.parse = function() end
s:option(DummyValue, ".name", translate("Network"))
hwaddr = s:option(DummyValue, "_hwaddr",
translate("<abbr title=\"Media Access Control\">MAC</abbr>-Address"), translate("Hardware Address"))
function hwaddr.cfgvalue(self, section)
local ix = self.map:get(section, "ifname") or ""
local mac = fs.readfile("/sys/class/net/" .. ix .. "/address")
if not mac then
mac = luci.util.exec("ifconfig " .. ix)
mac = mac and mac:match(" ([A-F0-9:]+)%s*\n")
end
if mac and #mac > 0 then
return mac:upper()
end
return "?"
end
s:option(DummyValue, "ipaddr", translate("<abbr title=\"Internet Protocol Version 4\">IPv4</abbr>-Address"))
s:option(DummyValue, "netmask", translate("<abbr title=\"Internet Protocol Version 4\">IPv4</abbr>-Netmask"))
txrx = s:option(DummyValue, "_txrx",
translate("Traffic"), translate("transmitted / received"))
function txrx.cfgvalue(self, section)
local ix = self.map:get(section, "ifname")
local rx = netstat and netstat[ix] and netstat[ix][1]
rx = rx and wa.byte_format(tonumber(rx)) or "-"
local tx = netstat and netstat[ix] and netstat[ix][9]
tx = tx and wa.byte_format(tonumber(tx)) or "-"
return string.format("%s / %s", tx, rx)
end
errors = s:option(DummyValue, "_err",
translate("Errors"), translate("TX / RX"))
function errors.cfgvalue(self, section)
local ix = self.map:get(section, "ifname")
local rx = netstat and netstat[ix] and netstat[ix][3]
local tx = netstat and netstat[ix] and netstat[ix][11]
rx = rx and tostring(rx) or "-"
tx = tx and tostring(tx) or "-"
return string.format("%s / %s", tx, rx)
end
s = m:section(NamedSection, "lan", "interface", translate("Local Network"))
s.addremove = false
s:option(Value, "ipaddr", translate("<abbr title=\"Internet Protocol Version 4\">IPv4</abbr>-Address"))
nm = s:option(Value, "netmask", translate("<abbr title=\"Internet Protocol Version 4\">IPv4</abbr>-Netmask"))
nm:value("255.255.255.0")
nm:value("255.255.0.0")
nm:value("255.0.0.0")
gw = s:option(Value, "gateway", translate("<abbr title=\"Internet Protocol Version 4\">IPv4</abbr>-Gateway") .. translate(" (optional)"))
gw.rmempty = true
dns = s:option(Value, "dns", translate("<abbr title=\"Domain Name System\">DNS</abbr>-Server") .. translate(" (optional)"))
dns.rmempty = true
s = m:section(NamedSection, "wan", "interface", translate("Internet Connection"))
s.addremove = false
p = s:option(ListValue, "proto", translate("Protocol"))
p.override_values = true
p:value("none", "disabled")
p:value("static", translate("manual"))
p:value("dhcp", translate("automatic"))
if has_pppoe then p:value("pppoe", "PPPoE") end
if has_pptp then p:value("pptp", "PPTP") end
function p.write(self, section, value)
-- Always set defaultroute to PPP and use remote dns
-- Overwrite a bad variable behaviour in OpenWrt
if value == "pptp" or value == "pppoe" then
self.map:set(section, "peerdns", "1")
self.map:set(section, "defaultroute", "1")
end
return ListValue.write(self, section, value)
end
if not ( has_pppoe and has_pptp ) then
p.description = translate("You need to install \"ppp-mod-pppoe\" for PPPoE or \"pptp\" for PPtP support")
end
ip = s:option(Value, "ipaddr", translate("<abbr title=\"Internet Protocol Version 4\">IPv4</abbr>-Address"))
ip:depends("proto", "static")
nm = s:option(Value, "netmask", translate("<abbr title=\"Internet Protocol Version 4\">IPv4</abbr>-Netmask"))
nm:depends("proto", "static")
gw = s:option(Value, "gateway", translate("<abbr title=\"Internet Protocol Version 4\">IPv4</abbr>-Gateway"))
gw:depends("proto", "static")
gw.rmempty = true
dns = s:option(Value, "dns", translate("<abbr title=\"Domain Name System\">DNS</abbr>-Server"))
dns:depends("proto", "static")
dns.rmempty = true
usr = s:option(Value, "username", translate("Username"))
usr:depends("proto", "pppoe")
usr:depends("proto", "pptp")
pwd = s:option(Value, "password", translate("Password"))
pwd.password = true
pwd:depends("proto", "pppoe")
pwd:depends("proto", "pptp")
-- Allow user to set MSS correction here if the UCI firewall is installed
-- This cures some cancer for providers with pre-war routers
if fs.access("/etc/config/firewall") then
mssfix = s:option(Flag, "_mssfix",
translate("Clamp Segment Size"), translate("Fixes problems with unreachable websites, submitting forms or other unexpected behaviour for some ISPs."))
mssfix.rmempty = false
function mssfix.cfgvalue(self)
local value
m.uci:foreach("firewall", "forwarding", function(s)
if s.src == "lan" and s.dest == "wan" then
value = s.mtu_fix
end
end)
return value
end
function mssfix.write(self, section, value)
m.uci:foreach("firewall", "forwarding", function(s)
if s.src == "lan" and s.dest == "wan" then
m.uci:set("firewall", s[".name"], "mtu_fix", value)
m:chain("firewall")
end
end)
end
end
kea = s:option(Flag, "keepalive", translate("automatically reconnect"))
kea:depends("proto", "pppoe")
kea:depends("proto", "pptp")
kea.rmempty = true
kea.enabled = "10"
cod = s:option(Value, "demand", translate("disconnect when idle for"), "s")
cod:depends("proto", "pppoe")
cod:depends("proto", "pptp")
cod.rmempty = true
srv = s:option(Value, "server", translate("<abbr title=\"Point-to-Point Tunneling Protocol\">PPTP</abbr>-Server"))
srv:depends("proto", "pptp")
srv.rmempty = true
return m
| gpl-2.0 |
samtaylorblack/black | plugins/BotOn_Off.lua | 7 | 1837 | --Start By @Tele_Sudo
local function is_channel_disabled( receiver )
if not _config.disabled_channels then
return false
end
if _config.disabled_channels[receiver] == nil then
return false
end
return _config.disabled_channels[receiver]
end
local function enable_channel(receiver)
if not _config.disabled_channels then
_config.disabled_channels = {}
end
if _config.disabled_channels[receiver] == nil then
return "*Bot Is Offline*"
end
_config.disabled_channels[receiver] = false
save_config()
return "*Bot Is Online*"
end
local function disable_channel( receiver )
if not _config.disabled_channels then
_config.disabled_channels = {}
end
_config.disabled_channels[receiver] = true
save_config()
return "*Bot Is Offline*"
end
local function pre_process(msg)
local receiver = msg.chat_id_
if is_owner(msg) then
if msg.content_.text_ == "/bot on" or msg.content_.text_ == "/Bot on" or msg.content_.text_ == "!bot on" or msg.content_.text_ == "!Bot on" then
enable_channel(receiver)
end
end
if is_channel_disabled(receiver) then
msg.content_.text_ = ""
end
return msg
end
local function run(msg, matches)
local receiver = msg.chat_id_
local hash = 'usecommands:'..msg.sender_user_id_..':'..msg.chat_id_
redis:incr(hash)
if not is_owner(msg) then
return '*You Not Owner*'
end
if matches[1] == 'on' then
return enable_channel(receiver)
end
if matches[1] == 'off' then
return disable_channel(receiver)
end
end
return {
description = "Plugin to manage channels. Enable or disable channel.",
usage = {
"/channel enable: enable current channel",
"/channel disable: disable current channel" },
patterns = {
"^[!/][Bb]ot (on)",
"^[!/][Bb]ot (off)" },
run = run,
moderated = true,
pre_process = pre_process
}
--End By @Tele_Sudo
-- Channel @LuaError | gpl-3.0 |
MrPolicy/HodTG | plugins/Me.lua | 1 | 2711 | do
local function get_msgs_user_chat(user_id, chat_id)
local user_info = {}
local uhash = 'user:'..user_id
local user = redis:hgetall(uhash)
local um_hash = 'msgs:'..user_id..':'..chat_id
user_info.msgs = tonumber(redis:get(um_hash) or 0)
user_info.name = user_print_name(user)..' ['..user_id..']'
return user_info
end
local function chat_stat(chat_id, typee)
-- Users on chat
local hash = ''
if typee == 'channel' then
hash = 'channel:'..chat_id..':users'
else
hash = 'chat:'..chat_id..':users'
end
local users = redis:smembers(hash)
local users_info = {}
-- Get user info
for i = 1, #users do
local user_id = users[i]
local user_info = get_msgs_user_chat(user_id, chat_id)
table.insert(users_info, user_info)
end
-- Sort users by msgs number
table.sort(users_info, function(a, b)
if a.msgs and b.msgs then
return a.msgs > b.msgs
end
end)
local arian = '0'
local text = 'users in this chat \n'
for k,user in pairs(users_info) do
--text = text..user.name..' = '..user.msgs..'\n'
arian = arian + user.msgs
end
return arian
end
local function rsusername_cb(extra, success, result)
if success == 1 then
local user = result.peer_id
local name = string.gsub(result.print_name, "_", " ")
local chatid = get_receiver(extra.msg)
local username = result.username
function round2(num, idp)
return tonumber(string.format("%." .. (idp or 0) .. "f", num))
end
local r = tonumber(chat_stat(extra.msg.to.id, extra.msg.to.type) or 0)
local hashs = 'msgs:'..result.peer_id..':'..extra.msg.to.id
local msgss = redis:get(hashs)
local percent = msgss / r * 100
local text = "Your name : "..name .." \n number of messages sent by you : "..msgss .." ("..round2 (percent).."%) \n all messages posted in the group : "..r .. ""
local text = "Your name : "..name .." \n number of messages sent by you : "..msgss .." ("..round2 (percent).."%) \n all messages posted in the group : "..r .. ""
text = string.gsub(text, '0', '۰')
text = string.gsub(text, '1', '۱')
text = string.gsub(text, '2', '۲')
text = string.gsub(text, '3', '۳')
text = string.gsub(text, '4', '۴')
text = string.gsub(text, '5', '۵')
text = string.gsub(text, '6', '۶')
text = string.gsub(text, '7', '۷')
text = string.gsub(text, '8', '۸')
text = string.gsub(text, '9', '۹')
return send_large_msg(chatid,text )
end
end
local function run(msg, matches)
local chat_id = msg.to.id
--return chat_stat(chat_id)
resolve_username(msg.from.username, rsusername_cb, {msg=msg})
end
return {
patterns = {
"^[!/](me)$",
},
run = run
}
end
| gpl-2.0 |
Sasu98/Nerd-Gaming-Public | resources/[no_ng_tag]/admin/client/gui/admin_screenshot.lua | 7 | 6732 | --[[**********************************
*
* Multi Theft Auto - Admin Panel
*
* gui\admin_screenshot.lua
*
* Original File by MCvarial
*
**************************************]]
aScreenShotWindows = {}
aScreenShotForm = nil
function aPlayerScreenShot (player)
if aScreenShotForm == nil then
local x,y = guiGetScreenSize()
aScreenShotForm = guiCreateWindow ( x / 2 - 300, y / 2 - 125, 600, 250, "Screenshot Management", false )
aScreenShotList = guiCreateGridList ( 0.03, 0.08, 0.70, 0.90, true, aScreenShotForm )
aScreenShotNew = guiCreateButton ( 0.75, 0.08, 0.42, 0.09, "Take New", true, aScreenShotForm )
aScreenShotDelete = guiCreateButton ( 0.75, 0.18, 0.42, 0.09, "Delete", true, aScreenShotForm )
aScreenShotView = guiCreateButton ( 0.75, 0.28, 0.42, 0.09, "View", true, aScreenShotForm )
aScreenShotRefresh = guiCreateButton ( 0.75, 0.38, 0.42, 0.09, "Refresh", true, aScreenShotForm )
aScreenShotClose = guiCreateButton ( 0.75, 0.88, 0.42, 0.09, "Close", true, aScreenShotForm )
guiGridListAddColumn(aScreenShotList,"Player",0.31 )
guiGridListAddColumn(aScreenShotList,"Admin",0.31 )
guiGridListAddColumn(aScreenShotList,"Date",0.27 )
addEventHandler("onClientGUIClick",aScreenShotForm,aScreenShotsClick)
addEventHandler("onClientGUIDoubleClick",aScreenShotForm,aScreenShotsDoubleClick)
aRegister("PlayerScreenShot",aScreenShotForm,aPlayerScreenShot,aPlayerScreenShotClose)
end
guiSetVisible(aScreenShotForm,true)
guiBringToFront(aScreenShotForm)
aScreenShotsRefresh()
end
function aScreenShotsRefresh ()
if aScreenShotList then
guiGridListClear(aScreenShotList)
triggerServerEvent("aScreenShot",resourceRoot,"list",localPlayer)
end
end
function aPlayerScreenShotClose ()
if ( aScreenShotForm ) then
removeEventHandler ( "onClientGUIClick", aScreenShotForm, aScreenShotsClick )
removeEventHandler ( "onClientGUIDoubleClick", aScreenShotForm, aScreenShotsDoubleClick )
destroyElement ( aScreenShotForm )
aScreenShotForm,aScreenShotList,aScreenShotNew,aScreenShotDelete,aScreenShotView,aScreenShotRefresh,aScreenShotClose,aScreenShotForm = nil,nil,nil,nil,nil,nil,nil,nil
end
end
function aScreenShotsDoubleClick (button)
if button == "left" then
if source == aScreenShotList then
local row = guiGridListGetSelectedItem(aScreenShotList)
if row ~= -1 then
triggerServerEvent("aScreenShot",resourceRoot,"view",localPlayer,guiGridListGetItemData(aScreenShotList,row,1),guiGridListGetItemText(aScreenShotList,row,1))
end
end
end
end
function aScreenShotsClick (button)
if button == "left" then
if source == aScreenShotClose then
aPlayerScreenShotClose()
elseif source == aScreenShotNew then
if guiGridListGetSelectedItem(aTab1.PlayerList ) == -1 then
aMessageBox("error","No player selected!")
else
local name = guiGridListGetItemPlayerName(aTab1.PlayerList,guiGridListGetSelectedItem(aTab1.PlayerList),1)
triggerServerEvent("aScreenShot",resourceRoot,"new",localPlayer,getPlayerFromNick(name))
end
elseif source == aScreenShotDelete then
local row = guiGridListGetSelectedItem ( aScreenShotList )
if row ~= -1 then
triggerServerEvent("aScreenShot",resourceRoot,"delete",localPlayer,guiGridListGetItemData(aScreenShotList,row,1))
guiGridListRemoveRow(aScreenShotList,row)
end
elseif source == aScreenShotRefresh then
aScreenShotsRefresh()
elseif source == aScreenShotView then
local row = guiGridListGetSelectedItem(aScreenShotList)
if row ~= -1 then
triggerServerEvent("aScreenShot",resourceRoot,"view",localPlayer,guiGridListGetItemData(aScreenShotList,row,1),guiGridListGetItemText(aScreenShotList,row,1))
end
else
for player,gui in pairs (aScreenShotWindows) do
if gui.button == source or source == gui.screenshot then
destroyElement(gui.window)
aScreenShotWindows[player] = nil
end
end
end
end
end
addEvent("aClientScreenShot",true)
addEventHandler("aClientScreenShot",resourceRoot,
function (action,player,data,arg1,arg2,arg3)
if action == "new" then
local title
if type(player) == "string" then
title = player
elseif isElement(player) then
title = getPlayerName(player)
else
return
end
local x, y = guiGetScreenSize()
aScreenShotWindows[player] = {}
aScreenShotWindows[player].window = guiCreateWindow((x/2)-400,(y/2)-300,800,600,title,false)
aScreenShotWindows[player].label = guiCreateLabel(0,0,1,1,"Loading...",true,aScreenShotWindows[player].window)
aScreenShotWindows[player].button = guiCreateButton(0.93,0.95,0.6,0.4,"Close",true,aScreenShotWindows[player].window)
addEventHandler ( "onClientGUIClick", aScreenShotWindows[player].button, aScreenShotsClick )
guiLabelSetHorizontalAlign(aScreenShotWindows[player].label,"center")
guiLabelSetVerticalAlign(aScreenShotWindows[player].label,"center")
elseif action == "list" then
if not isElement(aScreenShotList) then return end
guiGridListClear ( aScreenShotList )
for i,screenshot in ipairs (data) do
local row = guiGridListAddRow(aScreenShotList)
guiGridListSetItemText(aScreenShotList,row,1,screenshot.player,false,false)
guiGridListSetItemText(aScreenShotList,row,2,screenshot.admin,false,false)
guiGridListSetItemText(aScreenShotList,row,3,screenshot.realtime,false,false)
guiGridListSetItemData(aScreenShotList,row,1,screenshot.id)
end
else
if not aScreenShotWindows[player] or not isElement(aScreenShotWindows[player].window) then return end
if action == "view" then
local time = tostring(getRealTime().timestamp)
local file = fileCreate("screenshots/"..time..".jpg")
fileWrite(file,data)
fileClose(file)
aScreenShotWindows[player].screenshot = guiCreateStaticImage(0,0,1,1,"screenshots/"..time..".jpg",true,aScreenShotWindows[player].window)
addEventHandler ( "onClientGUIClick", aScreenShotWindows[player].screenshot, aScreenShotsClick )
guiBringToFront(aScreenShotWindows[player].button)
if isElement(player) and isElement(aScreenShotList) then
local row = guiGridListAddRow(aScreenShotList)
guiGridListSetItemText(aScreenShotList,row,1,getPlayerName(player),false,false)
guiGridListSetItemText(aScreenShotList,row,2,arg1,false,false)
guiGridListSetItemText(aScreenShotList,row,3,arg2,false,false)
guiGridListSetItemData(aScreenShotList,row,1,arg3)
end
elseif action == "minimized" then
guiSetText(aScreenShotWindows[player].label,"Player is minimized, try again later")
elseif action == "disabled" then
guiSetText(aScreenShotWindows[player].label,"Player does not allow taking screenshots")
elseif action == "quit" then
guiSetText(aScreenShotWindows[player].label,"Player has quit")
end
end
end
) | mit |
LORgames/premake-core | modules/gmake/tests/cs/test_links.lua | 15 | 1041 | --
-- tests/actions/make/cs/test_links.lua
-- Tests linking for C# Makefiles.
-- Copyright (c) 2013 Jason Perkins and the Premake project
--
local p = premake
local suite = test.declare("make_cs_links")
local make = p.make
local cs = p.make.cs
local project = p.project
--
-- Setup
--
local wks, prj
function suite.setup()
wks, prj = test.createWorkspace()
end
local function prepare()
local cfg = test.getconfig(prj, "Debug")
make.csLinkCmd(cfg, p.tools.dotnet)
end
--
-- Should return an empty assignment if nothing has been specified.
--
function suite.isEmptyAssignment_onNoSettings()
prepare()
test.capture [[
DEPENDS =
]]
end
--
-- Files that can be compiled should be listed here.
--
function suite.doesListLinkDependencyFiles()
links { "MyProject2", "MyProject3" }
test.createproject(wks)
kind "SharedLib"
language "C#"
test.createproject(wks)
kind "SharedLib"
language "C#"
prepare ()
test.capture [[
DEPENDS = bin/Debug/MyProject2.dll bin/Debug/MyProject3.dll
]]
end
| bsd-3-clause |
mnemnion/grym | lib/pl/func.lua | 3 | 10405 | --- Functional helpers like composition, binding and placeholder expressions.
-- Placeholder expressions are useful for short anonymous functions, and were
-- inspired by the Boost Lambda library.
--
-- > utils.import 'pl.func'
-- > ls = List{10,20,30}
-- > = ls:map(_1+1)
-- {11,21,31}
--
-- They can also be used to _bind_ particular arguments of a function.
--
-- > p = bind(print,'start>',_0)
-- > p(10,20,30)
-- > start> 10 20 30
--
-- See @{07-functional.md.Creating_Functions_from_Functions|the Guide}
--
-- Dependencies: `pl.utils`, `pl.tablex`
-- @module pl.func
local type,setmetatable,getmetatable,rawset = type,setmetatable,getmetatable,rawset
local concat,append = table.concat,table.insert
local tostring = tostring
local utils = require 'pl.utils'
local pairs,rawget,unpack = pairs,rawget,utils.unpack
local tablex = require 'pl.tablex'
local map = tablex.map
local _DEBUG = rawget(_G,'_DEBUG')
local assert_arg = utils.assert_arg
local func = {}
-- metatable for Placeholder Expressions (PE)
local _PEMT = {}
local function P (t)
setmetatable(t,_PEMT)
return t
end
func.PE = P
local function isPE (obj)
return getmetatable(obj) == _PEMT
end
func.isPE = isPE
-- construct a placeholder variable (e.g _1 and _2)
local function PH (idx)
return P {op='X',repr='_'..idx, index=idx}
end
-- construct a constant placeholder variable (e.g _C1 and _C2)
local function CPH (idx)
return P {op='X',repr='_C'..idx, index=idx}
end
func._1,func._2,func._3,func._4,func._5 = PH(1),PH(2),PH(3),PH(4),PH(5)
func._0 = P{op='X',repr='...',index=0}
function func.Var (name)
local ls = utils.split(name,'[%s,]+')
local res = {}
for i = 1, #ls do
append(res,P{op='X',repr=ls[i],index=0})
end
return unpack(res)
end
function func._ (value)
return P{op='X',repr=value,index='wrap'}
end
local repr
func.Nil = func.Var 'nil'
function _PEMT.__index(obj,key)
return P{op='[]',obj,key}
end
function _PEMT.__call(fun,...)
return P{op='()',fun,...}
end
function _PEMT.__tostring (e)
return repr(e)
end
function _PEMT.__unm(arg)
return P{op='-',arg}
end
function func.Not (arg)
return P{op='not',arg}
end
function func.Len (arg)
return P{op='#',arg}
end
local function binreg(context,t)
for name,op in pairs(t) do
rawset(context,name,function(x,y)
return P{op=op,x,y}
end)
end
end
local function import_name (name,fun,context)
rawset(context,name,function(...)
return P{op='()',fun,...}
end)
end
local imported_functions = {}
local function is_global_table (n)
return type(_G[n]) == 'table'
end
--- wrap a table of functions. This makes them available for use in
-- placeholder expressions.
-- @string tname a table name
-- @tab context context to put results, defaults to environment of caller
function func.import(tname,context)
assert_arg(1,tname,'string',is_global_table,'arg# 1: not a name of a global table')
local t = _G[tname]
context = context or _G
for name,fun in pairs(t) do
import_name(name,fun,context)
imported_functions[fun] = name
end
end
--- register a function for use in placeholder expressions.
-- @func fun a function
-- @string[opt] name an optional name
-- @return a placeholder functiond
function func.register (fun,name)
assert_arg(1,fun,'function')
if name then
assert_arg(2,name,'string')
imported_functions[fun] = name
end
return function(...)
return P{op='()',fun,...}
end
end
function func.lookup_imported_name (fun)
return imported_functions[fun]
end
local function _arg(...) return ... end
function func.Args (...)
return P{op='()',_arg,...}
end
-- binary and unary operators, with their precedences (see 2.5.6)
local operators = {
['or'] = 0,
['and'] = 1,
['=='] = 2, ['~='] = 2, ['<'] = 2, ['>'] = 2, ['<='] = 2, ['>='] = 2,
['..'] = 3,
['+'] = 4, ['-'] = 4,
['*'] = 5, ['/'] = 5, ['%'] = 5,
['not'] = 6, ['#'] = 6, ['-'] = 6,
['^'] = 7
}
-- comparisons (as prefix functions)
binreg (func,{And='and',Or='or',Eq='==',Lt='<',Gt='>',Le='<=',Ge='>='})
-- standard binary operators (as metamethods)
binreg (_PEMT,{__add='+',__sub='-',__mul='*',__div='/',__mod='%',__pow='^',__concat='..'})
binreg (_PEMT,{__eq='=='})
--- all elements of a table except the first.
-- @tab ls a list-like table.
function func.tail (ls)
assert_arg(1,ls,'table')
local res = {}
for i = 2,#ls do
append(res,ls[i])
end
return res
end
--- create a string representation of a placeholder expression.
-- @param e a placeholder expression
-- @param lastpred not used
function repr (e,lastpred)
local tail = func.tail
if isPE(e) then
local pred = operators[e.op]
local ls = map(repr,e,pred)
if pred then --unary or binary operator
if #ls ~= 1 then
local s = concat(ls,' '..e.op..' ')
if lastpred and lastpred > pred then
s = '('..s..')'
end
return s
else
return e.op..' '..ls[1]
end
else -- either postfix, or a placeholder
if e.op == '[]' then
return ls[1]..'['..ls[2]..']'
elseif e.op == '()' then
local fn
if ls[1] ~= nil then -- was _args, undeclared!
fn = ls[1]
else
fn = ''
end
return fn..'('..concat(tail(ls),',')..')'
else
return e.repr
end
end
elseif type(e) == 'string' then
return '"'..e..'"'
elseif type(e) == 'function' then
local name = func.lookup_imported_name(e)
if name then return name else return tostring(e) end
else
return tostring(e) --should not really get here!
end
end
func.repr = repr
-- collect all the non-PE values in this PE into vlist, and replace each occurence
-- with a constant PH (_C1, etc). Return the maximum placeholder index found.
local collect_values
function collect_values (e,vlist)
if isPE(e) then
if e.op ~= 'X' then
local m = 0
for i = 1,#e do
local subx = e[i]
local pe = isPE(subx)
if pe then
if subx.op == 'X' and subx.index == 'wrap' then
subx = subx.repr
pe = false
else
m = math.max(m,collect_values(subx,vlist))
end
end
if not pe then
append(vlist,subx)
e[i] = CPH(#vlist)
end
end
return m
else -- was a placeholder, it has an index...
return e.index
end
else -- plain value has no placeholder dependence
return 0
end
end
func.collect_values = collect_values
--- instantiate a PE into an actual function. First we find the largest placeholder used,
-- e.g. _2; from this a list of the formal parameters can be build. Then we collect and replace
-- any non-PE values from the PE, and build up a constant binding list.
-- Finally, the expression can be compiled, and e.__PE_function is set.
-- @param e a placeholder expression
-- @return a function
function func.instantiate (e)
local consts,values,parms = {},{},{}
local rep, err, fun
local n = func.collect_values(e,values)
for i = 1,#values do
append(consts,'_C'..i)
if _DEBUG then print(i,values[i]) end
end
for i =1,n do
append(parms,'_'..i)
end
consts = concat(consts,',')
parms = concat(parms,',')
rep = repr(e)
local fstr = ('return function(%s) return function(%s) return %s end end'):format(consts,parms,rep)
if _DEBUG then print(fstr) end
fun,err = utils.load(fstr,'fun')
if not fun then return nil,err end
fun = fun() -- get wrapper
fun = fun(unpack(values)) -- call wrapper (values could be empty)
e.__PE_function = fun
return fun
end
--- instantiate a PE unless it has already been done.
-- @param e a placeholder expression
-- @return the function
function func.I(e)
if rawget(e,'__PE_function') then
return e.__PE_function
else return func.instantiate(e)
end
end
utils.add_function_factory(_PEMT,func.I)
--- bind the first parameter of the function to a value.
-- @function func.bind1
-- @func fn a function of one or more arguments
-- @param p a value
-- @return a function of one less argument
-- @usage (bind1(math.max,10))(20) == math.max(10,20)
func.bind1 = utils.bind1
func.curry = func.bind1
--- create a function which chains two functions.
-- @func f a function of at least one argument
-- @func g a function of at least one argument
-- @return a function
-- @usage printf = compose(io.write,string.format)
function func.compose (f,g)
return function(...) return f(g(...)) end
end
--- bind the arguments of a function to given values.
-- `bind(fn,v,_2)` is equivalent to `bind1(fn,v)`.
-- @func fn a function of at least one argument
-- @param ... values or placeholder variables
-- @return a function
-- @usage (bind(f,_1,a))(b) == f(a,b)
-- @usage (bind(f,_2,_1))(a,b) == f(b,a)
function func.bind(fn,...)
local args = table.pack(...)
local holders,parms,bvalues,values = {},{},{'fn'},{}
local nv,maxplace,varargs = 1,0,false
for i = 1,args.n do
local a = args[i]
if isPE(a) and a.op == 'X' then
append(holders,a.repr)
maxplace = math.max(maxplace,a.index)
if a.index == 0 then varargs = true end
else
local v = '_v'..nv
append(bvalues,v)
append(holders,v)
append(values,a)
nv = nv + 1
end
end
for np = 1,maxplace do
append(parms,'_'..np)
end
if varargs then append(parms,'...') end
bvalues = concat(bvalues,',')
parms = concat(parms,',')
holders = concat(holders,',')
local fstr = ([[
return function (%s)
return function(%s) return fn(%s) end
end
]]):format(bvalues,parms,holders)
if _DEBUG then print(fstr) end
local res,err = utils.load(fstr)
res = res()
return res(fn,unpack(values))
end
return func
| mit |
moteus/lua-log | lua/log/writer/net/zmq/_private/impl.lua | 4 | 1497 | local Log = require "log"
local Z = require "log.writer.net.zmq._private.compat"
local zmq, zthreads = Z.zmq, Z.threads
local zstrerror, zassert = Z.strerror, Z.assert
local ETERM = Z.ETERM
local zconnect, zbind = Z.connect, Z.bind
local log_ctx
local function context(ctx)
-- we have to use same context for all writers
if ctx and log_ctx then assert(ctx == log_ctx) end
if log_ctx then return log_ctx end
log_ctx = ctx or (zthreads and zthreads.get_parent_ctx()) or zassert(zmq.init(1))
return log_ctx
end
local function socket(ctx, stype, is_srv, addr, timeout)
local stypes = {
PUSH = zmq.PUSH;
PUB = zmq.PUB;
}
stype = assert(stypes[stype], 'Unsupported socket type')
timeout = timeout or 100
ctx = context(ctx)
local skt = ctx:socket(stype)
if ctx.autoclose then ctx:autoclose(skt) end
skt:set_sndtimeo(timeout)
skt:set_linger(timeout)
if is_srv then zassert(zbind(skt, addr))
else zassert(zconnect(skt, addr)) end
if not ctx.autoclose then
Log.add_cleanup(function() skt:close() end)
end
return skt
end
local function init(stype, is_srv)
local M = {}
function M.new(ctx, addr, timeout)
if ctx and not Z.is_ctx(ctx) then
ctx, addr, timeout = nil, ctx, addr
end
local skt = socket(ctx, stype, is_srv, addr, timeout)
return function(fmt, ...) skt:send((fmt(...))) end
end
return M
end
return {
init = init;
context = context;
} | mit |
Anarchid/Zero-K | LuaRules/Gadgets/unit_marketplace.lua | 6 | 3919 | --------------------------------------------------------------------------------
--------------------------------------------------------------------------------
if not gadgetHandler:IsSyncedCode() then
return
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
function gadget:GetInfo()
return {
name = "MarketPlace",
desc = "Buy and Sell your units.",
author = "CarRepairer",
date = "2010-07-22",
license = "GNU GPL, v2 or later",
layer = 1,
enabled = false,
}
end
local TESTMODE = false
local echo = Spring.Echo
local spGetPlayerInfo = Spring.GetPlayerInfo
local spGetTeamInfo = Spring.GetTeamInfo
local market = {}
if not GG.shareunits then
GG.shareunits = {}
end
local function CheckOffer(data)
local saleprice = data.sell
local buyers = data.buy
if buyers and saleprice then
for teamID, buyprice in pairs(buyers) do
if saleprice+0 <= buyprice+0 then
return teamID, saleprice
end
end
end
return false, false
end
local function CheckOffers()
for unitID, data in pairs(market) do
local customer, saleprice = CheckOffer(data)
if customer then
local teamID = market[unitID].team
market[unitID] = nil
GG.AddDebt(customer, teamID, saleprice)
GG.shareunits[unitID] = true
GG.allowTransfer = true
Spring.TransferUnit(unitID, customer, true)
GG.allowTransfer = false
Spring.SetUnitRulesParam( unitID, 'buy'..teamID, 0, {allied=true} )
Spring.SetUnitRulesParam( unitID, 'sell'..teamID, 0, {allied=true} )
end
end
end
-------------------------------------------------------------------------------------
--Callins
function gadget:RecvLuaMsg(msg, playerID)
local msgTable = Spring.Utilities.ExplodeString( '|', msg )
local command = msgTable[1]
local sell = command == '$sell'
local buy = command == '$buy'
if buy or sell then
local _,_,spec,teamID, allianceID = spGetPlayerInfo(playerID, false)
if spec then
return
end
if( #msgTable ~= 3 ) then
Spring.Log(gadget:GetInfo().name, LOG.WARNING, '<MarketPlace> (A) Player ' .. playerID .. ' on team ' .. teamID .. ' tried to send a nonsensical command.')
return false
end
local unitID = msgTable[2]+0
local price = msgTable[3]+0
if( type(unitID) ~= 'number' or type(price) ~= 'number' ) then
Spring.Log(gadget:GetInfo().name, LOG.WARNING, '<MarketPlace> (B) Player ' .. playerID .. ' on team ' .. teamID .. ' tried to send a nonsensical command.')
return false
end
local unitTeamID = Spring.GetUnitTeam(unitID)
if not market[unitID] then
market[unitID] = {}
end
market[unitID].team = unitTeamID
if sell then
if unitTeamID ~= teamID then
echo ('<MarketPlace> You cannot sell a unit that\'s not yours, Player ' .. playerID .. ' on team ' .. teamID)
return
else
--echo 'put for sale'
market[unitID].sell = price > 0 and price or nil
Spring.SetUnitRulesParam( unitID, 'sell'..teamID, price, {allied=true} )
end
elseif buy then
if not market[unitID].buy then
market[unitID].buy = {}
end
market[unitID].buy[teamID] = price > 0 and price or nil
echo( unitID, 'buy'..teamID, price )
Spring.SetUnitRulesParam( unitID, 'buy'..teamID, price, {allied=true} )
end
end
end
function gadget:GameFrame(f)
if (f%32) < 0.1 then
CheckOffers()
end
end
function gadget:Initialize()
if TESTMODE then
local allUnits = Spring.GetAllUnits()
for _,unitID in ipairs(allUnits) do
local teamID = Spring.GetUnitTeam(unitID)
market[unitID] = {}
market[unitID].sell = 500
market[unitID].team = teamID
Spring.SetUnitRulesParam( unitID, 'sell'..teamID, 500, {allied=true} )
end
end
end
--[[
function gadget:UnitCreated(unitID, unitDefID)
end
function gadget:UnitDestroyed(unitID, unitDefID, unitTeam)
end
--]]
| gpl-2.0 |
Bew78LesellB/awesome | lib/wibox/widget/progressbar.lua | 7 | 13615 | ---------------------------------------------------------------------------
--- A progressbar widget.
--
-- To add text on top of the progressbar, a `wibox.layout.stack` can be used:
--
--@DOC_wibox_widget_progressbar_text_EXAMPLE@
--
-- To display the progressbar vertically, use a `wibox.container.rotate` widget:
--
--@DOC_wibox_widget_progressbar_vertical_EXAMPLE@
--
-- By default, this widget will take all the available size. To prevent this,
-- a `wibox.container.constraint` widget or the `forced_width`/`forced_height`
-- properties have to be used.
--
--@DOC_wibox_widget_defaults_progressbar_EXAMPLE@
--
-- @author Julien Danjou <julien@danjou.info>
-- @copyright 2009 Julien Danjou
-- @classmod wibox.widget.progressbar
---------------------------------------------------------------------------
local setmetatable = setmetatable
local ipairs = ipairs
local math = math
local gdebug = require("gears.debug")
local base = require("wibox.widget.base")
local color = require("gears.color")
local beautiful = require("beautiful")
local shape = require("gears.shape")
local gtable = require("gears.table")
local progressbar = { mt = {} }
--- The progressbar border color.
-- If the value is nil, no border will be drawn.
--
-- @property border_color
-- @tparam gears.color color The border color to set.
-- @see gears.color
--- The progressbar border width.
-- @property border_width
--- The progressbar inner border color.
-- If the value is nil, no border will be drawn.
--
-- @property bar_border_color
-- @tparam gears.color color The border color to set.
-- @see gears.color
--- The progressbar inner border width.
-- @property bar_border_width
--- The progressbar foreground color.
--
-- @property color
-- @tparam gears.color color The progressbar color.
-- @see gears.color
--- The progressbar background color.
--
-- @property background_color
-- @tparam gears.color color The progressbar background color.
-- @see gears.color
--- The progressbar inner shape.
--
--@DOC_wibox_widget_progressbar_bar_shape_EXAMPLE@
--
-- @property bar_shape
-- @tparam[opt=gears.shape.rectangle] gears.shape shape
-- @see gears.shape
--- The progressbar shape.
--
--@DOC_wibox_widget_progressbar_shape_EXAMPLE@
--
-- @property shape
-- @tparam[opt=gears.shape.rectangle] gears.shape shape
-- @see gears.shape
--- Set the progressbar to draw vertically.
-- This doesn't do anything anymore, use a `wibox.container.rotate` widget.
-- @deprecated set_vertical
-- @tparam boolean vertical
--- Force the inner part (the bar) to fit in the background shape.
--
--@DOC_wibox_widget_progressbar_clip_EXAMPLE@
--
-- @property clip
-- @tparam[opt=true] boolean clip
--- The progressbar to draw ticks. Default is false.
--
-- @property ticks
-- @param boolean
--- The progressbar ticks gap.
--
-- @property ticks_gap
-- @param number
--- The progressbar ticks size.
--
-- @property ticks_size
-- @param number
--- The maximum value the progressbar should handle.
--
-- @property max_value
-- @param number
--- The progressbar background color.
-- @beautiful beautiful.progressbar_bg
--- The progressbar foreground color.
-- @beautiful beautiful.progressbar_fg
--- The progressbar shape.
-- @beautiful beautiful.progressbar_shape
-- @see gears.shape
--- The progressbar border color.
-- @beautiful beautiful.progressbar_border_color
--- The progressbar outer border width.
-- @beautiful beautiful.progressbar_border_width
--- The progressbar inner shape.
-- @beautiful beautiful.progressbar_bar_shape
-- @see gears.shape
--- The progressbar bar border width.
-- @beautiful beautiful.progressbar_bar_border_width
--- The progressbar bar border color.
-- @beautiful beautiful.progressbar_bar_border_color
--- The progressbar margins.
-- Note that if the `clip` is disabled, this allows the background to be smaller
-- than the bar.
--
-- See the `clip` example.
--
-- @tparam[opt=0] (table|number|nil) margins A table for each side or a number
-- @tparam[opt=0] number margins.top
-- @tparam[opt=0] number margins.bottom
-- @tparam[opt=0] number margins.left
-- @tparam[opt=0] number margins.right
-- @property margins
-- @see clip
--- The progressbar padding.
-- Note that if the `clip` is disabled, this allows the bar to be taller
-- than the background.
--
-- See the `clip` example.
--
-- @tparam[opt=0] (table|number|nil) padding A table for each side or a number
-- @tparam[opt=0] number padding.top
-- @tparam[opt=0] number padding.bottom
-- @tparam[opt=0] number padding.left
-- @tparam[opt=0] number padding.right
-- @property paddings
-- @see clip
--- The progressbar margins.
-- Note that if the `clip` is disabled, this allows the background to be smaller
-- than the bar.
-- @tparam[opt=0] (table|number|nil) margins A table for each side or a number
-- @tparam[opt=0] number margins.top
-- @tparam[opt=0] number margins.bottom
-- @tparam[opt=0] number margins.left
-- @tparam[opt=0] number margins.right
-- @beautiful beautiful.progressbar_margins
-- @see clip
--- The progressbar padding.
-- Note that if the `clip` is disabled, this allows the bar to be taller
-- than the background.
-- @tparam[opt=0] (table|number|nil) padding A table for each side or a number
-- @tparam[opt=0] number padding.top
-- @tparam[opt=0] number padding.bottom
-- @tparam[opt=0] number padding.left
-- @tparam[opt=0] number padding.right
-- @beautiful beautiful.progressbar_paddings
-- @see clip
local properties = { "border_color", "color" , "background_color",
"value" , "max_value" , "ticks",
"ticks_gap" , "ticks_size", "border_width",
"shape" , "bar_shape" , "bar_border_width",
"clip" , "margins" , "bar_border_color",
"paddings",
}
function progressbar.draw(pbar, _, cr, width, height)
local ticks_gap = pbar._private.ticks_gap or 1
local ticks_size = pbar._private.ticks_size or 4
-- We want one pixel wide lines
cr:set_line_width(1)
local max_value = pbar._private.max_value
local value = math.min(max_value, math.max(0, pbar._private.value))
if value >= 0 then
value = value / max_value
end
local border_width = pbar._private.border_width
or beautiful.progressbar_border_width or 0
local bcol = pbar._private.border_color or beautiful.progressbar_border_color
border_width = bcol and border_width or 0
local bg = pbar._private.background_color or
beautiful.progressbar_bg or "#ff0000aa"
local bg_width, bg_height = width, height
local clip = pbar._private.clip ~= false and beautiful.progressbar_clip ~= false
-- Apply the margins
local margin = pbar._private.margins or beautiful.progressbar_margins
if margin then
if type(margin) == "number" then
cr:translate(margin, margin)
bg_width, bg_height = bg_width - 2*margin, bg_height - 2*margin
else
cr:translate(margin.left or 0, margin.top or 0)
bg_height = bg_height -
(margin.top or 0) - (margin.bottom or 0)
bg_width = bg_width -
(margin.left or 0) - (margin.right or 0)
end
end
-- Draw the background shape
if border_width > 0 then
-- Cairo draw half of the border outside of the path area
cr:translate(border_width/2, border_width/2)
bg_width, bg_height = bg_width - border_width, bg_height - border_width
cr:set_line_width(border_width)
end
local background_shape = pbar._private.shape or
beautiful.progressbar_shape or shape.rectangle
background_shape(cr, bg_width, bg_height)
cr:set_source(color(bg))
local over_drawn_width = bg_width + border_width
local over_drawn_height = bg_height + border_width
if border_width > 0 then
cr:fill_preserve()
-- Draw the border
cr:set_source(color(bcol))
cr:stroke()
over_drawn_width = over_drawn_width - 2*border_width
over_drawn_height = over_drawn_height - 2*border_width
else
cr:fill()
end
-- Undo the translation
cr:translate(-border_width/2, -border_width/2)
-- Make sure the bar stay in the shape
if clip then
background_shape(cr, bg_width, bg_height)
cr:clip()
cr:translate(border_width, border_width)
else
-- Assume the background size is irrelevant to the bar itself
if type(margin) == "number" then
cr:translate(-margin, -margin)
else
cr:translate(-(margin.left or 0), -(margin.top or 0))
end
over_drawn_height = height
over_drawn_width = width
end
-- Apply the padding
local padding = pbar._private.paddings or beautiful.progressbar_paddings
if padding then
if type(padding) == "number" then
cr:translate(padding, padding)
over_drawn_height = over_drawn_height - 2*padding
over_drawn_width = over_drawn_width - 2*padding
else
cr:translate(padding.left or 0, padding.top or 0)
over_drawn_height = over_drawn_height -
(padding.top or 0) - (padding.bottom or 0)
over_drawn_width = over_drawn_width -
(padding.left or 0) - (padding.right or 0)
end
end
over_drawn_width = math.max(over_drawn_width , 0)
over_drawn_height = math.max(over_drawn_height, 0)
local rel_x = over_drawn_width * value
-- Draw the progressbar shape
local bar_shape = pbar._private.bar_shape or
beautiful.progressbar_bar_shape or shape.rectangle
local bar_border_width = pbar._private.bar_border_width or
beautiful.progressbar_bar_border_width or pbar._private.border_width or
beautiful.progressbar_border_width or 0
local bar_border_color = pbar._private.bar_border_color or
beautiful.progressbar_bar_border_color
bar_border_width = bar_border_color and bar_border_width or 0
over_drawn_width = over_drawn_width - bar_border_width
over_drawn_height = over_drawn_height - bar_border_width
cr:translate(bar_border_width/2, bar_border_width/2)
bar_shape(cr, rel_x, over_drawn_height)
cr:set_source(color(pbar._private.color or beautiful.progressbar_fg or "#ff0000"))
if bar_border_width > 0 then
cr:fill_preserve()
cr:set_source(color(bar_border_color))
cr:set_line_width(bar_border_width)
cr:stroke()
else
cr:fill()
end
if pbar._private.ticks then
for i=0, width / (ticks_size+ticks_gap)-border_width do
local rel_offset = over_drawn_width / 1 - (ticks_size+ticks_gap) * i
if rel_offset <= rel_x then
cr:rectangle(rel_offset,
border_width,
ticks_gap,
over_drawn_height)
end
end
cr:set_source(color(pbar._private.background_color or "#000000aa"))
cr:fill()
end
end
function progressbar:fit(_, width, height)
return width, height
end
--- Set the progressbar value.
-- @param value The progress bar value between 0 and 1.
function progressbar:set_value(value)
value = value or 0
self._private.value = value
self:emit_signal("widget::redraw_needed")
return self
end
function progressbar:set_max_value(max_value)
self._private.max_value = max_value
self:emit_signal("widget::redraw_needed")
end
--- Set the progressbar height.
-- This method is deprecated. Use a `wibox.container.constraint` widget or
-- `forced_height`.
-- @param height The height to set.
-- @deprecated set_height
function progressbar:set_height(height)
gdebug.deprecate("Use a `wibox.container.constraint` widget or `forced_height`", {deprecated_in=4})
self:set_forced_height(height)
end
--- Set the progressbar width.
-- This method is deprecated. Use a `wibox.container.constraint` widget or
-- `forced_width`.
-- @param width The width to set.
-- @deprecated set_width
function progressbar:set_width(width)
gdebug.deprecate("Use a `wibox.container.constraint` widget or `forced_width`", {deprecated_in=4})
self:set_forced_width(width)
end
-- Build properties function
for _, prop in ipairs(properties) do
if not progressbar["set_" .. prop] then
progressbar["set_" .. prop] = function(pbar, value)
pbar._private[prop] = value
pbar:emit_signal("widget::redraw_needed")
return pbar
end
end
end
function progressbar:set_vertical(value) --luacheck: no unused_args
gdebug.deprecate("Use a `wibox.container.rotate` widget", {deprecated_in=4})
end
--- Create a progressbar widget.
-- @param args Standard widget() arguments. You should add width and height
-- key to set progressbar geometry.
-- @return A progressbar widget.
-- @function wibox.widget.progressbar
function progressbar.new(args)
args = args or {}
local pbar = base.make_widget(nil, nil, {
enable_properties = true,
})
pbar._private.width = args.width or 100
pbar._private.height = args.height or 20
pbar._private.value = 0
pbar._private.max_value = 1
gtable.crush(pbar, progressbar, true)
return pbar
end
function progressbar.mt:__call(...)
return progressbar.new(...)
end
--@DOC_widget_COMMON@
--@DOC_object_COMMON@
return setmetatable(progressbar, progressbar.mt)
-- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
| gpl-2.0 |
iamgreaser/iceball | pkg/base/lib_namegen.lua | 4 | 1536 | --[[
This file is part of Ice Lua Components.
Ice Lua Components is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Ice Lua Components 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 Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with Ice Lua Components. If not, see <http://www.gnu.org/licenses/>.
]]
-- yes, this is a great idea!
do
local n_base1 = {
"b","c","ch","cl","d","fl","h","j","l","m","n","r","sh","spl","th","thr","w","z",
}
local n_base2 = {
"alt","arp","at","each","erf","erp","iff","it","itt","ing","izz","og","ong","oog","oop","ooze","ug","urf",
}
local n_base3 = {
"ator","ate","er","es","ette","ing","it","iser","le","ler","man","ner","son","ter"
}
function name_generate()
local s1 = n_base1[math.floor(math.random()*#n_base1+1)]
local s2 = n_base2[math.floor(math.random()*#n_base2+1)]
local s3 = n_base3[math.floor(math.random()*#n_base3+1)]
if string.sub(s2,-1,-1) == "e" and string.sub(s3,1,1) == "e" then
s2 = string.sub(s2,1,-2)
end
local s = s1..s2..s3
return s
end
--[[local i
for i=1,100 do
print("name "..i..": "..name_generate())
end]]
end
| gpl-3.0 |
b1v1r/ironbee | lua/ironbee/waggle/generator.lua | 2 | 6682 | #!/usr/bin/lua
--[[--------------------------------------------------------------------------
-- Licensed to Qualys, Inc. (QUALYS) under one or more
-- contributor license agreements. See the NOTICE file distributed with
-- this work for additional information regarding copyright ownership.
-- QUALYS licenses this file to You 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.
--]]--------------------------------------------------------------------------
--
-- IronBee Waggle --- Generator
--
-- Generates rules.
--
-- @author Sam Baskinger <sbaskinger@qualys.com>
local Util = require('ironbee/waggle/util')
local Action = require('ironbee/waggle/actionrule')
local RuleExt = require('ironbee/waggle/ruleext')
local StreamInspect = require('ironbee/waggle/streaminspect')
-- ###########################################################################
-- Generator - generate a rules.conf or similar
-- ###########################################################################
local Generator = {}
Generator.__index = Generator
Generator.type = 'generator'
Generator.new = function(self)
local g = {}
return setmetatable(g, self)
end
Generator.gen_op = function(self, rule)
if rule.is_a(RuleExt) then
return rule.data.op
else
if string.sub(rule.data.op, 1, 1) == '!' then
return string.format("!@%s", string.sub(rule.data.op, 2))
else
return string.format("@%s", rule.data.op)
end
end
end
Generator.gen_fields = function(self, rule)
local field_list = {}
for _, field in ipairs(rule.data.fields) do
local f = field.collection
if field.selector then
f = f .. ':' .. field.selector
end
if field.transformation then
f = f .. '.' .. field.transformation
end
table.insert(field_list, f)
end
return '"' .. table.concat(field_list, '" "') .. '"'
end
-- Generate actions, including tags, etc.
--
-- This ignores the 'chain' action. That is inserted as-needed.
Generator.gen_actions = function(self, rule)
local t = {}
-- Add the tags.
for val,_ in pairs(rule.data.tags) do
table.insert(t, "tag:"..val)
end
-- Add the actions that are not id, rev, or phase.
-- They may only appear once.
for _, act in pairs(rule.data.actions) do
if act.name ~= 'id'
and act.name ~= 'rev'
and act.name ~= 'phase'
then
if act.argument then
table.insert(t, act.name .. ":"..act.argument)
else
table.insert(t, act.name)
end
end
end
-- Add the message if it exists.
if rule.data.message then
table.insert(t, "msg:"..rule.data.message)
end
if #t > 0 then
return '"' .. table.concat(t, '" "') .. '"'
else
return ''
end
end
-- Generate a string that represents an IronBee rules configuration.
--
-- @param[in] self The generator.
-- @param[in] plan The plan generated by Planner:new():plan(db) or equivalent.
-- @param[in] db The SignatureDatabase used to plan.
Generator.generate = function(self, plan, db)
-- String we are going to return representing the final configuration.
local s = ''
for _, chain in ipairs(plan) do
for i, link in ipairs(chain) do
local rule_id = link.rule
local result = link.result
local rule = db.db[rule_id]
if rule:is_a(Rule) then
if rule.data.comment then
s = s .. "# ".. string.gsub(rule.data.comment, "\n", "\n# ") .."\n"
end
s = s .. string.format(
"%s %s %s \"%s\" %s",
rule.data.rule_type,
self:gen_fields(rule),
self:gen_op(rule),
rule.data.op_arg,
self:gen_actions(rule))
-- The first rule in a chain gets the ID, message, phase, etc.
if i == 1 then
local last_rule = db.db[chain[#chain].rule]
s = s .. ' "id:' .. last_rule.data.id .. '"'
s = s .. ' "rev:' .. last_rule.data.version .. '"'
if last_rule.data.phase then
s = s .. ' "phase:' .. last_rule.data.phase .. '"'
end
end
if i ~= #chain then
s = s .. ' chain'
end
elseif rule:is_a(RuleExt) then
if rule.data.comment then
s = s .. "# ".. string.gsub(rule.data.comment, "\n", "\n# ") .."\n"
end
s = s .. string.format(
"%s %s %s \"%s\" %s \"id:%s\" \"rev:%s\"",
rule.data.rule_type,
self:gen_fields(rule),
self:gen_op(rule),
rule.data.op_arg,
self:gen_actions(rule),
rule.data.id,
rule.data.version)
elseif rule:is_a(Action) then
if rule.data.comment then
s = s .. "# ".. string.gsub(rule.data.comment, "\n", "\n# ") .."\n"
end
s = s .. string.format(
"%s %s \"id:%s\" \"rev:%s\"",
rule.data.rule_type,
self:gen_actions(rule),
rule.data.id,
rule.data.version)
elseif rule.is_a(StreamInspect) then
if rule.data.comment then
s = s .. "# ".. string.gsub(rule.data.comment, "\n", "\n# ") .."\n"
end
s = s .. string.format(
"%s %s %s \"%s\" %s \"id:%s\" \"rev:%s\"",
rule.data.rule_type,
self:gen_fields(rule),
self:gen_op(rule),
rule.data.op_arg,
self:gen_actions(rule),
rule.data.id,
rule.data.version)
end
s = s .. "\n"
end
end
return s
end
return Generator
| apache-2.0 |
Sasu98/Nerd-Gaming-Public | resources/[shaders]/SHDRSkyBox/c_shader_skybox_alt.lua | 2 | 4859 | -- Skybox alternative v0.46 by Ren712
-- Based on GTASA Skybox mod by Shemer
-- knoblauch700@o2.pl
local sphereObjScale=100 -- set object scale
local sphereShadScale={1,1,0.9} -- object scale in VS
local makeAngular=true -- set to true if you have spheric texture
local sphereTexScale={1,1,1} -- scale the texture in PS
local FadeEffect = true -- horizon effect fading
local SkyVis = 1-- sky visibility vs fading fog ammount (0 - sky not visible )
-- color variables below
local ColorAdd=-0.15 -- 0 to -0.4 -- standard colors are too bright
local ColorPow=2 -- 1 to 2 -- contrast
local shadCloudsTexDisabled=false
local modelID=15057 -- that's probably the best model to replace ... or not
--setWeather(7) -- the chosen weather (you might delete that but choose a proper one)
setCloudsEnabled(true)
local skydome_shader = nil
local null_shader = nil
local skydome_texture = nil
local getLastTick,getLastTock = 0,0
function startShaderResource()
if salEffectEnabled then return end
skydome_shader = dxCreateShader ( "shaders/shader_skydome.fx",0,0,true,"object" )
null_shader = dxCreateShader ( "shaders/shader_null.fx" )
skydome_texture=dxCreateTexture("textures/skydome.jpg")
if not skydome_shader or not null_shader or not skydome_texture then
outputChatBox('Could not start Skybox alternative !',255,0,0)
return
else
outputConsole('Shader skybox alternative v0.45 has started.')
end
setCloudsEnabled(false)
dxSetShaderValue ( skydome_shader, "gTEX", skydome_texture )
dxSetShaderValue ( skydome_shader, "gAlpha", 1 )
dxSetShaderValue ( skydome_shader, "makeAngular", makeAngular )
dxSetShaderValue ( skydome_shader, "gObjScale", sphereShadScale )
dxSetShaderValue ( skydome_shader, "gTexScale",sphereTexScale )
dxSetShaderValue ( skydome_shader, "gFadeEffect", FadeEffect )
dxSetShaderValue ( skydome_shader, "gSkyVis", SkyVis )
dxSetShaderValue ( skydome_shader, "gColorAdd", ColorAdd )
dxSetShaderValue ( skydome_shader, "gColorPow", ColorPow )
-- apply to texture
engineApplyShaderToWorldTexture ( skydome_shader, "skybox_tex" )
if shadCloudsTexDisabled then engineApplyShaderToWorldTexture ( null_shader, "cloudmasked*" ) end
txd_skybox = engineLoadTXD('models/skybox_model.txd')
engineImportTXD(txd_skybox, modelID)
dff_skybox = engineLoadDFF('models/skybox_model.dff', modelID)
engineReplaceModel(dff_skybox, modelID)
local cam_x,cam_y,cam_z = getElementPosition(getLocalPlayer())
skyBoxBoxa = createObject ( modelID, cam_x, cam_y, cam_z, 0, 0, 0, true )
setObjectScale(skyBoxBoxa,sphereObjScale)
setElementAlpha(skyBoxBoxa,1)
addEventHandler ( "onClientHUDRender", getRootElement (), renderSphere ) -- sky object
addEventHandler ( "onClientHUDRender", getRootElement (), renderTime ) -- time
applyWeatherInfluence()
salEffectEnabled = true
end
function stopShaderResource()
if not salEffectEnabled then return end
removeEventHandler ( "onClientHUDRender", getRootElement (), renderSphere ) -- sky object
removeEventHandler ( "onClientHUDRender", getRootElement (), renderTime ) -- time
if null_shader then
engineRemoveShaderFromWorldTexture ( null_shader, "cloudmasked*" )
destroyElement(null_shader)
null_shader=nil
end
engineRemoveShaderFromWorldTexture ( skydome_shader, "skybox_tex" )
destroyElement(skyBoxBoxa)
destroyElement(skydome_shader)
destroyElement(skydome_texture)
skyBoxBoxa=nil
skydome_shader=nil
skydome_texture=false
salEffectEnabled = false
end
lastWeather=0
function renderSphere()
-- Updates the position of the object
if getTickCount ( ) - getLastTock < 2 then return end
local cam_x, cam_y, cam_z, lx, ly, lz = getCameraMatrix()
if cam_z<=200 then setElementPosition ( skyBoxBoxa, cam_x, cam_y, 80,false )
else setElementPosition ( skyBoxBoxa, cam_x, cam_y, 80+cam_z-200,false ) end
local r1, g1, b1, r2, g2, b2 = getSkyGradient()
local skyBott = {r2/255, g2/255, b2/255, 1}
dxSetShaderValue ( skydome_shader, "gSkyBott", skyBott )
if getWeather()~=lastWeather then applyWeatherInfluence() end
lastWeather=getWeather()
getLastTock = getTickCount ()
end
function renderTime()
local hour, minute = getTime ( )
if getTickCount ( ) - getLastTick < 100 then return end
if not skydome_shader then return end
if hour >= 20 then
local dusk_aspect = ((hour-20)*60+minute)/240
dusk_aspect = 1-dusk_aspect
dxSetShaderValue ( skydome_shader, "gAlpha", dusk_aspect)
end
if hour <= 2 then
dxSetShaderValue ( skydome_shader, "gAlpha", 0)
end
if hour > 2 and hour <= 6 then
local dawn_aspect = ((hour-3)*60+minute)/180
dawn_aspect = dawn_aspect
dxSetShaderValue ( skydome_shader, "gAlpha", dawn_aspect)
end
if hour > 6 and hour < 20 then
dxSetShaderValue ( skydome_shader, "gAlpha", 1)
end
getLastTick = getTickCount ()
end
function applyWeatherInfluence()
setSunSize (0)
setSunColor(0, 0, 0, 0, 0, 0)
end | mit |
PichotM/DarkRP | gamemode/modules/fadmin/fadmin/playeractions/teleport/cl_init.lua | 6 | 2349 |
FAdmin.StartHooks["zz_Teleport"] = function()
FAdmin.Messages.RegisterNotification{
name = "goto",
hasTarget = true,
message = {"instigator", " teleported to ", "targets"}
}
FAdmin.Messages.RegisterNotification{
name = "bring",
hasTarget = true,
message = {"instigator", " brought ", "targets", " to them"}
}
FAdmin.Access.AddPrivilege("Teleport", 2)
FAdmin.Commands.AddCommand("Teleport", nil, "[Player]")
FAdmin.Commands.AddCommand("TP", nil, "[Player]")
FAdmin.Commands.AddCommand("Bring", nil, "<Player>", "[Player]")
FAdmin.Commands.AddCommand("goto", nil, "<Player>")
FAdmin.ScoreBoard.Player:AddActionButton("Teleport", "fadmin/icons/teleport", Color(0, 200, 0, 255),
function(ply) return FAdmin.Access.PlayerHasPrivilege(LocalPlayer(), "Teleport") end,
function(ply, button)
RunConsoleCommand("_FAdmin", "Teleport", ply:UserID())
end)
FAdmin.ScoreBoard.Player:AddActionButton("Goto", "fadmin/icons/teleport", Color(0, 200, 0, 255),
function(ply) return FAdmin.Access.PlayerHasPrivilege(LocalPlayer(), "Teleport") and ply ~= LocalPlayer() end,
function(ply, button)
RunConsoleCommand("_FAdmin", "goto", ply:UserID())
end)
FAdmin.ScoreBoard.Player:AddActionButton("Bring", "fadmin/icons/teleport", Color(0, 200, 0, 255),
function(ply) return FAdmin.Access.PlayerHasPrivilege(LocalPlayer(), "Teleport") and ply ~= LocalPlayer() end,
function(ply, button)
local menu = DermaMenu()
local Padding = vgui.Create("DPanel")
Padding:SetPaintBackgroundEnabled(false)
Padding:SetSize(1,5)
menu:AddPanel(Padding)
local Title = vgui.Create("DLabel")
Title:SetText(" Bring to:\n")
Title:SetFont("UiBold")
Title:SizeToContents()
Title:SetTextColor(color_black)
menu:AddPanel(Title)
local uid = ply:UserID()
menu:AddOption("Yourself", function() RunConsoleCommand("_FAdmin", "bring", uid) end)
for k, v in pairs(DarkRP.nickSortedPlayers()) do
if v ~= LocalPlayer() then
local vUid = v:UserID()
menu:AddOption(v:Nick(), function() RunConsoleCommand("_FAdmin", "bring", uid, vUid) end)
end
end
menu:Open()
end)
end
| mit |
Insurgencygame/LivingDead | TheLivingDeadv0.1.sdd/lups/particleclasses/jet.lua | 1 | 6353 | -- $Id: Jet.lua 3171 2008-11-06 09:06:29Z det $
-----------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------
local Jet = {}
Jet.__index = Jet
local jitShader
local tex --//screencopy
local timerUniform
-----------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------
function Jet.GetInfo()
return {
name = "Jet",
backup = "", --// backup class, if this class doesn't work (old cards,ati's,etc.)
desc = "",
layer = 4, --// extreme simply z-ordering :x
--// gfx requirement
fbo = true,
shader = true,
distortion= true,
atiseries = 2,
ms = -1,
intel = -1,
}
end
Jet.Default = {
layer = 4,
life = math.huge,
repeatEffect = true,
emitVector = {0,0,-1},
pos = {0,0,0}, --// not used
width = 4,
length = 50,
distortion = 0.02,
animSpeed = 1,
texture1 = "bitmaps/GPL/Lups/perlin_noise.jpg", --// noise texture
texture2 = ":c:bitmaps/GPL/Lups/jet.bmp", --// jitter shape
}
-----------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------
local spGetGameSeconds = Spring.GetGameSeconds
local glUseShader = gl.UseShader
local glUniform = gl.Uniform
local glTexture = gl.Texture
local glCallList = gl.CallList
function Jet:BeginDrawDistortion()
glUseShader(jitShader)
glUniform(timerUniform, spGetGameSeconds())
end
function Jet:EndDrawDistortion()
glUseShader(0)
glTexture(1,false)
glTexture(2,false)
end
function Jet:DrawDistortion()
glTexture(1,self.texture1)
glTexture(2,self.texture2)
glCallList(self.dList)
end
-----------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------
-- used if repeatEffect=true;
function Jet:ReInitialize()
self.dieGameFrame = self.dieGameFrame + self.life
end
function Jet.Initialize()
jitShader = gl.CreateShader({
vertex = [[
uniform float timer;
varying float distortion;
varying vec4 texCoords;
const vec4 centerPos = vec4(0.0,0.0,0.0,1.0);
// gl_vertex.xy := width/length
// gl_vertex.zw := texcoord
// gl_MultiTexCoord0.x := (quad_width) / (quad_length) (used to normalize the texcoord dimensions)
// gl_MultiTexCoord0.y := distortion strength
// gl_MultiTexCoord0.z := animation speed
// gl_MultiTexCoord1 := emit vector
void main()
{
texCoords.st = gl_Vertex.pq;
texCoords.pq = gl_Vertex.pq;
texCoords.p *= gl_MultiTexCoord0.x;
texCoords.pq += timer*gl_MultiTexCoord0.z;
gl_Position = gl_ModelViewMatrix * centerPos;
vec3 dir3 = vec3(gl_ModelViewMatrix * gl_MultiTexCoord1) - gl_Position.xyz;
vec3 v = normalize( dir3 );
vec3 w = normalize( -vec3(gl_Position) );
vec3 u = normalize( cross(w,v) );
gl_Position.xyz += gl_Vertex.x*v + gl_Vertex.y*u;
gl_Position = gl_ProjectionMatrix * gl_Position;
distortion = gl_MultiTexCoord0.y;
}
]],
fragment = [[
uniform sampler2D noiseMap;
uniform sampler2D mask;
varying float distortion;
varying vec4 texCoords;
void main(void)
{
float opac = texture2D(mask,texCoords.st).r;
vec2 noiseVec = (texture2D(noiseMap, texCoords.pq).st - 0.5) * distortion * opac;
gl_FragColor = vec4(noiseVec.xy,0.0,gl_FragCoord.z);
}
]],
uniformInt = {
noiseMap = 1,
mask = 2,
},
uniform = {
timer = 0,
}
})
if (jitShader == nil) then
print(PRIO_MAJOR,"LUPS->Jet: shader error: "..gl.GetShaderLog())
return false
end
timerUniform = gl.GetUniformLocation(jitShader, 'timer')
end
function Jet:Finalize()
if (gl.DeleteShader) then
gl.DeleteShader(jitShader)
end
end
-----------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------
local glMultiTexCoord = gl.MultiTexCoord
local glVertex = gl.Vertex
local glCreateList = gl.CreateList
local glDeleteList = gl.DeleteList
local glBeginEnd = gl.BeginEnd
local GL_QUADS = GL.QUADS
local function BeginEndDrawList(self)
local ev = self.emitVector
glMultiTexCoord(0,self.width/self.length,self.distortion,0.2*self.animSpeed)
glMultiTexCoord(1,ev[1],ev[2],ev[3],1)
--// xy = width/length ; zw = texcoord
local w = self.width
local l = self.length
glVertex(-l,-w, 1,0)
glVertex(0, -w, 1,1)
glVertex(0, w, 0,1)
glVertex(-l, w, 0,0)
end
function Jet:CreateParticle()
self.dList = glCreateList(glBeginEnd,GL_QUADS,
BeginEndDrawList,self)
--// used for visibility check
self.radius = self.length
self.dieGameFrame = thisGameFrame + self.life
end
-----------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------
local MergeTable = MergeTable
local setmetatable = setmetatable
function Jet.Create(Options)
local newObject = MergeTable(Options, Jet.Default)
setmetatable(newObject,Jet) -- make handle lookup
newObject:CreateParticle()
return newObject
end
function Jet:Destroy()
--gl.DeleteTexture(self.texture1)
--gl.DeleteTexture(self.texture2)
glDeleteList(self.dList)
end
-----------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------
return Jet | gpl-2.0 |
jirutka/luapak | luapak/build/toolchain/utils.lua | 1 | 1311 | ---------
-- Utilities for toolchain modules.
--
-- **Note: This module is not part of public API!**
----
local fs = require 'luarocks.fs'
local lrutil = require 'luarocks.util'
local log = require 'luapak.logging'
local concat = table.concat
local push = table.insert
local variable_substitutions = lrutil.variable_substitutions
local M = {}
--- Runs a command displaying its execution on standard output.
--
-- @tparam string ... The command and arguments.
-- @return bool true if command succeeds (status code 0), false otherwise.
function M.execute (...)
log.debug('Executing: '..concat({...}, ' '))
return fs.execute(...)
end
--- Pushes the `flag` with `values` into the given table `tab` and substitutes
-- all variables in `values`.
--
-- @tparam {string,...} tab The target table to push flags into.
-- @tparam string flag The flag with single format pattern to be substituted by `values`.
-- @tparam {string,...}|string|nil values
-- @tparam ?{[string]=...} variables
function M.push_flags (tab, flag, values, variables)
variables = variables or {}
if not values then
return
end
if type(values) ~= 'table' then
values = { tostring(values) }
end
variable_substitutions(values, variables)
for _, v in ipairs(values) do
push(tab, flag:format(v))
end
end
return M
| mit |
BarnamehNevisan/ss | plugins/inpm.lua | 243 | 3007 | do
local function pairsByKeys (t, f)
local a = {}
for n in pairs(t) do table.insert(a, n) end
table.sort(a, f)
local i = 0 -- iterator variable
local iter = function () -- iterator function
i = i + 1
if a[i] == nil then return nil
else return a[i], t[a[i]]
end
end
return iter
end
local function chat_list(msg)
local data = load_data(_config.moderation.data)
local groups = 'groups'
if not data[tostring(groups)] then
return 'No groups at the moment'
end
local message = 'List of Groups:\n*Use /join (ID) to join*\n\n '
for k,v in pairs(data[tostring(groups)]) do
local settings = data[tostring(v)]['settings']
for m,n in pairsByKeys(settings) do
if m == 'set_name' then
name = n
end
end
message = message .. '👥 '.. name .. ' (ID: ' .. v .. ')\n\n '
end
local file = io.open("./groups/lists/listed_groups.txt", "w")
file:write(message)
file:flush()
file:close()
return message
end
local function run(msg, matches)
if msg.to.type ~= 'chat' or is_sudo(msg) or is_admin(msg) and is_realm(msg) then
local data = load_data(_config.moderation.data)
if matches[1] == 'join' and data[tostring(matches[2])] then
if is_banned(msg.from.id, matches[2]) then
return 'You are banned.'
end
if is_gbanned(msg.from.id) then
return 'You are globally banned.'
end
if data[tostring(matches[2])]['settings']['lock_member'] == 'yes' and not is_owner2(msg.from.id, matches[2]) then
return 'Group is private.'
end
local chat_id = "chat#id"..matches[2]
local user_id = "user#id"..msg.from.id
chat_add_user(chat_id, user_id, ok_cb, false)
local group_name = data[tostring(matches[2])]['settings']['set_name']
return "Added you to chat:\n\n👥"..group_name.." (ID:"..matches[2]..")"
elseif matches[1] == 'join' and not data[tostring(matches[2])] then
return "Chat not found."
end
if matches[1] == 'chats'then
if is_admin(msg) and msg.to.type == 'chat' then
return chat_list(msg)
elseif msg.to.type ~= 'chat' then
return chat_list(msg)
end
end
if matches[1] == 'chatlist'then
if is_admin(msg) and msg.to.type == 'chat' then
send_document("chat#id"..msg.from.id, "./groups/lists/listed_groups.txt", ok_cb, false)
elseif msg.to.type ~= 'chat' then
send_document("user#id"..msg.from.id, "./groups/lists/listed_groups.txt", ok_cb, false)
end
end
end
end
return {
patterns = {
"^[/!](chats)$",
"^[/!](chatlist)$",
"^[/!](join) (.*)$",
"^[/!](kickme) (.*)$",
"^!!tgservice (chat_add_user)$"
},
run = run,
}
end
| gpl-2.0 |
hacklex/OpenRA | mods/cnc/maps/gdi04a/gdi04a.lua | 21 | 4901 | AutoTrigger = { CPos.New(51, 47), CPos.New(52, 47), CPos.New(53, 47), CPos.New(54, 47) }
GDIHeliTrigger = { CPos.New(27, 55), CPos.New(27, 56), CPos.New(28, 56), CPos.New(28, 57), CPos.New(28, 58), CPos.New(28, 59)}
Nod1Units = { "e1", "e1", "e3", "e3" }
Auto1Units = { "e1", "e1", "e3" }
KillsUntilReinforcements = 12
HeliDelay = { 83, 137, 211 }
GDIReinforcements = { "e2", "e2", "e2", "e2", "e2" }
GDIReinforcementsWaypoints = { GDIReinforcementsEntry.Location, GDIReinforcementsWP1.Location }
NodHelis = {
{ delay = DateTime.Seconds(HeliDelay[1]), entry = { NodHeliEntry.Location, NodHeliLZ1.Location }, types = { "e1", "e1", "e3" } },
{ delay = DateTime.Seconds(HeliDelay[2]), entry = { NodHeliEntry.Location, NodHeliLZ2.Location }, types = { "e1", "e1", "e1", "e1" } },
{ delay = DateTime.Seconds(HeliDelay[3]), entry = { NodHeliEntry.Location, NodHeliLZ3.Location }, types = { "e1", "e1", "e3" } }
}
SendHeli = function(heli)
units = Reinforcements.ReinforceWithTransport(enemy, "tran", heli.types, heli.entry, { heli.entry[1] })
Utils.Do(units[2], function(actor)
actor.Hunt()
Trigger.OnIdle(actor, actor.Hunt)
Trigger.OnKilled(actor, KillCounter)
end)
Trigger.AfterDelay(heli.delay, function() SendHeli(heli) end)
end
SendGDIReinforcements = function()
Media.PlaySpeechNotification(player, "Reinforce")
Reinforcements.ReinforceWithTransport(player, "apc", GDIReinforcements, GDIReinforcementsWaypoints, nil, function(apc, team)
table.insert(team, apc)
Trigger.OnAllKilled(team, function() Trigger.AfterDelay(DateTime.Seconds(5), SendGDIReinforcements) end)
Utils.Do(team, function(unit) unit.Stance = "Defend" end)
end)
end
BuildNod1 = function()
if HandOfNod.IsDead then
return
end
local func = function(team)
Utils.Do(team, function(actor)
Trigger.OnIdle(actor, actor.Hunt)
Trigger.OnKilled(actor, KillCounter)
end)
Trigger.OnAllKilled(team, BuildNod1)
end
if not HandOfNod.Build(Nod1Units, func) then
Trigger.AfterDelay(DateTime.Seconds(5), BuildNod1)
end
end
BuildAuto1 = function()
if HandOfNod.IsDead then
return
end
local func = function(team)
Utils.Do(team, function(actor)
Trigger.OnIdle(actor, actor.Hunt)
Trigger.OnKilled(actor, KillCounter)
end)
end
if not HandOfNod.IsDead and HandOfNod.Build(Auto1Units, func) then
Trigger.AfterDelay(DateTime.Seconds(5), BuildAuto1)
end
end
kills = 0
KillCounter = function() kills = kills + 1 end
ReinforcementsSent = false
Tick = function()
enemy.Cash = 1000
if not ReinforcementsSent and kills >= KillsUntilReinforcements then
ReinforcementsSent = true
player.MarkCompletedObjective(reinforcementsObjective)
SendGDIReinforcements()
end
if player.HasNoRequiredUnits() then
Trigger.AfterDelay(DateTime.Seconds(1), function() player.MarkFailedObjective(gdiObjective) end)
end
end
SetupWorld = function()
Utils.Do(enemy.GetGroundAttackers(enemy), function(unit)
Trigger.OnKilled(unit, KillCounter)
end)
Utils.Do(player.GetGroundAttackers(), function(unit)
unit.Stance = "Defend"
end)
Hunter1.Hunt()
Hunter2.Hunt()
Trigger.OnRemovedFromWorld(crate, function() player.MarkCompletedObjective(gdiObjective) end)
end
WorldLoaded = function()
player = Player.GetPlayer("GDI")
enemy = Player.GetPlayer("Nod")
SetupWorld()
Trigger.OnObjectiveAdded(player, function(p, id)
Media.DisplayMessage(p.GetObjectiveDescription(id), "New " .. string.lower(p.GetObjectiveType(id)) .. " objective")
end)
Trigger.OnObjectiveCompleted(player, function(p, id)
Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective completed")
end)
Trigger.OnObjectiveFailed(player, function(p, id)
Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective failed")
end)
Trigger.OnPlayerWon(player, function()
Media.PlaySpeechNotification(player, "Win")
end)
Trigger.OnPlayerLost(player, function()
Media.PlaySpeechNotification(player, "Lose")
end)
gdiObjective = player.AddPrimaryObjective("Retrieve the crate with the stolen rods.")
reinforcementsObjective = player.AddSecondaryObjective("Eliminate " .. KillsUntilReinforcements .. " Nod units for reinforcements.")
enemy.AddPrimaryObjective("Defend against the GDI forces.")
BuildNod1()
Utils.Do(NodHelis, function(heli)
Trigger.AfterDelay(heli.delay, function() SendHeli(heli) end)
end)
autoTrigger = false
Trigger.OnEnteredFootprint(AutoTrigger, function(a, id)
if not autoTrigger and a.Owner == player then
autoTrigger = true
Trigger.RemoveFootprintTrigger(id)
BuildAuto1()
end
end)
gdiHeliTrigger = false
Trigger.OnEnteredFootprint(GDIHeliTrigger, function(a, id)
if not gdiHeliTrigger and a.Owner == player then
gdiHeliTrigger = true
Trigger.RemoveFootprintTrigger(id)
Reinforcements.ReinforceWithTransport(player, "tran", nil, { GDIHeliEntry.Location, GDIHeliLZ.Location })
end
end)
Camera.Position = Actor56.CenterPosition
end
| gpl-3.0 |
mohammad4569/matrix | plugins/invite.lua | 299 | 1025 | -- Invite other user to the chat group.
-- Use !invite name User_name or !invite id id_number
-- The User_name is the print_name (there are no spaces but _)
do
local function callback(extra, success, result)
vardump(success)
vardump(result)
end
local function run(msg, matches)
local user = matches[2]
-- User submitted a user name
if matches[1] == "name" then
user = string.gsub(user," ","_")
end
-- User submitted an id
if matches[1] == "id" then
user = 'user#id'..user
end
-- The message must come from a chat group
if msg.to.type == 'chat' then
local chat = 'chat#id'..msg.to.id
chat_add_user(chat, user, callback, false)
return "Add: "..user.." to "..chat
else
return 'This isnt a chat group!'
end
end
return {
description = "Invite other user to the chat group",
usage = {
"!invite name [user_name]",
"!invite id [user_id]" },
patterns = {
"^!invite (name) (.*)$",
"^!invite (id) (%d+)$"
},
run = run,
moderation = true
}
end | gpl-2.0 |
Motiejus/tictactoelib | tictactoelib/play.lua | 1 | 2168 | local Board = require("board")
local validate = function(board, a1, b1, x1, y1, x2, y2)
if a1 ~= nil and not (a1 == x1 and b1 == y1) then
return false, "incorrect placement"
end
if x1 == nil or y1 == nil or x2 == nil or y2 == nil then
return false, "4 numbers expected, got nil"
end
for _, i in ipairs({x1, y1, x2, y2}) do
if type(i) ~= "number" then
return false, "number expected, got " .. type(i)
end
if not (i >= 1 and i <= 3) then
return false, "number out of bounds"
end
end
if board[x1][y1][x2][y2] then
return false, "non-empty spot"
end
return true
end
-- Yields:
-- xo; moveresult; log; board
-- moveresult ::
-- * {"state_coords", state_coords}
-- * {"error", error_string}
-- state_coords ::
-- {state, {x1, y1, x2, y2}}
-- state ::
-- * "x" ("x" won)
-- * "o" ("o" won)
-- * "draw"
-- * "continue"
local play = function(p1, p2)
local board, state = Board.new(), nil
local p, xo, a1, b1 = p1, "x", nil, nil
while state == nil do
local pp = function() return p(xo, board:copy(), a1, b1) end
collectgarbage()
local success, x1_or_err, y1, x2, y2 = pcall(pp)
collectgarbage()
if not success then
coroutine.yield(xo, {"error", x1_or_err}, "", board)
return
end
local x1 = x1_or_err
local valid, err = validate(board, a1, b1, x1, y1, x2, y2)
if not valid then
coroutine.yield(xo, {"error", err}, "", board)
return
end
board[x1][y1][x2][y2] = xo
state = board:state()
state_ret = state == nil and "continue" or state
state_coords = {"state_coords", {state_ret, {x1, y1, x2, y2}}}
coroutine.yield(xo, state_coords, "", board)
p = p == p1 and p2 or p1
xo = xo == "x" and "o" or "x"
if board[x2][y2]:state() == nil then
a1, b1 = x2, y2
else
a1, b1 = nil, nil
end
end
end
return function(p1, p2) return coroutine.wrap(function() play(p1, p2) end) end
| apache-2.0 |
b1v1r/ironbee | lua/event_processor.lua | 2 | 8323 | -- ========================================================================
-- Licensed to Qualys, Inc. (QUALYS) under one or more
-- contributor license agreements. See the NOTICE file distributed with
-- this work for additional information regarding copyright ownership.
-- QUALYS licenses this file to You 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.
-- ========================================================================
local ibmod = ...
-- ========================================================================
-- This module processes events to:
--
-- * Supress potential False Positives
-- * Categorize
-- * Promote events to alerts
--
-- Categories for events must be specified via tags in the following form:
--
-- tag:cat/<category-name>
--
-- Example:
-- tag:cat/XSS
--
-- This module is designed to be used with the threat_level.lua module.
--
--
-- Directives:
--
-- EventProcessorCategoryFilter <category> <min-confidence>
--
-- Defines the minimum acceptable event confidence for a given
-- category.
--
-- EventProcessorDefaultFilter <min-confidence>
--
-- Defines the minimum acceptable event confidence for an
-- undefined category.
--
-- Usage:
--
-- # Load the lua support module
-- LoadModule "ibmod_lua.so"
--
-- # Load this lua module
-- LuaLoadModule "event_processor.lua"
-- LuaLoadModule "threat_level.lua"
--
-- # Set the Filters
-- EventProcessorCategoryFilter XSS 75
-- EventProcessorCategoryFilter SQLi 25
-- EventProcessorCategoryFilter LFi 25
-- EventProcessorCategoryFilter RFi 50
-- EventProcessorDefaultFilter 50
--
-- # Set the minimum allowed event confidence
-- # to be considered in the threat score calculation
-- ThreatLevelMinConfidence 25
--
-- # Define a site with rules to utilize this module
-- <Site default>
-- SiteId 138E7FB0-1129-4FA5-8A63-432CE0BBD37A
-- Service *:*
-- Hostname *
--
-- # Generate some events
-- Rule ARGS @rx foo id:test/1 rev:1 msg:TEST1 \
-- tag:cat/XSS \
-- event confidence:50 severity:70
-- Rule ARGS @rx bar id:test/2 rev:1 msg:TEST2 \
-- tag:cat/SQLi \
-- event confidence:50 severity:80
-- Rule ARGS @rx boo id:test/3 rev:1 msg:TEST3 \
-- tag:cat/LFi \
-- event confidence:10 severity:100
--
-- # Check the threat level, blocking >=75
-- Rule THREAT_LEVEL @ge 75 id:test/100 rev:1 phase:REQUEST \
-- "msg:Testing THREAT_LEVEL" \
-- event block:phase
-- </Site>
-- ========================================================================
-- ---------------------------------------------------------
-- Handle "EventProcessorCategoryFilter <category> <num>"
-- directive.
-- ---------------------------------------------------------
ibmod:register_param2_directive(
"EventProcessorCategoryFilter",
function(ib_module, module_config, name, param1, param2)
local numval = tonumber(param2)
-- Validate parameter
if ((numval < 0) or (numval > 100)) then
ibmod:logError("Directive \"%s %s %s\" confidence value must be in range 0-100",
name, param1, param2)
return nil
end
-- Store in the config
if module_config["cat-min"] == nil then
module_config["cat-min"] = {}
end
module_config["cat-min"][param1] = numval
return 0
end
)
-- ---------------------------------------------------------
-- Handle "EventProcessorDefaultFilter <num>"
-- directive.
-- ---------------------------------------------------------
ibmod:register_param1_directive(
"EventProcessorDefaultFilter",
function(ib_module, module_config, name, param1)
local numval = tonumber(param1)
-- Validate parameter
if ((numval < 0) or (numval > 100)) then
ibmod:logError("Directive \"%s %s\" confidence value must be in range 0-100",
name, param1)
return nil
end
-- Store in the config
module_config["def-min"] = numval
return 0
end
)
-- ---------------------------------------------------------
-- Get the category from an event
-- ---------------------------------------------------------
local get_category = function(evt)
local cat
--[[ Run through all tags in the event and pick
the last "cat/<cat-name>" tag, extracting
the <cat-name> as the category. ]]
evt:forEachTag(
function(tag)
local cat_str = string.match(tag, [[^cat/(.*)]])
if cat_str ~= nil then
cat = cat_str
end
end
)
return cat
end
-- ---------------------------------------------------------
-- Process the events.
-- ---------------------------------------------------------
local process_events = function(ib)
--[[ Run through events, supressing events if needed. ]]
for i,evt in ib:events() do
if evt:getSuppress() == "none" then
local cat = get_category(evt)
if cat ~= nil then
--[[ Fetch the minimum confidence based on the
event category or the default. ]]
local min_confidence = ib.config["cat-min"][cat]
if min_confidence == nil then
min_confidence = ib.config["def-min"]
if min_confidence == nil then
min_confidence = 0
end
end
--[[ Suppress if confidence is too low. ]]
local c = evt:getConfidence()
if c < min_confidence then
ib:logDebug("Supressing low confidence event: %s", evt:getMsg())
evt:setSuppress("false_positive")
end
end
end
end
return 0
end
-- ---------------------------------------------------------
-- Generate alerts.
-- ---------------------------------------------------------
local generate_alerts = function(ib)
local evt_cat = {}
--[[ Run through events, generating scores for categorization. ]]
for i,evt in ib:events() do
if evt:getSuppress() == "none" then
local cat = get_category(evt)
if cat ~= nil then
local s = evt:getSeverity()
if evt_cat[cat] == nil then
evt_cat[cat] = { 1, s, { evt } }
else
table.insert(evt_cat[cat][3], evt)
evt_cat[cat] = { evt_cat[cat][1] + 1, evt_cat[cat][2] + s, evt_cat[cat][3] }
end
end
end
end
--[[ Run through events in the category and promote the
events to alerts. ]]
local cat_final
local cat_severity = 0
for cat,val in pairs(evt_cat) do
if val[2] > cat_severity then
cat_severity = val[2]
cat_final = cat
end
end
if cat_final ~= nil then
for i,evt in pairs(evt_cat[cat_final][3]) do
if evt:getType() ~= "alert" then
ib:logInfo("Promoting event to alert status: %s", evt:getMsg())
evt:setType("alert")
end
end
end
return 0
end
-- ---------------------------------------------------------
-- Process events when an event is triggered.
-- ---------------------------------------------------------
ibmod:handle_logevent_state(process_events)
-- ---------------------------------------------------------
-- Generate alerts before logging.
-- ---------------------------------------------------------
ibmod:handle_postprocess_state(generate_alerts)
-- Return IB_OK.
return 0
| apache-2.0 |
Anarchid/Zero-K | units/chickenlandqueen.lua | 4 | 12201 | return { chickenlandqueen = {
unitname = [[chickenlandqueen]],
name = [[Chicken Queen]],
description = [[Clucking Hell!]],
acceleration = 3.0,
activateWhenBuilt = true,
autoHeal = 0,
brakeRate = 18.0,
buildCostEnergy = 0,
buildCostMetal = 0,
builder = false,
buildPic = [[chickenflyerqueen.png]],
buildTime = 40000,
canGuard = true,
canMove = true,
canPatrol = true,
canSubmerge = false,
cantBeTransported = true,
category = [[LAND]],
collisionSphereScale = 1,
collisionVolumeOffsets = [[0 0 15]],
collisionVolumeScales = [[46 110 120]],
collisionVolumeType = [[box]],
customParams = {
selection_scale = 2,
},
explodeAs = [[SMALL_UNITEX]],
footprintX = 4,
footprintZ = 4,
iconType = [[chickenq]],
idleAutoHeal = 5,
idleTime = 1800,
leaveTracks = true,
maxDamage = 200000,
maxVelocity = 2.5,
minCloakDistance = 250,
movementClass = [[AKBOT4]],
noAutoFire = false,
noChaseCategory = [[TERRAFORM SATELLITE FIXEDWING GUNSHIP STUPIDTARGET MINE]],
objectName = [[chickenflyerqueen.s3o]],
power = 65536,
reclaimable = false,
script = [[chickenlandqueen.lua]],
selfDestructAs = [[SMALL_UNITEX]],
sfxtypes = {
explosiongenerators = {
[[custom:blood_spray]],
[[custom:blood_explode]],
[[custom:dirt]],
},
},
sightDistance = 2048,
sonarDistance = 2048,
trackOffset = 18,
trackStrength = 8,
trackStretch = 1,
trackType = [[ChickenTrack]],
trackWidth = 100,
turnRate = 480,
upright = true,
workerTime = 0,
weapons = {
{
def = [[MELEE]],
mainDir = [[0 0 1]],
maxAngleDif = 150,
onlyTargetCategory = [[SWIM LAND SUB SINK TURRET FLOAT SHIP HOVER]],
},
{
def = [[FIREGOO]],
mainDir = [[0 0 1]],
maxAngleDif = 150,
onlyTargetCategory = [[SWIM LAND SINK TURRET FLOAT SHIP HOVER]],
},
{
def = [[SPORES]],
onlyTargetCategory = [[FIXEDWING LAND SINK TURRET SHIP SWIM FLOAT GUNSHIP HOVER]],
},
{
def = [[SPORES]],
onlyTargetCategory = [[FIXEDWING LAND SINK TURRET SHIP SWIM FLOAT GUNSHIP HOVER]],
},
{
def = [[SPORES]],
onlyTargetCategory = [[FIXEDWING LAND SINK TURRET SHIP SWIM FLOAT GUNSHIP HOVER]],
},
{
def = [[QUEENCRUSH]],
onlyTargetCategory = [[SWIM LAND SINK TURRET FLOAT SHIP HOVER]],
},
{
def = [[DODOBOMB]],
onlyTargetCategory = [[NONE]],
},
{
def = [[BASILISKBOMB]],
onlyTargetCategory = [[NONE]],
},
{
def = [[TIAMATBOMB]],
onlyTargetCategory = [[NONE]],
},
},
weaponDefs = {
BASILISKBOMB = {
name = [[Basilisk Bomb]],
accuracy = 60000,
areaOfEffect = 48,
avoidFeature = false,
avoidFriendly = false,
burnblow = true,
collideFriendly = false,
craterBoost = 1,
craterMult = 2,
customparams = {
spawns_name = "chickenc",
spawns_expire = 0,
},
damage = {
default = 180,
},
explosionGenerator = [[custom:none]],
fireStarter = 70,
flightTime = 0,
impulseBoost = 0,
impulseFactor = 0.4,
interceptedByShieldType = 0,
model = [[chickenc.s3o]],
range = 500,
reloadtime = 10,
smokeTrail = false,
startVelocity = 200,
tolerance = 8000,
tracks = false,
turnRate = 4000,
turret = true,
waterweapon = true,
weaponAcceleration = 200,
weaponType = [[AircraftBomb]],
weaponVelocity = 200,
},
DODOBOMB = {
name = [[Dodo Bomb]],
accuracy = 60000,
areaOfEffect = 1,
avoidFeature = false,
avoidFriendly = false,
burnblow = true,
collideFriendly = false,
craterBoost = 0,
craterMult = 0,
customparams = {
spawns_name = "chicken_dodo",
spawns_expire = 30,
},
damage = {
default = 1,
},
explosionGenerator = [[custom:none]],
fireStarter = 70,
flightTime = 0,
impactOnly = true,
impulseBoost = 0,
impulseFactor = 0.4,
interceptedByShieldType = 0,
model = [[chicken_dodobomb.s3o]],
range = 500,
reloadtime = 10,
smokeTrail = false,
startVelocity = 200,
tolerance = 8000,
tracks = false,
turnRate = 4000,
turret = true,
waterweapon = true,
weaponAcceleration = 200,
weaponType = [[AircraftBomb]],
weaponVelocity = 200,
},
TIAMATBOMB = {
name = [[Tiamat Bomb]],
accuracy = 60000,
areaOfEffect = 72,
avoidFeature = false,
avoidFriendly = false,
burnblow = true,
collideFriendly = false,
craterBoost = 1,
craterMult = 2,
customparams = {
spawns_name = "chicken_tiamat",
spawns_expire = 0,
},
damage = {
default = 350,
},
explosionGenerator = [[custom:none]],
fireStarter = 70,
flightTime = 0,
impulseBoost = 0,
impulseFactor = 0.4,
interceptedByShieldType = 0,
model = [[chickenbroodqueen.s3o]],
noSelfDamage = true,
range = 500,
reloadtime = 10,
smokeTrail = false,
startVelocity = 200,
tolerance = 8000,
tracks = false,
turnRate = 4000,
turret = true,
waterweapon = true,
weaponAcceleration = 200,
weaponType = [[AircraftBomb]],
weaponVelocity = 200,
},
FIREGOO = {
name = [[Napalm Goo]],
areaOfEffect = 256,
burst = 8,
burstrate = 0.033,
cegTag = [[queen_trail_fire]],
customParams = {
light_radius = 500,
},
craterBoost = 0,
craterMult = 0,
damage = {
default = 400,
planes = 400,
},
explosionGenerator = [[custom:napalm_koda]],
firestarter = 400,
impulseBoost = 0,
impulseFactor = 0.4,
intensity = 0.7,
interceptedByShieldType = 1,
noSelfDamage = true,
proximityPriority = -4,
range = 1200,
reloadtime = 6,
rgbColor = [[0.8 0.4 0]],
size = 8,
sizeDecay = 0,
soundHit = [[weapon/burn_mixed]],
soundStart = [[chickens/bigchickenroar]],
sprayAngle = 6100,
tolerance = 5000,
turret = true,
weaponType = [[Cannon]],
weaponVelocity = 600,
},
MELEE = {
name = [[Chicken Claws]],
areaOfEffect = 32,
craterBoost = 1,
craterMult = 0,
damage = {
default = 1000,
planes = 1000,
},
explosionGenerator = [[custom:NONE]],
impulseBoost = 0,
impulseFactor = 1,
interceptedByShieldType = 0,
noSelfDamage = true,
range = 200,
reloadtime = 1,
size = 0,
soundStart = [[chickens/bigchickenbreath]],
targetborder = 1,
tolerance = 5000,
turret = true,
waterWeapon = true,
weaponType = [[Cannon]],
weaponVelocity = 600,
},
QUEENCRUSH = {
name = [[Chicken Kick]],
areaOfEffect = 400,
collideFriendly = false,
craterBoost = 0.001,
craterMult = 0.002,
customParams = {
lups_noshockwave = "1",
},
damage = {
default = 10,
chicken = 0.001,
planes = 10,
},
edgeEffectiveness = 1,
explosionGenerator = [[custom:NONE]],
impulseBoost = 500,
impulseFactor = 1,
intensity = 1,
interceptedByShieldType = 1,
noSelfDamage = true,
range = 512,
reloadtime = 1,
rgbColor = [[1 1 1]],
thickness = 1,
tolerance = 100,
turret = true,
weaponType = [[Cannon]],
weaponVelocity = 0.8,
},
SPORES = {
name = [[Spores]],
areaOfEffect = 24,
avoidFriendly = false,
burst = 8,
burstrate = 0.1,
collideFriendly = false,
craterBoost = 0,
craterMult = 0,
customParams = {
light_radius = 0,
},
damage = {
default = 75,
planes = [[150]],
},
dance = 60,
explosionGenerator = [[custom:NONE]],
fireStarter = 0,
flightTime = 5,
groundbounce = 1,
heightmod = 0.5,
impactOnly = true,
impulseBoost = 0,
impulseFactor = 0.4,
interceptedByShieldType = 2,
metalpershot = 0,
model = [[chickeneggpink.s3o]],
noSelfDamage = true,
range = 600,
reloadtime = 4,
smokeTrail = true,
startVelocity = 100,
texture1 = [[]],
texture2 = [[sporetrail]],
tolerance = 10000,
tracks = true,
turnRate = 24000,
turret = true,
waterweapon = true,
weaponAcceleration = 100,
weaponType = [[MissileLauncher]],
weaponVelocity = 500,
wobble = 32000,
},
},
} }
| gpl-2.0 |
Insurgencygame/LivingDead | TheLivingDeadv0.1.sdd/units/unused/armalab.lua | 1 | 2802 | return {
armalab = {
acceleration = 0,
brakerate = 0,
buildangle = 1024,
buildcostenergy = 13761,
buildcostmetal = 2729,
builder = true,
buildinggrounddecaldecayspeed = 30,
buildinggrounddecalsizex = 7,
buildinggrounddecalsizey = 7,
buildinggrounddecaltype = "armalab_aoplane.dds",
buildpic = "ARMALAB.DDS",
buildtime = 16224,
canmove = true,
category = "ALL NOTLAND PLANT NOTSUB NOWEAPON NOTSHIP NOTAIR NOTHOVER SURFACE",
collisionvolumescales = "75 32 91",
collisionvolumetest = 1,
collisionvolumetype = "Box",
corpse = "DEAD",
description = "Produces Level 2 Kbots",
energystorage = 200,
explodeas = "LARGE_BUILDINGEX",
footprintx = 6,
footprintz = 6,
icontype = "building",
idleautoheal = 5,
idletime = 1800,
maxdamage = 3808,
maxslope = 15,
maxwaterdepth = 0,
metalstorage = 200,
name = "Advanced Kbot Lab",
objectname = "ARMALAB",
radardistance = 50,
seismicsignature = 0,
selfdestructas = "LARGE_BUILDING",
sightdistance = 286,
terraformspeed = 1000,
usebuildinggrounddecal = true,
workertime = 300,
yardmap = "occccooccccooccccooccccooccccoocccco",
buildoptions = {
[10] = "armfboy",
[11] = "armspid",
[12] = "armaak",
[13] = "armvader",
[14] = "armdecom",
[15] = "armscab",
[16] = "armaser",
[17] = "armspy",
[18] = "armmark",
[1] = "armack",
[2] = "armfark",
[3] = "armfast",
[4] = "armamph",
[5] = "armzeus",
[6] = "armmav",
[7] = "armsptk",
[8] = "armfido",
[9] = "armsnipe",
},
featuredefs = {
dead = {
blocking = true,
category = "corpses",
collisionvolumeoffsets = "0 -17 -1",
collisionvolumescales = "73 56 89",
collisionvolumetest = 1,
collisionvolumetype = "CylZ",
damage = 2285,
description = "Advanced Kbot Lab Wreckage",
energy = 0,
featuredead = "HEAP",
featurereclamate = "SMUDGE01",
footprintx = 5,
footprintz = 6,
height = 20,
hitdensity = 100,
metal = 1773,
object = "ARMALAB_DEAD",
reclaimable = true,
seqnamereclamate = "TREE1RECLAMATE",
world = "All Worlds",
},
heap = {
blocking = false,
category = "heaps",
damage = 1143,
description = "Advanced Kbot Lab Heap",
energy = 0,
featurereclamate = "SMUDGE01",
footprintx = 5,
footprintz = 5,
height = 4,
hitdensity = 100,
metal = 887,
object = "5X5A",
reclaimable = true,
seqnamereclamate = "TREE1RECLAMATE",
world = "All Worlds",
},
},
sounds = {
canceldestruct = "cancel2",
underattack = "warning1",
unitcomplete = "untdone",
count = {
[1] = "count6",
[2] = "count5",
[3] = "count4",
[4] = "count3",
[5] = "count2",
[6] = "count1",
},
select = {
[1] = "plabactv",
},
},
},
}
| gpl-2.0 |
gbox3d/nodemcu-firmware | lua_modules/http/http.lua | 89 | 6624 | ------------------------------------------------------------------------------
-- HTTP server module
--
-- LICENCE: http://opensource.org/licenses/MIT
-- Vladimir Dronnikov <dronnikov@gmail.com>
------------------------------------------------------------------------------
local collectgarbage, tonumber, tostring = collectgarbage, tonumber, tostring
local http
do
------------------------------------------------------------------------------
-- request methods
------------------------------------------------------------------------------
local make_req = function(conn, method, url)
local req = {
conn = conn,
method = method,
url = url,
}
-- return setmetatable(req, {
-- })
return req
end
------------------------------------------------------------------------------
-- response methods
------------------------------------------------------------------------------
local send = function(self, data, status)
local c = self.conn
-- TODO: req.send should take care of response headers!
if self.send_header then
c:send("HTTP/1.1 ")
c:send(tostring(status or 200))
-- TODO: real HTTP status code/name table
c:send(" OK\r\n")
-- we use chunked transfer encoding, to not deal with Content-Length:
-- response header
self:send_header("Transfer-Encoding", "chunked")
-- TODO: send standard response headers, such as Server:, Date:
end
if data then
-- NB: no headers allowed after response body started
if self.send_header then
self.send_header = nil
-- end response headers
c:send("\r\n")
end
-- chunked transfer encoding
c:send(("%X\r\n"):format(#data))
c:send(data)
c:send("\r\n")
end
end
local send_header = function(self, name, value)
local c = self.conn
-- NB: quite a naive implementation
c:send(name)
c:send(": ")
c:send(value)
c:send("\r\n")
end
-- finalize request, optionally sending data
local finish = function(self, data, status)
local c = self.conn
-- NB: req.send takes care of response headers
if data then
self:send(data, status)
end
-- finalize chunked transfer encoding
c:send("0\r\n\r\n")
-- close connection
c:close()
end
--
local make_res = function(conn)
local res = {
conn = conn,
}
-- return setmetatable(res, {
-- send_header = send_header,
-- send = send,
-- finish = finish,
-- })
res.send_header = send_header
res.send = send
res.finish = finish
return res
end
------------------------------------------------------------------------------
-- HTTP parser
------------------------------------------------------------------------------
local http_handler = function(handler)
return function(conn)
local req, res
local buf = ""
local method, url
local ondisconnect = function(conn)
collectgarbage("collect")
end
-- header parser
local cnt_len = 0
local onheader = function(conn, k, v)
-- TODO: look for Content-Type: header
-- to help parse body
-- parse content length to know body length
if k == "content-length" then
cnt_len = tonumber(v)
end
if k == "expect" and v == "100-continue" then
conn:send("HTTP/1.1 100 Continue\r\n")
end
-- delegate to request object
if req and req.onheader then
req:onheader(k, v)
end
end
-- body data handler
local body_len = 0
local ondata = function(conn, chunk)
-- NB: do not reset node in case of lengthy requests
tmr.wdclr()
-- feed request data to request handler
if not req or not req.ondata then return end
req:ondata(chunk)
-- NB: once length of seen chunks equals Content-Length:
-- onend(conn) is called
body_len = body_len + #chunk
-- print("-B", #chunk, body_len, cnt_len, node.heap())
if body_len >= cnt_len then
req:ondata()
end
end
local onreceive = function(conn, chunk)
-- merge chunks in buffer
if buf then
buf = buf .. chunk
else
buf = chunk
end
-- consume buffer line by line
while #buf > 0 do
-- extract line
local e = buf:find("\r\n", 1, true)
if not e then break end
local line = buf:sub(1, e - 1)
buf = buf:sub(e + 2)
-- method, url?
if not method then
local i
-- NB: just version 1.1 assumed
_, i, method, url = line:find("^([A-Z]+) (.-) HTTP/1.1$")
if method then
-- make request and response objects
req = make_req(conn, method, url)
res = make_res(conn)
end
-- header line?
elseif #line > 0 then
-- parse header
local _, _, k, v = line:find("^([%w-]+):%s*(.+)")
-- header seems ok?
if k then
k = k:lower()
onheader(conn, k, v)
end
-- headers end
else
-- spawn request handler
-- NB: do not reset in case of lengthy requests
tmr.wdclr()
handler(req, res)
tmr.wdclr()
-- NB: we feed the rest of the buffer as starting chunk of body
ondata(conn, buf)
-- buffer no longer needed
buf = nil
-- NB: we explicitly reassign receive handler so that
-- next received chunks go directly to body handler
conn:on("receive", ondata)
-- parser done
break
end
end
end
conn:on("receive", onreceive)
conn:on("disconnection", ondisconnect)
end
end
------------------------------------------------------------------------------
-- HTTP server
------------------------------------------------------------------------------
local srv
local createServer = function(port, handler)
-- NB: only one server at a time
if srv then srv:close() end
srv = net.createServer(net.TCP, 15)
-- listen
srv:listen(port, http_handler(handler))
return srv
end
------------------------------------------------------------------------------
-- HTTP server methods
------------------------------------------------------------------------------
http = {
createServer = createServer,
}
end
return http
| mit |
Insurgencygame/LivingDead | TheLivingDeadv0.1.sdd/units/unused/armham.lua | 1 | 2925 | return {
armham = {
acceleration = 0.11999999731779,
brakerate = 0.22499999403954,
buildcostenergy = 1231,
buildcostmetal = 121,
buildpic = "ARMHAM.DDS",
buildtime = 2210,
canmove = true,
category = "KBOT MOBILE WEAPON ALL NOTSUB NOTSHIP NOTAIR NOTHOVER SURFACE",
corpse = "DEAD",
description = "Light Plasma Kbot",
energymake = 0.60000002384186,
energyuse = 0.60000002384186,
explodeas = "BIG_UNITEX",
footprintx = 2,
footprintz = 2,
idleautoheal = 5,
idletime = 1800,
mass = 300,
maxdamage = 810,
maxslope = 14,
maxvelocity = 1.539999961853,
maxwaterdepth = 12,
movementclass = "KBOT2",
name = "Hammer",
nochasecategory = "VTOL",
objectname = "ARMHAM",
seismicsignature = 0,
selfdestructas = "BIG_UNIT",
sightdistance = 380,
smoothanim = true,
turnrate = 1094,
upright = true,
featuredefs = {
dead = {
blocking = true,
category = "corpses",
collisionvolumeoffsets = "1.85908508301 -3.40689422363 2.59911346436",
collisionvolumescales = "31.0182495117 8.18759155273 36.3284454346",
collisionvolumetype = "Box",
damage = 486,
description = "Hammer Wreckage",
energy = 0,
featuredead = "HEAP",
featurereclamate = "SMUDGE01",
footprintx = 2,
footprintz = 2,
height = 40,
hitdensity = 100,
metal = 79,
object = "ARMHAM_DEAD",
reclaimable = true,
seqnamereclamate = "TREE1RECLAMATE",
world = "All Worlds",
},
heap = {
blocking = false,
category = "heaps",
damage = 243,
description = "Hammer Heap",
energy = 0,
featurereclamate = "SMUDGE01",
footprintx = 2,
footprintz = 2,
height = 4,
hitdensity = 100,
metal = 32,
object = "2X2E",
reclaimable = true,
seqnamereclamate = "TREE1RECLAMATE",
world = "All Worlds",
},
},
sounds = {
canceldestruct = "cancel2",
underattack = "warning1",
cant = {
[1] = "cantdo4",
},
count = {
[1] = "count6",
[2] = "count5",
[3] = "count4",
[4] = "count3",
[5] = "count2",
[6] = "count1",
},
ok = {
[1] = "kbarmmov",
},
select = {
[1] = "kbarmsel",
},
},
weapondefs = {
arm_ham = {
areaofeffect = 36,
craterboost = 0,
cratermult = 0,
explosiongenerator = "custom:LIGHT_PLASMA",
gravityaffected = "true",
impulseboost = 0.12300000339746,
impulsefactor = 0.12300000339746,
name = "PlasmaCannon",
noselfdamage = true,
predictboost = 0.40000000596046,
range = 380,
reloadtime = 1.75,
soundhit = "xplomed3",
soundstart = "cannon1",
turret = true,
weapontype = "Cannon",
weaponvelocity = 286,
damage = {
bombers = 21,
default = 104,
fighters = 21,
subs = 5,
vtol = 21,
},
},
},
weapons = {
[1] = {
badtargetcategory = "VTOL",
def = "ARM_HAM",
onlytargetcategory = "NOTSUB",
},
},
},
}
| gpl-2.0 |
codneutro/L2D | sys/lua/L2D/player/player.lua | 1 | 1407 | ---
-- Player implementation
--
-- @author x[N]ir
-- @release 04/04/16
--
--- Player array
-- @tfield table players
players = {};
---
-- Saves the specified player into the database
--
-- @tparam int id player ID
--
function savePlayer(id)
local lines = {};
local p = players[id];
--> User received files but leave during download process (-__-)
if (p) then
local userFile = USERS_FOLDER..p.usgn..".dat";
for k, v in pairs(p) do
lines[#lines + 1] = v;
end
File.writeLines(userFile, lines);
printDebug(p.nick.." ["..p.usgn.."] has been saved");
end
end
---
-- Returns the loaded player
--
-- @tparam int id player ID
-- @treturn Player a player
--
function loadPlayer(id)
local usgn = player(id, "usgn");
local userFile = USERS_FOLDER..usgn..".dat";
local p = Player.new(id);
p.usgn = usgn;
if (File.isFile(userFile)) then
File.loadFile(userFile);
for k, v in pairs(p) do
if (k ~= "nick") then
p[k] = tonumber(File.getLine());
else
p[k] = File.getLine();
end
end
end
printDebug(p.nick.." ["..p.usgn.."] has been loaded");
return p;
end
---
-- Returns a player id from usgn or -1 on error
--
-- @tparam int usgn player USGN
-- @treturn int player's ID associated with the usgn
--
function getPlayerID(usgn)
for k, id in pairs(player(0, "table")) do
if(player(id, "usgn") == usgn) then
return id;
end
end
return -1;
end | gpl-3.0 |
Goranaws/Dominos | Dominos/libs/LibKeyBound-1.0/LibKeyBound-1.0.lua | 1 | 18271 | --[[
Name: LibKeyBound-1.0
Revision: $Rev: 109 $
Author(s): Gello, Maul, Toadkiller, Tuller
Website: http://www.wowace.com/wiki/LibKeyBound-1.0
Documentation: http://www.wowace.com/wiki/LibKeyBound-1.0
SVN: http://svn.wowace.com/wowace/trunk/LibKeyBound-1.0
Description: An intuitive keybindings system: mouseover frame, click keys or buttons.
Dependencies: CallbackHandler-1.0
--]]
local MAJOR = 'LibKeyBound-1.0'
local MINOR = tonumber(("$Revision: 109 $"):match("(%d+)")) + 90000
--[[
LibKeyBound-1.0
ClickBinder by Gello and TrinityBinder by Maul -> keyBound by Tuller -> LibKeyBound library by Toadkiller
Functions needed to implement
button:GetHotkey() - returns the current hotkey assigned to the given button
Functions to implement if using a custom keybindings system:
button:SetKey(key) - binds the given key to the given button
button:FreeKey(key) - unbinds the given key from all other buttons
button:ClearBindings() - removes all keys bound to the given button
button:GetBindings() - returns a string listing all bindings of the given button
button:GetActionName() - what we're binding to, used for printing
--]]
local LibKeyBound, oldminor = LibStub:NewLibrary(MAJOR, MINOR)
if not LibKeyBound then return end -- no upgrade needed
local _G = _G
local NUM_MOUSE_BUTTONS = 31
-- CallbackHandler
LibKeyBound.events = LibKeyBound.events or _G.LibStub('CallbackHandler-1.0'):New(LibKeyBound)
local L = LibKeyBoundLocale10
LibKeyBound.L = L
-- ToDo delete global LibKeyBoundLocale10 at some point
LibKeyBound.Binder = LibKeyBound.Binder or {}
-- #NODOC
function LibKeyBound:Initialize()
do
local f = CreateFrame('Frame', 'KeyboundDialog', UIParent)
f:SetFrameStrata('DIALOG')
f:SetToplevel(true)
f:EnableMouse(true)
f:SetMovable(true)
f:SetClampedToScreen(true)
f:SetWidth(360)
f:SetHeight(140)
f:SetBackdrop{
bgFile='Interface\\DialogFrame\\UI-DialogBox-Background' ,
edgeFile='Interface\\DialogFrame\\UI-DialogBox-Border',
tile = true,
insets = {left = 11, right = 12, top = 12, bottom = 11},
tileSize = 32,
edgeSize = 32,
}
f:SetPoint('TOP', 0, -24)
f:Hide()
f:SetScript('OnShow', function() PlaySound(SOUNDKIT.IG_MAINMENU_OPEN) end)
f:SetScript('OnHide', function() PlaySound(SOUNDKIT.IG_MAINMENU_CLOSE) end)
f:RegisterForDrag('LeftButton')
f:SetScript('OnDragStart', function(f) f:StartMoving() end)
f:SetScript('OnDragStop', function(f) f:StopMovingOrSizing() end)
local header = f:CreateTexture(nil, 'ARTWORK')
header:SetTexture('Interface\\DialogFrame\\UI-DialogBox-Header')
header:SetWidth(256); header:SetHeight(64)
header:SetPoint('TOP', 0, 12)
local title = f:CreateFontString('ARTWORK')
title:SetFontObject('GameFontNormal')
title:SetPoint('TOP', header, 'TOP', 0, -14)
title:SetText(L.BindingMode)
local desc = f:CreateFontString('ARTWORK')
desc:SetFontObject('GameFontHighlight')
desc:SetJustifyV('TOP')
desc:SetJustifyH('LEFT')
desc:SetPoint('TOPLEFT', 18, -32)
desc:SetPoint('BOTTOMRIGHT', -18, 48)
desc:SetText(format(L.BindingsHelp, GetBindingText('ESCAPE', 'KEY_')))
-- Per character bindings checkbox
local perChar = CreateFrame('CheckButton', 'KeyboundDialogCheck', f, 'OptionsCheckButtonTemplate')
_G[perChar:GetName() .. 'Text']:SetText(CHARACTER_SPECIFIC_KEYBINDINGS)
perChar:SetScript('OnShow', function(self)
self:SetChecked(GetCurrentBindingSet() == 2)
end)
local current
perChar:SetScript('OnClick', function(self)
current = (perChar:GetChecked() and 2) or 1
LoadBindings(current)
end)
-- Okay bindings checkbox
local okayBindings = CreateFrame('CheckButton', 'KeyboundDialogOkay', f, 'OptionsButtonTemplate')
getglobal(okayBindings:GetName() .. 'Text'):SetText(OKAY)
okayBindings:SetScript('OnClick', function(self)
current = (perChar:GetChecked() and 2) or 1
if InCombatLockdown() then
self:RegisterEvent('PLAYER_REGEN_ENABLED')
else
SaveBindings(current)
LibKeyBound:Deactivate()
end
end)
okayBindings:SetScript('OnHide', function(self)
current = (perChar:GetChecked() and 2) or 1
if InCombatLockdown() then
self:RegisterEvent('PLAYER_REGEN_ENABLED')
else
SaveBindings(current)
end
end)
okayBindings:SetScript('OnEvent', function(self, event)
SaveBindings(current)
self:UnregisterEvent(event)
LibKeyBound:Deactivate()
end)
-- Cancel bindings checkbox
local cancelBindings = CreateFrame('CheckButton', 'KeyboundDialogCancel', f, 'OptionsButtonTemplate')
getglobal(cancelBindings:GetName() .. 'Text'):SetText(CANCEL)
cancelBindings:SetScript('OnClick', function(self)
if InCombatLockdown() then
self:RegisterEvent('PLAYER_REGEN_ENABLED')
else
LoadBindings(GetCurrentBindingSet())
LibKeyBound:Deactivate()
end
end)
cancelBindings:SetScript('OnEvent', function(self, event)
LoadBindings(GetCurrentBindingSet())
self:UnregisterEvent(event)
LibKeyBound:Deactivate()
end)
--position buttons
perChar:SetPoint('BOTTOMLEFT', 14, 32)
cancelBindings:SetPoint('BOTTOMRIGHT', -14, 14)
okayBindings:SetPoint('RIGHT', cancelBindings, 'LEFT')
self.dialog = f
end
SlashCmdList['LibKeyBoundSlashCOMMAND'] = function() self:Toggle() end
SLASH_LibKeyBoundSlashCOMMAND1 = '/libkeybound'
SLASH_LibKeyBoundSlashCOMMAND2 = '/kb'
SLASH_LibKeyBoundSlashCOMMAND3 = '/lkb'
LibKeyBound.initialized = true
end
-- Default color to indicate bindable frames in your mod.
LibKeyBound.colorKeyBoundMode = LibKeyBound.colorKeyBoundMode or { 0, 1, 1, 0.5 }
--[[
LibKeyBound:SetColorKeyBoundMode([r][, g][, b][, a])
--]]
--[[
Arguments:
number - red, default 0
number - green, default 0
number - blue, default 0
number - alpha, default 1
Example:
if (MyMod.keyBoundMode) then
overlayFrame:SetBackdropColor(LibKeyBound:GetColorKeyBoundMode())
end
...
local r, g, b, a = LibKeyBound:GetColorKeyBoundMode()
Notes:
* Returns the color to use on your participating buttons during KeyBound Mode
* Values are unpacked and ready to use as color arguments
--]]
function LibKeyBound:SetColorKeyBoundMode(r, g, b, a)
r, g, b, a = r or 0, g or 0, b or 0, a or 1
LibKeyBound.colorKeyBoundMode[1] = r
LibKeyBound.colorKeyBoundMode[2] = g
LibKeyBound.colorKeyBoundMode[3] = b
LibKeyBound.colorKeyBoundMode[4] = a
LibKeyBound.events:Fire('LIBKEYBOUND_MODE_COLOR_CHANGED')
end
--[[
Returns:
* number - red
* number - green
* number - blue
* number - alpha
Example:
if (MyMod.keyBoundMode) then
overlayFrame:SetBackdropColor(LibKeyBound:GetColorKeyBoundMode())
end
...
local r, g, b, a = LibKeyBound:GetColorKeyBoundMode()
Notes:
* Returns the color to use on your participating buttons during KeyBound Mode
* Values are unpacked and ready to use as color arguments
--]]
function LibKeyBound:GetColorKeyBoundMode()
return unpack(LibKeyBound.colorKeyBoundMode)
end
function LibKeyBound:PLAYER_REGEN_ENABLED()
if self.enabled then
UIErrorsFrame:AddMessage(L.CombatBindingsEnabled, 1, 0.3, 0.3, 1, UIERRORS_HOLD_TIME)
self.dialog:Hide()
end
end
function LibKeyBound:PLAYER_REGEN_DISABLED()
if self.enabled then
self:Set(nil)
UIErrorsFrame:AddMessage(L.CombatBindingsDisabled, 1, 0.3, 0.3, 1, UIERRORS_HOLD_TIME)
self.dialog:Show()
end
end
--[[
Notes:
* Switches KeyBound Mode between on and off
Example:
local LibKeyBound = LibStub('LibKeyBound-1.0')
LibKeyBound:Toggle()
--]]
function LibKeyBound:Toggle()
if (LibKeyBound:IsShown()) then
LibKeyBound:Deactivate()
else
LibKeyBound:Activate()
end
end
--[[
Notes:
* Switches KeyBound Mode to on
Example:
local LibKeyBound = LibStub('LibKeyBound-1.0')
LibKeyBound:Activate()
--]]
function LibKeyBound:Activate()
if not self:IsShown() then
if InCombatLockdown() then
UIErrorsFrame:AddMessage(L.CannotBindInCombat, 1, 0.3, 0.3, 1, UIERRORS_HOLD_TIME)
else
self.enabled = true
if not self.frame then
self.frame = LibKeyBound.Binder:Create()
end
self:Set(nil)
self.dialog:Show()
self.events:Fire('LIBKEYBOUND_ENABLED')
end
end
end
--[[
Notes:
* Switches KeyBound Mode to off
Example:
local LibKeyBound = LibStub('LibKeyBound-1.0')
LibKeyBound:Deactivate()
--]]
function LibKeyBound:Deactivate()
if self:IsShown() then
self.enabled = nil
self:Set(nil)
self.dialog:Hide()
self.events:Fire('LIBKEYBOUND_DISABLED')
end
end
--[[
Returns:
boolean - true if KeyBound Mode is currently on
Example:
local LibKeyBound = LibStub('LibKeyBound-1.0')
local isKeyBoundMode = LibKeyBound:IsShown()
if (isKeyBoundMode) then
-- Do something
else
-- Do another thing
end
Notes:
* Is KeyBound Mode currently on
--]]
function LibKeyBound:IsShown()
return self.enabled
end
--[[
Arguments:
table - the button frame
Example:
local button = this
LibKeyBound:Set(button)
Notes:
* Sets up button for keybinding
* Call this in your OnEnter script for the button
* Current bindings are shown in the tooltip
* Primary binding is shown in green in the button text
--]]
function LibKeyBound:Set(button)
local bindFrame = self.frame
if button and self:IsShown() and not InCombatLockdown() then
bindFrame.button = button
bindFrame:SetAllPoints(button)
bindFrame.text:SetFontObject('GameFontNormalLarge')
bindFrame.text:SetText(button:GetHotkey())
if bindFrame.text:GetStringWidth() > bindFrame:GetWidth() then
bindFrame.text:SetFontObject('GameFontNormal')
end
bindFrame:Show()
bindFrame:OnEnter()
elseif bindFrame then
bindFrame.button = nil
bindFrame:ClearAllPoints()
bindFrame:Hide()
end
end
--[[
Arguments:
string - the keyString to shorten
Returns:
string - the shortened displayString
Example:
local key1 = GetBindingKey(button:GetName())
local displayKey = LibKeyBound:ToShortKey(key1)
return displayKey
Notes:
* Shortens the key text (returned from GetBindingKey etc.)
* Result is suitable for display on a button
* Can be used for your button:GetHotkey() return value
--]]
function LibKeyBound:ToShortKey(key)
if key then
key = key:upper()
key = key:gsub(' ', '')
key = key:gsub('ALT%-', L['Alt'])
key = key:gsub('CTRL%-', L['Ctrl'])
key = key:gsub('SHIFT%-', L['Shift'])
key = key:gsub('NUMPAD', L['NumPad'])
key = key:gsub('PLUS', '%+')
key = key:gsub('MINUS', '%-')
key = key:gsub('MULTIPLY', '%*')
key = key:gsub('DIVIDE', '%/')
key = key:gsub('BACKSPACE', L['Backspace'])
for i = 1, NUM_MOUSE_BUTTONS do
key = key:gsub('BUTTON' .. i, L['Button' .. i])
end
key = key:gsub('CAPSLOCK', L['Capslock'])
key = key:gsub('CLEAR', L['Clear'])
key = key:gsub('DELETE', L['Delete'])
key = key:gsub('END', L['End'])
key = key:gsub('HOME', L['Home'])
key = key:gsub('INSERT', L['Insert'])
key = key:gsub('MOUSEWHEELDOWN', L['Mouse Wheel Down'])
key = key:gsub('MOUSEWHEELUP', L['Mouse Wheel Up'])
key = key:gsub('NUMLOCK', L['Num Lock'])
key = key:gsub('PAGEDOWN', L['Page Down'])
key = key:gsub('PAGEUP', L['Page Up'])
key = key:gsub('SCROLLLOCK', L['Scroll Lock'])
key = key:gsub('SPACEBAR', L['Spacebar'])
key = key:gsub('SPACE', L['Spacebar'])
key = key:gsub('TAB', L['Tab'])
key = key:gsub('DOWNARROW', L['Down Arrow'])
key = key:gsub('LEFTARROW', L['Left Arrow'])
key = key:gsub('RIGHTARROW', L['Right Arrow'])
key = key:gsub('UPARROW', L['Up Arrow'])
return key
end
end
--[[ Binder Widget ]]--
function LibKeyBound.Binder:Create()
local binder = CreateFrame('Button')
binder:RegisterForClicks('anyUp')
binder:SetFrameStrata('DIALOG')
binder:EnableKeyboard(true)
binder:EnableMouseWheel(true)
for k,v in pairs(self) do
binder[k] = v
end
local bg = binder:CreateTexture()
bg:SetTexture(0, 0, 0, 0.5)
bg:SetAllPoints(binder)
local text = binder:CreateFontString('OVERLAY')
text:SetFontObject('GameFontNormalLarge')
text:SetTextColor(0, 1, 0)
text:SetAllPoints(binder)
binder.text = text
binder:SetScript('OnClick', self.OnKeyDown)
binder:SetScript('OnKeyDown', self.OnKeyDown)
binder:SetScript('OnMouseWheel', self.OnMouseWheel)
binder:SetScript('OnEnter', self.OnEnter)
binder:SetScript('OnLeave', self.OnLeave)
binder:SetScript('OnHide', self.OnHide)
binder:Hide()
return binder
end
function LibKeyBound.Binder:OnHide()
LibKeyBound:Set(nil)
end
function LibKeyBound.Binder:OnKeyDown(key)
local button = self.button
if not button then return end
if (key == 'UNKNOWN' or key == 'LSHIFT' or key == 'RSHIFT' or
key == 'LCTRL' or key == 'RCTRL' or key == 'LALT' or key == 'RALT') then
return
end
local screenshotKey = GetBindingKey('SCREENSHOT')
if screenshotKey and key == screenshotKey then
Screenshot()
return
end
local openChatKey = GetBindingKey('OPENCHAT')
if openChatKey and key == openChatKey then
ChatFrameEditBox:Show()
return
end
if key == 'ESCAPE' then
self:ClearBindings(button)
LibKeyBound:Set(button)
return
end
-- dont bind unmodified left or right button
if (key == 'LeftButton' or key == 'RightButton') and not IsModifierKeyDown() then
return
end
--handle mouse button substitutions
if key == 'LeftButton' then
key = 'BUTTON1'
elseif key == 'RightButton' then
key = 'BUTTON2'
elseif key == 'MiddleButton' then
key = 'BUTTON3'
elseif key:match('^Button%d+$') then
key = key:upper()
end
--apply modifiers
if IsModifierKeyDown() then
if IsShiftKeyDown() then
key = 'SHIFT-' .. key
end
if IsControlKeyDown() then
key = 'CTRL-' .. key
end
if IsAltKeyDown() then
key = 'ALT-' .. key
end
end
if button:IsMouseOver() then
self:SetKey(button, key)
LibKeyBound:Set(button)
end
end
function LibKeyBound.Binder:OnMouseWheel(arg1)
if arg1 > 0 then
self:OnKeyDown('MOUSEWHEELUP')
else
self:OnKeyDown('MOUSEWHEELDOWN')
end
end
function LibKeyBound.Binder:OnEnter()
local button = self.button
if button and not InCombatLockdown() then
if self:GetRight() >= (GetScreenWidth() / 2) then
GameTooltip:SetOwner(self, 'ANCHOR_LEFT')
else
GameTooltip:SetOwner(self, 'ANCHOR_RIGHT')
end
if button.GetActionName then
GameTooltip:SetText(button:GetActionName(), 1, 1, 1)
else
GameTooltip:SetText(button:GetName(), 1, 1, 1)
end
local bindings = self:GetBindings(button)
if bindings then
GameTooltip:AddLine(bindings, 0, 1, 0)
GameTooltip:AddLine(L.ClearTip)
else
GameTooltip:AddLine(L.NoKeysBoundTip, 0, 1, 0)
end
GameTooltip:Show()
else
GameTooltip:Hide()
end
end
function LibKeyBound.Binder:OnLeave()
LibKeyBound:Set(nil)
GameTooltip:Hide()
end
--[[ Update Functions ]]--
function LibKeyBound.Binder:ToBinding(button)
return format('CLICK %s:LeftButton', button:GetName())
end
function LibKeyBound.Binder:FreeKey(button, key)
local msg
if button.FreeKey then
local action = button:FreeKey(key)
if button:FreeKey(key) then
msg = format(L.UnboundKey, GetBindingText(key, 'KEY_'), action)
end
else
local action = GetBindingAction(key)
if action and action ~= '' and action ~= self:ToBinding(button) then
msg = format(L.UnboundKey, GetBindingText(key, 'KEY_'), action)
end
end
if msg then
UIErrorsFrame:AddMessage(msg, 1, 0.82, 0, 1, UIERRORS_HOLD_TIME)
end
end
function LibKeyBound.Binder:SetKey(button, key)
if InCombatLockdown() then
UIErrorsFrame:AddMessage(L.CannotBindInCombat, 1, 0.3, 0.3, 1, UIERRORS_HOLD_TIME)
else
self:FreeKey(button, key)
if button.SetKey then
button:SetKey(key)
else
SetBindingClick(key, button:GetName(), 'LeftButton')
end
local msg
if button.GetActionName then
msg = format(L.BoundKey, GetBindingText(key, 'KEY_'), button:GetActionName())
else
msg = format(L.BoundKey, GetBindingText(key, 'KEY_'), button:GetName())
end
UIErrorsFrame:AddMessage(msg, 1, 1, 1, 1, UIERRORS_HOLD_TIME)
end
end
function LibKeyBound.Binder:ClearBindings(button)
if InCombatLockdown() then
UIErrorsFrame:AddMessage(L.CannotBindInCombat, 1, 0.3, 0.3, 1, UIERRORS_HOLD_TIME)
else
if button.ClearBindings then
button:ClearBindings()
else
local binding = self:ToBinding(button)
while (GetBindingKey(binding)) do
SetBinding(GetBindingKey(binding), nil)
end
end
local msg
if button.GetActionName then
msg = format(L.ClearedBindings, button:GetActionName())
else
msg = format(L.ClearedBindings, button:GetName())
end
UIErrorsFrame:AddMessage(msg, 1, 1, 1, 1, UIERRORS_HOLD_TIME)
end
end
function LibKeyBound.Binder:GetBindings(button)
if button.GetBindings then
return button:GetBindings()
end
local keys
local binding = self:ToBinding(button)
for i = 1, select('#', GetBindingKey(binding)) do
local hotKey = select(i, GetBindingKey(binding))
if keys then
keys = keys .. ', ' .. GetBindingText(hotKey, 'KEY_')
else
keys = GetBindingText(hotKey, 'KEY_')
end
end
return keys
end
LibKeyBound.EventButton = LibKeyBound.EventButton or CreateFrame('Frame')
do
local EventButton = LibKeyBound.EventButton
EventButton:UnregisterAllEvents()
EventButton:SetScript('OnEvent', function(self, event, addon)
if (event == 'PLAYER_REGEN_DISABLED') then
LibKeyBound:PLAYER_REGEN_DISABLED()
elseif (event == 'PLAYER_REGEN_ENABLED') then
LibKeyBound:PLAYER_REGEN_ENABLED()
elseif (event == 'PLAYER_LOGIN' and not LibKeyBound.initialized) then
LibKeyBound:Initialize()
EventButton:UnregisterEvent('PLAYER_LOGIN')
end
end)
if IsLoggedIn() and not LibKeyBound.initialized then
LibKeyBound:Initialize()
elseif not LibKeyBound.initialized then
EventButton:RegisterEvent('PLAYER_LOGIN')
end
EventButton:RegisterEvent('PLAYER_REGEN_ENABLED')
EventButton:RegisterEvent('PLAYER_REGEN_DISABLED')
end
| bsd-3-clause |
The-HalcyonDays/darkstar | scripts/globals/items/silken_sash.lua | 36 | 1212 | -----------------------------------------
-- ID: 5632
-- Item: Silken Sash
-- Food Effect: 4 Hrs, All Races
-----------------------------------------
-- TODO: Group Effect
-- HP Recovered while healing +3
-- MP Recovered while healing +5
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
result = 0
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,14400,5632);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_HPHEAL, 3);
target:addMod(MOD_MPHEAL, 5);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_HPHEAL, 3);
target:delMod(MOD_MPHEAL, 5);
end;
| gpl-3.0 |
APItools/monitor | lua/autoswagger/lib/md5.lua | 2 | 8414 | -------------------------------------------------------------------------------
-- MD5 computation in Lua (5.1)
-------------------------------------------------------------------------------
-- bit lib implementions
local floor, abs, max = math.floor, math.abs, math.max
local char, byte, format, rep, sub =
string.char, string.byte, string.format, string.rep, string.sub
local function check_int(n)
-- checking not float
if(n - floor(n) > 0) then
error("trying to use bitwise operation on non-integer!")
end
end
local function tbl2number(tbl)
local n = #tbl
local rslt = 0
local power = 1
for i = 1, n do
rslt = rslt + tbl[i]*power
power = power*2
end
return rslt
end
local function expand(tbl_m, tbl_n)
local big = {}
local small = {}
if(#tbl_m > #tbl_n) then
big = tbl_m
small = tbl_n
else
big = tbl_n
small = tbl_m
end
-- expand small
for i = #small + 1, #big do
small[i] = 0
end
end
local to_bits -- needs to be declared before bit_not
local function bit_not(n)
local tbl = to_bits(n)
local size = max(#tbl, 32)
for i = 1, size do
if(tbl[i] == 1) then
tbl[i] = 0
else
tbl[i] = 1
end
end
return tbl2number(tbl)
end
-- defined as local above
to_bits = function (n)
check_int(n)
if(n < 0) then
-- negative
return to_bits(bit_not(abs(n)) + 1)
end
-- to bits table
local tbl = {}
local cnt = 1
while (n > 0) do
local last = n % 2
if(last == 1) then
tbl[cnt] = 1
else
tbl[cnt] = 0
end
n = (n-last)/2
cnt = cnt + 1
end
return tbl
end
local function bit_or(m, n)
local tbl_m = to_bits(m)
local tbl_n = to_bits(n)
expand(tbl_m, tbl_n)
local tbl = {}
local rslt = max(#tbl_m, #tbl_n)
for i = 1, rslt do
if(tbl_m[i]== 0 and tbl_n[i] == 0) then
tbl[i] = 0
else
tbl[i] = 1
end
end
return tbl2number(tbl)
end
local function bit_and(m, n)
local tbl_m = to_bits(m)
local tbl_n = to_bits(n)
expand(tbl_m, tbl_n)
local tbl = {}
local rslt = max(#tbl_m, #tbl_n)
for i = 1, rslt do
if(tbl_m[i]== 0 or tbl_n[i] == 0) then
tbl[i] = 0
else
tbl[i] = 1
end
end
return tbl2number(tbl)
end
local function bit_xor(m, n)
local tbl_m = to_bits(m)
local tbl_n = to_bits(n)
expand(tbl_m, tbl_n)
local tbl = {}
local rslt = max(#tbl_m, #tbl_n)
for i = 1, rslt do
if(tbl_m[i] ~= tbl_n[i]) then
tbl[i] = 1
else
tbl[i] = 0
end
end
return tbl2number(tbl)
end
local function bit_rshift(n, bits)
check_int(n)
local high_bit = 0
if(n < 0) then
-- negative
n = bit_not(abs(n)) + 1
high_bit = 2147483648 -- 0x80000000
end
for i=1, bits do
n = n/2
n = bit_or(floor(n), high_bit)
end
return floor(n)
end
local function bit_lshift(n, bits)
check_int(n)
if(n < 0) then
-- negative
n = bit_not(abs(n)) + 1
end
for i=1, bits do
n = n*2
end
return bit_and(n, 4294967295) -- 0xFFFFFFFF
end
-- convert little-endian 32-bit int to a 4-char string
local function lei2str(i)
local f=function (s) return char( bit_and( bit_rshift(i, s), 255)) end
return f(0)..f(8)..f(16)..f(24)
end
-- convert raw string to big-endian int
local function str2bei(s)
local v=0
for i=1, #s do
v = v * 256 + byte(s, i)
end
return v
end
-- convert raw string to little-endian int
local function str2lei(s)
local v=0
for i = #s,1,-1 do
v = v*256 + byte(s, i)
end
return v
end
-- cut up a string in little-endian ints of given size
local function cut_le_str(s,...)
local o, r = 1, {}
local args = {...}
for i=1, #args do
table.insert(r, str2lei(sub(s, o, o + args[i] - 1)))
o = o + args[i]
end
return r
end
local swap = function (w) return str2bei(lei2str(w)) end
local function hex2binaryaux(hexval)
return char(tonumber(hexval, 16))
end
local function hex2binary(hex)
local result, _ = hex:gsub('..', hex2binaryaux)
return result
end
-- An MD5 mplementation in Lua, requires bitlib (hacked to use LuaBit from above, ugh)
-- 10/02/2001 jcw@equi4.com
local FF = 0xffffffff
local CONSTS = {
0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee,
0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501,
0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be,
0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821,
0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa,
0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8,
0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed,
0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a,
0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c,
0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70,
0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x04881d05,
0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665,
0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039,
0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1,
0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1,
0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391,
0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476
}
local f=function (x,y,z) return bit_or(bit_and(x,y),bit_and(-x-1,z)) end
local g=function (x,y,z) return bit_or(bit_and(x,z),bit_and(y,-z-1)) end
local h=function (x,y,z) return bit_xor(x,bit_xor(y,z)) end
local i=function (x,y,z) return bit_xor(y,bit_or(x,-z-1)) end
local z=function (f,a,b,c,d,x,s,ac)
a=bit_and(a+f(b,c,d)+x+ac,FF)
-- be *very* careful that left shift does not cause rounding!
return bit_or(bit_lshift(bit_and(a,bit_rshift(FF,s)),s),bit_rshift(a,32-s))+b
end
local function transform(A,B,C,D,X)
local a,b,c,d=A,B,C,D
local t=CONSTS
a=z(f,a,b,c,d,X[ 0], 7,t[ 1])
d=z(f,d,a,b,c,X[ 1],12,t[ 2])
c=z(f,c,d,a,b,X[ 2],17,t[ 3])
b=z(f,b,c,d,a,X[ 3],22,t[ 4])
a=z(f,a,b,c,d,X[ 4], 7,t[ 5])
d=z(f,d,a,b,c,X[ 5],12,t[ 6])
c=z(f,c,d,a,b,X[ 6],17,t[ 7])
b=z(f,b,c,d,a,X[ 7],22,t[ 8])
a=z(f,a,b,c,d,X[ 8], 7,t[ 9])
d=z(f,d,a,b,c,X[ 9],12,t[10])
c=z(f,c,d,a,b,X[10],17,t[11])
b=z(f,b,c,d,a,X[11],22,t[12])
a=z(f,a,b,c,d,X[12], 7,t[13])
d=z(f,d,a,b,c,X[13],12,t[14])
c=z(f,c,d,a,b,X[14],17,t[15])
b=z(f,b,c,d,a,X[15],22,t[16])
a=z(g,a,b,c,d,X[ 1], 5,t[17])
d=z(g,d,a,b,c,X[ 6], 9,t[18])
c=z(g,c,d,a,b,X[11],14,t[19])
b=z(g,b,c,d,a,X[ 0],20,t[20])
a=z(g,a,b,c,d,X[ 5], 5,t[21])
d=z(g,d,a,b,c,X[10], 9,t[22])
c=z(g,c,d,a,b,X[15],14,t[23])
b=z(g,b,c,d,a,X[ 4],20,t[24])
a=z(g,a,b,c,d,X[ 9], 5,t[25])
d=z(g,d,a,b,c,X[14], 9,t[26])
c=z(g,c,d,a,b,X[ 3],14,t[27])
b=z(g,b,c,d,a,X[ 8],20,t[28])
a=z(g,a,b,c,d,X[13], 5,t[29])
d=z(g,d,a,b,c,X[ 2], 9,t[30])
c=z(g,c,d,a,b,X[ 7],14,t[31])
b=z(g,b,c,d,a,X[12],20,t[32])
a=z(h,a,b,c,d,X[ 5], 4,t[33])
d=z(h,d,a,b,c,X[ 8],11,t[34])
c=z(h,c,d,a,b,X[11],16,t[35])
b=z(h,b,c,d,a,X[14],23,t[36])
a=z(h,a,b,c,d,X[ 1], 4,t[37])
d=z(h,d,a,b,c,X[ 4],11,t[38])
c=z(h,c,d,a,b,X[ 7],16,t[39])
b=z(h,b,c,d,a,X[10],23,t[40])
a=z(h,a,b,c,d,X[13], 4,t[41])
d=z(h,d,a,b,c,X[ 0],11,t[42])
c=z(h,c,d,a,b,X[ 3],16,t[43])
b=z(h,b,c,d,a,X[ 6],23,t[44])
a=z(h,a,b,c,d,X[ 9], 4,t[45])
d=z(h,d,a,b,c,X[12],11,t[46])
c=z(h,c,d,a,b,X[15],16,t[47])
b=z(h,b,c,d,a,X[ 2],23,t[48])
a=z(i,a,b,c,d,X[ 0], 6,t[49])
d=z(i,d,a,b,c,X[ 7],10,t[50])
c=z(i,c,d,a,b,X[14],15,t[51])
b=z(i,b,c,d,a,X[ 5],21,t[52])
a=z(i,a,b,c,d,X[12], 6,t[53])
d=z(i,d,a,b,c,X[ 3],10,t[54])
c=z(i,c,d,a,b,X[10],15,t[55])
b=z(i,b,c,d,a,X[ 1],21,t[56])
a=z(i,a,b,c,d,X[ 8], 6,t[57])
d=z(i,d,a,b,c,X[15],10,t[58])
c=z(i,c,d,a,b,X[ 6],15,t[59])
b=z(i,b,c,d,a,X[13],21,t[60])
a=z(i,a,b,c,d,X[ 4], 6,t[61])
d=z(i,d,a,b,c,X[11],10,t[62])
c=z(i,c,d,a,b,X[ 2],15,t[63])
b=z(i,b,c,d,a,X[ 9],21,t[64])
return A+a,B+b,C+c,D+d
end
----------------------------------------------------------------
local md5 = {}
function md5.sumhexa(s)
local msgLen = #s
local padLen = 56 - msgLen % 64
if msgLen % 64 > 56 then padLen = padLen + 64 end
if padLen == 0 then padLen = 64 end
s = s .. char(128) .. rep(char(0),padLen-1) .. lei2str(8*msgLen) .. lei2str(0)
assert(#s % 64 == 0)
local t = CONSTS
local a,b,c,d = t[65],t[66],t[67],t[68]
for i=1,#s,64 do
local X = cut_le_str(sub(s,i,i+63),4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4)
assert(#X == 16)
X[0] = table.remove(X,1) -- zero based!
a,b,c,d = transform(a,b,c,d,X)
end
return format("%08x%08x%08x%08x",swap(a),swap(b),swap(c),swap(d))
end
function md5.sum(s)
return hex2binary(md5.sumhexa(s))
end
return md5
| mit |
The-HalcyonDays/darkstar | scripts/globals/weaponskills/heavy_swing.lua | 30 | 1339 | -----------------------------------
-- Heavy Swing
-- Staff weapon skill
-- Skill Level: 5
-- Deacription:Delivers a single-hit attack. Damage varies with TP.
-- Will stack with Sneak Attack.
-- Aligned with the Thunder Gorget.
-- Aligned with the Thunder Belt.
-- Element: None
-- Modifiers: STR:30%
-- 100%TP 200%TP 300%TP
-- 1.00 1.25 2.25
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/weaponskills");
-----------------------------------
function onUseWeaponSkill(player, target, wsID)
local params = {};
params.numHits = 1;
params.ftp100 = 1; params.ftp200 = 1.25; params.ftp300 = 2.25;
params.str_wsc = 0.3; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0;
params.crit100 = 0.0; params.crit200 = 0.0; params.crit300 = 0.0;
params.canCrit = false;
params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0;
params.atkmulti = 1;
if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then
params.str_wsc = 1.0;
end
local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, params);
damage = damage * WEAPON_SKILL_POWER
return tpHits, extraHits, criticalHit, damage;
end
| gpl-3.0 |
The-HalcyonDays/darkstar | scripts/globals/mobskills/Spike_Flail.lua | 7 | 1247 | ---------------------------------------------------
-- Spike Flail
-- Deals extreme damage in a threefold attack to targets behind the user.
---------------------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/monstertpmoves");
---------------------------------------------------
function onMobSkillCheck(target,mob,skill)
if (mob:hasStatusEffect(EFFECT_MIGHTY_STRIKES)) then
return 1;
elseif (mob:hasStatusEffect(EFFECT_SUPER_BUFF)) then
return 1;
elseif (mob:hasStatusEffect(EFFECT_INVINCIBLE)) then
return 1;
elseif (mob:hasStatusEffect(EFFECT_BLOOD_WEAPON)) then
return 1;
elseif(target:isBehind(mob, 48) == false) then
return 1;
elseif (mob:AnimationSub() == 1) then
return 1;
end
return 0;
end;
function onMobWeaponSkill(target, mob, skill)
local numhits = 1;
local accmod = 2;
local dmgmod = math.random(5,7);
local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_DMG_VARIES,2,3,4);
local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_PHYSICAL,MOBPARAM_SLASH,MOBPARAM_3_SHADOW);
target:delHP(dmg);
return dmg;
end;
| gpl-3.0 |
zhaozg/luvit | tests/test-http-encoder.lua | 14 | 3883 | --[[
Copyright 2014 The Luvit Authors. All Rights Reserved.
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.
--]]
local encoder = require('http-codec').encoder
local deepEqual = require('deep-equal')
local function testEncoder(encoder, inputs)
local outputs = {}
local encode = encoder()
for i = 1, #inputs + 1 do
local chunk = encode(inputs[i])
if chunk and #chunk > 0 then
outputs[#outputs + 1] = chunk
end
end
return outputs
end
require('tap')(function (test)
test("server encoder", function ()
local output = testEncoder(encoder, {
{ code = 200 }
})
p(output)
assert(deepEqual({
"HTTP/1.1 200 OK\r\n\r\n"
}, output))
end)
test("server encoder - Keepalive", function ()
local output = testEncoder(encoder, {
{ code = 200,
{"Content-Length", 12}
},
"Hello World\n",
"",
{ code = 304 },
})
p(output)
assert(deepEqual({
"HTTP/1.1 200 OK\r\nContent-Length: 12\r\n\r\n",
"Hello World\n",
"HTTP/1.1 304 Not Modified\r\n\r\n",
}, output))
end)
test("server encoder - Chunked Encoding, explicit end", function ()
local output = testEncoder(encoder, {
{ code = 200,
{"Transfer-Encoding", "chunked"}
},
"Hello World\n",
"Another Chunk",
"",
{ code = 304 },
})
p(output)
assert(deepEqual({
"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n",
"c\r\nHello World\n\r\n",
"d\r\nAnother Chunk\r\n",
"0\r\n\r\n",
"HTTP/1.1 304 Not Modified\r\n\r\n",
}, output))
end)
test("server encoder - Chunked Encoding, auto end", function ()
local output = testEncoder(encoder, {
{ code = 200,
{"Transfer-Encoding", "chunked"}
},
"Hello World\n",
"Another Chunk",
})
p(output)
assert(deepEqual({
"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n",
"c\r\nHello World\n\r\n",
"d\r\nAnother Chunk\r\n",
"0\r\n\r\n",
}, output))
end)
test("server encoder - Chunked Encoding, auto keepalive end", function ()
local output = testEncoder(encoder, {
{ code = 200,
{"Transfer-Encoding", "chunked"}
},
"Hello World\n",
"Another Chunk",
{ code = 304 },
})
p(output)
assert(deepEqual({
"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n",
"c\r\nHello World\n\r\n",
"d\r\nAnother Chunk\r\n",
"0\r\n\r\nHTTP/1.1 304 Not Modified\r\n\r\n",
}, output))
end)
test("client encoder", function ()
local output = testEncoder(encoder, {
{ method = "GET", path = "/my-resource",
{"Accept", "*/*"}
},
"",
{ method = "GET", path = "/favicon.ico",
{"Accept", "*/*"}
},
{ method = "GET", path = "/orgs/luvit",
{"User-Agent", "Luvit Unit Tests"},
{"Host", "api.github.com"},
{"Accept", "*/*"},
{"Authorization", "token 6d2fc6ae08215d69d693f5ca76ea87c7780a4275"},
}
})
p(output)
assert(deepEqual({
"GET /my-resource HTTP/1.1\r\nAccept: */*\r\n\r\n",
"GET /favicon.ico HTTP/1.1\r\nAccept: */*\r\n\r\n",
"GET /orgs/luvit HTTP/1.1\r\nUser-Agent: Luvit Unit Tests\r\nHost: api.github.com\r\nAccept: */*\r\nAuthorization: token 6d2fc6ae08215d69d693f5ca76ea87c7780a4275\r\n\r\n"
}, output))
end)
end)
| apache-2.0 |
The-HalcyonDays/darkstar | scripts/globals/items/burning_cesti.lua | 16 | 1030 | -----------------------------------------
-- ID: 16398
-- Item: Burning Cesti
-- Additional Effect: Fire Damage
-----------------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------
-- onAdditionalEffect Action
-----------------------------------
function onAdditionalEffect(player,target,damage)
local chance = 5;
if (math.random(0,99) >= chance) then
return 0,0,0;
else
local dmg = math.random(3,10);
local params = {};
params.bonusmab = 0;
params.includemab = false;
dmg = addBonusesAbility(player, ELE_FIRE, target, dmg, params);
dmg = dmg * applyResistanceAddEffect(player,target,ELE_FIRE,0);
dmg = adjustForTarget(target,dmg,ELE_FIRE);
dmg = finalMagicNonSpellAdjustments(player,target,ELE_FIRE,dmg);
local message = 163;
if (dmg < 0) then
message = 167;
end
return SUBEFFECT_FIRE_DAMAGE,message,dmg;
end
end; | gpl-3.0 |
The-HalcyonDays/darkstar | scripts/zones/The_Garden_of_RuHmet/Zone.lua | 9 | 11407 | -----------------------------------
--
-- Zone: The_Garden_of_RuHmet (35)
--
-----------------------------------
package.loaded["scripts/zones/The_Garden_of_RuHmet/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/zones/The_Garden_of_RuHmet/TextIDs");
require("scripts/zones/The_Garden_of_RuHmet/MobIDs");
require("scripts/globals/missions");
require("scripts/globals/keyitems");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
zone:registerRegion(1, -421, -2, 377, -417, 0, 381); -- RDC
zone:registerRegion(2, -422, -2, -422, -418, 0, -418); -- +1
zone:registerRegion(3, 418, -2, 378, 422, 0, 382); -- +2
zone:registerRegion(4, -506,-4,697, -500,4,703);--hume niv 0 150 vers niv 1
zone:registerRegion(5, -507,-4,-103, -501,4,-97);--hume niv 1 158 vers niv 0
zone:registerRegion(6, -339,-4,-103, -332,4,-97);--hume niv 1 159 vers niv 2
zone:registerRegion(7, 501,-4,697, 507,4,702);--hume niv 2 169 vers niv 1
zone:registerRegion(8, 332,-4,696, 339,4,702);--hume niv 2 168 vers niv 3
zone:registerRegion(9, 332,-4,-102, 338,4,-97);--hume niv 3 178 vers niv 2
zone:registerRegion(10, -102,-4,541, -96,4,546);--elvaan niv 0 151 vers niv 1
zone:registerRegion(11, -103,-4,-259, -96,4,-252);--elvaan niv 1 160 vers niv 0
zone:registerRegion(12, -103,-4,-427, -67,4,-420);--elvaan niv 1 161 vers niv 2
zone:registerRegion(13, 736,-4,372, 742,4,379);--elvaan niv 2 171 vers niv 1
zone:registerRegion(14, 736,-4,540, 743,4,546);--elvaan niv 2 170 vers niv 3
zone:registerRegion(15, 737,-4,-259, 743,4,-252);--elvaan niv 3 179 vers niv 2
zone:registerRegion(16, -178,-4,97, -173,4,103);--galka niv 0 152 vers niv 1
zone:registerRegion(17, -178,-4,-703, -173,4,-697);--galka niv 1 162 vers niv 0
zone:registerRegion(18, -347,-4,-703, -340,4,-696);--galka niv 1 163 vers niv 2
zone:registerRegion(19, 492,-4,96, 499,4,103);--galka niv 2 173 vers niv 1
zone:registerRegion(20, 660,-4,96, 667,4,102);--galka niv 2 172 vers niv 3
zone:registerRegion(21, 660,-4,-702, 667,4,-697);--galka niv 3 180 vers niv 2
zone:registerRegion(22, -498,-4,97, -492,4,102);--taru niv 0 153 vers niv 1
zone:registerRegion(23, -499,-4,-703, -492,4,-697);--taru niv 1 164 vers niv 0
zone:registerRegion(24, -667,-4,-703, -661,4,-696);--taru niv 1 165 vers niv 2
zone:registerRegion(25, 172,-4,96, 178,4,102);--taru niv 2 175 vers niv 1
zone:registerRegion(26, 340,-4,97, 347,4,102);--taru niv 2 174 vers niv 3
zone:registerRegion(27, 340,-4,-703, 347,4,-697);--taru niv 3 181 vers niv 2
zone:registerRegion(28, -742,-4,373, -736,4,379);--mithra niv 0 154 vers niv 1
zone:registerRegion(29, -743,-4,-427, -736,4,-421);--mithra niv 1 166 vers niv 0
zone:registerRegion(30, -742,-4,-259, -737,4,-252);--mithra niv 1 167 vers niv 2
zone:registerRegion(31, 97,-4,541, 102,4,547);--mithra niv 2 177 vers niv 1
zone:registerRegion(32, 97,-4,372, 102,4,379);--mithra niv 2 176 vers niv 3
zone:registerRegion(33, 97,-4,-427, 102,4,-421);--mithra niv 3 182 vers niv 2
-- Give the Fortitude ??? a random spawn
local qm1 = GetNPCByID(Jailer_of_Fortitude_QM);
local qm1position = math.random(1,5);
qm1:setPos(Jailer_of_Fortitude_QM_POS[qm1position][1], Jailer_of_Fortitude_QM_POS[qm1position][2], Jailer_of_Fortitude_QM_POS[qm1position][3]);
--Give the Faith ??? a random spawn
local qm3 = GetNPCByID(Jailer_of_Faith_QM);
local qm3position = math.random(1,5);
qm3:setPos(Jailer_of_Faith_QM_POS[qm3position][1], Jailer_of_Faith_QM_POS[qm3position][2], Jailer_of_Faith_QM_POS[qm3position][3]);
end;
-----------------------------------
-- onGameHour
-----------------------------------
function onGameHour(npc, mob, player)
local VanadielHour = VanadielHour();
local qm2 = GetNPCByID(16921028); -- Jailer of Faith
local qm3 = GetNPCByID(16921029); -- Ix'aern drk
local s = math.random(6,12) -- wait time till change to next spawn pos, random 15~30 mins.
-- Jailer of Fortitude spawn randomiser
if (VanadielHour % 6 == 0) then
local qm1 = GetNPCByID(Jailer_of_Fortitude_QM);
qm1:hideNPC(60);
local qm1position = math.random(1,5);
qm1:setPos(Jailer_of_Fortitude_QM_POS[qm1position][1], Jailer_of_Fortitude_QM_POS[qm1position][2], Jailer_of_Fortitude_QM_POS[qm1position][3]);
end
-- Jailer of Faith spawn randomiser
if (VanadielHour % s == 0) then
-- Get the ??? NPC
local qm3 = GetNPCByID(Jailer_of_Faith_QM);
-- Hide it for 60 seconds
qm3:hideNPC(60);
-- Get a new random position from the possible places
local qm3position = math.random(1,5);
-- Set the new ??? place
qm3:setPos(Jailer_of_Faith_QM_POS[qm3position][1], Jailer_of_Faith_QM_POS[qm3position][2], Jailer_of_Faith_QM_POS[qm3position][3]);
end
--[[
-- Ix'DRK spawn randomiser
if(VanadielHour % 6 == 0) then -- Change ??? position every 6 hours Vana'diel time (~15 mins)
local qm2p = math.random(1,4); -- random for next @pos. -- start in spawn pos 1.
--print(qm2p)
qm3:hideNPC(30);
if (qm2p == 1) then
qm2:setPos(-240,5.00,440); -- spawn point 1 "Hume-Elvaan"
SetServerVariable("[POSI]Ix_aern_drk",1);
--printf("Qm2 is at pos 1");
elseif (qm2p == 2) then
qm2:setPos(-280,5.00,240); -- spawn point 2 "Elvaan-Galka"
SetServerVariable("[POSI]Ix_aern_drk",2);
--printf("Qm2 is at pos 2");
elseif (qm2p == 3) then
qm2:setPos(-560,5.00,239); -- spawn point 3 "Taru-Mithra"
SetServerVariable("[POSI]Ix_aern_drk",3);
--printf("Qm2 is at pos 3");
elseif (qm2p == 4) then
qm2:setPos(-600,5.00,440); -- spawn point 4 "Mithra-Hume"
SetServerVariable("[POSI]Ix_aern_drk",4);
--printf("Qm2 is at pos 4");
end
end ]]--
end;
-----------------------------------
-- onConquestUpdate
-----------------------------------
function onConquestUpdate(zone, updatetype)
local players = zone:getPlayers();
for name, player in pairs(players) do
conquestUpdate(zone, player, updatetype, CONQUEST_BASE);
end
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
local cs = -1;
if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then
player:setPos(-351.136,-2.25,-380,253);
end
if(player:getCurrentMission(COP) == WHEN_ANGELS_FALL and player:getVar("PromathiaStatus")==0)then
cs = 0x00C9 ;
end
player:setVar("Ru-Hmet-TP",0);
return cs;
end;
-----------------------------------
-- onRegionEnter
-----------------------------------
function onRegionEnter(player,region)
if(player:getVar("Ru-Hmet-TP")==0 and player:getAnimation()==0)then
switch (region:GetRegionID()): caseof
{
[1] = function (x)
if(player:getCurrentMission(COP)==DAWN or player:hasCompletedMission(COP,DAWN) or player:hasCompletedMission(COP,THE_LAST_VERSE) )then
player:startEvent(0x0065);
else
player:startEvent(0x009B);
end
end, --101
[2] = function (x)
if(player:hasKeyItem(BRAND_OF_DAWN) and player:hasKeyItem(BRAND_OF_TWILIGHT))then
player:startEvent(0x009C);
else
player:startEvent(0x00B7);
end
end, --102
[3] = function (x)
player:startEvent(0x0067);
end, --103
[4] = function (x) player:startEvent(0x0096);end,--hume niv 0 150 vers niv 1
[5] = function (x) player:startEvent(0x009E);end,--hume niv 1 158 vers niv 0
[6] = function (x) player:startEvent(0x009F);end,--hume niv 1 159 vers niv 2
[7] = function (x) player:startEvent(0x00A9);end,--hume niv 2 169 vers niv 1
[8] = function (x) player:startEvent(0x00A8);end,--hume niv 2 168 vers niv 3
[9] = function (x) player:startEvent(0x00B2);end,--hume niv 3 178 vers niv 2
[10] = function (x) player:startEvent(0x0097);end,--elvaan niv 0 151 vers niv 1
[11] = function (x) player:startEvent(0x00A0);end,--elvaan niv 1 160 vers niv 0
[12] = function (x) player:startEvent(0x00A1);end,--elvaan niv 1 161 vers niv 2
[13] = function (x) player:startEvent(0x00AB);end,--elvaan niv 2 171 vers niv 1
[14] = function (x) player:startEvent(0x00AA);end,--elvaan niv 2 170 vers niv 3
[15] = function (x) player:startEvent(0x00B3);end,--elvaan niv 3 179 vers niv 2
[16] = function (x) player:startEvent(0x0098);end,--galka niv 0 152 vers niv 1
[17] = function (x) player:startEvent(0x00A2);end,--galka niv 1 162 vers niv 0
[18] = function (x) player:startEvent(0x00A3);end,--galka niv 1 163 vers niv 2
[19] = function (x) player:startEvent(0x00AD);end,--galka niv 2 173 vers niv 1
[20] = function (x) player:startEvent(0x00AC);end,--galka niv 2 172 vers niv 3
[21] = function (x) player:startEvent(0x00B4);end,--galka niv 3 180 vers niv 2
[22] = function (x) player:startEvent(0x0099);end,--taru niv 0 153 vers niv 1
[23] = function (x) player:startEvent(0x00A4);end,--taru niv 1 164 vers niv 0
[24] = function (x) player:startEvent(0x00A5);end,--taru niv 1 165 vers niv 2
[25] = function (x) player:startEvent(0x00AF);end,--taru niv 2 175 vers niv 1
[26] = function (x) player:startEvent(0x00AE);end,--taru niv 2 174 vers niv 3
[27] = function (x) player:startEvent(0x00B5);end,--taru niv 3 181 vers niv 2
[28] = function (x) player:startEvent(0x009A);end,--mithra niv 0 154 vers niv 1
[29] = function (x) player:startEvent(0x00A6);end,--mithra niv 1 166 vers niv 0
[30] = function (x) player:startEvent(0x00A7);end,--mithra niv 1 167 vers niv 2
[31] = function (x) player:startEvent(0x00B1);end,--mithra niv 2 177 vers niv 1
[32] = function (x) player:startEvent(0x00B0);end,--mithra niv 2 176 vers niv 3
[33] = function (x) player:startEvent(0x00B6);end,--mithra niv 3 182 vers niv 2
}
end
end;
-----------------------------------
-- onRegionLeave
-----------------------------------
function onRegionLeave(player,region)
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if((csid >0x0095 and csid < 0x00B8)or csid ==0x0066 or csid ==0x0067 or csid ==0x0065)then
player:setVar("Ru-Hmet-TP",1);
end
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if(csid == 0x0065 and option == 1) then
player:setPos(540,-1,-499.900,62,0x24);
player:setVar("Ru-Hmet-TP",0);
elseif((csid >0x0095 and csid < 0x00B8)or csid ==0x0066 or csid ==0x0067 or csid == 0x0065 )then
player:setVar("Ru-Hmet-TP",0);
elseif(csid ==0x00C9)then
player:setVar("PromathiaStatus",1);
end
if(csid == 0x7d00 and option==1)then
player:setPos(420,0,398,68);
end
end; | gpl-3.0 |
The-HalcyonDays/darkstar | scripts/zones/East_Ronfaure_[S]/npcs/qm5.lua | 27 | 1615 | -----------------------------------
-- Area: East Ronfaure [S]
-- NPC: qm5 "???"
-- Involved in Quests: Steamed Rams
-- @pos 380.015 -26.5 -22.525
-----------------------------------
package.loaded["scripts/zones/East_Ronfaure_[S]/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/keyitems");
require("scripts/globals/campaign");
require("scripts/zones/East_Ronfaure_[S]/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getQuestStatus(CRYSTAL_WAR,STEAMED_RAMS) == QUEST_ACCEPTED) then
if (player:hasKeyItem(OXIDIZED_PLATE)) then
player:messageSpecial(NOTHING_OUT_OF_ORDINARY);
else
player:startEvent(0x0003);
end
else
player:messageSpecial(NOTHING_OUT_OF_ORDINARY);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish Action
-----------------------------------
function onEventFinish(player,csid,option)
-- print("CSID:",csid);
-- print("RESULT:",option);
if (csid == 0x0003) then
player:addKeyItem(OXIDIZED_PLATE);
player:messageSpecial(KEYITEM_OBTAINED,OXIDIZED_PLATE);
end
end; | gpl-3.0 |
The-HalcyonDays/darkstar | scripts/globals/items/bowl_of_sunset_soup.lua | 35 | 1498 | -----------------------------------------
-- ID: 4341
-- Item: bowl_of_sunset_soup
-- Food Effect: 4Hrs, All Races
-----------------------------------------
-- Agility 3
-- Vitality -1
-- HP Recovered While Healing 5
-- Ranged Accuracy % 9 (cap 20)
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,14400,4341);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_AGI, 3);
target:addMod(MOD_VIT, -1);
target:addMod(MOD_HPHEAL, 5);
target:addMod(MOD_FOOD_RACCP, 9);
target:addMod(MOD_FOOD_RACC_CAP, 20);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_AGI, 3);
target:delMod(MOD_VIT, -1);
target:delMod(MOD_HPHEAL, 5);
target:delMod(MOD_FOOD_RACCP, 9);
target:delMod(MOD_FOOD_RACC_CAP, 20);
end;
| gpl-3.0 |
The-HalcyonDays/darkstar | scripts/zones/Dynamis-Beaucedine/mobs/Goblin_Statue.lua | 15 | 3353 | -----------------------------------
-- Area: Dynamis Beaucedine
-- NPC: Goblin Statue
-- Map Position: http://images1.wikia.nocookie.net/__cb20090312005233/ffxi/images/thumb/b/b6/Bea.jpg/375px-Bea.jpg
-----------------------------------
package.loaded["scripts/zones/Dynamis-Beaucedine/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/dynamis");
require("scripts/zones/Dynamis-Beaucedine/TextIDs");
-----------------------------------
-- onMobSpawn Action
-----------------------------------
function onMobSpawn(mob)
mob:setMobMod(MOBMOD_SUPERLINK, mob:getShortID());
end;
-----------------------------------
-- onMobEngaged
-----------------------------------
function onMobEngaged(mob,target)
local X = mob:getXPos();
local Y = mob:getYPos();
local Z = mob:getZPos();
local spawnList = beaucedineGoblinList;
if(mob:getStatPoppedMobs() == false) then
mob:setStatPoppedMobs(true);
for nb = 1, table.getn(spawnList), 2 do
if(mob:getID() == spawnList[nb]) then
for nbi = 1, table.getn(spawnList[nb + 1]), 1 do
if((nbi % 2) == 0) then X=X+2; Z=Z+2; else X=X-2; Z=Z-2; end
local mobNBR = spawnList[nb + 1][nbi];
if(mobNBR <= 20) then
if(mobNBR == 0) then mobNBR = math.random(1,15); end -- Spawn random Vanguard (TEMPORARY)
local DynaMob = getDynaMob(target,mobNBR,2);
if(DynaMob ~= nil) then
-- Spawn Mob
SpawnMob(DynaMob):setMobMod(MOBMOD_SUPERLINK, mob:getShortID());
GetMobByID(DynaMob):setPos(X,Y,Z);
GetMobByID(DynaMob):setSpawn(X,Y,Z);
-- Spawn Pet for BST, DRG, and SMN
if(mobNBR == 9 or mobNBR == 15) then
SpawnMob(DynaMob + 1):setMobMod(MOBMOD_SUPERLINK, mob:getShortID());
GetMobByID(DynaMob + 1):setPos(X,Y,Z);
GetMobByID(DynaMob + 1):setSpawn(X,Y,Z);
end
end
elseif(mobNBR > 20) then
SpawnMob(mobNBR):setMobMod(MOBMOD_SUPERLINK, mob:getShortID());
local MJob = GetMobByID(mobNBR):getMainJob();
if(MJob == 9 or MJob == 15) then
-- Spawn Pet for BST, DRG, and SMN
SpawnMob(mobNBR + 1):setMobMod(MOBMOD_SUPERLINK, mob:getShortID());
GetMobByID(mobNBR + 1):setPos(X,Y,Z);
GetMobByID(mobNBR + 1):setSpawn(X,Y,Z);
end
end
end
end
end
end
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob,killer)
local mobID = mob:getID();
-- Time Bonus: 031 046
if(mobID == 17326860 and mob:isInBattlefieldList() == false) then
killer:addTimeToDynamis(15);
mob:addInBattlefieldList();
elseif(mobID == 17326875 and mob:isInBattlefieldList() == false) then
killer:addTimeToDynamis(15);
mob:addInBattlefieldList();
-- HP Bonus: 037 041 044 051 053
elseif(mobID == 17326866 or mobID == 17326870 or mobID == 17326873 or mobID == 17326880 or mobID == 17326882) then
killer:restoreHP(2000);
killer:messageBasic(024,(killer:getMaxHP()-killer:getHP()));
-- MP Bonus: 038 040 045 049 052 104
elseif(mobID == 17326867 or mobID == 17326869 or mobID == 17326874 or mobID == 17326878 or mobID == 17326881 or mobID == 17326933) then
killer:restoreMP(2000);
killer:messageBasic(025,(killer:getMaxMP()-killer:getMP()));
end
end; | gpl-3.0 |
The-HalcyonDays/darkstar | scripts/globals/mobskills/Foxfire.lua | 7 | 1177 | ---------------------------------------------
-- Foxfire
--
-- Description: Damage varies with TP. Additional effect: "Stun."
-- Type: Physical (Blunt)
-- RDM, THF, PLD, BST, BRD, RNG, NIN, and COR fomors).
--
---------------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/monstertpmoves");
---------------------------------------------
function onMobSkillCheck(target,mob,skill)
local job = mob:getMainJob();
if(job == JOB_RDM or job == JOB_THF or job == JOB_PLD or job == JOB_BST or job == JOB_RNG or job == JOB_BRD or job == JOB_NIN or job == JOB_COR) then
return 0;
end
return 1;
end;
function onMobWeaponSkill(target, mob, skill)
local numhits = 1;
local accmod = 1;
local dmgmod = 2.6;
local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_DMG_VARIES,1,2,3);
local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_PHYSICAL,MOBPARAM_BLUNT,info.hitslanded);
local typeEffect = EFFECT_STUN;
MobPhysicalStatusEffectMove(mob, target, skill, typeEffect, 1, 0, 6);
target:delHP(dmg);
return dmg;
end;
| gpl-3.0 |
kesor/wow-binder | Priest.lua | 1 | 3542 | local _, Binder = ...
local m1 = Binder.m1 -- Modifier.lua
local m2 = Binder.m2 -- Modifier.lua
Binder.priest = {}
Binder.priest["macros"] = {
["Mind Sear"] = "#showtooltip Mind Sear\n/cast [nochanneling: Mind Sear] Mind Sear",
["Mass Dispel"] = "#showtooltip Mass Dispel\n/cast !Mass Dispel",
["Lightwell"] = "#showtooltip Lightwell\n/cast !Lightwell",
["Mind Flay"] = "#showtooltip Mind Flay\n/cast [nochanneling: Mind Flay] Mind Flay",
}
Binder.priest["keybinds"] = {
["Fear Ward"] = { key = "`" },
["Smite"] = { key = "1" },
["Holy Fire"] = { key = "2" },
["Mind Spike"] = { key = "3" },
["Mind Blast"] = { key = "4" },
["Shadow Word: Death"] = { key = "5" },
["Greater Heal"] = { key = "C" },
["Mind Control"] = { key = "F" },
["Divine Hymn"] = { key = "H" },
["Prayer of Mending"] = { key = "R" },
["Fade"] = { key = "T" },
["Flash Heal"] = { key = "V" },
["Heal"] = { key = "X" },
["Leap of Faith"] = { key = "Z" },
["Mind Sear"] = { key = m1.."4" },
["Mind Soothe"] = { key = m1.."A" },
["Mind Vision"] = { key = m1.."C" },
["Inner Fire"] = { key = m1.."E" },
["Prayer of Healing"] = { key = m1.."F" },
["Power Word: Fortitude"] = { key = m1.."G" },
["Inner Will"] = { key = m1.."Q" },
["Hymn of Hope"] = { key = m1.."R" },
["Shackle Undead"] = { key = m1.."S" },
["Shadowfiend"] = { key = m1.."X" },
["Cure Disease"] = { key = m2.."2" },
["Archangel"] = { key = m2.."3" },
["Holy Nova"] = { key = m2.."4" },
["Levitate"] = { key = m2.."5" },
["Mana Burn"] = { key = m2.."A" },
["Renew"] = { key = m2.."C" },
["Devouring Plague"] = { key = m2.."D" },
["Dispel Magic"] = { key = m2.."E" },
["Psychic Scream"] = { key = m2.."F" },
["Shadow Protection"] = { key = m2.."G" },
["Resurrection"] = { key = m2.."L" },
["Power Word: Shield"] = { key = m2.."R" },
["Shadow Word: Pain"] = { key = m2.."S" },
["Desperate Prayer"] = { key = m2.."T" },
["Mass Dispel"] = { key = m2.."V" },
["Binding Heal"] = { key = m2.."X" },
}
Binder.priest["shadow keybinds"] = {
["Psychic Horror"] = { key = "6" },
["Silence"] = { key = "E" },
["Mind Flay"] = { key = "Q" },
["Shadowform"] = { key = m1.."W" },
["Vampiric Touch"] = { key = m2.."Q" },
["Vampiric Embrace"] = { key = m2.."T" },
["Dispersion"] = { key = m2.."Z" },
}
Binder.priest["holy keybinds"] = {
["Lightwell"] = { key = "6" },
["Holy Word: Chastise"] = { key = "E" },
["Circle of Healing"] = { key = "Q" },
["Chakra"] = { key = m2.."Q" },
["Guardian Spirit"] = { key = m2.."Z" },
}
Binder.priest["discipline keybinds"] = {
["Inner Focus"] = { key = "6" },
["Power Word: Barrier"] = { key = "E" },
["Penance"] = { key = "Q" },
["Power Infusion"] = { key = m2.."Q" },
["Pain Suppression"] = { key = m2.."Z" },
}
| bsd-3-clause |
The-HalcyonDays/darkstar | scripts/zones/Periqia/IDs.lua | 49 | 3842 | Periqia = {
text = {
-- General Texts
ITEM_CANNOT_BE_OBTAINED = 6378, -- You cannot obtain the item <item> come back again after sorting your inventory
ITEM_OBTAINED = 6381, -- Obtained: <item>
GIL_OBTAINED = 6384, -- Obtained <number> gil
KEYITEM_OBTAINED = 6384, -- Obtained key item: <keyitem>
-- Assault Texts
ASSAULT_31_START = 7447,
ASSAULT_32_START = 7448,
ASSAULT_33_START = 7449,
ASSAULT_34_START = 7450,
ASSAULT_35_START = 7451,
ASSAULT_36_START = 7452,
ASSAULT_37_START = 7453,
ASSAULT_38_START = 7454,
ASSAULT_39_START = 7455,
ASSAULT_40_START = 7456,
TIME_TO_COMPLETE = 7477,
MISSION_FAILED = 7478,
RUNE_UNLOCKED_POS = 7479,
RUNE_UNLOCKED = 7480,
ASSAULT_POINTS_OBTAINED = 7481,
TIME_REMAINING_MINUTES = 7482,
TIME_REMAINING_SECONDS = 7483,
PARTY_FALLEN = 7485,
-- Seagull Grounded
EXCALIACE_START = 7494,
EXCALIACE_END1 = 7495,
EXCALIACE_END2 = 7496,
EXCALIACE_ESCAPE = 7497,
EXCALIACE_PAIN1 = 7498,
EXCALIACE_PAIN2 = 7499,
EXCALIACE_PAIN3 = 7500,
EXCALIACE_PAIN4 = 7501,
EXCALIACE_PAIN5 = 7502,
EXCALIACE_CRAB1 = 7503,
EXCALIACE_CRAB2 = 7504,
EXCALIACE_CRAB3 = 7505,
EXCALIACE_DEBAUCHER1 = 7506,
EXCALIACE_DEBAUCHER2 = 7507,
EXCALIACE_RUN = 7508,
EXCALIACE_TOO_CLOSE = 7509,
EXCALIACE_TIRED = 7510,
EXCALIACE_CAUGHT = 7511,
},
mobs = {
-- Seagull Grounded
[31] = {
CRAB1 = 17006594,
CRAB2 = 17006595,
CRAB3 = 17006596,
CRAB4 = 17006597,
CRAB5 = 17006598,
CRAB6 = 17006599,
CRAB7 = 17006600,
CRAB8 = 17006601,
CRAB9 = 17006602,
DEBAUCHER1 = 17006603,
PUGIL1 = 17006604,
PUGIL2 = 17006605,
PUGIL3 = 17006606,
PUGIL4 = 17006607,
PUGIL5 = 17006608,
DEBAUCHER2 = 17006610,
DEBAUCHER3 = 17006611,
}
},
npcs = {
EXCALIACE = 17006593,
ANCIENT_LOCKBOX = 17006809,
RUNE_OF_RELEASE = 17006810,
_1K1 = 17006836,
_1K2 = 17006837,
_1K3 = 17006838,
_1K4 = 17006839,
_1K5 = 17006840,
_1K6 = 17006841,
_1K7 = 17006842,
_1K8 = 17006843,
_1K9 = 17006844,
_1KA = 17006845,
_1KB = 17006846,
_1KC = 17006847,
_1KD = 17006848,
_1KE = 17006849,
_1KF = 17006850,
_1KG = 17006851,
_1KH = 17006852,
_1KI = 17006853,
_1KJ = 17006854,
_1KK = 17006855,
_1KL = 17006856,
_1KM = 17006857,
_1KN = 17006858,
_1KO = 17006859,
_1KP = 17006860,
_1KQ = 17006861,
_1KR = 17006862,
_1KS = 17006863,
_1KT = 17006864,
_1KU = 17006865,
_1KV = 17006866,
_1KW = 17006867,
_1KX = 17006868,
_1KY = 17006869,
_1KZ = 17006870,
_JK0 = 17006871,
_JK1 = 17006872,
_JK2 = 17006873,
_JK3 = 17006874,
_JK4 = 17006875,
_JK5 = 17006876,
_JK6 = 17006877,
_JK7 = 17006878,
_JK8 = 17006879,
_JK9 = 17006880,
_JKA = 17006881,
_JKB = 17006882,
_JKC = 17006883,
_JKD = 17006884,
_JKE = 17006885,
_JKF = 17006886,
_JKG = 17006887,
_JKH = 17006888,
_JKI = 17006889,
_JKJ = 17006890,
_JKK = 17006891,
_JKL = 17006892,
_JKM = 17006893,
_JKN = 17006894,
_JKO = 17006895,
}
} | gpl-3.0 |
The-HalcyonDays/darkstar | scripts/zones/Al_Zahbi/npcs/Suldiran.lua | 17 | 1811 | -----------------------------------
-- Area: Al Zahbi
-- NPC: Suldiran
-- Type: NPC Quest
-- @zone: 48
-- @pos 41.658 -6.999 -42.528
--
-- Auto-Script: Requires Verification (Verified by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Al_Zahbi/TextIDs"] = nil;
require("scripts/globals/quests");
require("scripts/globals/settings");
require("scripts/globals/titles");
require("scripts/zones/Al_Zahbi/TextIDs");
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if(player:getQuestStatus(AHT_URHGAN,FEAR_OF_THE_DARK_II) ~= QUEST_AVAILABLE) then
if(trade:hasItemQty(2163,2) and trade:getItemCount() == 2) then
player:startEvent(0x0010);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if(player:getQuestStatus(AHT_URHGAN,FEAR_OF_THE_DARK_II) == QUEST_AVAILABLE) then
player:startEvent(0x000e);
else
player:startEvent(0x000f);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
if(csid == 0x000e and option == 1) then
player:addQuest(AHT_URHGAN,FEAR_OF_THE_DARK_II);
elseif(csid == 0x0010) then
player:tradeComplete();
player:addGil(GIL_RATE*200);
player:messageSpecial(GIL_OBTAINED,GIL_RATE*200);
player:addTitle(DARK_RESISTANT);
if(player:getQuestStatus(AHT_URHGAN,FEAR_OF_THE_DARK_II) == QUEST_ACCEPTED)then
player:completeQuest(AHT_URHGAN,FEAR_OF_THE_DARK_II);
end
end
end;
| gpl-3.0 |
otservme/global1053 | data/movements/scripts/pits of inferno quest/pitsOfInfernoQuestThrones.lua | 1 | 1275 | local thrones = {
[2080] = {text = "You have touched Infernatil's throne and absorbed some of his spirit.", animation = CONST_ME_FIRE},
[2081] = {text = "You have touched Tafariel's throne and absorbed some of his spirit.'", animation = CONST_ME_DEATH},
[2082] = {text = "You have touched Verminor's throne and absorbed some of his spirit.", animation = CONST_ME_POISON},
[2083] = {text = "You have touched Apocalypse's throne and absorbed some of his spirit.", animation = CONST_ME_EXPLOSION},
[2084] = {text = "You have touched Bazir's throne and absorbed some of his spirit.", animation = CONST_ME_MAGIC_GREEN},
[2085] = {text = "You have touched Ashfalor's throne and absorbed some of his spirit.", animation = CONST_ME_FIRE},
[2086] = {text = "You have touched Pumin's throne and absorbed some of his spirit.", animation = CONST_ME_DEATH}
}
function onStepIn(cid, item, position, lastPosition)
if(getPlayerStorageValue(cid, item.uid) < 1) then
setPlayerStorageValue(cid, item.uid, 1)
doSendMagicEffect(position, thrones[item.uid].animation)
doCreatureSay(cid, thrones[item.uid].text, TALKTYPE_ORANGE_1)
else
doPlayerSendTextMessage(cid, MESSAGE_EVENT_ADVANCE, "You've already absorbed energy from this throne.")
end
return true
end | gpl-2.0 |
The-HalcyonDays/darkstar | scripts/zones/Southern_San_dOria_[S]/npcs/Wyatt.lua | 17 | 1981 | -----------------------------------
-- Area: Southern SandOria [S]
-- NPC: Wyatt
-- @zone 80
-- @pos 124 0 84
-----------------------------------
package.loaded["scripts/zones/Southern_San_dOria_[S]/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Southern_San_dOria_[S]/TextIDs");
require("scripts/globals/titles");
require("scripts/globals/quests");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (trade:getItemCount() == 4 and trade:hasItemQty(2506,4)) then
player:startEvent(0x0004);
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local seeingSpots = player:getQuestStatus(CRYSTAL_WAR,SEEING_SPOTS);
if (seeingSpots == QUEST_AVAILABLE) then
player:startEvent(0x0002);
elseif (seeingSpots == QUEST_ACCEPTED) then
player:startEvent(0x0003);
else
player:showText(npc, WYATT_DIALOG);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (csid == 0x0002) then
player:addQuest(CRYSTAL_WAR,SEEING_SPOTS);
elseif (csid == 0x0004) then
player:tradeComplete();
if(player:getQuestStatus(CRYSTAL_WAR,SEEING_SPOTS) == QUEST_ACCEPTED) then
player:addTitle(LADY_KILLER);
player:addGil(GIL_RATE*3000);
player:messageSpecial(GIL_OBTAINED,GIL_RATE*3000);
player:completeQuest(CRYSTAL_WAR,SEEING_SPOTS);
else
player:addTitle(LADY_KILLER);
player:addGil(GIL_RATE*1500);
player:messageSpecial(GIL_OBTAINED,GIL_RATE*1500);
end
end
end; | gpl-3.0 |
The-HalcyonDays/darkstar | scripts/globals/items/salmon_rice_ball.lua | 21 | 1567 | -----------------------------------------
-- ID: 4590
-- Item: Salmon Rice Ball
-- Food Effect: 30Min, All Races
-----------------------------------------
-- HP +25
-- Dex +2
-- Vit +2
-- Mnd -1
-- hHP +1
-- Effect with enhancing equipment (Note: these are latents on gear with the effect)
-- Atk +40
-- Def +40
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,1800,4590);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_HP, 25);
target:addMod(MOD_DEX, 2);
target:addMod(MOD_VIT, 2);
target:addMod(MOD_MND, -1);
target:addMod(MOD_HPHEAL, 1);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_HP, 25);
target:delMod(MOD_DEX, 2);
target:delMod(MOD_VIT, 2);
target:delMod(MOD_MND, -1);
target:delMod(MOD_HPHEAL, 1);
end; | gpl-3.0 |
nvoron23/skia | tools/lua/paths.lua | 92 | 3129 | --
-- Copyright 2014 Google Inc.
--
-- Use of this source code is governed by a BSD-style license that can be
-- found in the LICENSE file.
--
-- Path scraping script.
-- This script is designed to count the number of times we fall back to software
-- rendering for a path in a given SKP. However, this script does not count an exact
-- number of uploads, since there is some overlap with clipping: e.g. two clipped paths
-- may cause three uploads to the GPU (set clip 1, set clip 2, unset clip 2/reset clip 1),
-- but these cases are rare.
draws = 0
drawPaths = 0
drawPathsAnti = 0
drawPathsConvexAnti = 0
clips = 0
clipPaths = 0
clipPathsAnti = 0
clipPathsConvexAnti = 0
usedPath = false
usedSWPath = false
skpsTotal = 0
skpsWithPath = 0
skpsWithSWPath = 0
function sk_scrape_startcanvas(c, fileName)
usedPath = false
usedSWPath = false
end
function sk_scrape_endcanvas(c, fileName)
skpsTotal = skpsTotal + 1
if usedPath then
skpsWithPath = skpsWithPath + 1
if usedSWPath then
skpsWithSWPath = skpsWithSWPath + 1
end
end
end
function string.starts(String,Start)
return string.sub(String,1,string.len(Start))==Start
end
function isPathValid(path)
if not path then
return false
end
if path:isEmpty() then
return false
end
if path:isRect() then
return false
end
return true
end
function sk_scrape_accumulate(t)
if (string.starts(t.verb, "draw")) then
draws = draws + 1
end
if (string.starts(t.verb, "clip")) then
clips = clips + 1
end
if t.verb == "clipPath" then
local path = t.path
if isPathValid(path) then
clipPaths = clipPaths + 1
usedPath = true
if t.aa then
clipPathsAnti = clipPathsAnti + 1
if path:isConvex() then
clipPathsConvexAnti = clipPathsConvexAnti + 1
else
usedSWPath = true
end
end
end
end
if t.verb == "drawPath" then
local path = t.path
local paint = t.paint
if paint and isPathValid(path) then
drawPaths = drawPaths + 1
usedPath = true
if paint:isAntiAlias() then
drawPathsAnti = drawPathsAnti + 1
if path:isConvex() then
drawPathsConvexAnti = drawPathsConvexAnti + 1
else
usedSWPath = true
end
end
end
end
end
function sk_scrape_summarize()
local swDrawPaths = drawPathsAnti - drawPathsConvexAnti
local swClipPaths = clipPathsAnti - clipPathsConvexAnti
io.write("clips = clips + ", clips, "\n");
io.write("draws = draws + ", draws, "\n");
io.write("clipPaths = clipPaths + ", clipPaths, "\n");
io.write("drawPaths = drawPaths + ", drawPaths, "\n");
io.write("swClipPaths = swClipPaths + ", swClipPaths, "\n");
io.write("swDrawPaths = swDrawPaths + ", swDrawPaths, "\n");
io.write("skpsTotal = skpsTotal + ", skpsTotal, "\n");
io.write("skpsWithPath = skpsWithPath + ", skpsWithPath, "\n");
io.write("skpsWithSWPath = skpsWithSWPath + ", skpsWithSWPath, "\n");
end
| bsd-3-clause |
Kinathka/gmod_airbase_vehicles | avehicle_heli/lua/entities/avehicle_ch46_rotor/init.lua | 1 | 2574 | AddCSLuaFile( "cl_init.lua" )
AddCSLuaFile( "shared.lua" )
include( 'shared.lua' )
function ENT:Initialize()
self:SetModel( "models/Flyboi/Ch46/ch46rotorm_fb.mdl" )
--A fix for the physics because the model's is currently bugged. Comment out this section and see below for defautls.
--local lowerBound = Vector(10, -250, -5)
--local upperBound = Vector(10, 250, 5)
--self.Entity:PhysicsInitBox(lowerBound, upperBound)
--self.Entity:SetCollisionBounds(lowerBound, upperBound)
--self.Entity:SetSolid( SOLID_BBOX )
--self:SetSolid( SOLID_VPHYSICS )
--Default model physics. Commented
self:PhysicsInit( SOLID_VPHYSICS )
self:SetSolid( SOLID_VPHYSICS )
self:SetMoveType( MOVETYPE_VPHYSICS )
--self:SetMoveType( MOVETYPE_FLY )
if IsValid(self.Heli) then
self:SetOwner(self.Heli)
end
self.ActiveAngleSpeed = 400
self.ImpactSound = CreateSound(self, "npc/manhack/grind5.wav")
self.PhysObj = self:GetPhysicsObject()
if ( self.PhysObj:IsValid() ) then
self.PhysObj:EnableGravity(true)
self.PhysObj:EnableDrag(true)
self.PhysObj:SetMass(1000)
--self.PhysObj:SetDamping(0,10.0)
self.PhysObj:Wake()
end
self.IsAVehicleObject = true
end
function ENT:PhysicsCollide( data, physobj )
if ( data.Speed > 350 && data.DeltaTime > 0.2 ) then
if IsValid(self.Heli) then
if( data.Speed > 12500 ) then
self.Heli:DamageHurt(8000, "rotor")
end
for i =1, 6 do
local e = EffectData()
e:SetOrigin( data.HitPos )
e:SetNormal( data.HitNormal + Vector( math.random(-12,12), math.random(-12,12), 4 ) )
e:SetScale( 20 )
util.Effect("ManhackSparks", e)
self.ImpactSound:PlayEx( 1.0, math.random( 100, 120 ) )
end
if IsValid(data.HitEntity) and (data.HitEntity:IsWorld() or data.HitEntity:GetClass() == "worldspawn") then
self.Heli:DamageHurt(4000, "rotor")
end
if IsValid(data.HitEntity) and not (data.HitEntity:IsNPC() or data.HitEntity:IsPlayer()) then
if IsValid(physobj) and !physobj:IsMoveable() then
self.Heli:DamageHurt(math.random(50,physobj:GetMass()/10), "rotor")
elseif IsValid(physobj) then
self.Heli:DamageHurt(math.random(1,physobj:GetMass()/50), "rotor")
end
end
end
else
self.ImpactSound:FadeOut( 0.25 )
end
end
function ENT:Think()
local phys = self:GetPhysicsObject()
if phys and phys:IsValid() then
if phys:GetAngleVelocity():Length() > self.ActiveAngleSpeed then
self:SetNWBool("rotor_online", true)
else
self:SetNWBool("rotor_online", false)
end
end
self.Entity:NextThink( CurTime() + 0.5 )
return true
end | lgpl-3.0 |
The-HalcyonDays/darkstar | scripts/zones/Caedarva_Mire/npcs/qm1.lua | 8 | 1167 | -----------------------------------
-- Area: Caedarva Mire
-- NPC: ??? (Spawn Verdelet(ZNM T2))
-- @pos 417 -19 -69 79
-----------------------------------
package.loaded["scripts/zones/Caedarva_Mire/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Caedarva_Mire/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if(trade:hasItemQty(2599,1) and trade:getItemCount() == 1) then -- Trade Mint Drop
player:tradeComplete();
SpawnMob(17101202,180):updateClaim(player);
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:messageSpecial(NOTHING_HAPPENS);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end; | gpl-3.0 |
The-HalcyonDays/darkstar | scripts/globals/items/rolanberry_pie_+1.lua | 35 | 1376 | -----------------------------------------
-- ID: 4339
-- Item: rolanberry_pie_+1
-- Food Effect: 60Min, All Races
-----------------------------------------
-- Magic 60
-- Intelligence 3
-- Health Regen While Healing 1
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,3600,4339);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_MP, 60);
target:addMod(MOD_INT, 3);
target:addMod(MOD_HPHEAL, 1);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_MP, 60);
target:delMod(MOD_INT, 3);
target:delMod(MOD_HPHEAL, 1);
end;
| gpl-3.0 |
coltonj96/UsefulCombinators | UsefulCombinators_0.2.0/prototypes/item/items.lua | 2 | 5898 | data:extend(
{
{
type = "item",
name = "timer-combinator",
icon = "__UsefulCombinators__/graphics/icons/timer-combinator.png",
flags = { "goes-to-quickbar" },
subgroup = "circuit-network",
place_result="timer-combinator",
order = "b[combinators]-u[timer-combinator]",
stack_size= 10,
},
{
type = "item",
name = "counting-combinator",
icon = "__UsefulCombinators__/graphics/icons/counting-combinator.png",
flags = { "goes-to-quickbar" },
subgroup = "circuit-network",
place_result="counting-combinator",
order = "b[combinators]-u[counting-combinator]",
stack_size= 10,
},
{
type = "item",
name = "random-combinator",
icon = "__UsefulCombinators__/graphics/icons/random-combinator.png",
flags = { "goes-to-quickbar" },
subgroup = "circuit-network",
place_result="random-combinator",
order = "b[combinators]-u[random-combinator]",
stack_size= 10,
}--[[,
{
type = "item",
name = "logic-combinator",
icon = "__UsefulCombinators__/graphics/icons/logic-combinator.png",
flags = { "goes-to-quickbar" },
subgroup = "circuit-network",
place_result="logic-combinator",
order = "b[combinators]-u[logic-combinator]",
stack_size= 10,
}]],
{
type = "item",
name = "comparator-combinator",
icon = "__UsefulCombinators__/graphics/icons/comparator-combinator.png",
flags = { "goes-to-quickbar" },
subgroup = "circuit-network",
place_result="comparator-combinator",
order = "b[combinators]-u[comparator-combinator]",
stack_size= 10,
},
{
type = "item",
name = "converter-combinator",
icon = "__UsefulCombinators__/graphics/icons/converter-combinator.png",
flags = { "goes-to-quickbar" },
subgroup = "circuit-network",
place_result="converter-combinator",
order = "b[combinators]-u[converter-combinator]",
stack_size= 10,
},
{
type = "item",
name = "min-combinator",
icon = "__UsefulCombinators__/graphics/icons/min-combinator.png",
flags = { "goes-to-quickbar" },
subgroup = "circuit-network",
place_result="min-combinator",
order = "b[combinators]-u[min-combinator]",
stack_size= 10,
},
{
type = "item",
name = "max-combinator",
icon = "__UsefulCombinators__/graphics/icons/max-combinator.png",
flags = { "goes-to-quickbar" },
subgroup = "circuit-network",
place_result="max-combinator",
order = "b[combinators]-u[max-combinator]",
stack_size= 10,
},
{
type = "item",
name = "and-gate-combinator",
icon = "__UsefulCombinators__/graphics/icons/and-gate-combinator.png",
flags = { "goes-to-quickbar" },
subgroup = "circuit-network",
place_result="and-gate-combinator",
order = "b[combinators]-u[and-gate-combinator]",
stack_size= 10,
},
{
type = "item",
name = "or-gate-combinator",
icon = "__UsefulCombinators__/graphics/icons/or-gate-combinator.png",
flags = { "goes-to-quickbar" },
subgroup = "circuit-network",
place_result="or-gate-combinator",
order = "b[combinators]-u[or-gate-combinator]",
stack_size= 10,
},
{
type = "item",
name = "not-gate-combinator",
icon = "__UsefulCombinators__/graphics/icons/not-gate-combinator.png",
flags = { "goes-to-quickbar" },
subgroup = "circuit-network",
place_result="not-gate-combinator",
order = "b[combinators]-u[not-gate-combinator]",
stack_size= 10,
},
{
type = "item",
name = "nand-gate-combinator",
icon = "__UsefulCombinators__/graphics/icons/nand-gate-combinator.png",
flags = { "goes-to-quickbar" },
subgroup = "circuit-network",
place_result="nand-gate-combinator",
order = "b[combinators]-u[nand-gate-combinator]",
stack_size= 10,
},
{
type = "item",
name = "nor-gate-combinator",
icon = "__UsefulCombinators__/graphics/icons/nor-gate-combinator.png",
flags = { "goes-to-quickbar" },
subgroup = "circuit-network",
place_result="nor-gate-combinator",
order = "b[combinators]-u[nor-gate-combinator]",
stack_size= 10,
},
{
type = "item",
name = "xor-gate-combinator",
icon = "__UsefulCombinators__/graphics/icons/xor-gate-combinator.png",
flags = { "goes-to-quickbar" },
subgroup = "circuit-network",
place_result="xor-gate-combinator",
order = "b[combinators]-u[xor-gate-combinator]",
stack_size= 10,
},
{
type = "item",
name = "xnor-gate-combinator",
icon = "__UsefulCombinators__/graphics/icons/xnor-gate-combinator.png",
flags = { "goes-to-quickbar" },
subgroup = "circuit-network",
place_result="xnor-gate-combinator",
order = "b[combinators]-u[xnor-gate-combinator]",
stack_size= 10,
},
{
type = "item",
name = "detector-combinator",
icon = "__UsefulCombinators__/graphics/icons/detector-combinator.png",
flags = { "goes-to-quickbar" },
subgroup = "circuit-network",
place_result="detector-combinator",
order = "b[combinators]-u[detector-combinator]",
stack_size= 10,
},
{
type = "item",
name = "sensor-combinator",
icon = "__UsefulCombinators__/graphics/icons/sensor-combinator.png",
flags = { "goes-to-quickbar" },
subgroup = "circuit-network",
place_result="sensor-combinator",
order = "b[combinators]-u[sensor-combinator]",
stack_size= 10,
},
{
type = "item",
name = "railway-combinator",
icon = "__UsefulCombinators__/graphics/icons/railway-combinator.png",
flags = { "goes-to-quickbar" },
subgroup = "circuit-network",
place_result="railway-combinator",
order = "b[combinators]-u[railway-combinator]",
stack_size= 10,
}
}) | mit |
hxw804781317/MT7620N | package/ralink/ui/luci-mtk/src/applications/luci-polipo/luasrc/model/cbi/polipo.lua | 79 | 5961 | --[[
LuCI - Lua Configuration Interface
Copyright 2008 Aleksandar Krsteski <alekrsteski@gmail.com>
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
$Id$
]]--
m = Map("polipo", translate("Polipo"),
translate("Polipo is a small and fast caching web proxy."))
-- General section
s = m:section(NamedSection, "general", "polipo", translate("Proxy"))
s:tab("general", translate("General Settings"))
s:tab("dns", translate("DNS and Query Settings"))
s:tab("proxy", translate("Parent Proxy"))
s:tab("logging", translate("Logging and RAM"))
-- General settings
s:taboption("general", Flag, "enabled", translate("enable"))
o = s:taboption("general", Value, "proxyAddress", translate("Listen address"),
translate("The interface on which Polipo will listen. To listen on all " ..
"interfaces use 0.0.0.0 or :: (IPv6)."))
o.placeholder = "0.0.0.0"
o.datatype = "ipaddr"
o = s:taboption("general", Value, "proxyPort", translate("Listen port"),
translate("Port on which Polipo will listen"))
o.optional = true
o.placeholder = "8123"
o.datatype = "port"
o = s:taboption("general", DynamicList, "allowedClients",
translate("Allowed clients"),
translate("When listen address is set to 0.0.0.0 or :: (IPv6), you must " ..
"list clients that are allowed to connect. The format is IP address " ..
"or network address (192.168.1.123, 192.168.1.0/24, " ..
"2001:660:116::/48 (IPv6))"))
o.datatype = "ipaddr"
o.placeholder = "0.0.0.0/0"
-- DNS settings
dns = s:taboption("dns", Value, "dnsNameServer", translate("DNS server address"),
translate("Set the DNS server address to use, if you want Polipo to use " ..
"different DNS server than the host system."))
dns.optional = true
dns.datatype = "ipaddr"
l = s:taboption("dns", ListValue, "dnsQueryIPv6",
translate("Query DNS for IPv6"))
l.default = "happily"
l:value("true", translate("Query only IPv6"))
l:value("happily", translate("Query IPv4 and IPv6, prefer IPv6"))
l:value("reluctantly", translate("Query IPv4 and IPv6, prefer IPv4"))
l:value("false", translate("Do not query IPv6"))
l = s:taboption("dns", ListValue, "dnsUseGethostbyname",
translate("Query DNS by hostname"))
l.default = "reluctantly"
l:value("true", translate("Always use system DNS resolver"))
l:value("happily",
translate("Query DNS directly, for unknown hosts fall back " ..
"to system resolver"))
l:value("reluctantly",
translate("Query DNS directly, fallback to system resolver"))
l:value("false", translate("Never use system DNS resolver"))
-- Proxy settings
o = s:taboption("proxy", Value, "parentProxy",
translate("Parent proxy address"),
translate("Parent proxy address (in host:port format), to which Polipo " ..
"will forward the requests."))
o.optional = true
o.datatype = "ipaddr"
o = s:taboption("proxy", Value, "parentAuthCredentials",
translate("Parent proxy authentication"),
translate("Basic HTTP authentication supported. Provide username and " ..
"password in username:password format."))
o.optional = true
o.placeholder = "username:password"
-- Logging
s:taboption("logging", Flag, "logSyslog", translate("Log to syslog"))
s:taboption("logging", Value, "logFacility",
translate("Syslog facility")):depends("logSyslog", "1")
v = s:taboption("logging", Value, "logFile",
translate("Log file location"),
translate("Use of external storage device is recommended, because the " ..
"log file is written frequently and can grow considerably."))
v:depends("logSyslog", "")
v.rmempty = true
o = s:taboption("logging", Value, "chunkHighMark",
translate("In RAM cache size (in bytes)"),
translate("How much RAM should Polipo use for its cache."))
o.datatype = "uinteger"
-- Disk cache section
s = m:section(NamedSection, "cache", "polipo", translate("On-Disk Cache"))
s:tab("general", translate("General Settings"))
s:tab("advanced", translate("Advanced Settings"))
-- Disk cache settings
s:taboption("general", Value, "diskCacheRoot", translate("Disk cache location"),
translate("Location where polipo will cache files permanently. Use of " ..
"external storage devices is recommended, because the cache can " ..
"grow considerably. Leave it empty to disable on-disk " ..
"cache.")).rmempty = true
s:taboption("general", Flag, "cacheIsShared", translate("Shared cache"),
translate("Enable if cache (proxy) is shared by multiple users."))
o = s:taboption("advanced", Value, "diskCacheTruncateSize",
translate("Truncate cache files size (in bytes)"),
translate("Size to which cached files should be truncated"))
o.optional = true
o.placeholder = "1048576"
o.datatype = "uinteger"
o = s:taboption("advanced", Value, "diskCacheTruncateTime",
translate("Truncate cache files time"),
translate("Time after which cached files will be truncated"))
o.optional = true
o.placeholder = "4d12h"
o = s:taboption("advanced", Value, "diskCacheUnlinkTime",
translate("Delete cache files time"),
translate("Time after which cached files will be deleted"))
o.optional = true
o.placeholder = "32d"
-- Poor man's multiplexing section
s = m:section(NamedSection, "pmm", "polipo",
translate("Poor Man's Multiplexing"),
translate("Poor Man's Multiplexing (PMM) is a technique that simulates " ..
"multiplexing by requesting an instance in multiple segments. It " ..
"tries to lower the latency caused by the weakness of HTTP " ..
"protocol. NOTE: some sites may not work with PMM enabled."))
s:option(Value, "pmmSize", translate("PMM segments size (in bytes)"),
translate("To enable PMM, PMM segment size must be set to some " ..
"positive value.")).rmempty = true
s:option(Value, "pmmFirstSize", translate("First PMM segment size (in bytes)"),
translate("Size of the first PMM segment. If not defined, it defaults " ..
"to twice the PMM segment size.")).rmempty = true
return m
| gpl-2.0 |
The-HalcyonDays/darkstar | scripts/zones/Rolanberry_Fields/npcs/qm1.lua | 25 | 1561 | -----------------------------------
-- Area: Rolanberry Fields
-- NPC: qm1 (???)
-- @pos -686.216 -31.556 -369.723 110
-- Notes: Spawns Chuglix Berrypaws for ACP mission "Gatherer of Light (I)"
-----------------------------------
package.loaded["scripts/zones/Rolanberry_Fields/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/zones/Rolanberry_Fields/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local Gob = GetMobAction(17228249);
if ( (Gob == ACTION_NONE or Gob == ACTION_SPAWN) and (player:hasKeyItem(JUG_OF_GREASY_GOBLIN_JUICE) == true) and (player:hasKeyItem(SEEDSPALL_CAERULUM) == false) and (player:hasKeyItem(VIRIDIAN_KEY) == false) ) then
SpawnMob(17228249,180):updateClaim(player);
else
player:messageSpecial(NOTHING_HAPPENS);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end; | gpl-3.0 |
rrpgfirecast/firecast | Plugins/Sheets/Ficha D&D Next/output/rdkObjs/08.Companheiro.Select.lfm.lua | 3 | 3474 | require("firecast.lua");
local __o_rrpgObjs = require("rrpgObjs.lua");
require("rrpgGUI.lua");
require("rrpgDialogs.lua");
require("rrpgLFM.lua");
require("ndb.lua");
require("locale.lua");
local __o_Utils = require("utils.lua");
local function constructNew_frmFichaRPGmeister8CS_svg()
local obj = GUI.fromHandle(_obj_newObject("form"));
local self = obj;
local sheet = nil;
rawset(obj, "_oldSetNodeObjectFunction", rawget(obj, "setNodeObject"));
function obj:setNodeObject(nodeObject)
sheet = nodeObject;
self.sheet = nodeObject;
self:_oldSetNodeObjectFunction(nodeObject);
end;
function obj:setNodeDatabase(nodeObject)
self:setNodeObject(nodeObject);
end;
_gui_assignInitialParentForForm(obj.handle);
obj:beginUpdate();
obj:setName("frmFichaRPGmeister8CS_svg");
obj:setWidth(180);
obj:setHeight(30);
obj:setTheme("dark");
obj.button1 = GUI.fromHandle(_obj_newObject("button"));
obj.button1:setParent(obj);
obj.button1:setWidth(30);
obj.button1:setHeight(30);
obj.button1:setText("X");
obj.button1:setName("button1");
obj.label1 = GUI.fromHandle(_obj_newObject("label"));
obj.label1:setParent(obj);
obj.label1:setLeft(35);
obj.label1:setTop(5);
obj.label1:setWidth(145);
obj.label1:setHeight(20);
obj.label1:setText("Teste de label");
obj.label1:setField("nomeComp");
obj.label1:setName("label1");
obj.dataLink1 = GUI.fromHandle(_obj_newObject("dataLink"));
obj.dataLink1:setParent(obj);
obj.dataLink1:setField("nomeComp");
obj.dataLink1:setDefaultValue("Nome Companheiro");
obj.dataLink1:setName("dataLink1");
obj._e_event0 = obj.button1:addEventListener("onClick",
function (_)
dialogs.confirmOkCancel("Tem certeza que quer apagar esse companheiro?",
function (confirmado)
if confirmado then
ndb.deleteNode(sheet);
end;
end);
end, obj);
function obj:_releaseEvents()
__o_rrpgObjs.removeEventListenerById(self._e_event0);
end;
obj._oldLFMDestroy = obj.destroy;
function obj:destroy()
self:_releaseEvents();
if (self.handle ~= 0) and (self.setNodeDatabase ~= nil) then
self:setNodeDatabase(nil);
end;
if self.dataLink1 ~= nil then self.dataLink1:destroy(); self.dataLink1 = nil; end;
if self.button1 ~= nil then self.button1:destroy(); self.button1 = nil; end;
if self.label1 ~= nil then self.label1:destroy(); self.label1 = nil; end;
self:_oldLFMDestroy();
end;
obj:endUpdate();
return obj;
end;
function newfrmFichaRPGmeister8CS_svg()
local retObj = nil;
__o_rrpgObjs.beginObjectsLoading();
__o_Utils.tryFinally(
function()
retObj = constructNew_frmFichaRPGmeister8CS_svg();
end,
function()
__o_rrpgObjs.endObjectsLoading();
end);
assert(retObj ~= nil);
return retObj;
end;
local _frmFichaRPGmeister8CS_svg = {
newEditor = newfrmFichaRPGmeister8CS_svg,
new = newfrmFichaRPGmeister8CS_svg,
name = "frmFichaRPGmeister8CS_svg",
dataType = "",
formType = "undefined",
formComponentName = "form",
title = "",
description=""};
frmFichaRPGmeister8CS_svg = _frmFichaRPGmeister8CS_svg;
Firecast.registrarForm(_frmFichaRPGmeister8CS_svg);
return _frmFichaRPGmeister8CS_svg;
| apache-2.0 |
cc-paw/cc-paw | releases/cc-paw/0.4.3/util.lua | 1 | 1367 | local util = {}
util.quiet = false
util.log = true
local logFile = "/var/log/cc-paw.log"
local errFile = "/var/log/cc-paw-errors.log"
-- print() with output toggling and logging
function util.p(...)
if not util.quiet then
print(...)
end
if util.log then
local args = {...}
local out = ""
for i = 1, #args do
out = out .. "\t" .. args[i]
end
local file = fs.open(logFile, fs.exists(logFile) and 'a' or 'w')
file.write(out .."\n")
file.close()
end
end
-- error() with logging
function util.e(msg)
local file = fs.open(errFile, fs.exists(errFile) and 'a' or 'w')
file.write(msg.."\n")
file.close()
error(msg)
end
-- assert() using our error function
function util.a(truthy, errMsg)
if truthy then
return truthy
else
e(errMsg)
end
end
local p, e, a = util.p, util.e, util.a
-- run pre/post install/upgrade/remove/purge scripts
function util.script(pkg, id, msg)
if package[id] then
p("Running "..msg.." script...")
ok, result, errMsg = pcall(loadstring(pkg[id])())
if not ok then
e(msg..'" script errored: "'..result..'"\nAborting.')
end
if not result == 0 then
e(msg..'" script failed: "'..errMsg..'"\nAborting.')
end
end
end
return util
| mit |
The-HalcyonDays/darkstar | scripts/globals/items/slice_of_ziz_meat.lua | 18 | 1283 | -----------------------------------------
-- ID: 5581
-- Item: Slice of Ziz Meat
-- Effect: 5 Minutes, food effect, Galka Only
-----------------------------------------
-- Strength +4
-- Intelligence -6
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
result = 0;
if (target:getRace() ~= 8) then
result = 247;
end
if(target:getMod(MOD_EAT_RAW_MEAT) == 1) then
result = 0;
end
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,300,5581);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_STR, 4);
target:addMod(MOD_INT,-6);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_STR, 4);
target:delMod(MOD_INT,-6);
end; | gpl-3.0 |
coltonj96/UsefulCombinators | UsefulCombinators_0.4.2/prototypes/item/items.lua | 3 | 8216 | data:extend(
{
{
type = "item-with-tags",
name = "timer-combinator",
icon = "__UsefulCombinators__/graphics/icons/timer-combinator.png",
icon_size = 32,
flags = { "goes-to-quickbar" },
group = "useful-combinators",
subgroup = "main",
place_result="timer-combinator",
order = "a[timer]",
stack_size= 50,
},
{
type = "item-with-tags",
name = "counting-combinator",
icon = "__UsefulCombinators__/graphics/icons/counting-combinator.png",
icon_size = 32,
flags = { "goes-to-quickbar" },
group = "useful-combinators",
subgroup = "main",
place_result="counting-combinator",
order = "b[counting]",
stack_size= 50,
},
{
type = "item-with-tags",
name = "random-combinator",
icon = "__UsefulCombinators__/graphics/icons/random-combinator.png",
icon_size = 32,
flags = { "goes-to-quickbar" },
group = "useful-combinators",
subgroup = "main",
place_result="random-combinator",
order = "c[random]",
stack_size= 50,
},
{
type = "item-with-tags",
name = "color-combinator",
icon = "__UsefulCombinators__/graphics/icons/color-combinator.png",
icon_size = 32,
flags = { "goes-to-quickbar" },
group = "useful-combinators",
subgroup = "other",
place_result="color-combinator",
order = "e[color]",
stack_size= 50,
},
{
type = "item-with-tags",
name = "converter-combinator",
icon = "__UsefulCombinators__/graphics/icons/converter-combinator.png",
icon_size = 32,
flags = { "goes-to-quickbar" },
group = "useful-combinators",
subgroup = "other",
place_result="converter-combinator",
order = "a[converter]",
stack_size= 50,
},
{
type = "item-with-tags",
name = "min-combinator",
icon = "__UsefulCombinators__/graphics/icons/min-combinator.png",
icon_size = 32,
flags = { "goes-to-quickbar" },
group = "useful-combinators",
subgroup = "main",
place_result="min-combinator",
order = "f[min]",
stack_size= 50,
},
{
type = "item-with-tags",
name = "max-combinator",
icon = "__UsefulCombinators__/graphics/icons/max-combinator.png",
icon_size = 32,
flags = { "goes-to-quickbar" },
group = "useful-combinators",
subgroup = "main",
place_result="max-combinator",
order = "e[max]",
stack_size= 50,
},
{
type = "item-with-tags",
name = "and-gate-combinator",
icon = "__UsefulCombinators__/graphics/icons/and-gate-combinator.png",
icon_size = 32,
flags = { "goes-to-quickbar" },
group = "useful-combinators",
subgroup = "logic-gates",
place_result="and-gate-combinator",
order = "a[and]",
stack_size= 50,
},
{
type = "item-with-tags",
name = "or-gate-combinator",
icon = "__UsefulCombinators__/graphics/icons/or-gate-combinator.png",
icon_size = 32,
flags = { "goes-to-quickbar" },
group = "useful-combinators",
subgroup = "logic-gates",
place_result="or-gate-combinator",
order = "o[or]",
stack_size= 50,
},
{
type = "item-with-tags",
name = "not-gate-combinator",
icon = "__UsefulCombinators__/graphics/icons/not-gate-combinator.png",
icon_size = 32,
flags = { "goes-to-quickbar" },
group = "useful-combinators",
subgroup = "logic-gates",
place_result="not-gate-combinator",
order = "n[not]",
stack_size= 50,
},
{
type = "item-with-tags",
name = "nand-gate-combinator",
icon = "__UsefulCombinators__/graphics/icons/nand-gate-combinator.png",
icon_size = 32,
flags = { "goes-to-quickbar" },
group = "useful-combinators",
subgroup = "logic-gates",
place_result="nand-gate-combinator",
order = "n[nand]",
stack_size= 50,
},
{
type = "item-with-tags",
name = "nor-gate-combinator",
icon = "__UsefulCombinators__/graphics/icons/nor-gate-combinator.png",
icon_size = 32,
flags = { "goes-to-quickbar" },
group = "useful-combinators",
subgroup = "logic-gates",
place_result="nor-gate-combinator",
order = "n[nor]",
stack_size= 50,
},
{
type = "item-with-tags",
name = "xor-gate-combinator",
icon = "__UsefulCombinators__/graphics/icons/xor-gate-combinator.png",
icon_size = 32,
flags = { "goes-to-quickbar" },
group = "useful-combinators",
subgroup = "logic-gates",
place_result="xor-gate-combinator",
order = "x[xor]",
stack_size= 50,
},
{
type = "item-with-tags",
name = "xnor-gate-combinator",
icon = "__UsefulCombinators__/graphics/icons/xnor-gate-combinator.png",
icon_size = 32,
flags = { "goes-to-quickbar" },
group = "useful-combinators",
subgroup = "logic-gates",
place_result="xnor-gate-combinator",
order = "x[xnor]",
stack_size= 50,
},
{
type = "item-with-tags",
name = "detector-combinator",
icon = "__UsefulCombinators__/graphics/icons/detector-combinator.png",
icon_size = 32,
flags = { "goes-to-quickbar" },
group = "useful-combinators",
subgroup = "other",
place_result="detector-combinator",
order = "b[detector]",
stack_size= 50,
},
{
type = "item-with-tags",
name = "sensor-combinator",
icon = "__UsefulCombinators__/graphics/icons/sensor-combinator.png",
icon_size = 32,
flags = { "goes-to-quickbar" },
group = "useful-combinators",
subgroup = "other",
place_result="sensor-combinator",
order = "c[sensor]",
stack_size= 50,
},
{
type = "item-with-tags",
name = "railway-combinator",
icon = "__UsefulCombinators__/graphics/icons/railway-combinator.png",
icon_size = 32,
flags = { "goes-to-quickbar" },
group = "useful-combinators",
subgroup = "other",
place_result="railway-combinator",
order = "d[railway]",
stack_size= 50,
},
{
type = "item-with-tags",
name = "emitter-combinator",
icon = "__UsefulCombinators__/graphics/icons/emitter-combinator.png",
icon_size = 32,
flags = { "goes-to-quickbar" },
group = "useful-combinators",
subgroup = "other",
place_result="emitter-combinator",
order = "f[emitter]",
stack_size= 50,
},
{
type = "item-with-tags",
name = "receiver-combinator",
icon = "__UsefulCombinators__/graphics/icons/receiver-combinator.png",
icon_size = 32,
flags = { "goes-to-quickbar" },
group = "useful-combinators",
subgroup = "other",
place_result="receiver-combinator",
order = "g[receiver]",
stack_size= 50,
},
{
type = "item-with-tags",
name = "power-combinator",
icon = "__UsefulCombinators__/graphics/icons/power-combinator.png",
icon_size = 32,
flags = { "goes-to-quickbar" },
group = "useful-combinators",
subgroup = "main",
place_result="power-combinator",
order = "d[power]",
stack_size= 50,
},
{
type = "item-with-tags",
name = "daytime-combinator",
icon = "__UsefulCombinators__/graphics/icons/daytime-combinator.png",
icon_size = 32,
flags = { "goes-to-quickbar" },
group = "useful-combinators",
subgroup = "other2",
place_result="daytime-combinator",
order = "a[daytime]",
stack_size= 50,
},
{
type = "item-with-tags",
name = "pollution-combinator",
icon = "__UsefulCombinators__/graphics/icons/pollution-combinator.png",
icon_size = 32,
flags = { "goes-to-quickbar" },
group = "useful-combinators",
subgroup = "other2",
place_result="pollution-combinator",
order = "c[pollution]",
stack_size= 50,
},
{
type = "item-with-tags",
name = "statistic-combinator",
icon = "__UsefulCombinators__/graphics/icons/statistic-combinator.png",
icon_size = 32,
flags = { "goes-to-quickbar" },
group = "useful-combinators",
subgroup = "other2",
place_result="statistic-combinator",
order = "b[statistic]",
stack_size= 50,
}
}) | mit |
The-HalcyonDays/darkstar | scripts/zones/Port_Windurst/npcs/Ryan.lua | 34 | 1805 | -----------------------------------
-- Area: Port Windurst
-- NPC: Ryan
-- Standard Merchant NPC
-----------------------------------
package.loaded["scripts/zones/Port_Windurst/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/shop");
require("scripts/zones/Port_Windurst/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,RYAN_SHOP_DIALOG);
stock = {
0x4100, 290, -- Bronze Axe
0x4097, 246, -- Bronze Sword
0x43B8, 5, -- Crossbow Bolt
0x3120, 235, -- Bronze Harness
0x3121, 2286, -- Brass Harness
0x31A0, 128, -- Bronze Mittens
0x31A1, 1255, -- Brass Mittens
0x3220, 191, -- Bronze Subligar
0x3221, 1840, -- Brass Subligar
0x32A0, 117, -- Bronze Leggings
0x32A1, 1140, -- Brass Leggings
0x3128, 1145, -- Kenpogi
0x31A8, 630, -- Tekko
0x3228, 915, -- Sitabaki
0x32A8, 584 -- Kyahan
}
showShop(player, WINDURST, stock);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.